diff --git a/.gitignore b/.gitignore index 6aa74f44ed0..ffacba65feb 100644 --- a/.gitignore +++ b/.gitignore @@ -1,5 +1,7 @@ htdocs/conf/conf.php htdocs/conf/conf.php.old +htdocs/conf/conf.php.sav +htdocs/conf/conf.php.back documents/ custom2/ test/report/ @@ -8,22 +10,33 @@ default.properties .settings/ .buildpath .gitmodules -dolibarr_install.log -upgrade.log -doxygen_warnings.log /.project +/.pydevproject /.vscode .DS_Store .idea *.iml Thumbs.db +/dolibarr_genesis.mp4 +# Log files +dolibarr_install.log +upgrade.log +doxygen_warnings.log # Vagrant generated files .vagrant # Composer installed repositories /htdocs/includes/**/.git # Composer autoloader and unwanted files +composer.phar htdocs/includes/autoload.php htdocs/includes/bin/ htdocs/includes/composer/ -/.pydevproject -/dolibarr_genesis.mp4 +htdocs/includes/doctrine/ +htdocs/includes/jakub-onderka/ +htdocs/includes/phpdocumentor/ +htdocs/includes/phpspec/ +htdocs/includes/phpunit/ +htdocs/includes/sebastian/ +htdocs/includes/squizlabs/ +htdocs/includes/symfony/ +htdocs/includes/webmozart/ diff --git a/ChangeLog b/ChangeLog index 2d398c83535..1ce34b5e87a 100644 --- a/ChangeLog +++ b/ChangeLog @@ -24,7 +24,7 @@ Following changes may create regressions for some external modules, but were nec * Removed function dol_micro_time. Use native PHP microtime instead. * The trigger BON_PRELEVEMENT_CREATE has been renamed into DIRECT_DEBIT_ORDER_CREATE. * The constant INVOICE_SHOW_POS_IN_EXPORT has been renamed into INVOICE_SHOW_POS. -* If your logo was visible on the menu bar, you must upload a new logo into 'Home-Setup-Company/Organization' to have it visible agin in menu. +* If your logo is no more visible on the menu bar, you must upload a new logo into 'Home-Setup-Company/Organization' to have it visible again. * All properties 'libstatut', 'labelstatut', 'labelstatus' were renamed into 'labelStatus'. * All properties 'labelstatusshort' and 'labelstatut_short' were renamed into 'labelStatusShort'. * All properties 'type_libelle' were renamed into 'type_label'. diff --git a/build/.gitignore b/build/.gitignore index be85c819547..54c5d8be9c3 100644 --- a/build/.gitignore +++ b/build/.gitignore @@ -5,6 +5,5 @@ /dolibarr-*.tgz /dolibarr-*.rpm /dolibarr-*.zip -/dolibarr-*.tgz /*.exe /html diff --git a/build/exakat/README.md b/build/exakat/README.md new file mode 100644 index 00000000000..3b9052e5281 --- /dev/null +++ b/build/exakat/README.md @@ -0,0 +1,29 @@ + +== Install exakat == +mkdir exakat +cd exakat +curl -o exakat.phar http://dist.exakat.io/index.php?file=latest +curl -o apache-tinkerpop-gremlin-server-3.3.5-bin.zip http://dist.exakat.io/apache-tinkerpop-gremlin-server-3.3.5-bin.zip +unzip apache-tinkerpop-gremlin-server-3.3.5-bin.zip +mv apache-tinkerpop-gremlin-server-3.3.5 tinkergraph +rm -rf apache-tinkerpop-gremlin-server-3.3.5-bin.zip +cd tinkergraph ./bin/gremlin-server.sh -i org.apache.tinkerpop neo4j-gremlin 3.3.5 +cd .. + +php exakat.phar version +php exakat.phar doctor + +== Init project == +php + + +Edit config.ini file to exclude some dirs: +ignore_dirs[] = "/htdocs/includes"; +ignore_dirs[] = "/scripts"; +ignore_dirs[] = "/build"; +ignore_dirs[] = "/dev"; +ignore_dirs[] = "/documents"; + + +== Analyze project == +php diff --git a/build/makepack-dolibarr.pl b/build/makepack-dolibarr.pl index 8e296163a46..f68ca6a77f5 100755 --- a/build/makepack-dolibarr.pl +++ b/build/makepack-dolibarr.pl @@ -461,15 +461,18 @@ if ($nboftargetok) { print "Clean $BUILDROOT\n"; $ret=`rm -f $BUILDROOT/$PROJECT/.buildpath`; $ret=`rm -fr $BUILDROOT/$PROJECT/.cache`; - $ret=`rm -fr $BUILDROOT/$PROJECT/.editorconfig`; + $ret=`rm -fr $BUILDROOT/$PROJECT/.codeclimate`; $ret=`rm -fr $BUILDROOT/$PROJECT/.externalToolBuilders`; $ret=`rm -fr $BUILDROOT/$PROJECT/.git*`; $ret=`rm -fr $BUILDROOT/$PROJECT/.project`; + $ret=`rm -fr $BUILDROOT/$PROJECT/.pydevproject`; $ret=`rm -fr $BUILDROOT/$PROJECT/.settings`; $ret=`rm -fr $BUILDROOT/$PROJECT/.scrutinizer.yml`; + $ret=`rm -fr $BUILDROOT/$PROJECT/.stickler.yml`; $ret=`rm -fr $BUILDROOT/$PROJECT/.travis.yml`; $ret=`rm -fr $BUILDROOT/$PROJECT/.tx`; $ret=`rm -f $BUILDROOT/$PROJECT/build.xml`; + $ret=`rm -f $BUILDROOT/$PROJECT/phpstan.neon`; $ret=`rm -f $BUILDROOT/$PROJECT/pom.xml`; $ret=`rm -fr $BUILDROOT/$PROJECT/build/html`; diff --git a/composer.json b/composer.json index a3407d7fa20..86acd2f8d60 100644 --- a/composer.json +++ b/composer.json @@ -24,10 +24,10 @@ "vendor-dir" : "htdocs/includes" }, "require" : { - "php" : ">=5.3.0", + "php" : ">=5.5.0", "ext-curl" : "*", "ckeditor/ckeditor" : "4.12.1", - "mike42/escpos-php" : "1.2.1", + "mike42/escpos-php" : "2.2", "mobiledetect/mobiledetectlib" : "2.8.33", "phpoffice/phpexcel" : "1.8.1", "restler/framework" : "3.0.0-RC6", @@ -48,13 +48,12 @@ "ext-mssql" : "To use with MSSQL (experimental)", "ext-pdo_sqlite" : "To use with SQLite (experimental)", "ext-gd" : "Image manipulation (Required but maybe built-in PHP)", - "ext-imagick" : "Image manipulation (TCPDF)", + "ext-imagick" : "Generation of thumbs from PDF", "ext-mcrypt" : "(Required but maybe built-in PHP)", "ext-openssl" : "Secure connections (Emails, SOAP\u2026)", - "ext-mbstring" : "Handle non UTF-8 databases", + "ext-mbstring" : "Handle non UTF-8 characters", "ext-soap" : "Native SOAP", - "ext-zip" : "ODT and Excel support", - "ext-xml" : "Excel support", - "firephp/firephp-core" : "Logging to Firebug console support" + "ext-zip" : "ODT, Excel and file compression support", + "ext-xml" : "Excel support" } } \ No newline at end of file diff --git a/htdocs/.gitignore b/htdocs/.gitignore index d51eaffd235..ef87c0455d6 100644 --- a/htdocs/.gitignore +++ b/htdocs/.gitignore @@ -16,9 +16,6 @@ /teclib* /test.php /ultimatepdf* -/lead -/dolimed* -/allscreens* /ecommerce/ /cabinetmed* /webmail* diff --git a/htdocs/accountancy/admin/account.php b/htdocs/accountancy/admin/account.php index 10a65cab2fe..56d60281078 100644 --- a/htdocs/accountancy/admin/account.php +++ b/htdocs/accountancy/admin/account.php @@ -24,12 +24,12 @@ */ require '../../main.inc.php'; -require_once DOL_DOCUMENT_ROOT . '/core/lib/admin.lib.php'; -require_once DOL_DOCUMENT_ROOT . '/core/lib/accounting.lib.php'; -require_once DOL_DOCUMENT_ROOT . '/accountancy/class/accountingaccount.class.php'; +require_once DOL_DOCUMENT_ROOT.'/core/lib/admin.lib.php'; +require_once DOL_DOCUMENT_ROOT.'/core/lib/accounting.lib.php'; +require_once DOL_DOCUMENT_ROOT.'/accountancy/class/accountingaccount.class.php'; // Load translation files required by the page -$langs->loadLangs(array("compta","bills","admin","accountancy","salaries")); +$langs->loadLangs(array("compta", "bills", "admin", "accountancy", "salaries")); $mesg = ''; $action = GETPOST('action', 'aZ09'); @@ -37,7 +37,7 @@ $cancel = GETPOST('cancel', 'alpha'); $id = GETPOST('id', 'int'); $rowid = GETPOST('rowid', 'int'); $massaction = GETPOST('massaction', 'aZ09'); -$contextpage=GETPOST('contextpage', 'aZ')?GETPOST('contextpage', 'aZ'):'accountingaccountlist'; // To manage different context of search +$contextpage = GETPOST('contextpage', 'aZ') ?GETPOST('contextpage', 'aZ') : 'accountingaccountlist'; // To manage different context of search $search_account = GETPOST('search_account', 'alpha'); $search_label = GETPOST('search_label', 'alpha'); @@ -58,10 +58,10 @@ if (empty($page) || $page == -1) { $page = 0; } // If $page is not defined, $offset = $limit * $page; $pageprev = $page - 1; $pagenext = $page + 1; -if (! $sortfield) $sortfield = "aa.account_number"; -if (! $sortorder) $sortorder = "ASC"; +if (!$sortfield) $sortfield = "aa.account_number"; +if (!$sortorder) $sortorder = "ASC"; -$arrayfields=array( +$arrayfields = array( 'aa.account_number'=>array('label'=>$langs->trans("AccountNumber"), 'checked'=>1), 'aa.label'=>array('label'=>$langs->trans("Label"), 'checked'=>1), 'aa.account_parent'=>array('label'=>$langs->trans("Accountparent"), 'checked'=>1), @@ -78,27 +78,27 @@ $accounting = new AccountingAccount($db); * Actions */ -if (GETPOST('cancel', 'alpha')) { $action='list'; $massaction=''; } -if (! GETPOST('confirmmassaction', 'alpha')) { $massaction=''; } +if (GETPOST('cancel', 'alpha')) { $action = 'list'; $massaction = ''; } +if (!GETPOST('confirmmassaction', 'alpha')) { $massaction = ''; } -$parameters=array(); -$reshook=$hookmanager->executeHooks('doActions', $parameters, $object, $action); // Note that $action and $object may have been modified by some hooks +$parameters = array(); +$reshook = $hookmanager->executeHooks('doActions', $parameters, $object, $action); // Note that $action and $object may have been modified by some hooks if ($reshook < 0) setEventMessages($hookmanager->error, $hookmanager->errors, 'errors'); if (empty($reshook)) { - if (! empty($cancel)) $action = ''; + if (!empty($cancel)) $action = ''; 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 + 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_account = ""; $search_label = ""; $search_accountparent = ""; $search_pcgtype = ""; $search_pcgsubtype = ""; - $search_array_options=array(); + $search_array_options = array(); } if (GETPOST('change_chart', 'alpha') && (GETPOST('valid_change_chart', 'int') || empty($conf->use_javascript_ajax))) @@ -108,8 +108,8 @@ if (empty($reshook)) if ($chartofaccounts > 0) { // Get language code for this $chartofaccounts - $sql ='SELECT code FROM '.MAIN_DB_PREFIX.'c_country as c, '.MAIN_DB_PREFIX.'accounting_system as a'; - $sql.=' WHERE c.rowid = a.fk_country AND a.rowid = '.(int) $chartofaccounts; + $sql = 'SELECT code FROM '.MAIN_DB_PREFIX.'c_country as c, '.MAIN_DB_PREFIX.'accounting_system as a'; + $sql .= ' WHERE c.rowid = a.fk_country AND a.rowid = '.(int) $chartofaccounts; $resql = $db->query($sql); if ($resql) { @@ -132,7 +132,7 @@ if (empty($reshook)) { $offsetforchartofaccount += $reg[1]; } - $offsetforchartofaccount+=($conf->entity * 100000000); + $offsetforchartofaccount += ($conf->entity * 100000000); $result = run_sql($sqlfile, 1, $conf->entity, 1, '', 'default', 32768, 0, $offsetforchartofaccount); @@ -146,7 +146,7 @@ if (empty($reshook)) } } - if (! dolibarr_set_const($db, 'CHARTOFACCOUNTS', $chartofaccounts, 'chaine', 0, '', $conf->entity)) { + if (!dolibarr_set_const($db, 'CHARTOFACCOUNTS', $chartofaccounts, 'chaine', 0, '', $conf->entity)) { $error++; } } else { @@ -179,12 +179,12 @@ if (empty($reshook)) * View */ -$form=new Form($db); +$form = new Form($db); llxHeader('', $langs->trans("ListAccounts")); if ($action == 'delete') { - $formconfirm = $html->formconfirm($_SERVER["PHP_SELF"] . '?id=' . $id, $langs->trans('DeleteAccount'), $langs->trans('ConfirmDeleteAccount'), 'confirm_delete', '', 0, 1); + $formconfirm = $html->formconfirm($_SERVER["PHP_SELF"].'?id='.$id, $langs->trans('DeleteAccount'), $langs->trans('ConfirmDeleteAccount'), 'confirm_delete', '', 0, 1); print $formconfirm; } @@ -192,11 +192,11 @@ $pcgver = $conf->global->CHARTOFACCOUNTS; $sql = "SELECT aa.rowid, aa.fk_pcg_version, aa.pcg_type, aa.pcg_subtype, aa.account_number, aa.account_parent , aa.label, aa.active, "; $sql .= " a2.rowid as rowid2, a2.label as label2, a2.account_number as account_number2"; -$sql .= " FROM " . MAIN_DB_PREFIX . "accounting_account as aa"; -$sql .= " LEFT JOIN ".MAIN_DB_PREFIX."accounting_system as asy ON aa.fk_pcg_version = asy.pcg_version AND aa.entity = " . $conf->entity; -if ($db->type == 'pgsql') $sql .= " LEFT JOIN ".MAIN_DB_PREFIX."accounting_account as a2 ON a2.rowid = aa.account_parent AND a2.entity = " . $conf->entity; -else $sql .= " LEFT JOIN ".MAIN_DB_PREFIX."accounting_account as a2 ON a2.rowid = aa.account_parent AND a2.entity = " . $conf->entity; -$sql .= " WHERE asy.rowid = " . $pcgver; +$sql .= " FROM ".MAIN_DB_PREFIX."accounting_account as aa"; +$sql .= " LEFT JOIN ".MAIN_DB_PREFIX."accounting_system as asy ON aa.fk_pcg_version = asy.pcg_version AND aa.entity = ".$conf->entity; +if ($db->type == 'pgsql') $sql .= " LEFT JOIN ".MAIN_DB_PREFIX."accounting_account as a2 ON a2.rowid = aa.account_parent AND a2.entity = ".$conf->entity; +else $sql .= " LEFT JOIN ".MAIN_DB_PREFIX."accounting_account as a2 ON a2.rowid = aa.account_parent AND a2.entity = ".$conf->entity; +$sql .= " WHERE asy.rowid = ".$pcgver; //print $sql; if (strlen(trim($search_account))) $sql .= natural_search("aa.account_number", $search_account); if (strlen(trim($search_label))) $sql .= natural_search("aa.label", $search_label); @@ -220,24 +220,24 @@ if (empty($conf->global->MAIN_DISABLE_FULL_SCANLIST)) $sql .= $db->plimit($limit + 1, $offset); -dol_syslog('accountancy/admin/account.php:: $sql=' . $sql); +dol_syslog('accountancy/admin/account.php:: $sql='.$sql); $resql = $db->query($sql); if ($resql) { $num = $db->num_rows($resql); - $param=''; - if (! empty($contextpage) && $contextpage != $_SERVER["PHP_SELF"]) $param.='&contextpage='.$contextpage; - if ($limit > 0 && $limit != $conf->liste_limit) $param.='&limit='.$limit; - if ($search_account) $param.= '&search_account='.urlencode($search_account); - if ($search_label) $param.= '&search_label='.urlencode($search_label); - if ($search_accountparent) $param.= '&search_accountparent='.urlencode($search_accountparent); - if ($search_pcgtype) $param.= '&search_pcgtype='.urlencode($search_pcgtype); - if ($search_pcgsubtype) $param.= '&search_pcgsubtype='.urlencode($search_pcgsubtype); - if ($optioncss != '') $param.='&optioncss='.$optioncss; + $param = ''; + if (!empty($contextpage) && $contextpage != $_SERVER["PHP_SELF"]) $param .= '&contextpage='.$contextpage; + if ($limit > 0 && $limit != $conf->liste_limit) $param .= '&limit='.$limit; + if ($search_account) $param .= '&search_account='.urlencode($search_account); + if ($search_label) $param .= '&search_label='.urlencode($search_label); + if ($search_accountparent) $param .= '&search_accountparent='.urlencode($search_accountparent); + if ($search_pcgtype) $param .= '&search_pcgtype='.urlencode($search_pcgtype); + if ($search_pcgsubtype) $param .= '&search_pcgsubtype='.urlencode($search_pcgsubtype); + if ($optioncss != '') $param .= '&optioncss='.$optioncss; - if (! empty($conf->use_javascript_ajax)) + if (!empty($conf->use_javascript_ajax)) { print ' '; } - print '
'; + print ''; if ($optioncss != '') print ''; print ''; print ''; @@ -266,17 +266,17 @@ if ($resql) print ''; print ''; - $newcardbutton.= dolGetButtonTitle($langs->trans("New"), $langs->trans("Addanaccount"), 'fa fa-plus-circle', './card.php?action=create'); + $newcardbutton .= dolGetButtonTitle($langs->trans("New"), $langs->trans("Addanaccount"), 'fa fa-plus-circle', './card.php?action=create'); print_barre_liste($langs->trans('ListAccounts'), $page, $_SERVER["PHP_SELF"], $param, $sortfield, $sortorder, '', $num, $nbtotalofrecords, 'title_accountancy', 0, $newcardbutton, '', $limit); // Box to select active chart of account - print $langs->trans("Selectchartofaccounts") . " : "; + print $langs->trans("Selectchartofaccounts")." : "; print ''; - if (! empty($arrayfields['aa.label']['checked'])) print ''; - if (! empty($arrayfields['aa.account_parent']['checked'])) print ''; - if (! empty($arrayfields['aa.pcg_type']['checked'])) print ''; - if (! empty($arrayfields['aa.pcg_subtype']['checked'])) print ''; - if (! empty($arrayfields['aa.active']['checked'])) print ' '; + if (!empty($arrayfields['aa.account_number']['checked'])) print ''; + if (!empty($arrayfields['aa.label']['checked'])) print ''; + if (!empty($arrayfields['aa.account_parent']['checked'])) print ''; + if (!empty($arrayfields['aa.pcg_type']['checked'])) print ''; + if (!empty($arrayfields['aa.pcg_subtype']['checked'])) print ''; + if (!empty($arrayfields['aa.active']['checked'])) print ' '; print ''; - $searchpicto=$form->showFilterAndCheckAddButtons($massactionbutton?1:0, 'checkforselect', 1); + $searchpicto = $form->showFilterAndCheckAddButtons($massactionbutton ? 1 : 0, 'checkforselect', 1); print $searchpicto; print ''; print ''; print ''; - if (! empty($arrayfields['aa.account_number']['checked'])) print_liste_field_titre($arrayfields['aa.account_number']['label'], $_SERVER["PHP_SELF"], "aa.account_number", "", $param, '', $sortfield, $sortorder); - if (! empty($arrayfields['aa.label']['checked'])) print_liste_field_titre($arrayfields['aa.label']['label'], $_SERVER["PHP_SELF"], "aa.label", "", $param, '', $sortfield, $sortorder); - if (! empty($arrayfields['aa.account_parent']['checked'])) print_liste_field_titre($arrayfields['aa.account_parent']['label'], $_SERVER["PHP_SELF"], "aa.account_parent", "", $param, '', $sortfield, $sortorder, 'left '); - if (! empty($arrayfields['aa.pcg_type']['checked'])) print_liste_field_titre($arrayfields['aa.pcg_type']['label'], $_SERVER["PHP_SELF"], 'aa.pcg_type', '', $param, '', $sortfield, $sortorder, '', $arrayfields['aa.pcg_type']['help']); - if (! empty($arrayfields['aa.pcg_subtype']['checked'])) print_liste_field_titre($arrayfields['aa.pcg_subtype']['label'], $_SERVER["PHP_SELF"], 'aa.pcg_subtype', '', $param, '', $sortfield, $sortorder, '', $arrayfields['aa.pcg_subtype']['help']); - if (! empty($arrayfields['aa.active']['checked'])) print_liste_field_titre($arrayfields['aa.active']['label'], $_SERVER["PHP_SELF"], 'aa.active', '', $param, '', $sortfield, $sortorder); + if (!empty($arrayfields['aa.account_number']['checked'])) print_liste_field_titre($arrayfields['aa.account_number']['label'], $_SERVER["PHP_SELF"], "aa.account_number", "", $param, '', $sortfield, $sortorder); + if (!empty($arrayfields['aa.label']['checked'])) print_liste_field_titre($arrayfields['aa.label']['label'], $_SERVER["PHP_SELF"], "aa.label", "", $param, '', $sortfield, $sortorder); + if (!empty($arrayfields['aa.account_parent']['checked'])) print_liste_field_titre($arrayfields['aa.account_parent']['label'], $_SERVER["PHP_SELF"], "aa.account_parent", "", $param, '', $sortfield, $sortorder, 'left '); + if (!empty($arrayfields['aa.pcg_type']['checked'])) print_liste_field_titre($arrayfields['aa.pcg_type']['label'], $_SERVER["PHP_SELF"], 'aa.pcg_type', '', $param, '', $sortfield, $sortorder, '', $arrayfields['aa.pcg_type']['help']); + if (!empty($arrayfields['aa.pcg_subtype']['checked'])) print_liste_field_titre($arrayfields['aa.pcg_subtype']['label'], $_SERVER["PHP_SELF"], 'aa.pcg_subtype', '', $param, '', $sortfield, $sortorder, '', $arrayfields['aa.pcg_subtype']['help']); + if (!empty($arrayfields['aa.active']['checked'])) print_liste_field_titre($arrayfields['aa.active']['label'], $_SERVER["PHP_SELF"], 'aa.active', '', $param, '', $sortfield, $sortorder); print_liste_field_titre($selectedfields, $_SERVER["PHP_SELF"], "", '', '', '', $sortfield, $sortorder, 'center maxwidthsearch '); print "\n"; $accountstatic = new AccountingAccount($db); $accountparent = new AccountingAccount($db); - $i=0; + $i = 0; while ($i < min($num, $limit)) { $obj = $db->fetch_object($resql); @@ -351,27 +351,27 @@ if ($resql) print ''; // Account number - if (! empty($arrayfields['aa.account_number']['checked'])) + if (!empty($arrayfields['aa.account_number']['checked'])) { print ""; print $accountstatic->getNomUrl(1, 0, 0, '', 0, 1); print "\n"; - if (! $i) $totalarray['nbfield']++; + if (!$i) $totalarray['nbfield']++; } // Account label - if (! empty($arrayfields['aa.label']['checked'])) + if (!empty($arrayfields['aa.label']['checked'])) { print ""; print $obj->label; print "\n"; - if (! $i) $totalarray['nbfield']++; + if (!$i) $totalarray['nbfield']++; } // Account parent - if (! empty($arrayfields['aa.account_parent']['checked'])) + if (!empty($arrayfields['aa.account_parent']['checked'])) { - if (! empty($obj->account_parent)) + if (!empty($obj->account_parent)) { $accountparent->id = $obj->rowid2; $accountparent->label = $obj->label2; @@ -380,63 +380,63 @@ if ($resql) print ""; print $accountparent->getNomUrl(1); print "\n"; - if (! $i) $totalarray['nbfield']++; + if (!$i) $totalarray['nbfield']++; } else { print ' '; - if (! $i) $totalarray['nbfield']++; + if (!$i) $totalarray['nbfield']++; } } // Chart of accounts type - if (! empty($arrayfields['aa.pcg_type']['checked'])) + if (!empty($arrayfields['aa.pcg_type']['checked'])) { print ""; print $obj->pcg_type; print "\n"; - if (! $i) $totalarray['nbfield']++; + if (!$i) $totalarray['nbfield']++; } // Chart of accounts subtype - if (! empty($arrayfields['aa.pcg_subtype']['checked'])) + if (!empty($arrayfields['aa.pcg_subtype']['checked'])) { print ""; print $obj->pcg_subtype; print "\n"; - if (! $i) $totalarray['nbfield']++; + if (!$i) $totalarray['nbfield']++; } // Activated or not - if (! empty($arrayfields['aa.active']['checked'])) + if (!empty($arrayfields['aa.active']['checked'])) { print ''; if (empty($obj->active)) { - print ''; + print ''; print img_picto($langs->trans("Disabled"), 'switch_off'); print ''; } else { - print ''; + print ''; print img_picto($langs->trans("Activated"), 'switch_on'); print ''; } print ''; - if (! $i) $totalarray['nbfield']++; + if (!$i) $totalarray['nbfield']++; } // Action print ''; if ($user->rights->accounting->chartofaccount) { - print ''; + print ''; print img_edit(); print ''; print ' '; - print ''; + print ''; print img_delete(); print ''; } - print '' . "\n"; - if (! $i) $totalarray['nbfield']++; + print ''."\n"; + if (!$i) $totalarray['nbfield']++; print "\n"; $i++; diff --git a/htdocs/accountancy/admin/accountmodel.php b/htdocs/accountancy/admin/accountmodel.php index 6f30f5ac7ec..da726597345 100644 --- a/htdocs/accountancy/admin/accountmodel.php +++ b/htdocs/accountancy/admin/accountmodel.php @@ -456,7 +456,7 @@ if ($id) print ''; print '
'; - print ''; + print '
'; // Form to add a new line if ($tabname[$id]) diff --git a/htdocs/accountancy/admin/card.php b/htdocs/accountancy/admin/card.php index f54c477ff52..8321b28ef04 100644 --- a/htdocs/accountancy/admin/card.php +++ b/htdocs/accountancy/admin/card.php @@ -24,15 +24,15 @@ */ require '../../main.inc.php'; -require_once DOL_DOCUMENT_ROOT . '/core/lib/accounting.lib.php'; -require_once DOL_DOCUMENT_ROOT . '/accountancy/class/accountingaccount.class.php'; -require_once DOL_DOCUMENT_ROOT . '/accountancy/class/accountancysystem.class.php'; -require_once DOL_DOCUMENT_ROOT . '/core/class/html.formaccounting.class.php'; +require_once DOL_DOCUMENT_ROOT.'/core/lib/accounting.lib.php'; +require_once DOL_DOCUMENT_ROOT.'/accountancy/class/accountingaccount.class.php'; +require_once DOL_DOCUMENT_ROOT.'/accountancy/class/accountancysystem.class.php'; +require_once DOL_DOCUMENT_ROOT.'/core/class/html.formaccounting.class.php'; $error = 0; // Load translation files required by the page -$langs->loadLangs(array("bills","accountancy")); +$langs->loadLangs(array("bills", "accountancy")); $mesg = ''; $action = GETPOST('action', 'aZ09'); @@ -55,24 +55,24 @@ $object = new AccountingAccount($db); if (GETPOST('cancel', 'alpha')) { - $urltogo=$backtopage?$backtopage:dol_buildpath('/accountancy/admin/account.php', 1); + $urltogo = $backtopage ? $backtopage : dol_buildpath('/accountancy/admin/account.php', 1); header("Location: ".$urltogo); exit; } if ($action == 'add' && $user->rights->accounting->chartofaccount) { - if (! $cancel) { - $sql = 'SELECT pcg_version FROM ' . MAIN_DB_PREFIX . 'accounting_system WHERE rowid=' . $conf->global->CHARTOFACCOUNTS; + if (!$cancel) { + $sql = 'SELECT pcg_version FROM '.MAIN_DB_PREFIX.'accounting_system WHERE rowid='.$conf->global->CHARTOFACCOUNTS; - dol_syslog('accountancy/admin/card.php:: $sql=' . $sql); + dol_syslog('accountancy/admin/card.php:: $sql='.$sql); $result = $db->query($sql); $obj = $db->fetch_object($result); // Clean code // To manage zero or not at the end of the accounting account - if($conf->global->ACCOUNTING_MANAGE_ZERO == 1) + if ($conf->global->ACCOUNTING_MANAGE_ZERO == 1) { $account_number = GETPOST('account_number', 'string'); } @@ -116,28 +116,28 @@ if ($action == 'add' && $user->rights->accounting->chartofaccount) setEventMessages($object->error, $object->errors, 'errors'); $action = "create"; } - if (! $error) + if (!$error) { setEventMessages("RecordCreatedSuccessfully", null, 'mesgs'); - $urltogo=$backtopage?$backtopage:dol_buildpath('/accountancy/admin/account.php', 1); + $urltogo = $backtopage ? $backtopage : dol_buildpath('/accountancy/admin/account.php', 1); header("Location: ".$urltogo); exit; } } } elseif ($action == 'edit' && $user->rights->accounting->chartofaccount) { - if (! $cancel) { + if (!$cancel) { $result = $object->fetch($id); - $sql = 'SELECT pcg_version FROM ' . MAIN_DB_PREFIX . 'accounting_system WHERE rowid=' . $conf->global->CHARTOFACCOUNTS; + $sql = 'SELECT pcg_version FROM '.MAIN_DB_PREFIX.'accounting_system WHERE rowid='.$conf->global->CHARTOFACCOUNTS; - dol_syslog('accountancy/admin/card.php:: $sql=' . $sql); + dol_syslog('accountancy/admin/card.php:: $sql='.$sql); $result2 = $db->query($sql); $obj = $db->fetch_object($result2); // Clean code // To manage zero or not at the end of the accounting account - if($conf->global->ACCOUNTING_MANAGE_ZERO == 1) + if ($conf->global->ACCOUNTING_MANAGE_ZERO == 1) { $account_number = GETPOST('account_number', 'string'); } @@ -166,21 +166,21 @@ if ($action == 'add' && $user->rights->accounting->chartofaccount) $result = $object->update($user); if ($result > 0) { - $urltogo=$backtopage?$backtopage:($_SERVER["PHP_SELF"]."?id=".$id); - header("Location: " . $urltogo); + $urltogo = $backtopage ? $backtopage : ($_SERVER["PHP_SELF"]."?id=".$id); + header("Location: ".$urltogo); exit(); } else { $mesg = $object->error; } } else { - $urltogo=$backtopage?$backtopage:($_SERVER["PHP_SELF"]."?id=".$id); - header("Location: " . $urltogo); + $urltogo = $backtopage ? $backtopage : ($_SERVER["PHP_SELF"]."?id=".$id); + header("Location: ".$urltogo); exit(); } } elseif ($action == 'delete' && $user->rights->accounting->chartofaccount) { $result = $object->fetch($id); - if (! empty($object->id)) { + if (!empty($object->id)) { $result = $object->delete($user); if ($result > 0) { @@ -205,7 +205,7 @@ $formaccounting = new FormAccounting($db); $accountsystem = new AccountancySystem($db); $accountsystem->fetch($conf->global->CHARTOFACCOUNTS); -$title = $langs->trans('AccountAccounting') ." - ". $langs->trans('Card'); +$title = $langs->trans('AccountAccounting')." - ".$langs->trans('Card'); $helpurl = ''; llxheader('', $title, $helpurl); @@ -214,50 +214,50 @@ llxheader('', $title, $helpurl); if ($action == 'create') { print load_fiche_titre($langs->trans('NewAccountingAccount')); - print '' . "\n"; - print ''; + print ''."\n"; + print ''; print ''; dol_fiche_head(); - print '
'; + print '
'; // Chart of account - print ''; + print ''; print ''; // Account number - print ''; - print ''; + print ''; + print ''; // Label - print ''; - print ''; + print ''; + print ''; // Account parent - print ''; + print ''; print ''; // Category - print ''; + print ''; print ''; // Chart of accounts type - print ''; + print ''; print ''; // Chart of acounts subtype - print ''; + print ''; print ''; print '
' . $langs->trans("Chartofaccounts") . '
'.$langs->trans("Chartofaccounts").''; print $accountsystem->ref; print '
' . $langs->trans("AccountNumber") . '
'.$langs->trans("AccountNumber").'
' . $langs->trans("Label") . '
'.$langs->trans("Label").'
' . $langs->trans("Accountparent") . '
'.$langs->trans("Accountparent").''; print $formaccounting->select_account($object->account_parent, 'account_parent', 1, null, 0, 0, 'minwidth200'); print '
' . $langs->trans("AccountingCategory") . '
'.$langs->trans("AccountingCategory").''; $formaccounting->select_accounting_category($object->account_category, 'account_category', 1, 0, 1); print '
' . $langs->trans("Pcgtype") . '
'.$langs->trans("Pcgtype").''; - print ''; + print ''; print '
' . $langs->trans("Pcgsubtype") . '
'.$langs->trans("Pcgsubtype").''; - print ''; + print ''; print '
'; @@ -265,9 +265,9 @@ if ($action == 'create') { dol_fiche_end(); print '
'; - print ''; + print ''; print '     '; - print ''; + print ''; print '
'; print ''; @@ -285,24 +285,24 @@ elseif ($id > 0 || $ref) { { dol_fiche_head($head, 'card', $langs->trans('AccountAccounting'), 0, 'billr'); - print '
' . "\n"; - print ''; + print ''."\n"; + print ''; print ''; - print ''; - print ''; + print ''; + print ''; - print ''; + print '
'; // Account number - print ''; - print ''; + print ''; + print ''; // Label - print ''; - print ''; + print ''; + print ''; // Account parent - print ''; + print ''; print ''; @@ -314,15 +314,15 @@ elseif ($id > 0 || $ref) { print ''; // Chart of accounts type - print ''; + print ''; print ''; // Chart of accounts subtype - print ''; + print ''; print ''; print '
' . $langs->trans("AccountNumber") . '
'.$langs->trans("AccountNumber").'
' . $langs->trans("Label") . '
'.$langs->trans("Label").'
' . $langs->trans("Accountparent") . '
'.$langs->trans("Accountparent").''; print $formaccounting->select_account($object->account_parent, 'account_parent', 1); print '
' . $langs->trans("Pcgtype") . '
'.$langs->trans("Pcgtype").''; - print ''; + print ''; print '
' . $langs->trans("Pcgsubtype") . '
'.$langs->trans("Pcgsubtype").''; - print ''; + print ''; print '
'; @@ -330,15 +330,15 @@ elseif ($id > 0 || $ref) { dol_fiche_end(); print '
'; - print ''; + print ''; print '     '; - print ''; + print ''; print '
'; print '
'; } else { // View mode - $linkback = '' . $langs->trans("BackToList") . ''; + $linkback = ''.$langs->trans("BackToList").''; dol_fiche_head($head, 'card', $langs->trans('AccountAccounting'), -1, 'billr'); @@ -348,30 +348,30 @@ elseif ($id > 0 || $ref) { print '
'; print '
'; - print ''; + print '
'; // Label - print ''; - print ''; + print ''; + print ''; // Account parent $accp = new AccountingAccount($db); - if (! empty($object->account_parent)) { + if (!empty($object->account_parent)) { $accp->fetch($object->account_parent, ''); } - print ''; - print ''; + print ''; + print ''; // Category print ""; // Chart of accounts type - print ''; - print ''; + print ''; + print ''; // Chart of accounts subtype - print ''; - print ''; + print ''; + print ''; print '
' . $langs->trans("Label") . '' . $object->label . '
'.$langs->trans("Label").''.$object->label.'
' . $langs->trans("Accountparent") . '' . $accp->account_number . ' - ' . $accp->label . '
'.$langs->trans("Accountparent").''.$accp->account_number.' - '.$accp->label.'
".$langs->trans("AccountingCategory")."".$object->account_category_label."
' . $langs->trans("Pcgtype") . '' . $object->pcg_type . '
'.$langs->trans("Pcgtype").''.$object->pcg_type.'
' . $langs->trans("Pcgsubtype") . '' . $object->pcg_subtype . '
'.$langs->trans("Pcgsubtype").''.$object->pcg_subtype.'
'; @@ -384,16 +384,16 @@ elseif ($id > 0 || $ref) { */ print '
'; - if (! empty($user->rights->accounting->chartofaccount)) { - print '' . $langs->trans('Modify') . ''; + if (!empty($user->rights->accounting->chartofaccount)) { + print ''.$langs->trans('Modify').''; } else { - print '' . $langs->trans('Modify') . ''; + print ''.$langs->trans('Modify').''; } - if (! empty($user->rights->accounting->chartofaccount)) { - print '' . $langs->trans('Delete') . ''; + if (!empty($user->rights->accounting->chartofaccount)) { + print ''.$langs->trans('Delete').''; } else { - print '' . $langs->trans('Delete') . ''; + print ''.$langs->trans('Delete').''; } print '
'; diff --git a/htdocs/accountancy/admin/categories.php b/htdocs/accountancy/admin/categories.php index 5fdd43eb020..7bbcf80ff1f 100644 --- a/htdocs/accountancy/admin/categories.php +++ b/htdocs/accountancy/admin/categories.php @@ -23,14 +23,14 @@ */ require '../../main.inc.php'; -require_once DOL_DOCUMENT_ROOT . '/core/lib/accounting.lib.php'; -require_once DOL_DOCUMENT_ROOT . '/accountancy/class/accountancycategory.class.php'; -require_once DOL_DOCUMENT_ROOT . '/core/class/html.formaccounting.class.php'; +require_once DOL_DOCUMENT_ROOT.'/core/lib/accounting.lib.php'; +require_once DOL_DOCUMENT_ROOT.'/accountancy/class/accountancycategory.class.php'; +require_once DOL_DOCUMENT_ROOT.'/core/class/html.formaccounting.class.php'; $error = 0; // Load translation files required by the page -$langs->loadLangs(array("bills","accountancy")); +$langs->loadLangs(array("bills", "accountancy")); $mesg = ''; $id = GETPOST('id', 'int'); @@ -59,16 +59,16 @@ $accountingcategory = new AccountancyCategory($db); */ // si ajout de comptes -if (! empty($selectcpt)) { +if (!empty($selectcpt)) { $cpts = array(); foreach ($selectcpt as $selectedoption) { - if (! array_key_exists($selectedoption, $cpts)) - $cpts[$selectedoption] = "'" . $selectedoption . "'"; + if (!array_key_exists($selectedoption, $cpts)) + $cpts[$selectedoption] = "'".$selectedoption."'"; } - $return= $accountingcategory->updateAccAcc($cat_id, $cpts); + $return = $accountingcategory->updateAccAcc($cat_id, $cpts); - if ($return<0) { + if ($return < 0) { setEventMessages($langs->trans('errors'), $accountingcategory->errors, 'errors'); } else { setEventMessages($langs->trans('RecordModifiedSuccessfully'), null, 'mesgs'); @@ -98,35 +98,35 @@ $linkback = '' . "\n"; -print ''; +print '
'."\n"; +print ''; print ''; dol_fiche_head(); -print ''; +print '
'; // Select the category -print ''; +print ''; print ''; // Select the accounts -if (! empty($cat_id)) +if (!empty($cat_id)) { $return = $accountingcategory->getAccountsWithNoCategory($cat_id); if ($return < 0) { setEventMessages(null, $accountingcategory->errors, 'errors'); } - print ''; + print ''; print ''; } @@ -158,8 +158,8 @@ if ($action == 'display' || $action == 'delete') { print '"; print "\n"; - if (! empty($cat_id)) { - $return = $accountingcategory->display($cat_id); // This load ->lines_display + if (!empty($cat_id)) { + $return = $accountingcategory->display($cat_id); // This load ->lines_display if ($return < 0) { setEventMessages(null, $accountingcategory->errors, 'errors'); } @@ -167,10 +167,10 @@ if ($action == 'display' || $action == 'delete') { if (is_array($accountingcategory->lines_display) && count($accountingcategory->lines_display) > 0) { foreach ($accountingcategory->lines_display as $cpt) { print ''; - print ''; - print ''; + print ''; + print ''; print ''; if ($action != 'editjournal') - print ''; + print ''; print '
' . $langs->trans("AccountingCategory") . '
'.$langs->trans("AccountingCategory").''; $formaccounting->select_accounting_category($cat_id, 'account_category', 1, 0, 0, 1); -print ''; +print ''; print '
' . $langs->trans("AddAccountFromBookKeepingWithNoCategories") . '
'.$langs->trans("AddAccountFromBookKeepingWithNoCategories").''; - $arraykeyvalue=array(); - foreach($accountingcategory->lines_cptbk as $key => $val) + $arraykeyvalue = array(); + foreach ($accountingcategory->lines_cptbk as $key => $val) { - $arraykeyvalue[length_accountg($val->numero_compte)] = length_accountg($val->numero_compte) . ' (' . $val->label_compte . ($val->doc_ref?' '.$val->doc_ref:'').')'; + $arraykeyvalue[length_accountg($val->numero_compte)] = length_accountg($val->numero_compte).' ('.$val->label_compte.($val->doc_ref ? ' '.$val->doc_ref : '').')'; } if (is_array($accountingcategory->lines_cptbk) && count($accountingcategory->lines_cptbk) > 0) { @@ -139,7 +139,7 @@ if (! empty($cat_id)) print '
'; print ajax_combobox('cpt_bk'); */ - print ' '; + print ' '; } print '
'.$langs->trans("Label")."
' . length_accountg($cpt->account_number) . '' . $cpt->label . ''.length_accountg($cpt->account_number).''.$cpt->label.''; - print ""; + print "rowid."'>"; print $langs->trans("DeleteFromCat"); print img_picto($langs->trans("DeleteFromCat"), 'unlink'); print ""; diff --git a/htdocs/accountancy/admin/categories_list.php b/htdocs/accountancy/admin/categories_list.php index 852349d0516..2d633debbae 100644 --- a/htdocs/accountancy/admin/categories_list.php +++ b/htdocs/accountancy/admin/categories_list.php @@ -32,13 +32,13 @@ require_once DOL_DOCUMENT_ROOT.'/core/lib/accounting.lib.php'; require_once DOL_DOCUMENT_ROOT.'/core/class/html.formaccounting.class.php'; // Load translation files required by the page -$langs->loadLangs(array("errors","admin","companies","resource","holiday","accountancy","hrm")); +$langs->loadLangs(array("errors", "admin", "companies", "resource", "holiday", "accountancy", "hrm")); -$action=GETPOST('action', 'aZ09')?GETPOST('action', 'aZ09'):'view'; -$confirm=GETPOST('confirm', 'alpha'); -$id=32; -$rowid=GETPOST('rowid', 'alpha'); -$code=GETPOST('code', 'alpha'); +$action = GETPOST('action', 'aZ09') ?GETPOST('action', 'aZ09') : 'view'; +$confirm = GETPOST('confirm', 'alpha'); +$id = 32; +$rowid = GETPOST('rowid', 'alpha'); +$code = GETPOST('code', 'alpha'); // Security access if (empty($user->rights->accounting->chartofaccount)) { @@ -50,15 +50,15 @@ $acts[1] = "disable"; $actl[0] = img_picto($langs->trans("Disabled"), 'switch_off'); $actl[1] = img_picto($langs->trans("Activated"), 'switch_on'); -$listoffset=GETPOST('listoffset', 'alpha'); -$listlimit=GETPOST('listlimit', 'int')>0?GETPOST('listlimit', 'int'):1000; +$listoffset = GETPOST('listoffset', 'alpha'); +$listlimit = GETPOST('listlimit', 'int') > 0 ?GETPOST('listlimit', 'int') : 1000; $active = 1; $sortfield = GETPOST("sortfield", 'aZ09comma'); $sortorder = GETPOST("sortorder", 'aZ09comma'); $page = GETPOST("page", 'int'); if (empty($page) || $page == -1) { $page = 0; } // If $page is not defined, or '' or -1 -$offset = $listlimit * $page ; +$offset = $listlimit * $page; $pageprev = $page - 1; $pagenext = $page + 1; @@ -71,52 +71,52 @@ $hookmanager->initHooks(array('admin')); // Put here declaration of dictionaries properties // Sort order to show dictionary (0 is space). All other dictionaries (added by modules) will be at end of this. -$taborder=array(32); +$taborder = array(32); // Name of SQL tables of dictionaries -$tabname=array(); -$tabname[32]= MAIN_DB_PREFIX."c_accounting_category"; +$tabname = array(); +$tabname[32] = MAIN_DB_PREFIX."c_accounting_category"; // Dictionary labels -$tablib=array(); -$tablib[32]= "DictionaryAccountancyCategory"; +$tablib = array(); +$tablib[32] = "DictionaryAccountancyCategory"; // Requests to extract data -$tabsql=array(); -$tabsql[32]= "SELECT a.rowid as rowid, a.code as code, a.label, a.range_account, a.category_type, a.formula, a.position as position, a.fk_country as country_id, c.code as country_code, c.label as country, a.active FROM ".MAIN_DB_PREFIX."c_accounting_category as a, ".MAIN_DB_PREFIX."c_country as c WHERE a.fk_country=c.rowid and c.active=1"; +$tabsql = array(); +$tabsql[32] = "SELECT a.rowid as rowid, a.code as code, a.label, a.range_account, a.category_type, a.formula, a.position as position, a.fk_country as country_id, c.code as country_code, c.label as country, a.active FROM ".MAIN_DB_PREFIX."c_accounting_category as a, ".MAIN_DB_PREFIX."c_country as c WHERE a.fk_country=c.rowid and c.active=1"; // Criteria to sort dictionaries -$tabsqlsort=array(); -$tabsqlsort[32]="position ASC"; +$tabsqlsort = array(); +$tabsqlsort[32] = "position ASC"; // Nom des champs en resultat de select pour affichage du dictionnaire -$tabfield=array(); -$tabfield[32]= "code,label,range_account,category_type,formula,position,country"; +$tabfield = array(); +$tabfield[32] = "code,label,range_account,category_type,formula,position,country"; // Nom des champs d'edition pour modification d'un enregistrement -$tabfieldvalue=array(); -$tabfieldvalue[32]= "code,label,range_account,category_type,formula,position,country_id"; +$tabfieldvalue = array(); +$tabfieldvalue[32] = "code,label,range_account,category_type,formula,position,country_id"; // Nom des champs dans la table pour insertion d'un enregistrement -$tabfieldinsert=array(); -$tabfieldinsert[32]= "code,label,range_account,category_type,formula,position,fk_country"; +$tabfieldinsert = array(); +$tabfieldinsert[32] = "code,label,range_account,category_type,formula,position,fk_country"; // Nom du rowid si le champ n'est pas de type autoincrement // Example: "" if id field is "rowid" and has autoincrement on // "nameoffield" if id field is not "rowid" or has not autoincrement on -$tabrowid=array(); -$tabrowid[32]= ""; +$tabrowid = array(); +$tabrowid[32] = ""; // Condition to show dictionary in setup page -$tabcond=array(); -$tabcond[32]= ! empty($conf->accounting->enabled); +$tabcond = array(); +$tabcond[32] = !empty($conf->accounting->enabled); // List of help for fields -$tabhelp=array(); +$tabhelp = array(); $tabhelp[32] = array('code'=>$langs->trans("EnterAnyCode"), 'category_type'=>$langs->trans("SetToYesIfGroupIsComputationOfOtherGroups"), 'formula'=>$langs->trans("EnterCalculationRuleIfPreviousFieldIsYes")); // List of check for fields (NOT USED YET) -$tabfieldcheck=array(); +$tabfieldcheck = array(); $tabfieldcheck[32] = array(); // Complete all arrays with entries found into modules @@ -125,7 +125,7 @@ complete_dictionary_with_modules($taborder, $tabname, $tablib, $tabsql, $tabsqls // Define elementList and sourceList (used for dictionary type of contacts "llx_c_type_contact") $elementList = array(); -$sourceList=array(); +$sourceList = array(); @@ -141,24 +141,24 @@ if (GETPOST('button_removefilter', 'alpha') || GETPOST('button_removefilter.x', // Actions add or modify an entry into a dictionary if (GETPOST('actionadd', 'alpha') || GETPOST('actionmodify', 'alpha')) { - $listfield=explode(',', str_replace(' ', '', $tabfield[$id])); - $listfieldinsert=explode(',', $tabfieldinsert[$id]); - $listfieldmodify=explode(',', $tabfieldinsert[$id]); - $listfieldvalue=explode(',', $tabfieldvalue[$id]); + $listfield = explode(',', str_replace(' ', '', $tabfield[$id])); + $listfieldinsert = explode(',', $tabfieldinsert[$id]); + $listfieldmodify = explode(',', $tabfieldinsert[$id]); + $listfieldvalue = explode(',', $tabfieldvalue[$id]); // Check that all fields are filled - $ok=1; + $ok = 1; foreach ($listfield as $f => $value) { if ($value == 'formula' && empty($_POST['formula'])) continue; if ($value == 'range_account' && empty($_POST['range_account'])) continue; if ($value == 'country' || $value == 'country_id') continue; - if (! isset($_POST[$value]) || $_POST[$value]=='') + if (!isset($_POST[$value]) || $_POST[$value] == '') { - $ok=0; - $fieldnamekey=$listfield[$f]; + $ok = 0; + $fieldnamekey = $listfield[$f]; // We take translate key of field - if ($fieldnamekey == 'libelle' || ($fieldnamekey == 'label')) $fieldnamekey='Label'; + if ($fieldnamekey == 'libelle' || ($fieldnamekey == 'label')) $fieldnamekey = 'Label'; if ($fieldnamekey == 'code') $fieldnamekey = 'Code'; if ($fieldnamekey == 'note') $fieldnamekey = 'Note'; if ($fieldnamekey == 'type') $fieldnamekey = 'Type'; @@ -170,23 +170,23 @@ if (GETPOST('actionadd', 'alpha') || GETPOST('actionmodify', 'alpha')) } if (isset($_POST["code"])) { - if ($_POST["code"]=='0') + if ($_POST["code"] == '0') { - $ok=0; + $ok = 0; setEventMessages($langs->transnoentities('ErrorCodeCantContainZero'), null, 'errors'); } } - if (! is_numeric(GETPOST('position', 'alpha'))) + if (!is_numeric(GETPOST('position', 'alpha'))) { $langs->loadLangs(array("errors")); - $ok=0; + $ok = 0; setEventMessages($langs->transnoentities('ErrorFieldMustBeANumeric', $langs->transnoentities("Position")), null, 'errors'); } // Clean some parameters - if ($_POST["accountancy_code"] <= 0) $_POST["accountancy_code"]=''; // If empty, we force to null - if ($_POST["accountancy_code_sell"] <= 0) $_POST["accountancy_code_sell"]=''; // If empty, we force to null - if ($_POST["accountancy_code_buy"] <= 0) $_POST["accountancy_code_buy"]=''; // If empty, we force to null + if ($_POST["accountancy_code"] <= 0) $_POST["accountancy_code"] = ''; // If empty, we force to null + if ($_POST["accountancy_code_sell"] <= 0) $_POST["accountancy_code_sell"] = ''; // If empty, we force to null + if ($_POST["accountancy_code_buy"] <= 0) $_POST["accountancy_code_buy"] = ''; // If empty, we force to null // Si verif ok et action add, on ajoute la ligne if ($ok && GETPOST('actionadd', 'alpha')) @@ -194,13 +194,13 @@ if (GETPOST('actionadd', 'alpha') || GETPOST('actionmodify', 'alpha')) if ($tabrowid[$id]) { // Recupere id libre pour insertion - $newid=0; + $newid = 0; $sql = "SELECT max(".$tabrowid[$id].") newid from ".$tabname[$id]; $result = $db->query($sql); if ($result) { $obj = $db->fetch_object($result); - $newid=($obj->newid + 1); + $newid = ($obj->newid + 1); } else { dol_print_error($db); } @@ -209,32 +209,32 @@ if (GETPOST('actionadd', 'alpha') || GETPOST('actionmodify', 'alpha')) // Add new entry $sql = "INSERT INTO ".$tabname[$id]." ("; // List of fields - if ($tabrowid[$id] && ! in_array($tabrowid[$id], $listfieldinsert)) $sql.= $tabrowid[$id].","; - $sql.= $tabfieldinsert[$id]; - $sql.=",active)"; - $sql.= " VALUES("; + if ($tabrowid[$id] && !in_array($tabrowid[$id], $listfieldinsert)) $sql .= $tabrowid[$id].","; + $sql .= $tabfieldinsert[$id]; + $sql .= ",active)"; + $sql .= " VALUES("; // List of values - if ($tabrowid[$id] && ! in_array($tabrowid[$id], $listfieldinsert)) $sql.= $newid.","; - $i=0; + if ($tabrowid[$id] && !in_array($tabrowid[$id], $listfieldinsert)) $sql .= $newid.","; + $i = 0; foreach ($listfieldinsert as $f => $value) { if ($value == 'entity') { $_POST[$listfieldvalue[$i]] = $conf->entity; } - if ($i) $sql.=","; - if ($_POST[$listfieldvalue[$i]] == '' && ! $listfieldvalue[$i] == 'formula') $sql.="null"; // For vat, we want/accept code = '' - else $sql.="'".$db->escape($_POST[$listfieldvalue[$i]])."'"; + if ($i) $sql .= ","; + if ($_POST[$listfieldvalue[$i]] == '' && !$listfieldvalue[$i] == 'formula') $sql .= "null"; // For vat, we want/accept code = '' + else $sql .= "'".$db->escape($_POST[$listfieldvalue[$i]])."'"; $i++; } - $sql.=",1)"; + $sql .= ",1)"; dol_syslog("actionadd", LOG_DEBUG); $result = $db->query($sql); if ($result) // Add is ok { setEventMessages($langs->transnoentities("RecordSaved"), null, 'mesgs'); - $_POST=array('id'=>$id); // Clean $_POST array, we keep only + $_POST = array('id'=>$id); // Clean $_POST array, we keep only } else { @@ -250,16 +250,16 @@ if (GETPOST('actionadd', 'alpha') || GETPOST('actionmodify', 'alpha')) // Si verif ok et action modify, on modifie la ligne if ($ok && GETPOST('actionmodify', 'alpha')) { - if ($tabrowid[$id]) { $rowidcol=$tabrowid[$id]; } - else { $rowidcol="rowid"; } + if ($tabrowid[$id]) { $rowidcol = $tabrowid[$id]; } + else { $rowidcol = "rowid"; } // Modify entry $sql = "UPDATE ".$tabname[$id]." SET "; // Modifie valeur des champs - if ($tabrowid[$id] && ! in_array($tabrowid[$id], $listfieldmodify)) + if ($tabrowid[$id] && !in_array($tabrowid[$id], $listfieldmodify)) { - $sql.= $tabrowid[$id]."="; - $sql.= "'".$db->escape($rowid)."', "; + $sql .= $tabrowid[$id]."="; + $sql .= "'".$db->escape($rowid)."', "; } $i = 0; foreach ($listfieldmodify as $field) @@ -270,18 +270,18 @@ if (GETPOST('actionadd', 'alpha') || GETPOST('actionmodify', 'alpha')) elseif ($field == 'entity') { $_POST[$listfieldvalue[$i]] = $conf->entity; } - if ($i) $sql.=","; - $sql.= $field."="; - if ($_POST[$listfieldvalue[$i]] == '' && ! $listfieldvalue[$i] == 'range_account') $sql.="null"; // For range_account, we want/accept code = '' - else $sql.="'".$db->escape($_POST[$listfieldvalue[$i]])."'"; + if ($i) $sql .= ","; + $sql .= $field."="; + if ($_POST[$listfieldvalue[$i]] == '' && !$listfieldvalue[$i] == 'range_account') $sql .= "null"; // For range_account, we want/accept code = '' + else $sql .= "'".$db->escape($_POST[$listfieldvalue[$i]])."'"; $i++; } - $sql.= " WHERE ".$rowidcol." = '".$rowid."'"; + $sql .= " WHERE ".$rowidcol." = '".$rowid."'"; dol_syslog("actionmodify", LOG_DEBUG); //print $sql; $resql = $db->query($sql); - if (! $resql) + if (!$resql) { setEventMessages($db->error(), null, 'errors'); } @@ -296,14 +296,14 @@ if (GETPOST('actioncancel', 'alpha')) if ($action == 'confirm_delete' && $confirm == 'yes') // delete { - if ($tabrowid[$id]) { $rowidcol=$tabrowid[$id]; } - else { $rowidcol="rowid"; } + if ($tabrowid[$id]) { $rowidcol = $tabrowid[$id]; } + else { $rowidcol = "rowid"; } $sql = "DELETE from ".$tabname[$id]." WHERE ".$rowidcol." = '".$db->escape($rowid)."'"; dol_syslog("delete", LOG_DEBUG); $result = $db->query($sql); - if (! $result) + if (!$result) { if ($db->errno() == 'DB_ERROR_CHILD_EXISTS') { @@ -319,8 +319,8 @@ if ($action == 'confirm_delete' && $confirm == 'yes') // delete // activate if ($action == $acts[0]) { - if ($tabrowid[$id]) { $rowidcol=$tabrowid[$id]; } - else { $rowidcol="rowid"; } + if ($tabrowid[$id]) { $rowidcol = $tabrowid[$id]; } + else { $rowidcol = "rowid"; } if ($rowid) { $sql = "UPDATE ".$tabname[$id]." SET active = 1 WHERE ".$rowidcol." = '".$db->escape($rowid)."'"; @@ -339,8 +339,8 @@ if ($action == $acts[0]) // disable if ($action == $acts[1]) { - if ($tabrowid[$id]) { $rowidcol=$tabrowid[$id]; } - else { $rowidcol="rowid"; } + if ($tabrowid[$id]) { $rowidcol = $tabrowid[$id]; } + else { $rowidcol = "rowid"; } if ($rowid) { $sql = "UPDATE ".$tabname[$id]." SET active = 0 WHERE ".$rowidcol." = '".$db->escape($rowid)."'"; @@ -359,8 +359,8 @@ if ($action == $acts[1]) // favorite if ($action == 'activate_favorite') { - if ($tabrowid[$id]) { $rowidcol=$tabrowid[$id]; } - else { $rowidcol="rowid"; } + if ($tabrowid[$id]) { $rowidcol = $tabrowid[$id]; } + else { $rowidcol = "rowid"; } if ($rowid) { $sql = "UPDATE ".$tabname[$id]." SET favorite = 1 WHERE ".$rowidcol." = '".$db->escape($rowid)."'"; @@ -379,8 +379,8 @@ if ($action == 'activate_favorite') // disable favorite if ($action == 'disable_favorite') { - if ($tabrowid[$id]) { $rowidcol=$tabrowid[$id]; } - else { $rowidcol="rowid"; } + if ($tabrowid[$id]) { $rowidcol = $tabrowid[$id]; } + else { $rowidcol = "rowid"; } if ($rowid) { $sql = "UPDATE ".$tabname[$id]." SET favorite = 0 WHERE ".$rowidcol." = '".$db->escape($rowid)."'"; @@ -402,13 +402,13 @@ if ($action == 'disable_favorite') */ $form = new Form($db); -$formadmin=new FormAdmin($db); +$formadmin = new FormAdmin($db); llxHeader('', $langs->trans('DictionaryAccountancyCategory')); -$titre=$langs->trans($tablib[$id]); -$linkback=''; -$titlepicto='title_setup'; +$titre = $langs->trans($tablib[$id]); +$linkback = ''; +$titlepicto = 'title_setup'; print load_fiche_titre($titre, $linkback, $titlepicto); @@ -417,7 +417,7 @@ print ''.$langs->trans("AccountingAccountGroupsDesc" // Confirmation de la suppression de la ligne if ($action == 'delete') { - print $form->formconfirm($_SERVER["PHP_SELF"].'?'.($page?'page='.$page.'&':'').'sortfield='.$sortfield.'&sortorder='.$sortorder.'&rowid='.$rowid.'&code='.$code.'&id='.$id.($search_country_id>0?'&search_country_id='.$search_country_id:''), $langs->trans('DeleteLine'), $langs->trans('ConfirmDeleteLine'), 'confirm_delete', '', 0, 1); + print $form->formconfirm($_SERVER["PHP_SELF"].'?'.($page ? 'page='.$page.'&' : '').'sortfield='.$sortfield.'&sortorder='.$sortorder.'&rowid='.$rowid.'&code='.$code.'&id='.$id.($search_country_id > 0 ? '&search_country_id='.$search_country_id : ''), $langs->trans('DeleteLine'), $langs->trans('ConfirmDeleteLine'), 'confirm_delete', '', 0, 1); } //var_dump($elementList); @@ -427,36 +427,36 @@ if ($action == 'delete') if ($id) { // Complete requete recherche valeurs avec critere de tri - $sql=$tabsql[$id]; + $sql = $tabsql[$id]; if ($search_country_id > 0) { - if (preg_match('/ WHERE /', $sql)) $sql.= " AND "; - else $sql.=" WHERE "; - $sql.= " (a.fk_country = ".$search_country_id." OR a.fk_country = 0)"; + if (preg_match('/ WHERE /', $sql)) $sql .= " AND "; + else $sql .= " WHERE "; + $sql .= " (a.fk_country = ".$search_country_id." OR a.fk_country = 0)"; } // If sort order is "country", we use country_code instead - if ($sortfield == 'country') $sortfield='country_code'; - $sql.=$db->order($sortfield, $sortorder); - $sql.=$db->plimit($listlimit+1, $offset); + if ($sortfield == 'country') $sortfield = 'country_code'; + $sql .= $db->order($sortfield, $sortorder); + $sql .= $db->plimit($listlimit + 1, $offset); //print $sql; - $fieldlist=explode(',', $tabfield[$id]); + $fieldlist = explode(',', $tabfield[$id]); print ''; print ''; print ''; print '
'; - print ''; + print '
'; // Form to add a new line if ($tabname[$id]) { - $alabelisused=0; + $alabelisused = 0; - $fieldlist=explode(',', $tabfield[$id]); + $fieldlist = explode(',', $tabfield[$id]); // Line for title print ''; @@ -464,55 +464,55 @@ if ($id) { // Determine le nom du champ par rapport aux noms possibles // dans les dictionnaires de donnees - $valuetoshow=ucfirst($fieldlist[$field]); // Par defaut - $valuetoshow=$langs->trans($valuetoshow); // try to translate - $class="left"; - if ($fieldlist[$field]=='type') { + $valuetoshow = ucfirst($fieldlist[$field]); // Par defaut + $valuetoshow = $langs->trans($valuetoshow); // try to translate + $class = "left"; + if ($fieldlist[$field] == 'type') { if ($tabname[$id] == MAIN_DB_PREFIX."c_paiement") { - $valuetoshow=$form->textwithtooltip($langs->trans("Type"), $langs->trans("TypePaymentDesc"), 2, 1, img_help(1, '')); + $valuetoshow = $form->textwithtooltip($langs->trans("Type"), $langs->trans("TypePaymentDesc"), 2, 1, img_help(1, '')); } else { - $valuetoshow=$langs->trans("Type"); + $valuetoshow = $langs->trans("Type"); } } - if ($fieldlist[$field]=='code') { - $valuetoshow=$langs->trans("Code"); + if ($fieldlist[$field] == 'code') { + $valuetoshow = $langs->trans("Code"); } - if ($fieldlist[$field]=='libelle' || $fieldlist[$field]=='label') { - $valuetoshow=$langs->trans("Label"); + if ($fieldlist[$field] == 'libelle' || $fieldlist[$field] == 'label') { + $valuetoshow = $langs->trans("Label"); } - if ($fieldlist[$field]=='libelle_facture') { - $valuetoshow=$langs->trans("LabelOnDocuments"); + if ($fieldlist[$field] == 'libelle_facture') { + $valuetoshow = $langs->trans("LabelOnDocuments"); } - if ($fieldlist[$field]=='country') { - $valuetoshow=$langs->trans("Country"); + if ($fieldlist[$field] == 'country') { + $valuetoshow = $langs->trans("Country"); } - if ($fieldlist[$field]=='accountancy_code') { - $valuetoshow=$langs->trans("AccountancyCode"); + if ($fieldlist[$field] == 'accountancy_code') { + $valuetoshow = $langs->trans("AccountancyCode"); } - if ($fieldlist[$field]=='accountancy_code_sell') { - $valuetoshow=$langs->trans("AccountancyCodeSell"); + if ($fieldlist[$field] == 'accountancy_code_sell') { + $valuetoshow = $langs->trans("AccountancyCodeSell"); } - if ($fieldlist[$field]=='accountancy_code_buy') { - $valuetoshow=$langs->trans("AccountancyCodeBuy"); + if ($fieldlist[$field] == 'accountancy_code_buy') { + $valuetoshow = $langs->trans("AccountancyCodeBuy"); } - if ($fieldlist[$field]=='pcg_version' || $fieldlist[$field]=='fk_pcg_version') { - $valuetoshow=$langs->trans("Pcg_version"); + if ($fieldlist[$field] == 'pcg_version' || $fieldlist[$field] == 'fk_pcg_version') { + $valuetoshow = $langs->trans("Pcg_version"); } - if ($fieldlist[$field]=='range_account') { - $valuetoshow=$langs->trans("Comment"); + if ($fieldlist[$field] == 'range_account') { + $valuetoshow = $langs->trans("Comment"); } - if ($fieldlist[$field]=='category_type') { - $valuetoshow=$langs->trans("Calculated"); + if ($fieldlist[$field] == 'category_type') { + $valuetoshow = $langs->trans("Calculated"); } if ($valuetoshow != '') { print ''; } - if ($fieldlist[$field]=='libelle' || $fieldlist[$field]=='label') $alabelisused=1; + if ($fieldlist[$field] == 'libelle' || $fieldlist[$field] == 'label') $alabelisused = 1; } print ''; print ""; - $colspan=count($fieldlist)+3; + $colspan = count($fieldlist) + 3; if ($id == 32) $colspan++; - print ''; // Keep   to have a line with enough height + print ''; // Keep   to have a line with enough height } // List of available record in database dol_syslog("htdocs/admin/dict", LOG_DEBUG); - $resql=$db->query($sql); + $resql = $db->query($sql); if ($resql) { $num = $db->num_rows($resql); $i = 0; $param = '&id='.$id; - if ($search_country_id > 0) $param.= '&search_country_id='.$search_country_id; + if ($search_country_id > 0) $param .= '&search_country_id='.$search_country_id; $paramwithsearch = $param; - if ($sortorder) $paramwithsearch.= '&sortorder='.$sortorder; - if ($sortfield) $paramwithsearch.= '&sortfield='.$sortfield; - if (GETPOST('from', 'alpha')) $paramwithsearch.= '&from='.GETPOST('from', 'alpha'); + if ($sortorder) $paramwithsearch .= '&sortorder='.$sortorder; + if ($sortfield) $paramwithsearch .= '&sortfield='.$sortfield; + if (GETPOST('from', 'alpha')) $paramwithsearch .= '&from='.GETPOST('from', 'alpha'); // There is several pages if ($num > $listlimit) { - print ''; } // Title line with search boxes print ''; - $filterfound=0; + $filterfound = 0; foreach ($fieldlist as $field => $value) { - $showfield=1; // By defaut + $showfield = 1; // By defaut - if ($fieldlist[$field]=='region_id' || $fieldlist[$field]=='country_id') { $showfield=0; } + if ($fieldlist[$field] == 'region_id' || $fieldlist[$field] == 'country_id') { $showfield = 0; } if ($showfield) { @@ -610,7 +610,7 @@ if ($id) print ''; @@ -622,80 +622,80 @@ if ($id) { // Determine le nom du champ par rapport aux noms possibles // dans les dictionnaires de donnees - $showfield=1; // By defaut - $class="left"; - $sortable=1; - $valuetoshow=''; + $showfield = 1; // By defaut + $class = "left"; + $sortable = 1; + $valuetoshow = ''; - $valuetoshow=ucfirst($fieldlist[$field]); // By defaut - $valuetoshow=$langs->trans($valuetoshow); // try to translate - if ($fieldlist[$field]=='source') { - $valuetoshow=$langs->trans("Contact"); + $valuetoshow = ucfirst($fieldlist[$field]); // By defaut + $valuetoshow = $langs->trans($valuetoshow); // try to translate + if ($fieldlist[$field] == 'source') { + $valuetoshow = $langs->trans("Contact"); } - if ($fieldlist[$field]=='price') { - $valuetoshow=$langs->trans("PriceUHT"); + if ($fieldlist[$field] == 'price') { + $valuetoshow = $langs->trans("PriceUHT"); } - if ($fieldlist[$field]=='taux') { + if ($fieldlist[$field] == 'taux') { if ($tabname[$id] != MAIN_DB_PREFIX."c_revenuestamp") { - $valuetoshow=$langs->trans("Rate"); + $valuetoshow = $langs->trans("Rate"); } else { - $valuetoshow=$langs->trans("Amount"); + $valuetoshow = $langs->trans("Amount"); } - $class='center'; + $class = 'center'; } - if ($fieldlist[$field]=='type') { - $valuetoshow=$langs->trans("Type"); + if ($fieldlist[$field] == 'type') { + $valuetoshow = $langs->trans("Type"); } - if ($fieldlist[$field]=='code') { - $valuetoshow=$langs->trans("Code"); + if ($fieldlist[$field] == 'code') { + $valuetoshow = $langs->trans("Code"); } - if ($fieldlist[$field]=='libelle' || $fieldlist[$field]=='label') { - $valuetoshow=$langs->trans("Label"); + if ($fieldlist[$field] == 'libelle' || $fieldlist[$field] == 'label') { + $valuetoshow = $langs->trans("Label"); } - if ($fieldlist[$field]=='country') { - $valuetoshow=$langs->trans("Country"); + if ($fieldlist[$field] == 'country') { + $valuetoshow = $langs->trans("Country"); } - if ($fieldlist[$field]=='region_id' || $fieldlist[$field]=='country_id') { - $showfield=0; + if ($fieldlist[$field] == 'region_id' || $fieldlist[$field] == 'country_id') { + $showfield = 0; } - if ($fieldlist[$field]=='accountancy_code') { - $valuetoshow=$langs->trans("AccountancyCode"); + if ($fieldlist[$field] == 'accountancy_code') { + $valuetoshow = $langs->trans("AccountancyCode"); } - if ($fieldlist[$field]=='accountancy_code_sell') { - $valuetoshow=$langs->trans("AccountancyCodeSell"); - $sortable=0; + if ($fieldlist[$field] == 'accountancy_code_sell') { + $valuetoshow = $langs->trans("AccountancyCodeSell"); + $sortable = 0; } - if ($fieldlist[$field]=='accountancy_code_buy') { - $valuetoshow=$langs->trans("AccountancyCodeBuy"); - $sortable=0; + if ($fieldlist[$field] == 'accountancy_code_buy') { + $valuetoshow = $langs->trans("AccountancyCodeBuy"); + $sortable = 0; } - if ($fieldlist[$field]=='fk_pcg_version') { - $valuetoshow=$langs->trans("Pcg_version"); + if ($fieldlist[$field] == 'fk_pcg_version') { + $valuetoshow = $langs->trans("Pcg_version"); } - if ($fieldlist[$field]=='account_parent') { - $valuetoshow=$langs->trans("Accountsparent"); + if ($fieldlist[$field] == 'account_parent') { + $valuetoshow = $langs->trans("Accountsparent"); } - if ($fieldlist[$field]=='pcg_type') { - $valuetoshow=$langs->trans("Pcg_type"); + if ($fieldlist[$field] == 'pcg_type') { + $valuetoshow = $langs->trans("Pcg_type"); } - if ($fieldlist[$field]=='pcg_subtype') { - $valuetoshow=$langs->trans("Pcg_subtype"); + if ($fieldlist[$field] == 'pcg_subtype') { + $valuetoshow = $langs->trans("Pcg_subtype"); } - if ($fieldlist[$field]=='type_template') { - $valuetoshow=$langs->trans("TypeOfTemplate"); + if ($fieldlist[$field] == 'type_template') { + $valuetoshow = $langs->trans("TypeOfTemplate"); } - if ($fieldlist[$field]=='range_account') { - $valuetoshow=$langs->trans("Comment"); + if ($fieldlist[$field] == 'range_account') { + $valuetoshow = $langs->trans("Comment"); } - if ($fieldlist[$field]=='category_type') { - $valuetoshow=$langs->trans("Calculated"); + if ($fieldlist[$field] == 'category_type') { + $valuetoshow = $langs->trans("Calculated"); } // Affiche nom du champ if ($showfield) { - print getTitleFieldOfList($valuetoshow, 0, $_SERVER["PHP_SELF"], ($sortable?$fieldlist[$field]:''), ($page?'page='.$page.'&':''), $param, "", $sortfield, $sortorder, $class.' '); + print getTitleFieldOfList($valuetoshow, 0, $_SERVER["PHP_SELF"], ($sortable ? $fieldlist[$field] : ''), ($page ? 'page='.$page.'&' : ''), $param, "", $sortfield, $sortorder, $class.' '); } } - print getTitleFieldOfList($langs->trans("Status"), 0, $_SERVER["PHP_SELF"], "active", ($page?'page='.$page.'&':''), $param, '', $sortfield, $sortorder, 'center '); + print getTitleFieldOfList($langs->trans("Status"), 0, $_SERVER["PHP_SELF"], "active", ($page ? 'page='.$page.'&' : ''), $param, '', $sortfield, $sortorder, 'center '); print getTitleFieldOfList(''); print getTitleFieldOfList(''); print getTitleFieldOfList(''); @@ -709,12 +709,12 @@ if ($id) $obj = $db->fetch_object($resql); //print_r($obj); print ''; - if ($action == 'edit' && ($rowid == (! empty($obj->rowid)?$obj->rowid:$obj->code))) + if ($action == 'edit' && ($rowid == (!empty($obj->rowid) ? $obj->rowid : $obj->code))) { - $tmpaction='edit'; - $parameters=array('fieldlist'=>$fieldlist, 'tabname'=>$tabname[$id]); - $reshook=$hookmanager->executeHooks('editDictionaryFieldlist', $parameters, $obj, $tmpaction); // Note that $action and $object may have been modified by some hooks - $error=$hookmanager->error; $errors=$hookmanager->errors; + $tmpaction = 'edit'; + $parameters = array('fieldlist'=>$fieldlist, 'tabname'=>$tabname[$id]); + $reshook = $hookmanager->executeHooks('editDictionaryFieldlist', $parameters, $obj, $tmpaction); // Note that $action and $object may have been modified by some hooks + $error = $hookmanager->error; $errors = $hookmanager->errors; // Show fields if (empty($reshook)) fieldListAccountingCategories($fieldlist, $obj, $tabname[$id], 'edit'); @@ -725,7 +725,7 @@ if ($id) print ''; print ''; print ''; - print '
'; + print '
'; print ''; print ''; print ''; @@ -733,71 +733,71 @@ if ($id) else { $tmpaction = 'view'; - $parameters=array('var'=>$var, 'fieldlist'=>$fieldlist, 'tabname'=>$tabname[$id]); - $reshook=$hookmanager->executeHooks('viewDictionaryFieldlist', $parameters, $obj, $tmpaction); // Note that $action and $object may have been modified by some hooks + $parameters = array('var'=>$var, 'fieldlist'=>$fieldlist, 'tabname'=>$tabname[$id]); + $reshook = $hookmanager->executeHooks('viewDictionaryFieldlist', $parameters, $obj, $tmpaction); // Note that $action and $object may have been modified by some hooks - $error=$hookmanager->error; $errors=$hookmanager->errors; + $error = $hookmanager->error; $errors = $hookmanager->errors; if (empty($reshook)) { foreach ($fieldlist as $field => $value) { - $showfield=1; - $class="left"; - $valuetoshow=$obj->{$fieldlist[$field]}; + $showfield = 1; + $class = "left"; + $valuetoshow = $obj->{$fieldlist[$field]}; if ($value == 'category_type') { $valuetoshow = yn($valuetoshow); } - elseif ($valuetoshow=='all') { - $valuetoshow=$langs->trans('All'); + elseif ($valuetoshow == 'all') { + $valuetoshow = $langs->trans('All'); } - elseif ($fieldlist[$field]=='country') { + elseif ($fieldlist[$field] == 'country') { if (empty($obj->country_code)) { - $valuetoshow='-'; + $valuetoshow = '-'; } else { - $key=$langs->trans("Country".strtoupper($obj->country_code)); - $valuetoshow=($key != "Country".strtoupper($obj->country_code)?$obj->country_code." - ".$key:$obj->country); + $key = $langs->trans("Country".strtoupper($obj->country_code)); + $valuetoshow = ($key != "Country".strtoupper($obj->country_code) ? $obj->country_code." - ".$key : $obj->country); } } - elseif ($fieldlist[$field]=='label' && $tabname[$id]==MAIN_DB_PREFIX.'c_country') { - $key=$langs->trans("Country".strtoupper($obj->code)); - $valuetoshow=($obj->code && $key != "Country".strtoupper($obj->code)?$key:$obj->{$fieldlist[$field]}); + elseif ($fieldlist[$field] == 'label' && $tabname[$id] == MAIN_DB_PREFIX.'c_country') { + $key = $langs->trans("Country".strtoupper($obj->code)); + $valuetoshow = ($obj->code && $key != "Country".strtoupper($obj->code) ? $key : $obj->{$fieldlist[$field]}); } - elseif ($fieldlist[$field]=='label' && $tabname[$id]==MAIN_DB_PREFIX.'c_availability') { + elseif ($fieldlist[$field] == 'label' && $tabname[$id] == MAIN_DB_PREFIX.'c_availability') { $langs->loadLangs(array("propal")); - $key=$langs->trans("AvailabilityType".strtoupper($obj->code)); - $valuetoshow=($obj->code && $key != "AvailabilityType".strtoupper($obj->code)?$key:$obj->{$fieldlist[$field]}); + $key = $langs->trans("AvailabilityType".strtoupper($obj->code)); + $valuetoshow = ($obj->code && $key != "AvailabilityType".strtoupper($obj->code) ? $key : $obj->{$fieldlist[$field]}); } - elseif ($fieldlist[$field]=='libelle' && $tabname[$id]==MAIN_DB_PREFIX.'c_actioncomm') { - $key=$langs->trans("Action".strtoupper($obj->code)); - $valuetoshow=($obj->code && $key != "Action".strtoupper($obj->code)?$key:$obj->{$fieldlist[$field]}); + elseif ($fieldlist[$field] == 'libelle' && $tabname[$id] == MAIN_DB_PREFIX.'c_actioncomm') { + $key = $langs->trans("Action".strtoupper($obj->code)); + $valuetoshow = ($obj->code && $key != "Action".strtoupper($obj->code) ? $key : $obj->{$fieldlist[$field]}); } - elseif ($fieldlist[$field]=='region_id' || $fieldlist[$field]=='country_id') { - $showfield=0; + elseif ($fieldlist[$field] == 'region_id' || $fieldlist[$field] == 'country_id') { + $showfield = 0; } - $class='tddict'; + $class = 'tddict'; // Show value for field if ($showfield) print ''; } } // Can an entry be erased or disabled ? - $iserasable=1;$canbedisabled=1;$canbemodified=1; // true by default + $iserasable = 1; $canbedisabled = 1; $canbemodified = 1; // true by default if (isset($obj->code)) { if (($obj->code == '0' || $obj->code == '' || preg_match('/unknown/i', $obj->code))) { $iserasable = 0; $canbedisabled = 0; } } - $canbemodified=$iserasable; + $canbemodified = $iserasable; - $url = $_SERVER["PHP_SELF"].'?'.($page?'page='.$page.'&':'').'sortfield='.$sortfield.'&sortorder='.$sortorder.'&rowid='.(! empty($obj->rowid)?$obj->rowid:(! empty($obj->code)?$obj->code:'')).'&code='.(! empty($obj->code)?urlencode($obj->code):''); + $url = $_SERVER["PHP_SELF"].'?'.($page ? 'page='.$page.'&' : '').'sortfield='.$sortfield.'&sortorder='.$sortorder.'&rowid='.(!empty($obj->rowid) ? $obj->rowid : (!empty($obj->code) ? $obj->code : '')).'&code='.(!empty($obj->code) ?urlencode($obj->code) : ''); if ($param) $url .= '&'.$param; - $url.='&'; + $url .= '&'; // Active print ''; } elseif ($fieldlist[$field] == 'country_id') { - if (! in_array('country', $fieldlist)) // If there is already a field country, we don't show country_id (avoid duplicate) + if (!in_array('country', $fieldlist)) // If there is already a field country, we don't show country_id (avoid duplicate) { - $country_id = (! empty($obj->{$fieldlist[$field]}) ? $obj->{$fieldlist[$field]} : 0); + $country_id = (!empty($obj->{$fieldlist[$field]}) ? $obj->{$fieldlist[$field]} : 0); print ''; @@ -904,21 +904,21 @@ function fieldListAccountingCategories($fieldlist, $obj = '', $tabname = '', $co } elseif ($fieldlist[$field] == 'category_type') { print ''; } elseif ($fieldlist[$field] == 'code' && isset($obj->{$fieldlist[$field]})) { - print ''; + print ''; } else { print ''; } } diff --git a/htdocs/accountancy/admin/closure.php b/htdocs/accountancy/admin/closure.php index a9199959905..cc69462d893 100644 --- a/htdocs/accountancy/admin/closure.php +++ b/htdocs/accountancy/admin/closure.php @@ -96,7 +96,7 @@ print '' print ''; // Define main accounts for closure -print '
'; - if (! empty($tabhelp[$id][$value]) && preg_match('/^http(s*):/i', $tabhelp[$id][$value])) print ''.$valuetoshow.' '.img_help(1, $valuetoshow).''; - elseif (! empty($tabhelp[$id][$value])) print $form->textwithpicto($valuetoshow, $tabhelp[$id][$value]); + if (!empty($tabhelp[$id][$value]) && preg_match('/^http(s*):/i', $tabhelp[$id][$value])) print ''.$valuetoshow.' '.img_help(1, $valuetoshow).''; + elseif (!empty($tabhelp[$id][$value])) print $form->textwithpicto($valuetoshow, $tabhelp[$id][$value]); else print $valuetoshow; print ''; @@ -533,14 +533,14 @@ if ($id) foreach ($fieldlist as $key=>$val) { if (GETPOST($val) != '') - $obj->$val=GETPOST($val); + $obj->$val = GETPOST($val); } } $tmpaction = 'create'; - $parameters=array('fieldlist'=>$fieldlist, 'tabname'=>$tabname[$id]); - $reshook=$hookmanager->executeHooks('createDictionaryFieldlist', $parameters, $obj, $tmpaction); // Note that $action and $object may have been modified by some hooks - $error=$hookmanager->error; $errors=$hookmanager->errors; + $parameters = array('fieldlist'=>$fieldlist, 'tabname'=>$tabname[$id]); + $reshook = $hookmanager->executeHooks('createDictionaryFieldlist', $parameters, $obj, $tmpaction); // Note that $action and $object may have been modified by some hooks + $error = $hookmanager->error; $errors = $hookmanager->errors; if (empty($reshook)) { @@ -552,42 +552,42 @@ if ($id) print '
 
 
'; - print_fleche_navigation($page, $_SERVER["PHP_SELF"], $paramwithsearch, ($num > $listlimit), ''); + print '
'; + print_fleche_navigation($page, $_SERVER["PHP_SELF"], $paramwithsearch, ($num > $listlimit), ''); print '
'; if ($filterfound) { - $searchpicto=$form->showFilterAndCheckAddButtons(0); + $searchpicto = $form->showFilterAndCheckAddButtons(0); print $searchpicto; } print '
'.$valuetoshow.''; @@ -865,38 +865,38 @@ $db->close(); */ function fieldListAccountingCategories($fieldlist, $obj = '', $tabname = '', $context = '') { - global $conf,$langs,$db; + global $conf, $langs, $db; global $form, $mysoc; global $region_id; - global $elementList,$sourceList,$localtax_typeList; + global $elementList, $sourceList, $localtax_typeList; global $bc; $formadmin = new FormAdmin($db); $formcompany = new FormCompany($db); - if (! empty($conf->accounting->enabled)) $formaccounting = new FormAccounting($db); + if (!empty($conf->accounting->enabled)) $formaccounting = new FormAccounting($db); foreach ($fieldlist as $field => $value) { if ($fieldlist[$field] == 'country') { print ''; - $fieldname='country'; + $fieldname = 'country'; if ($context == 'add') { - $fieldname='country_id'; + $fieldname = 'country_id'; print $form->select_country(GETPOST('country_id', 'int'), $fieldname, '', 28, 'maxwidth200 maxwidthonsmartphone'); } else { - print $form->select_country((! empty($obj->country_code)?$obj->country_code:(! empty($obj->country)?$obj->country:$mysoc->country_code)), $fieldname, '', 28, 'maxwidth200 maxwidthonsmartphone'); + print $form->select_country((!empty($obj->country_code) ? $obj->country_code : (!empty($obj->country) ? $obj->country : $mysoc->country_code)), $fieldname, '', 28, 'maxwidth200 maxwidthonsmartphone'); } print ''; print ''; print ''; - print $form->selectyesno($fieldlist[$field], (! empty($obj->{$fieldlist[$field]})?$obj->{$fieldlist[$field]}:''), 1); + print $form->selectyesno($fieldlist[$field], (!empty($obj->{$fieldlist[$field]}) ? $obj->{$fieldlist[$field]}:''), 1); print ''; - $size=''; $class=''; - if ($fieldlist[$field]=='code') $class='maxwidth100'; - if ($fieldlist[$field]=='position') $class='maxwidth50'; - if ($fieldlist[$field]=='libelle') $class='quatrevingtpercent'; - if ($fieldlist[$field]=='sortorder' || $fieldlist[$field]=='category_type') $size='size="2" '; - print ''; + $size = ''; $class = ''; + if ($fieldlist[$field] == 'code') $class = 'maxwidth100'; + if ($fieldlist[$field] == 'position') $class = 'maxwidth50'; + if ($fieldlist[$field] == 'libelle') $class = 'quatrevingtpercent'; + if ($fieldlist[$field] == 'sortorder' || $fieldlist[$field] == 'category_type') $size = 'size="2" '; + print ''; print '
'; +print '
'; foreach ($list_account_main as $key) { print ''; diff --git a/htdocs/accountancy/admin/defaultaccounts.php b/htdocs/accountancy/admin/defaultaccounts.php index 6b47578761c..6ddee1d147f 100644 --- a/htdocs/accountancy/admin/defaultaccounts.php +++ b/htdocs/accountancy/admin/defaultaccounts.php @@ -30,12 +30,12 @@ require '../../main.inc.php'; // Class -require_once DOL_DOCUMENT_ROOT . '/core/lib/admin.lib.php'; -require_once DOL_DOCUMENT_ROOT . '/core/lib/accounting.lib.php'; -require_once DOL_DOCUMENT_ROOT . '/core/class/html.formaccounting.class.php'; +require_once DOL_DOCUMENT_ROOT.'/core/lib/admin.lib.php'; +require_once DOL_DOCUMENT_ROOT.'/core/lib/accounting.lib.php'; +require_once DOL_DOCUMENT_ROOT.'/core/class/html.formaccounting.class.php'; // Load translation files required by the page -$langs->loadLangs(array("compta","bills","admin","accountancy","salaries","loan")); +$langs->loadLangs(array("compta", "bills", "admin", "accountancy", "salaries", "loan")); // Security check if (empty($user->rights->accounting->chartofaccount)) @@ -52,25 +52,40 @@ $list_account_main = array ( 'SALARIES_ACCOUNTING_ACCOUNT_PAYMENT', ); -$list_account = array ( - 'ACCOUNTING_PRODUCT_BUY_ACCOUNT', - 'ACCOUNTING_PRODUCT_SOLD_ACCOUNT', - 'ACCOUNTING_PRODUCT_SOLD_INTRA_ACCOUNT', - 'ACCOUNTING_PRODUCT_SOLD_EXPORT_ACCOUNT', - 'ACCOUNTING_SERVICE_BUY_ACCOUNT', - 'ACCOUNTING_SERVICE_SOLD_ACCOUNT', - 'ACCOUNTING_VAT_BUY_ACCOUNT', - 'ACCOUNTING_VAT_SOLD_ACCOUNT', - 'ACCOUNTING_VAT_PAY_ACCOUNT', - 'ACCOUNTING_ACCOUNT_SUSPENSE', - 'ACCOUNTING_ACCOUNT_TRANSFER_CASH', - 'DONATION_ACCOUNTINGACCOUNT', - 'ADHERENT_SUBSCRIPTION_ACCOUNTINGACCOUNT', - 'LOAN_ACCOUNTING_ACCOUNT_CAPITAL', - 'LOAN_ACCOUNTING_ACCOUNT_INTEREST', - 'LOAN_ACCOUNTING_ACCOUNT_INSURANCE' -); - +$list_account = array (); +$list_account[] = '---Product---'; +$list_account[] = 'ACCOUNTING_PRODUCT_BUY_ACCOUNT'; +$list_account[] = 'ACCOUNTING_PRODUCT_SOLD_ACCOUNT'; +if ($mysoc->isInEEC()) { + $list_account[] = 'ACCOUNTING_PRODUCT_SOLD_INTRA_ACCOUNT'; +} +$list_account[] = 'ACCOUNTING_PRODUCT_SOLD_EXPORT_ACCOUNT'; +$list_account[] = '---Service---'; +$list_account[] = 'ACCOUNTING_SERVICE_BUY_ACCOUNT'; +$list_account[] = 'ACCOUNTING_SERVICE_SOLD_ACCOUNT'; +if ($mysoc->isInEEC()) { + $list_account[] = 'ACCOUNTING_SERVICE_SOLD_INTRA_ACCOUNT'; +} +$list_account[] = 'ACCOUNTING_SERVICE_SOLD_EXPORT_ACCOUNT'; +$list_account[] = '---Other---'; +$list_account[] = 'ACCOUNTING_VAT_BUY_ACCOUNT'; +$list_account[] = 'ACCOUNTING_VAT_SOLD_ACCOUNT'; +$list_account[] = 'ACCOUNTING_VAT_PAY_ACCOUNT'; +$list_account[] = 'ACCOUNTING_ACCOUNT_SUSPENSE'; +if ($conf->banque->enabled) { + $list_account[] = 'ACCOUNTING_ACCOUNT_TRANSFER_CASH'; +} +if ($conf->don->enabled) { + $list_account[] = 'DONATION_ACCOUNTINGACCOUNT'; +} +if ($conf->adherent->enabled) { + $list_account[] = 'ADHERENT_SUBSCRIPTION_ACCOUNTINGACCOUNT'; +} +if ($conf->loan->enabled) { + $list_account[] = 'LOAN_ACCOUNTING_ACCOUNT_CAPITAL'; + $list_account[] = 'LOAN_ACCOUNTING_ACCOUNT_INTEREST'; + $list_account[] = 'LOAN_ACCOUNTING_ACCOUNT_INSURANCE'; +} /* * Actions @@ -82,12 +97,12 @@ if (GETPOST('change_chart', 'alpha')) { $chartofaccounts = GETPOST('chartofaccounts', 'int'); - if (! empty($chartofaccounts)) { - if (! dolibarr_set_const($db, 'CHARTOFACCOUNTS', $chartofaccounts, 'chaine', 0, '', $conf->entity)) { - $error ++; + if (!empty($chartofaccounts)) { + if (!dolibarr_set_const($db, 'CHARTOFACCOUNTS', $chartofaccounts, 'chaine', 0, '', $conf->entity)) { + $error++; } } else { - $error ++; + $error++; } } @@ -103,7 +118,12 @@ if ($action == 'update') { } foreach ($list_account as $constname) { - $constvalue = GETPOST($constname, 'alpha'); + $reg=array(); + if (preg_match('/---(.*)---/', $constname, $reg)) { // This is a separator + continue; + } + + $constvalue = GETPOST($constname, 'alpha'); if (! dolibarr_set_const($db, $constname, $constvalue, 'chaine', 0, '', $conf->entity)) { $error ++; @@ -133,27 +153,27 @@ print load_fiche_titre($langs->trans('MenuDefaultAccounts'), $linkback, 'title_a print ''.$langs->trans("DefaultBindingDesc").'
'; print '
'; -print ''; -print ''; +print ''; +print ''; print ''; // Define main accounts for thirdparty -print '
'; +print '
'; foreach ($list_account_main as $key) { print ''; // Param $label = $langs->trans($key); - $keydesc=$key.'_Desc'; + $keydesc = $key.'_Desc'; $htmltext = $langs->trans($keydesc); print ''; // Value - print ''; print ''; @@ -167,25 +187,31 @@ print '
'; // Define default accounts -print '
'; print $form->textwithpicto($label, $htmltext); print ''; // Do not force class=right, or it align also the content of the select box + print ''; // Do not force class=right, or it align also the content of the select box print $formaccounting->select_account($conf->global->$key, $key, 1, '', 1, 1); print '
'; +print '
'; foreach ($list_account as $key) { - print ''; - // Param - $label = $langs->trans($key); - print ''; - // Value - print ''; - print ''; + $reg=array(); + if (preg_match('/---(.*)---/', $key, $reg)) { + print ''; + } + else { + print ''; + // Param + $label = $langs->trans($key); + print ''; + // Value + print ''; + print ''; + } } print "
' . $label . ''; // Do not force class=right, or it align also the content of the select box - print $formaccounting->select_account($conf->global->$key, $key, 1, '', 1, 1); - print '
'.$langs->trans($reg[1]).'
' . $label . ''; // Do not force class=right, or it align also the content of the select box + print $formaccounting->select_account($conf->global->$key, $key, 1, '', 1, 1); + print '
\n"; -print '
'; +print '
'; print ''; diff --git a/htdocs/accountancy/admin/export.php b/htdocs/accountancy/admin/export.php index e506f5bf512..94664374a05 100644 --- a/htdocs/accountancy/admin/export.php +++ b/htdocs/accountancy/admin/export.php @@ -28,12 +28,12 @@ */ require '../../main.inc.php'; -require_once DOL_DOCUMENT_ROOT . '/core/lib/admin.lib.php'; -require_once DOL_DOCUMENT_ROOT . '/core/lib/accounting.lib.php'; -require_once DOL_DOCUMENT_ROOT . '/accountancy/class/accountancyexport.class.php'; +require_once DOL_DOCUMENT_ROOT.'/core/lib/admin.lib.php'; +require_once DOL_DOCUMENT_ROOT.'/core/lib/accounting.lib.php'; +require_once DOL_DOCUMENT_ROOT.'/accountancy/class/accountancyexport.class.php'; // Load translation files required by the page -$langs->loadLangs(array("compta","bills","admin","accountancy")); +$langs->loadLangs(array("compta", "bills", "admin", "accountancy")); // Security access if (empty($user->rights->accounting->chartofaccount)) @@ -57,7 +57,7 @@ $listformat = $configuration['format']; $listcr = $configuration['cr']; -$model_option = array ( +$model_option = array( '1' => array( 'label' => 'ACCOUNTING_EXPORT_FORMAT', 'param' => $listformat, @@ -86,37 +86,37 @@ if ($action == 'update') { $modelcsv = GETPOST('ACCOUNTING_EXPORT_MODELCSV', 'int'); - if (! empty($modelcsv)) { - if (! dolibarr_set_const($db, 'ACCOUNTING_EXPORT_MODELCSV', $modelcsv, 'chaine', 0, '', $conf->entity)) { - $error ++; + if (!empty($modelcsv)) { + if (!dolibarr_set_const($db, 'ACCOUNTING_EXPORT_MODELCSV', $modelcsv, 'chaine', 0, '', $conf->entity)) { + $error++; } //if ($modelcsv==AccountancyExport::$EXPORT_TYPE_QUADRATUS || $modelcsv==AccountancyExport::$EXPORT_TYPE_CIEL) { // dolibarr_set_const($db, 'ACCOUNTING_EXPORT_FORMAT', 'txt', 'chaine', 0, '', $conf->entity); //} } else { - $error ++; + $error++; } foreach ($main_option as $constname) { $constvalue = GETPOST($constname, 'alpha'); - if (! dolibarr_set_const($db, $constname, $constvalue, 'chaine', 0, '', $conf->entity)) { - $error ++; + if (!dolibarr_set_const($db, $constname, $constvalue, 'chaine', 0, '', $conf->entity)) { + $error++; } } foreach ($listparam[$modelcsv] as $key => $value) { $constante = $key; - if (strpos($constante, 'ACCOUNTING')!==false) { + if (strpos($constante, 'ACCOUNTING') !== false) { $constvalue = GETPOST($key, 'alpha'); - if (! dolibarr_set_const($db, $constante, $constvalue, 'chaine', 0, '', $conf->entity)) { - $error ++; + if (!dolibarr_set_const($db, $constante, $constvalue, 'chaine', 0, '', $conf->entity)) { + $error++; } } } - if (! $error) { + if (!$error) { // reload $configuration = AccountancyExport::getTypeConfig(); $listparam = $configuration['param']; @@ -138,7 +138,7 @@ $title = $langs->trans('ConfigAccountingExpert'); llxHeader('', $title); -$linkback=''; +$linkback = ''; // $linkback = '' . $langs->trans("BackToModuleList") . ''; print load_fiche_titre($langs->trans('ConfigAccountingExpert'), $linkback, 'accountancy'); @@ -187,17 +187,17 @@ print ' });'."\n"; print '})'."\n"; print ''."\n"; -print '
'; -print ''; +print ''; +print ''; print ''; /* * Main Options */ -print ''; +print '
'; print ''; -print ''; +print ''; print "\n"; $num = count($main_option); @@ -207,11 +207,11 @@ if ($num) { // Param $label = $langs->trans($key); - print ''; + print ''; // Value print ''; } } @@ -223,16 +223,16 @@ print "
\n"; /* * Export model */ -print '
' . $langs->trans('Options') . ''.$langs->trans('Options').'
' . $label . ''.$label.''; - print ''; + print ''; print '
'; +print '
'; print ''; -print ''; +print ''; print ''; print ''; -print ''; -if (! $conf->use_javascript_ajax) { +print ''; +if (!$conf->use_javascript_ajax) { print '"; @@ -254,9 +254,9 @@ print "
\n"; $num2 = count($model_option); if ($num2) { - print '
' . $langs->trans("Modelcsv") . ''.$langs->trans("Modelcsv").'
' . $langs->trans("Selectmodelcsv") . ''.$langs->trans("Selectmodelcsv").''; print $langs->trans("NotAvailableWhenAjaxDisabled"); print "
'; + print '
'; print ''; - print ''; + print ''; print "\n"; foreach ($model_option as $key) { @@ -264,14 +264,14 @@ if ($num2) { // Param $label = $key['label']; - print ''; + print ''; // Value print ''; @@ -280,7 +280,7 @@ if ($num2) { print "
' . $langs->trans('OtherOptions') . ''.$langs->trans('OtherOptions').'
' . $langs->trans($label) . ''.$langs->trans($label).''; if (is_array($key['param'])) { print $form->selectarray($label, $key['param'], $conf->global->$label, 0); } else { - print ''; + print ''; } print '
\n"; } -print '
'; +print '
'; print '
'; diff --git a/htdocs/accountancy/admin/fiscalyear.php b/htdocs/accountancy/admin/fiscalyear.php index 5b1fa9df4ec..7dd4ae1a935 100644 --- a/htdocs/accountancy/admin/fiscalyear.php +++ b/htdocs/accountancy/admin/fiscalyear.php @@ -22,13 +22,13 @@ */ require '../../main.inc.php'; -require_once DOL_DOCUMENT_ROOT . '/core/lib/date.lib.php'; -require_once DOL_DOCUMENT_ROOT . '/core/class/fiscalyear.class.php'; +require_once DOL_DOCUMENT_ROOT.'/core/lib/date.lib.php'; +require_once DOL_DOCUMENT_ROOT.'/core/class/fiscalyear.class.php'; $action = GETPOST('action', 'aZ09'); // Load variable for pagination -$limit = GETPOST('limit', 'int')?GETPOST('limit', 'int'):$conf->liste_limit; +$limit = GETPOST('limit', 'int') ?GETPOST('limit', 'int') : $conf->liste_limit; $sortfield = GETPOST('sortfield', 'alpha'); $sortorder = GETPOST('sortorder', 'alpha'); $page = GETPOST('page', 'int'); @@ -36,32 +36,32 @@ if (empty($page) || $page == -1) { $page = 0; } // If $page is not defined, $offset = $limit * $page; $pageprev = $page - 1; $pagenext = $page + 1; -if (! $sortfield) $sortfield="f.rowid"; // Set here default search field -if (! $sortorder) $sortorder="ASC"; +if (!$sortfield) $sortfield = "f.rowid"; // Set here default search field +if (!$sortorder) $sortorder = "ASC"; // Load translation files required by the page -$langs->loadLangs(array("admin","compta")); +$langs->loadLangs(array("admin", "compta")); // Security check if ($user->socid > 0) accessforbidden(); -if (! $user->rights->accounting->fiscalyear->write) // If we can read accounting records, we should be able to see fiscal year. +if (!$user->rights->accounting->fiscalyear->write) // If we can read accounting records, we should be able to see fiscal year. accessforbidden(); $error = 0; // List of status -static $tmpstatut2label = array ( +static $tmpstatut2label = array( '0' => 'OpenFiscalYear', '1' => 'CloseFiscalYear' ); -$statut2label = array ( +$statut2label = array( '' ); foreach ($tmpstatut2label as $key => $val) $statut2label[$key] = $langs->trans($val); -$errors = array (); +$errors = array(); $object = new Fiscalyear($db); @@ -85,9 +85,9 @@ $helpurl = ""; llxHeader('', $title, $helpurl); $sql = "SELECT f.rowid, f.label, f.date_start, f.date_end, f.statut, f.entity"; -$sql .= " FROM " . MAIN_DB_PREFIX . "accounting_fiscalyear as f"; -$sql .= " WHERE f.entity = " . $conf->entity; -$sql.=$db->order($sortfield, $sortorder); +$sql .= " FROM ".MAIN_DB_PREFIX."accounting_fiscalyear as f"; +$sql .= " WHERE f.entity = ".$conf->entity; +$sql .= $db->order($sortfield, $sortorder); // Count total nb of records $nbtotalofrecords = ''; @@ -102,7 +102,7 @@ if (empty($conf->global->MAIN_DISABLE_FULL_SCANLIST)) } } -$sql.= $db->plimit($limit+1, $offset); +$sql .= $db->plimit($limit + 1, $offset); $result = $db->query($sql); if ($result) @@ -112,7 +112,7 @@ if ($result) $i = 0; - $addbutton.= dolGetButtonTitle($langs->trans('NewFiscalYear'), '', 'fa fa-plus-circle', 'fiscalyear_card.php?action=create', '', $user->rights->accounting->fiscalyear->write); + $addbutton .= dolGetButtonTitle($langs->trans('NewFiscalYear'), '', 'fa fa-plus-circle', 'fiscalyear_card.php?action=create', '', $user->rights->accounting->fiscalyear->write); $title = $langs->trans('AccountingPeriods'); @@ -120,36 +120,36 @@ if ($result) // Load attribute_label print '
'; - print ''; + print '
'; print ''; - print ''; - print ''; - print ''; - print ''; - print ''; - print ''; - print ''; + print ''; + print ''; + print ''; + print ''; + print ''; + print ''; + print ''; print ''; if ($num) { $fiscalyearstatic = new Fiscalyear($db); - while ( $i < $num && $i < $max ) { + while ($i < $num && $i < $max) { $obj = $db->fetch_object($result); $fiscalyearstatic->id = $obj->rowid; print ''; - print ''; - print ''; - print ''; - print ''; - print ''; - print ''; - print ''; + print ''; + print ''; + print ''; + print ''; + print ''; + print ''; + print ''; print ''; $i++; } } else { - print ''; + print ''; } print '
' . $langs->trans("Ref") . '' . $langs->trans("Label") . '' . $langs->trans("DateStart") . '' . $langs->trans("DateEnd") . '' . $langs->trans("NumberOfAccountancyEntries") . '' . $langs->trans("NumberOfAccountancyMovements") . '' . $langs->trans("Statut") . ''.$langs->trans("Ref").''.$langs->trans("Label").''.$langs->trans("DateStart").''.$langs->trans("DateEnd").''.$langs->trans("NumberOfAccountancyEntries").''.$langs->trans("NumberOfAccountancyMovements").''.$langs->trans("Statut").'
' . img_object($langs->trans("ShowFiscalYear"), "technic") . ' ' . $obj->rowid . '' . $obj->label . '' . dol_print_date($db->jdate($obj->date_start), 'day') . '' . dol_print_date($db->jdate($obj->date_end), 'day') . '' . $object->getAccountancyEntriesByFiscalYear($obj->date_start, $obj->date_end) . '' . $object->getAccountancyMovementsByFiscalYear($obj->date_start, $obj->date_end) . '' . $fiscalyearstatic->LibStatut($obj->statut, 5) . ''.img_object($langs->trans("ShowFiscalYear"), "technic").' '.$obj->rowid.''.$obj->label.''.dol_print_date($db->jdate($obj->date_start), 'day').''.dol_print_date($db->jdate($obj->date_end), 'day').''.$object->getAccountancyEntriesByFiscalYear($obj->date_start, $obj->date_end).''.$object->getAccountancyMovementsByFiscalYear($obj->date_start, $obj->date_end).''.$fiscalyearstatic->LibStatut($obj->statut, 5).'
' . $langs->trans("None") . '
'.$langs->trans("None").'
'; print '
'; diff --git a/htdocs/accountancy/admin/fiscalyear_card.php b/htdocs/accountancy/admin/fiscalyear_card.php index 42b9d231fe3..3656a8f16a2 100644 --- a/htdocs/accountancy/admin/fiscalyear_card.php +++ b/htdocs/accountancy/admin/fiscalyear_card.php @@ -24,11 +24,11 @@ require '../../main.inc.php'; -require_once DOL_DOCUMENT_ROOT . '/core/lib/fiscalyear.lib.php'; -require_once DOL_DOCUMENT_ROOT . '/core/class/fiscalyear.class.php'; +require_once DOL_DOCUMENT_ROOT.'/core/lib/fiscalyear.lib.php'; +require_once DOL_DOCUMENT_ROOT.'/core/class/fiscalyear.class.php'; // Load translation files required by the page -$langs->loadLangs(array("admin","compta")); +$langs->loadLangs(array("admin", "compta")); // Security check if ($user->socid > 0) @@ -43,11 +43,11 @@ $confirm = GETPOST('confirm', 'alpha'); $id = GETPOST('id', 'int'); // List of statut -static $tmpstatut2label = array ( +static $tmpstatut2label = array( '0' => 'OpenFiscalYear', '1' => 'CloseFiscalYear' ); -$statut2label = array ( +$statut2label = array( '' ); foreach ($tmpstatut2label as $key => $val) @@ -74,7 +74,7 @@ if ($action == 'confirm_delete' && $confirm == "yes") { } elseif ($action == 'add') { - if (! GETPOST('cancel', 'alpha')) { + if (!GETPOST('cancel', 'alpha')) { $error = 0; $object->date_start = $date_start; @@ -85,14 +85,14 @@ elseif ($action == 'add') { if (empty($object->date_start) && empty($object->date_end)) { setEventMessages($langs->trans("ErrorFieldRequired", $langs->transnoentitiesnoconv("Date")), null, 'errors'); - $error ++; + $error++; } if (empty($object->label)) { setEventMessages($langs->trans("ErrorFieldRequired", $langs->transnoentitiesnoconv("Label")), null, 'errors'); - $error ++; + $error++; } - if (! $error) { + if (!$error) { $db->begin(); $id = $object->create($user); @@ -100,7 +100,7 @@ elseif ($action == 'add') { if ($id > 0) { $db->commit(); - header("Location: " . $_SERVER["PHP_SELF"] . "?id=" . $id); + header("Location: ".$_SERVER["PHP_SELF"]."?id=".$id); exit(); } else { $db->rollback(); @@ -119,7 +119,7 @@ elseif ($action == 'add') { // Update record elseif ($action == 'update') { - if (! GETPOST('cancel', 'alpha')) { + if (!GETPOST('cancel', 'alpha')) { $result = $object->fetch($id); $object->date_start = empty($_POST["fiscalyear"]) ? '' : $date_start; @@ -130,13 +130,13 @@ elseif ($action == 'update') { $result = $object->update($user); if ($result > 0) { - header("Location: " . $_SERVER["PHP_SELF"] . "?id=" . $id); + header("Location: ".$_SERVER["PHP_SELF"]."?id=".$id); exit(); } else { setEventMessages($object->error, $object->errors, 'errors'); } } else { - header("Location: " . $_SERVER["PHP_SELF"] . "?id=" . $id); + header("Location: ".$_SERVER["PHP_SELF"]."?id=".$id); exit(); } } @@ -149,7 +149,7 @@ elseif ($action == 'update') { $form = new Form($db); -$title = $langs->trans("Fiscalyear") . " - " . $langs->trans("Card"); +$title = $langs->trans("Fiscalyear")." - ".$langs->trans("Card"); $helpurl = ""; llxHeader("", $title, $helpurl); @@ -157,24 +157,24 @@ if ($action == 'create') { print load_fiche_titre($langs->trans("NewFiscalYear")); - print '
'; - print ''; + print ''; + print ''; print ''; dol_fiche_head(); - print ''; + print '
'; // Label - print ''; + print ''; // Date start - print ''; // Date end - print ''; @@ -192,9 +192,9 @@ if ($action == 'create') dol_fiche_end(); print '
'; - print ''; + print ''; print '     '; - print ''; + print ''; print '
'; print ''; @@ -206,36 +206,36 @@ if ($action == 'create') if ($action == 'edit') { dol_fiche_head($head, 'card', $langs->trans("Fiscalyear"), 0, 'cron'); - print '' . "\n"; - print ''; + print ''."\n"; + print ''; print ''; - print ''; + print ''; - print '
' . $langs->trans("Label") . '
'.$langs->trans("Label").'
' . $langs->trans("DateStart") . ''; + print '
'.$langs->trans("DateStart").''; print $form->selectDate(($date_start ? $date_start : ''), 'fiscalyear'); print '
' . $langs->trans("DateEnd") . ''; + print '
'.$langs->trans("DateEnd").''; print $form->selectDate(($date_end ? $date_end : - 1), 'fiscalyearend'); print '
'; + print '
'; // Ref print ""; - print ''; // Label - print ''; // Date start - print ''; // Date end - print ''; // Statut - print ''; @@ -243,9 +243,9 @@ if ($action == 'create') print '
' . $langs->trans("Ref") . ''; + print ''.$langs->trans("Ref").''; print $object->ref; print '
' . $langs->trans("Label") . ''; - print ''; + print '
'.$langs->trans("Label").''; + print ''; print '
' . $langs->trans("DateStart") . ''; + print '
'.$langs->trans("DateStart").''; print $form->selectDate($object->date_start ? $object->date_start : - 1, 'fiscalyear'); print '
' . $langs->trans("DateEnd") . ''; + print '
'.$langs->trans("DateEnd").''; print $form->selectDate($object->date_end ? $object->date_end : - 1, 'fiscalyearend'); print '
' . $langs->trans("Statut") . ''; + print '
'.$langs->trans("Statut").''; // print $form->selectarray('statut', $statut2label, $object->statut); print $object->getLibStatut(4); print '
'; print '
'; - print ''; + print ''; print '     '; - print ''; + print ''; print '
'; print ''; @@ -256,17 +256,17 @@ if ($action == 'create') * Confirm delete */ if ($action == 'delete') { - print $form->formconfirm($_SERVER["PHP_SELF"] . "?id=" . $id, $langs->trans("DeleteFiscalYear"), $langs->trans("ConfirmDeleteFiscalYear"), "confirm_delete"); + print $form->formconfirm($_SERVER["PHP_SELF"]."?id=".$id, $langs->trans("DeleteFiscalYear"), $langs->trans("ConfirmDeleteFiscalYear"), "confirm_delete"); } dol_fiche_head($head, 'card', $langs->trans("Fiscalyear"), 0, 'cron'); - print ''; + print '
'; - $linkback = '' . $langs->trans("BackToList") . ''; + $linkback = ''.$langs->trans("BackToList").''; // Ref - print ''; // Statut - print ''; + print ''; print "
' . $langs->trans("Ref") . ''; + print '
'.$langs->trans("Ref").''; print $object->ref; print ''; print $linkback; @@ -294,20 +294,20 @@ if ($action == 'create') print '
' . $langs->trans("Status") . '' . $object->getLibStatut(4) . '
'.$langs->trans("Status").''.$object->getLibStatut(4).'
"; dol_fiche_end(); - if (! empty($user->rights->accounting->fiscalyear->write)) + if (!empty($user->rights->accounting->fiscalyear->write)) { /* * Barre d'actions */ print '
'; - print '' . $langs->trans('Modify') . ''; + print ''.$langs->trans('Modify').''; // print '' . $langs->trans('Delete') . ''; diff --git a/htdocs/accountancy/admin/index.php b/htdocs/accountancy/admin/index.php index 0460f31af30..d4630c4505f 100644 --- a/htdocs/accountancy/admin/index.php +++ b/htdocs/accountancy/admin/index.php @@ -29,11 +29,11 @@ */ require '../../main.inc.php'; -require_once DOL_DOCUMENT_ROOT . '/core/lib/admin.lib.php'; -require_once DOL_DOCUMENT_ROOT . '/core/lib/accounting.lib.php'; +require_once DOL_DOCUMENT_ROOT.'/core/lib/admin.lib.php'; +require_once DOL_DOCUMENT_ROOT.'/core/lib/accounting.lib.php'; // Load translation files required by the page -$langs->loadLangs(array("compta","bills","admin","accountancy")); +$langs->loadLangs(array("compta", "bills", "admin", "accountancy")); // Security access if (empty($user->rights->accounting->chartofaccount)) @@ -44,9 +44,9 @@ if (empty($user->rights->accounting->chartofaccount)) $action = GETPOST('action', 'aZ09'); // Parameters ACCOUNTING_* and others -$list = array ( +$list = array( 'ACCOUNTING_LENGTH_GACCOUNT', - 'ACCOUNTING_LENGTH_AACCOUNT' , + 'ACCOUNTING_LENGTH_AACCOUNT', // 'ACCOUNTING_LENGTH_DESCRIPTION', // adjust size displayed for lines description for dol_trunc // 'ACCOUNTING_LENGTH_DESCRIPTION_ACCOUNT', // adjust size displayed for select account description for dol_trunc ); @@ -62,13 +62,13 @@ $accounting_mode = empty($conf->global->ACCOUNTING_MODE) ? 'RECETTES-DEPENSES' : if ($action == 'update') { $error = 0; - if (! $error) + if (!$error) { foreach ($list as $constname) { $constvalue = GETPOST($constname, 'alpha'); - if (! dolibarr_set_const($db, $constname, $constvalue, 'chaine', 0, '', $conf->entity)) { + if (!dolibarr_set_const($db, $constname, $constvalue, 'chaine', 0, '', $conf->entity)) { $error++; } } @@ -77,7 +77,7 @@ if ($action == 'update') { } } - if (! $error) { + if (!$error) { setEventMessages($langs->trans("SetupSaved"), null, 'mesgs'); } } @@ -85,10 +85,10 @@ if ($action == 'update') { if ($action == 'setlistsorttodo') { $setlistsorttodo = GETPOST('value', 'int'); $res = dolibarr_set_const($db, "ACCOUNTING_LIST_SORT_VENTILATION_TODO", $setlistsorttodo, 'yesno', 0, '', $conf->entity); - if (! $res > 0) - $error ++; + if (!$res > 0) + $error++; - if (! $error) { + if (!$error) { setEventMessages($langs->trans("SetupSaved"), null, 'mesgs'); } else { setEventMessages($langs->trans("Error"), null, 'mesgs'); @@ -98,9 +98,9 @@ if ($action == 'setlistsorttodo') { if ($action == 'setlistsortdone') { $setlistsortdone = GETPOST('value', 'int'); $res = dolibarr_set_const($db, "ACCOUNTING_LIST_SORT_VENTILATION_DONE", $setlistsortdone, 'yesno', 0, '', $conf->entity); - if (! $res > 0) - $error ++; - if (! $error) { + if (!$res > 0) + $error++; + if (!$error) { setEventMessages($langs->trans("SetupSaved"), null, 'mesgs'); } else { setEventMessages($langs->trans("Error"), null, 'mesgs'); @@ -110,9 +110,9 @@ if ($action == 'setlistsortdone') { if ($action == 'setmanagezero') { $setmanagezero = GETPOST('value', 'int'); $res = dolibarr_set_const($db, "ACCOUNTING_MANAGE_ZERO", $setmanagezero, 'yesno', 0, '', $conf->entity); - if (! $res > 0) - $error ++; - if (! $error) { + if (!$res > 0) + $error++; + if (!$error) { setEventMessages($langs->trans("SetupSaved"), null, 'mesgs'); } else { setEventMessages($langs->trans("Error"), null, 'mesgs'); @@ -122,9 +122,9 @@ if ($action == 'setmanagezero') { if ($action == 'setdisabledirectinput') { $setdisabledirectinput = GETPOST('value', 'int'); $res = dolibarr_set_const($db, "BANK_DISABLE_DIRECT_INPUT", $setdisabledirectinput, 'yesno', 0, '', $conf->entity); - if (! $res > 0) - $error ++; - if (! $error) { + if (!$res > 0) + $error++; + if (!$error) { setEventMessages($langs->trans("SetupSaved"), null, 'mesgs'); } else { setEventMessages($langs->trans("Error"), null, 'mesgs'); @@ -134,9 +134,9 @@ if ($action == 'setdisabledirectinput') { if ($action == 'setenabledraftexport') { $setenabledraftexport = GETPOST('value', 'int'); $res = dolibarr_set_const($db, "ACCOUNTING_ENABLE_EXPORT_DRAFT_JOURNAL", $setenabledraftexport, 'yesno', 0, '', $conf->entity); - if (! $res > 0) - $error ++; - if (! $error) { + if (!$res > 0) + $error++; + if (!$error) { setEventMessages($langs->trans("SetupSaved"), null, 'mesgs'); } else { setEventMessages($langs->trans("Error"), null, 'mesgs'); @@ -146,9 +146,9 @@ if ($action == 'setenabledraftexport') { if ($action == 'setenablesubsidiarylist') { $setenablesubsidiarylist = GETPOST('value', 'int'); $res = dolibarr_set_const($db, "ACCOUNTANCY_COMBO_FOR_AUX", $setenablesubsidiarylist, 'yesno', 0, '', $conf->entity); - if (! $res > 0) - $error ++; - if (! $error) { + if (!$res > 0) + $error++; + if (!$error) { setEventMessages($langs->trans("SetupSaved"), null, 'mesgs'); } else { setEventMessages($langs->trans("Error"), null, 'mesgs'); @@ -159,20 +159,20 @@ if ($action == 'setenablesubsidiarylist') { * View */ -$title= $langs->trans('ConfigAccountingExpert'); +$title = $langs->trans('ConfigAccountingExpert'); llxHeader('', $title); -$linkback=''; +$linkback = ''; //$linkback = '' . $langs->trans("BackToModuleList") . ''; print load_fiche_titre($langs->trans('ConfigAccountingExpert'), $linkback, 'accountancy'); -print '
'; -print ''; +print ''; +print ''; print ''; // Default mode for calculating turnover (parameter ACCOUNTING_MODE) /* -print ''; +print '
'; print ''; print ''; @@ -202,87 +202,87 @@ print '
'; // Others params -print '
' . $langs->trans('OptionMode') . '' . $langs->trans('Description') . '
'; +print '
'; print ''; -print ''; +print ''; print "\n"; -if (! empty($user->admin)) +if (!empty($user->admin)) { // TO DO Mutualize code for yes/no constants print ''; - print ''; - if (! empty($conf->global->ACCOUNTING_LIST_SORT_VENTILATION_TODO)) { - print ''; + if (!empty($conf->global->ACCOUNTING_LIST_SORT_VENTILATION_TODO)) { + print ''; } else { - print ''; } print ''; print ''; - print ''; - if (! empty($conf->global->ACCOUNTING_LIST_SORT_VENTILATION_DONE)) { - print ''; + if (!empty($conf->global->ACCOUNTING_LIST_SORT_VENTILATION_DONE)) { + print ''; } else { - print ''; } print ''; print ''; - print ''; - if (! empty($conf->global->ACCOUNTING_ENABLE_EXPORT_DRAFT_JOURNAL)) { - print ''; + if (!empty($conf->global->ACCOUNTING_ENABLE_EXPORT_DRAFT_JOURNAL)) { + print ''; } else { - print ''; } print ''; print ''; - print ''; - if (! empty($conf->global->BANK_DISABLE_DIRECT_INPUT)) { - print ''; + if (!empty($conf->global->BANK_DISABLE_DIRECT_INPUT)) { + print ''; } else { - print ''; } print ''; print ''; - print ''; - if (! empty($conf->global->ACCOUNTANCY_COMBO_FOR_AUX)) { - print ''; + if (!empty($conf->global->ACCOUNTANCY_COMBO_FOR_AUX)) { + print ''; } else { - print ''; } print ''; print ''; - print ''; - if (! empty($conf->global->ACCOUNTING_MANAGE_ZERO)) { - print ''; + if (!empty($conf->global->ACCOUNTING_MANAGE_ZERO)) { + print ''; } else { - print ''; } @@ -295,14 +295,14 @@ foreach ($list as $key) { print ''; - if (! empty($conf->global->ACCOUNTING_MANAGE_ZERO) && ($key == 'ACCOUNTING_LENGTH_GACCOUNT' || $key == 'ACCOUNTING_LENGTH_AACCOUNT')) continue; + if (!empty($conf->global->ACCOUNTING_MANAGE_ZERO) && ($key == 'ACCOUNTING_LENGTH_GACCOUNT' || $key == 'ACCOUNTING_LENGTH_AACCOUNT')) continue; // Param $label = $langs->trans($key); print ''; // Value print ''; print ''; @@ -311,7 +311,7 @@ foreach ($list as $key) print '
' . $langs->trans('OtherOptions') . ''.$langs->trans('OtherOptions').'
' . $langs->trans("ACCOUNTING_LIST_SORT_VENTILATION_TODO") . ''; + print ''.$langs->trans("ACCOUNTING_LIST_SORT_VENTILATION_TODO").''; print img_picto($langs->trans("Activated"), 'switch_on'); print ''; + print ''; print img_picto($langs->trans("Disabled"), 'switch_off'); print '
' . $langs->trans("ACCOUNTING_LIST_SORT_VENTILATION_DONE") . ''; + print ''.$langs->trans("ACCOUNTING_LIST_SORT_VENTILATION_DONE").''; print img_picto($langs->trans("Activated"), 'switch_on'); print ''; + print ''; print img_picto($langs->trans("Disabled"), 'switch_off'); print '
' . $langs->trans("ACCOUNTING_ENABLE_EXPORT_DRAFT_JOURNAL") . ''; + print ''.$langs->trans("ACCOUNTING_ENABLE_EXPORT_DRAFT_JOURNAL").''; print img_picto($langs->trans("Activated"), 'switch_on'); print ''; + print ''; print img_picto($langs->trans("Disabled"), 'switch_off'); print '
' . $langs->trans("BANK_DISABLE_DIRECT_INPUT") . ''; + print ''.$langs->trans("BANK_DISABLE_DIRECT_INPUT").''; print img_picto($langs->trans("Activated"), 'switch_on'); print ''; + print ''; print img_picto($langs->trans("Disabled"), 'switch_off'); print '
' . $langs->trans("ACCOUNTANCY_COMBO_FOR_AUX") . ''; + print ''.$langs->trans("ACCOUNTANCY_COMBO_FOR_AUX").''; print img_picto($langs->trans("Activated"), 'switch_on'); print ''; + print ''; print img_picto($langs->trans("Disabled"), 'switch_off'); print '
' . $langs->trans("ACCOUNTING_MANAGE_ZERO") . ''; + print ''.$langs->trans("ACCOUNTING_MANAGE_ZERO").''; print img_picto($langs->trans("Activated"), 'switch_on'); print ''; + print ''; print img_picto($langs->trans("Disabled"), 'switch_off'); print '
'.$label.''; - print ''; + print ''; print '
'; -print '
'; +print '
'; print '
'; print '
'; diff --git a/htdocs/accountancy/admin/journals_list.php b/htdocs/accountancy/admin/journals_list.php index 44fe3e936cd..7c834c56ad2 100644 --- a/htdocs/accountancy/admin/journals_list.php +++ b/htdocs/accountancy/admin/journals_list.php @@ -32,13 +32,13 @@ require_once DOL_DOCUMENT_ROOT.'/core/lib/accounting.lib.php'; require_once DOL_DOCUMENT_ROOT.'/accountancy/class/accountingjournal.class.php'; // Load translation files required by the page -$langs->loadLangs(array("admin","compta","accountancy")); +$langs->loadLangs(array("admin", "compta", "accountancy")); -$action=GETPOST('action', 'aZ09')?GETPOST('action', 'aZ09'):'view'; -$confirm=GETPOST('confirm', 'alpha'); -$id=35; -$rowid=GETPOST('rowid', 'alpha'); -$code=GETPOST('code', 'alpha'); +$action = GETPOST('action', 'aZ09') ?GETPOST('action', 'aZ09') : 'view'; +$confirm = GETPOST('confirm', 'alpha'); +$id = 35; +$rowid = GETPOST('rowid', 'alpha'); +$code = GETPOST('code', 'alpha'); // Security access if (empty($user->rights->accounting->chartofaccount)) @@ -51,19 +51,19 @@ $acts[1] = "disable"; $actl[0] = img_picto($langs->trans("Disabled"), 'switch_off'); $actl[1] = img_picto($langs->trans("Activated"), 'switch_on'); -$listoffset=GETPOST('listoffset', 'alpha'); -$listlimit=GETPOST('listlimit', 'int')>0?GETPOST('listlimit', 'int'):1000; +$listoffset = GETPOST('listoffset', 'alpha'); +$listlimit = GETPOST('listlimit', 'int') > 0 ?GETPOST('listlimit', 'int') : 1000; $active = 1; $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 -$offset = $listlimit * $page ; +$offset = $listlimit * $page; $pageprev = $page - 1; $pagenext = $page + 1; -if (empty($sortfield)) $sortfield='code'; -if (empty($sortorder)) $sortorder='ASC'; +if (empty($sortfield)) $sortfield = 'code'; +if (empty($sortorder)) $sortorder = 'ASC'; $error = 0; @@ -74,52 +74,52 @@ $hookmanager->initHooks(array('admin')); // Put here declaration of dictionaries properties // Sort order to show dictionary (0 is space). All other dictionaries (added by modules) will be at end of this. -$taborder=array(35); +$taborder = array(35); // Name of SQL tables of dictionaries -$tabname=array(); -$tabname[35]= MAIN_DB_PREFIX."accounting_journal"; +$tabname = array(); +$tabname[35] = MAIN_DB_PREFIX."accounting_journal"; // Dictionary labels -$tablib=array(); -$tablib[35]= "DictionaryAccountancyJournal"; +$tablib = array(); +$tablib[35] = "DictionaryAccountancyJournal"; // Requests to extract data -$tabsql=array(); -$tabsql[35]= "SELECT a.rowid as rowid, a.code as code, a.label, a.nature, a.active FROM ".MAIN_DB_PREFIX."accounting_journal as a"; +$tabsql = array(); +$tabsql[35] = "SELECT a.rowid as rowid, a.code as code, a.label, a.nature, a.active FROM ".MAIN_DB_PREFIX."accounting_journal as a"; // Criteria to sort dictionaries -$tabsqlsort=array(); -$tabsqlsort[35]="code ASC"; +$tabsqlsort = array(); +$tabsqlsort[35] = "code ASC"; // Nom des champs en resultat de select pour affichage du dictionnaire -$tabfield=array(); -$tabfield[35]= "code,label,nature"; +$tabfield = array(); +$tabfield[35] = "code,label,nature"; // Nom des champs d'edition pour modification d'un enregistrement -$tabfieldvalue=array(); -$tabfieldvalue[35]= "code,label,nature"; +$tabfieldvalue = array(); +$tabfieldvalue[35] = "code,label,nature"; // Nom des champs dans la table pour insertion d'un enregistrement -$tabfieldinsert=array(); -$tabfieldinsert[35]= "code,label,nature"; +$tabfieldinsert = array(); +$tabfieldinsert[35] = "code,label,nature"; // Nom du rowid si le champ n'est pas de type autoincrement // Example: "" if id field is "rowid" and has autoincrement on // "nameoffield" if id field is not "rowid" or has not autoincrement on -$tabrowid=array(); -$tabrowid[35]= ""; +$tabrowid = array(); +$tabrowid[35] = ""; // Condition to show dictionary in setup page -$tabcond=array(); -$tabcond[35]= ! empty($conf->accounting->enabled); +$tabcond = array(); +$tabcond[35] = !empty($conf->accounting->enabled); // List of help for fields -$tabhelp=array(); +$tabhelp = array(); $tabhelp[35] = array('code'=>$langs->trans("EnterAnyCode")); // List of check for fields (NOT USED YET) -$tabfieldcheck=array(); +$tabfieldcheck = array(); $tabfieldcheck[35] = array(); // Complete all arrays with entries found into modules @@ -151,25 +151,25 @@ if (GETPOST('button_removefilter', 'alpha') || GETPOST('button_removefilter.x', // Actions add or modify an entry into a dictionary if (GETPOST('actionadd', 'alpha') || GETPOST('actionmodify', 'alpha')) { - $listfield=explode(',', str_replace(' ', '', $tabfield[$id])); - $listfieldinsert=explode(',', $tabfieldinsert[$id]); - $listfieldmodify=explode(',', $tabfieldinsert[$id]); - $listfieldvalue=explode(',', $tabfieldvalue[$id]); + $listfield = explode(',', str_replace(' ', '', $tabfield[$id])); + $listfieldinsert = explode(',', $tabfieldinsert[$id]); + $listfieldmodify = explode(',', $tabfieldinsert[$id]); + $listfieldvalue = explode(',', $tabfieldvalue[$id]); // Check that all fields are filled - $ok=1; + $ok = 1; foreach ($listfield as $f => $value) { - if ($fieldnamekey == 'libelle' || ($fieldnamekey == 'label')) $fieldnamekey='Label'; + if ($fieldnamekey == 'libelle' || ($fieldnamekey == 'label')) $fieldnamekey = 'Label'; if ($fieldnamekey == 'code') $fieldnamekey = 'Code'; if ($fieldnamekey == 'nature') $fieldnamekey = 'NatureOfJournal'; } // Other checks if (isset($_POST["code"])) { - if ($_POST["code"]=='0') + if ($_POST["code"] == '0') { - $ok=0; + $ok = 0; setEventMessages($langs->transnoentities('ErrorCodeCantContainZero'), null, 'errors'); } /*if (!is_numeric($_POST['code'])) // disabled, code may not be in numeric base @@ -178,16 +178,16 @@ if (GETPOST('actionadd', 'alpha') || GETPOST('actionmodify', 'alpha')) $msg .= $langs->transnoentities('ErrorFieldFormat', $langs->transnoentities('Code')).'
'; }*/ } - if (! GETPOST('label', 'alpha')) + if (!GETPOST('label', 'alpha')) { setEventMessages($langs->transnoentities("ErrorFieldRequired", $langs->transnoentitiesnoconv("Label")), null, 'errors'); - $ok=0; + $ok = 0; } // Clean some parameters - if ($_POST["accountancy_code"] <= 0) $_POST["accountancy_code"]=''; // If empty, we force to null - if ($_POST["accountancy_code_sell"] <= 0) $_POST["accountancy_code_sell"]=''; // If empty, we force to null - if ($_POST["accountancy_code_buy"] <= 0) $_POST["accountancy_code_buy"]=''; // If empty, we force to null + if ($_POST["accountancy_code"] <= 0) $_POST["accountancy_code"] = ''; // If empty, we force to null + if ($_POST["accountancy_code_sell"] <= 0) $_POST["accountancy_code_sell"] = ''; // If empty, we force to null + if ($_POST["accountancy_code_buy"] <= 0) $_POST["accountancy_code_buy"] = ''; // If empty, we force to null // Si verif ok et action add, on ajoute la ligne if ($ok && GETPOST('actionadd', 'alpha')) @@ -195,13 +195,13 @@ if (GETPOST('actionadd', 'alpha') || GETPOST('actionmodify', 'alpha')) if ($tabrowid[$id]) { // Recupere id libre pour insertion - $newid=0; + $newid = 0; $sql = "SELECT max(".$tabrowid[$id].") newid from ".$tabname[$id]; $result = $db->query($sql); if ($result) { $obj = $db->fetch_object($result); - $newid=($obj->newid + 1); + $newid = ($obj->newid + 1); } else { dol_print_error($db); } @@ -210,34 +210,34 @@ if (GETPOST('actionadd', 'alpha') || GETPOST('actionmodify', 'alpha')) // Add new entry $sql = "INSERT INTO ".$tabname[$id]." ("; // List of fields - if ($tabrowid[$id] && ! in_array($tabrowid[$id], $listfieldinsert)) - $sql.= $tabrowid[$id].","; - $sql.= $tabfieldinsert[$id]; - $sql.=",active,entity)"; - $sql.= " VALUES("; + if ($tabrowid[$id] && !in_array($tabrowid[$id], $listfieldinsert)) + $sql .= $tabrowid[$id].","; + $sql .= $tabfieldinsert[$id]; + $sql .= ",active,entity)"; + $sql .= " VALUES("; // List of values - if ($tabrowid[$id] && ! in_array($tabrowid[$id], $listfieldinsert)) - $sql.= $newid.","; - $i=0; + if ($tabrowid[$id] && !in_array($tabrowid[$id], $listfieldinsert)) + $sql .= $newid.","; + $i = 0; foreach ($listfieldinsert as $f => $value) { if ($value == 'entity') { $_POST[$listfieldvalue[$i]] = $conf->entity; } - if ($i) $sql.=","; - if ($_POST[$listfieldvalue[$i]] == '') $sql.="null"; // For vat, we want/accept code = '' - else $sql.="'".$db->escape($_POST[$listfieldvalue[$i]])."'"; + if ($i) $sql .= ","; + if ($_POST[$listfieldvalue[$i]] == '') $sql .= "null"; // For vat, we want/accept code = '' + else $sql .= "'".$db->escape($_POST[$listfieldvalue[$i]])."'"; $i++; } - $sql.=",1,".$conf->entity.")"; + $sql .= ",1,".$conf->entity.")"; dol_syslog("actionadd", LOG_DEBUG); $result = $db->query($sql); if ($result) // Add is ok { setEventMessages($langs->transnoentities("RecordSaved"), null, 'mesgs'); - $_POST=array('id'=>$id); // Clean $_POST array, we keep only + $_POST = array('id'=>$id); // Clean $_POST array, we keep only } else { @@ -253,16 +253,16 @@ if (GETPOST('actionadd', 'alpha') || GETPOST('actionmodify', 'alpha')) // Si verif ok et action modify, on modifie la ligne if ($ok && GETPOST('actionmodify', 'alpha')) { - if ($tabrowid[$id]) { $rowidcol=$tabrowid[$id]; } - else { $rowidcol="rowid"; } + if ($tabrowid[$id]) { $rowidcol = $tabrowid[$id]; } + else { $rowidcol = "rowid"; } // Modify entry $sql = "UPDATE ".$tabname[$id]." SET "; // Modifie valeur des champs - if ($tabrowid[$id] && ! in_array($tabrowid[$id], $listfieldmodify)) + if ($tabrowid[$id] && !in_array($tabrowid[$id], $listfieldmodify)) { - $sql.= $tabrowid[$id]."="; - $sql.= "'".$db->escape($rowid)."', "; + $sql .= $tabrowid[$id]."="; + $sql .= "'".$db->escape($rowid)."', "; } $i = 0; foreach ($listfieldmodify as $field) @@ -273,19 +273,19 @@ if (GETPOST('actionadd', 'alpha') || GETPOST('actionmodify', 'alpha')) elseif ($field == 'entity') { $_POST[$listfieldvalue[$i]] = $conf->entity; } - if ($i) $sql.=","; - $sql.= $field."="; - if ($_POST[$listfieldvalue[$i]] == '' && ! ($listfieldvalue[$i] == 'code' && $id == 10)) $sql.="null"; // For vat, we want/accept code = '' - else $sql.="'".$db->escape($_POST[$listfieldvalue[$i]])."'"; + if ($i) $sql .= ","; + $sql .= $field."="; + if ($_POST[$listfieldvalue[$i]] == '' && !($listfieldvalue[$i] == 'code' && $id == 10)) $sql .= "null"; // For vat, we want/accept code = '' + else $sql .= "'".$db->escape($_POST[$listfieldvalue[$i]])."'"; $i++; } - $sql.= " WHERE ".$rowidcol." = '".$rowid."'"; - $sql.=" AND entity = ".$conf->entity; + $sql .= " WHERE ".$rowidcol." = '".$rowid."'"; + $sql .= " AND entity = ".$conf->entity; dol_syslog("actionmodify", LOG_DEBUG); //print $sql; $resql = $db->query($sql); - if (! $resql) + if (!$resql) { setEventMessages($db->error(), null, 'errors'); } @@ -300,15 +300,15 @@ if (GETPOST('actionadd', 'alpha') || GETPOST('actionmodify', 'alpha')) if ($action == 'confirm_delete' && $confirm == 'yes') // delete { - if ($tabrowid[$id]) { $rowidcol=$tabrowid[$id]; } - else { $rowidcol="rowid"; } + if ($tabrowid[$id]) { $rowidcol = $tabrowid[$id]; } + else { $rowidcol = "rowid"; } $sql = "DELETE from ".$tabname[$id]." WHERE ".$rowidcol."='".$rowid."'"; - $sql.=" AND entity = ".$conf->entity; + $sql .= " AND entity = ".$conf->entity; dol_syslog("delete", LOG_DEBUG); $result = $db->query($sql); - if (! $result) + if (!$result) { if ($db->errno() == 'DB_ERROR_CHILD_EXISTS') { @@ -324,8 +324,8 @@ if ($action == 'confirm_delete' && $confirm == 'yes') // delete // activate if ($action == $acts[0]) { - if ($tabrowid[$id]) { $rowidcol=$tabrowid[$id]; } - else { $rowidcol="rowid"; } + if ($tabrowid[$id]) { $rowidcol = $tabrowid[$id]; } + else { $rowidcol = "rowid"; } if ($rowid) { $sql = "UPDATE ".$tabname[$id]." SET active = 1 WHERE ".$rowidcol."='".$rowid."'"; @@ -333,7 +333,7 @@ if ($action == $acts[0]) elseif ($code) { $sql = "UPDATE ".$tabname[$id]." SET active = 1 WHERE code='".$code."'"; } - $sql.=" AND entity = ".$conf->entity; + $sql .= " AND entity = ".$conf->entity; $result = $db->query($sql); if (!$result) @@ -345,8 +345,8 @@ if ($action == $acts[0]) // disable if ($action == $acts[1]) { - if ($tabrowid[$id]) { $rowidcol=$tabrowid[$id]; } - else { $rowidcol="rowid"; } + if ($tabrowid[$id]) { $rowidcol = $tabrowid[$id]; } + else { $rowidcol = "rowid"; } if ($rowid) { $sql = "UPDATE ".$tabname[$id]." SET active = 0 WHERE ".$rowidcol."='".$rowid."'"; @@ -354,7 +354,7 @@ if ($action == $acts[1]) elseif ($code) { $sql = "UPDATE ".$tabname[$id]." SET active = 0 WHERE code='".$code."'"; } - $sql.=" AND entity = ".$conf->entity; + $sql .= " AND entity = ".$conf->entity; $result = $db->query($sql); if (!$result) @@ -369,16 +369,16 @@ if ($action == $acts[1]) */ $form = new Form($db); -$formadmin=new FormAdmin($db); +$formadmin = new FormAdmin($db); llxHeader(); -$titre=$langs->trans("DictionarySetup"); -$linkback=''; +$titre = $langs->trans("DictionarySetup"); +$linkback = ''; if ($id) { - $titre.=' - '.$langs->trans($tablib[$id]); - $titlepicto='title_accountancy'; + $titre .= ' - '.$langs->trans($tablib[$id]); + $titlepicto = 'title_accountancy'; } print load_fiche_titre($titre, $linkback, $titlepicto); @@ -387,7 +387,7 @@ print load_fiche_titre($titre, $linkback, $titlepicto); // Confirmation de la suppression de la ligne if ($action == 'delete') { - print $form->formconfirm($_SERVER["PHP_SELF"].'?'.($page?'page='.$page.'&':'').'sortfield='.$sortfield.'&sortorder='.$sortorder.'&rowid='.$rowid.'&code='.$code.'&id='.$id, $langs->trans('DeleteLine'), $langs->trans('ConfirmDeleteLine'), 'confirm_delete', '', 0, 1); + print $form->formconfirm($_SERVER["PHP_SELF"].'?'.($page ? 'page='.$page.'&' : '').'sortfield='.$sortfield.'&sortorder='.$sortorder.'&rowid='.$rowid.'&code='.$code.'&id='.$id, $langs->trans('DeleteLine'), $langs->trans('ConfirmDeleteLine'), 'confirm_delete', '', 0, 1); } //var_dump($elementList); @@ -397,29 +397,29 @@ if ($action == 'delete') if ($id) { // Complete requete recherche valeurs avec critere de tri - $sql=$tabsql[$id]; - $sql.= " WHERE a.entity = ".$conf->entity; + $sql = $tabsql[$id]; + $sql .= " WHERE a.entity = ".$conf->entity; // If sort order is "country", we use country_code instead - if ($sortfield == 'country') $sortfield='country_code'; - $sql.=$db->order($sortfield, $sortorder); - $sql.=$db->plimit($listlimit+1, $offset); + if ($sortfield == 'country') $sortfield = 'country_code'; + $sql .= $db->order($sortfield, $sortorder); + $sql .= $db->plimit($listlimit + 1, $offset); - $fieldlist=explode(',', $tabfield[$id]); + $fieldlist = explode(',', $tabfield[$id]); print ''; print ''; print ''; print '
'; - print ''; + print '
'; // Form to add a new line if ($tabname[$id]) { - $alabelisused=0; + $alabelisused = 0; - $fieldlist=explode(',', $tabfield[$id]); + $fieldlist = explode(',', $tabfield[$id]); // Line for title print ''; @@ -427,27 +427,27 @@ if ($id) { // Determine le nom du champ par rapport aux noms possibles // dans les dictionnaires de donnees - $valuetoshow=ucfirst($fieldlist[$field]); // Par defaut - $valuetoshow=$langs->trans($valuetoshow); // try to translate - $class="left"; - if ($fieldlist[$field]=='code') { - $valuetoshow=$langs->trans("Code"); + $valuetoshow = ucfirst($fieldlist[$field]); // Par defaut + $valuetoshow = $langs->trans($valuetoshow); // try to translate + $class = "left"; + if ($fieldlist[$field] == 'code') { + $valuetoshow = $langs->trans("Code"); } - if ($fieldlist[$field]=='libelle' || $fieldlist[$field]=='label') { - $valuetoshow=$langs->trans("Label"); + if ($fieldlist[$field] == 'libelle' || $fieldlist[$field] == 'label') { + $valuetoshow = $langs->trans("Label"); } - if ($fieldlist[$field]=='nature') { - $valuetoshow=$langs->trans("NatureOfJournal"); + if ($fieldlist[$field] == 'nature') { + $valuetoshow = $langs->trans("NatureOfJournal"); } if ($valuetoshow != '') { print ''; } - if ($fieldlist[$field]=='libelle' || $fieldlist[$field]=='label') $alabelisused=1; + if ($fieldlist[$field] == 'libelle' || $fieldlist[$field] == 'label') $alabelisused = 1; } print ''; print ""; - print ''; // Keep   to have a line with enough height + print ''; // Keep   to have a line with enough height } // List of available record in database dol_syslog("htdocs/admin/dict", LOG_DEBUG); - $resql=$db->query($sql); + $resql = $db->query($sql); if ($resql) { $num = $db->num_rows($resql); $i = 0; $param = '&id='.$id; - if ($search_country_id > 0) $param.= '&search_country_id='.$search_country_id; + if ($search_country_id > 0) $param .= '&search_country_id='.$search_country_id; $paramwithsearch = $param; - if ($sortorder) $paramwithsearch.= '&sortorder='.$sortorder; - if ($sortfield) $paramwithsearch.= '&sortfield='.$sortfield; - if (GETPOST('from', 'alpha')) $paramwithsearch.= '&from='.GETPOST('from', 'alpha'); + if ($sortorder) $paramwithsearch .= '&sortorder='.$sortorder; + if ($sortfield) $paramwithsearch .= '&sortfield='.$sortfield; + if (GETPOST('from', 'alpha')) $paramwithsearch .= '&from='.GETPOST('from', 'alpha'); // There is several pages if ($num > $listlimit) { - print ''; } @@ -536,10 +536,10 @@ if ($id) { // Determine le nom du champ par rapport aux noms possibles // dans les dictionnaires de donnees - $showfield=1; // By defaut - $class="left"; - $sortable=1; - $valuetoshow=''; + $showfield = 1; // By defaut + $class = "left"; + $sortable = 1; + $valuetoshow = ''; /* $tmparray=getLabelOfField($fieldlist[$field]); $showfield=$tmp['showfield']; @@ -547,24 +547,24 @@ if ($id) $align=$tmp['align']; $sortable=$tmp['sortable']; */ - $valuetoshow=ucfirst($fieldlist[$field]); // By defaut - $valuetoshow=$langs->trans($valuetoshow); // try to translate - if ($fieldlist[$field]=='code') { - $valuetoshow=$langs->trans("Code"); + $valuetoshow = ucfirst($fieldlist[$field]); // By defaut + $valuetoshow = $langs->trans($valuetoshow); // try to translate + if ($fieldlist[$field] == 'code') { + $valuetoshow = $langs->trans("Code"); } - if ($fieldlist[$field]=='libelle' || $fieldlist[$field]=='label') { - $valuetoshow=$langs->trans("Label"); + if ($fieldlist[$field] == 'libelle' || $fieldlist[$field] == 'label') { + $valuetoshow = $langs->trans("Label"); } - if ($fieldlist[$field]=='nature') { - $valuetoshow=$langs->trans("NatureOfJournal"); + if ($fieldlist[$field] == 'nature') { + $valuetoshow = $langs->trans("NatureOfJournal"); } // Affiche nom du champ if ($showfield) { - print getTitleFieldOfList($valuetoshow, 0, $_SERVER["PHP_SELF"], ($sortable?$fieldlist[$field]:''), ($page?'page='.$page.'&':''), $param, "", $sortfield, $sortorder, $class.' '); + print getTitleFieldOfList($valuetoshow, 0, $_SERVER["PHP_SELF"], ($sortable ? $fieldlist[$field] : ''), ($page ? 'page='.$page.'&' : ''), $param, "", $sortfield, $sortorder, $class.' '); } } - print getTitleFieldOfList($langs->trans("Status"), 0, $_SERVER["PHP_SELF"], "active", ($page?'page='.$page.'&':''), $param, '', $sortfield, $sortorder, 'center '); + print getTitleFieldOfList($langs->trans("Status"), 0, $_SERVER["PHP_SELF"], "active", ($page ? 'page='.$page.'&' : ''), $param, '', $sortfield, $sortorder, 'center '); print getTitleFieldOfList(''); print getTitleFieldOfList(''); print getTitleFieldOfList(''); @@ -578,12 +578,12 @@ if ($id) $obj = $db->fetch_object($resql); //print_r($obj); print ''; - if ($action == 'edit' && ($rowid == (! empty($obj->rowid)?$obj->rowid:$obj->code))) + if ($action == 'edit' && ($rowid == (!empty($obj->rowid) ? $obj->rowid : $obj->code))) { - $tmpaction='edit'; - $parameters=array('fieldlist'=>$fieldlist, 'tabname'=>$tabname[$id]); - $reshook=$hookmanager->executeHooks('editDictionaryFieldlist', $parameters, $obj, $tmpaction); // Note that $action and $object may have been modified by some hooks - $error=$hookmanager->error; $errors=$hookmanager->errors; + $tmpaction = 'edit'; + $parameters = array('fieldlist'=>$fieldlist, 'tabname'=>$tabname[$id]); + $reshook = $hookmanager->executeHooks('editDictionaryFieldlist', $parameters, $obj, $tmpaction); // Note that $action and $object may have been modified by some hooks + $error = $hookmanager->error; $errors = $hookmanager->errors; // Show fields if (empty($reshook)) fieldListJournal($fieldlist, $obj, $tabname[$id], 'edit'); @@ -593,44 +593,44 @@ if ($id) print ''; print ''; print ''; - print '
'; + print '
'; print ''; } else { $tmpaction = 'view'; - $parameters=array('var'=>$var, 'fieldlist'=>$fieldlist, 'tabname'=>$tabname[$id]); - $reshook=$hookmanager->executeHooks('viewDictionaryFieldlist', $parameters, $obj, $tmpaction); // Note that $action and $object may have been modified by some hooks + $parameters = array('var'=>$var, 'fieldlist'=>$fieldlist, 'tabname'=>$tabname[$id]); + $reshook = $hookmanager->executeHooks('viewDictionaryFieldlist', $parameters, $obj, $tmpaction); // Note that $action and $object may have been modified by some hooks - $error=$hookmanager->error; $errors=$hookmanager->errors; + $error = $hookmanager->error; $errors = $hookmanager->errors; if (empty($reshook)) { $langs->load("accountancy"); foreach ($fieldlist as $field => $value) { - $showfield=1; - $class="left"; - $valuetoshow=$obj->{$fieldlist[$field]}; - if ($valuetoshow=='all') { - $valuetoshow=$langs->trans('All'); + $showfield = 1; + $class = "left"; + $valuetoshow = $obj->{$fieldlist[$field]}; + if ($valuetoshow == 'all') { + $valuetoshow = $langs->trans('All'); } - elseif ($fieldlist[$field]=='nature' && $tabname[$id]==MAIN_DB_PREFIX.'accounting_journal') { - $key=$langs->trans("AccountingJournalType".strtoupper($obj->nature)); - $valuetoshow=($obj->nature && $key != "AccountingJournalType".strtoupper($langs->trans($obj->nature))?$key:$obj->{$fieldlist[$field]}); + elseif ($fieldlist[$field] == 'nature' && $tabname[$id] == MAIN_DB_PREFIX.'accounting_journal') { + $key = $langs->trans("AccountingJournalType".strtoupper($obj->nature)); + $valuetoshow = ($obj->nature && $key != "AccountingJournalType".strtoupper($langs->trans($obj->nature)) ? $key : $obj->{$fieldlist[$field]}); } - elseif ($fieldlist[$field]=='label' && $tabname[$id]==MAIN_DB_PREFIX.'accounting_journal') { - $valuetoshow=$langs->trans($obj->label); + elseif ($fieldlist[$field] == 'label' && $tabname[$id] == MAIN_DB_PREFIX.'accounting_journal') { + $valuetoshow = $langs->trans($obj->label); } - $class='tddict'; + $class = 'tddict'; // Show value for field if ($showfield) print ''; } } // Can an entry be erased or disabled ? - $iserasable=1;$canbedisabled=1;$canbemodified=1; // true by default + $iserasable = 1; $canbedisabled = 1; $canbemodified = 1; // true by default if (isset($obj->code) && $id != 10) { if (($obj->code == '0' || $obj->code == '' || preg_match('/unknown/i', $obj->code))) { $iserasable = 0; @@ -644,11 +644,11 @@ if ($id) } } - $canbemodified=$iserasable; + $canbemodified = $iserasable; - $url = $_SERVER["PHP_SELF"].'?'.($page?'page='.$page.'&':'').'sortfield='.$sortfield.'&sortorder='.$sortorder.'&rowid='.(! empty($obj->rowid)?$obj->rowid:(! empty($obj->code)?$obj->code:'')).'&code='.(! empty($obj->code)?urlencode($obj->code):''); + $url = $_SERVER["PHP_SELF"].'?'.($page ? 'page='.$page.'&' : '').'sortfield='.$sortfield.'&sortorder='.$sortorder.'&rowid='.(!empty($obj->rowid) ? $obj->rowid : (!empty($obj->code) ? $obj->code : '')).'&code='.(!empty($obj->code) ?urlencode($obj->code) : ''); if ($param) $url .= '&'.$param; - $url.='&'; + $url .= '&'; // Active print ''; } elseif ($fieldlist[$field] == 'code' && isset($obj->{$fieldlist[$field]})) { - print ''; + print ''; } else { print ''; } } diff --git a/htdocs/accountancy/admin/productaccount.php b/htdocs/accountancy/admin/productaccount.php index 091018dc909..13abe51ccaf 100644 --- a/htdocs/accountancy/admin/productaccount.php +++ b/htdocs/accountancy/admin/productaccount.php @@ -26,22 +26,22 @@ */ require '../../main.inc.php'; -require_once DOL_DOCUMENT_ROOT . '/core/lib/accounting.lib.php'; -require_once DOL_DOCUMENT_ROOT . '/core/lib/report.lib.php'; -require_once DOL_DOCUMENT_ROOT . '/core/lib/admin.lib.php'; -require_once DOL_DOCUMENT_ROOT . '/core/lib/date.lib.php'; -require_once DOL_DOCUMENT_ROOT . '/core/class/html.formaccounting.class.php'; -require_once DOL_DOCUMENT_ROOT . '/accountancy/class/accountingaccount.class.php'; -require_once DOL_DOCUMENT_ROOT . '/product/class/product.class.php'; +require_once DOL_DOCUMENT_ROOT.'/core/lib/accounting.lib.php'; +require_once DOL_DOCUMENT_ROOT.'/core/lib/report.lib.php'; +require_once DOL_DOCUMENT_ROOT.'/core/lib/admin.lib.php'; +require_once DOL_DOCUMENT_ROOT.'/core/lib/date.lib.php'; +require_once DOL_DOCUMENT_ROOT.'/core/class/html.formaccounting.class.php'; +require_once DOL_DOCUMENT_ROOT.'/accountancy/class/accountingaccount.class.php'; +require_once DOL_DOCUMENT_ROOT.'/product/class/product.class.php'; // Load translation files required by the page -$langs->loadLangs(array("companies","compta","accountancy","products")); +$langs->loadLangs(array("companies", "compta", "accountancy", "products")); // Security check if (empty($conf->accounting->enabled)) { accessforbidden(); } -if (! $user->rights->accounting->bind->write) +if (!$user->rights->accounting->bind->write) accessforbidden(); // search & action GETPOST @@ -60,6 +60,8 @@ $search_desc = GETPOST('search_desc', 'alpha'); $search_current_account = GETPOST('search_current_account', 'alpha'); $search_current_account_valid = GETPOST('search_current_account_valid', 'alpha'); if ($search_current_account_valid == '') $search_current_account_valid='withoutvalidaccount'; +$search_onsell = GETPOST('search_onsell', 'alpha'); +$search_onpurchase = GETPOST('search_onpurchase', 'alpha'); $accounting_product_mode = GETPOST('accounting_product_mode', 'alpha'); $btn_changeaccount = GETPOST('changeaccount', 'alpha'); @@ -75,23 +77,23 @@ if (empty($page) || $page == -1) { $page = 0; } // If $page is not defined, $offset = $limit * $page; $pageprev = $page - 1; $pagenext = $page + 1; -if (! $sortfield) $sortfield="p.ref"; -if (! $sortorder) $sortorder="ASC"; +if (!$sortfield) $sortfield = "p.ref"; +if (!$sortorder) $sortorder = "ASC"; -if (empty($action)) $action='list'; +if (empty($action)) $action = 'list'; -$arrayfields=array(); +$arrayfields = array(); /* * 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 +$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'); // Purge search criteria @@ -100,16 +102,18 @@ if (GETPOST('button_removefilter_x', 'alpha') || GETPOST('button_removefilter.x' $search_ref = ''; $search_label = ''; $search_desc = ''; + $search_onsell = ''; + $search_onpurchase = ''; $search_current_account = ''; $search_current_account_valid = '-1'; } // Sales or Purchase mode ? if ($action == 'update') { - if (! empty($btn_changetype)) { + if (!empty($btn_changetype)) { $error = 0; - $accounting_product_modes = array ( + $accounting_product_modes = array( 'ACCOUNTANCY_SELL', 'ACCOUNTANCY_SELL_INTRA', 'ACCOUNTANCY_SELL_EXPORT', @@ -117,17 +121,17 @@ if ($action == 'update') { ); if (in_array($accounting_product_mode, $accounting_product_modes)) { - if (! dolibarr_set_const($db, 'ACCOUNTING_PRODUCT_MODE', $accounting_product_mode, 'chaine', 0, '', $conf->entity)) { - $error ++; + if (!dolibarr_set_const($db, 'ACCOUNTING_PRODUCT_MODE', $accounting_product_mode, 'chaine', 0, '', $conf->entity)) { + $error++; } } else { - $error ++; + $error++; } } - if (! empty($btn_changeaccount)) { + if (!empty($btn_changeaccount)) { //$msg = '
' . $langs->trans("Processing") . '...
'; - if (! empty($chk_prod)) { + if (!empty($chk_prod)) { $accounting = new AccountingAccount($db); //$msg .= '
' . count($chk_prod) . ' ' . $langs->trans("SelectedLines") . '
'; @@ -136,37 +140,37 @@ if ($action == 'update') { $cpt = 0; $ok = 0; $ko = 0; foreach ($chk_prod as $productid) { - $accounting_account_id = GETPOST('codeventil_' . $productid); + $accounting_account_id = GETPOST('codeventil_'.$productid); $result = 0; if ($accounting_account_id > 0) { - $arrayofdifferentselectedvalues[$accounting_account_id]=$accounting_account_id; + $arrayofdifferentselectedvalues[$accounting_account_id] = $accounting_account_id; $result = $accounting->fetch($accounting_account_id, null, 1); } if ($result <= 0) { // setEventMessages(null, $accounting->errors, 'errors'); - $msg .= '
' . $langs->trans("ErrorDB") . ' : ' . $langs->trans("Product") . ' ' . $productid . ' ' . $langs->trans("NotVentilatedinAccount") . ' : id=' . $accounting_account_id . '
' . $sql . '
'; + $msg .= '
'.$langs->trans("ErrorDB").' : '.$langs->trans("Product").' '.$productid.' '.$langs->trans("NotVentilatedinAccount").' : id='.$accounting_account_id.'
'.$sql.'
'; $ko++; } else { $db->begin(); - $sql = " UPDATE " . MAIN_DB_PREFIX . "product"; + $sql = " UPDATE ".MAIN_DB_PREFIX."product"; if ($accounting_product_mode == 'ACCOUNTANCY_BUY') { - $sql .= " SET accountancy_code_buy = " . $accounting->account_number; + $sql .= " SET accountancy_code_buy = ".$accounting->account_number; } if ($accounting_product_mode == 'ACCOUNTANCY_SELL') { - $sql .= " SET accountancy_code_sell = " . $accounting->account_number; + $sql .= " SET accountancy_code_sell = ".$accounting->account_number; } if ($accounting_product_mode == 'ACCOUNTANCY_SELL_INTRA') { - $sql .= " SET accountancy_code_sell_intra = " . $accounting->account_number; + $sql .= " SET accountancy_code_sell_intra = ".$accounting->account_number; } if ($accounting_product_mode == 'ACCOUNTANCY_SELL_EXPORT') { - $sql .= " SET accountancy_code_sell_export = " . $accounting->account_number; + $sql .= " SET accountancy_code_sell_export = ".$accounting->account_number; } - $sql .= " WHERE rowid = " . $productid; + $sql .= " WHERE rowid = ".$productid; - dol_syslog("/accountancy/admin/productaccount.php sql=" . $sql, LOG_DEBUG); + dol_syslog("/accountancy/admin/productaccount.php sql=".$sql, LOG_DEBUG); if ($db->query($sql)) { $ok++; @@ -196,12 +200,14 @@ $form = new FormAccounting($db); // Default AccountingAccount RowId Product / Service // at this time ACCOUNTING_SERVICE_SOLD_ACCOUNT & ACCOUNTING_PRODUCT_SOLD_ACCOUNT are account number not accountingacount rowid -// so we need to get those default value rowid first +// so we need to get those the rowid of those default value first $accounting = new AccountingAccount($db); // TODO: we should need to check if result is already exists accountaccount rowid..... $aarowid_servbuy = $accounting->fetch('', $conf->global->ACCOUNTING_SERVICE_BUY_ACCOUNT, 1); $aarowid_prodbuy = $accounting->fetch('', $conf->global->ACCOUNTING_PRODUCT_BUY_ACCOUNT, 1); $aarowid_servsell = $accounting->fetch('', $conf->global->ACCOUNTING_SERVICE_SOLD_ACCOUNT, 1); +$aarowid_servsell_intra = $accounting->fetch('', $conf->global->ACCOUNTING_SERVICE_SOLD_INTRA_ACCOUNT, 1); +$aarowid_servsell_export = $accounting->fetch('', $conf->global->ACCOUNTING_SERVICE_SOLD_EXPORT_ACCOUNT, 1); $aarowid_prodsell = $accounting->fetch('', $conf->global->ACCOUNTING_PRODUCT_SOLD_ACCOUNT, 1); $aarowid_prodsell_intra = $accounting->fetch('', $conf->global->ACCOUNTING_PRODUCT_SOLD_INTRA_ACCOUNT, 1); $aarowid_prodsell_export = $accounting->fetch('', $conf->global->ACCOUNTING_PRODUCT_SOLD_EXPORT_ACCOUNT, 1); @@ -209,6 +215,8 @@ $aarowid_prodsell_export = $accounting->fetch('', $conf->global->ACCOUNTING_P $aacompta_servbuy = (! empty($conf->global->ACCOUNTING_SERVICE_BUY_ACCOUNT) ? $conf->global->ACCOUNTING_SERVICE_BUY_ACCOUNT : $langs->trans("CodeNotDef")); $aacompta_prodbuy = (! empty($conf->global->ACCOUNTING_PRODUCT_BUY_ACCOUNT) ? $conf->global->ACCOUNTING_PRODUCT_BUY_ACCOUNT : $langs->trans("CodeNotDef")); $aacompta_servsell = (! empty($conf->global->ACCOUNTING_SERVICE_SOLD_ACCOUNT) ? $conf->global->ACCOUNTING_SERVICE_SOLD_ACCOUNT : $langs->trans("CodeNotDef")); +$aacompta_servsell_intra = (! empty($conf->global->ACCOUNTING_SERVICE_SOLD_INTRA_ACCOUNT) ? $conf->global->ACCOUNTING_SERVICE_SOLD_INTRA_ACCOUNT : $langs->trans("CodeNotDef")); +$aacompta_servsell_export = (! empty($conf->global->ACCOUNTING_SERVICE_SOLD_EXPORT_ACCOUNT) ? $conf->global->ACCOUNTING_SERVICE_SOLD_EXPORT_ACCOUNT : $langs->trans("CodeNotDef")); $aacompta_prodsell = (! empty($conf->global->ACCOUNTING_PRODUCT_SOLD_ACCOUNT) ? $conf->global->ACCOUNTING_PRODUCT_SOLD_ACCOUNT : $langs->trans("CodeNotDef")); $aacompta_prodsell_intra = (! empty($conf->global->ACCOUNTING_PRODUCT_SOLD_INTRA_ACCOUNT) ? $conf->global->ACCOUNTING_PRODUCT_SOLD_INTRA_ACCOUNT : $langs->trans("CodeNotDef")); $aacompta_prodsell_export = (! empty($conf->global->ACCOUNTING_PRODUCT_SOLD_EXPORT_ACCOUNT) ? $conf->global->ACCOUNTING_PRODUCT_SOLD_EXPORT_ACCOUNT : $langs->trans("CodeNotDef")); @@ -219,7 +227,9 @@ $pcgverid = $conf->global->CHARTOFACCOUNTS; $pcgvercode = dol_getIdFromCode($db, $pcgverid, 'accounting_system', 'rowid', 'pcg_version'); if (empty($pcgvercode)) $pcgvercode=$pcgverid; -$sql = "SELECT p.rowid, p.ref, p.label, p.description, p.tosell, p.tobuy, p.accountancy_code_sell, p.accountancy_code_sell_intra, p.accountancy_code_sell_export, p.accountancy_code_buy, p.tms, p.fk_product_type as product_type,"; +$sql = "SELECT p.rowid, p.ref, p.label, p.description, p.tosell, p.tobuy,"; +$sql.= " p.accountancy_code_sell, p.accountancy_code_sell_intra, p.accountancy_code_sell_export, p.accountancy_code_buy,"; +$sql.= " p.tms, p.fk_product_type as product_type,"; $sql.= " aa.rowid as aaid"; $sql.= " FROM " . MAIN_DB_PREFIX . "product as p"; $sql.= " LEFT JOIN ".MAIN_DB_PREFIX."accounting_account as aa ON"; @@ -236,7 +246,7 @@ elseif ($accounting_product_mode == 'ACCOUNTANCY_SELL_INTRA') } else { - $sql.=" p.accountancy_code_sell_intra = aa.account_number AND aa.fk_pcg_version = '" . $pcgvercode . "'"; + $sql.=" p.accountancy_code_sell_export = aa.account_number AND aa.fk_pcg_version = '" . $pcgvercode . "'"; } $sql.= ' WHERE p.entity IN ('.getEntity('product').')'; if ($accounting_product_mode == 'ACCOUNTANCY_BUY') { @@ -276,6 +286,9 @@ if (strlen(trim($search_label))) { if (strlen(trim($search_desc))) { $sql .= natural_search("p.description", $search_desc); } +if ($search_onsell != '' && $search_onsell != '-1') $sql.= natural_search('p.tosell', $search_onsell, 1); +if ($search_onpurchase != '' && $search_onpurchase != '-1') $sql.= natural_search('p.tobuy', $search_onpurchase, 1); + $sql .= $db->order($sortfield, $sortorder); $nbtotalofrecords = ''; @@ -292,24 +305,24 @@ if (empty($conf->global->MAIN_DISABLE_FULL_SCANLIST)) $sql .= $db->plimit($limit + 1, $offset); -dol_syslog("/accountancy/admin/productaccount.php:: sql=" . $sql, LOG_DEBUG); +dol_syslog("/accountancy/admin/productaccount.php:: sql=".$sql, LOG_DEBUG); $result = $db->query($sql); if ($result) { $num = $db->num_rows($result); $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 ($search_ref > 0) $param.="&search_desc=".urlencode($search_ref); - if ($search_label > 0) $param.="&search_desc=".urlencode($search_label); - if ($search_desc > 0) $param.="&search_desc=".urlencode($search_desc); - if ($search_current_account > 0) $param.="&search_current_account=".urlencode($search_current_account); - if ($search_current_account_valid && $search_current_account_valid != '-1') $param.="&search_current_account_valid=".urlencode($search_current_account_valid); - if ($accounting_product_mode) $param.='&accounting_product_mode='.urlencode($accounting_product_mode); + $param = ''; + if (!empty($contextpage) && $contextpage != $_SERVER["PHP_SELF"]) $param .= '&contextpage='.urlencode($contextpage); + if ($limit > 0 && $limit != $conf->liste_limit) $param .= '&limit='.urlencode($limit); + if ($search_ref > 0) $param .= "&search_desc=".urlencode($search_ref); + if ($search_label > 0) $param .= "&search_desc=".urlencode($search_label); + if ($search_desc > 0) $param .= "&search_desc=".urlencode($search_desc); + if ($search_current_account > 0) $param .= "&search_current_account=".urlencode($search_current_account); + if ($search_current_account_valid && $search_current_account_valid != '-1') $param .= "&search_current_account_valid=".urlencode($search_current_account_valid); + if ($accounting_product_mode) $param .= '&accounting_product_mode='.urlencode($accounting_product_mode); - print ''; + print ''; if ($optioncss != '') print ''; print ''; print ''; @@ -325,7 +338,7 @@ if ($result) print '
'; // Select mode - print '
'; - if (! empty($tabhelp[$id][$value]) && preg_match('/^http(s*):/i', $tabhelp[$id][$value])) print ''.$valuetoshow.' '.img_help(1, $valuetoshow).''; - elseif (! empty($tabhelp[$id][$value])) print $form->textwithpicto($valuetoshow, $tabhelp[$id][$value]); + if (!empty($tabhelp[$id][$value]) && preg_match('/^http(s*):/i', $tabhelp[$id][$value])) print ''.$valuetoshow.' '.img_help(1, $valuetoshow).''; + elseif (!empty($tabhelp[$id][$value])) print $form->textwithpicto($valuetoshow, $tabhelp[$id][$value]); else print $valuetoshow; print ''; @@ -468,14 +468,14 @@ if ($id) foreach ($fieldlist as $key=>$val) { if (GETPOST($val) != '') - $obj->$val=GETPOST($val); + $obj->$val = GETPOST($val); } } $tmpaction = 'create'; - $parameters=array('fieldlist'=>$fieldlist, 'tabname'=>$tabname[$id]); - $reshook=$hookmanager->executeHooks('createDictionaryFieldlist', $parameters, $obj, $tmpaction); // Note that $action and $object may have been modified by some hooks - $error=$hookmanager->error; $errors=$hookmanager->errors; + $parameters = array('fieldlist'=>$fieldlist, 'tabname'=>$tabname[$id]); + $reshook = $hookmanager->executeHooks('createDictionaryFieldlist', $parameters, $obj, $tmpaction); // Note that $action and $object may have been modified by some hooks + $error = $hookmanager->error; $errors = $hookmanager->errors; if (empty($reshook)) { @@ -487,31 +487,31 @@ if ($id) print '
 
 
'; - print_fleche_navigation($page, $_SERVER["PHP_SELF"], $paramwithsearch, ($num > $listlimit), ''); + print '
'; + print_fleche_navigation($page, $_SERVER["PHP_SELF"], $paramwithsearch, ($num > $listlimit), ''); print '
'.$valuetoshow.''; @@ -708,10 +708,10 @@ $db->close(); */ function fieldListJournal($fieldlist, $obj = '', $tabname = '', $context = '') { - global $conf,$langs,$db; + global $conf, $langs, $db; global $form, $mysoc; global $region_id; - global $elementList,$sourceList,$localtax_typeList; + global $elementList, $sourceList, $localtax_typeList; global $bc; $formadmin = new FormAdmin($db); @@ -722,20 +722,20 @@ function fieldListJournal($fieldlist, $obj = '', $tabname = '', $context = '') if ($fieldlist[$field] == 'nature') { print ''; - print $form->selectarray('nature', $sourceList, (! empty($obj->{$fieldlist[$field]})?$obj->{$fieldlist[$field]}:'')); + print $form->selectarray('nature', $sourceList, (!empty($obj->{$fieldlist[$field]}) ? $obj->{$fieldlist[$field]}:'')); print ''; - $size=''; $class=''; - if ($fieldlist[$field]=='code') $class='maxwidth100'; - if ($fieldlist[$field]=='label') $class='quatrevingtpercent'; - if ($fieldlist[$field]=='sortorder' || $fieldlist[$field]=='sens' || $fieldlist[$field]=='category_type') $size='size="2" '; - print ''; + $size = ''; $class = ''; + if ($fieldlist[$field] == 'code') $class = 'maxwidth100'; + if ($fieldlist[$field] == 'label') $class = 'quatrevingtpercent'; + if ($fieldlist[$field] == 'sortorder' || $fieldlist[$field] == 'sens' || $fieldlist[$field] == 'category_type') $size = 'size="2" '; + print ''; print '
'; + print '
'; print ''; print ''; print "\n"; @@ -369,9 +382,13 @@ if ($result) print ''; if (! empty($conf->global->ACCOUNTANCY_SHOW_PROD_DESC)) print ''; // On sell - if ($accounting_product_mode == 'ACCOUNTANCY_SELL' || $accounting_product_mode == 'ACCOUNTANCY_SELL_INTRA' || $accounting_product_mode == 'ACCOUNTANCY_SELL_EXPORT') print ''; + if ($accounting_product_mode == 'ACCOUNTANCY_SELL' || $accounting_product_mode == 'ACCOUNTANCY_SELL_INTRA' || $accounting_product_mode == 'ACCOUNTANCY_SELL_EXPORT') { + print ''; + } // On buy - if ($accounting_product_mode == 'ACCOUNTANCY_BUY') print ''; + elseif ($accounting_product_mode == 'ACCOUNTANCY_BUY') { + print ''; + } // Current account print ''; - if (! empty($conf->global->ACCOUNTANCY_SHOW_PROD_DESC)) + if (!empty($conf->global->ACCOUNTANCY_SHOW_PROD_DESC)) { // TODO ADJUST DESCRIPTION SIZE // print ''; // TODO: we shoul set a user defined value to adjust user square / wide screen size $trunclengh = empty($conf->global->ACCOUNTING_LENGTH_DESCRIPTION) ? 32 : $conf->global->ACCOUNTING_LENGTH_DESCRIPTION; - print ''; + print ''; } if ($accounting_product_mode == 'ACCOUNTANCY_SELL' || $accounting_product_mode == 'ACCOUNTANCY_SELL_INTRA' || $accounting_product_mode == 'ACCOUNTANCY_SELL_EXPORT') @@ -486,7 +529,7 @@ if ($result) } print ''; - // Dedicated account + // New account to set $defaultvalue=''; if ($accounting_product_mode == 'ACCOUNTANCY_BUY') { // Accounting account buy diff --git a/htdocs/accountancy/bookkeeping/balance.php b/htdocs/accountancy/bookkeeping/balance.php index 7d48790348d..02174ea2524 100644 --- a/htdocs/accountancy/bookkeeping/balance.php +++ b/htdocs/accountancy/bookkeeping/balance.php @@ -28,12 +28,12 @@ require '../../main.inc.php'; // Class -require_once DOL_DOCUMENT_ROOT . '/core/lib/accounting.lib.php'; -require_once DOL_DOCUMENT_ROOT . '/core/lib/date.lib.php'; -require_once DOL_DOCUMENT_ROOT . '/accountancy/class/bookkeeping.class.php'; -require_once DOL_DOCUMENT_ROOT . '/accountancy/class/accountancyexport.class.php'; -require_once DOL_DOCUMENT_ROOT . '/core/class/html.formaccounting.class.php'; -require_once DOL_DOCUMENT_ROOT . '/core/class/html.formother.class.php'; +require_once DOL_DOCUMENT_ROOT.'/core/lib/accounting.lib.php'; +require_once DOL_DOCUMENT_ROOT.'/core/lib/date.lib.php'; +require_once DOL_DOCUMENT_ROOT.'/accountancy/class/bookkeeping.class.php'; +require_once DOL_DOCUMENT_ROOT.'/accountancy/class/accountancyexport.class.php'; +require_once DOL_DOCUMENT_ROOT.'/core/class/html.formaccounting.class.php'; +require_once DOL_DOCUMENT_ROOT.'/core/class/html.formother.class.php'; // Load translation files required by the page $langs->loadLangs(array("accountancy")); @@ -45,7 +45,7 @@ $action = GETPOST('action', 'aZ09'); if (GETPOST("exportcsv", 'alpha')) $action = 'export_csv'; // Load variable for pagination -$limit = GETPOST('limit', 'int')?GETPOST('limit', 'int'):$conf->liste_limit; +$limit = GETPOST('limit', 'int') ?GETPOST('limit', 'int') : $conf->liste_limit; $sortfield = GETPOST('sortfield', 'alpha'); $sortorder = GETPOST('sortorder', 'alpha'); $page = GETPOST('page', 'int'); @@ -75,18 +75,18 @@ $formaccounting = new FormAccounting($db); $formother = new FormOther($db); $form = new Form($db); -if (empty($search_date_start) && ! GETPOSTISSET('formfilteraction')) +if (empty($search_date_start) && !GETPOSTISSET('formfilteraction')) { - $sql = "SELECT date_start, date_end from ".MAIN_DB_PREFIX."accounting_fiscalyear "; - $sql.= " where date_start < '".$db->idate(dol_now())."' and date_end > '".$db->idate(dol_now())."'"; - $sql.= $db->plimit(1); + $sql = "SELECT date_start, date_end from ".MAIN_DB_PREFIX."accounting_fiscalyear "; + $sql .= " where date_start < '".$db->idate(dol_now())."' and date_end > '".$db->idate(dol_now())."'"; + $sql .= $db->plimit(1); $res = $db->query($sql); if ($res->num_rows > 0) { $fiscalYear = $db->fetch_object($res); $search_date_start = strtotime($fiscalYear->date_start); $search_date_end = strtotime($fiscalYear->date_end); } else { - $month_start= ($conf->global->SOCIETE_FISCAL_MONTH_START?($conf->global->SOCIETE_FISCAL_MONTH_START):1); + $month_start = ($conf->global->SOCIETE_FISCAL_MONTH_START ? ($conf->global->SOCIETE_FISCAL_MONTH_START) : 1); $year_start = dol_print_date(dol_now(), '%Y'); $year_end = $year_start + 1; $month_end = $month_start - 1; @@ -105,26 +105,26 @@ if ($sortfield == "") $sortfield = "t.numero_compte"; -$param=''; -if (! empty($contextpage) && $contextpage != $_SERVER["PHP_SELF"]) $param.='&contextpage='.urlencode($contextpage); -if ($limit > 0 && $limit != $conf->liste_limit) $param.='&limit='.urlencode($limit); +$param = ''; +if (!empty($contextpage) && $contextpage != $_SERVER["PHP_SELF"]) $param .= '&contextpage='.urlencode($contextpage); +if ($limit > 0 && $limit != $conf->liste_limit) $param .= '&limit='.urlencode($limit); -$filter = array (); -if (! empty($search_date_start)) { +$filter = array(); +if (!empty($search_date_start)) { $filter['t.doc_date>='] = $search_date_start; - $param .= '&date_startmonth=' . GETPOST('date_startmonth', 'int') . '&date_startday=' . GETPOST('date_startday', 'int') . '&date_startyear=' . GETPOST('date_startyear', 'int'); + $param .= '&date_startmonth='.GETPOST('date_startmonth', 'int').'&date_startday='.GETPOST('date_startday', 'int').'&date_startyear='.GETPOST('date_startyear', 'int'); } -if (! empty($search_date_end)) { +if (!empty($search_date_end)) { $filter['t.doc_date<='] = $search_date_end; - $param .= '&date_endmonth=' . GETPOST('date_endmonth', 'int') . '&date_endday=' . GETPOST('date_endday', 'int') . '&date_endyear=' . GETPOST('date_endyear', 'int'); + $param .= '&date_endmonth='.GETPOST('date_endmonth', 'int').'&date_endday='.GETPOST('date_endday', 'int').'&date_endyear='.GETPOST('date_endyear', 'int'); } -if (! empty($search_accountancy_code_start)) { +if (!empty($search_accountancy_code_start)) { $filter['t.numero_compte>='] = $search_accountancy_code_start; - $param .= '&search_accountancy_code_start=' . $search_accountancy_code_start; + $param .= '&search_accountancy_code_start='.$search_accountancy_code_start; } -if (! empty($search_accountancy_code_end)) { +if (!empty($search_accountancy_code_end)) { $filter['t.numero_compte<='] = $search_accountancy_code_end; - $param .= '&search_accountancy_code_end=' . $search_accountancy_code_end; + $param .= '&search_accountancy_code_end='.$search_accountancy_code_end; } /* @@ -151,7 +151,7 @@ if ($action == 'export_csv') $filename = 'balance'; $type_export = 'balance'; - include DOL_DOCUMENT_ROOT . '/accountancy/tpl/export_journal.tpl.php'; + include DOL_DOCUMENT_ROOT.'/accountancy/tpl/export_journal.tpl.php'; $result = $object->fetchAllBalance($sortorder, $sortfield, $limit, 0, $filter); if ($result < 0) { @@ -160,11 +160,11 @@ if ($action == 'export_csv') foreach ($object->lines as $line) { - print length_accountg($line->numero_compte) . $sep; - print $object->get_compte_desc($line->numero_compte) . $sep; - print price($line->debit) . $sep; - print price($line->credit) . $sep; - print price($line->debit - $line->credit) . $sep; + print length_accountg($line->numero_compte).$sep; + print $object->get_compte_desc($line->numero_compte).$sep; + print price($line->debit).$sep; + print price($line->credit).$sep; + print price($line->debit - $line->credit).$sep; print "\n"; } @@ -203,20 +203,20 @@ if ($action != 'export_csv') print ''; print ''; - $button = 'global->ACCOUNTING_EXPORT_FORMAT.')" />'; + $button = 'global->ACCOUNTING_EXPORT_FORMAT.')" />'; print_barre_liste($title_page, $page, $_SERVER["PHP_SELF"], $param, $sortfield, $sortorder, $button, $result, $nbtotalofrecords, 'title_accountancy', 0, '', '', $limit); $moreforfilter = ''; $moreforfilter .= '
'; - $moreforfilter .= $langs->trans('DateStart') . ': '; - $moreforfilter .= $form->selectDate($search_date_start?$search_date_start:-1, 'date_start', 0, 0, 1, '', 1, 0); - $moreforfilter .= $langs->trans('DateEnd') . ': '; - $moreforfilter .= $form->selectDate($search_date_end?$search_date_end:-1, 'date_end', 0, 0, 1, '', 1, 0); + $moreforfilter .= $langs->trans('DateStart').': '; + $moreforfilter .= $form->selectDate($search_date_start ? $search_date_start : -1, 'date_start', 0, 0, 1, '', 1, 0); + $moreforfilter .= $langs->trans('DateEnd').': '; + $moreforfilter .= $form->selectDate($search_date_end ? $search_date_end : -1, 'date_end', 0, 0, 1, '', 1, 0); $moreforfilter .= '
'; - if (! empty($moreforfilter)) { + if (!empty($moreforfilter)) { print '
'; print $moreforfilter; $parameters = array(); @@ -225,7 +225,7 @@ if ($action != 'export_csv') print '
'; } - print '
' . $langs->trans('Options') . '' . $langs->trans('Description') . '
'.$form->selectyesno('search_onsell', $search_onsell, 1, false, 1).''.$form->selectyesno('search_onpurchase', $search_onpurchase, 1, false, 1).''; print ''; @@ -389,6 +406,7 @@ if ($result) print_liste_field_titre("Ref", $_SERVER["PHP_SELF"], "p.ref", "", $param, '', $sortfield, $sortorder); print_liste_field_titre("Label", $_SERVER["PHP_SELF"], "p.label", "", $param, '', $sortfield, $sortorder); if (! empty($conf->global->ACCOUNTANCY_SHOW_PROD_DESC)) print_liste_field_titre("Description", $_SERVER["PHP_SELF"], "p.description", "", $param, '', $sortfield, $sortorder); + // On sell / On purchase if ($accounting_product_mode == 'ACCOUNTANCY_SELL') { print_liste_field_titre("OnSell", $_SERVER["PHP_SELF"], "p.tosell", "", $param, '', $sortfield, $sortorder, 'center '); $fieldtosortaccount="p.accountancy_code_sell"; @@ -424,20 +442,45 @@ if ($result) $product_static->status = $obj->tosell; $product_static->status_buy = $obj->tobuy; - if ($obj->product_type == 0 && $accounting_product_mode == 'ACCOUNTANCY_SELL') { - $compta_prodsell = (! empty($conf->global->ACCOUNTING_PRODUCT_SOLD_ACCOUNT) ? $conf->global->ACCOUNTING_PRODUCT_SOLD_ACCOUNT : $langs->trans("CodeNotDef")); - $compta_prodsell_id = $aarowid_prodsell; - } elseif ($obj->product_type == 0 && $accounting_product_mode == 'ACCOUNTANCY_SELL_INTRA') { - $compta_prodsell = (! empty($conf->global->ACCOUNTING_PRODUCT_SOLD_INTRA_ACCOUNT) ? $conf->global->ACCOUNTING_PRODUCT_SOLD_INTRA_ACCOUNT : $langs->trans("CodeNotDef")); - $compta_prodsell_id = $aarowid_prodsell_intra; - } elseif ($obj->product_type == 0 && $accounting_product_mode == 'ACCOUNTANCY_SELL_EXPORT') { - $compta_prodsell = (! empty($conf->global->ACCOUNTING_PRODUCT_SOLD_EXPORT_ACCOUNT) ? $conf->global->ACCOUNTING_PRODUCT_SOLD_EXPORT_ACCOUNT : $langs->trans("CodeNotDef")); - $compta_prodsell_id = $aarowid_prodsell_export; - } else { - $compta_prodsell = (! empty($conf->global->ACCOUNTING_SERVICE_SOLD_ACCOUNT) ? $conf->global->ACCOUNTING_SERVICE_SOLD_ACCOUNT : $langs->trans("CodeNotDef")); - $compta_prodsell_id = $aarowid_servsell; + // Sales + if ($obj->product_type == 0) { + if ($accounting_product_mode == 'ACCOUNTANCY_SELL') { + $compta_prodsell = (! empty($conf->global->ACCOUNTING_PRODUCT_SOLD_ACCOUNT) ? $conf->global->ACCOUNTING_PRODUCT_SOLD_ACCOUNT : $langs->trans("CodeNotDef")); + $compta_prodsell_id = $aarowid_prodsell; + } + elseif ($accounting_product_mode == 'ACCOUNTANCY_SELL_INTRA') { + $compta_prodsell = (! empty($conf->global->ACCOUNTING_PRODUCT_SOLD_INTRA_ACCOUNT) ? $conf->global->ACCOUNTING_PRODUCT_SOLD_INTRA_ACCOUNT : $langs->trans("CodeNotDef")); + $compta_prodsell_id = $aarowid_prodsell_intra; + } + elseif ($accounting_product_mode == 'ACCOUNTANCY_SELL_EXPORT') { + $compta_prodsell = (! empty($conf->global->ACCOUNTING_PRODUCT_SOLD_EXPORT_ACCOUNT) ? $conf->global->ACCOUNTING_PRODUCT_SOLD_EXPORT_ACCOUNT : $langs->trans("CodeNotDef")); + $compta_prodsell_id = $aarowid_prodsell_export; + } + else { + $compta_prodsell = (! empty($conf->global->ACCOUNTING_SERVICE_SOLD_ACCOUNT) ? $conf->global->ACCOUNTING_SERVICE_SOLD_ACCOUNT : $langs->trans("CodeNotDef")); + $compta_prodsell_id = $aarowid_servsell; + } + } + else { + if ($accounting_product_mode == 'ACCOUNTANCY_SELL') { + $compta_prodsell = (! empty($conf->global->ACCOUNTING_SERVICE_SOLD_ACCOUNT) ? $conf->global->ACCOUNTING_SERVICE_SOLD_ACCOUNT : $langs->trans("CodeNotDef")); + $compta_prodsell_id = $aarowid_prodsell; + } + elseif ($accounting_product_mode == 'ACCOUNTANCY_SELL_INTRA') { + $compta_prodsell = (! empty($conf->global->ACCOUNTING_SERVICE_SOLD_INTRA_ACCOUNT) ? $conf->global->ACCOUNTING_SERVICE_SOLD_INTRA_ACCOUNT : $langs->trans("CodeNotDef")); + $compta_prodsell_id = $aarowid_prodsell_intra; + } + elseif ($accounting_product_mode == 'ACCOUNTANCY_SELL_EXPORT') { + $compta_prodsell = (! empty($conf->global->ACCOUNTING_SERVICE_SOLD_EXPORT_ACCOUNT) ? $conf->global->ACCOUNTING_SERVICE_SOLD_EXPORT_ACCOUNT : $langs->trans("CodeNotDef")); + $compta_prodsell_id = $aarowid_prodsell_export; + } + else { + $compta_prodsell = (! empty($conf->global->ACCOUNTING_SERVICE_SOLD_ACCOUNT) ? $conf->global->ACCOUNTING_SERVICE_SOLD_ACCOUNT : $langs->trans("CodeNotDef")); + $compta_prodsell_id = $aarowid_servsell; + } } + // Purchases if ($obj->product_type == 0) { $compta_prodbuy = (! empty($conf->global->ACCOUNTING_PRODUCT_BUY_ACCOUNT) ? $conf->global->ACCOUNTING_PRODUCT_BUY_ACCOUNT : $langs->trans("CodeNotDef")); $compta_prodbuy_id = $aarowid_prodbuy; @@ -454,13 +497,13 @@ if ($result) print ''.$obj->label.'' . $obj->description . '' . nl2br(dol_trunc($obj->description, $trunclengh)) . ''.nl2br(dol_trunc($obj->description, $trunclengh)).'
'; + print '
'; print ''; print ''; print ''; @@ -265,7 +265,7 @@ if ($action != 'export_csv') $description = $object->get_compte_desc($line->numero_compte); // Search description of the account $root_account_description = $object->get_compte_racine($line->numero_compte); if (empty($description)) { - $link = '' . img_edit_add() . ''; + $link = ''.img_edit_add().''; } print ''; @@ -291,12 +291,12 @@ if ($action != 'export_csv') // $object->get_compte_racine($line->numero_compte); - print ''; - print ''; - print ''; - print ''; - print ''; - print ''; + print ''; + print ''; + print ''; + print ''; + print ''; print "\n"; @@ -305,11 +305,11 @@ if ($action != 'export_csv') $sous_total_credit += $line->credit; } - print ''; + print ''; print "\n"; print ''; - print ''; + print ''; print "\n"; print ''; diff --git a/htdocs/accountancy/bookkeeping/balancebymonth.php b/htdocs/accountancy/bookkeeping/balancebymonth.php index bdc78911513..f27d535f57c 100644 --- a/htdocs/accountancy/bookkeeping/balancebymonth.php +++ b/htdocs/accountancy/bookkeeping/balancebymonth.php @@ -26,11 +26,11 @@ */ require '../../main.inc.php'; -require_once DOL_DOCUMENT_ROOT . '/core/lib/date.lib.php'; -require_once DOL_DOCUMENT_ROOT . '/core/lib/accounting.lib.php'; +require_once DOL_DOCUMENT_ROOT.'/core/lib/date.lib.php'; +require_once DOL_DOCUMENT_ROOT.'/core/lib/accounting.lib.php'; // Load translation files required by the page -$langs->loadLangs(array("bills","compta","accountancy","other")); +$langs->loadLangs(array("bills", "compta", "accountancy", "other")); // Filter $year = GETPOST("year", 'int'); @@ -49,17 +49,17 @@ if ($year == 0) { llxHeader('', $langs->trans("Bookkeeping")); -$textprevyear = '' . img_previous() . ''; -$textnextyear = ' ' . img_next() . ''; +$textprevyear = ''.img_previous().''; +$textnextyear = ' '.img_next().''; -print load_fiche_titre($langs->trans("AccountBalanceByMonth") . ' ' . $textprevyear . ' ' . $langs->trans("Year") . ' ' . $year_start . ' ' . $textnextyear); +print load_fiche_titre($langs->trans("AccountBalanceByMonth").' '.$textprevyear.' '.$langs->trans("Year").' '.$year_start.' '.$textnextyear); -$sql = "SELECT count(*) FROM " . MAIN_DB_PREFIX . "facturedet as fd"; -$sql .= " , " . MAIN_DB_PREFIX . "facture as f"; +$sql = "SELECT count(*) FROM ".MAIN_DB_PREFIX."facturedet as fd"; +$sql .= " , ".MAIN_DB_PREFIX."facture as f"; $sql .= " WHERE fd.fk_code_ventilation = 0"; $sql .= " AND f.rowid = fd.fk_facture AND f.fk_statut = 1;"; -dol_syslog('accountancy/bookkeeping/balancebymonth.php:: $sql=' . $sql); +dol_syslog('accountancy/bookkeeping/balancebymonth.php:: $sql='.$sql); $result = $db->query($sql); if ($result) { $row = $db->fetch_row($result); @@ -70,12 +70,12 @@ if ($result) { $y = $year_current; -print '
'; @@ -236,7 +236,7 @@ if ($action != 'export_csv') print $formaccounting->select_account($search_accountancy_code_end, 'search_accountancy_code_end', 1, array(), 1, 1, ''); print ''; - $searchpicto=$form->showFilterAndCheckAddButtons(0); + $searchpicto = $form->showFilterAndCheckAddButtons(0); print $searchpicto; print '
' . length_accountg($line->numero_compte) . '' . $description . '' . price($line->debit) . '' . price($line->credit) . '' . price($line->debit - $line->credit) . '' . $link; + print ''.length_accountg($line->numero_compte).''.$description.''.price($line->debit).''.price($line->credit).''.price($line->debit - $line->credit).''.$link; print '
' . $langs->trans("SubTotal") . ':' . price($sous_total_debit) . '' . price($sous_total_credit) . '' . price(price2num($sous_total_debit - $sous_total_credit)) . '
'.$langs->trans("SubTotal").':'.price($sous_total_debit).''.price($sous_total_credit).''.price(price2num($sous_total_debit - $sous_total_credit)).' 
' . $langs->trans("AccountBalance") . ':' . price($total_debit) . '' . price($total_credit) . '' . price(price2num($total_debit - $total_credit)) . '
'.$langs->trans("AccountBalance").':'.price($total_debit).''.price($total_credit).''.price(price2num($total_debit - $total_credit)).' 
'; +print '
'; print ''; -print ''; -for($i = 1; $i <= 12; $i++) +print ''; +for ($i = 1; $i <= 12; $i++) { - print ''; + print ''; } print ''; print ''; @@ -94,9 +94,9 @@ $sql .= " ROUND(SUM(IF(MONTH(bk.doc_date)=10,bk.montant,0)),2) AS 'Octobre',"; $sql .= " ROUND(SUM(IF(MONTH(bk.doc_date)=11,bk.montant,0)),2) AS 'Novembre',"; $sql .= " ROUND(SUM(IF(MONTH(bk.doc_date)=12,bk.montant,0)),2) AS 'Decembre',"; $sql .= " ROUND(SUM(bk.montant),2) as 'Total'"; -$sql .= " FROM " . MAIN_DB_PREFIX . "accounting_bookkeeping as bk"; -$sql .= " WHERE bk.doc_date >= '" . $db->idate(dol_get_first_day($y, 1, false)) . "'"; -$sql .= " AND bk.doc_date <= '" . $db->idate(dol_get_last_day($y, 12, false)) . "'"; +$sql .= " FROM ".MAIN_DB_PREFIX."accounting_bookkeeping as bk"; +$sql .= " WHERE bk.doc_date >= '".$db->idate(dol_get_first_day($y, 1, false))."'"; +$sql .= " AND bk.doc_date <= '".$db->idate(dol_get_last_day($y, 12, false))."'"; $sql .= " GROUP BY bk.numero_compte"; $resql = $db->query($sql); @@ -104,26 +104,26 @@ if ($resql) { $i = 0; $num = $db->num_rows($resql); - while ( $i < $num ) { + while ($i < $num) { $row = $db->fetch_row($resql); - print ''; - print ''; - print ''; - print ''; - print ''; - print ''; - print ''; - print ''; - print ''; - print ''; - print ''; - print ''; - print ''; - print ''; + print ''; + print ''; + print ''; + print ''; + print ''; + print ''; + print ''; + print ''; + print ''; + print ''; + print ''; + print ''; + print ''; + print ''; print ''; - $i ++; + $i++; } $db->free($resql); } else { diff --git a/htdocs/accountancy/bookkeeping/card.php b/htdocs/accountancy/bookkeeping/card.php index ca6403279e1..c1513a93a23 100644 --- a/htdocs/accountancy/bookkeeping/card.php +++ b/htdocs/accountancy/bookkeeping/card.php @@ -26,23 +26,23 @@ */ require '../../main.inc.php'; -require_once DOL_DOCUMENT_ROOT . '/core/lib/accounting.lib.php'; -require_once DOL_DOCUMENT_ROOT . '/accountancy/class/bookkeeping.class.php'; -require_once DOL_DOCUMENT_ROOT . '/core/class/html.formaccounting.class.php'; -require_once DOL_DOCUMENT_ROOT . '/compta/facture/class/facture.class.php'; -require_once DOL_DOCUMENT_ROOT . '/fourn/class/fournisseur.facture.class.php'; -require_once DOL_DOCUMENT_ROOT . '/accountancy/class/accountingjournal.class.php'; -require_once DOL_DOCUMENT_ROOT . '/accountancy/class/accountingaccount.class.php'; +require_once DOL_DOCUMENT_ROOT.'/core/lib/accounting.lib.php'; +require_once DOL_DOCUMENT_ROOT.'/accountancy/class/bookkeeping.class.php'; +require_once DOL_DOCUMENT_ROOT.'/core/class/html.formaccounting.class.php'; +require_once DOL_DOCUMENT_ROOT.'/compta/facture/class/facture.class.php'; +require_once DOL_DOCUMENT_ROOT.'/fourn/class/fournisseur.facture.class.php'; +require_once DOL_DOCUMENT_ROOT.'/accountancy/class/accountingjournal.class.php'; +require_once DOL_DOCUMENT_ROOT.'/accountancy/class/accountingaccount.class.php'; // Load translation files required by the page $langs->loadLangs(array("accountancy", "bills", "compta")); $action = GETPOST('action', 'aZ09'); -$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') -$id = GETPOST('id', 'int'); // id of record -$mode = GETPOST('mode', 'aZ09'); // '' or 'tmp' -$piece_num = GETPOST("piece_num", 'int'); // id of transaction (several lines share the same transaction id) +$id = GETPOST('id', 'int'); // id of record +$mode = GETPOST('mode', 'aZ09'); // '' or 'tmp' +$piece_num = GETPOST("piece_num", 'int'); // id of transaction (several lines share the same transaction id) // Security check if ($user->socid > 0) { @@ -66,14 +66,14 @@ $subledger_account = GETPOST('subledger_account', 'alphanohtml'); if ($subledger_account == - 1) { $subledger_account = null; } -$label_operation= GETPOST('label_operation', 'alphanohtml'); +$label_operation = GETPOST('label_operation', 'alphanohtml'); $debit = price2num(GETPOST('debit', 'alpha')); $credit = price2num(GETPOST('credit', 'alpha')); $save = GETPOST('save', 'alpha'); -if (! empty($save)) $action = 'add'; +if (!empty($save)) $action = 'add'; $update = GETPOST('update', 'alpha'); -if (! empty($update)) $action = 'confirm_update'; +if (!empty($update)) $action = 'confirm_update'; $object = new BookKeeping($db); @@ -88,16 +88,16 @@ if ($action == "confirm_update") { if ((floatval($debit) != 0.0) && (floatval($credit) != 0.0)) { $error++; setEventMessages($langs->trans('ErrorDebitCredit'), null, 'errors'); - $action='update'; + $action = 'update'; } if (empty($accountingaccount_number) || $accountingaccount_number == '-1') { $error++; setEventMessages($langs->trans('ErrorFieldRequired', $langs->transnoentitiesnoconv("AccountAccountingShort")), null, 'errors'); - $action='update'; + $action = 'update'; } - if (! $error) + if (!$error) { $object = new BookKeeping($db); @@ -109,7 +109,7 @@ if ($action == "confirm_update") { $object->numero_compte = $accountingaccount_number; $object->subledger_account = $subledger_account; $object->label_compte = $accountingaccount_label; - $object->label_operation= $label_operation; + $object->label_operation = $label_operation; $object->debit = $debit; $object->credit = $credit; @@ -147,22 +147,22 @@ elseif ($action == "add") { { $error++; setEventMessages($langs->trans('ErrorDebitCredit'), null, 'errors'); - $action=''; + $action = ''; } if (empty($accountingaccount_number) || $accountingaccount_number == '-1') { $error++; setEventMessages($langs->trans('ErrorFieldRequired', $langs->transnoentitiesnoconv("AccountAccountingShort")), null, 'errors'); - $action=''; + $action = ''; } - if (! $error) { + if (!$error) { $object = new BookKeeping($db); $object->numero_compte = $accountingaccount_number; $object->subledger_account = $subledger_account; $object->label_compte = $accountingaccount_label; - $object->label_operation= $label_operation; + $object->label_operation = $label_operation; $object->debit = $debit; $object->credit = $credit; $object->doc_date = GETPOST('doc_date', 'alpha'); @@ -223,18 +223,18 @@ elseif ($action == "confirm_create") { $object = new BookKeeping($db); - if (! $journal_code || $journal_code == '-1') { + if (!$journal_code || $journal_code == '-1') { setEventMessages($langs->trans('ErrorFieldRequired', $langs->transnoentitiesnoconv("Journal")), null, 'errors'); - $action='create'; + $action = 'create'; $error++; } - if (! GETPOST('next_num_mvt', 'alpha')) + if (!GETPOST('next_num_mvt', 'alpha')) { setEventMessages($langs->trans("ErrorFieldRequired", $langs->transnoentitiesnoconv("NumPiece")), null, 'errors'); $error++; } - if (! $error) + if (!$error) { $object->label_compte = ''; $object->debit = 0; @@ -258,7 +258,7 @@ elseif ($action == "confirm_create") { setEventMessages($langs->trans('RecordSaved'), null, 'mesgs'); } $action = 'update'; - $id=$object->id; + $id = $object->id; $piece_num = $object->piece_num; } } @@ -329,7 +329,7 @@ llxHeader('', $langs->trans("CreateMvts")); // Confirmation to delete the command if ($action == 'delete') { - $formconfirm = $html->formconfirm($_SERVER["PHP_SELF"] . '?id=' . $id.'&mode='. $mode, $langs->trans('DeleteMvt'), $langs->trans('ConfirmDeleteMvt'), 'confirm_delete', '', 0, 1); + $formconfirm = $html->formconfirm($_SERVER["PHP_SELF"].'?id='.$id.'&mode='.$mode, $langs->trans('DeleteMvt'), $langs->trans('ConfirmDeleteMvt'), 'confirm_delete', '', 0, 1); print $formconfirm; } @@ -345,16 +345,16 @@ if ($action == 'create') dol_print_error('', 'Failed to get next piece number'); } - print ''; + print ''; if ($optioncss != '') print ''; print ''; - print '' . "\n"; - print '' . "\n"; - print '' . "\n"; + print ''."\n"; + print ''."\n"; + print ''."\n"; dol_fiche_head(); - print '
' . $langs->trans("Label") . ''.$langs->trans("Label").'' . $langs->trans("MonthShort".sprintf("%02s", $i)) . ''.$langs->trans("MonthShort".sprintf("%02s", $i)).''.$langs->trans("Total").'
' . length_accountg($row[0]) . '' . price($row[1]) . '' . price($row[2]) . '' . price($row[3]) . '' . price($row[4]) . '' . price($row[5]) . '' . price($row[6]) . '' . price($row[7]) . '' . price($row[8]) . '' . price($row[9]) . '' . price($row[10]) . '' . price($row[11]) . '' . price($row[12]) . '' . price($row[13]) . '
'.length_accountg($row[0]).''.price($row[1]).''.price($row[2]).''.price($row[3]).''.price($row[4]).''.price($row[5]).''.price($row[6]).''.price($row[7]).''.price($row[8]).''.price($row[9]).''.price($row[10]).''.price($row[11]).''.price($row[12]).''.price($row[13]).'
'; + print '
'; /*print ''; print ''; @@ -362,19 +362,19 @@ if ($action == 'create') print '';*/ print ''; - print ''; + print ''; print ''; print ''; print ''; - print ''; - print ''; + print ''; + print ''; print ''; print ''; - print ''; + print ''; print ''; print ''; @@ -390,9 +390,9 @@ if ($action == 'create') dol_fiche_end(); print '
'; - print ''; + print ''; print '     '; - print ''; + print ''; print '
'; print ''; @@ -403,15 +403,15 @@ if ($action == 'create') setEventMessages($object->error, $object->errors, 'errors'); } - if (! empty($object->piece_num)) + if (!empty($object->piece_num)) { - $backlink = '' . $langs->trans('BackToList') . ''; + $backlink = ''.$langs->trans('BackToList').''; print load_fiche_titre($langs->trans("UpdateMvts"), $backlink); - $head=array(); - $h=0; - $head[$h][0] = $_SERVER['PHP_SELF'].'?piece_num='.$object->piece_num.($mode?'&mode='.$mode:''); + $head = array(); + $h = 0; + $head[$h][0] = $_SERVER['PHP_SELF'].'?piece_num='.$object->piece_num.($mode ? '&mode='.$mode : ''); $head[$h][1] = $langs->trans("Transaction"); $head[$h][2] = 'transaction'; $h++; @@ -428,8 +428,8 @@ if ($action == 'create') // Account movement print ''; - print ''; - print ''; + print ''; + print ''; print ''; // Date @@ -438,17 +438,17 @@ if ($action == 'create') print $langs->trans('Docdate'); print ''; if ($action != 'editdate') - print ''; + print ''; print '
' . $langs->trans("NumPiece") . '
' . $langs->trans("Docdate") . ''.$langs->trans("Docdate").''; print $html->selectDate('', 'doc_date', '', '', '', "create_mvt", 1, 1); print '
' . $langs->trans("Codejournal") . '' . $formaccounting->select_journal($journal_code, 'code_journal', 0, 0, 1, 1) . ''.$langs->trans("Codejournal").''.$formaccounting->select_journal($journal_code, 'code_journal', 0, 0, 1, 1).'
' . $langs->trans("Piece") . ''.$langs->trans("Piece").'
' . $langs->trans("NumMvts") . '' . $object->piece_num . ''.$langs->trans("NumMvts").''.$object->piece_num.'
piece_num .'&mode='. $mode .'">'.img_edit($langs->transnoentitiesnoconv('SetDate'), 1).'piece_num.'&mode='.$mode.'">'.img_edit($langs->transnoentitiesnoconv('SetDate'), 1).'
'; print '
'; if ($action == 'editdate') { - print '
'; + print ''; if ($optioncss != '') print ''; print ''; print ''; print ''; print $form->selectDate($object->doc_date ? $object->doc_date : - 1, 'doc_date', '', '', '', "setdate"); - print ''; + print ''; print '
'; } else { print $object->doc_date ? dol_print_date($object->doc_date, 'day') : ' '; @@ -462,20 +462,20 @@ if ($action == 'create') print $langs->trans('Codejournal'); print '
piece_num.'&mode='. $mode .'">'.img_edit($langs->transnoentitiesnoconv('Edit'), 1).'piece_num.'&mode='.$mode.'">'.img_edit($langs->transnoentitiesnoconv('Edit'), 1).'
'; print ''; if ($action == 'editjournal') { - print '
'; + print ''; if ($optioncss != '') print ''; print ''; print ''; print ''; print $formaccounting->select_journal($object->code_journal, 'code_journal', 0, 0, array(), 1, 1); - print ''; + print ''; print '
'; } else { - print $object->code_journal ; + print $object->code_journal; } print ''; print ''; @@ -486,20 +486,20 @@ if ($action == 'create') print $langs->trans('Piece'); print ''; if ($action != 'editdocref') - print '
piece_num.'&mode='. $mode .'">'.img_edit($langs->transnoentitiesnoconv('Edit'), 1).''; + print 'piece_num.'&mode='.$mode.'">'.img_edit($langs->transnoentitiesnoconv('Edit'), 1).''; print ''; print ''; if ($action == 'editdocref') { - print '
'; + print ''; if ($optioncss != '') print ''; print ''; print ''; print ''; print ''; - print ''; + print ''; print '
'; } else { - print $object->doc_ref ; + print $object->doc_ref; } print ''; print ''; @@ -514,17 +514,17 @@ if ($action == 'create') print ''; // Doc type - if(! empty($object->doc_type)) + if (!empty($object->doc_type)) { print ''; - print ''; - print ''; + print ''; + print ''; print ''; } // Date document creation print ''; - print ''; + print ''; print ''; @@ -536,11 +536,11 @@ if ($action == 'create') print ''; print '
' . $langs->trans("Doctype") . '' . $object->doc_type . ''.$langs->trans("Doctype").''.$object->doc_type.'
' . $langs->trans("DateCreation") . ''.$langs->trans("DateCreation").''; print $object->date_creation ? dol_print_date($object->date_creation, 'day') : ' '; print '' . $langs->trans("Status") . ''; if (empty($object->validated)) { - print ''; + print ''; print img_picto($langs->trans("Disabled"), 'switch_off'); print ''; } else { - print ''; + print ''; print img_picto($langs->trans("Activated"), 'switch_on'); print ''; } @@ -586,16 +586,16 @@ if ($action == 'create') } else { print load_fiche_titre($langs->trans("ListeMvts"), '', ''); - print '
'; + print ''; if ($optioncss != '') print ''; print ''; - print '' . "\n"; - print '' . "\n"; - print '' . "\n"; - print '' . "\n"; - print '' . "\n"; - print '' . "\n"; - print '' . "\n"; + print ''."\n"; + print ''."\n"; + print ''."\n"; + print ''."\n"; + print ''."\n"; + print ''."\n"; + print ''."\n"; print ""; if (count($object->linesmvt) > 0) { @@ -620,12 +620,12 @@ if ($action == 'create') if ($action == 'update' && $line->id == $id) { print ''; print ''; - print ''; - print ''; - print ''; + print ''; + print ''; + print ''; print ''; } else { $accountingaccount->fetch(null, $line->numero_compte, true); - print ''; - print ''; - print ''; - print ''; - print ''; + print ''; + print ''; + print ''; + print ''; + print ''; print ''; print ''; print ''; print ''; print ''; - print ''; + print ''; print ''; } print '
'; - print $formaccounting->select_account((GETPOSTISSET("accountingaccount_number") ? GETPOST("accountingaccount_number", "alpha") : $line->numero_compte), 'accountingaccount_number', 1, array (), 1, 1, ''); + print $formaccounting->select_account((GETPOSTISSET("accountingaccount_number") ? GETPOST("accountingaccount_number", "alpha") : $line->numero_compte), 'accountingaccount_number', 1, array(), 1, 1, ''); print ''; // TODO For the moment we keep a free input text instead of a combo. The select_auxaccount has problem because it does not // use setup of keypress to select thirdparty and this hang browser on large database. - if (! empty($conf->global->ACCOUNTANCY_COMBO_FOR_AUX)) + if (!empty($conf->global->ACCOUNTANCY_COMBO_FOR_AUX)) { print $formaccounting->select_auxaccount((GETPOSTISSET("subledger_account") ? GETPOST("subledger_account", "alpha") : $line->subledger_account), 'subledger_account', 1); } @@ -634,30 +634,30 @@ if ($action == 'create') print 'subledger_account).'">'; } print 'label_operation). '">debit)) . '">credit)) . '">label_operation).'">debit)).'">credit)).'">'; - print '' . "\n"; - print ''; + print ''."\n"; + print ''; print '' . $accountingaccount->getNomUrl(0, 1, 1, '', 0) . '' . length_accounta($line->subledger_account) . '' . $line->label_operation. '' . price($line->debit) . '' . price($line->credit) . ''.$accountingaccount->getNomUrl(0, 1, 1, '', 0).''.length_accounta($line->subledger_account).''.$line->label_operation.''.price($line->debit).''.price($line->credit).''; - print 'id . '&piece_num=' . $line->piece_num . '&mode='.$mode.'">'; + print 'id.'&piece_num='.$line->piece_num.'&mode='.$mode.'">'; print img_edit(); print '  '; - $actiontodelete='delete'; - if ($mode == '_tmp' || $action != 'delmouv') $actiontodelete='confirm_delete'; + $actiontodelete = 'delete'; + if ($mode == '_tmp' || $action != 'delmouv') $actiontodelete = 'confirm_delete'; - print ''; + print ''; print img_delete(); print ''; @@ -677,12 +677,12 @@ if ($action == 'create') if ($action == "" || $action == 'add') { print '
'; - print $formaccounting->select_account('', 'accountingaccount_number', 1, array (), 1, 1, ''); + print $formaccounting->select_account('', 'accountingaccount_number', 1, array(), 1, 1, ''); print ''; // TODO For the moment we keep a free input text instead of a combo. The select_auxaccount has problem because it does not // use setup of keypress to select thirdparty and this hang browser on large database. - if (! empty($conf->global->ACCOUNTANCY_COMBO_FOR_AUX)) + if (!empty($conf->global->ACCOUNTANCY_COMBO_FOR_AUX)) { print $formaccounting->select_auxaccount('', 'subledger_account', 1); } @@ -694,19 +694,19 @@ if ($action == 'create') print '
'; - if ($mode=='_tmp' && $action=='') + if ($mode == '_tmp' && $action == '') { print '
'; print '
'; if ($total_debit == $total_credit) { - print ''.$langs->trans("ValidTransaction").''; + print ''.$langs->trans("ValidTransaction").''; } else { @@ -714,7 +714,7 @@ if ($action == 'create') } print '   '; - print ''.$langs->trans("Cancel").''; + print ''.$langs->trans("Cancel").''; print "
"; } diff --git a/htdocs/accountancy/bookkeeping/list.php b/htdocs/accountancy/bookkeeping/list.php index f449a99c8bf..d898be2b208 100644 --- a/htdocs/accountancy/bookkeeping/list.php +++ b/htdocs/accountancy/bookkeeping/list.php @@ -25,14 +25,14 @@ * \brief List operation of book keeping */ require '../../main.inc.php'; -require_once DOL_DOCUMENT_ROOT . '/accountancy/class/accountancyexport.class.php'; -require_once DOL_DOCUMENT_ROOT . '/core/lib/accounting.lib.php'; -require_once DOL_DOCUMENT_ROOT . '/accountancy/class/bookkeeping.class.php'; -require_once DOL_DOCUMENT_ROOT . '/accountancy/class/accountingjournal.class.php'; -require_once DOL_DOCUMENT_ROOT . '/core/class/html.formother.class.php'; -require_once DOL_DOCUMENT_ROOT . '/core/class/html.formaccounting.class.php'; -require_once DOL_DOCUMENT_ROOT . '/core/lib/date.lib.php'; -require_once DOL_DOCUMENT_ROOT . '/core/lib/admin.lib.php'; +require_once DOL_DOCUMENT_ROOT.'/accountancy/class/accountancyexport.class.php'; +require_once DOL_DOCUMENT_ROOT.'/core/lib/accounting.lib.php'; +require_once DOL_DOCUMENT_ROOT.'/accountancy/class/bookkeeping.class.php'; +require_once DOL_DOCUMENT_ROOT.'/accountancy/class/accountingjournal.class.php'; +require_once DOL_DOCUMENT_ROOT.'/core/class/html.formother.class.php'; +require_once DOL_DOCUMENT_ROOT.'/core/class/html.formaccounting.class.php'; +require_once DOL_DOCUMENT_ROOT.'/core/lib/date.lib.php'; +require_once DOL_DOCUMENT_ROOT.'/core/lib/admin.lib.php'; // Load translation files required by the page $langs->loadLangs(array("accountancy")); @@ -88,7 +88,7 @@ $search_ledger_code = GETPOST('search_ledger_code', 'alpha'); $search_lettering_code = GETPOST('search_lettering_code', 'alpha'); // Load variable for pagination -$limit = GETPOST('limit', 'int')?GETPOST('limit', 'int'):(empty($conf->global->ACCOUNTING_LIMIT_LIST_VENTILATION)?$conf->liste_limit:$conf->global->ACCOUNTING_LIMIT_LIST_VENTILATION); +$limit = GETPOST('limit', 'int') ?GETPOST('limit', 'int') : (empty($conf->global->ACCOUNTING_LIMIT_LIST_VENTILATION) ? $conf->liste_limit : $conf->global->ACCOUNTING_LIMIT_LIST_VENTILATION); $sortfield = GETPOST('sortfield', 'alpha'); $sortorder = GETPOST('sortorder', 'alpha'); $page = GETPOST('page', 'int'); @@ -107,12 +107,12 @@ $formaccounting = new FormAccounting($db); $formother = new FormOther($db); $form = new Form($db); -if (! in_array($action, array('export_file', 'delmouv', 'delmouvconfirm')) && ! isset($_POST['begin']) && ! isset($_GET['begin']) && ! isset($_POST['formfilteraction']) && GETPOST('page', 'int') == '' && ! GETPOST('noreset', 'int') && $user->rights->accounting->mouvements->export) +if (!in_array($action, array('export_file', 'delmouv', 'delmouvconfirm')) && !isset($_POST['begin']) && !isset($_GET['begin']) && !isset($_POST['formfilteraction']) && GETPOST('page', 'int') == '' && !GETPOST('noreset', 'int') && $user->rights->accounting->mouvements->export) { - if (empty($search_date_start) && empty($search_date_end) && ! GETPOSTISSET('restore_lastsearch_values')) + if (empty($search_date_start) && empty($search_date_end) && !GETPOSTISSET('restore_lastsearch_values')) { $query = "SELECT date_start, date_end from ".MAIN_DB_PREFIX."accounting_fiscalyear "; - $query.= " where date_start < '".$db->idate(dol_now())."' and date_end > '".$db->idate(dol_now())."' limit 1"; + $query .= " where date_start < '".$db->idate(dol_now())."' and date_end > '".$db->idate(dol_now())."' limit 1"; $res = $db->query($query); if ($res->num_rows > 0) { @@ -120,9 +120,9 @@ if (! in_array($action, array('export_file', 'delmouv', 'delmouvconfirm')) && ! $search_date_start = strtotime($fiscalYear->date_start); $search_date_end = strtotime($fiscalYear->date_end); } else { - $month_start= ($conf->global->SOCIETE_FISCAL_MONTH_START?($conf->global->SOCIETE_FISCAL_MONTH_START):1); + $month_start = ($conf->global->SOCIETE_FISCAL_MONTH_START ? ($conf->global->SOCIETE_FISCAL_MONTH_START) : 1); $year_start = dol_print_date(dol_now(), '%Y'); - if (dol_print_date(dol_now(), '%m') < $month_start) $year_start--; // If current month is lower that starting fiscal month, we start last year + if (dol_print_date(dol_now(), '%m') < $month_start) $year_start--; // If current month is lower that starting fiscal month, we start last year $year_end = $year_start + 1; $month_end = $month_start - 1; if ($month_end < 1) @@ -137,7 +137,7 @@ if (! in_array($action, array('export_file', 'delmouv', 'delmouvconfirm')) && ! } -$arrayfields=array( +$arrayfields = array( 't.piece_num'=>array('label'=>$langs->trans("TransactionNumShort"), 'checked'=>1), 't.doc_date'=>array('label'=>$langs->trans("Docdate"), 'checked'=>1), 't.doc_ref'=>array('label'=>$langs->trans("Piece"), 'checked'=>1), @@ -155,7 +155,7 @@ $arrayfields=array( if (empty($conf->global->ACCOUNTING_ENABLE_LETTERING)) unset($arrayfields['t.lettering_code']); -$listofformat=AccountancyExport::getType(); +$listofformat = AccountancyExport::getType(); $formatexportset = $conf->global->ACCOUNTING_EXPORT_MODELCSV; if (empty($listofformat[$formatexportset])) $formatexportset = 1; @@ -166,8 +166,8 @@ $error = 0; * 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 @@ -318,7 +318,7 @@ if (empty($reshook)) if ($action == 'delbookkeeping' && $user->rights->accounting->mouvements->supprimer) { $import_key = GETPOST('importkey', 'alpha'); - if (! empty($import_key)) { + if (!empty($import_key)) { $result = $object->deleteByImportkey($import_key); if ($result < 0) { setEventMessages($object->error, $object->errors, 'errors'); @@ -331,15 +331,15 @@ if ($action == 'delbookkeeping' && $user->rights->accounting->mouvements->suppri } if ($action == 'delbookkeepingyearconfirm' && $user->rights->accounting->mouvements->supprimer_tous) { $delyear = GETPOST('delyear', 'int'); - if ($delyear==-1) { - $delyear=0; + if ($delyear == -1) { + $delyear = 0; } $deljournal = GETPOST('deljournal', 'alpha'); - if ($deljournal==-1) { - $deljournal=0; + if ($deljournal == -1) { + $deljournal = 0; } - if (! empty($delyear) || ! empty($deljournal)) + if (!empty($delyear) || !empty($deljournal)) { $result = $object->deleteByYearAndJournal($delyear, $deljournal); if ($result < 0) { @@ -351,7 +351,7 @@ if ($action == 'delbookkeepingyearconfirm' && $user->rights->accounting->mouveme } // Make a redirect to avoid to launch the delete later after a back button - header("Location: list.php".($param?'?'.$param:'')); + header("Location: list.php".($param ? '?'.$param : '')); exit; } else @@ -362,7 +362,7 @@ if ($action == 'delbookkeepingyearconfirm' && $user->rights->accounting->mouveme if ($action == 'delmouvconfirm' && $user->rights->accounting->mouvements->supprimer) { $mvt_num = GETPOST('mvt_num', 'int'); - if (! empty($mvt_num)) { + if (!empty($mvt_num)) { $result = $object->deleteMvtNum($mvt_num); if ($result < 0) { setEventMessages($object->error, $object->errors, 'errors'); @@ -372,15 +372,15 @@ if ($action == 'delmouvconfirm' && $user->rights->accounting->mouvements->suppri setEventMessages($langs->trans("RecordDeleted"), null, 'mesgs'); } - header("Location: list.php?noreset=1".($param?'&'.$param:'')); + header("Location: list.php?noreset=1".($param ? '&'.$param : '')); exit; } } if ($action == 'setreexport') { $setreexport = GETPOST('value', 'int'); - if (! dolibarr_set_const($db, "ACCOUNTING_REEXPORT", $setreexport, 'yesno', 0, '', $conf->entity)) $error++; + if (!dolibarr_set_const($db, "ACCOUNTING_REEXPORT", $setreexport, 'yesno', 0, '', $conf->entity)) $error++; - if (! $error) { + if (!$error) { if ($conf->global->ACCOUNTING_REEXPORT == 1) { setEventMessages($langs->trans("ExportOfPiecesAlreadyExportedIsEnable"), null, 'mesgs'); } else { @@ -421,27 +421,27 @@ $sql .= " t.piece_num,"; $sql .= " t.date_creation,"; $sql .= " t.tms as date_modification,"; $sql .= " t.date_export"; -$sql .= ' FROM ' . MAIN_DB_PREFIX . $object->table_element . ' as t'; +$sql .= ' FROM '.MAIN_DB_PREFIX.$object->table_element.' as t'; // Manage filter -$sqlwhere = array (); +$sqlwhere = array(); if (count($filter) > 0) { foreach ($filter as $key => $value) { if ($key == 't.doc_date') { - $sqlwhere[] = $key . '=\'' . $db->idate($value) . '\''; + $sqlwhere[] = $key.'=\''.$db->idate($value).'\''; } elseif ($key == 't.doc_date>=' || $key == 't.doc_date<=') { - $sqlwhere[] = $key . '\'' . $db->idate($value) . '\''; + $sqlwhere[] = $key.'\''.$db->idate($value).'\''; } elseif ($key == 't.numero_compte>=' || $key == 't.numero_compte<=' || $key == 't.subledger_account>=' || $key == 't.subledger_account<=') { - $sqlwhere[] = $key . '\'' . $db->escape($value) . '\''; + $sqlwhere[] = $key.'\''.$db->escape($value).'\''; } elseif ($key == 't.fk_doc' || $key == 't.fk_docdet' || $key == 't.piece_num') { - $sqlwhere[] = $key . '=' . $value; + $sqlwhere[] = $key.'='.$value; } elseif ($key == 't.subledger_account' || $key == 't.numero_compte') { - $sqlwhere[] = $key . ' LIKE \'' . $db->escape($value) . '%\''; + $sqlwhere[] = $key.' LIKE \''.$db->escape($value).'%\''; } elseif ($key == 't.date_creation>=' || $key == 't.date_creation<=') { - $sqlwhere[] = $key . '\'' . $db->idate($value) . '\''; + $sqlwhere[] = $key.'\''.$db->idate($value).'\''; } elseif ($key == 't.tms>=' || $key == 't.tms<=') { - $sqlwhere[] = $key . '\'' . $db->idate($value) . '\''; + $sqlwhere[] = $key.'\''.$db->idate($value).'\''; } elseif ($key == 't.date_export>=' || $key == 't.date_export<=') { - $sqlwhere[] = $key . '\'' . $db->idate($value) . '\''; + $sqlwhere[] = $key.'\''.$db->idate($value).'\''; } elseif ($key == 't.credit' || $key == 't.debit') { $sqlwhere[] = natural_search($key, $value, 1, 1); } else { @@ -449,14 +449,14 @@ if (count($filter) > 0) { } } } -$sql.= ' WHERE t.entity IN (' . getEntity('accountancy') . ')'; +$sql .= ' WHERE t.entity IN ('.getEntity('accountancy').')'; if ($conf->global->ACCOUNTING_REEXPORT == 0) { $sql .= " AND t.date_export IS NULL"; } if (count($sqlwhere) > 0) { - $sql .= ' AND ' . implode(' AND ', $sqlwhere); + $sql .= ' AND '.implode(' AND ', $sqlwhere); } -if (! empty($sortfield)) { +if (!empty($sortfield)) { $sql .= $db->order($sortfield, $sortorder); } //print $sql; @@ -478,14 +478,14 @@ if ($action == 'export_file' && $user->rights->accounting->mouvements->export) { $accountancyexport = new AccountancyExport($db); $accountancyexport->export($object->lines, $formatexportset); - if (! empty($accountancyexport->errors)) + if (!empty($accountancyexport->errors)) { setEventMessages('', $accountancyexport->errors, 'errors'); } else { // Specify as export : update field date_export - $error=0; + $error = 0; $db->begin(); if (is_array($object->lines)) @@ -494,13 +494,13 @@ if ($action == 'export_file' && $user->rights->accounting->mouvements->export) { { $now = dol_now(); - $sql = " UPDATE " . MAIN_DB_PREFIX . "accounting_bookkeeping"; - $sql .= " SET date_export = '" . $db->idate($now) . "'"; - $sql .= " WHERE rowid = " . $movement->id; + $sql = " UPDATE ".MAIN_DB_PREFIX."accounting_bookkeeping"; + $sql .= " SET date_export = '".$db->idate($now)."'"; + $sql .= " WHERE rowid = ".$movement->id; - dol_syslog("/accountancy/bookeeping/list.php Function export_file Specify movements as exported sql=" . $sql, LOG_DEBUG); + dol_syslog("/accountancy/bookeeping/list.php Function export_file Specify movements as exported sql=".$sql, LOG_DEBUG); $result = $db->query($sql); - if (! $result) + if (!$result) { $error++; break; @@ -508,7 +508,7 @@ if ($action == 'export_file' && $user->rights->accounting->mouvements->export) { } } - if (! $error) + if (!$error) { $db->commit(); // setEventMessages($langs->trans("AllExportedMovementsWereRecordedAsExported"), null, 'mesgs'); @@ -550,10 +550,10 @@ if (is_numeric($nbtotalofrecords) && $limit > $nbtotalofrecords) } else { - $sql.= $db->plimit($limit+1, $offset); + $sql .= $db->plimit($limit + 1, $offset); - $resql=$db->query($sql); - if (! $resql) + $resql = $db->query($sql); + if (!$resql) { dol_print_error($db); exit; @@ -574,7 +574,7 @@ if ($action == 'delmouv') { print $formconfirm; } if ($action == 'delbookkeepingyear') { - $form_question = array (); + $form_question = array(); $delyear = GETPOST('delyear'); $deljournal = GETPOST('deljournal'); @@ -584,16 +584,16 @@ if ($action == 'delbookkeepingyear') { $year_array = $formaccounting->selectyear_accountancy_bookkepping($delyear, 'delyear', 0, 'array'); $journal_array = $formaccounting->select_journal($deljournal, 'deljournal', '', 1, 1, 1, '', 0, 1); - $form_question['delyear'] = array ( + $form_question['delyear'] = array( 'name' => 'delyear', 'type' => 'select', 'label' => $langs->trans('DelYear'), 'values' => $year_array, 'default' => $delyear ); - $form_question['deljournal'] = array ( + $form_question['deljournal'] = array( 'name' => 'deljournal', - 'type' => 'other', // We don't use select here, the journal_array is already a select html component + 'type' => 'other', // We don't use select here, the journal_array is already a select html component 'label' => $langs->trans('DelJournal'), 'value' => $journal_array, 'default' => $deljournal @@ -604,10 +604,10 @@ if ($action == 'delbookkeepingyear') { } //$param=''; param started before -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 ''; +print ''; print ''; print ''; if ($optioncss != '') print ''; @@ -620,27 +620,27 @@ if (count($filter)) $buttonLabel = $langs->trans("ExportFilteredList"); else $buttonLabel = $langs->trans("ExportList"); // Button re-export -if (! empty($conf->global->ACCOUNTING_REEXPORT)) { - $newcardbutton =''.img_picto($langs->trans("Activated"), 'switch_on').' '; +if (!empty($conf->global->ACCOUNTING_REEXPORT)) { + $newcardbutton = ''.img_picto($langs->trans("Activated"), 'switch_on').' '; } else { - $newcardbutton =''.img_picto($langs->trans("Disabled"), 'switch_off').' '; + $newcardbutton = ''.img_picto($langs->trans("Disabled"), 'switch_off').' '; } -$newcardbutton.= ''.$langs->trans("IncludeDocsAlreadyExported").''; +$newcardbutton .= ''.$langs->trans("IncludeDocsAlreadyExported").''; -$newcardbutton.= dolGetButtonTitle($buttonLabel, $langs->trans("ExportFilteredList").' ('.$listofformat[$formatexportset].')', 'fa fa-file-export paddingleft', $_SERVER["PHP_SELF"].'?action=export_file'.($param?'&'.$param:''), $user->rights->accounting->mouvements->export); +$newcardbutton .= dolGetButtonTitle($buttonLabel, $langs->trans("ExportFilteredList").' ('.$listofformat[$formatexportset].')', 'fa fa-file-export paddingleft', $_SERVER["PHP_SELF"].'?action=export_file'.($param ? '&'.$param : ''), $user->rights->accounting->mouvements->export); -$newcardbutton.= dolGetButtonTitle($langs->trans('GroupByAccountAccounting'), '', 'fa fa-stream paddingleft', DOL_URL_ROOT.'/accountancy/bookkeeping/listbyaccount.php?'.$param); +$newcardbutton .= dolGetButtonTitle($langs->trans('GroupByAccountAccounting'), '', 'fa fa-stream paddingleft', DOL_URL_ROOT.'/accountancy/bookkeeping/listbyaccount.php?'.$param); -$newcardbutton.= dolGetButtonTitle($langs->trans('NewAccountingMvt'), '', 'fa fa-plus-circle paddingleft', './card.php?action=create', '', $user->rights->accounting->mouvements->creer); +$newcardbutton .= dolGetButtonTitle($langs->trans('NewAccountingMvt'), '', 'fa fa-plus-circle paddingleft', './card.php?action=create', '', $user->rights->accounting->mouvements->creer); print_barre_liste($title_page, $page, $_SERVER["PHP_SELF"], $param, $sortfield, $sortorder, '', $num, $nbtotalofrecords, 'title_accountancy', 0, $newcardbutton, '', $limit); -$varpage=empty($contextpage)?$_SERVER["PHP_SELF"]:$contextpage; -$selectedfields=$form->multiSelectArrayWithCheckbox('selectedfields', $arrayfields, $varpage); // This also change content of $arrayfields -if ($massactionbutton) $selectedfields.=$form->showCheckAddButtons('checkforselect', 1); +$varpage = empty($contextpage) ? $_SERVER["PHP_SELF"] : $contextpage; +$selectedfields = $form->multiSelectArrayWithCheckbox('selectedfields', $arrayfields, $varpage); // This also change content of $arrayfields +if ($massactionbutton) $selectedfields .= $form->showCheckAddButtons('checkforselect', 1); -$parameters=array(); -$reshook=$hookmanager->executeHooks('printFieldPreListTitle', $parameters); // Note that $action and $object may have been modified by hook +$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; @@ -650,52 +650,52 @@ print ''; // Filters lines print ''; // Movement number -if (! empty($arrayfields['t.piece_num']['checked'])) +if (!empty($arrayfields['t.piece_num']['checked'])) { - print ''; + print ''; } // Date document -if (! empty($arrayfields['t.doc_date']['checked'])) +if (!empty($arrayfields['t.doc_date']['checked'])) { print ''; } // Ref document -if (! empty($arrayfields['t.doc_ref']['checked'])) +if (!empty($arrayfields['t.doc_ref']['checked'])) { - print ''; + print ''; } // Accountancy account -if (! empty($arrayfields['t.numero_compte']['checked'])) +if (!empty($arrayfields['t.numero_compte']['checked'])) { print ''; } // Subledger account -if (! empty($arrayfields['t.subledger_account']['checked'])) +if (!empty($arrayfields['t.subledger_account']['checked'])) { print ''; } // Label operation -if (! empty($arrayfields['t.label_operation']['checked'])) +if (!empty($arrayfields['t.label_operation']['checked'])) { print ''; } // Debit -if (! empty($arrayfields['t.debit']['checked'])) +if (!empty($arrayfields['t.debit']['checked'])) { print ''; } // Credit -if (! empty($arrayfields['t.credit']['checked'])) +if (!empty($arrayfields['t.credit']['checked'])) { print ''; } // Lettering code -if (! empty($arrayfields['t.lettering_code']['checked'])) +if (!empty($arrayfields['t.lettering_code']['checked'])) { print ''; } // Code journal -if (! empty($arrayfields['t.code_journal']['checked'])) +if (!empty($arrayfields['t.code_journal']['checked'])) { - print ''; + print ''; } // Fields from hook -$parameters=array('arrayfields'=>$arrayfields); -$reshook=$hookmanager->executeHooks('printFieldListOption', $parameters); // Note that $action and $object may have been modified by hook +$parameters = array('arrayfields'=>$arrayfields); +$reshook = $hookmanager->executeHooks('printFieldListOption', $parameters); // Note that $action and $object may have been modified by hook print $hookmanager->resPrint; // Date creation -if (! empty($arrayfields['t.date_creation']['checked'])) +if (!empty($arrayfields['t.date_creation']['checked'])) { print ''; } // Date modification -if (! empty($arrayfields['t.tms']['checked'])) +if (!empty($arrayfields['t.tms']['checked'])) { print ''; } // Date export -if (! empty($arrayfields['t.date_export']['checked'])) +if (!empty($arrayfields['t.date_export']['checked'])) { print ''; } // Action column print ''; print "\n"; print ''; -if (! empty($arrayfields['t.piece_num']['checked'])) print_liste_field_titre($arrayfields['t.piece_num']['label'], $_SERVER['PHP_SELF'], "t.piece_num", "", $param, "", $sortfield, $sortorder); -if (! empty($arrayfields['t.doc_date']['checked'])) print_liste_field_titre($arrayfields['t.doc_date']['label'], $_SERVER['PHP_SELF'], "t.doc_date", "", $param, '', $sortfield, $sortorder, 'center '); -if (! empty($arrayfields['t.doc_ref']['checked'])) print_liste_field_titre($arrayfields['t.doc_ref']['label'], $_SERVER['PHP_SELF'], "t.doc_ref", "", $param, "", $sortfield, $sortorder); -if (! empty($arrayfields['t.numero_compte']['checked'])) print_liste_field_titre($arrayfields['t.numero_compte']['label'], $_SERVER['PHP_SELF'], "t.numero_compte", "", $param, "", $sortfield, $sortorder); -if (! empty($arrayfields['t.subledger_account']['checked'])) print_liste_field_titre($arrayfields['t.subledger_account']['label'], $_SERVER['PHP_SELF'], "t.subledger_account", "", $param, "", $sortfield, $sortorder); -if (! empty($arrayfields['t.label_operation']['checked'])) print_liste_field_titre($arrayfields['t.label_operation']['label'], $_SERVER['PHP_SELF'], "t.label_operation", "", $param, "", $sortfield, $sortorder); -if (! empty($arrayfields['t.debit']['checked'])) print_liste_field_titre($arrayfields['t.debit']['label'], $_SERVER['PHP_SELF'], "t.debit", "", $param, '', $sortfield, $sortorder, 'right '); -if (! empty($arrayfields['t.credit']['checked'])) print_liste_field_titre($arrayfields['t.credit']['label'], $_SERVER['PHP_SELF'], "t.credit", "", $param, '', $sortfield, $sortorder, 'right '); -if (! empty($arrayfields['t.lettering_code']['checked'])) print_liste_field_titre($arrayfields['t.lettering_code']['label'], $_SERVER['PHP_SELF'], "t.lettering_code", "", $param, '', $sortfield, $sortorder, 'center '); -if (! empty($arrayfields['t.code_journal']['checked'])) print_liste_field_titre($arrayfields['t.code_journal']['label'], $_SERVER['PHP_SELF'], "t.code_journal", "", $param, '', $sortfield, $sortorder, 'center '); +if (!empty($arrayfields['t.piece_num']['checked'])) print_liste_field_titre($arrayfields['t.piece_num']['label'], $_SERVER['PHP_SELF'], "t.piece_num", "", $param, "", $sortfield, $sortorder); +if (!empty($arrayfields['t.doc_date']['checked'])) print_liste_field_titre($arrayfields['t.doc_date']['label'], $_SERVER['PHP_SELF'], "t.doc_date", "", $param, '', $sortfield, $sortorder, 'center '); +if (!empty($arrayfields['t.doc_ref']['checked'])) print_liste_field_titre($arrayfields['t.doc_ref']['label'], $_SERVER['PHP_SELF'], "t.doc_ref", "", $param, "", $sortfield, $sortorder); +if (!empty($arrayfields['t.numero_compte']['checked'])) print_liste_field_titre($arrayfields['t.numero_compte']['label'], $_SERVER['PHP_SELF'], "t.numero_compte", "", $param, "", $sortfield, $sortorder); +if (!empty($arrayfields['t.subledger_account']['checked'])) print_liste_field_titre($arrayfields['t.subledger_account']['label'], $_SERVER['PHP_SELF'], "t.subledger_account", "", $param, "", $sortfield, $sortorder); +if (!empty($arrayfields['t.label_operation']['checked'])) print_liste_field_titre($arrayfields['t.label_operation']['label'], $_SERVER['PHP_SELF'], "t.label_operation", "", $param, "", $sortfield, $sortorder); +if (!empty($arrayfields['t.debit']['checked'])) print_liste_field_titre($arrayfields['t.debit']['label'], $_SERVER['PHP_SELF'], "t.debit", "", $param, '', $sortfield, $sortorder, 'right '); +if (!empty($arrayfields['t.credit']['checked'])) print_liste_field_titre($arrayfields['t.credit']['label'], $_SERVER['PHP_SELF'], "t.credit", "", $param, '', $sortfield, $sortorder, 'right '); +if (!empty($arrayfields['t.lettering_code']['checked'])) print_liste_field_titre($arrayfields['t.lettering_code']['label'], $_SERVER['PHP_SELF'], "t.lettering_code", "", $param, '', $sortfield, $sortorder, 'center '); +if (!empty($arrayfields['t.code_journal']['checked'])) print_liste_field_titre($arrayfields['t.code_journal']['label'], $_SERVER['PHP_SELF'], "t.code_journal", "", $param, '', $sortfield, $sortorder, 'center '); // Hook fields -$parameters=array('arrayfields'=>$arrayfields,'param'=>$param,'sortfield'=>$sortfield,'sortorder'=>$sortorder); -$reshook=$hookmanager->executeHooks('printFieldListTitle', $parameters); // Note that $action and $object may have been modified by hook +$parameters = array('arrayfields'=>$arrayfields, 'param'=>$param, 'sortfield'=>$sortfield, 'sortorder'=>$sortorder); +$reshook = $hookmanager->executeHooks('printFieldListTitle', $parameters); // Note that $action and $object may have been modified by hook print $hookmanager->resPrint; -if (! empty($arrayfields['t.date_creation']['checked'])) print_liste_field_titre($arrayfields['t.date_creation']['label'], $_SERVER['PHP_SELF'], "t.date_creation", "", $param, '', $sortfield, $sortorder, 'center '); -if (! empty($arrayfields['t.tms']['checked'])) print_liste_field_titre($arrayfields['t.tms']['label'], $_SERVER['PHP_SELF'], "t.tms", "", $param, '', $sortfield, $sortorder, 'center '); -if (! empty($arrayfields['t.date_export']['checked'])) print_liste_field_titre($arrayfields['t.date_export']['label'], $_SERVER['PHP_SELF'], "t.date_export", "", $param, '', $sortfield, $sortorder, 'center '); +if (!empty($arrayfields['t.date_creation']['checked'])) print_liste_field_titre($arrayfields['t.date_creation']['label'], $_SERVER['PHP_SELF'], "t.date_creation", "", $param, '', $sortfield, $sortorder, 'center '); +if (!empty($arrayfields['t.tms']['checked'])) print_liste_field_titre($arrayfields['t.tms']['label'], $_SERVER['PHP_SELF'], "t.tms", "", $param, '', $sortfield, $sortorder, 'center '); +if (!empty($arrayfields['t.date_export']['checked'])) print_liste_field_titre($arrayfields['t.date_export']['label'], $_SERVER['PHP_SELF'], "t.date_export", "", $param, '', $sortfield, $sortorder, 'center '); print_liste_field_titre($selectedfields, $_SERVER["PHP_SELF"], "", '', '', '', $sortfield, $sortorder, 'center maxwidthsearch '); print "\n"; @@ -833,12 +833,12 @@ $line = new BookKeepingLine(); // Loop on record // -------------------------------------------------------------------- -$i=0; -$totalarray=array(); +$i = 0; +$totalarray = array(); while ($i < min($num, $limit)) { $obj = $db->fetch_object($resql); - if (empty($obj)) break; // Should not happen + if (empty($obj)) break; // Should not happen $line->id = $obj->rowid; $line->doc_date = $db->jdate($obj->doc_date); @@ -1006,8 +1006,8 @@ print ''; // TODO Replace this with mass delete action if ($user->rights->accounting->mouvements->supprimer_tous) { - print '
' . "\n"; - print '' . $langs->trans("DeleteMvt") . ''; + print '
'."\n"; + print ''.$langs->trans("DeleteMvt").''; print '
'; } diff --git a/htdocs/accountancy/bookkeeping/listbyaccount.php b/htdocs/accountancy/bookkeeping/listbyaccount.php index 4f275e3e2b0..5ceb9eb66a8 100644 --- a/htdocs/accountancy/bookkeeping/listbyaccount.php +++ b/htdocs/accountancy/bookkeeping/listbyaccount.php @@ -27,12 +27,12 @@ require '../../main.inc.php'; -require_once DOL_DOCUMENT_ROOT . '/core/lib/accounting.lib.php'; -require_once DOL_DOCUMENT_ROOT . '/accountancy/class/bookkeeping.class.php'; -require_once DOL_DOCUMENT_ROOT . '/accountancy/class/accountingjournal.class.php'; -require_once DOL_DOCUMENT_ROOT . '/core/class/html.formaccounting.class.php'; -require_once DOL_DOCUMENT_ROOT . '/core/class/html.formother.class.php'; -require_once DOL_DOCUMENT_ROOT . '/core/lib/date.lib.php'; +require_once DOL_DOCUMENT_ROOT.'/core/lib/accounting.lib.php'; +require_once DOL_DOCUMENT_ROOT.'/accountancy/class/bookkeeping.class.php'; +require_once DOL_DOCUMENT_ROOT.'/accountancy/class/accountingjournal.class.php'; +require_once DOL_DOCUMENT_ROOT.'/core/class/html.formaccounting.class.php'; +require_once DOL_DOCUMENT_ROOT.'/core/class/html.formother.class.php'; +require_once DOL_DOCUMENT_ROOT.'/core/lib/date.lib.php'; // Load translation files required by the page $langs->loadLangs(array("accountancy")); @@ -59,7 +59,7 @@ $search_debit = GETPOST('search_debit', 'alpha'); $search_credit = GETPOST('search_credit', 'alpha'); // Load variable for pagination -$limit = GETPOST('limit', 'int')?GETPOST('limit', 'int'):(empty($conf->global->ACCOUNTING_LIMIT_LIST_VENTILATION)?$conf->liste_limit:$conf->global->ACCOUNTING_LIMIT_LIST_VENTILATION); +$limit = GETPOST('limit', 'int') ?GETPOST('limit', 'int') : (empty($conf->global->ACCOUNTING_LIMIT_LIST_VENTILATION) ? $conf->liste_limit : $conf->global->ACCOUNTING_LIMIT_LIST_VENTILATION); $sortfield = GETPOST('sortfield', 'alpha'); $sortorder = GETPOST('sortorder', 'alpha'); $page = GETPOST('page', 'int'); @@ -81,9 +81,9 @@ if (empty($search_date_start) && empty($search_date_end) && GETPOSTISSET('search $search_date_start = strtotime($fiscalYear->date_start); $search_date_end = strtotime($fiscalYear->date_end); } else { - $month_start= ($conf->global->SOCIETE_FISCAL_MONTH_START?($conf->global->SOCIETE_FISCAL_MONTH_START):1); + $month_start = ($conf->global->SOCIETE_FISCAL_MONTH_START ? ($conf->global->SOCIETE_FISCAL_MONTH_START) : 1); $year_start = dol_print_date(dol_now(), '%Y'); - if (dol_print_date(dol_now(), '%m') < $month_start) $year_start--; // If current month is lower that starting fiscal month, we start last year + if (dol_print_date(dol_now(), '%m') < $month_start) $year_start--; // If current month is lower that starting fiscal month, we start last year $year_end = $year_start + 1; $month_end = $month_start - 1; if ($month_end < 1) @@ -112,76 +112,76 @@ if (GETPOST('button_removefilter_x', 'alpha') || GETPOST('button_removefilter.x' $search_label_operation = ''; $search_direction = ''; $search_ledger_code = ''; - $search_date_start=''; - $search_date_end=''; - $search_date_startyear=''; - $search_date_startmonth=''; - $search_date_startday=''; - $search_date_endyear=''; - $search_date_endmonth=''; - $search_date_endday=''; + $search_date_start = ''; + $search_date_end = ''; + $search_date_startyear = ''; + $search_date_startmonth = ''; + $search_date_startday = ''; + $search_date_endyear = ''; + $search_date_endmonth = ''; + $search_date_endday = ''; $search_debit = ''; $search_credit = ''; } // Must be after the remove filter action, before the export. $param = ''; -$filter = array (); +$filter = array(); -if (! empty($search_date_start)) { +if (!empty($search_date_start)) { $filter['t.doc_date>='] = $search_date_start; - $param .= '&search_date_startmonth=' . GETPOST('search_date_startmonth', 'int') . '&search_date_startday=' . GETPOST('search_date_startday', 'int') . '&search_date_startyear=' . GETPOST('search_date_startyear', 'int'); + $param .= '&search_date_startmonth='.GETPOST('search_date_startmonth', 'int').'&search_date_startday='.GETPOST('search_date_startday', 'int').'&search_date_startyear='.GETPOST('search_date_startyear', 'int'); } -if (! empty($search_date_end)) { +if (!empty($search_date_end)) { $filter['t.doc_date<='] = $search_date_end; - $param .= '&search_date_endmonth=' . GETPOST('search_date_endmonth', 'int') . '&search_date_endday=' . GETPOST('search_date_endday', 'int') . '&search_date_endyear=' . GETPOST('search_date_endyear', 'int'); + $param .= '&search_date_endmonth='.GETPOST('search_date_endmonth', 'int').'&search_date_endday='.GETPOST('search_date_endday', 'int').'&search_date_endyear='.GETPOST('search_date_endyear', 'int'); } -if (! empty($search_doc_date)) { +if (!empty($search_doc_date)) { $filter['t.doc_date'] = $search_doc_date; - $param .= '&doc_datemonth=' . GETPOST('doc_datemonth', 'int') . '&doc_dateday=' . GETPOST('doc_dateday', 'int') . '&doc_dateyear=' . GETPOST('doc_dateyear', 'int'); + $param .= '&doc_datemonth='.GETPOST('doc_datemonth', 'int').'&doc_dateday='.GETPOST('doc_dateday', 'int').'&doc_dateyear='.GETPOST('doc_dateyear', 'int'); } -if (! empty($search_accountancy_code_start)) { +if (!empty($search_accountancy_code_start)) { $filter['t.numero_compte>='] = $search_accountancy_code_start; - $param .= '&search_accountancy_code_start=' . urlencode($search_accountancy_code_start); + $param .= '&search_accountancy_code_start='.urlencode($search_accountancy_code_start); } -if (! empty($search_accountancy_code_end)) { +if (!empty($search_accountancy_code_end)) { $filter['t.numero_compte<='] = $search_accountancy_code_end; - $param .= '&search_accountancy_code_end=' . urlencode($search_accountancy_code_end); + $param .= '&search_accountancy_code_end='.urlencode($search_accountancy_code_end); } -if (! empty($search_label_account)) { +if (!empty($search_label_account)) { $filter['t.label_compte'] = $search_label_account; - $param .= '&search_label_compte=' . urlencode($search_label_account); + $param .= '&search_label_compte='.urlencode($search_label_account); } -if (! empty($search_doc_ref)) { +if (!empty($search_doc_ref)) { $filter['t.doc_ref'] = $search_doc_ref; - $param .= '&search_doc_ref=' . urlencode($search_doc_ref); + $param .= '&search_doc_ref='.urlencode($search_doc_ref); } -if (! empty($search_label_operation)) { +if (!empty($search_label_operation)) { $filter['t.label_operation'] = $search_label_operation; - $param .= '&search_label_operation=' . urlencode($search_label_operation); + $param .= '&search_label_operation='.urlencode($search_label_operation); } -if (! empty($search_direction)) { +if (!empty($search_direction)) { $filter['t.sens'] = $search_direction; - $param .= '&search_direction=' . urlencode($search_direction); + $param .= '&search_direction='.urlencode($search_direction); } -if (! empty($search_ledger_code)) { +if (!empty($search_ledger_code)) { $filter['t.code_journal'] = $search_ledger_code; - $param .= '&search_ledger_code=' . urlencode($search_ledger_code); + $param .= '&search_ledger_code='.urlencode($search_ledger_code); } -if (! empty($search_debit)) { +if (!empty($search_debit)) { $filter['t.debit'] = $search_debit; - $param .= '&search_debit=' . urlencode($search_debit); + $param .= '&search_debit='.urlencode($search_debit); } -if (! empty($search_credit)) { +if (!empty($search_credit)) { $filter['t.credit'] = $search_credit; - $param .= '&search_credit=' . urlencode($search_credit); + $param .= '&search_credit='.urlencode($search_credit); } if ($action == 'delmouvconfirm') { $mvt_num = GETPOST('mvt_num', 'int'); - if (! empty($mvt_num)) { + if (!empty($mvt_num)) { $result = $object->deleteMvtNum($mvt_num); if ($result < 0) { setEventMessages($object->error, $object->errors, 'errors'); @@ -200,7 +200,7 @@ $formaccounting = new FormAccounting($db); $formother = new FormOther($db); $form = new Form($db); -$title_page = $langs->trans("Bookkeeping") . ' ' . strtolower($langs->trans("By")) . ' ' . strtolower($langs->trans("AccountAccounting")); +$title_page = $langs->trans("Bookkeeping").' '.strtolower($langs->trans("By")).' '.strtolower($langs->trans("AccountAccounting")); llxHeader('', $title_page); @@ -236,7 +236,7 @@ if ($action == 'delbookkeepingyear') { } $year_array = $formaccounting->selectyear_accountancy_bookkepping($delyear, 'delyear', 0, 'array'); - $form_question['delyear'] = array ( + $form_question['delyear'] = array( 'name' => 'delyear', 'type' => 'select', 'label' => $langs->trans('DelYear'), @@ -278,28 +278,28 @@ print '
'; print ''; print ''; print ''; -print ''; -print ''; +print ''; +print ''; print ''; print ''; -print ''; +print ''; print ''; print ''; @@ -321,9 +321,9 @@ $total_debit = 0; $total_credit = 0; $sous_total_debit = 0; $sous_total_credit = 0; -$displayed_account_number = null; // Start with undefined to be able to distinguish with empty +$displayed_account_number = null; // Start with undefined to be able to distinguish with empty -$i=0; +$i = 0; while ($i < min($num, $limit)) { $line = $object->lines[$i]; @@ -361,8 +361,8 @@ while ($i < min($num, $limit)) print ''; print ''; - print ''; - print ''; + print ''; + print ''; // TODO Add a link according to doc_type and fk_doc print '
'; print '
'; - print $langs->trans('From') . ' '; - print $form->selectDate($search_date_start?$search_date_start:-1, 'search_date_start', 0, 0, 1); + print $langs->trans('From').' '; + print $form->selectDate($search_date_start ? $search_date_start : -1, 'search_date_start', 0, 0, 1); print '
'; print '
'; - print $langs->trans('to') . ' '; - print $form->selectDate($search_date_end?$search_date_end:-1, 'search_date_end', 0, 0, 1); + print $langs->trans('to').' '; + print $form->selectDate($search_date_end ? $search_date_end : -1, 'search_date_end', 0, 0, 1); print '
'; print '
'; print '
'; print $langs->trans('From').' '; - print $formaccounting->select_account($search_accountancy_code_start, 'search_accountancy_code_start', 1, array (), 1, 1, 'maxwidth200'); + print $formaccounting->select_account($search_accountancy_code_start, 'search_accountancy_code_start', 1, array(), 1, 1, 'maxwidth200'); print '
'; print '
'; print $langs->trans('to').' '; - print $formaccounting->select_account($search_accountancy_code_end, 'search_accountancy_code_end', 1, array (), 1, 1, 'maxwidth200'); + print $formaccounting->select_account($search_accountancy_code_end, 'search_accountancy_code_end', 1, array(), 1, 1, 'maxwidth200'); print '
'; print '
'; print '
'; print $langs->trans('From').' '; // TODO For the moment we keep a free input text instead of a combo. The select_auxaccount has problem because it does not // use setup of keypress to select thirdparty and this hang browser on large database. - if (! empty($conf->global->ACCOUNTANCY_COMBO_FOR_AUX)) + if (!empty($conf->global->ACCOUNTANCY_COMBO_FOR_AUX)) { print $formaccounting->select_auxaccount($search_accountancy_aux_code_start, 'search_accountancy_aux_code_start', 1); } @@ -708,7 +708,7 @@ if (! empty($arrayfields['t.subledger_account']['checked'])) print $langs->trans('to').' '; // TODO For the moment we keep a free input text instead of a combo. The select_auxaccount has problem because it does not // use setup of keypress to select thirdparty and this hang browser on large database. - if (! empty($conf->global->ACCOUNTANCY_COMBO_FOR_AUX)) + if (!empty($conf->global->ACCOUNTANCY_COMBO_FOR_AUX)) { print $formaccounting->select_auxaccount($search_accountancy_aux_code_end, 'search_accountancy_aux_code_end', 1); } @@ -720,111 +720,111 @@ if (! empty($arrayfields['t.subledger_account']['checked'])) print '
'; - print ''; + print ''; print ''; print ''; print ''; print ''; print ''; - print ''; + print ''; print ''; print '
'; - print $langs->trans('From') . ' '; + print $langs->trans('From').' '; print $form->selectDate($search_date_creation_start, 'date_creation_start', 0, 0, 1); print '
'; print '
'; - print $langs->trans('to') . ' '; + print $langs->trans('to').' '; print $form->selectDate($search_date_creation_end, 'date_creation_end', 0, 0, 1); print '
'; print '
'; print '
'; - print $langs->trans('From') . ' '; + print $langs->trans('From').' '; print $form->selectDate($search_date_modification_start, 'date_modification_start', 0, 0, 1); print '
'; print '
'; - print $langs->trans('to') . ' '; + print $langs->trans('to').' '; print $form->selectDate($search_date_modification_end, 'date_modification_end', 0, 0, 1); print '
'; print '
'; print '
'; - print $langs->trans('From') . ' '; + print $langs->trans('From').' '; print $form->selectDate($search_date_export_start, 'date_export_start', 0, 0, 1); print '
'; print '
'; - print $langs->trans('to') . ' '; + print $langs->trans('to').' '; print $form->selectDate($search_date_export_end, 'date_export_end', 0, 0, 1); print '
'; print '
'; -$searchpicto=$form->showFilterButtons(); +$searchpicto = $form->showFilterButtons(); print $searchpicto; print '
'; print '
'; print $langs->trans('From').' '; -print $formaccounting->select_account($search_accountancy_code_start, 'search_accountancy_code_start', 1, array (), 1, 1, 'maxwidth200'); +print $formaccounting->select_account($search_accountancy_code_start, 'search_accountancy_code_start', 1, array(), 1, 1, 'maxwidth200'); print '
'; print '
'; print $langs->trans('to').' '; -print $formaccounting->select_account($search_accountancy_code_end, 'search_accountancy_code_end', 1, array (), 1, 1, 'maxwidth200'); +print $formaccounting->select_account($search_accountancy_code_end, 'search_accountancy_code_end', 1, array(), 1, 1, 'maxwidth200'); print '
'; print '
'; -print $langs->trans('From') . ': '; +print $langs->trans('From').': '; print $form->selectDate($search_date_start, 'search_date_start', 0, 0, 1); print '
'; -print $langs->trans('to') . ': '; +print $langs->trans('to').': '; print $form->selectDate($search_date_end, 'search_date_end', 0, 0, 1); print '
'; -$searchpicto=$form->showFilterAndCheckAddButtons(0); +$searchpicto = $form->showFilterAndCheckAddButtons(0); print $searchpicto; print '
 '.$line->piece_num.'' . dol_print_date($line->doc_date, 'day') . ''.$line->piece_num.''.dol_print_date($line->doc_date, 'day').''; diff --git a/htdocs/accountancy/bookkeeping/thirdparty_lettering_customer.php b/htdocs/accountancy/bookkeeping/thirdparty_lettering_customer.php index 8a04e8b621a..9cb863aec7d 100644 --- a/htdocs/accountancy/bookkeeping/thirdparty_lettering_customer.php +++ b/htdocs/accountancy/bookkeeping/thirdparty_lettering_customer.php @@ -67,7 +67,7 @@ $search_doc_ref = GETPOST("search_doc_ref", 'alpha'); */ $lettering = GETPOST('lettering', 'alpha'); -if (! empty($lettering)) { +if (!empty($lettering)) { $action = $lettering; } @@ -127,8 +127,8 @@ if ($action == 'autolettrage') { $form = new Form($db); $formaccounting = new FormAccounting($db); -$title=$object->name." - ".$langs->trans('TabLetteringCustomer'); -$help_url='EN:Module_Third_Parties|FR:Module_Tiers|ES:Empresas'; +$title = $object->name." - ".$langs->trans('TabLetteringCustomer'); +$help_url = 'EN:Module_Third_Parties|FR:Module_Tiers|ES:Empresas'; llxHeader('', $title, $help_url); $head = societe_prepare_head($object); @@ -164,13 +164,13 @@ $solde = 0; // Count total nb of records and calc total sum $nbtotalofrecords = ''; $resql = $db->query($sql); -if (! $resql) { +if (!$resql) { dol_print_error($db); exit(); } $nbtotalofrecords = $db->num_rows($resql); -while ( $obj = $db->fetch_object($resql) ) { +while ($obj = $db->fetch_object($resql)) { $debit += $obj->debit; $credit += $obj->credit; @@ -181,7 +181,7 @@ $sql .= $db->plimit($limit + 1, $offset); dol_syslog("/accountancy/bookkeeping/thirdparty_lettering_customer.php", LOG_DEBUG); $resql = $db->query($sql); -if (! $resql) { +if (!$resql) { dol_print_error($db); exit(); } @@ -205,7 +205,7 @@ if ($resql) { print_barre_liste($title, $page, $_SERVER["PHP_SELF"], $param, $sortfield, $sortorder, '', $num, $nbtotalofrecords, 'title_companies', 0, $letteringbutton, '', $limit); print '
'; - print ''."\n"; + print '
'."\n"; /* print ''; diff --git a/htdocs/accountancy/bookkeeping/thirdparty_lettering_supplier.php b/htdocs/accountancy/bookkeeping/thirdparty_lettering_supplier.php index f9cf57df344..338c795b4b2 100644 --- a/htdocs/accountancy/bookkeeping/thirdparty_lettering_supplier.php +++ b/htdocs/accountancy/bookkeeping/thirdparty_lettering_supplier.php @@ -89,7 +89,7 @@ $lettering = new Lettering($db); $object = new Societe($db); $object->id = $socid; $result = $object->fetch($socid); -if ($result<0) +if ($result < 0) { setEventMessages($object->error, $object->errors, 'errors'); } @@ -126,8 +126,8 @@ if ($action == 'autolettrage') { $form = new Form($db); $formaccounting = new FormAccounting($db); -$title=$object->name." - ".$langs->trans('TabLetteringSupplier'); -$help_url='EN:Module_Third_Parties|FR:Module_Tiers|ES:Empresas'; +$title = $object->name." - ".$langs->trans('TabLetteringSupplier'); +$help_url = 'EN:Module_Third_Parties|FR:Module_Tiers|ES:Empresas'; llxHeader('', $title, $help_url); $head = societe_prepare_head($object); @@ -159,7 +159,7 @@ $solde = 0; // Count total nb of records and calc total sum $nbtotalofrecords = ''; $resql = $db->query($sql); -if (! $resql) +if (!$resql) { dol_print_error($db); exit; @@ -203,7 +203,7 @@ if ($resql) { print_barre_liste($title, $page, $_SERVER["PHP_SELF"], $param, $sortfield, $sortorder, '', $num, $nbtotalofrecords, 'title_companies', 0, $letteringbutton, '', $limit); print '
'; - print '
'."\n"; + print '
'."\n"; /* print ''; diff --git a/htdocs/accountancy/class/accountancycategory.class.php b/htdocs/accountancy/class/accountancycategory.class.php index d68c9fa54a7..5e99f3fc4a6 100644 --- a/htdocs/accountancy/class/accountancycategory.class.php +++ b/htdocs/accountancy/class/accountancycategory.class.php @@ -57,6 +57,12 @@ class AccountancyCategory // extends CommonObject */ public $table_element='c_accounting_category'; + /** + * @var int ID + * @deprecated + */ + public $rowid; + /** * @var int ID */ diff --git a/htdocs/accountancy/class/accountancyexport.class.php b/htdocs/accountancy/class/accountancyexport.class.php index 7e8f14f2a53..f36b98b15b1 100644 --- a/htdocs/accountancy/class/accountancyexport.class.php +++ b/htdocs/accountancy/class/accountancyexport.class.php @@ -31,7 +31,7 @@ * \brief Class accountancy export */ -require_once DOL_DOCUMENT_ROOT . '/core/lib/functions.lib.php'; +require_once DOL_DOCUMENT_ROOT.'/core/lib/functions.lib.php'; /** * Manage the different format accountancy export @@ -39,7 +39,7 @@ require_once DOL_DOCUMENT_ROOT . '/core/lib/functions.lib.php'; class AccountancyExport { // Type of export. Used into $conf->global->ACCOUNTING_EXPORT_MODELCSV - public static $EXPORT_TYPE_CONFIGURABLE = 1; // CSV + public static $EXPORT_TYPE_CONFIGURABLE = 1; // CSV public static $EXPORT_TYPE_AGIRIS = 10; public static $EXPORT_TYPE_EBP = 15; public static $EXPORT_TYPE_CEGID = 20; @@ -83,7 +83,7 @@ class AccountancyExport $this->db = &$db; $this->separator = $conf->global->ACCOUNTING_EXPORT_SEPARATORCSV; - $this->end_line = empty($conf->global->ACCOUNTING_EXPORT_ENDLINE)?"\n":($conf->global->ACCOUNTING_EXPORT_ENDLINE==1?"\n":"\r\n"); + $this->end_line = empty($conf->global->ACCOUNTING_EXPORT_ENDLINE) ? "\n" : ($conf->global->ACCOUNTING_EXPORT_ENDLINE == 1 ? "\n" : "\r\n"); } /** @@ -125,7 +125,7 @@ class AccountancyExport */ private static function getFormatCode($type) { - $formatcode = array ( + $formatcode = array( self::$EXPORT_TYPE_CONFIGURABLE => 'csv', self::$EXPORT_TYPE_CEGID => 'cegid', self::$EXPORT_TYPE_COALA => 'coala', @@ -153,14 +153,14 @@ class AccountancyExport { global $conf, $langs; - return array ( + return array( 'param' => array( self::$EXPORT_TYPE_CONFIGURABLE => array( 'label' => $langs->trans('Modelcsv_configurable'), - 'ACCOUNTING_EXPORT_FORMAT' => empty($conf->global->ACCOUNTING_EXPORT_FORMAT)?'txt':$conf->global->ACCOUNTING_EXPORT_FORMAT, - 'ACCOUNTING_EXPORT_SEPARATORCSV' => empty($conf->global->ACCOUNTING_EXPORT_SEPARATORCSV)?',':$conf->global->ACCOUNTING_EXPORT_SEPARATORCSV, - 'ACCOUNTING_EXPORT_ENDLINE' => empty($conf->global->ACCOUNTING_EXPORT_ENDLINE)?1:$conf->global->ACCOUNTING_EXPORT_ENDLINE, - 'ACCOUNTING_EXPORT_DATE' => empty($conf->global->ACCOUNTING_EXPORT_DATE)?'%d%m%Y':$conf->global->ACCOUNTING_EXPORT_DATE, + 'ACCOUNTING_EXPORT_FORMAT' => empty($conf->global->ACCOUNTING_EXPORT_FORMAT) ? 'txt' : $conf->global->ACCOUNTING_EXPORT_FORMAT, + 'ACCOUNTING_EXPORT_SEPARATORCSV' => empty($conf->global->ACCOUNTING_EXPORT_SEPARATORCSV) ? ',' : $conf->global->ACCOUNTING_EXPORT_SEPARATORCSV, + 'ACCOUNTING_EXPORT_ENDLINE' => empty($conf->global->ACCOUNTING_EXPORT_ENDLINE) ? 1 : $conf->global->ACCOUNTING_EXPORT_ENDLINE, + 'ACCOUNTING_EXPORT_DATE' => empty($conf->global->ACCOUNTING_EXPORT_DATE) ? '%d%m%Y' : $conf->global->ACCOUNTING_EXPORT_DATE, ), self::$EXPORT_TYPE_CEGID => array( 'label' => $langs->trans('Modelcsv_CEGID'), @@ -209,11 +209,11 @@ class AccountancyExport 'ACCOUNTING_EXPORT_FORMAT' => 'txt', ), ), - 'cr'=> array ( + 'cr'=> array( '1' => $langs->trans("Unix"), '2' => $langs->trans("Windows") ), - 'format' => array ( + 'format' => array( 'csv' => $langs->trans("csv"), 'txt' => $langs->trans("txt") ), @@ -231,13 +231,13 @@ class AccountancyExport public function export(&$TData, $formatexportset) { global $conf, $langs; - global $search_date_end; // Used into /accountancy/tpl/export_journal.tpl.php + global $search_date_end; // Used into /accountancy/tpl/export_journal.tpl.php // Define name of file to save $filename = 'general_ledger-'.$this->getFormatCode($formatexportset); $type_export = 'general_ledger'; - include DOL_DOCUMENT_ROOT . '/accountancy/tpl/export_journal.tpl.php'; + include DOL_DOCUMENT_ROOT.'/accountancy/tpl/export_journal.tpl.php'; switch ($formatexportset) { @@ -303,13 +303,13 @@ class AccountancyExport $separator = ";"; $end_line = "\n"; - print $date . $separator; - print $line->code_journal . $separator; - print length_accountg($line->numero_compte) . $separator; - print length_accounta($line->subledger_account) . $separator; - print $line->sens . $separator; - print price($line->montant) . $separator; - print $line->label_operation . $separator; + print $date.$separator; + print $line->code_journal.$separator; + print length_accountg($line->numero_compte).$separator; + print length_accounta($line->subledger_account).$separator; + print $line->sens.$separator; + print price($line->montant).$separator; + print $line->label_operation.$separator; print $line->doc_ref; print $end_line; } @@ -328,22 +328,22 @@ class AccountancyExport $separator = ";"; $end_line = "\n"; - print $line->code_journal . $separator; - print $date . $separator; - print $line->piece_num . $separator; - print length_accountg($line->numero_compte) . $separator; - print '' . $separator; - print $line->label_operation . $separator; - print $date . $separator; - if ($line->sens=='D') { - print price($line->montant) . $separator; - print '' . $separator; - }elseif ($line->sens=='C') { - print '' . $separator; - print price($line->montant) . $separator; + print $line->code_journal.$separator; + print $date.$separator; + print $line->piece_num.$separator; + print length_accountg($line->numero_compte).$separator; + print ''.$separator; + print $line->label_operation.$separator; + print $date.$separator; + if ($line->sens == 'D') { + print price($line->montant).$separator; + print ''.$separator; + }elseif ($line->sens == 'C') { + print ''.$separator; + print price($line->montant).$separator; } - print $line->doc_ref . $separator; - print $line->label_operation . $separator; + print $line->doc_ref.$separator; + print $line->label_operation.$separator; print $end_line; } } @@ -362,15 +362,15 @@ class AccountancyExport foreach ($objectLines as $line) { $date = dol_print_date($line->doc_date, '%d/%m/%Y'); - print $date . $separator; - print $line->code_journal . $separator; - print length_accountg($line->numero_compte) . $separator; - print $line->piece_num . $separator; - print $line->doc_ref . $separator; - print price($line->debit) . $separator; - print price($line->credit) . $separator; - print 'E' . $separator; - print length_accountg($line->subledger_account) . $separator; + print $date.$separator; + print $line->code_journal.$separator; + print length_accountg($line->numero_compte).$separator; + print $line->piece_num.$separator; + print $line->doc_ref.$separator; + print price($line->debit).$separator; + print price($line->credit).$separator; + print 'E'.$separator; + print length_accountg($line->subledger_account).$separator; print $end_line; } } @@ -389,26 +389,26 @@ class AccountancyExport $end_line = "\n"; foreach ($objectLines as $line) { - print $line->piece_num . $separator; + print $line->piece_num.$separator; $date = dol_print_date($line->doc_date, '%d/%m/%Y'); - print $date . $separator; + print $date.$separator; if (empty($line->subledger_account)) { - print 'G' . $separator; - print length_accounta($line->numero_compte) . $separator; + print 'G'.$separator; + print length_accounta($line->numero_compte).$separator; } else { if (substr($line->numero_compte, 0, 3) == '411') { - print 'C' . $separator; + print 'C'.$separator; } if (substr($line->numero_compte, 0, 3) == '401') { - print 'F' . $separator; + print 'F'.$separator; } - print length_accountg($line->subledger_account) . $separator; + print length_accountg($line->subledger_account).$separator; } - print price($line->debit) . $separator; - print price($line->credit) . $separator; - print dol_trunc($line->label_operation, 32) . $separator; + print price($line->debit).$separator; + print price($line->credit).$separator; + print dol_trunc($line->label_operation, 32).$separator; print $end_line; } } @@ -423,23 +423,23 @@ class AccountancyExport { global $conf; - $end_line ="\r\n"; + $end_line = "\r\n"; $i = 1; $date_ecriture = dol_print_date(dol_now(), $conf->global->ACCOUNTING_EXPORT_DATE); // format must be yyyymmdd foreach ($TData as $data) { $code_compta = $data->numero_compte; - if (! empty($data->subledger_account)) + if (!empty($data->subledger_account)) $code_compta = $data->subledger_account; - $Tab = array (); + $Tab = array(); $Tab['num_ecriture'] = str_pad($i, 5); $Tab['code_journal'] = str_pad($data->code_journal, 2); $Tab['date_ecriture'] = $date_ecriture; $Tab['date_ope'] = dol_print_date($data->doc_date, $conf->global->ACCOUNTING_EXPORT_DATE); $Tab['num_piece'] = str_pad(self::trunc($data->piece_num, 12), 12); $Tab['num_compte'] = str_pad(self::trunc($code_compta, 11), 11); - $Tab['libelle_ecriture'] = str_pad(self::trunc(dol_string_unaccent($data->doc_ref) . dol_string_unaccent($data->label_operation), 25), 25); + $Tab['libelle_ecriture'] = str_pad(self::trunc(dol_string_unaccent($data->doc_ref).dol_string_unaccent($data->label_operation), 25), 25); $Tab['montant'] = str_pad(abs($data->montant), 13, ' ', STR_PAD_LEFT); $Tab['type_montant'] = str_pad($data->sens, 1); $Tab['vide'] = str_repeat(' ', 18); @@ -449,7 +449,7 @@ class AccountancyExport $Tab['end_line'] = $end_line; print implode($Tab); - $i ++; + $i++; } } @@ -463,17 +463,17 @@ class AccountancyExport { global $conf; - $end_line ="\r\n"; + $end_line = "\r\n"; //We should use dol_now function not time however this is wrong date to transfert in accounting //$date_ecriture = dol_print_date(dol_now(), $conf->global->ACCOUNTING_EXPORT_DATE); // format must be ddmmyy //$date_ecriture = dol_print_date(time(), $conf->global->ACCOUNTING_EXPORT_DATE); // format must be ddmmyy foreach ($TData as $data) { $code_compta = $data->numero_compte; - if (! empty($data->subledger_account)) + if (!empty($data->subledger_account)) $code_compta = $data->subledger_account; - $Tab = array (); + $Tab = array(); $Tab['type_ligne'] = 'M'; $Tab['num_compte'] = str_pad(self::trunc($code_compta, 8), 8); $Tab['code_journal'] = str_pad(self::trunc($data->code_journal, 2), 2); @@ -484,19 +484,19 @@ class AccountancyExport //$Tab['date_ecriture'] = $date_ecriture; $Tab['date_ecriture'] = dol_print_date($data->doc_date, '%d%m%y'); $Tab['filler'] = ' '; - $Tab['libelle_ecriture'] = str_pad(self::trunc(dol_string_unaccent($data->doc_ref) . ' ' . dol_string_unaccent($data->label_operation), 20), 20); + $Tab['libelle_ecriture'] = str_pad(self::trunc(dol_string_unaccent($data->doc_ref).' '.dol_string_unaccent($data->label_operation), 20), 20); $Tab['sens'] = $data->sens; // C or D $Tab['signe_montant'] = '+'; //elarifr le montant doit etre en centimes sans point decimal ! - $Tab['montant'] = str_pad(abs($data->montant*100), 12, '0', STR_PAD_LEFT); // TODO manage negative amount + $Tab['montant'] = str_pad(abs($data->montant * 100), 12, '0', STR_PAD_LEFT); // TODO manage negative amount // $Tab['montant'] = str_pad(abs($data->montant), 12, '0', STR_PAD_LEFT); // TODO manage negative amount $Tab['contrepartie'] = str_repeat(' ', 8); // elarifr: date format must be fixed format : 6 char ddmmyy = %d%m%yand not defined by user / dolibarr setting - if (! empty($data->date_echeance)) + if (!empty($data->date_echeance)) //$Tab['date_echeance'] = dol_print_date($data->date_echeance, $conf->global->ACCOUNTING_EXPORT_DATE); - $Tab['date_echeance'] = dol_print_date($data->date_echeance, '%d%m%y'); // elarifr: format must be ddmmyy + $Tab['date_echeance'] = dol_print_date($data->date_echeance, '%d%m%y'); // elarifr: format must be ddmmyy else $Tab['date_echeance'] = '000000'; @@ -551,20 +551,20 @@ class AccountancyExport foreach ($objectLines as $line) { $date = dol_print_date($line->doc_date, '%d%m%Y'); - print $line->id . $separator; - print $date . $separator; - print $line->code_journal . $separator; + print $line->id.$separator; + print $date.$separator; + print $line->code_journal.$separator; if (empty($line->subledger_account)) { - print $line->numero_compte . $separator; + print $line->numero_compte.$separator; } else { - print $line->subledger_account . $separator; + print $line->subledger_account.$separator; } //print substr(length_accountg($line->numero_compte), 0, 2) . $separator; - print '"'.dol_trunc($line->label_operation, 40, 'right', 'UTF-8', 1).'"' . $separator; + print '"'.dol_trunc($line->label_operation, 40, 'right', 'UTF-8', 1).'"'.$separator; print '"'.dol_trunc($line->piece_num, 15, 'right', 'UTF-8', 1).'"'.$separator; print price2num(abs($line->montant)).$separator; print $line->sens.$separator; - print $date . $separator; + print $date.$separator; //print 'EUR'; print $end_line; } @@ -586,25 +586,25 @@ class AccountancyExport foreach ($objectLines as $line) { $date = dol_print_date($line->doc_date, '%d%m%Y'); - print $line->piece_num . $separator; - print self::toAnsi($line->label_operation) . $separator; - print $date . $separator; - print self::toAnsi($line->label_operation) . $separator; + print $line->piece_num.$separator; + print self::toAnsi($line->label_operation).$separator; + print $date.$separator; + print self::toAnsi($line->label_operation).$separator; if (empty($line->subledger_account)) { - print length_accountg($line->numero_compte) . $separator; - print self::toAnsi($line->label_compte) . $separator; + print length_accountg($line->numero_compte).$separator; + print self::toAnsi($line->label_compte).$separator; } else { - print length_accounta($line->subledger_account) . $separator; - print self::toAnsi($line->subledger_label) . $separator; + print length_accounta($line->subledger_account).$separator; + print self::toAnsi($line->subledger_label).$separator; } - print self::toAnsi($line->doc_ref) . $separator; - print price($line->debit) . $separator; - print price($line->credit) . $separator; - print price($line->montant) . $separator; - print $line->sens . $separator; - print $line->lettering_code . $separator; + print self::toAnsi($line->doc_ref).$separator; + print price($line->debit).$separator; + print price($line->credit).$separator; + print price($line->montant).$separator; + print $line->sens.$separator; + print $line->lettering_code.$separator; print $line->code_journal; print $end_line; } @@ -625,17 +625,17 @@ class AccountancyExport foreach ($objectLines as $line) { $date = dol_print_date($line->doc_date, '%d/%m/%Y'); - print $date . $separator; - print $line->code_journal . $separator; + print $date.$separator; + print $line->code_journal.$separator; if (empty($line->subledger_account)) { - print length_accountg($line->numero_compte) . $separator; + print length_accountg($line->numero_compte).$separator; } else { - print length_accounta($line->subledger_account) . $separator; + print length_accounta($line->subledger_account).$separator; } - print $line->doc_ref . $separator; - print $line->label_operation . $separator; - print price($line->debit) . $separator; - print price($line->credit) . $separator; + print $line->doc_ref.$separator; + print $line->label_operation.$separator; + print price($line->debit).$separator; + print price($line->credit).$separator; print $end_line; } @@ -668,7 +668,7 @@ class AccountancyExport $tab[] = price2num($line->montant); $tab[] = $line->code_journal; - print implode($separator, $tab) . $this->end_line; + print implode($separator, $tab).$this->end_line; } } @@ -683,23 +683,23 @@ class AccountancyExport $separator = "\t"; $end_line = "\n"; - print "JournalCode" . $separator; - print "JournalLib" . $separator; - print "EcritureNum" . $separator; - print "EcritureDate" . $separator; - print "CompteNum" . $separator; - print "CompteLib" . $separator; - print "CompAuxNum" . $separator; - print "CompAuxLib" . $separator; - print "PieceRef" . $separator; - print "PieceDate" . $separator; - print "EcritureLib" . $separator; - print "Debit" . $separator; - print "Credit" . $separator; - print "EcritureLet" . $separator; - print "DateLet" . $separator; - print "ValidDate" . $separator; - print "Montantdevise" . $separator; + print "JournalCode".$separator; + print "JournalLib".$separator; + print "EcritureNum".$separator; + print "EcritureDate".$separator; + print "CompteNum".$separator; + print "CompteLib".$separator; + print "CompAuxNum".$separator; + print "CompAuxLib".$separator; + print "PieceRef".$separator; + print "PieceDate".$separator; + print "EcritureLib".$separator; + print "Debit".$separator; + print "Credit".$separator; + print "EcritureLet".$separator; + print "DateLet".$separator; + print "ValidDate".$separator; + print "Montantdevise".$separator; print "Idevise"; print $end_line; @@ -709,55 +709,55 @@ class AccountancyExport $date_valid = dol_print_date($line->date_validated, '%d%m%Y'); // FEC:JournalCode - print $line->code_journal . $separator; + print $line->code_journal.$separator; // FEC:JournalLib - print $line->journal_label . $separator; + print $line->journal_label.$separator; // FEC:EcritureNum - print $line->piece_num . $separator; + print $line->piece_num.$separator; // FEC:EcritureDate - print $date_creation . $separator; + print $date_creation.$separator; // FEC:CompteNum - print $line->numero_compte . $separator; + print $line->numero_compte.$separator; // FEC:CompteLib - print $line->label_compte . $separator; + print $line->label_compte.$separator; // FEC:CompAuxNum - print $line->subledger_account . $separator; + print $line->subledger_account.$separator; // FEC:CompAuxLib - print $line->subledger_label . $separator; + print $line->subledger_label.$separator; // FEC:PieceRef - print $line->doc_ref . $separator; + print $line->doc_ref.$separator; // FEC:PieceDate - print $date_doc . $separator; + print $date_doc.$separator; // FEC:EcritureLib - print $line->label_operation . $separator; + print $line->label_operation.$separator; // FEC:Debit - print price2num($line->debit) . $separator; + print price2num($line->debit).$separator; // FEC:Credit - print price2num($line->credit) . $separator; + print price2num($line->credit).$separator; // FEC:EcritureLet - print $line->lettering_code . $separator; + print $line->lettering_code.$separator; // FEC:DateLet - print $line->date_lettering . $separator; + print $line->date_lettering.$separator; // FEC:ValidDate - print $date_valid . $separator; + print $date_valid.$separator; // FEC:Montantdevise - print $line->multicurrency_amount . $separator; + print $line->multicurrency_amount.$separator; // FEC:Idevise print $line->multicurrency_code; @@ -785,121 +785,121 @@ class AccountancyExport // Print header line print "Blg,Datum,Kto,S/H,Grp,GKto,SId,SIdx,KIdx,BTyp,MTyp,Code,Netto,Steuer,FW-Betrag,Tx1,Tx2,PkKey,OpId,Flag"; print $this->end_line; - $thisPieceNum= ""; - $thisPieceAccountNr= ""; - $aSize= count($objectLines); + $thisPieceNum = ""; + $thisPieceAccountNr = ""; + $aSize = count($objectLines); foreach ($objectLines as $aIndex=>$line) { - $sammelBuchung= false; - if ($aIndex-2 >= 0 && $objectLines[$aIndex-2]->piece_num == $line->piece_num) + $sammelBuchung = false; + if ($aIndex - 2 >= 0 && $objectLines[$aIndex - 2]->piece_num == $line->piece_num) { - $sammelBuchung= true; + $sammelBuchung = true; } - elseif ($aIndex+2 < $aSize && $objectLines[$aIndex+2]->piece_num == $line->piece_num) + elseif ($aIndex + 2 < $aSize && $objectLines[$aIndex + 2]->piece_num == $line->piece_num) { - $sammelBuchung= true; + $sammelBuchung = true; } - elseif ($aIndex+1 < $aSize - && $objectLines[$aIndex+1]->piece_num == $line->piece_num - && $aIndex-1 < $aSize - && $objectLines[$aIndex-1]->piece_num == $line->piece_num + elseif ($aIndex + 1 < $aSize + && $objectLines[$aIndex + 1]->piece_num == $line->piece_num + && $aIndex - 1 < $aSize + && $objectLines[$aIndex - 1]->piece_num == $line->piece_num ) { - $sammelBuchung= true; + $sammelBuchung = true; } //Blg - print $line->piece_num . $this->separator; + print $line->piece_num.$this->separator; // Datum $date = dol_print_date($line->doc_date, '%d.%m.%Y'); - print $date . $this->separator; + print $date.$this->separator; // Kto - print length_accountg($line->numero_compte) . $this->separator; + print length_accountg($line->numero_compte).$this->separator; // S/H if ($line->sens == 'D') { - print 'S' . $this->separator; + print 'S'.$this->separator; } else { - print 'H' . $this->separator; + print 'H'.$this->separator; } //Grp - print self::trunc($line->code_journal, 1) . $this->separator; + print self::trunc($line->code_journal, 1).$this->separator; // GKto if (empty($line->code_tiers)) { if ($line->piece_num == $thisPieceNum) { - print length_accounta($thisPieceAccountNr) . $this->separator; + print length_accounta($thisPieceAccountNr).$this->separator; } else { - print "div" . $this->separator; + print "div".$this->separator; } } else { - print length_accounta($line->code_tiers) . $this->separator; + print length_accounta($line->code_tiers).$this->separator; } //SId print $this->separator; //SIdx - print "0" . $this->separator; + print "0".$this->separator; //KIdx - print "0" . $this->separator; + print "0".$this->separator; //BTyp - print "0" . $this->separator; + print "0".$this->separator; //MTyp 1=Fibu Einzelbuchung 2=Sammebuchung if ($sammelBuchung) { - print "2" . $this->separator; + print "2".$this->separator; } else { - print "1" . $this->separator; + print "1".$this->separator; } // Code - print '""' . $this->separator; + print '""'.$this->separator; // Netto if ($line->montant >= 0) { - print $line->montant . $this->separator; + print $line->montant.$this->separator; } else { - print $line->montant*-1 . $this->separator; + print ($line->montant * -1).$this->separator; } // Steuer - print "0.00" . $this->separator; + print "0.00".$this->separator; // FW-Betrag - print "0.00" . $this->separator; + print "0.00".$this->separator; // Tx1 - $line1= self::toAnsi($line->label_compte, 29); + $line1 = self::toAnsi($line->label_compte, 29); if ($line1 == "LIQ" || $line1 == "LIQ Beleg ok" || strlen($line1) <= 3) { - $line1= ""; + $line1 = ""; } - $line2= self::toAnsi($line->doc_ref, 29); + $line2 = self::toAnsi($line->doc_ref, 29); if (strlen($line1) == 0) { - $line1= $line2; - $line2= ""; + $line1 = $line2; + $line2 = ""; } if (strlen($line1) > 0 && strlen($line2) > 0 && (strlen($line1) + strlen($line2)) < 27) { - $line1= $line1 . ' / ' . $line2; - $line2= ""; + $line1 = $line1.' / '.$line2; + $line2 = ""; } - print '"' . self::toAnsi($line1). '"' . $this->separator; + print '"'.self::toAnsi($line1).'"'.$this->separator; // Tx2 - print '"' . self::toAnsi($line2). '"' . $this->separator; + print '"'.self::toAnsi($line2).'"'.$this->separator; //PkKey - print "0" . $this->separator; + print "0".$this->separator; //OpId print $this->separator; @@ -910,8 +910,8 @@ class AccountancyExport if ($line->piece_num !== $thisPieceNum) { - $thisPieceNum= $line->piece_num; - $thisPieceAccountNr= $line->numero_compte; + $thisPieceNum = $line->piece_num; + $thisPieceAccountNr = $line->numero_compte; } } } @@ -932,23 +932,23 @@ class AccountancyExport foreach ($objectLines as $line) { $date_document = dol_print_date($line->doc_date, '%Y%m%d'); - $date_creation = dol_print_date($line->date_creation, '%Y%m%d'); + $date_creation = dol_print_date($line->date_creation, '%Y%m%d'); // TYPE $type_enregistrement = 'E'; // For write movement - print $type_enregistrement . $separator; + print $type_enregistrement.$separator; // JNAL - print substr($line->code_journal, 0, 2) . $separator; + print substr($line->code_journal, 0, 2).$separator; // NECR - print $line->id . $separator; + print $line->id.$separator; // NPIE - print $line->piece_num . $separator; + print $line->piece_num.$separator; // DATP - print $date_document . $separator; + print $date_document.$separator; // LIBE - print $line->label_operation . $separator; + print $line->label_operation.$separator; // DATH - print $line->date_lim_reglement . $separator; + print $line->date_lim_reglement.$separator; // CNPI if ($line->doc_type == 'supplier_invoice') { if ($line->montant < 0) { @@ -965,7 +965,7 @@ class AccountancyExport } else { $nature_piece = ''; } - print $nature_piece . $separator; + print $nature_piece.$separator; // RACI /* if (! empty($line->subledger_account)) { @@ -983,28 +983,28 @@ class AccountancyExport */ print $separator; // deprecated CPTG & CPTA use instead // MONT - print price(abs($line->montant), 0, '', 1, 2) . $separator; + print price(abs($line->montant), 0, '', 1, 2).$separator; // CODC - print $line->sens . $separator; + print $line->sens.$separator; // CPTG - print length_accountg($line->numero_compte) . $separator; + print length_accountg($line->numero_compte).$separator; // DATE - print $date_creation . $separator; + print $date_creation.$separator; // CLET - print $line->lettering_code . $separator; + print $line->lettering_code.$separator; // DATL - print $line->date_lettering . $separator; + print $line->date_lettering.$separator; // CPTA - if (! empty($line->subledger_account)) { - print length_accounta($line->subledger_account) . $separator; + if (!empty($line->subledger_account)) { + print length_accounta($line->subledger_account).$separator; } else { print $separator; } // CNAT - if ($line->doc_type == 'supplier_invoice' && ! empty($line->subledger_account)) { - print 'F' . $separator; - } elseif ($line->doc_type == 'customer_invoice' && ! empty($line->subledger_account)) { - print 'C' . $separator; + if ($line->doc_type == 'supplier_invoice' && !empty($line->subledger_account)) { + print 'F'.$separator; + } elseif ($line->doc_type == 'customer_invoice' && !empty($line->subledger_account)) { + print 'C'.$separator; } else { print $separator; } @@ -1017,17 +1017,17 @@ class AccountancyExport // DATV print $separator; // REFD - print $line->doc_ref . $separator; + print $line->doc_ref.$separator; // CODH print $separator; // NSEQ print $separator; // MTDV - print '0' . $separator; + print '0'.$separator; // CODV print $separator; // TXDV - print '0' . $separator; + print '0'.$separator; // MOPM print $separator; // BONP @@ -1066,43 +1066,43 @@ class AccountancyExport /* * Charlemagne export need header */ - print $langs->transnoentitiesnoconv('Date') . $separator; - print self::trunc($langs->transnoentitiesnoconv('Journal'), 6) . $separator; - print self::trunc($langs->transnoentitiesnoconv('Account'), 15) . $separator; - print self::trunc($langs->transnoentitiesnoconv('LabelAccount'), 60) . $separator; - print self::trunc($langs->transnoentitiesnoconv('Piece'), 20) . $separator; - print self::trunc($langs->transnoentitiesnoconv('LabelOperation'), 60) . $separator; - print $langs->transnoentitiesnoconv('Amount') . $separator; - print 'S' . $separator; - print self::trunc($langs->transnoentitiesnoconv('Analytic') . ' 1', 15) . $separator; - print self::trunc($langs->transnoentitiesnoconv('AnalyticLabel') . ' 1', 60) . $separator; - print self::trunc($langs->transnoentitiesnoconv('Analytic') . ' 2', 15) . $separator; - print self::trunc($langs->transnoentitiesnoconv('AnalyticLabel') . ' 2', 60) . $separator; - print self::trunc($langs->transnoentitiesnoconv('Analytic') . ' 3', 15) . $separator; - print self::trunc($langs->transnoentitiesnoconv('AnalyticLabel') . ' 3', 60) . $separator; + print $langs->transnoentitiesnoconv('Date').$separator; + print self::trunc($langs->transnoentitiesnoconv('Journal'), 6).$separator; + print self::trunc($langs->transnoentitiesnoconv('Account'), 15).$separator; + print self::trunc($langs->transnoentitiesnoconv('LabelAccount'), 60).$separator; + print self::trunc($langs->transnoentitiesnoconv('Piece'), 20).$separator; + print self::trunc($langs->transnoentitiesnoconv('LabelOperation'), 60).$separator; + print $langs->transnoentitiesnoconv('Amount').$separator; + print 'S'.$separator; + print self::trunc($langs->transnoentitiesnoconv('Analytic').' 1', 15).$separator; + print self::trunc($langs->transnoentitiesnoconv('AnalyticLabel').' 1', 60).$separator; + print self::trunc($langs->transnoentitiesnoconv('Analytic').' 2', 15).$separator; + print self::trunc($langs->transnoentitiesnoconv('AnalyticLabel').' 2', 60).$separator; + print self::trunc($langs->transnoentitiesnoconv('Analytic').' 3', 15).$separator; + print self::trunc($langs->transnoentitiesnoconv('AnalyticLabel').' 3', 60).$separator; print $end_line; - foreach($objectLines as $line) { + foreach ($objectLines as $line) { $date = dol_print_date($line->doc_date, '%Y%m%d'); - print $date . $separator; //Date + print $date.$separator; //Date - print self::trunc($line->code_journal, 6) . $separator; //Journal code + print self::trunc($line->code_journal, 6).$separator; //Journal code - if(!empty($line->subledger_account)) $account = $line->subledger_account; + if (!empty($line->subledger_account)) $account = $line->subledger_account; else $account = $line->numero_compte; - print self::trunc($account, 15) . $separator;//Account number + print self::trunc($account, 15).$separator; //Account number - print self::trunc($line->label_compte, 60) . $separator;//Account label - print self::trunc($line->doc_ref, 20) . $separator;//Piece - print self::trunc($line->label_operation, 60) . $separator;//Operation label - print price(abs($line->montant)) . $separator;//Amount - print $line->sens . $separator;//Direction - print $separator;//Analytic - print $separator;//Analytic - print $separator;//Analytic - print $separator;//Analytic - print $separator;//Analytic - print $separator;//Analytic + print self::trunc($line->label_compte, 60).$separator; //Account label + print self::trunc($line->doc_ref, 20).$separator; //Piece + print self::trunc($line->label_operation, 60).$separator; //Operation label + print price(abs($line->montant)).$separator; //Amount + print $line->sens.$separator; //Direction + print $separator; //Analytic + print $separator; //Analytic + print $separator; //Analytic + print $separator; //Analytic + print $separator; //Analytic + print $separator; //Analytic print $end_line; } } @@ -1129,10 +1129,10 @@ class AccountancyExport */ public static function toAnsi($str, $size = -1) { - $retVal= dol_string_nohtmltag($str, 1, 'Windows-1251'); + $retVal = dol_string_nohtmltag($str, 1, 'Windows-1251'); if ($retVal >= 0 && $size >= 0) { - $retVal= mb_substr($retVal, 0, $size, 'Windows-1251'); + $retVal = mb_substr($retVal, 0, $size, 'Windows-1251'); } return $retVal; } diff --git a/htdocs/accountancy/class/accountancysystem.class.php b/htdocs/accountancy/class/accountancysystem.class.php index 4f93aa18875..c59e87dfd93 100644 --- a/htdocs/accountancy/class/accountancysystem.class.php +++ b/htdocs/accountancy/class/accountancysystem.class.php @@ -36,7 +36,7 @@ class AccountancySystem /** * @var string Error code (or message) */ - public $error=''; + public $error = ''; /** * @var int ID @@ -48,7 +48,14 @@ class AccountancySystem */ public $fk_pcg_version; + /** + * @var string pcg type + */ public $pcg_type; + + /** + * @var string pcg subtype + */ public $pcg_subtype; /** @@ -61,7 +68,14 @@ class AccountancySystem */ public $label; + /** + * @var string account number + */ public $account_number; + + /** + * @var string account parent + */ public $account_parent; /** diff --git a/htdocs/accountancy/class/accountingaccount.class.php b/htdocs/accountancy/class/accountingaccount.class.php index 0cfc0d24826..b244d8be123 100644 --- a/htdocs/accountancy/class/accountingaccount.class.php +++ b/htdocs/accountancy/class/accountingaccount.class.php @@ -154,7 +154,7 @@ class AccountingAccount extends CommonObject * @param int $rowid Id * @param string $account_number Account number * @param int|boolean $limittocurrentchart 1 or true=Load record only if it is into current active char of account - * @param string $limittoachartaccount 'ABC'=Load record only if it is into chart account with code 'ABC'. + * @param string $limittoachartaccount 'ABC'=Load record only if it is into chart account with code 'ABC' (better and faster than previous parameter if you have chart of account code). * @return int <0 if KO, 0 if not found, Id of record if OK and found */ public function fetch($rowid = null, $account_number = null, $limittocurrentchart = 0, $limittoachartaccount = '') diff --git a/htdocs/accountancy/class/accountingjournal.class.php b/htdocs/accountancy/class/accountingjournal.class.php index f922ac06655..1191187a139 100644 --- a/htdocs/accountancy/class/accountingjournal.class.php +++ b/htdocs/accountancy/class/accountingjournal.class.php @@ -29,12 +29,12 @@ class AccountingJournal extends CommonObject /** * @var string ID to identify managed object */ - public $element='accounting_journal'; + public $element = 'accounting_journal'; /** * @var string Name of table without prefix where object is stored */ - public $table_element='accounting_journal'; + public $table_element = 'accounting_journal'; /** * @var int Field with ID of parent key if this field has a parent @@ -42,8 +42,7 @@ class AccountingJournal extends CommonObject public $fk_element = ''; /** - * 0=No test on entity, 1=Test with field entity, 2=Test with link by societe - * @var int + * @var int 0=No test on entity, 1=Test with field entity, 2=Test with link by societe */ public $ismultientitymanaged = 0; @@ -57,6 +56,9 @@ class AccountingJournal extends CommonObject */ public $rowid; + /** + * @var string Accounting journal code + */ public $code; /** @@ -64,9 +66,19 @@ class AccountingJournal extends CommonObject */ public $label; - public $nature; // 1:various operations, 2:sale, 3:purchase, 4:bank, 5:expense-report, 8:inventory, 9: has-new + /** + * @var int 1:various operations, 2:sale, 3:purchase, 4:bank, 5:expense-report, 8:inventory, 9: has-new + */ + public $nature; + + /** + * @var int is active or not + */ public $active; + /** + * @var array array of lines + */ public $lines; /** @@ -93,29 +105,29 @@ class AccountingJournal extends CommonObject if ($rowid || $journal_code) { $sql = "SELECT rowid, code, label, nature, active"; - $sql.= " FROM ".MAIN_DB_PREFIX."accounting_journal"; + $sql .= " FROM ".MAIN_DB_PREFIX."accounting_journal"; $sql .= " WHERE"; if ($rowid) { - $sql .= " rowid = " . (int) $rowid; + $sql .= " rowid = ".(int) $rowid; } elseif ($journal_code) { - $sql .= " code = '" . $this->db->escape($journal_code) . "'"; - $sql .= " AND entity = " . $conf->entity; + $sql .= " code = '".$this->db->escape($journal_code)."'"; + $sql .= " AND entity = ".$conf->entity; } - dol_syslog(get_class($this)."::fetch sql=" . $sql, LOG_DEBUG); + dol_syslog(get_class($this)."::fetch sql=".$sql, LOG_DEBUG); $result = $this->db->query($sql); if ($result) { $obj = $this->db->fetch_object($result); if ($obj) { - $this->id = $obj->rowid; + $this->id = $obj->rowid; $this->rowid = $obj->rowid; $this->code = $obj->code; - $this->ref = $obj->code; + $this->ref = $obj->code; $this->label = $obj->label; $this->nature = $obj->nature; $this->active = $obj->active; @@ -127,8 +139,8 @@ class AccountingJournal extends CommonObject } else { - $this->error = "Error " . $this->db->lasterror(); - $this->errors[] = "Error " . $this->db->lasterror(); + $this->error = "Error ".$this->db->lasterror(); + $this->errors[] = "Error ".$this->db->lasterror(); } } return -1; @@ -149,38 +161,38 @@ class AccountingJournal extends CommonObject public function fetchAll($sortorder = '', $sortfield = '', $limit = 0, $offset = 0, array $filter = array(), $filtermode = 'AND') { $sql = "SELECT rowid, code, label, nature, active"; - $sql .= ' FROM ' . MAIN_DB_PREFIX . $this->table_element . ' as t'; + $sql .= ' FROM '.MAIN_DB_PREFIX.$this->table_element.' as t'; // Manage filter $sqlwhere = array(); if (count($filter) > 0) { foreach ($filter as $key => $value) { if ($key == 't.code' || $key == 't.label' || $key == 't.nature') { - $sqlwhere[] = $key . '\'' . $this->db->escape($value) . '\''; + $sqlwhere[] = $key.'\''.$this->db->escape($value).'\''; } elseif ($key == 't.rowid' || $key == 't.active') { - $sqlwhere[] = $key . '=' . $value; + $sqlwhere[] = $key.'='.$value; } } } $sql .= ' WHERE 1 = 1'; - $sql .= " AND entity IN (" . getEntity('accountancy') . ")"; + $sql .= " AND entity IN (".getEntity('accountancy').")"; if (count($sqlwhere) > 0) { - $sql .= ' AND ' . implode(' ' . $filtermode . ' ', $sqlwhere); + $sql .= ' AND '.implode(' '.$filtermode.' ', $sqlwhere); } - if (! empty($sortfield)) { + if (!empty($sortfield)) { $sql .= $this->db->order($sortfield, $sortorder); } - if (! empty($limit)) { - $sql .= ' ' . $this->db->plimit($limit + 1, $offset); + if (!empty($limit)) { + $sql .= ' '.$this->db->plimit($limit + 1, $offset); } $this->lines = array(); - dol_syslog(get_class($this) . "::fetch sql=" . $sql, LOG_DEBUG); + dol_syslog(get_class($this)."::fetch sql=".$sql, LOG_DEBUG); $resql = $this->db->query($sql); if ($resql) { $num = $this->db->num_rows($resql); - while ( $obj = $this->db->fetch_object($resql) ) { + while ($obj = $this->db->fetch_object($resql)) { $line = new self($this->db); $line->id = $obj->rowid; @@ -196,10 +208,10 @@ class AccountingJournal extends CommonObject return $num; } else { - $this->errors[] = 'Error ' . $this->db->lasterror(); - dol_syslog(__METHOD__ . ' ' . join(',', $this->errors), LOG_ERR); + $this->errors[] = 'Error '.$this->db->lasterror(); + dol_syslog(__METHOD__.' '.join(',', $this->errors), LOG_ERR); - return - 1; + return -1; } } @@ -217,34 +229,34 @@ class AccountingJournal extends CommonObject { global $langs, $conf, $user; - if (! empty($conf->dol_no_mouse_hover)) $notooltip=1; // Force disable tooltips + if (!empty($conf->dol_no_mouse_hover)) $notooltip = 1; // Force disable tooltips $result = ''; - $url = DOL_URL_ROOT . '/accountancy/admin/journals_list.php?id=35'; + $url = DOL_URL_ROOT.'/accountancy/admin/journals_list.php?id=35'; - $label = '' . $langs->trans("ShowAccountingJournal") . ''; - if (! empty($this->code)) - $label .= '
'.$langs->trans('Code') . ': ' . $this->code; - if (! empty($this->label)) - $label .= '
'.$langs->trans('Label') . ': ' . $langs->transnoentities($this->label); - if ($moretitle) $label.=' - '.$moretitle; + $label = ''.$langs->trans("ShowAccountingJournal").''; + if (!empty($this->code)) + $label .= '
'.$langs->trans('Code').': '.$this->code; + if (!empty($this->label)) + $label .= '
'.$langs->trans('Label').': '.$langs->transnoentities($this->label); + if ($moretitle) $label .= ' - '.$moretitle; - $linkclose=''; + $linkclose = ''; if (empty($notooltip)) { - if (! empty($conf->global->MAIN_OPTIMIZEFORTEXTBROWSER)) + if (!empty($conf->global->MAIN_OPTIMIZEFORTEXTBROWSER)) { - $label=$langs->trans("ShowAccountingJournal"); - $linkclose.=' alt="'.dol_escape_htmltag($label, 1).'"'; + $label = $langs->trans("ShowAccountingJournal"); + $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"'; } - $linkstart=''; - $linkend=''; + $linkstart = ''; + $linkend = ''; if ($nourl) { @@ -254,11 +266,11 @@ class AccountingJournal extends CommonObject } $label_link = $this->code; - if ($withlabel) $label_link .= ' - ' . $langs->transnoentities($this->label); + if ($withlabel) $label_link .= ' - '.$langs->transnoentities($this->label); $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.= $label_link; + 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 .= $label_link; $result .= $linkend; return $result; @@ -292,7 +304,7 @@ class AccountingJournal extends CommonObject if ($mode == 0) { - $prefix=''; + $prefix = ''; if ($nature == 9) return $langs->trans('AccountingJournalType9'); elseif ($nature == 5) return $langs->trans('AccountingJournalType5'); elseif ($nature == 4) return $langs->trans('AccountingJournalType4'); diff --git a/htdocs/accountancy/class/bookkeeping.class.php b/htdocs/accountancy/class/bookkeeping.class.php index 9e58ffed942..d8a33ac1054 100644 --- a/htdocs/accountancy/class/bookkeeping.class.php +++ b/htdocs/accountancy/class/bookkeeping.class.php @@ -25,7 +25,7 @@ */ // Class -require_once DOL_DOCUMENT_ROOT . '/core/class/commonobject.class.php'; +require_once DOL_DOCUMENT_ROOT.'/core/class/commonobject.class.php'; /** * Class to manage Ledger (General Ledger and Subledger) @@ -38,7 +38,7 @@ class BookKeeping extends CommonObject public $error; /** - * @var string[] Error codes (or messages) + * @var string[] Array of Error codes (or messages) */ public $errors = array(); @@ -60,14 +60,21 @@ class BookKeeping extends CommonObject /** * @var BookKeepingLine[] Lines */ - public $lines = array (); + public $lines = array(); /** * @var int ID */ public $id; + /** + * @var string Date of source document, in db date NOT NULL + */ public $doc_date; + + /** + * @var int Deadline for payment + */ public $date_lim_reglement; /** @@ -119,9 +126,25 @@ class BookKeeping extends CommonObject * @var string label operation */ public $label_operation; + + /** + * @var float FEC:Debit + */ public $debit; + + /** + * @var float FEC:Credit + */ public $credit; + + /** + * @var float FEC:Amount (Not necessary) + */ public $montant; + + /** + * @var string FEC:Sens (Not necessary) + */ public $sens; /** @@ -129,9 +152,24 @@ class BookKeeping extends CommonObject */ public $fk_user_author; + /** + * @var string key for import + */ public $import_key; + + /** + * @var string code journal + */ public $code_journal; + + /** + * @var string label journal + */ public $journal_label; + + /** + * @var int accounting transaction id + */ public $piece_num; /** @@ -140,7 +178,6 @@ class BookKeeping extends CommonObject public $picto = 'generic'; - /** * Constructor * @@ -230,17 +267,17 @@ class BookKeeping extends CommonObject $langs->loadLangs(array("errors")); if (in_array($this->doc_type, array('bank', 'expense_report'))) { - $this->errors[]=$langs->trans('ErrorFieldAccountNotDefinedForBankLine', $this->fk_docdet, $this->doc_type); + $this->errors[] = $langs->trans('ErrorFieldAccountNotDefinedForBankLine', $this->fk_docdet, $this->doc_type); } else { //$this->errors[]=$langs->trans('ErrorFieldAccountNotDefinedForInvoiceLine', $this->doc_ref, $this->label_compte); - $mesg=$this->doc_ref.', '.$langs->trans("AccountAccounting").': '.$this->numero_compte; + $mesg = $this->doc_ref.', '.$langs->trans("AccountAccounting").': '.$this->numero_compte; if ($this->subledger_account && $this->subledger_account != $this->numero_compte) { - $mesg.=', '.$langs->trans("SubledgerAccount").': '.$this->subledger_account; + $mesg .= ', '.$langs->trans("SubledgerAccount").': '.$this->subledger_account; } - $this->errors[]=$langs->trans('ErrorFieldAccountNotDefinedForLine', $mesg); + $this->errors[] = $langs->trans('ErrorFieldAccountNotDefinedForLine', $mesg); } return -1; @@ -256,13 +293,13 @@ class BookKeeping extends CommonObject // WARNING: This is not reliable, label may have been modified. This is just a small protection. // The page to make journalization make the test on couple doc_type - fk_doc only. $sql = "SELECT count(*) as nb"; - $sql .= " FROM " . MAIN_DB_PREFIX . $this->table_element; - $sql .= " WHERE doc_type = '" . $this->db->escape($this->doc_type) . "'"; - $sql .= " AND fk_doc = " . $this->fk_doc; + $sql .= " FROM ".MAIN_DB_PREFIX.$this->table_element; + $sql .= " WHERE doc_type = '".$this->db->escape($this->doc_type)."'"; + $sql .= " AND fk_doc = ".$this->fk_doc; //$sql .= " AND fk_docdet = " . $this->fk_docdet; // This field can be 0 if record is for several lines - $sql .= " AND numero_compte = '" . $this->db->escape($this->numero_compte) . "'"; - $sql .= " AND label_operation = '" . $this->db->escape($this->label_operation) . "'"; - $sql .= " AND entity IN (" . getEntity('accountancy') . ")"; + $sql .= " AND numero_compte = '".$this->db->escape($this->numero_compte)."'"; + $sql .= " AND label_operation = '".$this->db->escape($this->label_operation)."'"; + $sql .= " AND entity IN (".getEntity('accountancy').")"; $resql = $this->db->query($sql); @@ -272,39 +309,39 @@ class BookKeeping extends CommonObject { // Determine piece_num $sqlnum = "SELECT piece_num"; - $sqlnum .= " FROM " . MAIN_DB_PREFIX . $this->table_element; - $sqlnum .= " WHERE doc_type = '" . $this->db->escape($this->doc_type) . "'"; // For example doc_type = 'bank' - $sqlnum .= " AND fk_docdet = " . $this->db->escape($this->fk_docdet); // fk_docdet is rowid into llx_bank or llx_facturedet or llx_facturefourndet, or ... - $sqlnum .= " AND doc_ref = '" . $this->db->escape($this->doc_ref) . "'"; // ref of source object - $sqlnum .= " AND entity IN (" . getEntity('accountancy') . ")"; + $sqlnum .= " FROM ".MAIN_DB_PREFIX.$this->table_element; + $sqlnum .= " WHERE doc_type = '".$this->db->escape($this->doc_type)."'"; // For example doc_type = 'bank' + $sqlnum .= " AND fk_docdet = ".$this->db->escape($this->fk_docdet); // fk_docdet is rowid into llx_bank or llx_facturedet or llx_facturefourndet, or ... + $sqlnum .= " AND doc_ref = '".$this->db->escape($this->doc_ref)."'"; // ref of source object + $sqlnum .= " AND entity IN (".getEntity('accountancy').")"; - dol_syslog(get_class($this) . ":: create sqlnum=" . $sqlnum, LOG_DEBUG); + dol_syslog(get_class($this).":: create sqlnum=".$sqlnum, LOG_DEBUG); $resqlnum = $this->db->query($sqlnum); if ($resqlnum) { $objnum = $this->db->fetch_object($resqlnum); $this->piece_num = $objnum->piece_num; } - dol_syslog(get_class($this) . ":: create this->piece_num=" . $this->piece_num, LOG_DEBUG); + dol_syslog(get_class($this).":: create this->piece_num=".$this->piece_num, LOG_DEBUG); if (empty($this->piece_num)) { $sqlnum = "SELECT MAX(piece_num)+1 as maxpiecenum"; - $sqlnum .= " FROM " . MAIN_DB_PREFIX . $this->table_element; - $sqlnum .= " WHERE entity IN (" . getEntity('accountancy') . ")"; + $sqlnum .= " FROM ".MAIN_DB_PREFIX.$this->table_element; + $sqlnum .= " WHERE entity IN (".getEntity('accountancy').")"; - dol_syslog(get_class($this) . ":: create sqlnum=" . $sqlnum, LOG_DEBUG); + dol_syslog(get_class($this).":: create sqlnum=".$sqlnum, LOG_DEBUG); $resqlnum = $this->db->query($sqlnum); if ($resqlnum) { $objnum = $this->db->fetch_object($resqlnum); $this->piece_num = $objnum->maxpiecenum; } } - dol_syslog(get_class($this) . ":: create this->piece_num=" . $this->piece_num, LOG_DEBUG); + dol_syslog(get_class($this).":: create this->piece_num=".$this->piece_num, LOG_DEBUG); if (empty($this->piece_num)) { $this->piece_num = 1; } $now = dol_now(); - $sql = "INSERT INTO " . MAIN_DB_PREFIX . $this->table_element . " ("; + $sql = "INSERT INTO ".MAIN_DB_PREFIX.$this->table_element." ("; $sql .= "doc_date"; $sql .= ", date_lim_reglement"; $sql .= ", doc_type"; @@ -329,60 +366,60 @@ class BookKeeping extends CommonObject $sql .= ', entity'; $sql .= ") VALUES ("; $sql .= "'".$this->db->idate($this->doc_date)."'"; - $sql .= ", ".(! isset($this->date_lim_reglement) || dol_strlen($this->date_lim_reglement) == 0 ? 'NULL' : "'".$this->db->idate($this->date_lim_reglement)."'"); - $sql .= ",'" . $this->db->escape($this->doc_type) . "'"; - $sql .= ",'" . $this->db->escape($this->doc_ref) . "'"; - $sql .= "," . $this->fk_doc; - $sql .= "," . $this->fk_docdet; - $sql .= ",'" . $this->db->escape($this->thirdparty_code) . "'"; - $sql .= ",'" . $this->db->escape($this->subledger_account) . "'"; - $sql .= ",'" . $this->db->escape($this->subledger_label) . "'"; - $sql .= ",'" . $this->db->escape($this->numero_compte) . "'"; - $sql .= ",'" . $this->db->escape($this->label_compte) . "'"; - $sql .= ",'" . $this->db->escape($this->label_operation) . "'"; - $sql .= "," . $this->debit; - $sql .= "," . $this->credit; - $sql .= "," . $this->montant; - $sql .= ",'" . $this->db->escape($this->sens) . "'"; - $sql .= ",'" . $this->db->escape($this->fk_user_author) . "'"; + $sql .= ", ".(!isset($this->date_lim_reglement) || dol_strlen($this->date_lim_reglement) == 0 ? 'NULL' : "'".$this->db->idate($this->date_lim_reglement)."'"); + $sql .= ",'".$this->db->escape($this->doc_type)."'"; + $sql .= ",'".$this->db->escape($this->doc_ref)."'"; + $sql .= ",".$this->fk_doc; + $sql .= ",".$this->fk_docdet; + $sql .= ",'".$this->db->escape($this->thirdparty_code)."'"; + $sql .= ",'".$this->db->escape($this->subledger_account)."'"; + $sql .= ",'".$this->db->escape($this->subledger_label)."'"; + $sql .= ",'".$this->db->escape($this->numero_compte)."'"; + $sql .= ",'".$this->db->escape($this->label_compte)."'"; + $sql .= ",'".$this->db->escape($this->label_operation)."'"; + $sql .= ",".$this->debit; + $sql .= ",".$this->credit; + $sql .= ",".$this->montant; + $sql .= ",'".$this->db->escape($this->sens)."'"; + $sql .= ",'".$this->db->escape($this->fk_user_author)."'"; $sql .= ",'".$this->db->idate($now)."'"; - $sql .= ",'" . $this->db->escape($this->code_journal) . "'"; - $sql .= ",'" . $this->db->escape($this->journal_label) . "'"; - $sql .= "," . $this->db->escape($this->piece_num); - $sql .= ", " . (! isset($this->entity) ? $conf->entity : $this->entity); + $sql .= ",'".$this->db->escape($this->code_journal)."'"; + $sql .= ",'".$this->db->escape($this->journal_label)."'"; + $sql .= ",".$this->db->escape($this->piece_num); + $sql .= ", ".(!isset($this->entity) ? $conf->entity : $this->entity); $sql .= ")"; - dol_syslog(get_class($this) . ":: create sql=" . $sql, LOG_DEBUG); + dol_syslog(get_class($this).":: create sql=".$sql, LOG_DEBUG); $resql = $this->db->query($sql); if ($resql) { - $id = $this->db->last_insert_id(MAIN_DB_PREFIX . $this->table_element); + $id = $this->db->last_insert_id(MAIN_DB_PREFIX.$this->table_element); if ($id > 0) { $this->id = $id; $result = 0; } else { $result = -2; - $error ++; - $this->errors[] = 'Error Create Error ' . $result . ' lecture ID'; - dol_syslog(__METHOD__ . ' ' . join(',', $this->errors), LOG_ERR); + $error++; + $this->errors[] = 'Error Create Error '.$result.' lecture ID'; + dol_syslog(__METHOD__.' '.join(',', $this->errors), LOG_ERR); } } else { $result = -1; - $error ++; - $this->errors[] = 'Error ' . $this->db->lasterror(); - dol_syslog(__METHOD__ . ' ' . join(',', $this->errors), LOG_ERR); + $error++; + $this->errors[] = 'Error '.$this->db->lasterror(); + dol_syslog(__METHOD__.' '.join(',', $this->errors), LOG_ERR); } } else { // Already exists $result = -3; $error++; - $this->error='BookkeepingRecordAlreadyExists'; - dol_syslog(__METHOD__ . ' ' . $this->error, LOG_WARNING); + $this->error = 'BookkeepingRecordAlreadyExists'; + dol_syslog(__METHOD__.' '.$this->error, LOG_WARNING); } } else { $result = -5; - $error ++; - $this->errors[] = 'Error ' . $this->db->lasterror(); - dol_syslog(__METHOD__ . ' ' . join(',', $this->errors), LOG_ERR); + $error++; + $this->errors[] = 'Error '.$this->db->lasterror(); + dol_syslog(__METHOD__.' '.join(',', $this->errors), LOG_ERR); } // Uncomment this and change MYOBJECT to your own tag if you @@ -421,45 +458,45 @@ class BookKeeping extends CommonObject global $dolibarr_main_authentication, $dolibarr_main_demo; global $menumanager; - 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 = ''; $companylink = ''; - $label = '' . $langs->trans("Transaction") . ''; - $label.= '
'; - $label.= '' . $langs->trans('Ref') . ': ' . $this->piece_num; + $label = ''.$langs->trans("Transaction").''; + $label .= '
'; + $label .= ''.$langs->trans('Ref').': '.$this->piece_num; $url = DOL_URL_ROOT.'/accountancy/bookkeeping/card.php?piece_num='.$this->piece_num; 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'; + $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=''; + $linkclose = ''; if (empty($notooltip)) { - if (! empty($conf->global->MAIN_OPTIMIZEFORTEXTBROWSER)) + if (!empty($conf->global->MAIN_OPTIMIZEFORTEXTBROWSER)) { - $label=$langs->trans("ShowTransaction"); - $linkclose.=' alt="'.dol_escape_htmltag($label, 1).'"'; + $label = $langs->trans("ShowTransaction"); + $linkclose .= ' alt="'.dol_escape_htmltag($label, 1).'"'; } - $linkclose.=' title="'.dol_escape_htmltag($label, 1).'"'; - $linkclose.=' class="classfortooltip'.($morecss?' '.$morecss:'').'"'; + $linkclose .= ' title="'.dol_escape_htmltag($label, 1).'"'; + $linkclose .= ' class="classfortooltip'.($morecss ? ' '.$morecss : '').'"'; } - else $linkclose = ($morecss?' class="'.$morecss.'"':''); + else $linkclose = ($morecss ? ' class="'.$morecss.'"' : ''); $linkstart = ''; - $linkend=''; + $linkstart .= $linkclose.'>'; + $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->piece_num; + 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->piece_num; $result .= $linkend; //if ($withpicto != 2) $result.=(($addlabel && $this->label) ? $sep . dol_trunc($this->label, ($addlabel > 1 ? $addlabel : 0)) : ''); @@ -551,7 +588,7 @@ class BookKeeping extends CommonObject $this->journal_label = $langs->trans($this->journal_label); // Insert request - $sql = 'INSERT INTO ' . MAIN_DB_PREFIX . $this->table_element . $mode.' ('; + $sql = 'INSERT INTO '.MAIN_DB_PREFIX.$this->table_element.$mode.' ('; $sql .= 'doc_date,'; $sql .= 'date_lim_reglement,'; $sql .= 'doc_type,'; @@ -575,41 +612,41 @@ class BookKeeping extends CommonObject $sql .= 'piece_num,'; $sql .= 'entity'; $sql .= ') VALUES ('; - $sql .= ' ' . (! isset($this->doc_date) || dol_strlen($this->doc_date) == 0 ? 'NULL' : "'".$this->db->idate($this->doc_date)."'") . ','; - $sql .= ' ' . (! isset($this->date_lim_reglement) || dol_strlen($this->date_lim_reglement) == 0 ? 'NULL' : "'" . $this->db->idate($this->date_lim_reglement) . "'") . ','; - $sql .= ' ' . (! isset($this->doc_type) ? 'NULL' : "'" . $this->db->escape($this->doc_type) . "'") . ','; - $sql .= ' ' . (! isset($this->doc_ref) ? 'NULL' : "'" . $this->db->escape($this->doc_ref) . "'") . ','; - $sql .= ' ' . (empty($this->fk_doc) ? '0' : $this->fk_doc) . ','; - $sql .= ' ' . (empty($this->fk_docdet) ? '0' : $this->fk_docdet) . ','; - $sql .= ' ' . (! isset($this->thirdparty_code) ? 'NULL' : "'" . $this->db->escape($this->thirdparty_code) . "'") . ','; - $sql .= ' ' . (! isset($this->subledger_account) ? 'NULL' : "'" . $this->db->escape($this->subledger_account) . "'") . ','; - $sql .= ' ' . (! isset($this->subledger_label) ? 'NULL' : "'" . $this->db->escape($this->subledger_label) . "'") . ','; - $sql .= ' ' . (! isset($this->numero_compte) ? 'NULL' : "'" . $this->db->escape($this->numero_compte) . "'") . ','; - $sql .= ' ' . (! isset($this->label_compte) ? 'NULL' : "'" . $this->db->escape($this->label_compte) . "'") . ','; - $sql .= ' ' . (! isset($this->label_operation) ? 'NULL' : "'" . $this->db->escape($this->label_operation) . "'") . ','; - $sql .= ' ' . (! isset($this->debit) ? 'NULL' : $this->debit ). ','; - $sql .= ' ' . (! isset($this->credit) ? 'NULL' : $this->credit ). ','; - $sql .= ' ' . (! isset($this->montant) ? 'NULL' : $this->montant ). ','; - $sql .= ' ' . (! isset($this->sens) ? 'NULL' : "'" . $this->db->escape($this->sens) . "'") . ','; - $sql .= ' ' . $user->id . ','; - $sql .= ' ' . "'".$this->db->idate($now)."',"; - $sql .= ' ' . (empty($this->code_journal) ? 'NULL' : "'" . $this->db->escape($this->code_journal) . "'") . ','; - $sql .= ' ' . (empty($this->journal_label) ? 'NULL' : "'" . $this->db->escape($this->journal_label) . "'") . ','; - $sql .= ' ' . (empty($this->piece_num) ? 'NULL' : $this->db->escape($this->piece_num)).','; - $sql .= ' ' . (! isset($this->entity) ? $conf->entity : $this->entity); + $sql .= ' '.(!isset($this->doc_date) || dol_strlen($this->doc_date) == 0 ? 'NULL' : "'".$this->db->idate($this->doc_date)."'").','; + $sql .= ' '.(!isset($this->date_lim_reglement) || dol_strlen($this->date_lim_reglement) == 0 ? 'NULL' : "'".$this->db->idate($this->date_lim_reglement)."'").','; + $sql .= ' '.(!isset($this->doc_type) ? 'NULL' : "'".$this->db->escape($this->doc_type)."'").','; + $sql .= ' '.(!isset($this->doc_ref) ? 'NULL' : "'".$this->db->escape($this->doc_ref)."'").','; + $sql .= ' '.(empty($this->fk_doc) ? '0' : $this->fk_doc).','; + $sql .= ' '.(empty($this->fk_docdet) ? '0' : $this->fk_docdet).','; + $sql .= ' '.(!isset($this->thirdparty_code) ? 'NULL' : "'".$this->db->escape($this->thirdparty_code)."'").','; + $sql .= ' '.(!isset($this->subledger_account) ? 'NULL' : "'".$this->db->escape($this->subledger_account)."'").','; + $sql .= ' '.(!isset($this->subledger_label) ? 'NULL' : "'".$this->db->escape($this->subledger_label)."'").','; + $sql .= ' '.(!isset($this->numero_compte) ? 'NULL' : "'".$this->db->escape($this->numero_compte)."'").','; + $sql .= ' '.(!isset($this->label_compte) ? 'NULL' : "'".$this->db->escape($this->label_compte)."'").','; + $sql .= ' '.(!isset($this->label_operation) ? 'NULL' : "'".$this->db->escape($this->label_operation)."'").','; + $sql .= ' '.(!isset($this->debit) ? 'NULL' : $this->debit).','; + $sql .= ' '.(!isset($this->credit) ? 'NULL' : $this->credit).','; + $sql .= ' '.(!isset($this->montant) ? 'NULL' : $this->montant).','; + $sql .= ' '.(!isset($this->sens) ? 'NULL' : "'".$this->db->escape($this->sens)."'").','; + $sql .= ' '.$user->id.','; + $sql .= ' '."'".$this->db->idate($now)."',"; + $sql .= ' '.(empty($this->code_journal) ? 'NULL' : "'".$this->db->escape($this->code_journal)."'").','; + $sql .= ' '.(empty($this->journal_label) ? 'NULL' : "'".$this->db->escape($this->journal_label)."'").','; + $sql .= ' '.(empty($this->piece_num) ? 'NULL' : $this->db->escape($this->piece_num)).','; + $sql .= ' '.(!isset($this->entity) ? $conf->entity : $this->entity); $sql .= ')'; $this->db->begin(); $resql = $this->db->query($sql); - if (! $resql) { - $error ++; - $this->errors[] = 'Error ' . $this->db->lasterror(); - dol_syslog(__METHOD__ . ' ' . join(',', $this->errors), LOG_ERR); + if (!$resql) { + $error++; + $this->errors[] = 'Error '.$this->db->lasterror(); + dol_syslog(__METHOD__.' '.join(',', $this->errors), LOG_ERR); } - if (! $error) { - $this->id = $this->db->last_insert_id(MAIN_DB_PREFIX . $this->table_element . $mode); + if (!$error) { + $this->id = $this->db->last_insert_id(MAIN_DB_PREFIX.$this->table_element.$mode); // Uncomment this and change MYOBJECT to your own tag if you // want this action to call a trigger. @@ -626,7 +663,7 @@ class BookKeeping extends CommonObject if ($error) { $this->db->rollback(); - return - 1 * $error; + return -1 * $error; } else { $this->db->commit(); @@ -673,13 +710,13 @@ class BookKeeping extends CommonObject $sql .= " t.journal_label,"; $sql .= " t.piece_num,"; $sql .= " t.date_creation"; - $sql .= ' FROM ' . MAIN_DB_PREFIX . $this->table_element.$mode. ' as t'; + $sql .= ' FROM '.MAIN_DB_PREFIX.$this->table_element.$mode.' as t'; $sql .= ' WHERE 1 = 1'; - $sql .= " AND entity IN (" . getEntity('accountancy') . ")"; + $sql .= " AND entity IN (".getEntity('accountancy').")"; if (null !== $ref) { - $sql .= ' AND t.ref = ' . '\'' . $ref . '\''; + $sql .= ' AND t.ref = '.'\''.$ref.'\''; } else { - $sql .= ' AND t.rowid = ' . $id; + $sql .= ' AND t.rowid = '.$id; } $resql = $this->db->query($sql); @@ -721,10 +758,10 @@ class BookKeeping extends CommonObject return 0; } } else { - $this->errors[] = 'Error ' . $this->db->lasterror(); - dol_syslog(__METHOD__ . ' ' . join(',', $this->errors), LOG_ERR); + $this->errors[] = 'Error '.$this->db->lasterror(); + dol_syslog(__METHOD__.' '.join(',', $this->errors), LOG_ERR); - return - 1; + return -1; } } @@ -777,21 +814,21 @@ class BookKeeping extends CommonObject $sql .= " t.piece_num,"; $sql .= " t.date_creation"; // Manage filter - $sqlwhere = array (); + $sqlwhere = array(); if (count($filter) > 0) { foreach ($filter as $key => $value) { if ($key == 't.doc_date') { - $sqlwhere[] = $key . '=\'' . $this->db->idate($value) . '\''; + $sqlwhere[] = $key.'=\''.$this->db->idate($value).'\''; } elseif ($key == 't.doc_date>=' || $key == 't.doc_date<=') { - $sqlwhere[] = $key . '\'' . $this->db->idate($value) . '\''; + $sqlwhere[] = $key.'\''.$this->db->idate($value).'\''; } elseif ($key == 't.numero_compte>=' || $key == 't.numero_compte<=' || $key == 't.subledger_account>=' || $key == 't.subledger_account<=') { - $sqlwhere[] = $key . '\'' . $this->db->escape($value) . '\''; + $sqlwhere[] = $key.'\''.$this->db->escape($value).'\''; } elseif ($key == 't.fk_doc' || $key == 't.fk_docdet' || $key == 't.piece_num') { - $sqlwhere[] = $key . '=' . $value; + $sqlwhere[] = $key.'='.$value; } elseif ($key == 't.subledger_account' || $key == 't.numero_compte') { - $sqlwhere[] = $key . ' LIKE \'' . $this->db->escape($value) . '%\''; + $sqlwhere[] = $key.' LIKE \''.$this->db->escape($value).'%\''; } elseif ($key == 't.date_creation>=' || $key == 't.date_creation<=') { - $sqlwhere[] = $key . '\'' . $this->db->idate($value) . '\''; + $sqlwhere[] = $key.'\''.$this->db->idate($value).'\''; } elseif ($key == 't.credit' || $key == 't.debit') { $sqlwhere[] = natural_search($key, $value, 1, 1); } else { @@ -799,19 +836,19 @@ class BookKeeping extends CommonObject } } } - $sql .= ' FROM ' . MAIN_DB_PREFIX . $this->table_element . ' as t'; + $sql .= ' FROM '.MAIN_DB_PREFIX.$this->table_element.' as t'; $sql .= ' WHERE 1 = 1'; - $sql .= " AND entity IN (" . getEntity('accountancy') . ")"; + $sql .= " AND entity IN (".getEntity('accountancy').")"; if (count($sqlwhere) > 0) { - $sql .= ' AND ' . implode(' ' . $filtermode . ' ', $sqlwhere); + $sql .= ' AND '.implode(' '.$filtermode.' ', $sqlwhere); } // Affichage par compte comptable $sql .= ' ORDER BY t.numero_compte ASC'; - if (! empty($sortfield)) { - $sql .= ', ' . $sortfield . ' ' .$sortorder; + if (!empty($sortfield)) { + $sql .= ', '.$sortfield.' '.$sortorder; } - if (! empty($limit)) { - $sql .= ' ' . $this->db->plimit($limit + 1, $offset); + if (!empty($limit)) { + $sql .= ' '.$this->db->plimit($limit + 1, $offset); } $resql = $this->db->query($sql); @@ -858,8 +895,8 @@ class BookKeeping extends CommonObject return $num; } else { - $this->errors[] = 'Error ' . $this->db->lasterror(); - dol_syslog(__METHOD__ . ' ' . join(',', $this->errors), LOG_ERR); + $this->errors[] = 'Error '.$this->db->lasterror(); + dol_syslog(__METHOD__.' '.join(',', $this->errors), LOG_ERR); return -1; } @@ -909,27 +946,27 @@ class BookKeeping extends CommonObject $sql .= " t.date_creation,"; $sql .= " t.tms as date_modification,"; $sql .= " t.date_export"; - $sql .= ' FROM ' . MAIN_DB_PREFIX . $this->table_element . ' as t'; + $sql .= ' FROM '.MAIN_DB_PREFIX.$this->table_element.' as t'; // Manage filter - $sqlwhere = array (); + $sqlwhere = array(); if (count($filter) > 0) { foreach ($filter as $key => $value) { if ($key == 't.doc_date') { - $sqlwhere[] = $key . '=\'' . $this->db->idate($value) . '\''; + $sqlwhere[] = $key.'=\''.$this->db->idate($value).'\''; } elseif ($key == 't.doc_date>=' || $key == 't.doc_date<=') { - $sqlwhere[] = $key . '\'' . $this->db->idate($value) . '\''; + $sqlwhere[] = $key.'\''.$this->db->idate($value).'\''; } elseif ($key == 't.numero_compte>=' || $key == 't.numero_compte<=' || $key == 't.subledger_account>=' || $key == 't.subledger_account<=') { - $sqlwhere[] = $key . '\'' . $this->db->escape($value) . '\''; + $sqlwhere[] = $key.'\''.$this->db->escape($value).'\''; } elseif ($key == 't.fk_doc' || $key == 't.fk_docdet' || $key == 't.piece_num') { - $sqlwhere[] = $key . '=' . $value; + $sqlwhere[] = $key.'='.$value; } elseif ($key == 't.subledger_account' || $key == 't.numero_compte') { - $sqlwhere[] = $key . ' LIKE \'' . $this->db->escape($value) . '%\''; + $sqlwhere[] = $key.' LIKE \''.$this->db->escape($value).'%\''; } elseif ($key == 't.date_creation>=' || $key == 't.date_creation<=') { - $sqlwhere[] = $key . '\'' . $this->db->idate($value) . '\''; + $sqlwhere[] = $key.'\''.$this->db->idate($value).'\''; } elseif ($key == 't.tms>=' || $key == 't.tms<=') { - $sqlwhere[] = $key . '\'' . $this->db->idate($value) . '\''; + $sqlwhere[] = $key.'\''.$this->db->idate($value).'\''; } elseif ($key == 't.date_export>=' || $key == 't.date_export<=') { - $sqlwhere[] = $key . '\'' . $this->db->idate($value) . '\''; + $sqlwhere[] = $key.'\''.$this->db->idate($value).'\''; } elseif ($key == 't.credit' || $key == 't.debit') { $sqlwhere[] = natural_search($key, $value, 1, 1); } else { @@ -937,18 +974,18 @@ class BookKeeping extends CommonObject } } } - $sql.= ' WHERE t.entity IN (' . getEntity('accountancy') . ')'; + $sql .= ' WHERE t.entity IN ('.getEntity('accountancy').')'; if ($showAlreadyExportMovements == 0) { $sql .= " AND t.date_export IS NULL"; } if (count($sqlwhere) > 0) { - $sql .= ' AND ' . implode(' ' . $filtermode . ' ', $sqlwhere); + $sql .= ' AND '.implode(' '.$filtermode.' ', $sqlwhere); } - if (! empty($sortfield)) { + if (!empty($sortfield)) { $sql .= $this->db->order($sortfield, $sortorder); } - if (! empty($limit)) { - $sql .= ' ' . $this->db->plimit($limit + 1, $offset); + if (!empty($limit)) { + $sql .= ' '.$this->db->plimit($limit + 1, $offset); } $this->lines = array(); @@ -996,8 +1033,8 @@ class BookKeeping extends CommonObject return $num; } else { - $this->errors[] = 'Error ' . $this->db->lasterror(); - dol_syslog(__METHOD__ . ' ' . join(',', $this->errors), LOG_ERR); + $this->errors[] = 'Error '.$this->db->lasterror(); + dol_syslog(__METHOD__.' '.join(',', $this->errors), LOG_ERR); return -1; } } @@ -1026,40 +1063,40 @@ class BookKeeping extends CommonObject $sql .= " t.numero_compte,"; $sql .= " SUM(t.debit) as debit,"; $sql .= " SUM(t.credit) as credit"; - $sql .= ' FROM ' . MAIN_DB_PREFIX . $this->table_element . ' as t'; + $sql .= ' FROM '.MAIN_DB_PREFIX.$this->table_element.' as t'; // Manage filter - $sqlwhere = array (); + $sqlwhere = array(); if (count($filter) > 0) { foreach ($filter as $key => $value) { if ($key == 't.doc_date') { - $sqlwhere[] = $key . '=\'' . $this->db->idate($value) . '\''; + $sqlwhere[] = $key.'=\''.$this->db->idate($value).'\''; } elseif ($key == 't.doc_date>=' || $key == 't.doc_date<=') { - $sqlwhere[] = $key . '\'' . $this->db->idate($value) . '\''; + $sqlwhere[] = $key.'\''.$this->db->idate($value).'\''; } elseif ($key == 't.numero_compte>=' || $key == 't.numero_compte<=' || $key == 't.subledger_account>=' || $key == 't.subledger_account<=') { - $sqlwhere[] = $key . '\'' . $this->db->escape($value) . '\''; + $sqlwhere[] = $key.'\''.$this->db->escape($value).'\''; } elseif ($key == 't.fk_doc' || $key == 't.fk_docdet' || $key == 't.piece_num') { - $sqlwhere[] = $key . '=' . $value; + $sqlwhere[] = $key.'='.$value; } elseif ($key == 't.subledger_account' || $key == 't.numero_compte') { - $sqlwhere[] = $key . ' LIKE \'' . $this->db->escape($value) . '%\''; + $sqlwhere[] = $key.' LIKE \''.$this->db->escape($value).'%\''; } elseif ($key == 't.subledger_label') { - $sqlwhere[] = $key . ' LIKE \'' . $this->db->escape($value) . '%\''; + $sqlwhere[] = $key.' LIKE \''.$this->db->escape($value).'%\''; } else { - $sqlwhere[] = $key . ' LIKE \'%' . $this->db->escape($value) . '%\''; + $sqlwhere[] = $key.' LIKE \'%'.$this->db->escape($value).'%\''; } } } - $sql.= ' WHERE entity IN (' . getEntity('accountancy') . ')'; + $sql .= ' WHERE entity IN ('.getEntity('accountancy').')'; if (count($sqlwhere) > 0) { - $sql .= ' AND ' . implode(' ' . $filtermode . ' ', $sqlwhere); + $sql .= ' AND '.implode(' '.$filtermode.' ', $sqlwhere); } $sql .= ' GROUP BY t.numero_compte'; - if (! empty($sortfield)) { + if (!empty($sortfield)) { $sql .= $this->db->order($sortfield, $sortorder); } - if (! empty($limit)) { - $sql .= ' ' . $this->db->plimit($limit + 1, $offset); + if (!empty($limit)) { + $sql .= ' '.$this->db->plimit($limit + 1, $offset); } $resql = $this->db->query($sql); @@ -1084,10 +1121,10 @@ class BookKeeping extends CommonObject return $num; } else { - $this->errors[] = 'Error ' . $this->db->lasterror(); - dol_syslog(__METHOD__ . ' ' . join(',', $this->errors), LOG_ERR); + $this->errors[] = 'Error '.$this->db->lasterror(); + dol_syslog(__METHOD__.' '.join(',', $this->errors), LOG_ERR); - return - 1; + return -1; } } @@ -1168,36 +1205,36 @@ class BookKeeping extends CommonObject // Put here code to add a control on parameters values // Update request - $sql = 'UPDATE ' . MAIN_DB_PREFIX . $this->table_element . $mode.' SET'; - $sql .= ' doc_date = ' . (! isset($this->doc_date) || dol_strlen($this->doc_date) != 0 ? "'".$this->db->idate($this->doc_date)."'" : 'null') . ','; - $sql .= ' doc_type = ' . (isset($this->doc_type) ? "'" . $this->db->escape($this->doc_type) . "'" : "null") . ','; - $sql .= ' doc_ref = ' . (isset($this->doc_ref) ? "'" . $this->db->escape($this->doc_ref) . "'" : "null") . ','; - $sql .= ' fk_doc = ' . (isset($this->fk_doc) ? $this->fk_doc : "null") . ','; - $sql .= ' fk_docdet = ' . (isset($this->fk_docdet) ? $this->fk_docdet : "null") . ','; - $sql .= ' thirdparty_code = ' . (isset($this->thirdparty_code) ? "'" . $this->db->escape($this->thirdparty_code) . "'" : "null") . ','; - $sql .= ' subledger_account = ' . (isset($this->subledger_account) ? "'" . $this->db->escape($this->subledger_account) . "'" : "null") . ','; - $sql .= ' subledger_label = ' . (isset($this->subledger_label) ? "'" . $this->db->escape($this->subledger_label) . "'" : "null") . ','; - $sql .= ' numero_compte = ' . (isset($this->numero_compte) ? "'" . $this->db->escape($this->numero_compte) . "'" : "null") . ','; - $sql .= ' label_compte = ' . (isset($this->label_compte) ? "'" . $this->db->escape($this->label_compte) . "'" : "null") . ','; - $sql .= ' label_operation = ' . (isset($this->label_operation) ? "'" . $this->db->escape($this->label_operation) . "'" : "null") . ','; - $sql .= ' debit = ' . (isset($this->debit) ? $this->debit : "null") . ','; - $sql .= ' credit = ' . (isset($this->credit) ? $this->credit : "null") . ','; - $sql .= ' montant = ' . (isset($this->montant) ? $this->montant : "null") . ','; - $sql .= ' sens = ' . (isset($this->sens) ? "'" . $this->db->escape($this->sens) . "'" : "null") . ','; - $sql .= ' fk_user_author = ' . (isset($this->fk_user_author) ? $this->fk_user_author : "null") . ','; - $sql .= ' import_key = ' . (isset($this->import_key) ? "'" . $this->db->escape($this->import_key) . "'" : "null") . ','; - $sql .= ' code_journal = ' . (isset($this->code_journal) ? "'" . $this->db->escape($this->code_journal) . "'" : "null") . ','; - $sql .= ' journal_label = ' . (isset($this->journal_label) ? "'" . $this->db->escape($this->journal_label) . "'" : "null") . ','; - $sql .= ' piece_num = ' . (isset($this->piece_num) ? $this->piece_num : "null"); - $sql .= ' WHERE rowid=' . $this->id; + $sql = 'UPDATE '.MAIN_DB_PREFIX.$this->table_element.$mode.' SET'; + $sql .= ' doc_date = '.(!isset($this->doc_date) || dol_strlen($this->doc_date) != 0 ? "'".$this->db->idate($this->doc_date)."'" : 'null').','; + $sql .= ' doc_type = '.(isset($this->doc_type) ? "'".$this->db->escape($this->doc_type)."'" : "null").','; + $sql .= ' doc_ref = '.(isset($this->doc_ref) ? "'".$this->db->escape($this->doc_ref)."'" : "null").','; + $sql .= ' fk_doc = '.(isset($this->fk_doc) ? $this->fk_doc : "null").','; + $sql .= ' fk_docdet = '.(isset($this->fk_docdet) ? $this->fk_docdet : "null").','; + $sql .= ' thirdparty_code = '.(isset($this->thirdparty_code) ? "'".$this->db->escape($this->thirdparty_code)."'" : "null").','; + $sql .= ' subledger_account = '.(isset($this->subledger_account) ? "'".$this->db->escape($this->subledger_account)."'" : "null").','; + $sql .= ' subledger_label = '.(isset($this->subledger_label) ? "'".$this->db->escape($this->subledger_label)."'" : "null").','; + $sql .= ' numero_compte = '.(isset($this->numero_compte) ? "'".$this->db->escape($this->numero_compte)."'" : "null").','; + $sql .= ' label_compte = '.(isset($this->label_compte) ? "'".$this->db->escape($this->label_compte)."'" : "null").','; + $sql .= ' label_operation = '.(isset($this->label_operation) ? "'".$this->db->escape($this->label_operation)."'" : "null").','; + $sql .= ' debit = '.(isset($this->debit) ? $this->debit : "null").','; + $sql .= ' credit = '.(isset($this->credit) ? $this->credit : "null").','; + $sql .= ' montant = '.(isset($this->montant) ? $this->montant : "null").','; + $sql .= ' sens = '.(isset($this->sens) ? "'".$this->db->escape($this->sens)."'" : "null").','; + $sql .= ' fk_user_author = '.(isset($this->fk_user_author) ? $this->fk_user_author : "null").','; + $sql .= ' import_key = '.(isset($this->import_key) ? "'".$this->db->escape($this->import_key)."'" : "null").','; + $sql .= ' code_journal = '.(isset($this->code_journal) ? "'".$this->db->escape($this->code_journal)."'" : "null").','; + $sql .= ' journal_label = '.(isset($this->journal_label) ? "'".$this->db->escape($this->journal_label)."'" : "null").','; + $sql .= ' piece_num = '.(isset($this->piece_num) ? $this->piece_num : "null"); + $sql .= ' WHERE rowid='.$this->id; $this->db->begin(); $resql = $this->db->query($sql); - if (! $resql) { - $error ++; - $this->errors[] = 'Error ' . $this->db->lasterror(); - dol_syslog(__METHOD__ . ' ' . join(',', $this->errors), LOG_ERR); + if (!$resql) { + $error++; + $this->errors[] = 'Error '.$this->db->lasterror(); + dol_syslog(__METHOD__.' '.join(',', $this->errors), LOG_ERR); } // Uncomment this and change MYOBJECT to your own tag if you @@ -1214,7 +1251,7 @@ class BookKeeping extends CommonObject if ($error) { $this->db->rollback(); - return - 1 * $error; + return -1 * $error; } else { $this->db->commit(); @@ -1233,19 +1270,19 @@ class BookKeeping extends CommonObject */ public function updateByMvt($piece_num = '', $field = '', $value = '', $mode = '') { - $error=0; + $error = 0; $this->db->begin(); - $sql = "UPDATE " . MAIN_DB_PREFIX . $this->table_element . $mode . " as ab"; - $sql .= ' SET ab.' . $field . '=' . (is_numeric($value)?$value:"'".$this->db->escape($value)."'"); - $sql .= ' WHERE ab.piece_num=' . $piece_num ; + $sql = "UPDATE ".MAIN_DB_PREFIX.$this->table_element.$mode." as ab"; + $sql .= ' SET ab.'.$field.'='.(is_numeric($value) ? $value : "'".$this->db->escape($value)."'"); + $sql .= ' WHERE ab.piece_num='.$piece_num; $resql = $this->db->query($sql); - if (! $resql) { + if (!$resql) { $error++; - $this->errors[] = 'Error ' . $this->db->lasterror(); - dol_syslog(__METHOD__ . ' ' . join(',', $this->errors), LOG_ERR); + $this->errors[] = 'Error '.$this->db->lasterror(); + dol_syslog(__METHOD__.' '.join(',', $this->errors), LOG_ERR); } if ($error) { $this->db->rollback(); @@ -1284,15 +1321,15 @@ class BookKeeping extends CommonObject // // End call triggers //} - if (! $error) { - $sql = 'DELETE FROM ' . MAIN_DB_PREFIX . $this->table_element.$mode; - $sql .= ' WHERE rowid=' . $this->id; + if (!$error) { + $sql = 'DELETE FROM '.MAIN_DB_PREFIX.$this->table_element.$mode; + $sql .= ' WHERE rowid='.$this->id; $resql = $this->db->query($sql); - if (! $resql) { - $error ++; - $this->errors[] = 'Error ' . $this->db->lasterror(); - dol_syslog(__METHOD__ . ' ' . join(',', $this->errors), LOG_ERR); + if (!$resql) { + $error++; + $this->errors[] = 'Error '.$this->db->lasterror(); + dol_syslog(__METHOD__.' '.join(',', $this->errors), LOG_ERR); } } @@ -1300,7 +1337,7 @@ class BookKeeping extends CommonObject if ($error) { $this->db->rollback(); - return - 1 * $error; + return -1 * $error; } else { $this->db->commit(); @@ -1320,16 +1357,16 @@ class BookKeeping extends CommonObject // first check if line not yet in bookkeeping $sql = "DELETE"; - $sql .= " FROM " . MAIN_DB_PREFIX . $this->table_element; - $sql .= " WHERE import_key = '" . $this->db->escape($importkey) . "'"; + $sql .= " FROM ".MAIN_DB_PREFIX.$this->table_element; + $sql .= " WHERE import_key = '".$this->db->escape($importkey)."'"; $resql = $this->db->query($sql); - if (! $resql) { - $this->errors[] = "Error " . $this->db->lasterror(); - dol_syslog(get_class($this)."::delete Error " . $this->db->lasterror(), LOG_ERR); + if (!$resql) { + $this->errors[] = "Error ".$this->db->lasterror(); + dol_syslog(get_class($this)."::delete Error ".$this->db->lasterror(), LOG_ERR); $this->db->rollback(); - return - 1; + return -1; } $this->db->commit(); @@ -1357,18 +1394,18 @@ class BookKeeping extends CommonObject // first check if line not yet in bookkeeping $sql = "DELETE"; - $sql.= " FROM " . MAIN_DB_PREFIX . $this->table_element.$mode; - $sql.= " WHERE 1 = 1"; - if (! empty($delyear)) $sql.= " AND YEAR(doc_date) = " . $delyear; // FIXME Must use between - if (! empty($journal)) $sql.= " AND code_journal = '".$this->db->escape($journal)."'"; - $sql .= " AND entity IN (" . getEntity('accountancy') . ")"; + $sql .= " FROM ".MAIN_DB_PREFIX.$this->table_element.$mode; + $sql .= " WHERE 1 = 1"; + if (!empty($delyear)) $sql .= " AND YEAR(doc_date) = ".$delyear; // FIXME Must use between + if (!empty($journal)) $sql .= " AND code_journal = '".$this->db->escape($journal)."'"; + $sql .= " AND entity IN (".getEntity('accountancy').")"; $resql = $this->db->query($sql); - if (! $resql) { - $this->errors[] = "Error " . $this->db->lasterror(); + if (!$resql) { + $this->errors[] = "Error ".$this->db->lasterror(); foreach ($this->errors as $errmsg) { - dol_syslog(get_class($this) . "::delete " . $errmsg, LOG_ERR); - $this->error .= ($this->error ? ', ' . $errmsg : $errmsg); + dol_syslog(get_class($this)."::delete ".$errmsg, LOG_ERR); + $this->error .= ($this->error ? ', '.$errmsg : $errmsg); } $this->db->rollback(); return -1; @@ -1392,20 +1429,20 @@ class BookKeeping extends CommonObject // first check if line not yet in bookkeeping $sql = "DELETE"; - $sql .= " FROM " . MAIN_DB_PREFIX . $this->table_element; - $sql .= " WHERE piece_num = " . (int) $piecenum; - $sql .= " AND entity IN (" . getEntity('accountancy') . ")"; + $sql .= " FROM ".MAIN_DB_PREFIX.$this->table_element; + $sql .= " WHERE piece_num = ".(int) $piecenum; + $sql .= " AND entity IN (".getEntity('accountancy').")"; $resql = $this->db->query($sql); - if (! $resql) { - $this->errors[] = "Error " . $this->db->lasterror(); + if (!$resql) { + $this->errors[] = "Error ".$this->db->lasterror(); foreach ($this->errors as $errmsg) { - dol_syslog(get_class($this) . "::delete " . $errmsg, LOG_ERR); - $this->error .= ($this->error ? ', ' . $errmsg : $errmsg); + dol_syslog(get_class($this)."::delete ".$errmsg, LOG_ERR); + $this->error .= ($this->error ? ', '.$errmsg : $errmsg); } $this->db->rollback(); - return - 1; + return -1; } $this->db->commit(); @@ -1442,15 +1479,15 @@ class BookKeeping extends CommonObject // Other options if ($result < 0) { - $error ++; + $error++; $this->errors = $object->errors; - dol_syslog(__METHOD__ . ' ' . join(',', $this->errors), LOG_ERR); + dol_syslog(__METHOD__.' '.join(',', $this->errors), LOG_ERR); } unset($object->context['createfromclone']); // End - if (! $error) { + if (!$error) { $this->db->commit(); return $object->id; @@ -1471,7 +1508,7 @@ class BookKeeping extends CommonObject { global $user; - $now=dol_now(); + $now = dol_now(); $this->id = 0; $this->doc_date = $now; @@ -1509,11 +1546,11 @@ class BookKeeping extends CommonObject global $conf; $sql = "SELECT piece_num,doc_date,code_journal,journal_label,doc_ref,doc_type,date_creation"; - $sql .= " FROM " . MAIN_DB_PREFIX . $this->table_element.$mode; - $sql .= " WHERE piece_num = " . $piecenum; - $sql .= " AND entity IN (" . getEntity('accountancy') . ")"; + $sql .= " FROM ".MAIN_DB_PREFIX.$this->table_element.$mode; + $sql .= " WHERE piece_num = ".$piecenum; + $sql .= " AND entity IN (".getEntity('accountancy').")"; - dol_syslog(get_class($this) . "::" . __METHOD__, LOG_DEBUG); + dol_syslog(get_class($this)."::".__METHOD__, LOG_DEBUG); $result = $this->db->query($sql); if ($result) { $obj = $this->db->fetch_object($result); @@ -1526,9 +1563,9 @@ class BookKeeping extends CommonObject $this->doc_type = $obj->doc_type; $this->date_creation = $obj->date_creation; } else { - $this->error = "Error " . $this->db->lasterror(); - dol_syslog(get_class($this) . "::" . __METHOD__ . $this->error, LOG_ERR); - return - 1; + $this->error = "Error ".$this->db->lasterror(); + dol_syslog(get_class($this)."::".__METHOD__.$this->error, LOG_ERR); + return -1; } return 1; @@ -1544,10 +1581,10 @@ class BookKeeping extends CommonObject { global $conf; - $sql = "SELECT MAX(piece_num)+1 as max FROM " . MAIN_DB_PREFIX . $this->table_element.$mode; - $sql .= " WHERE entity IN (" . getEntity('accountancy') . ")"; + $sql = "SELECT MAX(piece_num)+1 as max FROM ".MAIN_DB_PREFIX.$this->table_element.$mode; + $sql .= " WHERE entity IN (".getEntity('accountancy').")"; - dol_syslog(get_class($this) . "getNextNumMvt sql=" . $sql, LOG_DEBUG); + dol_syslog(get_class($this)."getNextNumMvt sql=".$sql, LOG_DEBUG); $result = $this->db->query($sql); if ($result) { @@ -1556,9 +1593,9 @@ class BookKeeping extends CommonObject if (empty($result)) $result = 1; return $result; } else { - $this->error = "Error " . $this->db->lasterror(); - dol_syslog(get_class($this) . "::getNextNumMvt " . $this->error, LOG_ERR); - return - 1; + $this->error = "Error ".$this->db->lasterror(); + dol_syslog(get_class($this)."::getNextNumMvt ".$this->error, LOG_ERR); + return -1; } } @@ -1577,11 +1614,11 @@ class BookKeeping extends CommonObject $sql .= " doc_ref, fk_doc, fk_docdet, thirdparty_code, subledger_account, subledger_label,"; $sql .= " numero_compte, label_compte, label_operation, debit, credit,"; $sql .= " montant, sens, fk_user_author, import_key, code_journal, journal_label, piece_num, date_creation"; - $sql .= " FROM " . MAIN_DB_PREFIX . $this->table_element.$mode; - $sql .= " WHERE piece_num = " . $piecenum; - $sql .= " AND entity IN (" . getEntity('accountancy') . ")"; + $sql .= " FROM ".MAIN_DB_PREFIX.$this->table_element.$mode; + $sql .= " WHERE piece_num = ".$piecenum; + $sql .= " AND entity IN (".getEntity('accountancy').")"; - dol_syslog(get_class($this) . "::" . __METHOD__, LOG_DEBUG); + dol_syslog(get_class($this)."::".__METHOD__, LOG_DEBUG); $result = $this->db->query($sql); if ($result) { while ($obj = $this->db->fetch_object($result)) { @@ -1612,9 +1649,9 @@ class BookKeeping extends CommonObject $this->linesmvt[] = $line; } } else { - $this->error = "Error " . $this->db->lasterror(); - dol_syslog(get_class($this) . "::" . __METHOD__ . $this->error, LOG_ERR); - return - 1; + $this->error = "Error ".$this->db->lasterror(); + dol_syslog(get_class($this)."::".__METHOD__.$this->error, LOG_ERR); + return -1; } return 1; @@ -1636,15 +1673,15 @@ class BookKeeping extends CommonObject $sql .= " doc_ref, fk_doc, fk_docdet, thirdparty_code, subledger_account, subledger_label,"; $sql .= " numero_compte, label_compte, label_operation, debit, credit,"; $sql .= " montant, sens, fk_user_author, import_key, code_journal, piece_num"; - $sql .= " FROM " . MAIN_DB_PREFIX . $this->table_element; - $sql .= " WHERE entity IN (" . getEntity('accountancy') . ")"; + $sql .= " FROM ".MAIN_DB_PREFIX.$this->table_element; + $sql .= " WHERE entity IN (".getEntity('accountancy').")"; - dol_syslog(get_class($this) . "::export_bookkeeping", LOG_DEBUG); + dol_syslog(get_class($this)."::export_bookkeeping", LOG_DEBUG); $resql = $this->db->query($sql); if ($resql) { - $this->linesexport = array (); + $this->linesexport = array(); $num = $this->db->num_rows($resql); while ($obj = $this->db->fetch_object($resql)) { @@ -1676,9 +1713,9 @@ class BookKeeping extends CommonObject return $num; } else { - $this->error = "Error " . $this->db->lasterror(); - dol_syslog(get_class($this) . "::export_bookkeeping " . $this->error, LOG_ERR); - return - 1; + $this->error = "Error ".$this->db->lasterror(); + dol_syslog(get_class($this)."::export_bookkeeping ".$this->error, LOG_ERR); + return -1; } } @@ -1695,45 +1732,45 @@ class BookKeeping extends CommonObject $this->db->begin(); - if ($direction==0) + if ($direction == 0) { - $next_piecenum=$this->getNextNumMvt(); + $next_piecenum = $this->getNextNumMvt(); $now = dol_now(); if ($next_piecenum < 0) { $error++; } - $sql = 'INSERT INTO ' . MAIN_DB_PREFIX . $this->table_element . ' (doc_date, doc_type,'; + $sql = 'INSERT INTO '.MAIN_DB_PREFIX.$this->table_element.' (doc_date, doc_type,'; $sql .= ' doc_ref, fk_doc, fk_docdet, entity, thirdparty_code, subledger_account, subledger_label,'; $sql .= ' numero_compte, label_compte, label_operation, debit, credit,'; $sql .= ' montant, sens, fk_user_author, import_key, code_journal, journal_label, piece_num, date_creation)'; $sql .= ' SELECT doc_date, doc_type,'; $sql .= ' doc_ref, fk_doc, fk_docdet, entity, thirdparty_code, subledger_account, subledger_label,'; $sql .= ' numero_compte, label_compte, label_operation, debit, credit,'; - $sql .= ' montant, sens, fk_user_author, import_key, code_journal, journal_label, ' . $next_piecenum . ", '".$this->db->idate($now)."'"; - $sql .= ' FROM ' . MAIN_DB_PREFIX . $this->table_element . '_tmp WHERE piece_num = ' . $this->db->escape($piece_num); + $sql .= ' montant, sens, fk_user_author, import_key, code_journal, journal_label, '.$next_piecenum.", '".$this->db->idate($now)."'"; + $sql .= ' FROM '.MAIN_DB_PREFIX.$this->table_element.'_tmp WHERE piece_num = '.$this->db->escape($piece_num); $resql = $this->db->query($sql); - if (! $resql) { - $error ++; - $this->errors[] = 'Error ' . $this->db->lasterror(); - dol_syslog(__METHOD__ . ' ' . join(',', $this->errors), LOG_ERR); + if (!$resql) { + $error++; + $this->errors[] = 'Error '.$this->db->lasterror(); + dol_syslog(__METHOD__.' '.join(',', $this->errors), LOG_ERR); } - $sql = 'DELETE FROM ' . MAIN_DB_PREFIX . $this->table_element . '_tmp WHERE piece_num = ' . $this->db->escape($piece_num); + $sql = 'DELETE FROM '.MAIN_DB_PREFIX.$this->table_element.'_tmp WHERE piece_num = '.$this->db->escape($piece_num); $resql = $this->db->query($sql); - if (! $resql) { - $error ++; - $this->errors[] = 'Error ' . $this->db->lasterror(); - dol_syslog(__METHOD__ . ' ' . join(',', $this->errors), LOG_ERR); + if (!$resql) { + $error++; + $this->errors[] = 'Error '.$this->db->lasterror(); + dol_syslog(__METHOD__.' '.join(',', $this->errors), LOG_ERR); } - } elseif ($direction==1) { - $sql = 'DELETE FROM ' . MAIN_DB_PREFIX . $this->table_element . '_tmp WHERE piece_num = ' . $piece_num; + } elseif ($direction == 1) { + $sql = 'DELETE FROM '.MAIN_DB_PREFIX.$this->table_element.'_tmp WHERE piece_num = '.$piece_num; $resql = $this->db->query($sql); - if (! $resql) { - $error ++; - $this->errors[] = 'Error ' . $this->db->lasterror(); - dol_syslog(__METHOD__ . ' ' . join(',', $this->errors), LOG_ERR); + if (!$resql) { + $error++; + $this->errors[] = 'Error '.$this->db->lasterror(); + dol_syslog(__METHOD__.' '.join(',', $this->errors), LOG_ERR); } - $sql = 'INSERT INTO ' . MAIN_DB_PREFIX . $this->table_element . '_tmp (doc_date, doc_type,'; + $sql = 'INSERT INTO '.MAIN_DB_PREFIX.$this->table_element.'_tmp (doc_date, doc_type,'; $sql .= ' doc_ref, fk_doc, fk_docdet, thirdparty_code, subledger_account, subledger_label,'; $sql .= ' numero_compte, label_compte, label_operation, debit, credit,'; $sql .= ' montant, sens, fk_user_author, import_key, code_journal, journal_label, piece_num)'; @@ -1741,27 +1778,27 @@ class BookKeeping extends CommonObject $sql .= ' doc_ref, fk_doc, fk_docdet, thirdparty_code, subledger_account, subledger_label,'; $sql .= ' numero_compte, label_compte, label_operation, debit, credit,'; $sql .= ' montant, sens, fk_user_author, import_key, code_journal, journal_label, piece_num'; - $sql .= ' FROM ' . MAIN_DB_PREFIX . $this->table_element.' WHERE piece_num = ' . $piece_num; + $sql .= ' FROM '.MAIN_DB_PREFIX.$this->table_element.' WHERE piece_num = '.$piece_num; $resql = $this->db->query($sql); - if (! $resql) { - $error ++; - $this->errors[] = 'Error ' . $this->db->lasterror(); - dol_syslog(__METHOD__ . ' ' . join(',', $this->errors), LOG_ERR); + if (!$resql) { + $error++; + $this->errors[] = 'Error '.$this->db->lasterror(); + dol_syslog(__METHOD__.' '.join(',', $this->errors), LOG_ERR); } - $sql = 'DELETE FROM ' . MAIN_DB_PREFIX . $this->table_element . '_tmp WHERE piece_num = ' . $piece_num; + $sql = 'DELETE FROM '.MAIN_DB_PREFIX.$this->table_element.'_tmp WHERE piece_num = '.$piece_num; $resql = $this->db->query($sql); - if (! $resql) { - $error ++; - $this->errors[] = 'Error ' . $this->db->lasterror(); - dol_syslog(__METHOD__ . ' ' . join(',', $this->errors), LOG_ERR); + if (!$resql) { + $error++; + $this->errors[] = 'Error '.$this->db->lasterror(); + dol_syslog(__METHOD__.' '.join(',', $this->errors), LOG_ERR); } } - if (! $error) { + if (!$error) { $this->db->commit(); return 1; } else { $this->db->rollback(); - return - 1; + return -1; } /* $sql = "DELETE FROM "; @@ -1793,26 +1830,26 @@ class BookKeeping extends CommonObject // phpcs:enable global $conf; - require_once DOL_DOCUMENT_ROOT . '/core/lib/accounting.lib.php'; + require_once DOL_DOCUMENT_ROOT.'/core/lib/accounting.lib.php'; $pcgver = $conf->global->CHARTOFACCOUNTS; $sql = "SELECT DISTINCT ab.numero_compte as account_number, aa.label as label, aa.rowid as rowid, aa.fk_pcg_version"; - $sql .= " FROM " . MAIN_DB_PREFIX . "accounting_bookkeeping as ab"; - $sql .= " LEFT JOIN " . MAIN_DB_PREFIX . "accounting_account as aa ON aa.account_number = ab.numero_compte"; + $sql .= " FROM ".MAIN_DB_PREFIX."accounting_bookkeeping as ab"; + $sql .= " LEFT JOIN ".MAIN_DB_PREFIX."accounting_account as aa ON aa.account_number = ab.numero_compte"; $sql .= " AND aa.active = 1"; - $sql .= " INNER JOIN " . MAIN_DB_PREFIX . "accounting_system as asy ON aa.fk_pcg_version = asy.pcg_version"; - $sql .= " AND asy.rowid = " . $pcgver; - $sql .= " AND ab.entity IN (" . getEntity('accountancy') . ")"; + $sql .= " INNER JOIN ".MAIN_DB_PREFIX."accounting_system as asy ON aa.fk_pcg_version = asy.pcg_version"; + $sql .= " AND asy.rowid = ".$pcgver; + $sql .= " AND ab.entity IN (".getEntity('accountancy').")"; $sql .= " ORDER BY account_number ASC"; - dol_syslog(get_class($this) . "::select_account", LOG_DEBUG); + dol_syslog(get_class($this)."::select_account", LOG_DEBUG); $resql = $this->db->query($sql); - if (! $resql) { - $this->error = "Error " . $this->db->lasterror(); - dol_syslog(get_class($this) . "::select_account " . $this->error, LOG_ERR); - return - 1; + if (!$resql) { + $this->error = "Error ".$this->db->lasterror(); + dol_syslog(get_class($this)."::select_account ".$this->error, LOG_ERR); + return -1; } $out = ajax_combobox($htmlname, $event); @@ -1821,7 +1858,7 @@ class BookKeeping extends CommonObject $selected = null; while ($obj = $this->db->fetch_object($resql)) { - $label = length_accountg($obj->account_number) . ' - ' . $obj->label; + $label = length_accountg($obj->account_number).' - '.$obj->label; $select_value_in = $obj->rowid; $select_value_out = $obj->rowid; @@ -1861,17 +1898,17 @@ class BookKeeping extends CommonObject $pcgver = $conf->global->CHARTOFACCOUNTS; $sql = "SELECT root.account_number, root.label as label"; - $sql .= " FROM " . MAIN_DB_PREFIX . "accounting_account as aa"; - $sql .= " INNER JOIN " . MAIN_DB_PREFIX . "accounting_system as asy ON aa.fk_pcg_version = asy.pcg_version"; - $sql .= " AND asy.rowid = " . $pcgver; - $sql .= " LEFT JOIN " . MAIN_DB_PREFIX . "accounting_account as parent ON aa.account_parent = parent.rowid"; - $sql .= " LEFT JOIN " . MAIN_DB_PREFIX . "accounting_account as root ON parent.account_parent = root.rowid"; - $sql .= " WHERE aa.account_number = '" . $account . "'"; + $sql .= " FROM ".MAIN_DB_PREFIX."accounting_account as aa"; + $sql .= " INNER JOIN ".MAIN_DB_PREFIX."accounting_system as asy ON aa.fk_pcg_version = asy.pcg_version"; + $sql .= " AND asy.rowid = ".$pcgver; + $sql .= " LEFT JOIN ".MAIN_DB_PREFIX."accounting_account as parent ON aa.account_parent = parent.rowid"; + $sql .= " LEFT JOIN ".MAIN_DB_PREFIX."accounting_account as root ON parent.account_parent = root.rowid"; + $sql .= " WHERE aa.account_number = '".$account."'"; $sql .= " AND parent.active = 1"; $sql .= " AND root.active = 1"; - $sql .= " AND aa.entity IN (" . getEntity('accountancy') . ")"; + $sql .= " AND aa.entity IN (".getEntity('accountancy').")"; - dol_syslog(get_class($this) . "::select_account sql=" . $sql, LOG_DEBUG); + dol_syslog(get_class($this)."::select_account sql=".$sql, LOG_DEBUG); $resql = $this->db->query($sql); if ($resql) { $obj = ''; @@ -1881,8 +1918,8 @@ class BookKeeping extends CommonObject return $obj->label; } else { - $this->error = "Error " . $this->db->lasterror(); - dol_syslog(__METHOD__ . " " . $this->error, LOG_ERR); + $this->error = "Error ".$this->db->lasterror(); + dol_syslog(__METHOD__." ".$this->error, LOG_ERR); return -1; } @@ -1902,29 +1939,29 @@ class BookKeeping extends CommonObject $pcgver = $conf->global->CHARTOFACCOUNTS; $sql = "SELECT aa.account_number, aa.label, aa.rowid, aa.fk_pcg_version, cat.label as category"; - $sql .= " FROM " . MAIN_DB_PREFIX . "accounting_account as aa "; - $sql .= " INNER JOIN " . MAIN_DB_PREFIX . "accounting_system as asy ON aa.fk_pcg_version = asy.pcg_version"; - $sql .= " AND aa.account_number = '" . $account . "'"; - $sql .= " AND asy.rowid = " . $pcgver; + $sql .= " FROM ".MAIN_DB_PREFIX."accounting_account as aa "; + $sql .= " INNER JOIN ".MAIN_DB_PREFIX."accounting_system as asy ON aa.fk_pcg_version = asy.pcg_version"; + $sql .= " AND aa.account_number = '".$account."'"; + $sql .= " AND asy.rowid = ".$pcgver; $sql .= " AND aa.active = 1"; - $sql .= " LEFT JOIN " . MAIN_DB_PREFIX . "c_accounting_category as cat ON aa.fk_accounting_category = cat.rowid"; - $sql .= " WHERE aa.entity IN (" . getEntity('accountancy') . ")"; + $sql .= " LEFT JOIN ".MAIN_DB_PREFIX."c_accounting_category as cat ON aa.fk_accounting_category = cat.rowid"; + $sql .= " WHERE aa.entity IN (".getEntity('accountancy').")"; - dol_syslog(get_class($this) . "::select_account sql=" . $sql, LOG_DEBUG); + dol_syslog(get_class($this)."::select_account sql=".$sql, LOG_DEBUG); $resql = $this->db->query($sql); if ($resql) { $obj = ''; if ($this->db->num_rows($resql)) { $obj = $this->db->fetch_object($resql); } - if(empty($obj->category)){ + if (empty($obj->category)) { return $obj->label; - }else{ + } else { return $obj->label.' ('.$obj->category.')'; } } else { - $this->error = "Error " . $this->db->lasterror(); - dol_syslog(__METHOD__ . " " . $this->error, LOG_ERR); + $this->error = "Error ".$this->db->lasterror(); + dol_syslog(__METHOD__." ".$this->error, LOG_ERR); return -1; } } @@ -1981,6 +2018,13 @@ class BookKeepingLine */ public $date_creation; + /** + * @var integer|string $date_modification; + */ public $date_modification; + + /** + * @var integer|string $date_export; + */ public $date_export; } diff --git a/htdocs/accountancy/closure/index.php b/htdocs/accountancy/closure/index.php index 599742460ae..39ed325b5fe 100644 --- a/htdocs/accountancy/closure/index.php +++ b/htdocs/accountancy/closure/index.php @@ -23,12 +23,12 @@ */ require '../../main.inc.php'; -require_once DOL_DOCUMENT_ROOT . '/core/lib/date.lib.php'; -require_once DOL_DOCUMENT_ROOT . '/core/lib/accounting.lib.php'; -require_once DOL_DOCUMENT_ROOT . '/accountancy/class/bookkeeping.class.php'; +require_once DOL_DOCUMENT_ROOT.'/core/lib/date.lib.php'; +require_once DOL_DOCUMENT_ROOT.'/core/lib/accounting.lib.php'; +require_once DOL_DOCUMENT_ROOT.'/accountancy/class/bookkeeping.class.php'; // Load translation files required by the page -$langs->loadLangs(array("compta","bills","other","main","accountancy")); +$langs->loadLangs(array("compta", "bills", "other", "main", "accountancy")); // Security check if (empty($conf->accounting->enabled)) { @@ -36,16 +36,16 @@ if (empty($conf->accounting->enabled)) { } if ($user->socid > 0) accessforbidden(); -if (! $user->rights->accounting->fiscalyear->write) +if (!$user->rights->accounting->fiscalyear->write) accessforbidden(); -$month_start= ($conf->global->SOCIETE_FISCAL_MONTH_START?($conf->global->SOCIETE_FISCAL_MONTH_START):1); +$month_start = ($conf->global->SOCIETE_FISCAL_MONTH_START ? ($conf->global->SOCIETE_FISCAL_MONTH_START) : 1); if (GETPOST("year", 'int')) $year_start = GETPOST("year", 'int'); else { $year_start = dol_print_date(dol_now(), '%Y'); - if (dol_print_date(dol_now(), '%m') < $month_start) $year_start--; // If current month is lower that starting fiscal month, we start last year + if (dol_print_date(dol_now(), '%m') < $month_start) $year_start--; // If current month is lower that starting fiscal month, we start last year } $year_end = $year_start + 1; $month_end = $month_start - 1; @@ -69,54 +69,54 @@ $year_current = $year_start; llxHeader('', $langs->trans("Closure")); -$textprevyear = '' . img_previous() . ''; -$textnextyear = ' ' . img_next() . ''; +$textprevyear = ''.img_previous().''; +$textnextyear = ' '.img_next().''; -print load_fiche_titre($langs->trans("Closure") . " " . $textprevyear . " " . $langs->trans("Year") . " " . $year_start . " " . $textnextyear, '', 'title_accountancy'); +print load_fiche_titre($langs->trans("Closure")." ".$textprevyear." ".$langs->trans("Year")." ".$year_start." ".$textnextyear, '', 'title_accountancy'); -print ''.$langs->trans("DescClosure") . '
'; +print ''.$langs->trans("DescClosure").'
'; print '
'; $y = $year_current; -$buttonbind = '' . $langs->trans("ValidateMovements") . ''; +$buttonbind = ''.$langs->trans("ValidateMovements").''; print_barre_liste($langs->trans("OverviewOfMovementsNotValidated"), '', '', '', '', '', '', -1, '', '', 0, $buttonbind, '', 0, 1, 1); print '
'; -print '
'; -for($i = 1; $i <= 12; $i ++) { - $j = $i + ($conf->global->SOCIETE_FISCAL_MONTH_START?$conf->global->SOCIETE_FISCAL_MONTH_START:1) - 1; - if ($j > 12) $j-=12; - print ''; +print '
' . $langs->trans('MonthShort' . str_pad($j, 2, '0', STR_PAD_LEFT)) . '
'; +for ($i = 1; $i <= 12; $i++) { + $j = $i + ($conf->global->SOCIETE_FISCAL_MONTH_START ? $conf->global->SOCIETE_FISCAL_MONTH_START : 1) - 1; + if ($j > 12) $j -= 12; + print ''; } -print ''; +print ''; $sql = "SELECT COUNT(b.rowid) as detail,"; -for($i = 1; $i <= 12; $i ++) { - $j = $i + ($conf->global->SOCIETE_FISCAL_MONTH_START?$conf->global->SOCIETE_FISCAL_MONTH_START:1) - 1; - if ($j > 12) $j-=12; - $sql .= " SUM(" . $db->ifsql('MONTH(b.doc_date)=' . $j, '1', '0') . ") AS month" . str_pad($j, 2, '0', STR_PAD_LEFT) . ","; +for ($i = 1; $i <= 12; $i++) { + $j = $i + ($conf->global->SOCIETE_FISCAL_MONTH_START ? $conf->global->SOCIETE_FISCAL_MONTH_START : 1) - 1; + if ($j > 12) $j -= 12; + $sql .= " SUM(".$db->ifsql('MONTH(b.doc_date)='.$j, '1', '0').") AS month".str_pad($j, 2, '0', STR_PAD_LEFT).","; } $sql .= " COUNT(b.rowid) as total"; -$sql .= " FROM " . MAIN_DB_PREFIX . "accounting_bookkeeping as b"; -$sql .= " WHERE b.doc_date >= '" . $db->idate($search_date_start) . "'"; -$sql .= " AND b.doc_date <= '" . $db->idate($search_date_end) . "'"; -$sql .= " AND b.entity IN (" . getEntity('bookkeeping', 0) . ")"; // We don't share object for accountancy +$sql .= " FROM ".MAIN_DB_PREFIX."accounting_bookkeeping as b"; +$sql .= " WHERE b.doc_date >= '".$db->idate($search_date_start)."'"; +$sql .= " AND b.doc_date <= '".$db->idate($search_date_end)."'"; +$sql .= " AND b.entity IN (".getEntity('bookkeeping', 0).")"; // We don't share object for accountancy -dol_syslog('htdocs/accountancy/closure/index.php sql=' . $sql, LOG_DEBUG); +dol_syslog('htdocs/accountancy/closure/index.php sql='.$sql, LOG_DEBUG); $resql = $db->query($sql); if ($resql) { $num = $db->num_rows($resql); while ($row = $db->fetch_row($resql)) { print ''; - for($i = 1; $i <= 12; $i ++) { - print ''; + for ($i = 1; $i <= 12; $i++) { + print ''; } - print ''; + print ''; print ''; } diff --git a/htdocs/accountancy/closure/validate.php b/htdocs/accountancy/closure/validate.php index 0498e5e2dec..fe7fda5054f 100644 --- a/htdocs/accountancy/closure/validate.php +++ b/htdocs/accountancy/closure/validate.php @@ -23,12 +23,12 @@ */ require '../../main.inc.php'; -require_once DOL_DOCUMENT_ROOT . '/core/lib/date.lib.php'; -require_once DOL_DOCUMENT_ROOT . '/core/lib/accounting.lib.php'; -require_once DOL_DOCUMENT_ROOT . '/accountancy/class/bookkeeping.class.php'; +require_once DOL_DOCUMENT_ROOT.'/core/lib/date.lib.php'; +require_once DOL_DOCUMENT_ROOT.'/core/lib/accounting.lib.php'; +require_once DOL_DOCUMENT_ROOT.'/accountancy/class/bookkeeping.class.php'; // Load translation files required by the page -$langs->loadLangs(array("compta","bills","other","main","accountancy")); +$langs->loadLangs(array("compta", "bills", "other", "main", "accountancy")); // Security check if (empty($conf->accounting->enabled)) { @@ -36,16 +36,16 @@ if (empty($conf->accounting->enabled)) { } if ($user->socid > 0) accessforbidden(); - if (! $user->rights->accounting->fiscalyear->write) + if (!$user->rights->accounting->fiscalyear->write) accessforbidden(); -$month_start= ($conf->global->SOCIETE_FISCAL_MONTH_START?($conf->global->SOCIETE_FISCAL_MONTH_START):1); +$month_start = ($conf->global->SOCIETE_FISCAL_MONTH_START ? ($conf->global->SOCIETE_FISCAL_MONTH_START) : 1); if (GETPOST("year", 'int')) $year_start = GETPOST("year", 'int'); else { $year_start = dol_print_date(dol_now(), '%Y'); - if (dol_print_date(dol_now(), '%m') < $month_start) $year_start--; // If current month is lower that starting fiscal month, we start last year + if (dol_print_date(dol_now(), '%m') < $month_start) $year_start--; // If current month is lower that starting fiscal month, we start last year } $year_end = $year_start + 1; $month_end = $month_start - 1; @@ -68,14 +68,14 @@ if ($action == 'validate') // Update database $db->begin(); - $sql = "UPDATE " . MAIN_DB_PREFIX . "accounting_bookkeeping as b"; - $sql .= " SET b.date_validated = '" . $db->idate($now) . "'"; + $sql = "UPDATE ".MAIN_DB_PREFIX."accounting_bookkeeping as b"; + $sql .= " SET b.date_validated = '".$db->idate($now)."'"; $sql .= ' WHERE b.date_validated IS NULL'; dol_syslog("htdocs/accountancy/closure/validate.php validate", LOG_DEBUG); $resql = $db->query($sql); - if (! $resql1) { - $error ++; + if (!$resql1) { + $error++; $db->rollback(); setEventMessages($db->lasterror(), null, 'errors'); } else { @@ -91,13 +91,13 @@ if ($action == 'validate') llxHeader('', $langs->trans("ValidateMovements")); -$textprevyear = '' . img_previous() . ''; -$textnextyear = ' ' . img_next() . ''; +$textprevyear = ''.img_previous().''; +$textnextyear = ' '.img_next().''; -print load_fiche_titre($langs->trans("ValidateMovements") . " " . $textprevyear . " " . $langs->trans("Year") . " " . $year_start . " " . $textnextyear, '', 'title_accountancy'); +print load_fiche_titre($langs->trans("ValidateMovements")." ".$textprevyear." ".$langs->trans("Year")." ".$year_start." ".$textnextyear, '', 'title_accountancy'); -print $langs->trans("DescValidateMovements") . '
'; +print $langs->trans("DescValidateMovements").'
'; print '
'; @@ -106,40 +106,40 @@ $y = $year_current; print_barre_liste($langs->trans("SelectMonthAndValidate"), '', '', '', '', '', '', -1, '', '', 0, '', 'class="right"', 0, 1, 1); print '
'; -print '
'.$langs->trans('MonthShort'.str_pad($j, 2, '0', STR_PAD_LEFT)).'' . $langs->trans("Total") . '
'.$langs->trans("Total").'
' . $row[$i] . ''.$row[$i].'' . $row[13] . ''.$row[13].'
'; +print '
'; print ''; -for($i = 1; $i <= 12; $i ++) { - $j = $i + ($conf->global->SOCIETE_FISCAL_MONTH_START?$conf->global->SOCIETE_FISCAL_MONTH_START:1) - 1; - if ($j > 12) $j-=12; - print ''; +for ($i = 1; $i <= 12; $i++) { + $j = $i + ($conf->global->SOCIETE_FISCAL_MONTH_START ? $conf->global->SOCIETE_FISCAL_MONTH_START : 1) - 1; + if ($j > 12) $j -= 12; + print ''; } -print ''; +print ''; print ''; $sql = "SELECT COUNT(b.rowid) as detail,"; -for($i = 1; $i <= 12; $i ++) { - $j = $i + ($conf->global->SOCIETE_FISCAL_MONTH_START?$conf->global->SOCIETE_FISCAL_MONTH_START:1) - 1; - if ($j > 12) $j-=12; - $sql .= " SUM(" . $db->ifsql('MONTH(b.doc_date)=' . $j, '1', '0') . ") AS month" . str_pad($j, 2, '0', STR_PAD_LEFT) . ","; +for ($i = 1; $i <= 12; $i++) { + $j = $i + ($conf->global->SOCIETE_FISCAL_MONTH_START ? $conf->global->SOCIETE_FISCAL_MONTH_START : 1) - 1; + if ($j > 12) $j -= 12; + $sql .= " SUM(".$db->ifsql('MONTH(b.doc_date)='.$j, '1', '0').") AS month".str_pad($j, 2, '0', STR_PAD_LEFT).","; } $sql .= " COUNT(b.rowid) as total"; -$sql .= " FROM " . MAIN_DB_PREFIX . "accounting_bookkeeping as b"; -$sql .= " WHERE b.doc_date >= '" . $db->idate($search_date_start) . "'"; -$sql .= " AND b.doc_date <= '" . $db->idate($search_date_end) . "'"; -$sql .= " AND b.entity IN (" . getEntity('bookkeeping', 0) . ")"; // We don't share object for accountancy +$sql .= " FROM ".MAIN_DB_PREFIX."accounting_bookkeeping as b"; +$sql .= " WHERE b.doc_date >= '".$db->idate($search_date_start)."'"; +$sql .= " AND b.doc_date <= '".$db->idate($search_date_end)."'"; +$sql .= " AND b.entity IN (".getEntity('bookkeeping', 0).")"; // We don't share object for accountancy -dol_syslog('htdocs/accountancy/closure/index.php sql=' . $sql, LOG_DEBUG); +dol_syslog('htdocs/accountancy/closure/index.php sql='.$sql, LOG_DEBUG); $resql = $db->query($sql); if ($resql) { $num = $db->num_rows($resql); while ($row = $db->fetch_row($resql)) { - for($i = 1; $i <= 12; $i ++) { - print '' ; + for ($i = 1; $i <= 12; $i++) { + print ''; } - print ''; + print ''; } $db->free($resql); @@ -149,7 +149,7 @@ if ($resql) { print ''; print "
' . $langs->trans('MonthShort' . str_pad($j, 2, '0', STR_PAD_LEFT)) . ''.$langs->trans('MonthShort'.str_pad($j, 2, '0', STR_PAD_LEFT)).'' . $langs->trans("Total") . '
'.$langs->trans("Total").'
' . $row[$i] . '

'; - print ''; - print '
'.$row[$i].'

'; + print ''; + print '
' . $row[13] . ''.$row[13].'
\n"; -print '
'; +print '
'; print '
'; // End of page diff --git a/htdocs/accountancy/customer/card.php b/htdocs/accountancy/customer/card.php index 62ae458d283..eb7156eee82 100644 --- a/htdocs/accountancy/customer/card.php +++ b/htdocs/accountancy/customer/card.php @@ -24,11 +24,11 @@ */ require '../../main.inc.php'; -require_once DOL_DOCUMENT_ROOT . '/compta/facture/class/facture.class.php'; -require_once DOL_DOCUMENT_ROOT . '/core/class/html.formaccounting.class.php'; +require_once DOL_DOCUMENT_ROOT.'/compta/facture/class/facture.class.php'; +require_once DOL_DOCUMENT_ROOT.'/core/class/html.formaccounting.class.php'; // Load translation files required by the page -$langs->loadLangs(array("bills","accountancy")); +$langs->loadLangs(array("bills", "accountancy")); $action = GETPOST('action', 'alpha'); $cancel = GETPOST('cancel', 'alpha'); @@ -48,16 +48,16 @@ if ($user->socid > 0) if ($action == 'ventil' && $user->rights->accounting->bind->write) { - if (! $cancel) + if (!$cancel) { if ($codeventil < 0) $codeventil = 0; - $sql = " UPDATE " . MAIN_DB_PREFIX . "facturedet"; - $sql .= " SET fk_code_ventilation = " . $codeventil; - $sql .= " WHERE rowid = " . $id; + $sql = " UPDATE ".MAIN_DB_PREFIX."facturedet"; + $sql .= " SET fk_code_ventilation = ".$codeventil; + $sql .= " WHERE rowid = ".$id; $resql = $db->query($sql); - if (! $resql) { + if (!$resql) { setEventMessages($db->lasterror(), null, 'errors'); } else @@ -93,18 +93,18 @@ $form = new Form($db); $facture_static = new Facture($db); $formaccounting = new FormAccounting($db); -if (! empty($id)) { +if (!empty($id)) { $sql = "SELECT f.ref, f.rowid as facid, l.fk_product, l.description, l.price,"; $sql .= " l.qty, l.rowid, l.tva_tx, l.remise_percent, l.subprice, p.accountancy_code_sell as code_sell,"; $sql .= " l.fk_code_ventilation, aa.account_number, aa.label"; - $sql .= " FROM " . MAIN_DB_PREFIX . "facturedet as l"; - $sql .= " LEFT JOIN " . MAIN_DB_PREFIX . "product as p ON p.rowid = l.fk_product"; - $sql .= " LEFT JOIN " . MAIN_DB_PREFIX . "accounting_account as aa ON l.fk_code_ventilation = aa.rowid"; - $sql .= " INNER JOIN " . MAIN_DB_PREFIX . "facture as f ON f.rowid = l.fk_facture"; - $sql .= " WHERE f.fk_statut > 0 AND l.rowid = " . $id; - $sql .= " AND f.entity IN (" . getEntity('invoice', 0) . ")"; // We don't share object for accountancy + $sql .= " FROM ".MAIN_DB_PREFIX."facturedet as l"; + $sql .= " LEFT JOIN ".MAIN_DB_PREFIX."product as p ON p.rowid = l.fk_product"; + $sql .= " LEFT JOIN ".MAIN_DB_PREFIX."accounting_account as aa ON l.fk_code_ventilation = aa.rowid"; + $sql .= " INNER JOIN ".MAIN_DB_PREFIX."facture as f ON f.rowid = l.fk_facture"; + $sql .= " WHERE f.fk_statut > 0 AND l.rowid = ".$id; + $sql .= " AND f.entity IN (".getEntity('invoice', 0).")"; // We don't share object for accountancy - dol_syslog("/accounting/customer/card.php sql=" . $sql, LOG_DEBUG); + dol_syslog("/accounting/customer/card.php sql=".$sql, LOG_DEBUG); $result = $db->query($sql); if ($result) { @@ -114,8 +114,8 @@ if (! empty($id)) { if ($num_lines) { $objp = $db->fetch_object($result); - print '' . "\n"; - print ''; + print ''."\n"; + print ''; print ''; print ''; @@ -123,18 +123,18 @@ if (! empty($id)) { dol_fiche_head(); - print ''; + print '
'; // Ref facture - print ''; + print ''; $facture_static->ref = $objp->ref; $facture_static->id = $objp->facid; - print ''; + print ''; print ''; - print ''; - print ''; - print ''; + print ''; + print ''; print '
' . $langs->trans("Invoice") . '
'.$langs->trans("Invoice").'' . $facture_static->getNomUrl(1) . ''.$facture_static->getNomUrl(1).'
' . $langs->trans("Line") . '' . nl2br($objp->description) . '
' . $langs->trans("Account") . ''; + print '
'.$langs->trans("Line").''.nl2br($objp->description).'
'.$langs->trans("Account").''; print $formaccounting->select_account($objp->fk_code_ventilation, 'codeventil', 1); print '
'; @@ -142,9 +142,9 @@ if (! empty($id)) { dol_fiche_end(); print '
'; - print ''; + print ''; print '     '; - print ''; + print ''; print '
'; print ''; diff --git a/htdocs/accountancy/customer/index.php b/htdocs/accountancy/customer/index.php index b3ef45c1feb..49bda732640 100644 --- a/htdocs/accountancy/customer/index.php +++ b/htdocs/accountancy/customer/index.php @@ -27,13 +27,13 @@ */ require '../../main.inc.php'; -require_once DOL_DOCUMENT_ROOT . '/core/lib/date.lib.php'; -require_once DOL_DOCUMENT_ROOT . '/core/lib/accounting.lib.php'; -require_once DOL_DOCUMENT_ROOT . '/core/lib/company.lib.php'; -require_once DOL_DOCUMENT_ROOT . '/compta/facture/class/facture.class.php'; +require_once DOL_DOCUMENT_ROOT.'/core/lib/date.lib.php'; +require_once DOL_DOCUMENT_ROOT.'/core/lib/accounting.lib.php'; +require_once DOL_DOCUMENT_ROOT.'/core/lib/company.lib.php'; +require_once DOL_DOCUMENT_ROOT.'/compta/facture/class/facture.class.php'; // Load translation files required by the page -$langs->loadLangs(array("compta","bills","other","main","accountancy")); +$langs->loadLangs(array("compta", "bills", "other", "main", "accountancy")); // Security check if (empty($conf->accounting->enabled)) { @@ -41,16 +41,16 @@ if (empty($conf->accounting->enabled)) { } if ($user->socid > 0) accessforbidden(); -if (! $user->rights->accounting->bind->write) +if (!$user->rights->accounting->bind->write) accessforbidden(); -$month_start= ($conf->global->SOCIETE_FISCAL_MONTH_START?($conf->global->SOCIETE_FISCAL_MONTH_START):1); +$month_start = ($conf->global->SOCIETE_FISCAL_MONTH_START ? ($conf->global->SOCIETE_FISCAL_MONTH_START) : 1); if (GETPOST("year", 'int')) $year_start = GETPOST("year", 'int'); else { $year_start = dol_print_date(dol_now(), '%Y'); - if (dol_print_date(dol_now(), '%m') < $month_start) $year_start--; // If current month is lower that starting fiscal month, we start last year + if (dol_print_date(dol_now(), '%m') < $month_start) $year_start--; // If current month is lower that starting fiscal month, we start last year } $year_end = $year_start + 1; $month_end = $month_start - 1; @@ -77,20 +77,20 @@ if ($action == 'clean' || $action == 'validatehistory') { // Clean database $db->begin(); - $sql1 = "UPDATE " . MAIN_DB_PREFIX . "facturedet as fd"; + $sql1 = "UPDATE ".MAIN_DB_PREFIX."facturedet as fd"; $sql1 .= " SET fk_code_ventilation = 0"; $sql1 .= ' WHERE fd.fk_code_ventilation NOT IN'; $sql1 .= ' (SELECT accnt.rowid '; - $sql1 .= ' FROM ' . MAIN_DB_PREFIX . 'accounting_account as accnt'; - $sql1 .= ' INNER JOIN ' . MAIN_DB_PREFIX . 'accounting_system as syst'; - $sql1 .= ' ON accnt.fk_pcg_version = syst.pcg_version AND syst.rowid=' . $conf->global->CHARTOFACCOUNTS . ' AND accnt.entity = '.$conf->entity.')'; - $sql1 .= ' AND fd.fk_facture IN (SELECT rowid FROM ' . MAIN_DB_PREFIX . 'facture WHERE entity = '.$conf->entity.')'; + $sql1 .= ' FROM '.MAIN_DB_PREFIX.'accounting_account as accnt'; + $sql1 .= ' INNER JOIN '.MAIN_DB_PREFIX.'accounting_system as syst'; + $sql1 .= ' ON accnt.fk_pcg_version = syst.pcg_version AND syst.rowid='.$conf->global->CHARTOFACCOUNTS.' AND accnt.entity = '.$conf->entity.')'; + $sql1 .= ' AND fd.fk_facture IN (SELECT rowid FROM '.MAIN_DB_PREFIX.'facture WHERE entity = '.$conf->entity.')'; $sql1 .= ' AND fk_code_ventilation <> 0'; dol_syslog("htdocs/accountancy/customer/index.php fixaccountancycode", LOG_DEBUG); $resql1 = $db->query($sql1); - if (! $resql1) { - $error ++; + if (!$resql1) { + $error++; $db->rollback(); setEventMessages($db->lasterror(), null, 'errors'); } else { @@ -121,26 +121,26 @@ if ($action == 'validatehistory') { // Customer Invoice lines (must be same request than into page list.php for manual binding) $sql = "SELECT f.rowid as facid, f.ref as ref, f.datef, f.type as ftype,"; - $sql.= " l.rowid, l.fk_product, l.description, l.total_ht, l.fk_code_ventilation, l.product_type as type_l, l.tva_tx as tva_tx_line, l.vat_src_code,"; - $sql.= " p.rowid as product_id, p.ref as product_ref, p.label as product_label, p.fk_product_type as type, p.accountancy_code_sell as code_sell, p.tva_tx as tva_tx_prod,"; - $sql.= " p.accountancy_code_sell_intra as code_sell_intra, p.accountancy_code_sell_export as code_sell_export,"; - $sql.= " aa.rowid as aarowid, aa2.rowid as aarowid_intra, aa3.rowid as aarowid_export,"; - $sql.= " co.code as country_code, co.label as country_label,"; - $sql.= " s.tva_intra"; - $sql.= " FROM " . MAIN_DB_PREFIX . "facture as f"; - $sql.= " INNER JOIN " . MAIN_DB_PREFIX . "societe as s ON s.rowid = f.fk_soc"; - $sql.= " LEFT JOIN " . MAIN_DB_PREFIX . "c_country as co ON co.rowid = s.fk_pays "; - $sql.= " INNER JOIN " . MAIN_DB_PREFIX . "facturedet as l ON f.rowid = l.fk_facture"; - $sql.= " LEFT JOIN " . MAIN_DB_PREFIX . "product as p ON p.rowid = l.fk_product"; - $sql.= " LEFT JOIN " . MAIN_DB_PREFIX . "accounting_account as aa ON p.accountancy_code_sell = aa.account_number AND aa.active = 1 AND aa.fk_pcg_version = '" . $chartaccountcode."' AND aa.entity = " . $conf->entity; - $sql.= " LEFT JOIN " . MAIN_DB_PREFIX . "accounting_account as aa2 ON p.accountancy_code_sell_intra = aa2.account_number AND aa2.active = 1 AND aa2.fk_pcg_version = '" . $chartaccountcode."' AND aa2.entity = " . $conf->entity; - $sql.= " LEFT JOIN " . MAIN_DB_PREFIX . "accounting_account as aa3 ON p.accountancy_code_sell_export = aa3.account_number AND aa3.active = 1 AND aa3.fk_pcg_version = '" . $chartaccountcode."' AND aa3.entity = " . $conf->entity; - $sql.= " WHERE f.fk_statut > 0 AND l.fk_code_ventilation <= 0"; - $sql.= " AND l.product_type <= 2"; + $sql .= " l.rowid, l.fk_product, l.description, l.total_ht, l.fk_code_ventilation, l.product_type as type_l, l.tva_tx as tva_tx_line, l.vat_src_code,"; + $sql .= " p.rowid as product_id, p.ref as product_ref, p.label as product_label, p.fk_product_type as type, p.accountancy_code_sell as code_sell, p.tva_tx as tva_tx_prod,"; + $sql .= " p.accountancy_code_sell_intra as code_sell_intra, p.accountancy_code_sell_export as code_sell_export,"; + $sql .= " aa.rowid as aarowid, aa2.rowid as aarowid_intra, aa3.rowid as aarowid_export,"; + $sql .= " co.code as country_code, co.label as country_label,"; + $sql .= " s.tva_intra"; + $sql .= " FROM ".MAIN_DB_PREFIX."facture as f"; + $sql .= " INNER JOIN ".MAIN_DB_PREFIX."societe as s ON s.rowid = f.fk_soc"; + $sql .= " LEFT JOIN ".MAIN_DB_PREFIX."c_country as co ON co.rowid = s.fk_pays "; + $sql .= " INNER JOIN ".MAIN_DB_PREFIX."facturedet as l ON f.rowid = l.fk_facture"; + $sql .= " LEFT JOIN ".MAIN_DB_PREFIX."product as p ON p.rowid = l.fk_product"; + $sql .= " LEFT JOIN ".MAIN_DB_PREFIX."accounting_account as aa ON p.accountancy_code_sell = aa.account_number AND aa.active = 1 AND aa.fk_pcg_version = '".$chartaccountcode."' AND aa.entity = ".$conf->entity; + $sql .= " LEFT JOIN ".MAIN_DB_PREFIX."accounting_account as aa2 ON p.accountancy_code_sell_intra = aa2.account_number AND aa2.active = 1 AND aa2.fk_pcg_version = '".$chartaccountcode."' AND aa2.entity = ".$conf->entity; + $sql .= " LEFT JOIN ".MAIN_DB_PREFIX."accounting_account as aa3 ON p.accountancy_code_sell_export = aa3.account_number AND aa3.active = 1 AND aa3.fk_pcg_version = '".$chartaccountcode."' AND aa3.entity = ".$conf->entity; + $sql .= " WHERE f.fk_statut > 0 AND l.fk_code_ventilation <= 0"; + $sql .= " AND l.product_type <= 2"; dol_syslog('htdocs/accountancy/customer/index.php'); $result = $db->query($sql); - if (! $result) { + if (!$result) { $error++; setEventMessages($db->lasterror(), null, 'errors'); } else { @@ -172,12 +172,12 @@ if ($action == 'validatehistory') { if ($objp->aarowid_suggest > 0) { - $sqlupdate = "UPDATE " . MAIN_DB_PREFIX . "facturedet"; - $sqlupdate.= " SET fk_code_ventilation = ".$objp->aarowid_suggest; - $sqlupdate.= " WHERE fk_code_ventilation <= 0 AND product_type <= 2 AND rowid = ".$objp->rowid; + $sqlupdate = "UPDATE ".MAIN_DB_PREFIX."facturedet"; + $sqlupdate .= " SET fk_code_ventilation = ".$objp->aarowid_suggest; + $sqlupdate .= " WHERE fk_code_ventilation <= 0 AND product_type <= 2 AND rowid = ".$objp->rowid; $resqlupdate = $db->query($sqlupdate); - if (! $resqlupdate) + if (!$resqlupdate) { $error++; setEventMessages($db->lasterror(), null, 'errors'); @@ -206,64 +206,64 @@ if ($action == 'validatehistory') { llxHeader('', $langs->trans("CustomersVentilation")); -$textprevyear = '' . img_previous() . ''; -$textnextyear = ' ' . img_next() . ''; +$textprevyear = ''.img_previous().''; +$textnextyear = ' '.img_next().''; -print load_fiche_titre($langs->trans("CustomersVentilation") . " " . $textprevyear . " " . $langs->trans("Year") . " " . $year_start . " " . $textnextyear, '', 'title_accountancy'); +print load_fiche_titre($langs->trans("CustomersVentilation")." ".$textprevyear." ".$langs->trans("Year")." ".$year_start." ".$textnextyear, '', 'title_accountancy'); -print ''.$langs->trans("DescVentilCustomer") . '
'; -print $langs->trans("DescVentilMore", $langs->transnoentitiesnoconv("ValidateHistory"), $langs->transnoentitiesnoconv("ToBind")) . '
'; +print ''.$langs->trans("DescVentilCustomer").'
'; +print $langs->trans("DescVentilMore", $langs->transnoentitiesnoconv("ValidateHistory"), $langs->transnoentitiesnoconv("ToBind")).'
'; print '

'; $y = $year_current; -$buttonbind = '' . $langs->trans("ValidateHistory") . ''; +$buttonbind = ''.$langs->trans("ValidateHistory").''; print_barre_liste($langs->trans("OverviewOfAmountOfLinesNotBound"), '', '', '', '', '', '', -1, '', '', 0, $buttonbind, '', 0, 1, 1); //print load_fiche_titre($langs->trans("OverviewOfAmountOfLinesNotBound"), $buttonbind, ''); print '
'; -print ''; -print ''; -print ''; -for($i = 1; $i <= 12; $i ++) { - $j = $i + ($conf->global->SOCIETE_FISCAL_MONTH_START?$conf->global->SOCIETE_FISCAL_MONTH_START:1) - 1; - if ($j > 12) $j-=12; - print ''; +print '
' . $langs->trans("Account") . '' . $langs->trans("Label") . '' . $langs->trans('MonthShort' . str_pad($j, 2, '0', STR_PAD_LEFT)) . '
'; +print ''; +print ''; +for ($i = 1; $i <= 12; $i++) { + $j = $i + ($conf->global->SOCIETE_FISCAL_MONTH_START ? $conf->global->SOCIETE_FISCAL_MONTH_START : 1) - 1; + if ($j > 12) $j -= 12; + print ''; } -print ''; +print ''; -$sql = "SELECT " . $db->ifsql('aa.account_number IS NULL', "'tobind'", 'aa.account_number') . " AS codecomptable,"; -$sql .= " " . $db->ifsql('aa.label IS NULL', "'tobind'", 'aa.label') . " AS intitule,"; -for($i = 1; $i <= 12; $i ++) { - $j = $i + ($conf->global->SOCIETE_FISCAL_MONTH_START?$conf->global->SOCIETE_FISCAL_MONTH_START:1) - 1; - if ($j > 12) $j-=12; - $sql .= " SUM(" . $db->ifsql('MONTH(f.datef)=' . $j, 'fd.total_ht', '0') . ") AS month" . str_pad($j, 2, '0', STR_PAD_LEFT) . ","; +$sql = "SELECT ".$db->ifsql('aa.account_number IS NULL', "'tobind'", 'aa.account_number')." AS codecomptable,"; +$sql .= " ".$db->ifsql('aa.label IS NULL', "'tobind'", 'aa.label')." AS intitule,"; +for ($i = 1; $i <= 12; $i++) { + $j = $i + ($conf->global->SOCIETE_FISCAL_MONTH_START ? $conf->global->SOCIETE_FISCAL_MONTH_START : 1) - 1; + if ($j > 12) $j -= 12; + $sql .= " SUM(".$db->ifsql('MONTH(f.datef)='.$j, 'fd.total_ht', '0').") AS month".str_pad($j, 2, '0', STR_PAD_LEFT).","; } $sql .= " SUM(fd.total_ht) as total"; -$sql .= " FROM " . MAIN_DB_PREFIX . "facturedet as fd"; -$sql .= " LEFT JOIN " . MAIN_DB_PREFIX . "facture as f ON f.rowid = fd.fk_facture"; -$sql .= " LEFT JOIN " . MAIN_DB_PREFIX . "accounting_account as aa ON aa.rowid = fd.fk_code_ventilation"; -$sql .= " WHERE f.datef >= '" . $db->idate($search_date_start) . "'"; -$sql .= " AND f.datef <= '" . $db->idate($search_date_end) . "'"; +$sql .= " FROM ".MAIN_DB_PREFIX."facturedet as fd"; +$sql .= " LEFT JOIN ".MAIN_DB_PREFIX."facture as f ON f.rowid = fd.fk_facture"; +$sql .= " LEFT JOIN ".MAIN_DB_PREFIX."accounting_account as aa ON aa.rowid = fd.fk_code_ventilation"; +$sql .= " WHERE f.datef >= '".$db->idate($search_date_start)."'"; +$sql .= " AND f.datef <= '".$db->idate($search_date_end)."'"; $sql .= " AND f.fk_statut > 0"; -$sql .= " AND f.entity IN (" . getEntity('invoice', 0) . ")"; // We don't share object for accountancy +$sql .= " AND f.entity IN (".getEntity('invoice', 0).")"; // We don't share object for accountancy $sql .= " AND aa.account_number IS NULL"; -if (! empty($conf->global->FACTURE_DEPOSITS_ARE_JUST_PAYMENTS)) { - $sql .= " AND f.type IN (" . Facture::TYPE_STANDARD . "," . Facture::TYPE_REPLACEMENT . "," . Facture::TYPE_CREDIT_NOTE . "," . Facture::TYPE_SITUATION . ")"; +if (!empty($conf->global->FACTURE_DEPOSITS_ARE_JUST_PAYMENTS)) { + $sql .= " AND f.type IN (".Facture::TYPE_STANDARD.",".Facture::TYPE_REPLACEMENT.",".Facture::TYPE_CREDIT_NOTE.",".Facture::TYPE_SITUATION.")"; } else { - $sql .= " AND f.type IN (" . Facture::TYPE_STANDARD . "," . Facture::TYPE_REPLACEMENT . "," . Facture::TYPE_CREDIT_NOTE . "," . Facture::TYPE_DEPOSIT . "," . Facture::TYPE_SITUATION . ")"; + $sql .= " AND f.type IN (".Facture::TYPE_STANDARD.",".Facture::TYPE_REPLACEMENT.",".Facture::TYPE_CREDIT_NOTE.",".Facture::TYPE_DEPOSIT.",".Facture::TYPE_SITUATION.")"; } $sql .= " GROUP BY fd.fk_code_ventilation,aa.account_number,aa.label"; -dol_syslog('htdocs/accountancy/customer/index.php sql=' . $sql, LOG_DEBUG); +dol_syslog('htdocs/accountancy/customer/index.php sql='.$sql, LOG_DEBUG); $resql = $db->query($sql); if ($resql) { $num = $db->num_rows($resql); - while ( $row = $db->fetch_row($resql)) { + while ($row = $db->fetch_row($resql)) { print ''; - for($i = 2; $i <= 12; $i ++) { - print ''; + for ($i = 2; $i <= 12; $i++) { + print ''; } - print ''; - print ''; + print ''; + print ''; print ''; } $db->free($resql); @@ -300,35 +300,35 @@ print_barre_liste($langs->trans("OverviewOfAmountOfLinesBound"), '', '', '', '', //print load_fiche_titre($langs->trans("OverviewOfAmountOfLinesBound"), '', ''); print '
'; -print '
'.$langs->trans("Account").''.$langs->trans("Label").''.$langs->trans('MonthShort'.str_pad($j, 2, '0', STR_PAD_LEFT)).'' . $langs->trans("Total") . '
'.$langs->trans("Total").'
'; if ($row[0] == 'tobind') { @@ -278,11 +278,11 @@ if ($resql) { } else print $row[1]; print '' . price($row[$i]) . ''.price($row[$i]).'' . price($row[13]) . '' . price($row[14]) . ''.price($row[13]).''.price($row[14]).'
'; -print ''; -print ''; -for($i = 1; $i <= 12; $i ++) { - $j = $i + ($conf->global->SOCIETE_FISCAL_MONTH_START?$conf->global->SOCIETE_FISCAL_MONTH_START:1) - 1; - if ($j > 12) $j-=12; - print ''; +print '
' . $langs->trans("Account") . '' . $langs->trans("Label") . '' . $langs->trans('MonthShort' . str_pad($j, 2, '0', STR_PAD_LEFT)) . '
'; +print ''; +print ''; +for ($i = 1; $i <= 12; $i++) { + $j = $i + ($conf->global->SOCIETE_FISCAL_MONTH_START ? $conf->global->SOCIETE_FISCAL_MONTH_START : 1) - 1; + if ($j > 12) $j -= 12; + print ''; } -print ''; +print ''; -$sql = "SELECT " . $db->ifsql('aa.account_number IS NULL', "'tobind'", 'aa.account_number') . " AS codecomptable,"; -$sql .= " " . $db->ifsql('aa.label IS NULL', "'tobind'", 'aa.label') . " AS intitule,"; -for($i = 1; $i <= 12; $i ++) { - $j = $i + ($conf->global->SOCIETE_FISCAL_MONTH_START?$conf->global->SOCIETE_FISCAL_MONTH_START:1) - 1; - if ($j > 12) $j-=12; - $sql .= " SUM(" . $db->ifsql('MONTH(f.datef)=' . $j, 'fd.total_ht', '0') . ") AS month" . str_pad($j, 2, '0', STR_PAD_LEFT) . ","; +$sql = "SELECT ".$db->ifsql('aa.account_number IS NULL', "'tobind'", 'aa.account_number')." AS codecomptable,"; +$sql .= " ".$db->ifsql('aa.label IS NULL', "'tobind'", 'aa.label')." AS intitule,"; +for ($i = 1; $i <= 12; $i++) { + $j = $i + ($conf->global->SOCIETE_FISCAL_MONTH_START ? $conf->global->SOCIETE_FISCAL_MONTH_START : 1) - 1; + if ($j > 12) $j -= 12; + $sql .= " SUM(".$db->ifsql('MONTH(f.datef)='.$j, 'fd.total_ht', '0').") AS month".str_pad($j, 2, '0', STR_PAD_LEFT).","; } $sql .= " SUM(fd.total_ht) as total"; -$sql .= " FROM " . MAIN_DB_PREFIX . "facturedet as fd"; -$sql .= " LEFT JOIN " . MAIN_DB_PREFIX . "facture as f ON f.rowid = fd.fk_facture"; -$sql .= " LEFT JOIN " . MAIN_DB_PREFIX . "accounting_account as aa ON aa.rowid = fd.fk_code_ventilation"; -$sql .= " WHERE f.datef >= '" . $db->idate($search_date_start) . "'"; -$sql .= " AND f.datef <= '" . $db->idate($search_date_end) . "'"; -$sql .= " AND f.entity IN (" . getEntity('invoice', 0) . ")"; // We don't share object for accountancy +$sql .= " FROM ".MAIN_DB_PREFIX."facturedet as fd"; +$sql .= " LEFT JOIN ".MAIN_DB_PREFIX."facture as f ON f.rowid = fd.fk_facture"; +$sql .= " LEFT JOIN ".MAIN_DB_PREFIX."accounting_account as aa ON aa.rowid = fd.fk_code_ventilation"; +$sql .= " WHERE f.datef >= '".$db->idate($search_date_start)."'"; +$sql .= " AND f.datef <= '".$db->idate($search_date_end)."'"; +$sql .= " AND f.entity IN (".getEntity('invoice', 0).")"; // We don't share object for accountancy $sql .= " AND f.fk_statut > 0"; -if (! empty($conf->global->FACTURE_DEPOSITS_ARE_JUST_PAYMENTS)) { - $sql .= " AND f.type IN (" . Facture::TYPE_STANDARD . "," . Facture::TYPE_REPLACEMENT . "," . Facture::TYPE_CREDIT_NOTE . "," . Facture::TYPE_SITUATION . ")"; +if (!empty($conf->global->FACTURE_DEPOSITS_ARE_JUST_PAYMENTS)) { + $sql .= " AND f.type IN (".Facture::TYPE_STANDARD.",".Facture::TYPE_REPLACEMENT.",".Facture::TYPE_CREDIT_NOTE.",".Facture::TYPE_SITUATION.")"; } else { - $sql .= " AND f.type IN (" . Facture::TYPE_STANDARD . "," . Facture::TYPE_REPLACEMENT . "," . Facture::TYPE_CREDIT_NOTE . "," . Facture::TYPE_DEPOSIT . "," . Facture::TYPE_SITUATION . ")"; + $sql .= " AND f.type IN (".Facture::TYPE_STANDARD.",".Facture::TYPE_REPLACEMENT.",".Facture::TYPE_CREDIT_NOTE.",".Facture::TYPE_DEPOSIT.",".Facture::TYPE_SITUATION.")"; } $sql .= " AND aa.account_number IS NOT NULL"; $sql .= " GROUP BY fd.fk_code_ventilation,aa.account_number,aa.label"; @@ -338,7 +338,7 @@ $resql = $db->query($sql); if ($resql) { $num = $db->num_rows($resql); - while ( $row = $db->fetch_row($resql)) { + while ($row = $db->fetch_row($resql)) { print ''; - for($i = 2; $i <= 12; $i++) { - print ''; + for ($i = 2; $i <= 12; $i++) { + print ''; } - print ''; - print ''; + print ''; + print ''; print ''; } $db->free($resql); @@ -379,32 +379,32 @@ if ($conf->global->MAIN_FEATURES_LEVEL > 0) // This part of code looks strange. //print load_fiche_titre($langs->trans("OtherInfo"), '', ''); print '
'; - print '
'.$langs->trans("Account").''.$langs->trans("Label").''.$langs->trans('MonthShort'.str_pad($j, 2, '0', STR_PAD_LEFT)).'' . $langs->trans("Total") . '
'.$langs->trans("Total").'
'; if ($row[0] == 'tobind') { @@ -355,11 +355,11 @@ if ($resql) { else print $row[1]; print '' . price($row[$i]) . ''.price($row[$i]).'' . price($row[13]) . '' . price($row[14]) . ''.price($row[13]).''.price($row[14]).'
'; - print ''; - for($i = 1; $i <= 12; $i ++) { - $j = $i + ($conf->global->SOCIETE_FISCAL_MONTH_START?$conf->global->SOCIETE_FISCAL_MONTH_START:1) - 1; - if ($j > 12) $j-=12; - print ''; + print '
' . $langs->trans("TotalVente") . '' . $langs->trans('MonthShort' . str_pad($j, 2, '0', STR_PAD_LEFT)) . '
'; + print ''; + for ($i = 1; $i <= 12; $i++) { + $j = $i + ($conf->global->SOCIETE_FISCAL_MONTH_START ? $conf->global->SOCIETE_FISCAL_MONTH_START : 1) - 1; + if ($j > 12) $j -= 12; + print ''; } - print ''; + print ''; - $sql = "SELECT '" . $langs->trans("TotalVente") . "' AS total,"; - for($i = 1; $i <= 12; $i ++) { - $j = $i + ($conf->global->SOCIETE_FISCAL_MONTH_START?$conf->global->SOCIETE_FISCAL_MONTH_START:1) - 1; - if ($j > 12) $j-=12; - $sql .= " SUM(" . $db->ifsql('MONTH(f.datef)=' . $j, 'fd.total_ht', '0') . ") AS month" . str_pad($j, 2, '0', STR_PAD_LEFT) . ","; + $sql = "SELECT '".$langs->trans("TotalVente")."' AS total,"; + for ($i = 1; $i <= 12; $i++) { + $j = $i + ($conf->global->SOCIETE_FISCAL_MONTH_START ? $conf->global->SOCIETE_FISCAL_MONTH_START : 1) - 1; + if ($j > 12) $j -= 12; + $sql .= " SUM(".$db->ifsql('MONTH(f.datef)='.$j, 'fd.total_ht', '0').") AS month".str_pad($j, 2, '0', STR_PAD_LEFT).","; } $sql .= " SUM(fd.total_ht) as total"; - $sql .= " FROM " . MAIN_DB_PREFIX . "facturedet as fd"; - $sql .= " LEFT JOIN " . MAIN_DB_PREFIX . "facture as f ON f.rowid = fd.fk_facture"; - $sql .= " WHERE f.datef >= '" . $db->idate($search_date_start) . "'"; - $sql .= " AND f.datef <= '" . $db->idate($search_date_end) . "'"; - $sql .= " AND f.entity IN (" . getEntity('invoice', 0) . ")"; // We don't share object for accountancy + $sql .= " FROM ".MAIN_DB_PREFIX."facturedet as fd"; + $sql .= " LEFT JOIN ".MAIN_DB_PREFIX."facture as f ON f.rowid = fd.fk_facture"; + $sql .= " WHERE f.datef >= '".$db->idate($search_date_start)."'"; + $sql .= " AND f.datef <= '".$db->idate($search_date_end)."'"; + $sql .= " AND f.entity IN (".getEntity('invoice', 0).")"; // We don't share object for accountancy $sql .= " AND f.fk_statut > 0"; - if (! empty($conf->global->FACTURE_DEPOSITS_ARE_JUST_PAYMENTS)) { - $sql .= " AND f.type IN (" . Facture::TYPE_STANDARD . "," . Facture::TYPE_REPLACEMENT . "," . Facture::TYPE_CREDIT_NOTE . "," . Facture::TYPE_SITUATION . ")"; + if (!empty($conf->global->FACTURE_DEPOSITS_ARE_JUST_PAYMENTS)) { + $sql .= " AND f.type IN (".Facture::TYPE_STANDARD.",".Facture::TYPE_REPLACEMENT.",".Facture::TYPE_CREDIT_NOTE.",".Facture::TYPE_SITUATION.")"; } else { - $sql .= " AND f.type IN (" . Facture::TYPE_STANDARD . "," . Facture::TYPE_REPLACEMENT . "," . Facture::TYPE_CREDIT_NOTE . "," . Facture::TYPE_DEPOSIT . "," . Facture::TYPE_SITUATION . ")"; + $sql .= " AND f.type IN (".Facture::TYPE_STANDARD.",".Facture::TYPE_REPLACEMENT.",".Facture::TYPE_CREDIT_NOTE.",".Facture::TYPE_DEPOSIT.",".Facture::TYPE_SITUATION.")"; } dol_syslog('htdocs/accountancy/customer/index.php'); @@ -413,11 +413,11 @@ if ($conf->global->MAIN_FEATURES_LEVEL > 0) // This part of code looks strange. $num = $db->num_rows($resql); while ($row = $db->fetch_row($resql)) { - print ''; - for($i = 1; $i <= 12; $i ++) { - print ''; + print ''; + for ($i = 1; $i <= 12; $i++) { + print ''; } - print ''; + print ''; print ''; } $db->free($resql); @@ -428,35 +428,35 @@ if ($conf->global->MAIN_FEATURES_LEVEL > 0) // This part of code looks strange. print ''; - if (! empty($conf->margin->enabled)) { + if (!empty($conf->margin->enabled)) { print "
\n"; print '
'; - print '
'.$langs->trans("TotalVente").''.$langs->trans('MonthShort'.str_pad($j, 2, '0', STR_PAD_LEFT)).'' . $langs->trans("Total") . '
'.$langs->trans("Total").'
' . $row[0] . '' . price($row[$i]) . '
'.$row[0].''.price($row[$i]).'' . price($row[13]) . ''.price($row[13]).'
'; - print ''; - for($i = 1; $i <= 12; $i ++) { - $j = $i + ($conf->global->SOCIETE_FISCAL_MONTH_START?$conf->global->SOCIETE_FISCAL_MONTH_START:1) - 1; - if ($j > 12) $j-=12; - print ''; + print '
' . $langs->trans("TotalMarge") . '' . $langs->trans('MonthShort' . str_pad($j, 2, '0', STR_PAD_LEFT)) . '
'; + print ''; + for ($i = 1; $i <= 12; $i++) { + $j = $i + ($conf->global->SOCIETE_FISCAL_MONTH_START ? $conf->global->SOCIETE_FISCAL_MONTH_START : 1) - 1; + if ($j > 12) $j -= 12; + print ''; } - print ''; + print ''; - $sql = "SELECT '" . $langs->trans("Vide") . "' AS marge,"; - for($i = 1; $i <= 12; $i ++) { - $j = $i + ($conf->global->SOCIETE_FISCAL_MONTH_START?$conf->global->SOCIETE_FISCAL_MONTH_START:1) - 1; - if ($j > 12) $j-=12; - $sql .= " SUM(" . $db->ifsql('MONTH(f.datef)=' . $j, '(fd.total_ht-(fd.qty * fd.buy_price_ht))', '0') . ") AS month" . str_pad($j, 2, '0', STR_PAD_LEFT) . ","; + $sql = "SELECT '".$langs->trans("Vide")."' AS marge,"; + for ($i = 1; $i <= 12; $i++) { + $j = $i + ($conf->global->SOCIETE_FISCAL_MONTH_START ? $conf->global->SOCIETE_FISCAL_MONTH_START : 1) - 1; + if ($j > 12) $j -= 12; + $sql .= " SUM(".$db->ifsql('MONTH(f.datef)='.$j, '(fd.total_ht-(fd.qty * fd.buy_price_ht))', '0').") AS month".str_pad($j, 2, '0', STR_PAD_LEFT).","; } $sql .= " SUM((fd.total_ht-(fd.qty * fd.buy_price_ht))) as total"; - $sql .= " FROM " . MAIN_DB_PREFIX . "facturedet as fd"; - $sql .= " LEFT JOIN " . MAIN_DB_PREFIX . "facture as f ON f.rowid = fd.fk_facture"; - $sql .= " WHERE f.datef >= '" . $db->idate($search_date_start) . "'"; - $sql .= " AND f.datef <= '" . $db->idate($search_date_end) . "'"; - $sql .= " AND f.entity IN (" . getEntity('invoice', 0) . ")"; // We don't share object for accountancy + $sql .= " FROM ".MAIN_DB_PREFIX."facturedet as fd"; + $sql .= " LEFT JOIN ".MAIN_DB_PREFIX."facture as f ON f.rowid = fd.fk_facture"; + $sql .= " WHERE f.datef >= '".$db->idate($search_date_start)."'"; + $sql .= " AND f.datef <= '".$db->idate($search_date_end)."'"; + $sql .= " AND f.entity IN (".getEntity('invoice', 0).")"; // We don't share object for accountancy $sql .= " AND f.fk_statut > 0"; - if (! empty($conf->global->FACTURE_DEPOSITS_ARE_JUST_PAYMENTS)) { - $sql .= " AND f.type IN (" . Facture::TYPE_STANDARD . "," . Facture::TYPE_REPLACEMENT . "," . Facture::TYPE_CREDIT_NOTE . "," . Facture::TYPE_SITUATION . ")"; + if (!empty($conf->global->FACTURE_DEPOSITS_ARE_JUST_PAYMENTS)) { + $sql .= " AND f.type IN (".Facture::TYPE_STANDARD.",".Facture::TYPE_REPLACEMENT.",".Facture::TYPE_CREDIT_NOTE.",".Facture::TYPE_SITUATION.")"; } else { - $sql .= " AND f.type IN (" . Facture::TYPE_STANDARD . "," . Facture::TYPE_REPLACEMENT . "," . Facture::TYPE_CREDIT_NOTE . "," . Facture::TYPE_DEPOSIT . "," . Facture::TYPE_SITUATION . ")"; + $sql .= " AND f.type IN (".Facture::TYPE_STANDARD.",".Facture::TYPE_REPLACEMENT.",".Facture::TYPE_CREDIT_NOTE.",".Facture::TYPE_DEPOSIT.",".Facture::TYPE_SITUATION.")"; } dol_syslog('htdocs/accountancy/customer/index.php'); @@ -465,11 +465,11 @@ if ($conf->global->MAIN_FEATURES_LEVEL > 0) // This part of code looks strange. $num = $db->num_rows($resql); while ($row = $db->fetch_row($resql)) { - print ''; - for($i = 1; $i <= 12; $i ++) { - print ''; + print ''; + for ($i = 1; $i <= 12; $i++) { + print ''; } - print ''; + print ''; print ''; } $db->free($resql); diff --git a/htdocs/accountancy/customer/lines.php b/htdocs/accountancy/customer/lines.php index 9d32bbaebf4..10742b863d2 100644 --- a/htdocs/accountancy/customer/lines.php +++ b/htdocs/accountancy/customer/lines.php @@ -26,16 +26,16 @@ */ require '../../main.inc.php'; -require_once DOL_DOCUMENT_ROOT . '/core/class/html.formaccounting.class.php'; -require_once DOL_DOCUMENT_ROOT . '/compta/facture/class/facture.class.php'; -require_once DOL_DOCUMENT_ROOT . '/product/class/product.class.php'; -require_once DOL_DOCUMENT_ROOT . '/core/lib/accounting.lib.php'; -require_once DOL_DOCUMENT_ROOT . '/core/class/html.formother.class.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.'/core/class/html.formaccounting.class.php'; +require_once DOL_DOCUMENT_ROOT.'/compta/facture/class/facture.class.php'; +require_once DOL_DOCUMENT_ROOT.'/product/class/product.class.php'; +require_once DOL_DOCUMENT_ROOT.'/core/lib/accounting.lib.php'; +require_once DOL_DOCUMENT_ROOT.'/core/class/html.formother.class.php'; +require_once DOL_DOCUMENT_ROOT.'/core/lib/date.lib.php'; +require_once DOL_DOCUMENT_ROOT.'/core/lib/company.lib.php'; // Load translation files required by the page -$langs->loadLangs(array("bills","compta","accountancy","productbatch")); +$langs->loadLangs(array("bills", "compta", "accountancy", "productbatch")); $account_parent = GETPOST('account_parent'); $changeaccount = GETPOST('changeaccount'); @@ -48,14 +48,14 @@ $search_desc = GETPOST('search_desc', 'alpha'); $search_amount = GETPOST('search_amount', 'alpha'); $search_account = GETPOST('search_account', 'alpha'); $search_vat = GETPOST('search_vat', 'alpha'); -$search_day=GETPOST("search_day", "int"); -$search_month=GETPOST("search_month", "int"); -$search_year=GETPOST("search_year", "int"); +$search_day = GETPOST("search_day", "int"); +$search_month = GETPOST("search_month", "int"); +$search_year = GETPOST("search_year", "int"); $search_country = GETPOST('search_country', 'alpha'); $search_tvaintra = GETPOST('search_tvaintra', 'alpha'); // Load variable for pagination -$limit = GETPOST('limit', 'int')?GETPOST('limit', 'int'):(empty($conf->global->ACCOUNTING_LIMIT_LIST_VENTILATION)?$conf->liste_limit:$conf->global->ACCOUNTING_LIMIT_LIST_VENTILATION); +$limit = GETPOST('limit', 'int') ?GETPOST('limit', 'int') : (empty($conf->global->ACCOUNTING_LIMIT_LIST_VENTILATION) ? $conf->liste_limit : $conf->global->ACCOUNTING_LIMIT_LIST_VENTILATION); $sortfield = GETPOST('sortfield', 'alpha'); $sortorder = GETPOST('sortorder', 'alpha'); $page = GETPOST('page', 'int'); @@ -63,9 +63,9 @@ if (empty($page) || $page < 0) $page = 0; $pageprev = $page - 1; $pagenext = $page + 1; $offset = $limit * $page; -if (! $sortfield) +if (!$sortfield) $sortfield = "f.datef, f.ref, fd.rowid"; -if (! $sortorder) { +if (!$sortorder) { if ($conf->global->ACCOUNTING_LIST_SORT_VENTILATION_DONE > 0) { $sortorder = "DESC"; } @@ -74,7 +74,7 @@ if (! $sortorder) { // Security check if ($user->socid > 0) accessforbidden(); -if (! $user->rights->accounting->bind->write) +if (!$user->rights->accounting->bind->write) accessforbidden(); $formaccounting = new FormAccounting($db); @@ -105,27 +105,27 @@ if (GETPOST('button_removefilter_x', 'alpha') || GETPOST('button_removefilter.x' if (is_array($changeaccount) && count($changeaccount) > 0) { $error = 0; - if (! (GETPOST('account_parent', 'int') >= 0)) + if (!(GETPOST('account_parent', 'int') >= 0)) { $error++; setEventMessages($langs->trans("ErrorFieldRequired", $langs->transnoentitiesnoconv("Account")), null, 'errors'); } - if (! $error) + if (!$error) { $db->begin(); - $sql1 = "UPDATE " . MAIN_DB_PREFIX . "facturedet as l"; - $sql1 .= " SET l.fk_code_ventilation=" . (GETPOST('account_parent', 'int') > 0 ? GETPOST('account_parent', 'int') : '0'); - $sql1 .= ' WHERE l.rowid IN (' . implode(',', $changeaccount) . ')'; + $sql1 = "UPDATE ".MAIN_DB_PREFIX."facturedet as l"; + $sql1 .= " SET l.fk_code_ventilation=".(GETPOST('account_parent', 'int') > 0 ? GETPOST('account_parent', 'int') : '0'); + $sql1 .= ' WHERE l.rowid IN ('.implode(',', $changeaccount).')'; - dol_syslog('accountancy/customer/lines.php::changeaccount sql= ' . $sql1); + dol_syslog('accountancy/customer/lines.php::changeaccount sql= '.$sql1); $resql1 = $db->query($sql1); - if (! $resql1) { - $error ++; + if (!$resql1) { + $error++; setEventMessages($db->lasterror(), null, 'errors'); } - if (! $error) { + if (!$error) { $db->commit(); setEventMessages($langs->trans('Save'), null, 'mesgs'); } else { @@ -133,7 +133,7 @@ if (is_array($changeaccount) && count($changeaccount) > 0) { setEventMessages($db->lasterror(), null, 'errors'); } - $account_parent = ''; // Protection to avoid to mass apply it a second time + $account_parent = ''; // Protection to avoid to mass apply it a second time } } @@ -145,7 +145,7 @@ if (is_array($changeaccount) && count($changeaccount) > 0) { $form = new Form($db); $formother = new FormOther($db); -llxHeader('', $langs->trans("CustomersVentilation") . ' - ' . $langs->trans("Dispatched")); +llxHeader('', $langs->trans("CustomersVentilation").' - '.$langs->trans("Dispatched")); print ''."\n"; @@ -523,9 +523,9 @@ if ($object->id > 0 && (empty($action) || ($action != 'edit' && $action != 'crea print ''; print ''; // List filters - foreach($object->filters as $rulefilter) + foreach ($object->filters as $rulefilter) { - $rulefilterobj=new EmailCollectorFilter($db); + $rulefilterobj = new EmailCollectorFilter($db); $rulefilterobj->fetch($rulefilter['id']); print ''; @@ -552,16 +552,16 @@ if ($object->id > 0 && (empty($action) || ($action != 'edit' && $action != 'crea // Add operation print ''; print ''; @@ -571,11 +571,11 @@ if ($object->id > 0 && (empty($action) || ($action != 'edit' && $action != 'crea // List operations $nboflines = count($object->actions); $table_element_line = 'emailcollector_emailcollectoraction'; - $fk_element='position'; - $i=0; - foreach($object->actions as $ruleaction) + $fk_element = 'position'; + $i = 0; + foreach ($object->actions as $ruleaction) { - $ruleactionobj=new EmailcollectorAction($db); + $ruleactionobj = new EmailcollectorAction($db); $ruleactionobj->fetch($ruleaction['id']); print ''; @@ -604,7 +604,7 @@ if ($object->id > 0 && (empty($action) || ($action != 'edit' && $action != 'crea { print ''.img_up('default', 0, 'imgupforline').''; } - if ($i < count($object->actions)-1) { + if ($i < count($object->actions) - 1) { print ''.img_down('default', 0, 'imgdownforline').''; } print ''; @@ -620,15 +620,15 @@ if ($object->id > 0 && (empty($action) || ($action != 'edit' && $action != 'crea print ''; print '
'.$langs->trans("TotalMarge").''.$langs->trans('MonthShort'.str_pad($j, 2, '0', STR_PAD_LEFT)).'' . $langs->trans("Total") . '
'.$langs->trans("Total").'
' . $row[0] . '' . price(price2num($row[$i])) . '
'.$row[0].''.price(price2num($row[$i])).'' . price(price2num($row[13])) . ''.price(price2num($row[13])).'
'; - $arrayoftypes=array( + $arrayoftypes = array( 'loadthirdparty'=>$langs->trans('LoadThirdPartyFromName', $langs->transnoentities("ThirdPartyName")), 'loadandcreatethirdparty'=>$langs->trans('LoadThirdPartyFromNameOrCreate', $langs->transnoentities("ThirdPartyName")), 'recordevent'=>'RecordEvent'); - if ($conf->projet->enabled) $arrayoftypes['project']='CreateLeadAndThirdParty'; - if ($conf->ticket->enabled) $arrayoftypes['ticket']='CreateTicketAndThirdParty'; + if ($conf->projet->enabled) $arrayoftypes['project'] = 'CreateLeadAndThirdParty'; + if ($conf->ticket->enabled) $arrayoftypes['ticket'] = 'CreateTicketAndThirdParty'; print $form->selectarray('operationtype', $arrayoftypes, '', 1, 0, 0, '', 1, 0, 0, '', 'maxwidth300'); print ''; print ''; - $htmltext=$langs->transnoentitiesnoconv("OperationParamDesc"); + $htmltext = $langs->transnoentitiesnoconv("OperationParamDesc"); //var_dump($htmltext); print $form->textwithpicto('', $htmltext); print '
'; - if (! empty($conf->use_javascript_ajax)) { + if (!empty($conf->use_javascript_ajax)) { $urltorefreshaftermove = DOL_URL_ROOT.'/admin/emailcollector_card.php?id='.$id; - include DOL_DOCUMENT_ROOT . '/core/tpl/ajaxrow.tpl.php'; + include DOL_DOCUMENT_ROOT.'/core/tpl/ajaxrow.tpl.php'; } print ''; print '
'; - print ''; // End
+ print '
'; // End
print '

'; @@ -637,26 +637,26 @@ if ($object->id > 0 && (empty($action) || ($action != 'edit' && $action != 'crea // Buttons for actions if ($action != 'presend' && $action != 'editline') { - print '
' . "\n"; + print '
'."\n"; $parameters = array(); $reshook = $hookmanager->executeHooks('addMoreActionsButtons', $parameters, $object, $action); // Note that $action and $object may have been modified by hook if ($reshook < 0) setEventMessages($hookmanager->error, $hookmanager->errors, 'errors'); if (empty($reshook)) { - print ''; + print ''; // Clone - print ''; + print ''; - print ''; + print ''; - print ''; + print ''; } - print '
' . "\n"; + print '
'."\n"; } - if (! empty($debuginfo)) + if (!empty($debuginfo)) { print info_admin($debuginfo); } diff --git a/htdocs/admin/emailcollector_list.php b/htdocs/admin/emailcollector_list.php index 9cb83e3784b..add400b6aef 100644 --- a/htdocs/admin/emailcollector_list.php +++ b/htdocs/admin/emailcollector_list.php @@ -26,9 +26,9 @@ require_once DOL_DOCUMENT_ROOT.'/core/lib/admin.lib.php'; require_once DOL_DOCUMENT_ROOT.'/core/lib/agenda.lib.php'; require_once DOL_DOCUMENT_ROOT.'/core/class/events.class.php'; -require_once DOL_DOCUMENT_ROOT . '/core/class/html.formcompany.class.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.'/core/class/html.formcompany.class.php'; +require_once DOL_DOCUMENT_ROOT.'/core/lib/date.lib.php'; +require_once DOL_DOCUMENT_ROOT.'/core/lib/company.lib.php'; dol_include_once('/emailcollector/class/emailcollector.class.php'); if (!$user->admin) accessforbidden(); @@ -37,20 +37,20 @@ if (empty($conf->emailcollector->enabled)) accessforbidden(); // Load traductions files required by page $langs->loadLangs(array("admin", "other")); -$action = GETPOST('action', 'aZ09')?GETPOST('action', 'aZ09'):'view'; // The action 'add', 'create', 'edit', 'update', 'view', ... -$massaction = GETPOST('massaction', 'alpha'); // The bulk action (combo box choice into lists) -$show_files = GETPOST('show_files', 'int'); // Show files area generated by bulk actions ? -$confirm = GETPOST('confirm', 'alpha'); // Result of a confirmation -$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'):'emailcollectorlist'; // 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') +$action = GETPOST('action', 'aZ09') ?GETPOST('action', 'aZ09') : 'view'; // The action 'add', 'create', 'edit', 'update', 'view', ... +$massaction = GETPOST('massaction', 'alpha'); // The bulk action (combo box choice into lists) +$show_files = GETPOST('show_files', 'int'); // Show files area generated by bulk actions ? +$confirm = GETPOST('confirm', 'alpha'); // Result of a confirmation +$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') : 'emailcollectorlist'; // 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') -$id = GETPOST('id', 'int'); +$id = GETPOST('id', 'int'); // Load variable for pagination -$limit = GETPOST('limit', 'int')?GETPOST('limit', 'int'):$conf->liste_limit; +$limit = GETPOST('limit', 'int') ?GETPOST('limit', 'int') : $conf->liste_limit; $sortfield = GETPOST('sortfield', 'alpha'); $sortorder = GETPOST('sortorder', 'alpha'); $page = GETPOST('page', 'int'); @@ -64,7 +64,7 @@ $pagenext = $page + 1; // Initialize technical objects $object = new EmailCollector($db); $extrafields = new ExtraFields($db); -$diroutputmassaction = $conf->emailcollector->dir_output . '/temp/massgeneration/' . $user->id; +$diroutputmassaction = $conf->emailcollector->dir_output.'/temp/massgeneration/'.$user->id; $hookmanager->initHooks(array('emailcollectorlist')); // Note that conf->hooks_modules contains array // Fetch optionals attributes and labels @@ -73,11 +73,11 @@ $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 -$socid=0; +$socid = 0; if ($user->socid > 0) // Protection if external user { //$socid = $user->socid; @@ -86,34 +86,34 @@ if ($user->socid > 0) // Protection if external user //$result = restrictedArea($user, 'emailcollector', $id, ''); // Initialize array of search criterias -$search_all=trim(GETPOST("search_all", 'alpha')); -$search=array(); -foreach($object->fields as $key => $val) +$search_all = trim(GETPOST("search_all", 'alpha')); +$search = array(); +foreach ($object->fields as $key => $val) { - if (GETPOST('search_'.$key, 'alpha')) $search[$key]=GETPOST('search_'.$key, 'alpha'); + 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) +foreach ($object->fields as $key => $val) { - if ($val['searchall']) $fieldstosearchall['t.'.$key]=$val['label']; + if ($val['searchall']) $fieldstosearchall['t.'.$key] = $val['label']; } // Definition of fields for list -$arrayfields=array(); -foreach($object->fields as $key => $val) +$arrayfields = array(); +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'], 'position'=>$val['position']); + if (!empty($val['visible'])) $arrayfields['t.'.$key] = array('label'=>$val['label'], 'checked'=>(($val['visible'] < 0) ? 0 : 1), 'enabled'=>$val['enabled'], '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) + 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], 'checked'=>(($extrafields->attributes[$object->table_element]['list'][$key]<0)?0:1), 'position'=>$extrafields->attributes[$object->table_element]['pos'][$key], 'enabled'=>(abs($extrafields->attributes[$object->table_element]['list'][$key])!=3 && $extrafields->attributes[$object->table_element]['perms'][$key])); + if (!empty($extrafields->attributes[$object->table_element]['list'][$key])) + $arrayfields["ef.".$key] = array('label'=>$extrafields->attributes[$object->table_element]['label'][$key], 'checked'=>(($extrafields->attributes[$object->table_element]['list'][$key] < 0) ? 0 : 1), 'position'=>$extrafields->attributes[$object->table_element]['pos'][$key], 'enabled'=>(abs($extrafields->attributes[$object->table_element]['list'][$key]) != 3 && $extrafields->attributes[$object->table_element]['perms'][$key])); } } $object->fields = dol_sort_array($object->fields, 'position'); @@ -125,11 +125,11 @@ $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(); -$reshook=$hookmanager->executeHooks('doActions', $parameters, $object, $action); // Note that $action and $object may have been modified by some hooks +$parameters = array(); +$reshook = $hookmanager->executeHooks('doActions', $parameters, $object, $action); // Note that $action and $object may have been modified by some hooks if ($reshook < 0) setEventMessages($hookmanager->error, $hookmanager->errors, 'errors'); if (empty($reshook)) @@ -138,24 +138,24 @@ if (empty($reshook)) 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 { - foreach($object->fields as $key => $val) + foreach ($object->fields as $key => $val) { - $search[$key]=''; + $search[$key] = ''; } - $toselect=''; - $search_array_options=array(); + $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')) { - $massaction=''; // Protection to avoid mass action if we force a new search during a mass action confirmation + $massaction = ''; // Protection to avoid mass action if we force a new search during a mass action confirmation } // Mass actions - $objectclass='EmailCollector'; - $objectlabel='EmailCollector'; + $objectclass = 'EmailCollector'; + $objectlabel = 'EmailCollector'; $permissiontoread = $user->rights->emailcollector->read; $permissiontodelete = $user->rights->emailcollector->delete; $uploaddir = $conf->emailcollector->dir_output; @@ -168,47 +168,47 @@ if (empty($reshook)) * View */ -$form=new Form($db); +$form = new Form($db); -$now=dol_now(); +$now = dol_now(); //$help_url="EN:Module_EmailCollector|FR:Module_EmailCollector_FR|ES:Módulo_EmailCollector"; -$help_url=''; +$help_url = ''; $title = $langs->trans('ListOf', $langs->transnoentitiesnoconv("EmailCollector")); // Build and execute select // -------------------------------------------------------------------- $sql = 'SELECT '; -foreach($object->fields as $key => $val) +foreach ($object->fields as $key => $val) { - $sql.='t.'.$key.', '; + $sql .= 't.'.$key.', '; } // Add fields from extrafields -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.', ' : ''); +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.', ' : ''); // Add fields from hooks -$parameters=array(); -$reshook=$hookmanager->executeHooks('printFieldListSelect', $parameters, $object); // Note that $action and $object may have been modified by hook -$sql.=$hookmanager->resPrint; -$sql=preg_replace('/, $/', '', $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) +$parameters = array(); +$reshook = $hookmanager->executeHooks('printFieldListSelect', $parameters, $object); // Note that $action and $object may have been modified by hook +$sql .= $hookmanager->resPrint; +$sql = preg_replace('/, $/', '', $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; - $mode_search=(($object->isInt($object->fields[$key]) || $object->isFloat($object->fields[$key]))?1:0); - if ($search[$key] != '') $sql.=natural_search($key, $search[$key], (($key == 'status')?2:$mode_search)); + $mode_search = (($object->isInt($object->fields[$key]) || $object->isFloat($object->fields[$key])) ? 1 : 0); + 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 -$parameters=array(); -$reshook=$hookmanager->executeHooks('printFieldListWhere', $parameters, $object); // Note that $action and $object may have been modified by hook -$sql.=$hookmanager->resPrint; +$parameters = array(); +$reshook = $hookmanager->executeHooks('printFieldListWhere', $parameters, $object); // Note that $action and $object may have been modified by hook +$sql .= $hookmanager->resPrint; /* If a group by is required $sql.= " GROUP BY " @@ -226,7 +226,7 @@ $sql.=$hookmanager->resPrint; $sql=preg_replace('/, $/','', $sql); */ -$sql.=$db->order($sortfield, $sortorder); +$sql .= $db->order($sortfield, $sortorder); // Count total nb of records $nbtotalofrecords = ''; @@ -247,10 +247,10 @@ if (is_numeric($nbtotalofrecords) && $limit > $nbtotalofrecords) } else { - $sql.= $db->plimit($limit+1, $offset); + $sql .= $db->plimit($limit + 1, $offset); - $resql=$db->query($sql); - if (! $resql) + $resql = $db->query($sql); + if (!$resql) { dol_print_error($db); exit; @@ -260,7 +260,7 @@ else } // Direct jump if only one record found -if ($num == 1 && ! empty($conf->global->MAIN_SEARCH_DIRECT_OPEN_IF_ONLY_ONE) && $search_all) +if ($num == 1 && !empty($conf->global->MAIN_SEARCH_DIRECT_OPEN_IF_ONLY_ONE) && $search_all) { $obj = $db->fetch_object($resql); $id = $obj->rowid; @@ -289,27 +289,27 @@ jQuery(document).ready(function() { }); '; -$arrayofselected=is_array($toselect)?$toselect:array(); +$arrayofselected = is_array($toselect) ? $toselect : array(); -$param=''; -if (! empty($contextpage) && $contextpage != $_SERVER["PHP_SELF"]) $param.='&contextpage='.urlencode($contextpage); -if ($limit > 0 && $limit != $conf->liste_limit) $param.='&limit='.urlencode($limit); -foreach($search as $key => $val) +$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) { - $param.= '&search_'.$key.'='.urlencode($search[$key]); + $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'; // List of mass actions available -$arrayofmassactions = array( +$arrayofmassactions = array( //'presend'=>$langs->trans("SendByMail"), //'builddoc'=>$langs->trans("PDFMerge"), ); -if ($user->rights->emailcollector->delete) $arrayofmassactions['predelete']=''.$langs->trans("Delete"); -if (GETPOST('nomassaction', 'int') || in_array($massaction, array('presend','predelete'))) $arrayofmassactions=array(); -$massactionbutton=$form->selectMassAction('', $arrayofmassactions); +if ($user->rights->emailcollector->delete) $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 ''; @@ -321,10 +321,10 @@ print ''; print ''; print ''; -$newcardbutton=''; +$newcardbutton = ''; //if ($user->rights->emailcollector->creer) //{ -$newcardbutton.= dolGetButtonTitle($langs->trans('New'), '', 'fa fa-plus-circle', 'emailcollector_card.php?action=create&backtopage='.urlencode($_SERVER['PHP_SELF'])); +$newcardbutton .= dolGetButtonTitle($langs->trans('New'), '', 'fa fa-plus-circle', 'emailcollector_card.php?action=create&backtopage='.urlencode($_SERVER['PHP_SELF'])); //} print_barre_liste($title, $page, $_SERVER["PHP_SELF"], $param, $sortfield, $sortorder, $massactionbutton, $num, $nbtotalofrecords, 'title_companies', 0, $newcardbutton, '', $limit); @@ -338,8 +338,8 @@ include DOL_DOCUMENT_ROOT.'/core/tpl/massactions_pre.tpl.php'; if ($sall) { - foreach($fieldstosearchall as $key => $val) $fieldstosearchall[$key]=$langs->trans($val); - print '
'.$langs->trans("FilterOnInto", $sall) . join(', ', $fieldstosearchall).'
'; + foreach ($fieldstosearchall as $key => $val) $fieldstosearchall[$key] = $langs->trans($val); + print '
'.$langs->trans("FilterOnInto", $sall).join(', ', $fieldstosearchall).'
'; } $moreforfilter = ''; @@ -347,47 +347,47 @@ $moreforfilter = ''; $moreforfilter.= $langs->trans('MyFilter') . ': '; $moreforfilter.= '
';*/ -$parameters=array(); -$reshook=$hookmanager->executeHooks('printFieldPreListTitle', $parameters, $object); // Note that $action and $object may have been modified by hook +$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($moreforfilter)) +if (!empty($moreforfilter)) { print '
'; print $moreforfilter; print '
'; } -$varpage=empty($contextpage)?$_SERVER["PHP_SELF"]:$contextpage; -$selectedfields=$form->multiSelectArrayWithCheckbox('selectedfields', $arrayfields, $varpage); // This also change content of $arrayfields -$selectedfields.=(count($arrayofmassactions) ? $form->showCheckAddButtons('checkforselect', 1) : ''); +$varpage = empty($contextpage) ? $_SERVER["PHP_SELF"] : $contextpage; +$selectedfields = $form->multiSelectArrayWithCheckbox('selectedfields', $arrayfields, $varpage); // This also change content of $arrayfields +$selectedfields .= (count($arrayofmassactions) ? $form->showCheckAddButtons('checkforselect', 1) : ''); -print '
'; // You can use div-table-responsive-no-min if you dont need reserved height for your table -print ''."\n"; +print '
'; // You can use div-table-responsive-no-min if you dont need reserved height for your table +print '
'."\n"; // Fields title search // -------------------------------------------------------------------- print ''; -foreach($object->fields as $key => $val) +foreach ($object->fields as $key => $val) { - $cssforfield=''; - if (in_array($val['type'], array('date','datetime','timestamp'))) $cssforfield.=($cssforfield?' ':'').'center'; - if (in_array($val['type'], array('timestamp'))) $cssforfield.=($cssforfield?' ':'').'nowrap'; - if ($key == 'status') $cssforfield.=($cssforfield?' ':'').'center'; - if (! empty($arrayfields['t.'.$key]['checked'])) print ''; + $cssforfield = ''; + if (in_array($val['type'], array('date', 'datetime', 'timestamp'))) $cssforfield .= ($cssforfield ? ' ' : '').'center'; + if (in_array($val['type'], array('timestamp'))) $cssforfield .= ($cssforfield ? ' ' : '').'nowrap'; + if ($key == 'status') $cssforfield .= ($cssforfield ? ' ' : '').'center'; + if (!empty($arrayfields['t.'.$key]['checked'])) print ''; } // Extra fields include DOL_DOCUMENT_ROOT.'/core/tpl/extrafields_list_search_input.tpl.php'; // Fields from hook -$parameters=array('arrayfields'=>$arrayfields); -$reshook=$hookmanager->executeHooks('printFieldListOption', $parameters, $object); // Note that $action and $object may have been modified by hook +$parameters = array('arrayfields'=>$arrayfields); +$reshook = $hookmanager->executeHooks('printFieldListOption', $parameters, $object); // Note that $action and $object may have been modified by hook print $hookmanager->resPrint; // Action column print ''; print ''."\n"; @@ -396,66 +396,66 @@ print ''."\n"; // Fields title label // -------------------------------------------------------------------- print ''; -foreach($object->fields as $key => $val) +foreach ($object->fields as $key => $val) { - $cssforfield=''; - if (in_array($val['type'], array('date','datetime','timestamp'))) $cssforfield.=($cssforfield?' ':'').'center'; - if (in_array($val['type'], array('timestamp'))) $cssforfield.=($cssforfield?' ':'').'nowrap'; - if ($key == 'status') $cssforfield.=($cssforfield?' ':'').'center'; - if (! empty($arrayfields['t.'.$key]['checked'])) + $cssforfield = ''; + if (in_array($val['type'], array('date', 'datetime', 'timestamp'))) $cssforfield .= ($cssforfield ? ' ' : '').'center'; + if (in_array($val['type'], array('timestamp'))) $cssforfield .= ($cssforfield ? ' ' : '').'nowrap'; + if ($key == 'status') $cssforfield .= ($cssforfield ? ' ' : '').'center'; + if (!empty($arrayfields['t.'.$key]['checked'])) { - print getTitleFieldOfList($arrayfields['t.'.$key]['label'], 0, $_SERVER['PHP_SELF'], 't.'.$key, '', $param, ($cssforfield?'class="'.$cssforfield.'"':''), $sortfield, $sortorder, ($cssforfield?$cssforfield.' ':''))."\n"; + print getTitleFieldOfList($arrayfields['t.'.$key]['label'], 0, $_SERVER['PHP_SELF'], 't.'.$key, '', $param, ($cssforfield ? 'class="'.$cssforfield.'"' : ''), $sortfield, $sortorder, ($cssforfield ? $cssforfield.' ' : ''))."\n"; } } // 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, $object); // Note that $action and $object may have been modified by hook +$parameters = array('arrayfields'=>$arrayfields, 'param'=>$param, 'sortfield'=>$sortfield, 'sortorder'=>$sortorder); +$reshook = $hookmanager->executeHooks('printFieldListTitle', $parameters, $object); // Note that $action and $object may have been modified by hook print $hookmanager->resPrint; print getTitleFieldOfList($selectedfields, 0, $_SERVER["PHP_SELF"], '', '', '', '', $sortfield, $sortorder, 'center maxwidthsearch ')."\n"; print ''."\n"; // Detect if we need a fetch on each output line -$needToFetchEachLine=0; +$needToFetchEachLine = 0; if (is_array($extrafields->attributes[$object->table_element]['computed']) && count($extrafields->attributes[$object->table_element]['computed']) > 0) { foreach ($extrafields->attributes[$object->table_element]['computed'] as $key => $val) { - if (preg_match('/\$object/', $val)) $needToFetchEachLine++; // There is at least one compute field that use $object + if (preg_match('/\$object/', $val)) $needToFetchEachLine++; // There is at least one compute field that use $object } } // Loop on record // -------------------------------------------------------------------- -$i=0; -$totalarray=array(); +$i = 0; +$totalarray = array(); while ($i < min($num, $limit)) { $obj = $db->fetch_object($resql); - if (empty($obj)) break; // Should not happen + if (empty($obj)) break; // Should not happen // Store properties in $object $object->id = $obj->rowid; - foreach($object->fields as $key => $val) + foreach ($object->fields as $key => $val) { if (property_exists($obj, $key)) $object->$key = $obj->$key; } // Show here line of result print ''; - foreach($object->fields as $key => $val) + foreach ($object->fields as $key => $val) { - $cssforfield=''; - if (in_array($val['type'], array('date','datetime','timestamp'))) $cssforfield.=($cssforfield?' ':'').'center'; - elseif ($key == 'status') $cssforfield.=($cssforfield?' ':'').'center'; + $cssforfield = ''; + 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 (! empty($arrayfields['t.'.$key]['checked'])) + if (!empty($arrayfields['t.'.$key]['checked'])) { print ''; if ($massactionbutton || $massaction) // If we are in select mode (massactionbutton defined) or if we have already selected and sent an action ($massaction) defined { - $selected=0; - if (in_array($obj->rowid, $arrayofselected)) $selected=1; - print ''; + $selected = 0; + if (in_array($obj->rowid, $arrayofselected)) $selected = 1; + print ''; } print ''; - if (! $i) $totalarray['nbfield']++; + if (!$i) $totalarray['nbfield']++; print ''; @@ -503,16 +503,16 @@ include DOL_DOCUMENT_ROOT.'/core/tpl/list_print_total.tpl.php'; // If no record found if ($num == 0) { - $colspan=1; - foreach($arrayfields as $key => $val) { if (! empty($val['checked'])) $colspan++; } + $colspan = 1; + foreach ($arrayfields as $key => $val) { if (!empty($val['checked'])) $colspan++; } print ''; } $db->free($resql); -$parameters=array('arrayfields'=>$arrayfields, 'sql'=>$sql); -$reshook=$hookmanager->executeHooks('printFieldListFooter', $parameters, $object); // Note that $action and $object may have been modified by hook +$parameters = array('arrayfields'=>$arrayfields, 'sql'=>$sql); +$reshook = $hookmanager->executeHooks('printFieldListFooter', $parameters, $object); // Note that $action and $object may have been modified by hook print $hookmanager->resPrint; print '
'; -$searchpicto=$form->showFilterButtons(); +$searchpicto = $form->showFilterButtons(); print $searchpicto; print '
'.$langs->trans("NoRecordFound").'
'."\n"; @@ -522,19 +522,19 @@ print ''."\n"; if (in_array('builddoc', $arrayofmassactions) && ($nbtotalofrecords === '' || $nbtotalofrecords)) { - $hidegeneratedfilelistifempty=1; - if ($massaction == 'builddoc' || $action == 'remove_file' || $show_files) $hidegeneratedfilelistifempty=0; + $hidegeneratedfilelistifempty = 1; + 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); // Show list of available documents - $urlsource=$_SERVER['PHP_SELF'].'?sortfield='.$sortfield.'&sortorder='.$sortorder; - $urlsource.=str_replace('&', '&', $param); + $urlsource = $_SERVER['PHP_SELF'].'?sortfield='.$sortfield.'&sortorder='.$sortorder; + $urlsource .= str_replace('&', '&', $param); - $filedir=$diroutputmassaction; - $genallowed=$user->rights->emailcollector->read; - $delallowed=$user->rights->emailcollector->create; + $filedir = $diroutputmassaction; + $genallowed = $user->rights->emailcollector->read; + $delallowed = $user->rights->emailcollector->create; print $formfile->showdocuments('massfilesarea_emailcollector', '', $filedir, $urlsource, 0, $delallowed, '', 1, 1, 0, 48, 1, $param, $title, '', '', '', null, $hidegeneratedfilelistifempty); } diff --git a/htdocs/admin/expedition.php b/htdocs/admin/expedition.php index 7cc2e7dff44..d0c4e0dc542 100644 --- a/htdocs/admin/expedition.php +++ b/htdocs/admin/expedition.php @@ -203,7 +203,7 @@ dol_fiche_head($head, 'shipment', $langs->trans("Sendings"), -1, 'sending'); print load_fiche_titre($langs->trans("SendingsNumberingModules")); -print ''; +print '
'; print ''; print ''; print ''; @@ -332,7 +332,7 @@ else dol_print_error($db); } -print '
'.$langs->trans("Name").''.$langs->trans("Description").'
'; +print '
'; print ''; print ''; print ''; diff --git a/htdocs/admin/expensereport.php b/htdocs/admin/expensereport.php index 8a5cef82ceb..3139de4849d 100644 --- a/htdocs/admin/expensereport.php +++ b/htdocs/admin/expensereport.php @@ -211,7 +211,7 @@ dol_fiche_head($head, 'expensereport', $langs->trans("ExpenseReports"), -1, 'tri print load_fiche_titre($langs->trans("ExpenseReportNumberingModules"), '', ''); -print '
'.$langs->trans("Name").''.$langs->trans("Description").'
'; +print '
'; print ''; print ''; print ''; @@ -334,7 +334,7 @@ else dol_print_error($db); } -print '
'.$langs->trans("Name").''.$langs->trans("Description").'
'; +print '
'; print ''; print ''; print ''; @@ -466,7 +466,7 @@ print ''; print ''; print load_fiche_titre($langs->trans("OtherOptions"), '', ''); -print '
'.$langs->trans("Name").''.$langs->trans("Description").'
'; +print '
'; print ''; print ''; print ''; diff --git a/htdocs/admin/expensereport_ik.php b/htdocs/admin/expensereport_ik.php index 4d10403c692..66897261207 100644 --- a/htdocs/admin/expensereport_ik.php +++ b/htdocs/admin/expensereport_ik.php @@ -110,7 +110,7 @@ if ($action == 'edit') echo ''; -echo '
'.$langs->trans("Parameter").'
'; +echo '
'; foreach ($rangesbycateg as $fk_c_exp_tax_cat => $Tab) { diff --git a/htdocs/admin/expensereport_rules.php b/htdocs/admin/expensereport_rules.php index a785d5f2927..610bd875c4f 100644 --- a/htdocs/admin/expensereport_rules.php +++ b/htdocs/admin/expensereport_rules.php @@ -161,7 +161,7 @@ if ($action != 'edit') echo ''; echo ''; - echo '
'; + echo '
'; echo ''; echo ''; @@ -204,7 +204,7 @@ if ($action == 'edit') echo ''; } -echo '
'.$langs->trans('ExpenseReportApplyTo').'
'; +echo '
'; echo ''; echo ''; diff --git a/htdocs/admin/export.php b/htdocs/admin/export.php index b12dcf4c530..42aa330d1bd 100644 --- a/htdocs/admin/export.php +++ b/htdocs/admin/export.php @@ -34,11 +34,11 @@ require_once DOL_DOCUMENT_ROOT.'/core/lib/admin.lib.php'; // Load translation files required by the page $langs->loadLangs(array('admin', 'exports', 'other')); -if (! $user->admin) +if (!$user->admin) accessforbidden(); -$action=GETPOST('action', 'alpha'); -$value=GETPOST('value', 'alpha'); +$action = GETPOST('action', 'alpha'); +$value = GETPOST('value', 'alpha'); /* * Actions @@ -51,18 +51,18 @@ include DOL_DOCUMENT_ROOT.'/core/actions_setmoduleoptions.inc.php'; * View */ -$form=new Form($db); +$form = new Form($db); $page_name = "ExportSetup"; llxHeader('', $langs->trans($page_name)); // Subheader -$linkback = '' . $langs->trans("BackToModuleList") . ''; +$linkback = ''.$langs->trans("BackToModuleList").''; print load_fiche_titre($langs->trans($page_name), $linkback); //$head = export_admin_prepare_head(); -$h=0; +$h = 0; $head = array(); $head[$h][0] = DOL_URL_ROOT.'/admin/export.php'; $head[$h][1] = $langs->trans("Setup"); @@ -72,7 +72,7 @@ $h++; dol_fiche_head($head, 'setup', $langs->trans("ExportsArea"), -1, "exports"); -print '
'.$langs->trans('ExpenseReportApplyTo').'
'; +print '
'; print ''; print ''."\n"; print ''; diff --git a/htdocs/admin/external_rss.php b/htdocs/admin/external_rss.php index 4bb2bf1c964..c73567a5745 100644 --- a/htdocs/admin/external_rss.php +++ b/htdocs/admin/external_rss.php @@ -200,7 +200,7 @@ print '
'; print ''; print ''; -print '
'.$langs->trans("Parameters").' 
'; +print '
'; print ''; print ''; print ''; @@ -254,7 +254,7 @@ if ($resql) print "
"; print ""; - print '
'.$langs->trans("NewRSS").''.$langs->trans("Example").'
'; + print '
'; print ''; print ""; diff --git a/htdocs/admin/facture.php b/htdocs/admin/facture.php index dccfcdfdda1..6f1f621b90a 100644 --- a/htdocs/admin/facture.php +++ b/htdocs/admin/facture.php @@ -279,7 +279,7 @@ dol_fiche_head($head, 'general', $langs->trans("Invoices"), -1, 'invoice'); print load_fiche_titre($langs->trans("BillsNumberingModule"), '', ''); -print '
'; +print '
'; print ''; print ''; print ''; @@ -468,7 +468,7 @@ else dol_print_error($db); } -print '
'.$langs->trans("Name").''.$langs->trans("Description").'
'; +print '
'; print ''; print ''; print ''; @@ -607,7 +607,7 @@ if(!empty($conf->global->INVOICE_USE_DEFAULT_DOCUMENT)) // Hidden conf print ''; print ''; print ''; - print '
'.$langs->trans("Name").''.$langs->trans("Description").'
'; + print '
'; print ''; print ''; print ''; @@ -648,7 +648,7 @@ print load_fiche_titre($langs->trans("SuggestedPaymentModesIfNotDefinedInInvoice print ''; print ''; -print '
'.$langs->trans("Type").''.$langs->trans("Name").'
'; +print '
'; print ''; print '
'; @@ -738,7 +738,7 @@ print ""; print "
"; print load_fiche_titre($langs->trans("OtherOptions"), '', ''); -print ''; +print '
'; print ''; print ''; print ''; diff --git a/htdocs/admin/facture_situation.php b/htdocs/admin/facture_situation.php index 71fc1f8eac2..0378f5cf0d4 100644 --- a/htdocs/admin/facture_situation.php +++ b/htdocs/admin/facture_situation.php @@ -85,7 +85,7 @@ print ''; _updateBtn(); -print '
'.$langs->trans("Parameter").''.$langs->trans("Value").'
'; +print '
'; _printOnOff('INVOICE_USE_SITUATION', $langs->trans('UseSituationInvoices')); diff --git a/htdocs/admin/fckeditor.php b/htdocs/admin/fckeditor.php index bbe8f0dd221..efe8ca1117d 100644 --- a/htdocs/admin/fckeditor.php +++ b/htdocs/admin/fckeditor.php @@ -149,7 +149,7 @@ if (empty($conf->use_javascript_ajax)) } else { - print '
'; + print '
'; print ''; print ''; print ''; diff --git a/htdocs/admin/fichinter.php b/htdocs/admin/fichinter.php index 876f4b90abb..b9e89450d33 100644 --- a/htdocs/admin/fichinter.php +++ b/htdocs/admin/fichinter.php @@ -37,13 +37,13 @@ require_once DOL_DOCUMENT_ROOT.'/fichinter/class/fichinter.class.php'; // Load translation files required by the page $langs->loadLangs(array('admin', 'errors', 'interventions', 'other')); -if (! $user->admin) accessforbidden(); +if (!$user->admin) accessforbidden(); $action = GETPOST('action', 'alpha'); $value = GETPOST('value', 'alpha'); $label = GETPOST('label', 'alpha'); $scandir = GETPOST('scan_dir', 'alpha'); -$type='ficheinter'; +$type = 'ficheinter'; /* @@ -54,13 +54,13 @@ include DOL_DOCUMENT_ROOT.'/core/actions_setmoduleoptions.inc.php'; if ($action == 'updateMask') { - $maskconst=GETPOST('maskconst', 'alpha'); - $maskvalue=GETPOST('maskvalue', 'alpha'); + $maskconst = GETPOST('maskconst', 'alpha'); + $maskvalue = GETPOST('maskvalue', 'alpha'); if ($maskconst) $res = dolibarr_set_const($db, $maskconst, $maskvalue, 'chaine', 0, '', $conf->entity); - if (! $res > 0) $error++; + if (!$res > 0) $error++; - if (! $error) + if (!$error) { setEventMessages($langs->trans("SetupSaved"), null, 'mesgs'); } @@ -72,20 +72,20 @@ if ($action == 'updateMask') elseif ($action == 'specimen') // For fiche inter { - $modele= GETPOST('module', 'alpha'); + $modele = GETPOST('module', 'alpha'); $inter = new Fichinter($db); $inter->initAsSpecimen(); // Search template files - $file=''; $classname=''; $filefound=0; - $dirmodels=array_merge(array('/'), (array) $conf->modules_parts['models']); - foreach($dirmodels as $reldir) + $file = ''; $classname = ''; $filefound = 0; + $dirmodels = array_merge(array('/'), (array) $conf->modules_parts['models']); + foreach ($dirmodels as $reldir) { - $file=dol_buildpath($reldir."core/modules/fichinter/doc/pdf_".$modele.".modules.php", 0); + $file = dol_buildpath($reldir."core/modules/fichinter/doc/pdf_".$modele.".modules.php", 0); if (file_exists($file)) { - $filefound=1; + $filefound = 1; $classname = "pdf_".$modele; break; } @@ -158,12 +158,12 @@ elseif ($action == 'setmod') elseif ($action == 'set_FICHINTER_FREE_TEXT') { - $freetext= GETPOST('FICHINTER_FREE_TEXT', 'none'); // No alpha here, we want exact string + $freetext = GETPOST('FICHINTER_FREE_TEXT', 'none'); // No alpha here, we want exact string $res = dolibarr_set_const($db, "FICHINTER_FREE_TEXT", $freetext, 'chaine', 0, '', $conf->entity); - if (! $res > 0) $error++; + if (!$res > 0) $error++; - if (! $error) + if (!$error) { setEventMessages($langs->trans("SetupSaved"), null, 'mesgs'); } @@ -175,12 +175,12 @@ elseif ($action == 'set_FICHINTER_FREE_TEXT') elseif ($action == 'set_FICHINTER_DRAFT_WATERMARK') { - $draft= GETPOST('FICHINTER_DRAFT_WATERMARK', 'alpha'); + $draft = GETPOST('FICHINTER_DRAFT_WATERMARK', 'alpha'); $res = dolibarr_set_const($db, "FICHINTER_DRAFT_WATERMARK", trim($draft), 'chaine', 0, '', $conf->entity); - if (! $res > 0) $error++; + if (!$res > 0) $error++; - if (! $error) + if (!$error) { setEventMessages($langs->trans("SetupSaved"), null, 'mesgs'); } @@ -195,9 +195,9 @@ elseif ($action == 'set_FICHINTER_PRINT_PRODUCTS') $val = GETPOST('FICHINTER_PRINT_PRODUCTS', 'alpha'); $res = dolibarr_set_const($db, "FICHINTER_PRINT_PRODUCTS", ($val == 'on' ? 1 : 0), 'bool', 0, '', $conf->entity); - if (! $res > 0) $error++; + if (!$res > 0) $error++; - if (! $error) + if (!$error) { setEventMessages($langs->trans("SetupSaved"), null, 'mesgs'); } @@ -252,17 +252,17 @@ elseif ($action == 'set_FICHINTER_PRINT_PRODUCTS') * View */ -$dirmodels=array_merge(array('/'), (array) $conf->modules_parts['models']); +$dirmodels = array_merge(array('/'), (array) $conf->modules_parts['models']); llxHeader(); -$form=new Form($db); +$form = new Form($db); -$linkback=''.$langs->trans("BackToModuleList").''; +$linkback = ''.$langs->trans("BackToModuleList").''; print load_fiche_titre($langs->trans("InterventionsSetup"), $linkback, 'title_setup'); -$head=fichinter_admin_prepare_head(); +$head = fichinter_admin_prepare_head(); dol_fiche_head($head, 'ficheinter', $langs->trans("Interventions"), -1, 'intervention'); @@ -270,7 +270,7 @@ dol_fiche_head($head, 'ficheinter', $langs->trans("Interventions"), -1, 'interve print load_fiche_titre($langs->trans("FicheinterNumberingModules"), '', ''); -print '
'.$langs->trans("ActivateFCKeditor").''.$langs->trans("Action").'
'; +print '
'; print ''; print ''; print ''; @@ -290,7 +290,7 @@ foreach ($dirmodels as $reldir) $handle = opendir($dir); if (is_resource($handle)) { - while (($file = readdir($handle))!==false) + while (($file = readdir($handle)) !== false) { if (preg_match('/^(mod_.*)\.php$/i', $file, $reg)) { @@ -304,7 +304,7 @@ foreach ($dirmodels as $reldir) if ($module->isEnabled()) { // Show modules according to features level - if ($module->version == 'development' && $conf->global->MAIN_FEATURES_LEVEL < 2) continue; + if ($module->version == 'development' && $conf->global->MAIN_FEATURES_LEVEL < 2) continue; if ($module->version == 'experimental' && $conf->global->MAIN_FEATURES_LEVEL < 1) continue; @@ -314,9 +314,9 @@ foreach ($dirmodels as $reldir) // Show example of numbering model print ''."\n"; @@ -331,21 +331,21 @@ foreach ($dirmodels as $reldir) } print ''; - $ficheinter=new Fichinter($db); + $ficheinter = new Fichinter($db); $ficheinter->initAsSpecimen(); // Info - $htmltooltip=''; - $htmltooltip.=''.$langs->trans("Version").': '.$module->getVersion().'
'; - $nextval=$module->getNextValue($mysoc, $ficheinter); + $htmltooltip = ''; + $htmltooltip .= ''.$langs->trans("Version").': '.$module->getVersion().'
'; + $nextval = $module->getNextValue($mysoc, $ficheinter); if ("$nextval" != $langs->trans("NotAvailable")) { // Keep " on nextval - $htmltooltip.=''.$langs->trans("NextValue").': '; + $htmltooltip .= ''.$langs->trans("NextValue").': '; if ($nextval) { - if (preg_match('/^Error/', $nextval) || $nextval=='NotConfigured') + if (preg_match('/^Error/', $nextval) || $nextval == 'NotConfigured') $nextval = $langs->trans($nextval); - $htmltooltip.=$nextval.'
'; + $htmltooltip .= $nextval.'
'; } else { - $htmltooltip.=$langs->trans($module->error).'
'; + $htmltooltip .= $langs->trans($module->error).'
'; } } print '
'.$langs->trans("Name").''.$langs->trans("Description").''; - $tmp=$module->getExample(); + $tmp = $module->getExample(); if (preg_match('/^Error/', $tmp)) print '
'.$langs->trans($tmp).'
'; - elseif ($tmp=='NotConfigured') print $langs->trans($tmp); + elseif ($tmp == 'NotConfigured') print $langs->trans($tmp); else print $tmp; print '
'; @@ -371,17 +371,17 @@ print '

'; print load_fiche_titre($langs->trans("TemplatePDFInterventions"), '', ''); // Defini tableau def des modeles -$type='ficheinter'; +$type = 'ficheinter'; $def = array(); $sql = "SELECT nom"; -$sql.= " FROM ".MAIN_DB_PREFIX."document_model"; -$sql.= " WHERE type = '".$type."'"; -$sql.= " AND entity = ".$conf->entity; -$resql=$db->query($sql); +$sql .= " FROM ".MAIN_DB_PREFIX."document_model"; +$sql .= " WHERE type = '".$type."'"; +$sql .= " AND entity = ".$conf->entity; +$resql = $db->query($sql); if ($resql) { $i = 0; - $num_rows=$db->num_rows($resql); + $num_rows = $db->num_rows($resql); while ($i < $num_rows) { $array = $db->fetch_array($resql); @@ -395,7 +395,7 @@ else } -print ''; +print '
'; print ''; print ''; print ''; @@ -413,36 +413,36 @@ foreach ($dirmodels as $reldir) if (is_dir($dir)) { - $handle=opendir($dir); + $handle = opendir($dir); if (is_resource($handle)) { - while (($file = readdir($handle))!==false) + while (($file = readdir($handle)) !== false) { - $filelist[]=$file; + $filelist[] = $file; } closedir($handle); arsort($filelist); - foreach($filelist as $file) + foreach ($filelist as $file) { if (preg_match('/\.modules\.php$/i', $file) && preg_match('/^(pdf_|doc_)/', $file)) { if (file_exists($dir.'/'.$file)) { - $name = substr($file, 4, dol_strlen($file) -16); - $classname = substr($file, 0, dol_strlen($file) -12); + $name = substr($file, 4, dol_strlen($file) - 16); + $classname = substr($file, 0, dol_strlen($file) - 12); require_once $dir.'/'.$file; $module = new $classname($db); - $modulequalified=1; - if ($module->version == 'development' && $conf->global->MAIN_FEATURES_LEVEL < 2) $modulequalified=0; - if ($module->version == 'experimental' && $conf->global->MAIN_FEATURES_LEVEL < 1) $modulequalified=0; + $modulequalified = 1; + if ($module->version == 'development' && $conf->global->MAIN_FEATURES_LEVEL < 2) $modulequalified = 0; + if ($module->version == 'experimental' && $conf->global->MAIN_FEATURES_LEVEL < 1) $modulequalified = 0; if ($modulequalified) { print ''; // Info - $htmltooltip = ''.$langs->trans("Name").': '.$module->name; - $htmltooltip.='
'.$langs->trans("Type").': '.($module->type?$module->type:$langs->trans("Unknown")); - $htmltooltip.='
'.$langs->trans("Width").'/'.$langs->trans("Height").': '.$module->page_largeur.'/'.$module->page_hauteur; - $htmltooltip.='

'.$langs->trans("FeaturesSupported").':'; - $htmltooltip.='
'.$langs->trans("Logo").': '.yn($module->option_logo, 1, 1); - $htmltooltip.='
'.$langs->trans("PaymentMode").': '.yn($module->option_modereg, 1, 1); - $htmltooltip.='
'.$langs->trans("PaymentConditions").': '.yn($module->option_condreg, 1, 1); - $htmltooltip.='
'.$langs->trans("MultiLanguage").': '.yn($module->option_multilang, 1, 1); - $htmltooltip.='
'.$langs->trans("WatermarkOnDraftOrders").': '.yn($module->option_draft_watermark, 1, 1); + $htmltooltip = ''.$langs->trans("Name").': '.$module->name; + $htmltooltip .= '
'.$langs->trans("Type").': '.($module->type ? $module->type : $langs->trans("Unknown")); + $htmltooltip .= '
'.$langs->trans("Width").'/'.$langs->trans("Height").': '.$module->page_largeur.'/'.$module->page_hauteur; + $htmltooltip .= '

'.$langs->trans("FeaturesSupported").':'; + $htmltooltip .= '
'.$langs->trans("Logo").': '.yn($module->option_logo, 1, 1); + $htmltooltip .= '
'.$langs->trans("PaymentMode").': '.yn($module->option_modereg, 1, 1); + $htmltooltip .= '
'.$langs->trans("PaymentConditions").': '.yn($module->option_condreg, 1, 1); + $htmltooltip .= '
'.$langs->trans("MultiLanguage").': '.yn($module->option_multilang, 1, 1); + $htmltooltip .= '
'.$langs->trans("WatermarkOnDraftOrders").': '.yn($module->option_draft_watermark, 1, 1); print ''; @@ -519,25 +519,25 @@ print "
"; */ print load_fiche_titre($langs->trans("OtherOptions"), '', ''); -print '
'.$langs->trans("Name").''.$langs->trans("Description").'
'; - print (empty($module->name)?$name:$module->name); + print (empty($module->name) ? $name : $module->name); print "\n"; if (method_exists($module, 'info')) print $module->info($langs); else print $module->description; @@ -477,15 +477,15 @@ foreach ($dirmodels as $reldir) print ''; print $form->textwithpicto('', $htmltooltip, -1, 0); print '
'; +print '
'; print ''; print ''; print ''; print "\n"; print "\n"; -$substitutionarray=pdf_getSubstitutionArray($langs, null, null, 2); -$substitutionarray['__(AnyTranslationKey)__']=$langs->trans("Translation"); +$substitutionarray = pdf_getSubstitutionArray($langs, null, null, 2); +$substitutionarray['__(AnyTranslationKey)__'] = $langs->trans("Translation"); $htmltext = ''.$langs->trans("AvailableVariables").':
'; -foreach($substitutionarray as $key => $val) $htmltext.=$key.'
'; -$htmltext.='
'; +foreach ($substitutionarray as $key => $val) $htmltext .= $key.'
'; +$htmltext .= ''; print ''; print ''; print ''; print '\n"; print ''; // Use services duration -print ''; -print ''; +print ''; +print ''; print ''; print ''; print ''; print ''; print ''; print ''; print ''; // Use duration -print ''; -print ''; +print ''; +print ''; print ''; print ''; print ''; print ''; print ''; print ''; print ''; // use date without hour -print ''; -print ''; +print ''; +print ''; print ''; print ''; print ''; print ''; print ''; print ''; print ''; diff --git a/htdocs/admin/geoipmaxmind.php b/htdocs/admin/geoipmaxmind.php index 7ed797b8618..0baf9a6cdc1 100644 --- a/htdocs/admin/geoipmaxmind.php +++ b/htdocs/admin/geoipmaxmind.php @@ -99,7 +99,7 @@ print ''; print ''; print ''; -print '
'.$langs->trans("Parameter").''.$langs->trans("Value").' 
'; print $form->textwithpicto($langs->trans("FreeLegalTextOnInterventions"), $langs->trans("AddCRIfTooLong").'

'.$htmltext, 1, 'help', '', 0, 2, 'freetexttooltip').'
'; -$variablename='FICHINTER_FREE_TEXT'; +$variablename = 'FICHINTER_FREE_TEXT'; if (empty($conf->global->PDF_ALLOW_HTML_FOR_FREE_TEXT)) { print ''; @@ -545,7 +545,7 @@ if (empty($conf->global->PDF_ALLOW_HTML_FOR_FREE_TEXT)) else { include_once DOL_DOCUMENT_ROOT.'/core/class/doleditor.class.php'; - $doleditor=new DolEditor($variablename, $conf->global->$variablename, '', 80, 'dolibarr_notes'); + $doleditor = new DolEditor($variablename, $conf->global->$variablename, '', 80, 'dolibarr_notes'); print $doleditor->Create(); } print '
'; @@ -580,50 +580,50 @@ print '' print "
'; print $langs->trans("UseServicesDurationOnFichinter"); print ''; -print 'global->FICHINTER_USE_SERVICE_DURATION?' checked':'') . '>'; +print 'global->FICHINTER_USE_SERVICE_DURATION ? ' checked' : '').'>'; print ''; -print ''; +print ''; print '
'; print $langs->trans("UseDurationOnFichinter"); print ''; -print 'global->FICHINTER_WITHOUT_DURATION?' checked':'') . '>'; +print 'global->FICHINTER_WITHOUT_DURATION ? ' checked' : '').'>'; print ''; -print ''; +print ''; print '
'; print $langs->trans("UseDateWithoutHourOnFichinter"); print ''; -print 'global->FICHINTER_DATE_WITHOUT_HOUR?' checked':'') . '>'; +print 'global->FICHINTER_DATE_WITHOUT_HOUR ? ' checked' : '').'>'; print ''; -print ''; +print ''; print '
'; +print '
'; print ''; print ''; print ''; diff --git a/htdocs/admin/holiday.php b/htdocs/admin/holiday.php index 2d3f986e6a1..f0b0218c0e5 100644 --- a/htdocs/admin/holiday.php +++ b/htdocs/admin/holiday.php @@ -202,7 +202,7 @@ dol_fiche_head($head, 'holiday', $langs->trans("Holidays"), -1, 'holiday'); print load_fiche_titre($langs->trans("HolidaysNumberingModules"), '', ''); print '
'; -print '
'.$langs->trans("Parameter").''.$langs->trans("Value").'
'; +print '
'; print ''; print ''; print ''; @@ -339,7 +339,7 @@ else print '
'; -print '
'.$langs->trans("Name").''.$langs->trans("Description").'
'; +print '
'; print ''; print ''; print ''; @@ -479,7 +479,7 @@ print ''; print load_fiche_titre($langs->trans("OtherOptions"), '', ''); print '
'; -print '
'.$langs->trans("Name").''.$langs->trans("Description").'
'; +print '
'; print ''; print ''; print ''; diff --git a/htdocs/admin/ihm.php b/htdocs/admin/ihm.php index dfbb548f5e0..d2044436937 100644 --- a/htdocs/admin/ihm.php +++ b/htdocs/admin/ihm.php @@ -233,7 +233,7 @@ print ''; clearstatcache(); print '
'; -print '
'.$langs->trans("Parameter").''.$langs->trans("Value").'
'; +print '
'; print ''; print ''; print ''; @@ -259,7 +259,7 @@ showSkins(null, 1); print '
'; // Other -print '
'.$langs->trans("Language").' 
'; +print '
'; print ''; print ''; print ''; @@ -375,7 +375,7 @@ print '
'.$langs->trans("Miscellaneous").' 
'."\n"; print '
'; // Other -print ''; +print '
'; print ''; print ''; print ''; diff --git a/htdocs/admin/index.php b/htdocs/admin/index.php index 2fe4d02e495..a7fe135d930 100644 --- a/htdocs/admin/index.php +++ b/htdocs/admin/index.php @@ -74,13 +74,13 @@ print $langs->trans("SetupDescription2", $langs->transnoentities("MenuCompanySet print '
'; // Show info setup company -if (empty($conf->global->MAIN_INFO_SOCIETE_NOM) || empty($conf->global->MAIN_INFO_SOCIETE_COUNTRY)) $setupcompanynotcomplete=1; -print img_picto('', 'puce').' '.$langs->trans("SetupDescription3", DOL_URL_ROOT.'/admin/company.php?mainmenu=home'.(empty($setupcompanynotcomplete)?'':'&action=edit'), $langs->transnoentities("Setup"), $langs->transnoentities("MenuCompanySetup")); -if (! empty($setupcompanynotcomplete)) +if (empty($conf->global->MAIN_INFO_SOCIETE_NOM) || empty($conf->global->MAIN_INFO_SOCIETE_COUNTRY)) $setupcompanynotcomplete = 1; +print img_picto('', 'puce').' '.$langs->trans("SetupDescription3", DOL_URL_ROOT.'/admin/company.php?mainmenu=home'.(empty($setupcompanynotcomplete) ? '' : '&action=edit'), $langs->transnoentities("Setup"), $langs->transnoentities("MenuCompanySetup")); +if (!empty($setupcompanynotcomplete)) { $langs->load("errors"); - $warnpicto=img_warning($langs->trans("WarningMandatorySetupNotComplete"), 'style="padding-right: 6px;"'); - print '
'; + $warnpicto = img_warning($langs->trans("WarningMandatorySetupNotComplete"), 'style="padding-right: 6px;"'); + print '
'; } print '
'; print '
'; @@ -96,10 +96,10 @@ if ($nbofactivatedmodules <= 1) $moreinfo .= ' '.img_warning($langs->trans("YouM print '
'.$moreinfo; */ -if (count($conf->modules) <= (empty($conf->global->MAIN_MIN_NB_ENABLED_MODULE_FOR_WARNING)?1:$conf->global->MAIN_MIN_NB_ENABLED_MODULE_FOR_WARNING)) // If only user module enabled +if (count($conf->modules) <= (empty($conf->global->MAIN_MIN_NB_ENABLED_MODULE_FOR_WARNING) ? 1 : $conf->global->MAIN_MIN_NB_ENABLED_MODULE_FOR_WARNING)) // If only user module enabled { $langs->load("errors"); - $warnpicto=img_warning($langs->trans("WarningEnableYourModulesApplications"), 'style="padding-right: 6px;"'); + $warnpicto = img_warning($langs->trans("WarningEnableYourModulesApplications"), 'style="padding-right: 6px;"'); print '
'; } print '
'; @@ -108,8 +108,8 @@ print '
'; print '
'; // Add hook to add information -$parameters=array(); -$reshook=$hookmanager->executeHooks('addHomeSetup', $parameters, $object, $action); // Note that $action and $object may have been modified by some hooks +$parameters = array(); +$reshook = $hookmanager->executeHooks('addHomeSetup', $parameters, $object, $action); // Note that $action and $object may have been modified by some hooks print $hookmanager->resPrint; if (empty($reshook)) { diff --git a/htdocs/admin/ldap.php b/htdocs/admin/ldap.php index dba2cee41a5..00158dbb5e6 100644 --- a/htdocs/admin/ldap.php +++ b/htdocs/admin/ldap.php @@ -111,7 +111,7 @@ print ''; dol_fiche_head($head, 'ldap', $langs->trans("LDAPSetup"), -1); -print '
'.$langs->trans("LoginPage").' 
'; +print '
'; // Liste de synchro actives print ''; diff --git a/htdocs/admin/ldap_contacts.php b/htdocs/admin/ldap_contacts.php index c466f4e6c1e..4e49bee1d44 100644 --- a/htdocs/admin/ldap_contacts.php +++ b/htdocs/admin/ldap_contacts.php @@ -116,7 +116,7 @@ print '
'; print ''; print ''; -print '
'; +print '
'; print ''; print ''; @@ -138,7 +138,7 @@ print ''; print '
'.$langs->trans("LDAPSynchronizeContacts").'
'; print '
'; -print ''; +print '
'; print ''; print ''; diff --git a/htdocs/admin/ldap_groups.php b/htdocs/admin/ldap_groups.php index 17f156ca223..284427e4536 100644 --- a/htdocs/admin/ldap_groups.php +++ b/htdocs/admin/ldap_groups.php @@ -34,7 +34,7 @@ require_once DOL_DOCUMENT_ROOT.'/core/class/ldap.class.php'; require_once DOL_DOCUMENT_ROOT.'/core/lib/ldap.lib.php'; // Load translation files required by the page -$langs->loadLangs(array("admin","errors")); +$langs->loadLangs(array("admin", "errors")); if (!$user->admin) accessforbidden(); @@ -48,25 +48,25 @@ $action = GETPOST('action', 'aZ09'); if ($action == 'setvalue' && $user->admin) { - $error=0; + $error = 0; $db->begin(); - if (! dolibarr_set_const($db, 'LDAP_GROUP_DN', GETPOST("group"), 'chaine', 0, '', $conf->entity)) $error++; - if (! dolibarr_set_const($db, 'LDAP_GROUP_OBJECT_CLASS', GETPOST("objectclass"), 'chaine', 0, '', $conf->entity)) $error++; + if (!dolibarr_set_const($db, 'LDAP_GROUP_DN', GETPOST("group"), 'chaine', 0, '', $conf->entity)) $error++; + if (!dolibarr_set_const($db, 'LDAP_GROUP_OBJECT_CLASS', GETPOST("objectclass"), 'chaine', 0, '', $conf->entity)) $error++; - if (! dolibarr_set_const($db, 'LDAP_GROUP_FIELD_FULLNAME', GETPOST("fieldfullname"), 'chaine', 0, '', $conf->entity)) $error++; + if (!dolibarr_set_const($db, 'LDAP_GROUP_FIELD_FULLNAME', GETPOST("fieldfullname"), 'chaine', 0, '', $conf->entity)) $error++; //if (! dolibarr_set_const($db, 'LDAP_GROUP_FIELD_NAME',$_POST["fieldname"],'chaine',0,'',$conf->entity)) $error++; - if (! dolibarr_set_const($db, 'LDAP_GROUP_FIELD_DESCRIPTION', GETPOST("fielddescription"), 'chaine', 0, '', $conf->entity)) $error++; - if (! dolibarr_set_const($db, 'LDAP_GROUP_FIELD_GROUPMEMBERS', GETPOST("fieldgroupmembers"), 'chaine', 0, '', $conf->entity)) $error++; - if (! dolibarr_set_const($db, 'LDAP_GROUP_FIELD_GROUPID', GETPOST("fieldgroupid"), 'chaine', 0, '', $conf->entity)) $error++; + if (!dolibarr_set_const($db, 'LDAP_GROUP_FIELD_DESCRIPTION', GETPOST("fielddescription"), 'chaine', 0, '', $conf->entity)) $error++; + if (!dolibarr_set_const($db, 'LDAP_GROUP_FIELD_GROUPMEMBERS', GETPOST("fieldgroupmembers"), 'chaine', 0, '', $conf->entity)) $error++; + if (!dolibarr_set_const($db, 'LDAP_GROUP_FIELD_GROUPID', GETPOST("fieldgroupid"), 'chaine', 0, '', $conf->entity)) $error++; // This one must be after the others - $valkey=''; - $key=GETPOST("key"); - if ($key) $valkey=$conf->global->$key; - if (! dolibarr_set_const($db, 'LDAP_KEY_GROUPS', $valkey, 'chaine', 0, '', $conf->entity)) $error++; + $valkey = ''; + $key = GETPOST("key"); + if ($key) $valkey = $conf->global->$key; + if (!dolibarr_set_const($db, 'LDAP_KEY_GROUPS', $valkey, 'chaine', 0, '', $conf->entity)) $error++; - if (! $error) + if (!$error) { $db->commit(); setEventMessages($langs->trans("SetupSaved"), null, 'mesgs'); @@ -85,14 +85,14 @@ if ($action == 'setvalue' && $user->admin) */ llxHeader('', $langs->trans("LDAPSetup"), 'EN:Module_LDAP_En|FR:Module_LDAP|ES:Módulo_LDAP'); -$linkback=''.$langs->trans("BackToModuleList").''; +$linkback = ''.$langs->trans("BackToModuleList").''; print load_fiche_titre($langs->trans("LDAPSetup"), $linkback, 'title_setup'); $head = ldap_prepare_head(); // Test si fonction LDAP actives -if (! function_exists("ldap_connect")) +if (!function_exists("ldap_connect")) { setEventMessages($langs->trans("LDAPFunctionsNotAvailableOnPHP"), null, 'errors'); } @@ -107,9 +107,9 @@ print '
'; print ''; print ''; -$form=new Form($db); +$form = new Form($db); -print '
'.$langs->trans("LDAPDolibarrMapping").'
'; +print '
'; print ''; print ''; @@ -131,7 +131,7 @@ print ''; print '
'.$langs->trans("LDAPSynchronizeGroups").'
'; print '
'; -print ''; +print '
'; print ''; print ''; @@ -145,7 +145,7 @@ print "\n"; print ''; -print '"; +print '"; print ''; // Name @@ -161,14 +161,14 @@ print ''; print ''; -print '"; +print '"; print ''; // User group print ''; -print '"; +print '"; print ''; // Group id @@ -194,11 +194,11 @@ print ''; */ if ($conf->global->LDAP_SYNCHRO_ACTIVE == 'dolibarr2ldap') { - $butlabel=$langs->trans("LDAPTestSynchroGroup"); - $testlabel='testgroup'; - $key=$conf->global->LDAP_KEY_GROUPS; - $dn=$conf->global->LDAP_GROUP_DN; - $objectclass=$conf->global->LDAP_GROUP_OBJECT_CLASS; + $butlabel = $langs->trans("LDAPTestSynchroGroup"); + $testlabel = 'testgroup'; + $key = $conf->global->LDAP_KEY_GROUPS; + $dn = $conf->global->LDAP_GROUP_DN; + $objectclass = $conf->global->LDAP_GROUP_OBJECT_CLASS; show_ldap_test_button($butlabel, $testlabel, $key, $dn, $objectclass); } @@ -208,26 +208,26 @@ if (function_exists("ldap_connect")) if ($_GET["action"] == 'testgroup') { // Creation objet - $object=new UserGroup($db); + $object = new UserGroup($db); $object->initAsSpecimen(); // Test synchro - $ldap=new Ldap(); - $result=$ldap->connect_bind(); + $ldap = new Ldap(); + $result = $ldap->connect_bind(); if ($result > 0) { - $info=$object->_load_ldap_info(); - $dn=$object->_load_ldap_dn($info); + $info = $object->_load_ldap_info(); + $dn = $object->_load_ldap_dn($info); // Get a gid number for objectclass PosixGroup if (in_array('posixGroup', $info['objectclass'])) { $info['gidNumber'] = $ldap->getNextGroupGid('LDAP_KEY_GROUPS'); } - $result1=$ldap->delete($dn); // To be sure to delete existing records - $result2=$ldap->add($dn, $info, $user); // Now the test - $result3=$ldap->delete($dn); // Clean what we did + $result1 = $ldap->delete($dn); // To be sure to delete existing records + $result2 = $ldap->add($dn, $info, $user); // Now the test + $result3 = $ldap->delete($dn); // Clean what we did if ($result2 > 0) { diff --git a/htdocs/admin/ldap_members.php b/htdocs/admin/ldap_members.php index 618e5ac87d5..457e63d0330 100644 --- a/htdocs/admin/ldap_members.php +++ b/htdocs/admin/ldap_members.php @@ -133,7 +133,7 @@ dol_fiche_head($head, 'members', $langs->trans("LDAPSetup"), -1); print $langs->trans("LDAPDescMembers").'
'; print '
'; -print '
'.$langs->trans("LDAPDolibarrMapping").'
'.$langs->trans("LDAPFieldName").''; print ''; print ''.$langs->trans("LDAPFieldCommonNameExample").'global->LDAP_KEY_GROUPS && $conf->global->LDAP_KEY_GROUPS==$conf->global->LDAP_GROUP_FIELD_FULLNAME)?' checked':'').">global->LDAP_KEY_GROUPS && $conf->global->LDAP_KEY_GROUPS == $conf->global->LDAP_GROUP_FIELD_FULLNAME) ? ' checked' : '').">
'.$langs->trans("LDAPFieldDescription").''; print ''; print ''.$langs->trans("LDAPFieldDescriptionExample").'global->LDAP_KEY_GROUPS && $conf->global->LDAP_KEY_GROUPS==$conf->global->LDAP_GROUP_FIELD_DESCRIPTION)?' checked':'').">global->LDAP_KEY_GROUPS && $conf->global->LDAP_KEY_GROUPS == $conf->global->LDAP_GROUP_FIELD_DESCRIPTION) ? ' checked' : '').">
'.$langs->trans("LDAPFieldGroupMembers").''; print ''; print ''.$langs->trans("LDAPFieldGroupMembersExample").'global->LDAP_KEY_GROUPS && $conf->global->LDAP_KEY_GROUPS==$conf->global->LDAP_GROUP_FIELD_GROUPMEMBERS)?' checked':'').">global->LDAP_KEY_GROUPS && $conf->global->LDAP_KEY_GROUPS == $conf->global->LDAP_GROUP_FIELD_GROUPMEMBERS) ? ' checked' : '').">
'; +print '
'; print ''; print ''; @@ -162,7 +162,7 @@ print ''; print '
'.$langs->trans("LDAPSynchronizeMembers").'
'; print '
'; -print ''; +print '
'; print ''; print ''; diff --git a/htdocs/admin/ldap_members_types.php b/htdocs/admin/ldap_members_types.php index 45d0d488c8a..adc60f8969c 100644 --- a/htdocs/admin/ldap_members_types.php +++ b/htdocs/admin/ldap_members_types.php @@ -48,23 +48,23 @@ $action = GETPOST('action', 'aZ09'); if ($action == 'setvalue' && $user->admin) { - $error=0; + $error = 0; $db->begin(); - if (! dolibarr_set_const($db, 'LDAP_MEMBER_TYPE_DN', GETPOST("membertype"), 'chaine', 0, '', $conf->entity)) $error++; - if (! dolibarr_set_const($db, 'LDAP_MEMBER_TYPE_OBJECT_CLASS', GETPOST("objectclass"), 'chaine', 0, '', $conf->entity)) $error++; + if (!dolibarr_set_const($db, 'LDAP_MEMBER_TYPE_DN', GETPOST("membertype"), 'chaine', 0, '', $conf->entity)) $error++; + if (!dolibarr_set_const($db, 'LDAP_MEMBER_TYPE_OBJECT_CLASS', GETPOST("objectclass"), 'chaine', 0, '', $conf->entity)) $error++; - if (! dolibarr_set_const($db, 'LDAP_MEMBER_TYPE_FIELD_FULLNAME', GETPOST("fieldfullname"), 'chaine', 0, '', $conf->entity)) $error++; - if (! dolibarr_set_const($db, 'LDAP_MEMBER_TYPE_FIELD_DESCRIPTION', GETPOST("fielddescription"), 'chaine', 0, '', $conf->entity)) $error++; - if (! dolibarr_set_const($db, 'LDAP_MEMBER_TYPE_FIELD_GROUPMEMBERS', GETPOST("fieldmembertypemembers"), 'chaine', 0, '', $conf->entity)) $error++; + if (!dolibarr_set_const($db, 'LDAP_MEMBER_TYPE_FIELD_FULLNAME', GETPOST("fieldfullname"), 'chaine', 0, '', $conf->entity)) $error++; + if (!dolibarr_set_const($db, 'LDAP_MEMBER_TYPE_FIELD_DESCRIPTION', GETPOST("fielddescription"), 'chaine', 0, '', $conf->entity)) $error++; + if (!dolibarr_set_const($db, 'LDAP_MEMBER_TYPE_FIELD_GROUPMEMBERS', GETPOST("fieldmembertypemembers"), 'chaine', 0, '', $conf->entity)) $error++; // This one must be after the others - $valkey=''; - $key=GETPOST("key"); - if ($key) $valkey=$conf->global->$key; - if (! dolibarr_set_const($db, 'LDAP_KEY_MEMBERS_TYPES', $valkey, 'chaine', 0, '', $conf->entity)) $error++; + $valkey = ''; + $key = GETPOST("key"); + if ($key) $valkey = $conf->global->$key; + if (!dolibarr_set_const($db, 'LDAP_KEY_MEMBERS_TYPES', $valkey, 'chaine', 0, '', $conf->entity)) $error++; - if (! $error) + if (!$error) { $db->commit(); setEventMessages($langs->trans("SetupSaved"), null, 'mesgs'); @@ -83,14 +83,14 @@ if ($action == 'setvalue' && $user->admin) */ llxHeader('', $langs->trans("LDAPSetup"), 'EN:Module_LDAP_En|FR:Module_LDAP|ES:Módulo_LDAP'); -$linkback=''.$langs->trans("BackToModuleList").''; +$linkback = ''.$langs->trans("BackToModuleList").''; print load_fiche_titre($langs->trans("LDAPSetup"), $linkback, 'title_setup'); $head = ldap_prepare_head(); // Test si fonction LDAP actives -if (! function_exists("ldap_connect")) +if (!function_exists("ldap_connect")) { setEventMessages($langs->trans("LDAPFunctionsNotAvailableOnPHP"), null, 'errors'); } @@ -105,9 +105,9 @@ print '
'; print ''; print ''; -$form=new Form($db); +$form = new Form($db); -print '
'.$langs->trans("LDAPDolibarrMapping").'
'; +print '
'; print ''; print ''; @@ -129,7 +129,7 @@ print ''; print '
'.$langs->trans("LDAPSynchronizeMembersTypes").'
'; print '
'; -print ''; +print '
'; print ''; print ''; @@ -143,21 +143,21 @@ print "\n"; print ''; -print '"; +print '"; print ''; // Description print ''; -print '"; +print '"; print ''; // User group print ''; -print '"; +print '"; print ''; print '
'.$langs->trans("LDAPDolibarrMapping").'
'.$langs->trans("LDAPFieldName").''; print ''; print ''.$langs->trans("LDAPFieldCommonNameExample").'global->LDAP_KEY_MEMBERS_TYPES && $conf->global->LDAP_KEY_MEMBERS_TYPES==$conf->global->LDAP_MEMBER_TYPE_FIELD_FULLNAME)?' checked':'').">global->LDAP_KEY_MEMBERS_TYPES && $conf->global->LDAP_KEY_MEMBERS_TYPES == $conf->global->LDAP_MEMBER_TYPE_FIELD_FULLNAME) ? ' checked' : '').">
'.$langs->trans("LDAPFieldDescription").''; print ''; print ''.$langs->trans("LDAPFieldDescriptionExample").'global->LDAP_KEY_MEMBERS_TYPES && $conf->global->LDAP_KEY_MEMBER_TYPES==$conf->global->LDAP_MEMBER_TYPE_FIELD_DESCRIPTION)?' checked':'').">global->LDAP_KEY_MEMBERS_TYPES && $conf->global->LDAP_KEY_MEMBER_TYPES == $conf->global->LDAP_MEMBER_TYPE_FIELD_DESCRIPTION) ? ' checked' : '').">
'.$langs->trans("LDAPFieldGroupMembers").''; print ''; print ''.$langs->trans("LDAPFieldGroupMembersExample").'global->LDAP_KEY_MEMBERS_TYPES && $conf->global->LDAP_KEY_MEMBERS_TYPES==$conf->global->LDAP_MEMBER_TYPE_FIELD_GROUPMEMBERS)?' checked':'').">global->LDAP_KEY_MEMBERS_TYPES && $conf->global->LDAP_KEY_MEMBERS_TYPES == $conf->global->LDAP_MEMBER_TYPE_FIELD_GROUPMEMBERS) ? ' checked' : '').">
'; @@ -176,11 +176,11 @@ print ''; */ if ($conf->global->LDAP_MEMBER_TYPE_ACTIVE == '1') { - $butlabel=$langs->trans("LDAPTestSynchroMemberType"); - $testlabel='testmembertype'; - $key=$conf->global->LDAP_KEY_MEMBERS_TYPES; - $dn=$conf->global->LDAP_MEMBER_TYPE_DN; - $objectclass=$conf->global->LDAP_MEMBER_TYPE_OBJECT_CLASS; + $butlabel = $langs->trans("LDAPTestSynchroMemberType"); + $testlabel = 'testmembertype'; + $key = $conf->global->LDAP_KEY_MEMBERS_TYPES; + $dn = $conf->global->LDAP_MEMBER_TYPE_DN; + $objectclass = $conf->global->LDAP_MEMBER_TYPE_OBJECT_CLASS; show_ldap_test_button($butlabel, $testlabel, $key, $dn, $objectclass); } @@ -190,26 +190,26 @@ if (function_exists("ldap_connect")) if ($_GET["action"] == 'testmembertype') { // Creation objet - $object=new AdherentType($db); + $object = new AdherentType($db); $object->initAsSpecimen(); // Test synchro - $ldap=new Ldap(); - $result=$ldap->connect_bind(); + $ldap = new Ldap(); + $result = $ldap->connect_bind(); if ($result > 0) { - $info=$object->_load_ldap_info(); - $dn=$object->_load_ldap_dn($info); + $info = $object->_load_ldap_info(); + $dn = $object->_load_ldap_dn($info); // Get a gid number for objectclass PosixGroup if (in_array('posixGroup', $info['objectclass'])) { $info['gidNumber'] = $ldap->getNextGroupGid('LDAP_KEY_MEMBERS_TYPES'); } - $result1=$ldap->delete($dn); // To be sure to delete existing records - $result2=$ldap->add($dn, $info, $user); // Now the test - $result3=$ldap->delete($dn); // Clean what we did + $result1 = $ldap->delete($dn); // To be sure to delete existing records + $result2 = $ldap->add($dn, $info, $user); // Now the test + $result3 = $ldap->delete($dn); // Clean what we did if ($result2 > 0) { diff --git a/htdocs/admin/ldap_users.php b/htdocs/admin/ldap_users.php index 8d1f7d3279e..1b800612d62 100644 --- a/htdocs/admin/ldap_users.php +++ b/htdocs/admin/ldap_users.php @@ -129,7 +129,7 @@ print $langs->trans("LDAPDescUsers").'
'; print '
'; -print ''; +print '
'; print ''; print ''; @@ -158,7 +158,7 @@ print ''; print '
'.$langs->trans("LDAPSynchronizeUsers").'
'; print '
'; -print ''; +print '
'; print ''; print ''; diff --git a/htdocs/admin/limits.php b/htdocs/admin/limits.php index 27f99ecb4f1..f7b32a2c5ef 100644 --- a/htdocs/admin/limits.php +++ b/htdocs/admin/limits.php @@ -101,7 +101,7 @@ if ($action == 'edit') clearstatcache(); - print '
'.$langs->trans("LDAPDolibarrMapping").'
'; + print '
'; print ''; @@ -135,7 +135,7 @@ if ($action == 'edit') } else { - print '
'.$langs->trans("Parameters").''.$langs->trans("Value").'
'; + print '
'; print ''; diff --git a/htdocs/admin/livraison.php b/htdocs/admin/livraison.php index 794020cfc95..6d08456a470 100644 --- a/htdocs/admin/livraison.php +++ b/htdocs/admin/livraison.php @@ -43,7 +43,7 @@ $action = GETPOST('action', 'alpha'); $value = GETPOST('value', 'alpha'); $label = GETPOST('label', 'alpha'); $scandir = GETPOST('scan_dir', 'alpha'); -$type='delivery'; +$type = 'delivery'; /* @@ -54,13 +54,13 @@ include DOL_DOCUMENT_ROOT.'/core/actions_setmoduleoptions.inc.php'; if ($action == 'updateMask') { - $maskconstdelivery=GETPOST('maskconstdelivery', 'alpha'); - $maskdelivery=GETPOST('maskdelivery', 'alpha'); + $maskconstdelivery = GETPOST('maskconstdelivery', 'alpha'); + $maskdelivery = GETPOST('maskdelivery', 'alpha'); if ($maskconstdelivery) $res = dolibarr_set_const($db, $maskconstdelivery, $maskdelivery, 'chaine', 0, '', $conf->entity); - if (! $res > 0) $error++; + if (!$res > 0) $error++; - if (! $error) + if (!$error) { setEventMessages($langs->trans("SetupSaved"), null, 'mesgs'); } @@ -72,12 +72,12 @@ if ($action == 'updateMask') if ($action == 'set_DELIVERY_FREE_TEXT') { - $free=GETPOST('DELIVERY_FREE_TEXT', 'none'); // No alpha here, we want exact string - $res=dolibarr_set_const($db, "DELIVERY_FREE_TEXT", $free, 'chaine', 0, '', $conf->entity); + $free = GETPOST('DELIVERY_FREE_TEXT', 'none'); // No alpha here, we want exact string + $res = dolibarr_set_const($db, "DELIVERY_FREE_TEXT", $free, 'chaine', 0, '', $conf->entity); - if (! $res > 0) $error++; + if (!$res > 0) $error++; - if (! $error) + if (!$error) { setEventMessages($langs->trans("SetupSaved"), null, 'mesgs'); } @@ -89,20 +89,20 @@ if ($action == 'set_DELIVERY_FREE_TEXT') if ($action == 'specimen') { - $modele=GETPOST('module', 'alpha'); + $modele = GETPOST('module', 'alpha'); $sending = new Livraison($db); $sending->initAsSpecimen(); // Search template files - $file=''; $classname=''; $filefound=0; - $dirmodels=array_merge(array('/'), (array) $conf->modules_parts['models']); - foreach($dirmodels as $reldir) + $file = ''; $classname = ''; $filefound = 0; + $dirmodels = array_merge(array('/'), (array) $conf->modules_parts['models']); + foreach ($dirmodels as $reldir) { - $file=dol_buildpath($reldir."core/modules/livraison/doc/pdf_".$modele.".modules.php", 0); + $file = dol_buildpath($reldir."core/modules/livraison/doc/pdf_".$modele.".modules.php", 0); if (file_exists($file)) { - $filefound=1; + $filefound = 1; $classname = "pdf_".$modele; break; } @@ -176,13 +176,13 @@ if ($action == 'setmod') * View */ -$dirmodels=array_merge(array('/'), (array) $conf->modules_parts['models']); +$dirmodels = array_merge(array('/'), (array) $conf->modules_parts['models']); llxHeader("", ""); -$form=new Form($db); +$form = new Form($db); -$linkback=''.$langs->trans("BackToModuleList").''; +$linkback = ''.$langs->trans("BackToModuleList").''; print load_fiche_titre($langs->trans("SendingsSetup"), $linkback, 'title_setup'); print '
'; $head = expedition_admin_prepare_head(); @@ -194,7 +194,7 @@ dol_fiche_head($head, 'receivings', $langs->trans("Receivings"), -1, 'sending'); print load_fiche_titre($langs->trans("DeliveryOrderNumberingModules"), '', ''); -print '
'.$langs->trans("Parameter").''.$langs->trans("Value").'
'; +print '
'; print ''; print ''; print ''; @@ -214,11 +214,11 @@ foreach ($dirmodels as $reldir) $handle = opendir($dir); if (is_resource($handle)) { - while (($file = readdir($handle))!==false) + while (($file = readdir($handle)) !== false) { - if (substr($file, 0, 14) == 'mod_livraison_' && substr($file, dol_strlen($file)-3, 3) == 'php') + if (substr($file, 0, 14) == 'mod_livraison_' && substr($file, dol_strlen($file) - 3, 3) == 'php') { - $file = substr($file, 0, dol_strlen($file)-4); + $file = substr($file, 0, dol_strlen($file) - 4); require_once $dir.$file.'.php'; @@ -227,7 +227,7 @@ foreach ($dirmodels as $reldir) if ($module->isEnabled()) { // Show modules according to features level - if ($module->version == 'development' && $conf->global->MAIN_FEATURES_LEVEL < 2) continue; + if ($module->version == 'development' && $conf->global->MAIN_FEATURES_LEVEL < 2) continue; if ($module->version == 'experimental' && $conf->global->MAIN_FEATURES_LEVEL < 1) continue; @@ -237,11 +237,11 @@ foreach ($dirmodels as $reldir) // Show example of numbering module print ''."\n"; @@ -256,21 +256,21 @@ foreach ($dirmodels as $reldir) } print ''; - $livraison=new Livraison($db); + $livraison = new Livraison($db); $livraison->initAsSpecimen(); // Info - $htmltooltip=''; - $htmltooltip.=''.$langs->trans("Version").': '.$module->getVersion().'
'; - $nextval=$module->getNextValue($mysoc, $livraison); + $htmltooltip = ''; + $htmltooltip .= ''.$langs->trans("Version").': '.$module->getVersion().'
'; + $nextval = $module->getNextValue($mysoc, $livraison); if ("$nextval" != $langs->trans("NotAvailable")) { // Keep " on nextval - $htmltooltip.=''.$langs->trans("NextValue").': '; + $htmltooltip .= ''.$langs->trans("NextValue").': '; if ($nextval) { - if (preg_match('/^Error/', $nextval) || $nextval=='NotConfigured') + if (preg_match('/^Error/', $nextval) || $nextval == 'NotConfigured') $nextval = $langs->trans($nextval); - $htmltooltip.=$nextval.'
'; + $htmltooltip .= $nextval.'
'; } else { - $htmltooltip.=$langs->trans($module->error).'
'; + $htmltooltip .= $langs->trans($module->error).'
'; } } @@ -297,19 +297,19 @@ print '
'; print load_fiche_titre($langs->trans("DeliveryOrderModel"), '', ''); // Defini tableau def de modele -$type="delivery"; +$type = "delivery"; $def = array(); $sql = "SELECT nom"; -$sql.= " FROM ".MAIN_DB_PREFIX."document_model"; -$sql.= " WHERE type = '".$type."'"; -$sql.= " AND entity = ".$conf->entity; +$sql .= " FROM ".MAIN_DB_PREFIX."document_model"; +$sql .= " WHERE type = '".$type."'"; +$sql .= " AND entity = ".$conf->entity; -$resql=$db->query($sql); +$resql = $db->query($sql); if ($resql) { $i = 0; - $num_rows=$db->num_rows($resql); + $num_rows = $db->num_rows($resql); while ($i < $num_rows) { $array = $db->fetch_array($resql); @@ -322,7 +322,7 @@ else dol_print_error($db); } -print '
'.$langs->trans("Name").''.$langs->trans("Description").''; - $tmp=$module->getExample(); + $tmp = $module->getExample(); if (preg_match('/^Error/', $tmp)) { $langs->load("errors"); print '
'.$langs->trans($tmp).'
'; } - elseif ($tmp=='NotConfigured') print $langs->trans($tmp); + elseif ($tmp == 'NotConfigured') print $langs->trans($tmp); else print $tmp; print '
'; +print '
'; print ''; print ''; print ''; @@ -343,33 +343,33 @@ foreach ($dirmodels as $reldir) $handle = opendir($dir); if (is_resource($handle)) { - while (($file = readdir($handle))!==false) + while (($file = readdir($handle)) !== false) { - $filelist[]=$file; + $filelist[] = $file; } closedir($handle); arsort($filelist); - foreach($filelist as $file) + foreach ($filelist as $file) { if (preg_match('/\.modules\.php$/i', $file) && preg_match('/^(pdf_|doc_)/', $file)) { if (file_exists($dir.'/'.$file)) { - $name = substr($file, 4, dol_strlen($file) -16); - $classname = substr($file, 0, dol_strlen($file) -12); + $name = substr($file, 4, dol_strlen($file) - 16); + $classname = substr($file, 0, dol_strlen($file) - 12); require_once $dir.'/'.$file; $module = new $classname($db); - $modulequalified=1; - if ($module->version == 'development' && $conf->global->MAIN_FEATURES_LEVEL < 2) $modulequalified=0; - if ($module->version == 'experimental' && $conf->global->MAIN_FEATURES_LEVEL < 1) $modulequalified=0; + $modulequalified = 1; + if ($module->version == 'development' && $conf->global->MAIN_FEATURES_LEVEL < 2) $modulequalified = 0; + if ($module->version == 'experimental' && $conf->global->MAIN_FEATURES_LEVEL < 1) $modulequalified = 0; if ($modulequalified) { print ''; // Info - $htmltooltip = ''.$langs->trans("Type").': '.($module->type?$module->type:$langs->trans("Unknown")); - $htmltooltip.='
'.$langs->trans("Width").'/'.$langs->trans("Height").': '.$module->page_largeur.'/'.$module->page_hauteur; - $htmltooltip.='

'.$langs->trans("FeaturesSupported").':'; - $htmltooltip.='
'.$langs->trans("Logo").': '.yn($module->option_logo, 1, 1); + $htmltooltip = ''.$langs->trans("Type").': '.($module->type ? $module->type : $langs->trans("Unknown")); + $htmltooltip .= '
'.$langs->trans("Width").'/'.$langs->trans("Height").': '.$module->page_largeur.'/'.$module->page_hauteur; + $htmltooltip .= '

'.$langs->trans("FeaturesSupported").':'; + $htmltooltip .= '
'.$langs->trans("Logo").': '.yn($module->option_logo, 1, 1); print ''; @@ -440,25 +440,25 @@ print '
'.$langs->trans("Name").''.$langs->trans("Description").'
'; - print (empty($module->name)?$name:$module->name); + print (empty($module->name) ? $name : $module->name); print "\n"; if (method_exists($module, 'info')) print $module->info($langs); else print $module->description; @@ -404,10 +404,10 @@ foreach ($dirmodels as $reldir) print ''; print $form->textwithpicto('', $htmltooltip, 1, 0); print '
'; print "
"; print load_fiche_titre($langs->trans("OtherOptions"), '', ''); -print ''; +print '
'; print ''; print ''; print ''; print ''; print "\n"; -$substitutionarray=pdf_getSubstitutionArray($langs, null, null, 2); -$substitutionarray['__(AnyTranslationKey)__']=$langs->trans("Translation"); +$substitutionarray = pdf_getSubstitutionArray($langs, null, null, 2); +$substitutionarray['__(AnyTranslationKey)__'] = $langs->trans("Translation"); $htmltext = ''.$langs->trans("AvailableVariables").':
'; -foreach($substitutionarray as $key => $val) $htmltext.=$key.'
'; -$htmltext.='
'; +foreach ($substitutionarray as $key => $val) $htmltext .= $key.'
'; +$htmltext .= ''; print ''; print ''; print ''; print '
'.$langs->trans("Parameter").''.$langs->trans("Value").' 
'; print $form->textwithpicto($langs->trans("FreeLegalTextOnDeliveryReceipts"), $langs->trans("AddCRIfTooLong").'

'.$htmltext, 1, 'help', '', 0, 2, 'freetexttooltip').'
'; -$variablename='DELIVERY_FREE_TEXT'; +$variablename = 'DELIVERY_FREE_TEXT'; if (empty($conf->global->PDF_ALLOW_HTML_FOR_FREE_TEXT)) { print ''; @@ -466,7 +466,7 @@ if (empty($conf->global->PDF_ALLOW_HTML_FOR_FREE_TEXT)) else { include_once DOL_DOCUMENT_ROOT.'/core/class/doleditor.class.php'; - $doleditor=new DolEditor($variablename, $conf->global->$variablename, '', 80, 'dolibarr_notes'); + $doleditor = new DolEditor($variablename, $conf->global->$variablename, '', 80, 'dolibarr_notes'); print $doleditor->Create(); } print '
'; diff --git a/htdocs/admin/loan.php b/htdocs/admin/loan.php index 46d104736b0..a97952cb2df 100644 --- a/htdocs/admin/loan.php +++ b/htdocs/admin/loan.php @@ -26,7 +26,7 @@ require '../main.inc.php'; // Class require_once DOL_DOCUMENT_ROOT.'/core/lib/admin.lib.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.'/core/class/html.formaccounting.class.php'; // Load translation files required by the page $langs->loadLangs(array('admin', 'loan')); @@ -38,7 +38,7 @@ if (!$user->admin) $action = GETPOST('action', 'alpha'); // Other parameters LOAN_* -$list = array ( +$list = array( 'LOAN_ACCOUNTING_ACCOUNT_CAPITAL', 'LOAN_ACCOUNTING_ACCOUNT_INTEREST', 'LOAN_ACCOUNTING_ACCOUNT_INSURANCE' @@ -60,7 +60,7 @@ if ($action == 'update') } } - if (! $error) + if (!$error) { setEventMessages($langs->trans("SetupSaved"), null, 'mesgs'); } @@ -77,9 +77,9 @@ if ($action == 'update') llxHeader(); $form = new Form($db); -if (! empty($conf->accounting->enabled)) $formaccounting = new FormAccounting($db); +if (!empty($conf->accounting->enabled)) $formaccounting = new FormAccounting($db); -$linkback=''.$langs->trans("BackToModuleList").''; +$linkback = ''.$langs->trans("BackToModuleList").''; print load_fiche_titre($langs->trans('ConfigLoan'), $linkback, 'title_setup'); print ''; @@ -89,9 +89,9 @@ print ''; /* * Params */ -print ''; +print '
'; print ''; -print ''; +print ''; print "\n"; foreach ($list as $key) @@ -104,7 +104,7 @@ foreach ($list as $key) // Value print '
' . $langs->trans('Options') . ''.$langs->trans('Options').'
'; - if (! empty($conf->accounting->enabled)) + if (!empty($conf->accounting->enabled)) { print $formaccounting->select_account($conf->global->$key, $key, 1, '', 1, 1); } diff --git a/htdocs/admin/mailing.php b/htdocs/admin/mailing.php index 6ff32e1d406..715633ca77e 100644 --- a/htdocs/admin/mailing.php +++ b/htdocs/admin/mailing.php @@ -105,7 +105,7 @@ print ''; print ''; print ''; -print ''; +print '
'; print ''; print ''; print ''; diff --git a/htdocs/admin/mails.php b/htdocs/admin/mails.php index 61fb0448c8b..c52f899a03f 100644 --- a/htdocs/admin/mails.php +++ b/htdocs/admin/mails.php @@ -111,6 +111,8 @@ if ($action == 'presend' && GETPOST('trackid', 'alphanohtml') == 'testhtml') $ * View */ +$form = new Form($db); + $linuxlike=1; if (preg_match('/^win/i', PHP_OS)) $linuxlike=0; if (preg_match('/^mac/i', PHP_OS)) $linuxlike=0; @@ -139,8 +141,6 @@ $listofmethods['swiftmailer']='Swift Mailer socket library'; if ($action == 'edit') { - $form=new Form($db); - if ($conf->use_javascript_ajax) { print "\n".''; -$arrayofselected=is_array($toselect)?$toselect:array(); +$arrayofselected = is_array($toselect) ? $toselect : array(); -$param=''; -if (! empty($contextpage) && $contextpage != $_SERVER["PHP_SELF"]) $param.='&contextpage='.urlencode($contextpage); -if ($limit > 0 && $limit != $conf->liste_limit) $param.='&limit='.urlencode($limit); -foreach($search as $key => $val) +$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) { - $param.= '&search_'.$key.'='.urlencode($search[$key]); + 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'; // List of mass actions available -$arrayofmassactions = array( +$arrayofmassactions = array( //'presend'=>$langs->trans("SendByMail"), //'builddoc'=>$langs->trans("PDFMerge"), ); -if ($user->rights->monmodule->delete) $arrayofmassactions['predelete']=''.$langs->trans("Delete"); -if (in_array($massaction, array('presend','predelete'))) $arrayofmassactions=array(); -$massactionbutton=$form->selectMassAction('', $arrayofmassactions); +//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 ''; @@ -311,59 +350,103 @@ print ''; print ''; print ''; +$newcardbutton = ''; +if ($action != 'create') { + $newcardbutton = dolGetButtonTitle($langs->trans('New'), '', 'fa fa-plus-circle', $_SERVER['PHP_SELF'].'?action=create', '', $permissiontoadd); +} else { + print ''; + if ($optioncss != '') print ''; + print ''; + print ''; + print ''; + print ''; + print ''; + print ''; + print '
'.$langs->trans("Parameter").''.$langs->trans("Value").'
'; + print ''; + print ''; + print ''; + print ''; + print ''; + print '
'.$langs->trans("Label").'
'.$langs->trans("Email").'
'.$langs->trans("Signature").'
'.$langs->trans("Position").'
'.$langs->trans("Status").''; + print ''; + print '
'; + print '
'; + print '
'; + print ''; + print '   '; + print ''; + print '
'; + print ''; +} + +print_barre_liste('', $page, $_SERVER["PHP_SELF"], $param, $sortfield, $sortorder, $massactionbutton, $num, $nbtotalofrecords, 'title_companies', 0, $newcardbutton, '', $limit); //print_barre_liste($title, $page, $_SERVER["PHP_SELF"], $param, $sortfield, $sortorder, $massactionbutton, $num, $nbtotalofrecords, 'title_companies', 0, '', '', $limit); -$topicmail="Information"; +$topicmail = "Information"; //$modelmail="subscription"; -$objecttmp=new EmailSenderProfile($db); +$objecttmp = new EmailSenderProfile($db); //$trackid='sub'.$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); + print '
'.$langs->trans("FilterOnInto", $search_all).join(', ', $fieldstosearchall).'
'; +} + $moreforfilter = ''; /*$moreforfilter.='
'; $moreforfilter.= $langs->trans('MyFilter') . ': '; $moreforfilter.= '
';*/ -$parameters=array(); -$reshook=$hookmanager->executeHooks('printFieldPreListTitle', $parameters, $object); // Note that $action and $object may have been modified by hook +$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($moreforfilter)) +if (!empty($moreforfilter)) { print '
'; print $moreforfilter; print '
'; } -$varpage=empty($contextpage)?$_SERVER["PHP_SELF"]:$contextpage; -$selectedfields=$form->multiSelectArrayWithCheckbox('selectedfields', $arrayfields, $varpage); // This also change content of $arrayfields -$selectedfields.=(count($arrayofmassactions) ? $form->showCheckAddButtons('checkforselect', 1) : ''); +$varpage = empty($contextpage) ? $_SERVER["PHP_SELF"] : $contextpage; +$selectedfields = $form->multiSelectArrayWithCheckbox('selectedfields', $arrayfields, $varpage); // This also change content of $arrayfields +$selectedfields .= (count($arrayofmassactions) ? $form->showCheckAddButtons('checkforselect', 1) : ''); -print '
'; // You can use div-table-responsive-no-min if you dont need reserved height for your table -print ''."\n"; +print '
'; // You can use div-table-responsive-no-min if you dont need reserved height for your table +print '
'."\n"; // Fields title search // -------------------------------------------------------------------- print ''; -foreach($object->fields as $key => $val) +foreach ($object->fields as $key => $val) { - $align=''; - if (in_array($val['type'], array('date','datetime','timestamp'))) $align.=($align?' ':'').'center'; - if (in_array($val['type'], array('timestamp'))) $align.=($align?' ':'').'nowrap'; - if ($key == 'status') $align.=($align?' ':'').'center'; - if (! empty($arrayfields['t.'.$key]['checked'])) print ''; + $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'])) + { + print ''; + } } // Extra fields include DOL_DOCUMENT_ROOT.'/core/tpl/extrafields_list_search_input.tpl.php'; // Fields from hook -$parameters=array('arrayfields'=>$arrayfields); -$reshook=$hookmanager->executeHooks('printFieldListOption', $parameters, $object); // Note that $action and $object may have been modified by hook +$parameters = array('arrayfields'=>$arrayfields); +$reshook = $hookmanager->executeHooks('printFieldListOption', $parameters, $object); // Note that $action and $object may have been modified by hook print $hookmanager->resPrint; // Action column print ''; print ''."\n"; @@ -372,68 +455,81 @@ print ''."\n"; // Fields title label // -------------------------------------------------------------------- print ''; -foreach($object->fields as $key => $val) +foreach ($object->fields as $key => $val) { - $align=''; - if (in_array($val['type'], array('date','datetime','timestamp'))) $align.=($align?' ':'').'center'; - if (in_array($val['type'], array('timestamp'))) $align.=($align?' ':'').'nowrap'; - if ($key == 'status') $align.=($align?' ':'').'center'; - if (! empty($arrayfields['t.'.$key]['checked'])) print getTitleFieldOfList($arrayfields['t.'.$key]['label'], 0, $_SERVER['PHP_SELF'], 't.'.$key, '', $param, ($align?'class="'.$align.'"':''), $sortfield, $sortorder, $align.' ')."\n"; + $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'])) + { + print getTitleFieldOfList($arrayfields['t.'.$key]['label'], 0, $_SERVER['PHP_SELF'], 't.'.$key, '', $param, ($cssforfield ? 'class="'.$cssforfield.'"' : ''), $sortfield, $sortorder, ($cssforfield ? $cssforfield.' ' : ''))."\n"; + } } // 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, $object); // Note that $action and $object may have been modified by hook +$parameters = array('arrayfields'=>$arrayfields, 'param'=>$param, 'sortfield'=>$sortfield, 'sortorder'=>$sortorder); +$reshook = $hookmanager->executeHooks('printFieldListTitle', $parameters, $object); // Note that $action and $object may have been modified by hook print $hookmanager->resPrint; -print getTitleFieldOfList($selectedfields, 0, $_SERVER["PHP_SELF"], "", '', '', 'align="center"', $sortfield, $sortorder, 'maxwidthsearch ')."\n"; +// Action column +print getTitleFieldOfList($selectedfields, 0, $_SERVER["PHP_SELF"], '', '', '', '', $sortfield, $sortorder, 'center maxwidthsearch ')."\n"; print ''."\n"; // Detect if we need a fetch on each output line -$needToFetchEachLine=0; -foreach ($extrafields->attributes[$object->table_element]['computed'] as $key => $val) +$needToFetchEachLine = 0; +if (is_array($extrafields->attributes[$object->table_element]['computed']) && count($extrafields->attributes[$object->table_element]['computed']) > 0) { - if (preg_match('/\$object/', $val)) $needToFetchEachLine++; // There is at least one compute field that use $object + 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 + } } // Loop on record // -------------------------------------------------------------------- -$i=0; -$totalarray=array(); -while ($i < min($num, $limit)) +$i = 0; +$totalarray = array(); +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->id = $obj->rowid; - foreach($object->fields as $key => $val) + foreach ($object->fields as $key => $val) { if (property_exists($obj, $key)) $object->$key = $obj->$key; } // Show here line of result print ''; - foreach($object->fields as $key => $val) + foreach ($object->fields as $key => $val) { - $align=''; - if (in_array($val['type'], array('date','datetime','timestamp'))) $align.=($align?' ':'').'center'; - if (in_array($val['type'], array('timestamp'))) $align.=($align?' ':'').'nowrap'; - if ($key == 'status') $align.=($align?' ':'').'center'; - if (! empty($arrayfields['t.'.$key]['checked'])) + $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('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 (!empty($arrayfields['t.'.$key]['checked'])) { - print ''; - print $object->showOutputField($val, $key, $obj->$key, ''); + print ''; + if ($key == 'status') print $object->getLibStatut(5); + elseif (in_array($val['type'], array('date', 'datetime', 'timestamp'))) print $object->showOutputField($val, $key, $db->jdate($obj->$key), ''); + else print $object->showOutputField($val, $key, $obj->$key, ''); print ''; - if (! $i) $totalarray['nbfield']++; - if (! empty($val['isameasure'])) + if (!$i) $totalarray['nbfield']++; + if (!empty($val['isameasure'])) { - if (! $i) $totalarray['pos'][$totalarray['nbfield']]='t.'.$key; + if (!$i) $totalarray['pos'][$totalarray['nbfield']] = 't.'.$key; $totalarray['val']['t.'.$key] += $obj->$key; } } @@ -441,21 +537,29 @@ while ($i < min($num, $limit)) // Extra fields include DOL_DOCUMENT_ROOT.'/core/tpl/extrafields_list_print_fields.tpl.php'; // Fields from hook - $parameters=array('arrayfields'=>$arrayfields, 'obj'=>$obj); - $reshook=$hookmanager->executeHooks('printFieldListValue', $parameters, $object); // Note that $action and $object may have been modified by hook + $parameters = array('arrayfields'=>$arrayfields, 'obj'=>$obj, 'i'=>$i, 'totalarray'=>&$totalarray); + $reshook = $hookmanager->executeHooks('printFieldListValue', $parameters, $object); // Note that $action and $object may have been modified by hook print $hookmanager->resPrint; // Action column - print ''; - if (! $i) $totalarray['nbfield']++; + if (!$i) $totalarray['nbfield']++; - print ''; + print ''."\n"; $i++; } @@ -467,16 +571,16 @@ include DOL_DOCUMENT_ROOT.'/core/tpl/list_print_total.tpl.php'; // If no record found if ($num == 0) { - $colspan=1; - foreach($arrayfields as $key => $val) { if (! empty($val['checked'])) $colspan++; } + $colspan = 1; + foreach ($arrayfields as $key => $val) { if (!empty($val['checked'])) $colspan++; } print ''; } $db->free($resql); -$parameters=array('arrayfields'=>$arrayfields, 'sql'=>$sql); -$reshook=$hookmanager->executeHooks('printFieldListFooter', $parameters, $object); // Note that $action and $object may have been modified by hook +$parameters = array('arrayfields'=>$arrayfields, 'sql'=>$sql); +$reshook = $hookmanager->executeHooks('printFieldListFooter', $parameters, $object); // Note that $action and $object may have been modified by hook print $hookmanager->resPrint; print '
'; + if (is_array($val['arrayofkeyval'])) print $form->selectarray('search_'.$key, $val['arrayofkeyval'], $search[$key], $val['notnull'], 0, 0, '', 1, 0, 0, '', 'maxwidth75'); + else print ''; + print ''; -$searchpicto=$form->showFilterButtons(); +$searchpicto = $form->showFilterButtons(); print $searchpicto; print '
'; + print ''; + $url = $_SERVER["PHP_SELF"].'?action=list&id='.$obj->rowid; + if ($limit) $url.='&limit='.urlencode($limit); + if ($page) $url.='&page='.urlencode($page); + if ($sortfield) $url.='&sortfield='.urlencode($sortfield); + if ($sortorder) $url.='&page='.urlencode($sortorder); + //print ''.img_edit().''; + //print '   '; + print ''.img_delete().'   '; if ($massactionbutton || $massaction) // If we are in select mode (massactionbutton defined) or if we have already selected and sent an action ($massaction) defined { - $selected=0; - if (in_array($obj->rowid, $arrayofselected)) $selected=1; - print ''; + $selected = 0; + if (in_array($obj->rowid, $arrayofselected)) $selected = 1; + print ''; } print '
'.$langs->trans("NoRecordFound").'
'."\n"; @@ -486,21 +590,21 @@ print ''."\n"; if (in_array('builddoc', $arrayofmassactions) && ($nbtotalofrecords === '' || $nbtotalofrecords)) { + $hidegeneratedfilelistifempty = 1; + 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); - $hidegeneratedfilelistifempty=1; - if ($massaction == 'builddoc' || $action == 'remove_file' || $show_files) $hidegeneratedfilelistifempty=0; - // Show list of available documents - $urlsource=$_SERVER['PHP_SELF'].'?sortfield='.$sortfield.'&sortorder='.$sortorder; - $urlsource.=str_replace('&', '&', $param); + $urlsource = $_SERVER['PHP_SELF'].'?sortfield='.$sortfield.'&sortorder='.$sortorder; + $urlsource .= str_replace('&', '&', $param); - $filedir=$diroutputmassaction; - $genallowed=$user->rights->monmodule->read; - $delallowed=$user->rights->monmodule->create; + $filedir = $diroutputmassaction; + $genallowed = $permissiontoread; + $delallowed = $permissiontoadd; - print $formfile->showdocuments('massfilesarea_monmodule', '', $filedir, $urlsource, 0, $delallowed, '', 1, 1, 0, 48, 1, $param, $title, '', '', '', null, $hidegeneratedfilelistifempty); + print $formfile->showdocuments('massfilesarea_emailsenderprofile', '', $filedir, $urlsource, 0, $delallowed, '', 1, 1, 0, 48, 1, $param, $title, '', '', '', null, $hidegeneratedfilelistifempty); } dol_fiche_end(); diff --git a/htdocs/admin/mails_templates.php b/htdocs/admin/mails_templates.php index 7ac91d51c8d..aa8a7e79719 100644 --- a/htdocs/admin/mails_templates.php +++ b/htdocs/admin/mails_templates.php @@ -451,7 +451,7 @@ print ''; print ''; print '
'; -print ''; +print '
'; // Line to enter new values (title) print ''; @@ -597,7 +597,7 @@ print ''; print ''; print '
'; -print '
'; +print '
'; // List of available record in database dol_syslog("htdocs/admin/dict", LOG_DEBUG); diff --git a/htdocs/admin/menus.php b/htdocs/admin/menus.php index 4187c4d3eb4..fdbf34a5e13 100644 --- a/htdocs/admin/menus.php +++ b/htdocs/admin/menus.php @@ -162,7 +162,7 @@ print "
\n"; clearstatcache(); // Gestionnaires de menu -print '
'; +print '
'; print ''; print ''; @@ -372,7 +372,7 @@ if ($conf->use_javascript_ajax) // Process remaining records (records that are not linked to root by any path) $remainingdata = array(); - foreach($data as $datar) + foreach ($data as $datar) { if (empty($datar['rowid']) || $tree_recur_alreadyadded[$datar['rowid']]) continue; $remainingdata[] = $datar; @@ -389,9 +389,9 @@ if ($conf->use_javascript_ajax) print ''; print '
'.$langs->trans("Menu").''; print $form->textwithpicto($langs->trans("InternalUsers"), $langs->trans("InternalExternalDesc")); diff --git a/htdocs/admin/menus/edit.php b/htdocs/admin/menus/edit.php index 5a54a9e5c9f..b55edaa4ba7 100644 --- a/htdocs/admin/menus/edit.php +++ b/htdocs/admin/menus/edit.php @@ -29,32 +29,32 @@ require_once DOL_DOCUMENT_ROOT.'/core/class/html.formadmin.class.php'; require_once DOL_DOCUMENT_ROOT.'/core/class/menubase.class.php'; // Load translation files required by the page -$langs->loadLangs(array("other","admin")); +$langs->loadLangs(array("other", "admin")); -if (! $user->admin) accessforbidden(); +if (!$user->admin) accessforbidden(); $dirstandard = array(); $dirsmartphone = array(); -$dirmenus=array_merge(array("/core/menus/"), (array) $conf->modules_parts['menus']); -foreach($dirmenus as $dirmenu) +$dirmenus = array_merge(array("/core/menus/"), (array) $conf->modules_parts['menus']); +foreach ($dirmenus as $dirmenu) { - $dirstandard[]=$dirmenu.'standard'; - $dirsmartphone[]=$dirmenu.'smartphone'; + $dirstandard[] = $dirmenu.'standard'; + $dirsmartphone[] = $dirmenu.'smartphone'; } -$action=GETPOST('action', 'aZ09'); +$action = GETPOST('action', 'aZ09'); -$menu_handler_top=$conf->global->MAIN_MENU_STANDARD; -$menu_handler_smartphone=$conf->global->MAIN_MENU_SMARTPHONE; -$menu_handler_top=preg_replace('/_backoffice.php/i', '', $menu_handler_top); -$menu_handler_top=preg_replace('/_frontoffice.php/i', '', $menu_handler_top); -$menu_handler_smartphone=preg_replace('/_backoffice.php/i', '', $menu_handler_smartphone); -$menu_handler_smartphone=preg_replace('/_frontoffice.php/i', '', $menu_handler_smartphone); +$menu_handler_top = $conf->global->MAIN_MENU_STANDARD; +$menu_handler_smartphone = $conf->global->MAIN_MENU_SMARTPHONE; +$menu_handler_top = preg_replace('/_backoffice.php/i', '', $menu_handler_top); +$menu_handler_top = preg_replace('/_frontoffice.php/i', '', $menu_handler_top); +$menu_handler_smartphone = preg_replace('/_backoffice.php/i', '', $menu_handler_smartphone); +$menu_handler_smartphone = preg_replace('/_frontoffice.php/i', '', $menu_handler_smartphone); -$menu_handler=$menu_handler_top; +$menu_handler = $menu_handler_top; -if (GETPOST("handler_origine")) $menu_handler=GETPOST("handler_origine"); -if (GETPOST("menu_handler")) $menu_handler=GETPOST("menu_handler"); +if (GETPOST("handler_origine")) $menu_handler = GETPOST("handler_origine"); +if (GETPOST("menu_handler")) $menu_handler = GETPOST("menu_handler"); @@ -64,53 +64,53 @@ if (GETPOST("menu_handler")) $menu_handler=GETPOST("menu_handler"); if ($action == 'update') { - if (! $_POST['cancel']) + if (!$_POST['cancel']) { - $leftmenu=''; $mainmenu=''; - if (! empty($_POST['menuIdParent']) && ! is_numeric($_POST['menuIdParent'])) + $leftmenu = ''; $mainmenu = ''; + if (!empty($_POST['menuIdParent']) && !is_numeric($_POST['menuIdParent'])) { - $tmp=explode('&', $_POST['menuIdParent']); - foreach($tmp as $s) + $tmp = explode('&', $_POST['menuIdParent']); + foreach ($tmp as $s) { if (preg_match('/fk_mainmenu=/', $s)) { - $mainmenu=preg_replace('/fk_mainmenu=/', '', $s); + $mainmenu = preg_replace('/fk_mainmenu=/', '', $s); } if (preg_match('/fk_leftmenu=/', $s)) { - $leftmenu=preg_replace('/fk_leftmenu=/', '', $s); + $leftmenu = preg_replace('/fk_leftmenu=/', '', $s); } } } $menu = new Menubase($db); - $result=$menu->fetch(GETPOST('menuId', 'int')); + $result = $menu->fetch(GETPOST('menuId', 'int')); if ($result > 0) { - $menu->titre=GETPOST('titre', 'alpha'); // deprecated - $menu->title=GETPOST('titre', 'alpha'); - $menu->leftmenu=GETPOST('leftmenu', 'aZ09'); - $menu->url=GETPOST('url', 'alpha'); - $menu->langs=GETPOST('langs', 'alpha'); - $menu->position=GETPOST('position', 'int'); - $menu->enabled=GETPOST('enabled', 'alpha'); - $menu->perms=GETPOST('perms', 'alpha'); - $menu->target=GETPOST('target', 'alpha'); - $menu->user=GETPOST('user', 'alpha'); - $menu->mainmenu=GETPOST('propertymainmenu', 'alpha'); + $menu->titre = GETPOST('titre', 'alpha'); // deprecated + $menu->title = GETPOST('titre', 'alpha'); + $menu->leftmenu = GETPOST('leftmenu', 'aZ09'); + $menu->url = GETPOST('url', 'alpha'); + $menu->langs = GETPOST('langs', 'alpha'); + $menu->position = GETPOST('position', 'int'); + $menu->enabled = GETPOST('enabled', 'alpha'); + $menu->perms = GETPOST('perms', 'alpha'); + $menu->target = GETPOST('target', 'alpha'); + $menu->user = GETPOST('user', 'alpha'); + $menu->mainmenu = GETPOST('propertymainmenu', 'alpha'); if (is_numeric(GETPOST('menuIdParent', 'alpha'))) { - $menu->fk_menu=GETPOST('menuIdParent', 'alpha'); + $menu->fk_menu = GETPOST('menuIdParent', 'alpha'); } else { - if (GETPOST('type', 'alpha') == 'top') $menu->fk_menu=0; - else $menu->fk_menu=-1; - $menu->fk_mainmenu=$mainmenu; - $menu->fk_leftmenu=$leftmenu; + if (GETPOST('type', 'alpha') == 'top') $menu->fk_menu = 0; + else $menu->fk_menu = -1; + $menu->fk_mainmenu = $mainmenu; + $menu->fk_leftmenu = $leftmenu; } - $result=$menu->update($user); + $result = $menu->update($user); if ($result > 0) { setEventMessages($langs->trans("RecordModifiedSuccessfully"), null, 'mesgs'); @@ -144,91 +144,91 @@ if ($action == 'add') exit; } - $leftmenu=''; $mainmenu=''; - if (GETPOST('menuId', 'alpha', 3) && ! is_numeric(GETPOST('menuId', 'alpha', 3))) + $leftmenu = ''; $mainmenu = ''; + if (GETPOST('menuId', 'alpha', 3) && !is_numeric(GETPOST('menuId', 'alpha', 3))) { - $tmp=explode('&', GETPOST('menuId', 'alpha', 3)); - foreach($tmp as $s) + $tmp = explode('&', GETPOST('menuId', 'alpha', 3)); + foreach ($tmp as $s) { if (preg_match('/fk_mainmenu=/', $s)) { - $mainmenu=preg_replace('/fk_mainmenu=/', '', $s); + $mainmenu = preg_replace('/fk_mainmenu=/', '', $s); } if (preg_match('/fk_leftmenu=/', $s)) { - $leftmenu=preg_replace('/fk_leftmenu=/', '', $s); + $leftmenu = preg_replace('/fk_leftmenu=/', '', $s); } } } $langs->load("errors"); - $error=0; - if (! $error && ! $_POST['menu_handler']) + $error = 0; + if (!$error && !$_POST['menu_handler']) { setEventMessages($langs->trans("ErrorFieldRequired", $langs->transnoentities("MenuHandler")), null, 'errors'); $action = 'create'; $error++; } - if (! $error && ! $_POST['type']) + if (!$error && !$_POST['type']) { setEventMessages($langs->trans("ErrorFieldRequired", $langs->transnoentities("Type")), null, 'errors'); $action = 'create'; $error++; } - if (! $error && ! $_POST['url']) + if (!$error && !$_POST['url']) { setEventMessages($langs->trans("ErrorFieldRequired", $langs->transnoentitiesnoconv("URL")), null, 'errors'); $action = 'create'; $error++; } - if (! $error && ! $_POST['titre']) + if (!$error && !$_POST['titre']) { setEventMessages($langs->trans("ErrorFieldRequired", $langs->transnoentitiesnoconv("Title")), null, 'errors'); $action = 'create'; $error++; } - if (! $error && $_POST['menuId'] && $_POST['type'] == 'top') + if (!$error && $_POST['menuId'] && $_POST['type'] == 'top') { setEventMessages($langs->trans("ErrorTopMenuMustHaveAParentWithId0"), null, 'errors'); $action = 'create'; $error++; } - if (! $error && ! $_POST['menuId'] && $_POST['type'] == 'left') + if (!$error && !$_POST['menuId'] && $_POST['type'] == 'left') { setEventMessages($langs->trans("ErrorLeftMenuMustHaveAParentId"), null, 'errors'); $action = 'create'; $error++; } - if (! $error) + if (!$error) { $menu = new Menubase($db); - $menu->menu_handler=preg_replace('/_menu$/', '', GETPOST('menu_handler', 'aZ09')); - $menu->type=GETPOST('type', 'alpha'); - $menu->titre=GETPOST('titre', 'alpha'); // deprecated - $menu->title=GETPOST('titre', 'alpha'); - $menu->url=GETPOST('url', 'alpha'); - $menu->langs=GETPOST('langs', 'alpha'); - $menu->position=GETPOST('position', 'int'); - $menu->enabled=GETPOST('enabled', 'alpha'); - $menu->perms=GETPOST('perms', 'alpha'); - $menu->target=GETPOST('target', 'alpha'); - $menu->user=GETPOST('user', 'alpha'); - $menu->mainmenu=GETPOST('propertymainmenu', 'alpha'); + $menu->menu_handler = preg_replace('/_menu$/', '', GETPOST('menu_handler', 'aZ09')); + $menu->type = GETPOST('type', 'alpha'); + $menu->titre = GETPOST('titre', 'alpha'); // deprecated + $menu->title = GETPOST('titre', 'alpha'); + $menu->url = GETPOST('url', 'alpha'); + $menu->langs = GETPOST('langs', 'alpha'); + $menu->position = GETPOST('position', 'int'); + $menu->enabled = GETPOST('enabled', 'alpha'); + $menu->perms = GETPOST('perms', 'alpha'); + $menu->target = GETPOST('target', 'alpha'); + $menu->user = GETPOST('user', 'alpha'); + $menu->mainmenu = GETPOST('propertymainmenu', 'alpha'); if (is_numeric(GETPOST('menuId', 'alpha', 3))) { - $menu->fk_menu=GETPOST('menuId', 'alpha', 3); + $menu->fk_menu = GETPOST('menuId', 'alpha', 3); } else { - if (GETPOST('type', 'alpha') == 'top') $menu->fk_menu=0; - else $menu->fk_menu=-1; - $menu->fk_mainmenu=$mainmenu; - $menu->fk_leftmenu=$leftmenu; + if (GETPOST('type', 'alpha') == 'top') $menu->fk_menu = 0; + else $menu->fk_menu = -1; + $menu->fk_mainmenu = $mainmenu; + $menu->fk_leftmenu = $leftmenu; } - $result=$menu->create($user); + $result = $menu->create($user); if ($result > 0) { header("Location: ".DOL_URL_ROOT."/admin/menus/index.php?menu_handler=".GETPOST('menu_handler', 'aZ09')); @@ -248,7 +248,7 @@ if ($action == 'confirm_delete' && $_POST["confirm"] == 'yes') $this->db->begin(); $sql = "DELETE FROM ".MAIN_DB_PREFIX."menu WHERE rowid = ".GETPOST('menuId', 'int'); - $result=$db->query($sql); + $result = $db->query($sql); if ($result == 0) { @@ -257,14 +257,14 @@ if ($action == 'confirm_delete' && $_POST["confirm"] == 'yes') llxHeader(); setEventMessages($langs->trans("MenuDeleted"), null, 'mesgs'); llxFooter(); - exit ; + exit; } else { $this->db->rollback(); $reload = 0; - $_GET["action"]=''; + $_GET["action"] = ''; } } @@ -274,8 +274,8 @@ if ($action == 'confirm_delete' && $_POST["confirm"] == 'yes') * View */ -$form=new Form($db); -$formadmin=new FormAdmin($db); +$form = new Form($db); +$formadmin = new FormAdmin($db); llxHeader('', $langs->trans("Menu")); @@ -313,14 +313,14 @@ if ($action == 'create') dol_fiche_head(); - print ''; + print '
'; // Id $parent_rowid = GETPOST('menuId', 'int'); if (GETPOST('menuId', 'int')) { $sql = "SELECT m.rowid, m.mainmenu, m.leftmenu, m.level, m.langs FROM ".MAIN_DB_PREFIX."menu as m WHERE m.rowid = ".GETPOST('menuId', 'int'); - $res = $db->query($sql); + $res = $db->query($sql); if ($res) { while ($menu = $db->fetch_array($res)) @@ -337,7 +337,7 @@ if ($action == 'create') // Handler print ''; print ''; print ''; @@ -361,15 +361,15 @@ if ($action == 'create') { print ''; } print ''; // Mainmenu code print ''; - print ''; + print ''; print ''; @@ -382,7 +382,7 @@ if ($action == 'create') } else { - print ''; + print ''; } print ''; // Position - print ''; + print ''; // Target print ''; // Enabled - print ''; + print ''; // Perms - print ''; + print ''; print '
'.$langs->trans('MenuHandler').''; - $formadmin->select_menu_families($menu_handler.(preg_match('/_menu/', $menu_handler)?'':'_menu'), 'menu_handler', array_merge($dirstandard, $dirsmartphone)); + $formadmin->select_menu_families($menu_handler.(preg_match('/_menu/', $menu_handler) ? '' : '_menu'), 'menu_handler', array_merge($dirstandard, $dirsmartphone)); print ''.$langs->trans('DetailMenuHandler').'
'.$langs->trans('DetailType').'
'.$langs->trans('MainMenuCode').''; print $langs->trans("Example").': mytopmenukey'; print '
'.$langs->trans('DetailMenuIdParent'); print ', '.$langs->trans("Example").': fk_mainmenu=abc&fk_leftmenu=def'; @@ -398,19 +398,19 @@ if ($action == 'create') print '
'.$langs->trans('LangFile').''.$langs->trans('DetailLangs').'
'.$langs->trans('Position').''.$langs->trans('DetailPosition').'
'.$langs->trans('Position').''.$langs->trans('DetailPosition').'
'.$langs->trans('Target').''.$langs->trans('DetailTarget').'
'.$langs->trans('Enabled').''.$langs->trans('DetailEnabled').'
'.$langs->trans('Enabled').''.$langs->trans('DetailEnabled').'
'.$langs->trans('Rights').''.$langs->trans('DetailRight').'
'.$langs->trans('Rights').''.$langs->trans('DetailRight').'
'; @@ -436,10 +436,10 @@ elseif ($action == 'edit') dol_fiche_head(); - print ''; + print '
'; $menu = new Menubase($db); - $result=$menu->fetch(GETPOST('menuId', 'int')); + $result = $menu->fetch(GETPOST('menuId', 'int')); //var_dump($menu); // Id @@ -455,9 +455,9 @@ elseif ($action == 'edit') // User print ''; // Type @@ -473,7 +473,7 @@ elseif ($action == 'edit') } else {*/ - print ''; + print ''; //} print ''; - $valtouse=$menu->fk_menu; - if ($menu->fk_mainmenu) $valtouse='fk_mainmenu='.$menu->fk_mainmenu; - if ($menu->fk_leftmenu) $valtouse.='&fk_leftmenu='.$menu->fk_leftmenu; + $valtouse = $menu->fk_menu; + if ($menu->fk_mainmenu) $valtouse = 'fk_mainmenu='.$menu->fk_mainmenu; + if ($menu->fk_leftmenu) $valtouse .= '&fk_leftmenu='.$menu->fk_leftmenu; print ''; print ''; // Enabled print ''; // Perms print ''; print '
'.$langs->trans('MenuForUsers').''.$langs->trans('DetailUser').'
mainmenu).'">mainmenu).'">'; print $langs->trans("Example").': mytopmenukey'; @@ -483,9 +483,9 @@ elseif ($action == 'edit') // MenuId Parent print '
'.$langs->trans('MenuIdParent'); print ''.$langs->trans('DetailMenuIdParent'); print ', '.$langs->trans("Example").': fk_mainmenu=abc&fk_leftmenu=def'; @@ -508,18 +508,18 @@ elseif ($action == 'edit') // Target print '
'.$langs->trans('Target').''.$langs->trans('DetailTarget').'
'.$langs->trans('Enabled').''.$langs->trans('DetailEnabled'); - if (! empty($menu->enabled)) print ' ('.$langs->trans("ConditionIsCurrently").': '.yn(dol_eval($menu->enabled, 1)).')'; + if (!empty($menu->enabled)) print ' ('.$langs->trans("ConditionIsCurrently").': '.yn(dol_eval($menu->enabled, 1)).')'; print '
'.$langs->trans('Rights').''.$langs->trans('DetailRight'); - if (! empty($menu->perms)) print ' ('.$langs->trans("ConditionIsCurrently").': '.yn(dol_eval($menu->perms, 1)).')'; + if (!empty($menu->perms)) print ' ('.$langs->trans("ConditionIsCurrently").': '.yn(dol_eval($menu->perms, 1)).')'; print '
'; diff --git a/htdocs/admin/menus/index.php b/htdocs/admin/menus/index.php index 34543456bfe..c0c7b320a38 100644 --- a/htdocs/admin/menus/index.php +++ b/htdocs/admin/menus/index.php @@ -29,35 +29,35 @@ require_once DOL_DOCUMENT_ROOT.'/core/class/html.formadmin.class.php'; require_once DOL_DOCUMENT_ROOT.'/core/lib/treeview.lib.php'; // Load translation files required by the page -$langs->loadLangs(array("other","admin")); +$langs->loadLangs(array("other", "admin")); -if (! $user->admin) accessforbidden(); +if (!$user->admin) accessforbidden(); $dirstandard = array(); $dirsmartphone = array(); -$dirmenus=array_merge(array("/core/menus/"), (array) $conf->modules_parts['menus']); -foreach($dirmenus as $dirmenu) +$dirmenus = array_merge(array("/core/menus/"), (array) $conf->modules_parts['menus']); +foreach ($dirmenus as $dirmenu) { - $dirstandard[]=$dirmenu.'standard'; - $dirsmartphone[]=$dirmenu.'smartphone'; + $dirstandard[] = $dirmenu.'standard'; + $dirsmartphone[] = $dirmenu.'smartphone'; } -$action=GETPOST('action', 'alpha'); -$confirm=GETPOST('confirm', 'alpha'); +$action = GETPOST('action', 'alpha'); +$confirm = GETPOST('confirm', 'alpha'); -$menu_handler_top=$conf->global->MAIN_MENU_STANDARD; -$menu_handler_smartphone=$conf->global->MAIN_MENU_SMARTPHONE; -$menu_handler_top=preg_replace('/(_backoffice\.php|_menu\.php)/i', '', $menu_handler_top); -$menu_handler_top=preg_replace('/(_frontoffice\.php|_menu\.php)/i', '', $menu_handler_top); -$menu_handler_smartphone=preg_replace('/(_backoffice\.php|_menu\.php)/i', '', $menu_handler_smartphone); -$menu_handler_smartphone=preg_replace('/(_frontoffice\.php|_menu\.php)/i', '', $menu_handler_smartphone); +$menu_handler_top = $conf->global->MAIN_MENU_STANDARD; +$menu_handler_smartphone = $conf->global->MAIN_MENU_SMARTPHONE; +$menu_handler_top = preg_replace('/(_backoffice\.php|_menu\.php)/i', '', $menu_handler_top); +$menu_handler_top = preg_replace('/(_frontoffice\.php|_menu\.php)/i', '', $menu_handler_top); +$menu_handler_smartphone = preg_replace('/(_backoffice\.php|_menu\.php)/i', '', $menu_handler_smartphone); +$menu_handler_smartphone = preg_replace('/(_frontoffice\.php|_menu\.php)/i', '', $menu_handler_smartphone); -$menu_handler=$menu_handler_top; +$menu_handler = $menu_handler_top; -if (GETPOST("handler_origine")) $menu_handler=GETPOST("handler_origine"); -if (GETPOST("menu_handler")) $menu_handler=GETPOST("menu_handler"); +if (GETPOST("handler_origine")) $menu_handler = GETPOST("handler_origine"); +if (GETPOST("menu_handler")) $menu_handler = GETPOST("menu_handler"); -$menu_handler_to_search=preg_replace('/(_backoffice|_frontoffice|_menu)?(\.php)?/i', '', $menu_handler); +$menu_handler_to_search = preg_replace('/(_backoffice|_frontoffice|_menu)?(\.php)?/i', '', $menu_handler); /* @@ -66,18 +66,18 @@ $menu_handler_to_search=preg_replace('/(_backoffice|_frontoffice|_menu)?(\.php)? if ($action == 'up') { - $current=array(); - $previous=array(); + $current = array(); + $previous = array(); // Get current position $sql = "SELECT m.rowid, m.position, m.type, m.fk_menu"; - $sql.= " FROM ".MAIN_DB_PREFIX."menu as m"; - $sql.= " WHERE m.rowid = ".GETPOST("menuId", "int"); + $sql .= " FROM ".MAIN_DB_PREFIX."menu as m"; + $sql .= " WHERE m.rowid = ".GETPOST("menuId", "int"); dol_syslog("admin/menus/index.php ".$sql); $result = $db->query($sql); $num = $db->num_rows($result); $i = 0; - while($i < $num) + while ($i < $num) { $obj = $db->fetch_object($result); $current['rowid'] = $obj->rowid; @@ -89,18 +89,18 @@ if ($action == 'up') // Menu before $sql = "SELECT m.rowid, m.position"; - $sql.= " FROM ".MAIN_DB_PREFIX."menu as m"; - $sql.= " WHERE (m.position < ".($current['order'])." OR (m.position = ".($current['order'])." AND rowid < ".GETPOST("menuId", "int")."))"; - $sql.= " AND m.menu_handler='".$db->escape($menu_handler_to_search)."'"; - $sql.= " AND m.entity = ".$conf->entity; - $sql.= " AND m.type = '".$db->escape($current['type'])."'"; - $sql.= " AND m.fk_menu = '".$db->escape($current['fk_menu'])."'"; - $sql.= " ORDER BY m.position, m.rowid"; + $sql .= " FROM ".MAIN_DB_PREFIX."menu as m"; + $sql .= " WHERE (m.position < ".($current['order'])." OR (m.position = ".($current['order'])." AND rowid < ".GETPOST("menuId", "int")."))"; + $sql .= " AND m.menu_handler='".$db->escape($menu_handler_to_search)."'"; + $sql .= " AND m.entity = ".$conf->entity; + $sql .= " AND m.type = '".$db->escape($current['type'])."'"; + $sql .= " AND m.fk_menu = '".$db->escape($current['fk_menu'])."'"; + $sql .= " ORDER BY m.position, m.rowid"; dol_syslog("admin/menus/index.php ".$sql); $result = $db->query($sql); $num = $db->num_rows($result); $i = 0; - while($i < $num) + while ($i < $num) { $obj = $db->fetch_object($result); $previous['rowid'] = $obj->rowid; @@ -109,31 +109,31 @@ if ($action == 'up') } $sql = "UPDATE ".MAIN_DB_PREFIX."menu as m"; - $sql.= " SET m.position = ".$previous['order']; - $sql.= " WHERE m.rowid = ".$current['rowid']; // Up the selected entry + $sql .= " SET m.position = ".$previous['order']; + $sql .= " WHERE m.rowid = ".$current['rowid']; // Up the selected entry dol_syslog("admin/menus/index.php ".$sql); $db->query($sql); $sql = "UPDATE ".MAIN_DB_PREFIX."menu as m"; - $sql.= " SET m.position = ".($current['order']!=$previous['order']?$current['order']:$current['order']+1); - $sql.= " WHERE m.rowid = ".$previous['rowid']; // Descend celui du dessus + $sql .= " SET m.position = ".($current['order'] != $previous['order'] ? $current['order'] : $current['order'] + 1); + $sql .= " WHERE m.rowid = ".$previous['rowid']; // Descend celui du dessus dol_syslog("admin/menus/index.php ".$sql); $db->query($sql); } elseif ($action == 'down') { - $current=array(); - $next=array(); + $current = array(); + $next = array(); // Get current position $sql = "SELECT m.rowid, m.position, m.type, m.fk_menu"; - $sql.= " FROM ".MAIN_DB_PREFIX."menu as m"; - $sql.= " WHERE m.rowid = ".GETPOST("menuId", "int"); + $sql .= " FROM ".MAIN_DB_PREFIX."menu as m"; + $sql .= " WHERE m.rowid = ".GETPOST("menuId", "int"); dol_syslog("admin/menus/index.php ".$sql); $result = $db->query($sql); $num = $db->num_rows($result); $i = 0; - while($i < $num) + while ($i < $num) { $obj = $db->fetch_object($result); $current['rowid'] = $obj->rowid; @@ -145,18 +145,18 @@ elseif ($action == 'down') // Menu after $sql = "SELECT m.rowid, m.position"; - $sql.= " FROM ".MAIN_DB_PREFIX."menu as m"; - $sql.= " WHERE (m.position > ".($current['order'])." OR (m.position = ".($current['order'])." AND rowid > ".GETPOST("menuId", "int")."))"; - $sql.= " AND m.menu_handler='".$db->escape($menu_handler_to_search)."'"; - $sql.= " AND m.entity = ".$conf->entity; - $sql.= " AND m.type = '".$db->escape($current['type'])."'"; - $sql.= " AND m.fk_menu = '".$db->escape($current['fk_menu'])."'"; - $sql.= " ORDER BY m.position, m.rowid"; + $sql .= " FROM ".MAIN_DB_PREFIX."menu as m"; + $sql .= " WHERE (m.position > ".($current['order'])." OR (m.position = ".($current['order'])." AND rowid > ".GETPOST("menuId", "int")."))"; + $sql .= " AND m.menu_handler='".$db->escape($menu_handler_to_search)."'"; + $sql .= " AND m.entity = ".$conf->entity; + $sql .= " AND m.type = '".$db->escape($current['type'])."'"; + $sql .= " AND m.fk_menu = '".$db->escape($current['fk_menu'])."'"; + $sql .= " ORDER BY m.position, m.rowid"; dol_syslog("admin/menus/index.php ".$sql); $result = $db->query($sql); $num = $db->num_rows($result); $i = 0; - while($i < $num) + while ($i < $num) { $obj = $db->fetch_object($result); $next['rowid'] = $obj->rowid; @@ -165,13 +165,13 @@ elseif ($action == 'down') } $sql = "UPDATE ".MAIN_DB_PREFIX."menu as m"; - $sql.= " SET m.position = ".($current['order']!=$next['order']?$next['order']:$current['order']+1); // Down the selected entry - $sql.= " WHERE m.rowid = ".$current['rowid']; + $sql .= " SET m.position = ".($current['order'] != $next['order'] ? $next['order'] : $current['order'] + 1); // Down the selected entry + $sql .= " WHERE m.rowid = ".$current['rowid']; dol_syslog("admin/menus/index.php ".$sql); $db->query($sql); - $sql = "UPDATE ".MAIN_DB_PREFIX."menu as m"; // Up the next entry - $sql.= " SET m.position = ".$current['order']; - $sql.= " WHERE m.rowid = ".$next['rowid']; + $sql = "UPDATE ".MAIN_DB_PREFIX."menu as m"; // Up the next entry + $sql .= " SET m.position = ".$current['order']; + $sql .= " WHERE m.rowid = ".$next['rowid']; dol_syslog("admin/menus/index.php ".$sql); $db->query($sql); } @@ -181,8 +181,8 @@ elseif ($action == 'confirm_delete' && $confirm == 'yes') $db->begin(); $sql = "DELETE FROM ".MAIN_DB_PREFIX."menu"; - $sql.= " WHERE rowid = ".GETPOST('menuId', 'int'); - $resql=$db->query($sql); + $sql .= " WHERE rowid = ".GETPOST('menuId', 'int'); + $resql = $db->query($sql); if ($resql) { $db->commit(); @@ -190,14 +190,14 @@ elseif ($action == 'confirm_delete' && $confirm == 'yes') setEventMessages($langs->trans("MenuDeleted"), null, 'mesgs'); header("Location: ".DOL_URL_ROOT.'/admin/menus/index.php?menu_handler='.$menu_handler); - exit ; + exit; } else { $db->rollback(); $reload = 0; - $action=''; + $action = ''; } } @@ -206,11 +206,11 @@ elseif ($action == 'confirm_delete' && $confirm == 'yes') * View */ -$form=new Form($db); -$formadmin=new FormAdmin($db); +$form = new Form($db); +$formadmin = new FormAdmin($db); -$arrayofjs=array('/includes/jquery/plugins/jquerytreeview/jquery.treeview.js', '/includes/jquery/plugins/jquerytreeview/lib/jquery.cookie.js'); -$arrayofcss=array('/includes/jquery/plugins/jquerytreeview/jquery.treeview.css'); +$arrayofjs = array('/includes/jquery/plugins/jquerytreeview/jquery.treeview.js', '/includes/jquery/plugins/jquerytreeview/lib/jquery.cookie.js'); +$arrayofcss = array('/includes/jquery/plugins/jquerytreeview/jquery.treeview.css'); llxHeader('', $langs->trans("Menus"), '', '', 0, 0, $arrayofjs, $arrayofcss); @@ -303,16 +303,16 @@ if ($conf->use_javascript_ajax) //il faut d'abord declarer un element racine de l'arbre - $data[] = array('rowid'=>0,'fk_menu'=>-1,'title'=>"racine",'mainmenu'=>'','leftmenu'=>'','fk_mainmenu'=>'','fk_leftmenu'=>''); + $data[] = array('rowid'=>0, 'fk_menu'=>-1, 'title'=>"racine", 'mainmenu'=>'', 'leftmenu'=>'', 'fk_mainmenu'=>'', 'fk_leftmenu'=>''); //puis tous les elements enfants $sql = "SELECT m.rowid, m.titre, m.langs, m.mainmenu, m.leftmenu, m.fk_menu, m.fk_mainmenu, m.fk_leftmenu, m.position, m.module"; - $sql.= " FROM ".MAIN_DB_PREFIX."menu as m"; - $sql.= " WHERE menu_handler = '".$db->escape($menu_handler_to_search)."'"; - $sql.= " AND entity = ".$conf->entity; + $sql .= " FROM ".MAIN_DB_PREFIX."menu as m"; + $sql .= " WHERE menu_handler = '".$db->escape($menu_handler_to_search)."'"; + $sql .= " AND entity = ".$conf->entity; //$sql.= " AND fk_menu >= 0"; - $sql.= " ORDER BY m.position, m.rowid"; // Order is position then rowid (because we need a sort criteria when position is same) + $sql .= " ORDER BY m.position, m.rowid"; // Order is position then rowid (because we need a sort criteria when position is same) $res = $db->query($sql); if ($res) @@ -322,7 +322,7 @@ if ($conf->use_javascript_ajax) $i = 1; while ($menu = $db->fetch_array($res)) { - if (! empty($menu['langs'])) $langs->load($menu['langs']); + if (!empty($menu['langs'])) $langs->load($menu['langs']); $titre = $langs->trans($menu['titre']); $data[] = array( @@ -354,13 +354,13 @@ if ($conf->use_javascript_ajax) } } - global $tree_recur_alreadyadded; // This var was def into tree_recur + global $tree_recur_alreadyadded; // This var was def into tree_recur //var_dump($data); // Appelle de la fonction recursive (ammorce) avec recherche depuis la racine. //tree_recur($data, $data[0], 0, 'iddivjstree', 0, 1); // use this to get info on name and foreign keys of menu entry - tree_recur($data, $data[0], 0, 'iddivjstree', 0, 0); // $data[0] is virtual record 'racine' + tree_recur($data, $data[0], 0, 'iddivjstree', 0, 0); // $data[0] is virtual record 'racine' print '
'; - foreach($remainingdata as $datar) + foreach ($remainingdata as $datar) { - $father = array('rowid'=>$datar['rowid'],'title'=>"???",'mainmenu'=>$datar['fk_mainmenu'],'leftmenu'=>$datar['fk_leftmenu'],'fk_mainmenu'=>'','fk_leftmenu'=>''); + $father = array('rowid'=>$datar['rowid'], 'title'=>"???", 'mainmenu'=>$datar['fk_mainmenu'], 'leftmenu'=>$datar['fk_leftmenu'], 'fk_mainmenu'=>'', 'fk_leftmenu'=>''); //print 'Start with rowid='.$datar['rowid'].' mainmenu='.$father ['mainmenu'].' leftmenu='.$father ['leftmenu'].'
'."\n"; tree_recur($data, $father, 0, 'iddivjstree'.$datar['rowid'], 1, 1); } diff --git a/htdocs/admin/menus/other.php b/htdocs/admin/menus/other.php index e339b1854d8..b3df54ea265 100644 --- a/htdocs/admin/menus/other.php +++ b/htdocs/admin/menus/other.php @@ -81,7 +81,7 @@ dol_fiche_head($head, 'misc', $langs->trans("Menus"), -1); // Other Options -print ''; +print '
'; print ''; print ''; print ''; diff --git a/htdocs/admin/mrp.php b/htdocs/admin/mrp.php index 06c59338e58..359119e9091 100644 --- a/htdocs/admin/mrp.php +++ b/htdocs/admin/mrp.php @@ -210,7 +210,7 @@ dol_fiche_head($head, 'settings', $langs->trans("MOs"), -1, 'mrp'); print load_fiche_titre($langs->trans("MOsNumberingModules"), '', ''); -print '
'.$langs->trans("Parameters").''.$langs->trans("Status").'
'; +print '
'; print ''; print ''; print ''; @@ -465,7 +465,7 @@ print "
"; */ print load_fiche_titre($langs->trans("OtherOptions"), '', ''); -print '
'.$langs->trans("Name").''.$langs->trans("Description").'
'; +print '
'; print ''; print ''; print ''; diff --git a/htdocs/admin/multicurrency.php b/htdocs/admin/multicurrency.php index 63000d61c8b..d6a7fb26a98 100644 --- a/htdocs/admin/multicurrency.php +++ b/htdocs/admin/multicurrency.php @@ -33,7 +33,7 @@ require_once DOL_DOCUMENT_ROOT.'/multicurrency/class/multicurrency.class.php'; $langs->loadLangs(array('admin', 'multicurrency')); // Access control -if (! $user->admin) { +if (!$user->admin) { accessforbidden(); } @@ -48,8 +48,8 @@ $action = GETPOST('action', 'alpha'); if (preg_match('/set_([a-z0-9_\-]+)/i', $action, $reg)) { - $code=$reg[1]; - $value=GETPOST($code, 'alpha'); + $code = $reg[1]; + $value = GETPOST($code, 'alpha'); if (dolibarr_set_const($db, $code, $value, 'chaine', 0, '', $conf->entity) > 0) { setEventMessages($langs->trans("SetupSaved"), null, 'mesgs'); @@ -62,7 +62,7 @@ if (preg_match('/set_([a-z0-9_\-]+)/i', $action, $reg)) if (preg_match('/del_([a-z0-9_\-]+)/i', $action, $reg)) { - $code=$reg[1]; + $code = $reg[1]; if (dolibarr_del_const($db, $code, 0) > 0) { setEventMessages($langs->trans("SetupSaved"), null, 'mesgs'); @@ -75,7 +75,7 @@ if (preg_match('/del_([a-z0-9_\-]+)/i', $action, $reg)) if ($action == 'add_currency') { - $error=0; + $error = 0; $langs->loadCacheCurrencies(''); @@ -90,7 +90,7 @@ if ($action == 'add_currency') setEventMessages($langs->trans('ErrorFieldRequired', $langs->transnoentitiesnoconv("Rate")), null, 'errors'); $error++; } - if (! $error) + if (!$error) { if ($currency->create($user) > 0) { @@ -115,12 +115,12 @@ elseif ($action == 'update_currency') setEventMessages($langs->trans('ErrorFieldRequired', $langs->transnoentitiesnoconv("Rate")), null, 'errors'); $error++; } - if (! $error) + if (!$error) { if ($currency->fetch($fk_multicurrency) > 0) { - $result=$currency->updateRate($rate); - if ($result<0) { + $result = $currency->updateRate($rate); + if ($result < 0) { setEventMessages(null, $currency->errors, 'errors'); } } @@ -171,14 +171,14 @@ if ($resql) * View */ -$form=new Form($db); +$form = new Form($db); $page_name = "MultiCurrencySetup"; llxHeader('', $langs->trans($page_name)); // Subheader -$linkback = '' . $langs->trans("BackToModuleList") . ''; +$linkback = ''.$langs->trans("BackToModuleList").''; print load_fiche_titre($langs->trans($page_name), $linkback); // Configuration header @@ -186,7 +186,7 @@ $head = multicurrencyAdminPrepareHead(); dol_fiche_head($head, 'settings', $langs->trans("ModuleSetup"), -1, "multicurrency"); -print '
'.$langs->trans("Parameter").''.$langs->trans("Value").'
'; +print '
'; print ''; print ''."\n"; print ''."\n"; @@ -270,9 +270,9 @@ if (!empty($conf->global->MAIN_MULTICURRENCY_ALLOW_SYNCHRONIZATION)) print ''; print '
'; - print '
'.$langs->trans("Parameters").''.$langs->trans("Status").'
'; + print '
'; - $urlforapilayer='https://currencylayer.com'; //https://apilayer.net + $urlforapilayer = 'https://currencylayer.com'; //https://apilayer.net print ''; print ''."\n"; @@ -309,7 +309,7 @@ if (!empty($conf->global->MAIN_MULTICURRENCY_ALLOW_SYNCHRONIZATION)) } print '
'; -print '
'.$form->textwithpicto($langs->trans("CurrencyLayerAccount"), $langs->trans("CurrencyLayerAccount_help_to_synchronize", $urlforapilayer)).'
'; +print '
'; print ''; print ''."\n"; diff --git a/htdocs/admin/notification.php b/htdocs/admin/notification.php index 52de58b80b8..eb6f8d18fe4 100644 --- a/htdocs/admin/notification.php +++ b/htdocs/admin/notification.php @@ -47,45 +47,45 @@ if ($action == 'setvalue' && $user->admin) { $db->begin(); - $result=dolibarr_set_const($db, "NOTIFICATION_EMAIL_FROM", $_POST["email_from"], 'chaine', 0, '', $conf->entity); + $result = dolibarr_set_const($db, "NOTIFICATION_EMAIL_FROM", $_POST["email_from"], 'chaine', 0, '', $conf->entity); if ($result < 0) $error++; - if (! $error && is_array($_POST)) + if (!$error && is_array($_POST)) { //var_dump($_POST); - foreach($_POST as $key => $val) + foreach ($_POST as $key => $val) { - if (! preg_match('/^NOTIF_(.*)_key$/', $key, $reg)) continue; + if (!preg_match('/^NOTIF_(.*)_key$/', $key, $reg)) continue; - $newval=''; - $newkey=''; + $newval = ''; + $newkey = ''; - $shortkey=preg_replace('/_key$/', '', $key); + $shortkey = preg_replace('/_key$/', '', $key); //print $shortkey.'
'; if (preg_match('/^NOTIF_(.*)_old_(.*)_key/', $key, $reg)) { dolibarr_del_const($db, 'NOTIFICATION_FIXEDEMAIL_'.$reg[1].'_THRESHOLD_HIGHER_'.$reg[2], $conf->entity); - $newkey='NOTIFICATION_FIXEDEMAIL_'.$reg[1].'_THRESHOLD_HIGHER_'.((int) GETPOST($shortkey.'_amount')); - $newval=GETPOST($shortkey.'_key'); + $newkey = 'NOTIFICATION_FIXEDEMAIL_'.$reg[1].'_THRESHOLD_HIGHER_'.((int) GETPOST($shortkey.'_amount')); + $newval = GETPOST($shortkey.'_key'); //print $newkey.' - '.$newval.'
'; } elseif (preg_match('/^NOTIF_(.*)_new_key/', $key, $reg)) { // Add a new entry - $newkey='NOTIFICATION_FIXEDEMAIL_'.$reg[1].'_THRESHOLD_HIGHER_'.((int) GETPOST($shortkey.'_amount')); - $newval=GETPOST($shortkey.'_key'); + $newkey = 'NOTIFICATION_FIXEDEMAIL_'.$reg[1].'_THRESHOLD_HIGHER_'.((int) GETPOST($shortkey.'_amount')); + $newval = GETPOST($shortkey.'_key'); } if ($newkey && $newval) { - $result=dolibarr_set_const($db, $newkey, $newval, 'chaine', 0, '', $conf->entity); + $result = dolibarr_set_const($db, $newkey, $newval, 'chaine', 0, '', $conf->entity); } } } - if (! $error) + if (!$error) { $db->commit(); @@ -105,17 +105,17 @@ if ($action == 'setvalue' && $user->admin) * View */ -$form=new Form($db); +$form = new Form($db); $notify = new Notify($db); llxHeader('', $langs->trans("NotificationSetup")); -$linkback=''.$langs->trans("BackToModuleList").''; +$linkback = ''.$langs->trans("BackToModuleList").''; print load_fiche_titre($langs->trans("NotificationSetup"), $linkback, 'title_setup'); print $langs->trans("NotificationsDesc").'
'; print $langs->trans("NotificationsDescUser").'
'; -if (! empty($conf->societe->enabled)) print $langs->trans("NotificationsDescContact").'
'; +if (!empty($conf->societe->enabled)) print $langs->trans("NotificationsDescContact").'
'; print $langs->trans("NotificationsDescGlobal").'
'; print '
'; @@ -123,7 +123,7 @@ print ''; print ''; print ''; -print '
'.$form->textwithpicto($langs->trans("CurrenciesUsed"), $langs->transnoentitiesnoconv("CurrenciesUsed_help_to_add")).'
'; +print '
'; print ''; print ''; print ''; @@ -133,7 +133,7 @@ print ''; print ''; print ''; print '
'.$langs->trans("Parameter").''.$langs->trans("Value").'
'; print $langs->trans("NotificationEMailFrom").''; print ''; -if (! empty($conf->global->NOTIFICATION_EMAIL_FROM) && ! isValidEmail($conf->global->NOTIFICATION_EMAIL_FROM)) print ' '.img_warning($langs->trans("ErrorBadEMail")); +if (!empty($conf->global->NOTIFICATION_EMAIL_FROM) && !isValidEmail($conf->global->NOTIFICATION_EMAIL_FROM)) print ' '.img_warning($langs->trans("ErrorBadEMail")); print '
'; @@ -142,11 +142,11 @@ print '

'; // Notification per contacts -$title=$langs->trans("ListOfNotificationsPerUser"); -if (! empty($conf->societe->enabled)) $title=$langs->trans("ListOfNotificationsPerUserOrContact"); +$title = $langs->trans("ListOfNotificationsPerUser"); +if (!empty($conf->societe->enabled)) $title = $langs->trans("ListOfNotificationsPerUserOrContact"); print load_fiche_titre($title, '', ''); -print ''; +print '
'; print ''; print ''; /*print ''; @@ -155,16 +155,16 @@ print ''; print "\n"; // Load array of available notifications -$notificationtrigger=new InterfaceNotification($db); -$listofnotifiedevents=$notificationtrigger->getListOfManagedEvents(); +$notificationtrigger = new InterfaceNotification($db); +$listofnotifiedevents = $notificationtrigger->getListOfManagedEvents(); print ''; print ''; print '
'.$langs->trans("Label").''.$langs->trans("Code").''.$langs->trans("Label").'
'; -$i=0; -foreach($listofnotifiedevents as $notifiedevent) +$i = 0; +foreach ($listofnotifiedevents as $notifiedevent) { - $label=$langs->trans("Notify_".$notifiedevent['code']); //!=$langs->trans("Notify_".$notifiedevent['code'])?$langs->trans("Notify_".$notifiedevent['code']):$notifiedevent['label']; + $label = $langs->trans("Notify_".$notifiedevent['code']); //!=$langs->trans("Notify_".$notifiedevent['code'])?$langs->trans("Notify_".$notifiedevent['code']):$notifiedevent['label']; $elementLabel = $langs->trans(ucfirst($notifiedevent['elementtype'])); if ($notifiedevent['elementtype'] == 'order_supplier') $elementLabel = $langs->trans('SupplierOrder'); @@ -185,14 +185,14 @@ print '
'; print '
'; print '* '.$langs->trans("GoOntoUserCardToAddMore").'
'; -if (! empty($conf->societe->enabled)) print '** '.$langs->trans("GoOntoContactCardToAddMore").'
'; +if (!empty($conf->societe->enabled)) print '** '.$langs->trans("GoOntoContactCardToAddMore").'
'; print '
'; print '

'; print load_fiche_titre($langs->trans("ListOfFixedNotifications"), '', ''); -print ''; +print '
'; print ''; print ''; print ''; @@ -203,12 +203,12 @@ print ''; print "\n"; // Load array of available notifications -$notificationtrigger=new InterfaceNotification($db); -$listofnotifiedevents=$notificationtrigger->getListOfManagedEvents(); +$notificationtrigger = new InterfaceNotification($db); +$listofnotifiedevents = $notificationtrigger->getListOfManagedEvents(); -foreach($listofnotifiedevents as $notifiedevent) +foreach ($listofnotifiedevents as $notifiedevent) { - $label=$langs->trans("Notify_".$notifiedevent['code']); //!=$langs->trans("Notify_".$notifiedevent['code'])?$langs->trans("Notify_".$notifiedevent['code']):$notifiedevent['label']; + $label = $langs->trans("Notify_".$notifiedevent['code']); //!=$langs->trans("Notify_".$notifiedevent['code'])?$langs->trans("Notify_".$notifiedevent['code']):$notifiedevent['label']; $elementLabel = $langs->trans(ucfirst($notifiedevent['elementtype'])); // Special cases @@ -226,35 +226,35 @@ foreach($listofnotifiedevents as $notifiedevent) print ''; print ''; print '
'.$langs->trans("Module").''.$langs->trans("Code").''.'
'.$label.''; // Notification with threshold - foreach($conf->global as $key => $val) + foreach ($conf->global as $key => $val) { - if ($val == '' || ! preg_match('/^NOTIFICATION_FIXEDEMAIL_'.$notifiedevent['code'].'_THRESHOLD_HIGHER_(.*)/', $key, $reg)) continue; + if ($val == '' || !preg_match('/^NOTIFICATION_FIXEDEMAIL_'.$notifiedevent['code'].'_THRESHOLD_HIGHER_(.*)/', $key, $reg)) continue; - $param='NOTIFICATION_FIXEDEMAIL_'.$notifiedevent['code'].'_THRESHOLD_HIGHER_'.$reg[1]; - $value=GETPOST('NOTIF_'.$notifiedevent['code'].'_old_'.$reg[1].'_key')?GETPOST('NOTIF_'.$notifiedevent['code'].'_old_'.$reg[1].'_key', 'alpha'):$conf->global->$param; + $param = 'NOTIFICATION_FIXEDEMAIL_'.$notifiedevent['code'].'_THRESHOLD_HIGHER_'.$reg[1]; + $value = GETPOST('NOTIF_'.$notifiedevent['code'].'_old_'.$reg[1].'_key') ?GETPOST('NOTIF_'.$notifiedevent['code'].'_old_'.$reg[1].'_key', 'alpha') : $conf->global->$param; - $s=''; // Do not use type="email" here, we must be able to enter a list of email with , separator. - $arrayemail=explode(',', $value); - $showwarning=0; - foreach($arrayemail as $keydet => $valuedet) + $s = ''; // Do not use type="email" here, we must be able to enter a list of email with , separator. + $arrayemail = explode(',', $value); + $showwarning = 0; + foreach ($arrayemail as $keydet => $valuedet) { - $valuedet=trim($valuedet); - if (! empty($valuedet) && ! isValidEmail($valuedet, 1)) $showwarning++; + $valuedet = trim($valuedet); + if (!empty($valuedet) && !isValidEmail($valuedet, 1)) $showwarning++; } - if ((! empty($conf->global->$param)) && $showwarning) $s.=' '.img_warning($langs->trans("ErrorBadEMail")); + if ((!empty($conf->global->$param)) && $showwarning) $s .= ' '.img_warning($langs->trans("ErrorBadEMail")); print $form->textwithpicto($s, $langs->trans("YouCanUseCommaSeparatorForSeveralRecipients").'
'.$langs->trans("YouCanAlsoUseSupervisorKeyword"), 1, 'help', '', 0, 2); print '
'; } // New entry input fields - $s=''; // Do not use type="email" here, we must be able to enter a list of email with , separator. + $s = ''; // Do not use type="email" here, we must be able to enter a list of email with , separator. print $form->textwithpicto($s, $langs->trans("YouCanUseCommaSeparatorForSeveralRecipients").'
'.$langs->trans("YouCanAlsoUseSupervisorKeyword"), 1, 'help', '', 0, 2); print '
'; // Notification with threshold - foreach($conf->global as $key => $val) + foreach ($conf->global as $key => $val) { - if ($val == '' || ! preg_match('/^NOTIFICATION_FIXEDEMAIL_'.$notifiedevent['code'].'_THRESHOLD_HIGHER_(.*)/', $key, $reg)) continue; + if ($val == '' || !preg_match('/^NOTIFICATION_FIXEDEMAIL_'.$notifiedevent['code'].'_THRESHOLD_HIGHER_(.*)/', $key, $reg)) continue; print $langs->trans("AmountHT").' >= '; print '
'; diff --git a/htdocs/admin/oauth.php b/htdocs/admin/oauth.php index b0795152d05..25afbaad943 100644 --- a/htdocs/admin/oauth.php +++ b/htdocs/admin/oauth.php @@ -29,8 +29,8 @@ require_once DOL_DOCUMENT_ROOT.'/core/lib/oauth.lib.php'; // Define $urlwithroot -$urlwithouturlroot=preg_replace('/'.preg_quote(DOL_URL_ROOT, '/').'$/i', '', trim($dolibarr_main_url_root)); -$urlwithroot=$urlwithouturlroot.DOL_URL_ROOT; // This is to use external domain name found into config file +$urlwithouturlroot = preg_replace('/'.preg_quote(DOL_URL_ROOT, '/').'$/i', '', trim($dolibarr_main_url_root)); +$urlwithroot = $urlwithouturlroot.DOL_URL_ROOT; // This is to use external domain name found into config file //$urlwithroot=DOL_MAIN_URL_ROOT; // This is to use same domain name than current // Load translation files required by the page @@ -60,7 +60,7 @@ if ($action == 'update') $error++; } - if (! $error) + if (!$error) { setEventMessages($langs->trans("SetupSaved"), null); } else { @@ -76,7 +76,7 @@ llxHeader(); $form = new Form($db); -$linkback=''.$langs->trans("BackToModuleList").''; +$linkback = ''.$langs->trans("BackToModuleList").''; print load_fiche_titre($langs->trans('ConfigOAuth'), $linkback, 'title_setup'); print ''; @@ -90,31 +90,31 @@ dol_fiche_head($head, 'services', '', -1, 'technic'); print $langs->trans("ListOfSupportedOauthProviders").'

'; -print ''; +print '
'; -$i=0; +$i = 0; // $list is defined into oauth.lib.php foreach ($list as $key) { - $supported=0; - if (in_array($key[0], array_keys($supportedoauth2array))) $supported=1; - if (! $supported) continue; // show only supported + $supported = 0; + if (in_array($key[0], array_keys($supportedoauth2array))) $supported = 1; + if (!$supported) continue; // show only supported $i++; - print ''; + print ''; // Api Name $label = $langs->trans($key[0]); print ''; print ''; print ''; if ($supported) { - $redirect_uri=$urlwithroot.'/core/modules/oauth/'.$supportedoauth2array[$key[0]].'_oauthcallback.php'; + $redirect_uri = $urlwithroot.'/core/modules/oauth/'.$supportedoauth2array[$key[0]].'_oauthcallback.php'; print ''; print ''; print '\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 ''; - 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']++; } // Label - if (! empty($arrayfields['f.label']['checked'])) + if (!empty($arrayfields['f.label']['checked'])) { print ''; - if (! $i) $totalarray['nbfield']++; + if (!$i) $totalarray['nbfield']++; } // Date - if (! empty($arrayfields['f.datef']['checked'])) + if (!empty($arrayfields['f.datef']['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']++; } // Date modification - if (! empty($arrayfields['f.tms']['checked'])) + if (!empty($arrayfields['f.tms']['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 print ''; - if (! $i) $totalarray['nbfield']++; + if (!$i) $totalarray['nbfield']++; print "\n"; @@ -1110,8 +1111,8 @@ if ($resql) $db->free($resql); - $parameters=array('arrayfields'=>$arrayfields, 'sql'=>$sql); - $reshook=$hookmanager->executeHooks('printFieldListFooter', $parameters); // Note that $action and $object may have been modified by hook + $parameters = array('arrayfields'=>$arrayfields, 'sql'=>$sql); + $reshook = $hookmanager->executeHooks('printFieldListFooter', $parameters); // Note that $action and $object may have been modified by hook print $hookmanager->resPrint; print "
'.$label.''; - if (! empty($key[3])) print $langs->trans($key[3]); + if (!empty($key[3])) print $langs->trans($key[3]); print '
'.$langs->trans("UseTheFollowingUrlAsRedirectURI").''; diff --git a/htdocs/admin/oauthlogintokens.php b/htdocs/admin/oauthlogintokens.php index bb3c83c2ee2..01d36898c78 100644 --- a/htdocs/admin/oauthlogintokens.php +++ b/htdocs/admin/oauthlogintokens.php @@ -31,7 +31,7 @@ use OAuth\Common\Storage\DoliStorage; // Load translation files required by the page $langs->loadLangs(array('admin', 'printing', 'oauth')); -if (! $user->admin) accessforbidden(); +if (!$user->admin) accessforbidden(); $action = GETPOST('action', 'alpha'); $mode = GETPOST('mode', 'alpha'); @@ -39,9 +39,9 @@ $value = GETPOST('value', 'alpha'); $varname = GETPOST('varname', 'alpha'); $driver = GETPOST('driver', 'alpha'); -if (! empty($driver)) $langs->load($driver); +if (!empty($driver)) $langs->load($driver); -if (!$mode) $mode='setup'; +if (!$mode) $mode = 'setup'; /* @@ -57,15 +57,15 @@ if (!$mode) $mode='setup'; if ($action == 'setconst' && $user->admin) { - $error=0; + $error = 0; $db->begin(); foreach ($_POST['setupdriver'] as $setupconst) { //print '
'.print_r($setupconst, true).'
'; - $result=dolibarr_set_const($db, $setupconst['varname'], $setupconst['value'], 'chaine', 0, '', $conf->entity); - if (! $result > 0) $error++; + $result = dolibarr_set_const($db, $setupconst['varname'], $setupconst['value'], 'chaine', 0, '', $conf->entity); + if (!$result > 0) $error++; } - if (! $error) + if (!$error) { $db->commit(); setEventMessages($langs->trans("SetupSaved"), null); @@ -75,17 +75,17 @@ if ($action == 'setconst' && $user->admin) $db->rollback(); dol_print_error($db); } - $action=''; + $action = ''; } if ($action == 'setvalue' && $user->admin) { $db->begin(); - $result=dolibarr_set_const($db, $varname, $value, 'chaine', 0, '', $conf->entity); - if (! $result > 0) $error++; + $result = dolibarr_set_const($db, $varname, $value, 'chaine', 0, '', $conf->entity); + if (!$result > 0) $error++; - if (! $error) + if (!$error) { $db->commit(); setEventMessages($langs->trans("SetupSaved"), null); @@ -104,15 +104,15 @@ if ($action == 'setvalue' && $user->admin) */ // Define $urlwithroot -$urlwithouturlroot=preg_replace('/'.preg_quote(DOL_URL_ROOT, '/').'$/i', '', trim($dolibarr_main_url_root)); -$urlwithroot=$urlwithouturlroot.DOL_URL_ROOT; // This is to use external domain name found into config file +$urlwithouturlroot = preg_replace('/'.preg_quote(DOL_URL_ROOT, '/').'$/i', '', trim($dolibarr_main_url_root)); +$urlwithroot = $urlwithouturlroot.DOL_URL_ROOT; // This is to use external domain name found into config file //$urlwithroot=DOL_MAIN_URL_ROOT; // This is to use same domain name than current $form = new Form($db); llxHeader('', $langs->trans("PrintingSetup")); -$linkback=''.$langs->trans("BackToModuleList").''; +$linkback = ''.$langs->trans("BackToModuleList").''; print load_fiche_titre($langs->trans('ConfigOAuth'), $linkback, 'title_setup'); $head = oauthadmin_prepare_head(); @@ -124,52 +124,52 @@ if ($mode == 'setup' && $user->admin) { print $langs->trans("OAuthSetupForLogin")."

\n"; - foreach($list as $key) + foreach ($list as $key) { - $supported=0; - if (in_array($key[0], array_keys($supportedoauth2array))) $supported=1; - if (! $supported) continue; // show only supported + $supported = 0; + if (in_array($key[0], array_keys($supportedoauth2array))) $supported = 1; + if (!$supported) continue; // show only supported - $OAUTH_SERVICENAME='Unknown'; + $OAUTH_SERVICENAME = 'Unknown'; if ($key[0] == 'OAUTH_GITHUB_NAME') { - $OAUTH_SERVICENAME='GitHub'; - $urltorenew=$urlwithroot.'/core/modules/oauth/github_oauthcallback.php?state=user,public_repo&backtourl='.urlencode(DOL_URL_ROOT.'/admin/oauthlogintokens.php'); - $urltodelete=$urlwithroot.'/core/modules/oauth/github_oauthcallback.php?action=delete&backtourl='.urlencode(DOL_URL_ROOT.'/admin/oauthlogintokens.php'); - $urltocheckperms='https://github.com/settings/applications/'; + $OAUTH_SERVICENAME = 'GitHub'; + $urltorenew = $urlwithroot.'/core/modules/oauth/github_oauthcallback.php?state=user,public_repo&backtourl='.urlencode(DOL_URL_ROOT.'/admin/oauthlogintokens.php'); + $urltodelete = $urlwithroot.'/core/modules/oauth/github_oauthcallback.php?action=delete&backtourl='.urlencode(DOL_URL_ROOT.'/admin/oauthlogintokens.php'); + $urltocheckperms = 'https://github.com/settings/applications/'; } elseif ($key[0] == 'OAUTH_GOOGLE_NAME') { - $OAUTH_SERVICENAME='Google'; - $urltorenew=$urlwithroot.'/core/modules/oauth/google_oauthcallback.php?state=userinfo_email,userinfo_profile,cloud_print&backtourl='.urlencode(DOL_URL_ROOT.'/admin/oauthlogintokens.php'); - $urltodelete=$urlwithroot.'/core/modules/oauth/google_oauthcallback.php?action=delete&backtourl='.urlencode(DOL_URL_ROOT.'/admin/oauthlogintokens.php'); - $urltocheckperms='https://security.google.com/settings/security/permissions'; + $OAUTH_SERVICENAME = 'Google'; + $urltorenew = $urlwithroot.'/core/modules/oauth/google_oauthcallback.php?state=userinfo_email,userinfo_profile,cloud_print&backtourl='.urlencode(DOL_URL_ROOT.'/admin/oauthlogintokens.php'); + $urltodelete = $urlwithroot.'/core/modules/oauth/google_oauthcallback.php?action=delete&backtourl='.urlencode(DOL_URL_ROOT.'/admin/oauthlogintokens.php'); + $urltocheckperms = 'https://security.google.com/settings/security/permissions'; } elseif ($key[0] == 'OAUTH_STRIPE_TEST_NAME') { - $OAUTH_SERVICENAME='StripeTest'; - $urltorenew=$urlwithroot.'/core/modules/oauth/stripetest_oauthcallback.php?backtourl='.urlencode(DOL_URL_ROOT.'/admin/oauthlogintokens.php'); - $urltodelete=''; - $urltocheckperms=''; + $OAUTH_SERVICENAME = 'StripeTest'; + $urltorenew = $urlwithroot.'/core/modules/oauth/stripetest_oauthcallback.php?backtourl='.urlencode(DOL_URL_ROOT.'/admin/oauthlogintokens.php'); + $urltodelete = ''; + $urltocheckperms = ''; } elseif ($key[0] == 'OAUTH_STRIPE_LIVE_NAME') { - $OAUTH_SERVICENAME='StripeLive'; - $urltorenew=$urlwithroot.'/core/modules/oauth/stripelive_oauthcallback.php?backtourl='.urlencode(DOL_URL_ROOT.'/admin/oauthlogintokens.php'); - $urltodelete=''; - $urltocheckperms=''; + $OAUTH_SERVICENAME = 'StripeLive'; + $urltorenew = $urlwithroot.'/core/modules/oauth/stripelive_oauthcallback.php?backtourl='.urlencode(DOL_URL_ROOT.'/admin/oauthlogintokens.php'); + $urltodelete = ''; + $urltocheckperms = ''; } else { - $urltorenew=''; - $urltodelete=''; - $urltocheckperms=''; + $urltorenew = ''; + $urltodelete = ''; + $urltocheckperms = ''; } // Show value of token - $tokenobj=null; + $tokenobj = null; // Token require_once DOL_DOCUMENT_ROOT.'/includes/OAuth/bootstrap.php'; require_once DOL_DOCUMENT_ROOT.'/includes/OAuth/bootstrap.php'; @@ -179,14 +179,14 @@ if ($mode == 'setup' && $user->admin) { $tokenobj = $storage->retrieveAccessToken($OAUTH_SERVICENAME); } - catch(Exception $e) + catch (Exception $e) { // Return an error if token not found } // Set other properties - $refreshtoken=false; - $expiredat=''; + $refreshtoken = false; + $expiredat = ''; $expire = false; // Is token expired or will token expire in the next 30 seconds @@ -209,19 +209,19 @@ if ($mode == 'setup' && $user->admin) } else { - $expiredat=dol_print_date($endoflife, "dayhour"); + $expiredat = dol_print_date($endoflife, "dayhour"); } } } - $submit_enabled=0; + $submit_enabled = 0; print ''; print ''; print ''; - print ''."\n"; + print '
'."\n"; print ''; print ''; @@ -230,7 +230,7 @@ if ($mode == 'setup' && $user->admin) print "\n"; print ''; - print ''; + print ''; //var_dump($key); print $langs->trans("OAuthIDSecret").''; print ''."\n"; print ''; - print ''; + print ''; //var_dump($key); print $langs->trans("IsTokenGenerated"); print ''; @@ -270,7 +270,7 @@ if ($mode == 'setup' && $user->admin) print ''; print ''; - print ''; + print ''; //var_dump($key); print $langs->trans("Token").''; print ''; - print ''; + print ''; //var_dump($key); print $langs->trans("TOKEN_REFRESH").''; print ''; - print ''; + print ''; //var_dump($key); print $langs->trans("TOKEN_EXPIRED").''; print ''; - print ''; + print ''; //var_dump($key); print $langs->trans("TOKEN_EXPIRE_AT").''; print '
'.$langs->trans($key[0]).'
'; @@ -241,7 +241,7 @@ if ($mode == 'setup' && $user->admin) print '
'; @@ -292,7 +292,7 @@ if ($mode == 'setup' && $user->admin) { // Token refresh print '
'; @@ -302,7 +302,7 @@ if ($mode == 'setup' && $user->admin) // Token expired print '
'; @@ -312,7 +312,7 @@ if ($mode == 'setup' && $user->admin) // Token expired at print '
'; @@ -323,7 +323,7 @@ if ($mode == 'setup' && $user->admin) print '
'; - if (! empty($driver)) + if (!empty($driver)) { if ($submit_enabled) { print '
'; @@ -339,8 +339,8 @@ if ($mode == 'test' && $user->admin) { print $langs->trans('PrintTestDesc'.$driver)."

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

\n"; - print '
'; + print '
'; print ''; print ''; print ''; @@ -379,7 +379,7 @@ if ($mode == 'userconf' && $user->admin) print "\n"; $sql = 'SELECT p.rowid, p.printer_name, p.printer_location, p.printer_id, p.copy, p.module, p.driver, p.userid, u.login FROM '.MAIN_DB_PREFIX.'printing as p, '.MAIN_DB_PREFIX.'user as u WHERE p.userid=u.rowid'; $resql = $db->query($sql); - while ($row=$db->fetch_array($resql)) { + while ($row = $db->fetch_array($resql)) { print ''; print ''; print ''; diff --git a/htdocs/admin/openinghours.php b/htdocs/admin/openinghours.php index c29f6816a05..f07d80a109b 100644 --- a/htdocs/admin/openinghours.php +++ b/htdocs/admin/openinghours.php @@ -89,7 +89,7 @@ if (empty($action) || $action == 'edit' || $action == 'updateedit') print ''; print ''; - print '
'.$langs->trans("User").''.$langs->trans("PrintModule").'
'.$row['login'].''.$row['module'].'
'; + print '
'; print ''."\n"; print ''; - print ''; + print ''; + print ''; print ''; // Multicurrency Amount VAT - print ''; - print ''; + print ''; + print ''; print ''; // Multicurrency Amount TTC - print ''; - print ''; + print ''; + print ''; print ''; } // Amount print ''; print ''; // 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 ''; print ''; print ''; } - if ($societe->localtax2_assuj=="1") //Localtax2 + if ($societe->localtax2_assuj == "1") //Localtax2 { print ''; print ''; @@ -2708,27 +2708,27 @@ else $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; + $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; // 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, p.rowid, p.fk_bank,'; - $sql.= ' c.id as paiement_type,'; - $sql.= ' pf.amount,'; - $sql.= ' ba.rowid as baid, ba.ref as baref, ba.label, ba.number as banumber, ba.account_number, ba.fk_accountancy_journal'; - $sql.= ' FROM '.MAIN_DB_PREFIX.'paiementfourn as p'; - $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'; - $sql.= ' LEFT JOIN '.MAIN_DB_PREFIX.'c_paiement as c ON p.fk_paiement = c.id'; - $sql.= ' LEFT JOIN '.MAIN_DB_PREFIX.'paiementfourn_facturefourn as pf ON pf.fk_paiementfourn = p.rowid'; - $sql.= ' WHERE pf.fk_facturefourn = '.$object->id; - $sql.= ' ORDER BY p.datep, p.tms'; + $sql .= ' c.id as paiement_type,'; + $sql .= ' pf.amount,'; + $sql .= ' ba.rowid as baid, ba.ref as baref, ba.label, ba.number as banumber, ba.account_number, ba.fk_accountancy_journal'; + $sql .= ' FROM '.MAIN_DB_PREFIX.'paiementfourn as p'; + $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'; + $sql .= ' LEFT JOIN '.MAIN_DB_PREFIX.'c_paiement as c ON p.fk_paiement = c.id'; + $sql .= ' LEFT JOIN '.MAIN_DB_PREFIX.'paiementfourn_facturefourn as pf ON pf.fk_paiementfourn = p.rowid'; + $sql .= ' WHERE pf.fk_facturefourn = '.$object->id; + $sql .= ' ORDER BY p.datep, p.tms'; $result = $db->query($sql); if ($result) @@ -2739,10 +2739,10 @@ else print '
'; print '
'.$langs->trans("Day").''.$langs->trans("Value").'
'; diff --git a/htdocs/admin/payment.php b/htdocs/admin/payment.php index 65b66636a10..4fcb3c84786 100644 --- a/htdocs/admin/payment.php +++ b/htdocs/admin/payment.php @@ -109,7 +109,7 @@ dol_fiche_head($head, 'payment', $langs->trans("Invoices"), -1, 'invoice'); print load_fiche_titre($langs->trans("PaymentsNumberingModule"), '', ''); -print ''; +print '
'; print ''; print ''; print ''; @@ -235,7 +235,7 @@ print ''; print ''; print ''; -print '
'.$langs->trans("Name").''.$langs->trans("Description").'
'; +print '
'; print ''; print ''; print ''; diff --git a/htdocs/admin/pdf.php b/htdocs/admin/pdf.php index e9346f49a3a..144eabf9aab 100644 --- a/htdocs/admin/pdf.php +++ b/htdocs/admin/pdf.php @@ -35,7 +35,7 @@ require_once DOL_DOCUMENT_ROOT.'/core/lib/pdf.lib.php'; // Load translation files required by the page $langs->loadLangs(array('admin', 'languages', 'other', 'companies', 'products', 'members')); -if (! $user->admin) accessforbidden(); +if (!$user->admin) accessforbidden(); $action = GETPOST('action', 'alpha'); $cancel = GETPOST('cancel', 'alpha'); @@ -46,7 +46,7 @@ $cancel = GETPOST('cancel', 'alpha'); */ if ($cancel) { - $action=''; + $action = ''; } if ($action == 'update') @@ -102,12 +102,12 @@ elseif ($action == 'disable_pdfsecurity') * View */ -$wikihelp='EN:First_setup|FR:Premiers_paramétrages|ES:Primeras_configuraciones'; +$wikihelp = 'EN:First_setup|FR:Premiers_paramétrages|ES:Primeras_configuraciones'; llxHeader('', $langs->trans("Setup"), $wikihelp); -$form=new Form($db); -$formother=new FormOther($db); -$formadmin=new FormAdmin($db); +$form = new Form($db); +$formother = new FormOther($db); +$formadmin = new FormAdmin($db); $arraydetailsforpdffoot = array( 0 => $langs->transnoentitiesnoconv('NoDetails'), @@ -134,11 +134,11 @@ clearstatcache(); print load_fiche_titre($langs->trans("DictionaryPaperFormat"), '', ''); print '
'; -print '
'.$langs->trans("Parameter").''.$langs->trans("Value").'
'; +print '
'; print ''; -$selected=$conf->global->MAIN_PDF_FORMAT; -if (empty($selected)) $selected=dol_getDefaultFormat(); +$selected = $conf->global->MAIN_PDF_FORMAT; +if (empty($selected)) $selected = dol_getDefaultFormat(); // Show pdf format @@ -147,16 +147,16 @@ print $formadmin->select_paper_format($selected, 'MAIN_PDF_FORMAT'); print ''; print ''; print ''; print ''; print ''; print '
'.$langs->trans("Parameter").''.$langs->trans("Value").'
'.$langs->trans("MAIN_PDF_MARGIN_LEFT").''; -print ''; +print ''; print '
'.$langs->trans("MAIN_PDF_MARGIN_RIGHT").''; -print ''; +print ''; print '
'.$langs->trans("MAIN_PDF_MARGIN_TOP").''; -print ''; +print ''; print '
'.$langs->trans("MAIN_PDF_MARGIN_BOTTOM").''; -print ''; +print ''; print '
'; @@ -169,22 +169,22 @@ print '
'; print load_fiche_titre($langs->trans("PDFAddressForging"), '', ''); print '
'; -print ''; +print '
'; print ''; // Hide VAT Intra on address print ''; // Show prof id in address into pdf -for($i=1; $i<=6; $i++) +for ($i = 1; $i <= 6; $i++) { - if (! $noCountryCode) + if (!$noCountryCode) { - $pid=$langs->transcountry("ProfId".$i, $mysoc->country_code); - if ($pid == '-') $pid=false; + $pid = $langs->transcountry("ProfId".$i, $mysoc->country_code); + if ($pid == '-') $pid = false; } else { @@ -194,7 +194,7 @@ for($i=1; $i<=6; $i++) { print ''; } } @@ -207,43 +207,43 @@ print '
'; // Localtaxes -$locales =''; -$text=''; +$locales = ''; +$text = ''; if ($mysoc->useLocalTax(1) || $mysoc->useLocalTax(2)) { if ($mysoc->useLocalTax(1)) { $locales = $langs->transcountry("LT1", $mysoc->country_code); - $text =''; } if ($mysoc->useLocalTax(2)) { - $locales.=($locales?' & ':'').$langs->transcountry("LT2", $mysoc->country_code); + $locales .= ($locales ? ' & ' : '').$langs->transcountry("LT2", $mysoc->country_code); - $text.= ''; + $text .= ''; } } $title = $langs->trans("PDFRulesForSalesTax"); if ($mysoc->useLocalTax(1) || $mysoc->useLocalTax(2)) { - $title.=' - '.$langs->trans("PDFLocaltax", $locales); + $title .= ' - '.$langs->trans("PDFLocaltax", $locales); } print load_fiche_titre($title, '', ''); -print '
'.$langs->trans("Parameter").''.$langs->trans("Value").'
'.$langs->trans("ShowVATIntaInAddress").''; -print $form->selectyesno('MAIN_TVAINTRA_NOT_IN_ADDRESS', (! empty($conf->global->MAIN_TVAINTRA_NOT_IN_ADDRESS))?$conf->global->MAIN_TVAINTRA_NOT_IN_ADDRESS:0, 1); +print $form->selectyesno('MAIN_TVAINTRA_NOT_IN_ADDRESS', (!empty($conf->global->MAIN_TVAINTRA_NOT_IN_ADDRESS)) ? $conf->global->MAIN_TVAINTRA_NOT_IN_ADDRESS : 0, 1); print '
'.$langs->trans("ShowProfIdInAddress").' - '.$pid.''; $keyforconstant = 'MAIN_PROFID'.$i.'_IN_ADDRESS'; - print $form->selectyesno($keyforconstant, isset($conf->global->$keyforconstant)?$conf->global->$keyforconstant:0, 1, $noCountryCode); + print $form->selectyesno($keyforconstant, isset($conf->global->$keyforconstant) ? $conf->global->$keyforconstant : 0, 1, $noCountryCode); print '
' . $langs->trans("HideLocalTaxOnPDF", $langs->transcountry("LT1", $mysoc->country_code)) . ''; - $text.= $form->selectyesno('MAIN_PDF_MAIN_HIDE_SECOND_TAX', (!empty($conf->global->MAIN_PDF_MAIN_HIDE_SECOND_TAX)) ? $conf->global->MAIN_PDF_MAIN_HIDE_SECOND_TAX : 0, 1); + $text = '
'.$langs->trans("HideLocalTaxOnPDF", $langs->transcountry("LT1", $mysoc->country_code)).''; + $text .= $form->selectyesno('MAIN_PDF_MAIN_HIDE_SECOND_TAX', (!empty($conf->global->MAIN_PDF_MAIN_HIDE_SECOND_TAX)) ? $conf->global->MAIN_PDF_MAIN_HIDE_SECOND_TAX : 0, 1); $text .= '
' . $langs->trans("HideLocalTaxOnPDF", $langs->transcountry("LT2", $mysoc->country_code)) . ''; - $text.= $form->selectyesno('MAIN_PDF_MAIN_HIDE_THIRD_TAX', (!empty($conf->global->MAIN_PDF_MAIN_HIDE_THIRD_TAX)) ? $conf->global->MAIN_PDF_MAIN_HIDE_THIRD_TAX : 0, 1); - $text.= '
'.$langs->trans("HideLocalTaxOnPDF", $langs->transcountry("LT2", $mysoc->country_code)).''; + $text .= $form->selectyesno('MAIN_PDF_MAIN_HIDE_THIRD_TAX', (!empty($conf->global->MAIN_PDF_MAIN_HIDE_THIRD_TAX)) ? $conf->global->MAIN_PDF_MAIN_HIDE_THIRD_TAX : 0, 1); + $text .= '
'; +print '
'; print ''; // Hide any information on Sale tax / VAT print ''; // Locataxes @@ -257,37 +257,37 @@ print '
'; print load_fiche_titre($langs->trans("Other"), '', ''); print '
'; -print '
'.$langs->trans("Parameter").''.$langs->trans("Value").'
'.$langs->trans("HideAnyVATInformationOnPDF").''; -print $form->selectyesno('MAIN_GENERATE_DOCUMENTS_WITHOUT_VAT', (! empty($conf->global->MAIN_GENERATE_DOCUMENTS_WITHOUT_VAT))?$conf->global->MAIN_GENERATE_DOCUMENTS_WITHOUT_VAT:0, 1); +print $form->selectyesno('MAIN_GENERATE_DOCUMENTS_WITHOUT_VAT', (!empty($conf->global->MAIN_GENERATE_DOCUMENTS_WITHOUT_VAT)) ? $conf->global->MAIN_GENERATE_DOCUMENTS_WITHOUT_VAT : 0, 1); print '
'; +print '
'; print ''; //Desc print ''; //Ref print ''; //Details print ''; //Invert sender and recipient print ''; // Place customer adress to the ISO location print ''; @@ -307,7 +307,7 @@ print '
'; print load_fiche_titre($langs->trans("Library"), '', ''); print '
'; -print '
'.$langs->trans("Parameter").''.$langs->trans("Value").'
'.$langs->trans("HideDescOnPDF").''; -print $form->selectyesno('MAIN_GENERATE_DOCUMENTS_HIDE_DESC', (! empty($conf->global->MAIN_GENERATE_DOCUMENTS_HIDE_DESC))?$conf->global->MAIN_GENERATE_DOCUMENTS_HIDE_DESC:0, 1); +print $form->selectyesno('MAIN_GENERATE_DOCUMENTS_HIDE_DESC', (!empty($conf->global->MAIN_GENERATE_DOCUMENTS_HIDE_DESC)) ? $conf->global->MAIN_GENERATE_DOCUMENTS_HIDE_DESC : 0, 1); print '
'.$langs->trans("HideRefOnPDF").''; -print $form->selectyesno('MAIN_GENERATE_DOCUMENTS_HIDE_REF', (! empty($conf->global->MAIN_GENERATE_DOCUMENTS_HIDE_REF))?$conf->global->MAIN_GENERATE_DOCUMENTS_HIDE_REF:0, 1); +print $form->selectyesno('MAIN_GENERATE_DOCUMENTS_HIDE_REF', (!empty($conf->global->MAIN_GENERATE_DOCUMENTS_HIDE_REF)) ? $conf->global->MAIN_GENERATE_DOCUMENTS_HIDE_REF : 0, 1); print '
'.$langs->trans("HideDetailsOnPDF").''; -print $form->selectyesno('MAIN_GENERATE_DOCUMENTS_HIDE_DETAILS', (! empty($conf->global->MAIN_GENERATE_DOCUMENTS_HIDE_DETAILS))?$conf->global->MAIN_GENERATE_DOCUMENTS_HIDE_DETAILS:0, 1); +print $form->selectyesno('MAIN_GENERATE_DOCUMENTS_HIDE_DETAILS', (!empty($conf->global->MAIN_GENERATE_DOCUMENTS_HIDE_DETAILS)) ? $conf->global->MAIN_GENERATE_DOCUMENTS_HIDE_DETAILS : 0, 1); print '
'.$langs->trans("SwapSenderAndRecipientOnPDF").''; -print $form->selectyesno('MAIN_INVERT_SENDER_RECIPIENT', (! empty($conf->global->MAIN_INVERT_SENDER_RECIPIENT))?$conf->global->MAIN_INVERT_SENDER_RECIPIENT:0, 1); +print $form->selectyesno('MAIN_INVERT_SENDER_RECIPIENT', (!empty($conf->global->MAIN_INVERT_SENDER_RECIPIENT)) ? $conf->global->MAIN_INVERT_SENDER_RECIPIENT : 0, 1); print '
'.$langs->trans("PlaceCustomerAddressToIsoLocation").''; -print $form->selectyesno('MAIN_PDF_USE_ISO_LOCATION', (! empty($conf->global->MAIN_PDF_USE_ISO_LOCATION))?$conf->global->MAIN_PDF_USE_ISO_LOCATION:0, 1); +print $form->selectyesno('MAIN_PDF_USE_ISO_LOCATION', (!empty($conf->global->MAIN_PDF_USE_ISO_LOCATION)) ? $conf->global->MAIN_PDF_USE_ISO_LOCATION : 0, 1); print '
'."\n"; +print '
'."\n"; print ''."\n"; print ''."\n"; @@ -317,9 +317,9 @@ print "\n"; print ''."\n"; print ''."\n"; print ''; } // Other attributes $cols = 2; - include DOL_DOCUMENT_ROOT . '/core/tpl/extrafields_view.tpl.php'; + include DOL_DOCUMENT_ROOT.'/core/tpl/extrafields_view.tpl.php'; print '
'.$langs->trans("Name").'
'.$langs->trans("LibraryToBuildPDF").''; -$i=0; -$pdf=pdf_getInstance('A4'); -if (class_exists('FPDF') && ! class_exists('TCPDF')) +$i = 0; +$pdf = pdf_getInstance('A4'); +if (class_exists('FPDF') && !class_exists('TCPDF')) { if ($i) print ' + '; print 'FPDF'; diff --git a/htdocs/admin/perms.php b/htdocs/admin/perms.php index 8e1de4d83b6..23fa06887a9 100644 --- a/htdocs/admin/perms.php +++ b/htdocs/admin/perms.php @@ -124,7 +124,7 @@ dol_fiche_head($head, 'default', $langs->trans("Security"), -1); print info_admin(showModulesExludedForExternal($modules)).'
'."\n"; print '
'; -print ''; +print '
'; // Show permissions lines $sql = "SELECT r.id, r.libelle, r.module, r.perms, r.subperms, r.bydefault"; diff --git a/htdocs/admin/prelevement.php b/htdocs/admin/prelevement.php index 7dd00938dc9..1d9b181b295 100644 --- a/htdocs/admin/prelevement.php +++ b/htdocs/admin/prelevement.php @@ -210,7 +210,7 @@ print '
'; print ''; print ''; -print '
'; +print '
'; print ''; print ''; @@ -489,7 +489,7 @@ if (! empty($conf->global->MAIN_MODULE_NOTIFICATION)) print ''; print ''; - print '
'.$langs->trans("Parameter").'
'; + print '
'; print ''; print ''; print ''; diff --git a/htdocs/admin/propal.php b/htdocs/admin/propal.php index a0f817a40c1..dc58a2c4809 100644 --- a/htdocs/admin/propal.php +++ b/htdocs/admin/propal.php @@ -258,7 +258,7 @@ dol_fiche_head($head, 'general', $langs->trans("Proposals"), -1, 'propal'); */ print load_fiche_titre($langs->trans("ProposalsNumberingModules"), '', ''); -print '
'.$langs->trans("User").''.$langs->trans("Value").'
'; +print '
'; print ''; print '\n"; print '\n"; @@ -523,7 +523,7 @@ if (empty($conf->facture->enabled)) print ''; print ''; - print '
'.$langs->trans("Name")."'.$langs->trans("Description")."
'; + print '
'; print ''; print '
'; @@ -746,7 +746,7 @@ print "
\n
"; */ print load_fiche_titre($langs->trans("Notifications"), '', ''); -print ''; +print '
'; print ''; print ''; print ''; diff --git a/htdocs/admin/receiptprinter.php b/htdocs/admin/receiptprinter.php index 9d3d125f3da..8a2b3078c7d 100644 --- a/htdocs/admin/receiptprinter.php +++ b/htdocs/admin/receiptprinter.php @@ -350,7 +350,7 @@ if ($mode == 'config' && $user->admin) { dol_fiche_head(); print $langs->trans("ReceiptPrinterTypeDesc")."

\n"; - print '
'.$langs->trans("Parameter").'
'."\n"; + print '
'."\n"; print ''; print ''; print ''; @@ -363,7 +363,7 @@ if ($mode == 'config' && $user->admin) { dol_fiche_head(); print $langs->trans("ReceiptPrinterProfileDesc")."

\n"; - print '
'.$langs->trans("CONNECTOR_DUMMY").':'.$langs->trans("CONNECTOR_DUMMY_HELP").'
'.$langs->trans("CONNECTOR_NETWORK_PRINT").':'.$langs->trans("CONNECTOR_NETWORK_PRINT_HELP").'
'.$langs->trans("CONNECTOR_FILE_PRINT").':'.$langs->trans("CONNECTOR_FILE_PRINT_HELP").'
'."\n"; + print '
'."\n"; print ''; print ''; print ''; diff --git a/htdocs/admin/reception_setup.php b/htdocs/admin/reception_setup.php index 27564d6b4e0..eacf0deaf68 100644 --- a/htdocs/admin/reception_setup.php +++ b/htdocs/admin/reception_setup.php @@ -208,7 +208,7 @@ dol_fiche_head($head, 'reception', $langs->trans("Receptions"), -1, 'sending'); print load_fiche_titre($langs->trans("ReceptionsNumberingModules")); -print '
'.$langs->trans("PROFILE_DEFAULT").':'.$langs->trans("PROFILE_DEFAULT_HELP").'
'.$langs->trans("PROFILE_SIMPLE").':'.$langs->trans("PROFILE_SIMPLE_HELP").'
'.$langs->trans("PROFILE_EPOSTEP").':'.$langs->trans("PROFILE_EPOSTEP_HELP").'
'; +print '
'; print ''; print ''; print ''; @@ -337,7 +337,7 @@ else dol_print_error($db); } -print '
'.$langs->trans("Name").''.$langs->trans("Description").'
'; +print '
'; print ''; print ''; print ''; diff --git a/htdocs/admin/resource.php b/htdocs/admin/resource.php index 44e4d1ae9de..4304007d830 100644 --- a/htdocs/admin/resource.php +++ b/htdocs/admin/resource.php @@ -76,7 +76,7 @@ print ''; print ''; print ''; -print '
'.$langs->trans("Name").''.$langs->trans("Description").'
'; +print '
'; print ''; print ''."\n"; print ''."\n"; diff --git a/htdocs/admin/security.php b/htdocs/admin/security.php index 2089debcf04..1760651b693 100644 --- a/htdocs/admin/security.php +++ b/htdocs/admin/security.php @@ -27,22 +27,22 @@ require '../main.inc.php'; require_once DOL_DOCUMENT_ROOT.'/core/lib/admin.lib.php'; require_once DOL_DOCUMENT_ROOT.'/core/lib/security2.lib.php'; -$action=GETPOST('action', 'aZ09'); +$action = GETPOST('action', 'aZ09'); // Load translation files required by the page -$langs->loadLangs(array("users","admin","other")); +$langs->loadLangs(array("users", "admin", "other")); if (!$user->admin) accessforbidden(); // Allow/Disallow change to clear passwords once passwords are crypted -$allow_disable_encryption=true; +$allow_disable_encryption = true; /* * Actions */ if ($action == 'setgeneraterule') { - if (! dolibarr_set_const($db, 'USER_PASSWORD_GENERATED', $_GET["value"], 'chaine', 0, '', $conf->entity)) + if (!dolibarr_set_const($db, 'USER_PASSWORD_GENERATED', $_GET["value"], 'chaine', 0, '', $conf->entity)) { dol_print_error($db); } @@ -55,33 +55,33 @@ if ($action == 'setgeneraterule') if ($action == 'activate_encrypt') { - $error=0; + $error = 0; $db->begin(); dolibarr_set_const($db, "DATABASE_PWD_ENCRYPTED", "1", 'chaine', 0, '', $conf->entity); $sql = "SELECT u.rowid, u.pass, u.pass_crypted"; - $sql.= " FROM ".MAIN_DB_PREFIX."user as u"; - $sql.= " WHERE u.pass IS NOT NULL AND LENGTH(u.pass) < 32"; // Not a MD5 value + $sql .= " FROM ".MAIN_DB_PREFIX."user as u"; + $sql .= " WHERE u.pass IS NOT NULL AND LENGTH(u.pass) < 32"; // Not a MD5 value - $resql=$db->query($sql); + $resql = $db->query($sql); if ($resql) { - $numrows=$db->num_rows($resql); - $i=0; + $numrows = $db->num_rows($resql); + $i = 0; while ($i < $numrows) { - $obj=$db->fetch_object($resql); + $obj = $db->fetch_object($resql); if (dol_hash($obj->pass)) { $sql = "UPDATE ".MAIN_DB_PREFIX."user"; - $sql.= " SET pass_crypted = '".dol_hash($obj->pass)."', pass = NULL"; - $sql.= " WHERE rowid=".$obj->rowid; + $sql .= " SET pass_crypted = '".dol_hash($obj->pass)."', pass = NULL"; + $sql .= " WHERE rowid=".$obj->rowid; //print $sql; $resql2 = $db->query($sql); - if (! $resql2) + if (!$resql2) { dol_print_error($db); $error++; @@ -96,7 +96,7 @@ if ($action == 'activate_encrypt') //print $error." ".$sql; //exit; - if (! $error) + if (!$error) { $db->commit(); header("Location: security.php"); @@ -125,7 +125,7 @@ if ($action == 'activate_encryptdbpassconf') $result = encodedecode_dbpassconf(1); if ($result > 0) { - sleep(3); // Don't know why but we need to wait file is completely saved before making the reload. Even with flush and clearstatcache, we need to wait. + sleep(3); // Don't know why but we need to wait file is completely saved before making the reload. Even with flush and clearstatcache, we need to wait. // database value not required //dolibarr_set_const($db, "MAIN_DATABASE_PWD_CONFIG_ENCRYPTED", "1"); @@ -142,7 +142,7 @@ elseif ($action == 'disable_encryptdbpassconf') $result = encodedecode_dbpassconf(0); if ($result > 0) { - sleep(3); // Don't know why but we need to wait file is completely saved before making the reload. Even with flush and clearstatcache, we need to wait. + sleep(3); // Don't know why but we need to wait file is completely saved before making the reload. Even with flush and clearstatcache, we need to wait. // database value not required //dolibarr_del_const($db, "MAIN_DATABASE_PWD_CONFIG_ENCRYPTED",$conf->entity); @@ -196,7 +196,7 @@ if ($action == 'maj_pattern') */ $form = new Form($db); -$wikihelp='EN:Setup_Security|FR:Paramétrage_Sécurité|ES:Configuración_Seguridad'; +$wikihelp = 'EN:Setup_Security|FR:Paramétrage_Sécurité|ES:Configuración_Seguridad'; llxHeader('', $langs->trans("Passwords"), $wikihelp); print load_fiche_titre($langs->trans("SecuritySetup"), '', 'title_setup'); @@ -205,7 +205,7 @@ print $langs->trans("GeneratedPasswordDesc")."
\n"; print "
\n"; -$head=security_prepare_head(); +$head = security_prepare_head(); dol_fiche_head($head, 'passwords', $langs->trans("Security"), -1); @@ -220,11 +220,11 @@ print ''; // Charge tableau des modules generation $dir = "../core/modules/security/generate"; clearstatcache(); -$handle=opendir($dir); -$i=1; +$handle = opendir($dir); +$i = 1; if (is_resource($handle)) { - while (($file = readdir($handle))!==false) + while (($file = readdir($handle)) !== false) { if (preg_match('/(modGeneratePass[a-z]+)\.class\.php$/i', $file, $reg)) { @@ -233,7 +233,7 @@ if (is_resource($handle)) require_once $dir.'/'.$file; $obj = new $classname($db, $conf, $langs, $user); - $arrayhandler[$obj->id]=$obj; + $arrayhandler[$obj->id] = $obj; $i++; } } @@ -241,7 +241,7 @@ if (is_resource($handle)) } asort($arrayhandler); -print '
'.$langs->trans("Parameters").''.$langs->trans("Value").'
'; +print '
'; print ''; print ''; print ''; @@ -251,7 +251,7 @@ print ''; foreach ($arrayhandler as $key => $module) { // Show modules according to features level - if ($module->version == 'development' && $conf->global->MAIN_FEATURES_LEVEL < 2) continue; + if ($module->version == 'development' && $conf->global->MAIN_FEATURES_LEVEL < 2) continue; if ($module->version == 'experimental' && $conf->global->MAIN_FEATURES_LEVEL < 1) continue; if ($module->isEnabled()) @@ -265,9 +265,9 @@ foreach ($arrayhandler as $key => $module) // Show example of numbering module print ''."\n"; @@ -288,47 +288,47 @@ print ''; //if($conf->global->MAIN_SECURITY_DISABLEFORGETPASSLINK == 1) // Patter for Password Perso -if ($conf->global->USER_PASSWORD_GENERATED == "Perso"){ +if ($conf->global->USER_PASSWORD_GENERATED == "Perso") { $tabConf = explode(";", $conf->global->USER_PASSWORD_PATTERN); print '
'; - print '
'.$langs->trans("RuleForGeneratedPasswords").''.$langs->trans("Example").'
'; - $tmp=$module->getExample(); + $tmp = $module->getExample(); if (preg_match('/^Error/', $tmp)) { $langs->load("errors"); print '
'.$langs->trans($tmp).'
'; } - elseif ($tmp=='NotConfigured') print $langs->trans($tmp); + elseif ($tmp == 'NotConfigured') print $langs->trans($tmp); else print $tmp; print '
'; + print '
'; print ''; print ''; print ''; print ''; - print '"; + print '"; print ''; print ''; print ''; - print '"; + print '"; print ''; print ''; print ''; - print '"; + print '"; print ''; print ''; print ''; - print '"; + print '"; print ''; print ''; print ''; - print '"; + print '"; print ''; print ''; print ''; - print '"; + print '"; print ''; print ''; @@ -398,11 +398,11 @@ if ($conf->global->USER_PASSWORD_GENERATED == "Perso"){ // Cryptage mot de passe print '
'; -print ""; +print ""; print ''; print ""; -print '
'.$langs->trans("PasswordPatternDesc").'
' . $langs->trans("MinLength")."'.$langs->trans("MinLength")."
' . $langs->trans("NbMajMin")."'.$langs->trans("NbMajMin")."
' . $langs->trans("NbNumMin")."'.$langs->trans("NbNumMin")."
' . $langs->trans("NbSpeMin")."'.$langs->trans("NbSpeMin")."
' . $langs->trans("NbIteConsecutive")."'.$langs->trans("NbIteConsecutive")."
' . $langs->trans("NoAmbiCaracAutoGeneration")."'.$langs->trans("NoAmbiCaracAutoGeneration")." '.($tabConf[5] ? $langs->trans("Activated") : $langs->trans("Disabled")).'
'; +print '
'; print ''; print ''; print ''; @@ -413,12 +413,12 @@ print ''; print ''; print ''; print ''; -if (! $conf->global->DATABASE_PWD_ENCRYPTED) +if (!$conf->global->DATABASE_PWD_ENCRYPTED) { print ''; print ''; print ''; print ''; print ''; print ''; print '
'.$langs->trans("Parameters").''.$langs->trans("Activated").'
'.$langs->trans("DoNotStoreClearPassword").''; -if (! empty($conf->global->DATABASE_PWD_ENCRYPTED)) +if (!empty($conf->global->DATABASE_PWD_ENCRYPTED)) { print img_picto($langs->trans("Active"), 'tick'); } print ''; print ''.$langs->trans("Activate").''; @@ -426,7 +426,7 @@ if (! $conf->global->DATABASE_PWD_ENCRYPTED) } // Database conf file encryption -if (! empty($conf->global->DATABASE_PWD_ENCRYPTED)) +if (!empty($conf->global->DATABASE_PWD_ENCRYPTED)) { print ''; if ($allow_disable_encryption) @@ -449,7 +449,7 @@ print '
'.$langs->trans("MainDbPasswordFileConfEncrypted").''; -if (preg_match('/crypted:/i', $dolibarr_main_db_pass) || ! empty($dolibarr_main_db_encrypted_pass)) +if (preg_match('/crypted:/i', $dolibarr_main_db_pass) || !empty($dolibarr_main_db_encrypted_pass)) { print img_picto($langs->trans("Active"), 'tick'); } @@ -468,7 +468,7 @@ else { print ''.$langs->trans("Activate").''; } - if (! empty($dolibarr_main_db_encrypted_pass)) + if (!empty($dolibarr_main_db_encrypted_pass)) { print ''.$langs->trans("Disable").''; } @@ -484,7 +484,7 @@ print '
'.$langs->trans("DisableForgetPasswordLinkOnLogonPage").''; -if(! empty($conf->global->MAIN_SECURITY_DISABLEFORGETPASSLINK)) +if (!empty($conf->global->MAIN_SECURITY_DISABLEFORGETPASSLINK)) { print img_picto($langs->trans("Active"), 'tick'); } diff --git a/htdocs/admin/security_file.php b/htdocs/admin/security_file.php index 0bd2dcdb1be..aeb2ee0fe19 100644 --- a/htdocs/admin/security_file.php +++ b/htdocs/admin/security_file.php @@ -31,19 +31,19 @@ require_once DOL_DOCUMENT_ROOT.'/core/class/html.formfile.class.php'; // Load translation files required by the page $langs->loadLangs(array('users', 'admin', 'other')); -if (! $user->admin) +if (!$user->admin) accessforbidden(); -$action=GETPOST('action', 'alpha'); +$action = GETPOST('action', 'alpha'); -$upload_dir=$conf->admin->dir_temp; +$upload_dir = $conf->admin->dir_temp; /* * Actions */ -if (GETPOST('sendit') && ! empty($conf->global->MAIN_UPLOAD_DOC)) +if (GETPOST('sendit') && !empty($conf->global->MAIN_UPLOAD_DOC)) { require_once DOL_DOCUMENT_ROOT.'/core/lib/files.lib.php'; @@ -52,15 +52,15 @@ if (GETPOST('sendit') && ! empty($conf->global->MAIN_UPLOAD_DOC)) if ($action == 'updateform') { - $antivircommand = GETPOST('MAIN_ANTIVIRUS_COMMAND', 'none'); // Use GETPOST none because we must accept ". Example c:\Progra~1\ClamWin\bin\clamscan.exe - $antivirparam = GETPOST('MAIN_ANTIVIRUS_PARAM', 'none'); // Use GETPOST none because we must accept ". Example --database="C:\Program Files (x86)\ClamWin\lib" - $antivircommand = dol_string_nospecial($antivircommand, '', array("|", ";", "<", ">", "&")); // Sanitize command - $antivirparam = dol_string_nospecial($antivirparam, '', array("|", ";", "<", ">", "&")); // Sanitize params + $antivircommand = GETPOST('MAIN_ANTIVIRUS_COMMAND', 'none'); // Use GETPOST none because we must accept ". Example c:\Progra~1\ClamWin\bin\clamscan.exe + $antivirparam = GETPOST('MAIN_ANTIVIRUS_PARAM', 'none'); // Use GETPOST none because we must accept ". Example --database="C:\Program Files (x86)\ClamWin\lib" + $antivircommand = dol_string_nospecial($antivircommand, '', array("|", ";", "<", ">", "&")); // Sanitize command + $antivirparam = dol_string_nospecial($antivirparam, '', array("|", ";", "<", ">", "&")); // Sanitize params - $res3=dolibarr_set_const($db, 'MAIN_UPLOAD_DOC', GETPOST('MAIN_UPLOAD_DOC', 'alpha'), 'chaine', 0, '', $conf->entity); - $res4=dolibarr_set_const($db, "MAIN_UMASK", GETPOST('MAIN_UMASK', 'alpha'), 'chaine', 0, '', $conf->entity); - $res5=dolibarr_set_const($db, "MAIN_ANTIVIRUS_COMMAND", trim($antivircommand), 'chaine', 0, '', $conf->entity); - $res6=dolibarr_set_const($db, "MAIN_ANTIVIRUS_PARAM", trim($antivirparam), 'chaine', 0, '', $conf->entity); + $res3 = dolibarr_set_const($db, 'MAIN_UPLOAD_DOC', GETPOST('MAIN_UPLOAD_DOC', 'alpha'), 'chaine', 0, '', $conf->entity); + $res4 = dolibarr_set_const($db, "MAIN_UMASK", GETPOST('MAIN_UMASK', 'alpha'), 'chaine', 0, '', $conf->entity); + $res5 = dolibarr_set_const($db, "MAIN_ANTIVIRUS_COMMAND", trim($antivircommand), 'chaine', 0, '', $conf->entity); + $res6 = dolibarr_set_const($db, "MAIN_ANTIVIRUS_PARAM", trim($antivirparam), 'chaine', 0, '', $conf->entity); if ($res3 && $res4 && $res5 && $res6) setEventMessages($langs->trans("RecordModifiedSuccessfully"), null, 'mesgs'); } @@ -70,8 +70,8 @@ if ($action == 'updateform') elseif ($action == 'delete') { $langs->load("other"); - $file = $conf->admin->dir_temp . '/' . GETPOST('urlfile', 'alpha'); // Do not use urldecode here ($_GET and $_REQUEST are already decoded by PHP). - $ret=dol_delete_file($file); + $file = $conf->admin->dir_temp.'/'.GETPOST('urlfile', 'alpha'); // 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('urlfile', 'alpha')), null, 'mesgs'); else setEventMessages($langs->trans("ErrorFailToDeleteFile", GETPOST('urlfile', 'alpha')), null, 'errors'); Header('Location: '.$_SERVER["PHP_SELF"]); @@ -85,7 +85,7 @@ elseif ($action == 'delete') $form = new Form($db); -$wikihelp='EN:Setup_Security|FR:Paramétrage_Sécurité|ES:Configuración_Seguridad'; +$wikihelp = 'EN:Setup_Security|FR:Paramétrage_Sécurité|ES:Configuración_Seguridad'; llxHeader('', $langs->trans("Files"), $wikihelp); print load_fiche_titre($langs->trans("SecuritySetup"), '', 'title_setup'); @@ -98,16 +98,16 @@ print ''; print ''; print ''; -$head=security_prepare_head(); +$head = security_prepare_head(); dol_fiche_head($head, 'file', $langs->trans("Security"), -1); // Upload options -$var=false; +$var = false; print '
'; -print ''; +print '
'; print ''; print ''; print ''; @@ -115,8 +115,8 @@ print ''; print ''; print ''; print ''; print '"; print ''; @@ -164,7 +164,7 @@ print ''; print '"; print ''; @@ -180,11 +180,11 @@ print ''; // Form to test upload print '
'; -$formfile=new FormFile($db); +$formfile = new FormFile($db); $formfile->form_attach_new_file($_SERVER['PHP_SELF'], $langs->trans("FormToTestFileUploadForm"), 0, 0, 1, 50, '', '', 1, '', 0); // List of document -$filearray=dol_dir_list($upload_dir, "files", 0, '', '', 'name', SORT_ASC, 1); +$filearray = dol_dir_list($upload_dir, "files", 0, '', '', 'name', SORT_ASC, 1); $formfile->list_of_documents($filearray, null, 'admin_temp', ''); // End of page diff --git a/htdocs/admin/security_other.php b/htdocs/admin/security_other.php index c9bf1ba4357..87cd8519449 100644 --- a/htdocs/admin/security_other.php +++ b/htdocs/admin/security_other.php @@ -103,7 +103,7 @@ dol_fiche_head($head, 'misc', $langs->trans("Security"), -1); // Other Options -print '
'.$langs->trans("Parameters").''.$langs->trans("Value").'
'.$langs->trans("MaxSizeForUploadedFiles").'.'; -$max=@ini_get('upload_max_filesize'); -if ($max) print ' '.$langs->trans("MustBeLowerThanPHPLimit", $max*1024, $langs->trans("Kb")).'.'; +$max = @ini_get('upload_max_filesize'); +if ($max) print ' '.$langs->trans("MustBeLowerThanPHPLimit", $max * 1024, $langs->trans("Kb")).'.'; else print ' '.$langs->trans("NoMaxSizeByPHPLimit").'.'; print ''; @@ -142,18 +142,18 @@ print $langs->trans("AntiVirusCommandExample"); // Check command in inside safe_mode print ''; -if (ini_get('safe_mode') && ! empty($conf->global->MAIN_ANTIVIRUS_COMMAND)) +if (ini_get('safe_mode') && !empty($conf->global->MAIN_ANTIVIRUS_COMMAND)) { $langs->load("errors"); - $basedir=preg_replace('/"/', '', dirname($conf->global->MAIN_ANTIVIRUS_COMMAND)); - $listdir=explode(';', ini_get('safe_mode_exec_dir')); - if (! in_array($basedir, $listdir)) + $basedir = preg_replace('/"/', '', dirname($conf->global->MAIN_ANTIVIRUS_COMMAND)); + $listdir = explode(';', ini_get('safe_mode_exec_dir')); + if (!in_array($basedir, $listdir)) { print img_warning($langs->trans('WarningSafeModeOnCheckExecDir')); dol_syslog("safe_mode is on, basedir is ".$basedir.", safe_mode_exec_dir is ".ini_get('safe_mode_exec_dir'), LOG_WARNING); } } -print ''; +print ''; print "
'.$langs->trans("AntiVirusParam").'
'; print $langs->trans("AntiVirusParamExample"); print '
'; -print ''; +print ''; print "
'; +print '
'; print ''; print ''; print ''; diff --git a/htdocs/admin/sms.php b/htdocs/admin/sms.php index 1f37a36ec4f..021d6d99d4e 100644 --- a/htdocs/admin/sms.php +++ b/htdocs/admin/sms.php @@ -26,12 +26,12 @@ require '../main.inc.php'; require_once DOL_DOCUMENT_ROOT.'/core/lib/admin.lib.php'; // Load translation files required by the page -$langs->loadLangs(array("companies","admin","products","sms","other","errors")); +$langs->loadLangs(array("companies", "admin", "products", "sms", "other", "errors")); if (!$user->admin) accessforbidden(); -$substitutionarrayfortest=array( +$substitutionarrayfortest = array( '__ID__' => 'TESTIdRecord', '__PHONEFROM__' => 'TESTPhoneFrom', '__PHONETO__' => 'TESTPhoneTo', @@ -39,7 +39,7 @@ $substitutionarrayfortest=array( '__FIRSTNAME__' => 'TESTFirstname' ); -$action=GETPOST('action', 'aZ09'); +$action = GETPOST('action', 'aZ09'); /* @@ -63,16 +63,16 @@ if ($action == 'update' && empty($_POST["cancel"])) /* * Send sms */ -if ($action == 'send' && ! $_POST['cancel']) +if ($action == 'send' && !$_POST['cancel']) { - $error=0; + $error = 0; - $smsfrom=''; - if (! empty($_POST["fromsms"])) $smsfrom=GETPOST("fromsms"); - if (empty($smsfrom)) $smsfrom=GETPOST("fromname"); + $smsfrom = ''; + if (!empty($_POST["fromsms"])) $smsfrom = GETPOST("fromsms"); + if (empty($smsfrom)) $smsfrom = GETPOST("fromname"); $sendto = GETPOST("sendto"); $body = GETPOST('message'); - $deliveryreceipt= GETPOST("deliveryreceipt"); + $deliveryreceipt = GETPOST("deliveryreceipt"); $deferred = GETPOST('deferred'); $priority = GETPOST('priority'); $class = GETPOST('class'); @@ -82,40 +82,40 @@ if ($action == 'send' && ! $_POST['cancel']) include_once DOL_DOCUMENT_ROOT.'/core/class/html.formsms.class.php'; $formsms = new FormSms($db); - if (! empty($formsms->error)) + if (!empty($formsms->error)) { setEventMessages($formsms->error, $formsms->errors, 'errors'); - $action='test'; + $action = 'test'; $error++; } if (empty($body)) { setEventMessages($langs->trans("ErrorFieldRequired", $langs->transnoentities("Message")), null, 'errors'); - $action='test'; + $action = 'test'; $error++; } - if (empty($smsfrom) || ! str_replace('+', '', $smsfrom)) + if (empty($smsfrom) || !str_replace('+', '', $smsfrom)) { setEventMessages($langs->trans("ErrorFieldRequired", $langs->transnoentities("SmsFrom")), null, 'errors'); - $action='test'; + $action = 'test'; $error++; } - if (empty($sendto) || ! str_replace('+', '', $sendto)) + if (empty($sendto) || !str_replace('+', '', $sendto)) { setEventMessages($langs->trans("ErrorFieldRequired", $langs->transnoentities("SmsTo")), null, 'errors'); - $action='test'; + $action = 'test'; $error++; } - if (! $error) + if (!$error) { // Make substitutions into message complete_substitutions_array($substitutionarrayfortest, $langs); - $body=make_substitutions($body, $substitutionarrayfortest); + $body = make_substitutions($body, $substitutionarrayfortest); require_once DOL_DOCUMENT_ROOT.'/core/class/CSMSFile.class.php'; - $smsfile = new CSMSFile($sendto, $smsfrom, $body, $deliveryreceipt, $deferred, $priority, $class); // This define OvhSms->login, pass, session and account - $result=$smsfile->sendfile(); // This send SMS + $smsfile = new CSMSFile($sendto, $smsfrom, $body, $deliveryreceipt, $deferred, $priority, $class); // This define OvhSms->login, pass, session and account + $result = $smsfile->sendfile(); // This send SMS if ($result) { @@ -128,7 +128,7 @@ if ($action == 'send' && ! $_POST['cancel']) setEventMessages($smsfile->error, $smsfile->errors, 'errors'); } - $action=''; + $action = ''; } } @@ -138,11 +138,11 @@ if ($action == 'send' && ! $_POST['cancel']) * View */ -$linuxlike=1; -if (preg_match('/^win/i', PHP_OS)) $linuxlike=0; -if (preg_match('/^mac/i', PHP_OS)) $linuxlike=0; +$linuxlike = 1; +if (preg_match('/^win/i', PHP_OS)) $linuxlike = 0; +if (preg_match('/^mac/i', PHP_OS)) $linuxlike = 0; -$wikihelp='EN:Setup Sms|FR:Paramétrage Sms|ES:Configuración Sms'; +$wikihelp = 'EN:Setup Sms|FR:Paramétrage Sms|ES:Configuración Sms'; llxHeader('', $langs->trans("Setup"), $wikihelp); print load_fiche_titre($langs->trans("SmsSetup"), '', 'title_setup'); @@ -151,14 +151,14 @@ print ''.$langs->trans("SmsDesc")."
\n"; print "
\n"; // List of sending methods -$listofmethods=(is_array($conf->modules_parts['sms'])?$conf->modules_parts['sms']:array()); +$listofmethods = (is_array($conf->modules_parts['sms']) ? $conf->modules_parts['sms'] : array()); asort($listofmethods); if ($action == 'edit') { - $form=new Form($db); + $form = new Form($db); - if (! count($listofmethods)) print '
'.$langs->trans("NoSmsEngine", 'DoliStore').'
'; + if (!count($listofmethods)) print '
'.$langs->trans("NoSmsEngine", 'DoliStore').'
'; print ''; print ''; @@ -166,7 +166,7 @@ if ($action == 'edit') clearstatcache(); - print '
'.$langs->trans("Parameters").''.$langs->trans("Status").'
'; + print '
'; print ''; // Disable @@ -185,7 +185,7 @@ if ($action == 'edit') // From print ''; - print ''; // Autocopy to @@ -197,7 +197,7 @@ if ($action == 'edit') print '
'.$langs->trans("Parameter").''.$langs->trans("Value").'
'.$langs->trans("MAIN_MAIL_SMS_FROM", $langs->transnoentities("Undefined")).'
'; print '
'; - print ''; + print ''; print '     '; print ''; print '
'; @@ -207,9 +207,9 @@ if ($action == 'edit') } else { - if (! count($listofmethods)) print '
'.$langs->trans("NoSmsEngine", 'DoliStore').'
'; + if (!count($listofmethods)) print '
'.$langs->trans("NoSmsEngine", 'DoliStore').'
'; - print ''; + print '
'; print ''; // Disable @@ -220,15 +220,15 @@ else // Method print ''; // From print ''; print ''; // Autocopy to @@ -260,7 +260,7 @@ else print ''.$langs->trans("DoTestServerAvailability").''; }*/ - if (count($listofmethods) && ! empty($conf->global->MAIN_SMS_SENDMODE)) + if (count($listofmethods) && !empty($conf->global->MAIN_SMS_SENDMODE)) { print ''.$langs->trans("DoTestSend").''; } @@ -309,13 +309,10 @@ else $formsms->withfromreadonly=0; $formsms->withsubstit=0; $formsms->withfrom=1; - $formsms->witherrorsto=1; $formsms->withto=(isset($_POST['sendto'])?$_POST['sendto']:$user->user_mobile?$user->user_mobile:1); - $formsms->withfile=2; $formsms->withbody=(isset($_POST['message'])?(empty($_POST['message'])?1:$_POST['message']):$langs->trans("ThisIsATestMessage")); $formsms->withbodyreadonly=0; $formsms->withcancel=1; - $formsms->withfckeditor=0; // Tableau des substitutions $formsms->substit=$substitutionarrayfortest; // Tableau des parametres complementaires du post diff --git a/htdocs/admin/stock.php b/htdocs/admin/stock.php index 51bf959bb72..b36106b3e80 100644 --- a/htdocs/admin/stock.php +++ b/htdocs/admin/stock.php @@ -100,7 +100,7 @@ print '
'; //} // Title rule for stock decrease -print '
'.$langs->trans("Parameter").''.$langs->trans("Value").'
'.$langs->trans("MAIN_SMS_SENDMODE").''; - $text=$listofmethods[$conf->global->MAIN_SMS_SENDMODE]; - if (empty($text)) $text=$langs->trans("Undefined").' '.img_warning(); + $text = $listofmethods[$conf->global->MAIN_SMS_SENDMODE]; + if (empty($text)) $text = $langs->trans("Undefined").' '.img_warning(); print $text; print '
'.$langs->trans("MAIN_MAIL_SMS_FROM", $langs->transnoentities("Undefined")).''.$conf->global->MAIN_MAIL_SMS_FROM; - if (!empty($conf->global->MAIN_MAIL_SMS_FROM) && ! isValidPhone($conf->global->MAIN_MAIL_SMS_FROM)) print ' '.img_warning($langs->trans("ErrorBadPhone")); + if (!empty($conf->global->MAIN_MAIL_SMS_FROM) && !isValidPhone($conf->global->MAIN_MAIL_SMS_FROM)) print ' '.img_warning($langs->trans("ErrorBadPhone")); print '
'; +print '
'; print ''; print "\n"; print ''."\n"; @@ -202,7 +202,7 @@ print '
".$langs->trans("RuleForStockManagementDecrease")."'.$langs->trans("Status").'
'; print '
'; // Title rule for stock increase -print ''; +print '
'; print ''; print "\n"; print ''."\n"; @@ -314,7 +314,7 @@ print '
".$langs->trans("RuleForStockManagementIncrease")."'.$langs->trans("Status").'
'; print '
'; -print ''; +print '
'; print ''; print "\n"; print ''."\n"; @@ -392,7 +392,7 @@ if ( if ($virtualdiffersfromphysical) { - print '
".$langs->trans("RuleForStockAvailability")."'.$langs->trans("Status").'
'; + print '
'; print ''; print "\n"; print ''."\n"; @@ -414,7 +414,7 @@ if ($virtualdiffersfromphysical) } -print '
".$langs->trans("RuleForStockReplenishment")." ".img_help('help', $langs->trans("VirtualDiffersFromPhysical"))."'.$langs->trans("Status").'
'; +print '
'; print ''; print "\n"; @@ -464,7 +464,7 @@ print '
".$langs->trans("Other")."
'; print '
'; if ($conf->global->MAIN_FEATURES_LEVEL >= 2) { - print ''; + print '
'; print ''; print ''."\n"; print ''."\n"; diff --git a/htdocs/admin/supplier_invoice.php b/htdocs/admin/supplier_invoice.php index 9cb387aedc9..ff9a621f706 100644 --- a/htdocs/admin/supplier_invoice.php +++ b/htdocs/admin/supplier_invoice.php @@ -40,14 +40,14 @@ $langs->loadLangs(array("admin", "other", "orders")); if (!$user->admin) accessforbidden(); -$type=GETPOST('type', 'alpha'); -$value=GETPOST('value', 'alpha'); -$action=GETPOST('action', 'alpha'); +$type = GETPOST('type', 'alpha'); +$value = GETPOST('value', 'alpha'); +$action = GETPOST('action', 'alpha'); $label = GETPOST('label', 'alpha'); $scandir = GETPOST('scan_dir', 'alpha'); -$specimenthirdparty=new Societe($db); +$specimenthirdparty = new Societe($db); $specimenthirdparty->initAsSpecimen(); @@ -57,17 +57,17 @@ $specimenthirdparty->initAsSpecimen(); if ($action == 'updateMask') { - $maskconstinvoice=GETPOST('maskconstinvoice', 'alpha'); - $maskconstcredit=GETPOST('maskconstcredit', 'alpha'); - $maskinvoice=GETPOST('maskinvoice', 'alpha'); - $maskcredit=GETPOST('maskcredit', 'alpha'); + $maskconstinvoice = GETPOST('maskconstinvoice', 'alpha'); + $maskconstcredit = GETPOST('maskconstcredit', 'alpha'); + $maskinvoice = GETPOST('maskinvoice', 'alpha'); + $maskcredit = GETPOST('maskcredit', 'alpha'); if ($maskconstinvoice) $res = dolibarr_set_const($db, $maskconstinvoice, $maskinvoice, 'chaine', 0, '', $conf->entity); if ($maskconstcredit) $res = dolibarr_set_const($db, $maskconstcredit, $maskcredit, 'chaine', 0, '', $conf->entity); - if (! $res > 0) $error++; + if (!$res > 0) $error++; - if (! $error) + if (!$error) { setEventMessages($langs->trans("SetupSaved"), null, 'mesgs'); } @@ -79,21 +79,21 @@ if ($action == 'updateMask') if ($action == 'specimen') // For invoices { - $modele=GETPOST('module', 'alpha'); + $modele = GETPOST('module', 'alpha'); $facture = new FactureFournisseur($db); $facture->initAsSpecimen(); - $facture->thirdparty=$specimenthirdparty; // Define who should has build the invoice (so the supplier) + $facture->thirdparty = $specimenthirdparty; // Define who should has build the invoice (so the supplier) // Search template files - $file=''; $classname=''; $filefound=0; - $dirmodels=array_merge(array('/'), (array) $conf->modules_parts['models']); - foreach($dirmodels as $reldir) + $file = ''; $classname = ''; $filefound = 0; + $dirmodels = array_merge(array('/'), (array) $conf->modules_parts['models']); + foreach ($dirmodels as $reldir) { - $file=dol_buildpath($reldir."core/modules/supplier_invoice/pdf/pdf_".$modele.".modules.php", 0); + $file = dol_buildpath($reldir."core/modules/supplier_invoice/pdf/pdf_".$modele.".modules.php", 0); if (file_exists($file)) { - $filefound=1; + $filefound = 1; $classname = "pdf_".$modele; break; } @@ -176,13 +176,13 @@ if ($action == 'addcat') if ($action == 'set_SUPPLIER_INVOICE_FREE_TEXT') { - $freetext = GETPOST('SUPPLIER_INVOICE_FREE_TEXT', 'none'); // No alpha here, we want exact string + $freetext = GETPOST('SUPPLIER_INVOICE_FREE_TEXT', 'none'); // No alpha here, we want exact string $res = dolibarr_set_const($db, "SUPPLIER_INVOICE_FREE_TEXT", $freetext, 'chaine', 0, '', $conf->entity); - if (! $res > 0) $error++; + if (!$res > 0) $error++; - if (! $error) + if (!$error) { setEventMessages($langs->trans("SetupSaved"), null, 'mesgs'); } @@ -197,13 +197,13 @@ if ($action == 'set_SUPPLIER_INVOICE_FREE_TEXT') * View */ -$dirmodels=array_merge(array('/'), (array) $conf->modules_parts['models']); +$dirmodels = array_merge(array('/'), (array) $conf->modules_parts['models']); llxHeader("", ""); -$form=new Form($db); +$form = new Form($db); -$linkback=''.$langs->trans("BackToModuleList").''; +$linkback = ''.$langs->trans("BackToModuleList").''; print load_fiche_titre($langs->trans("SuppliersSetup"), $linkback, 'title_setup'); print "
"; @@ -217,7 +217,7 @@ dol_fiche_head($head, 'invoice', $langs->trans("Suppliers"), -1, 'company'); print load_fiche_titre($langs->trans("SuppliersInvoiceNumberingModel"), '', ''); -print '
'.$langs->trans("Inventory").''.$langs->trans("Status").'
'; +print '
'; print ''; print ''; print ''; @@ -237,11 +237,11 @@ foreach ($dirmodels as $reldir) $handle = opendir($dir); if (is_resource($handle)) { - while (($file = readdir($handle))!==false) + while (($file = readdir($handle)) !== false) { - if (substr($file, 0, 24) == 'mod_facture_fournisseur_' && substr($file, dol_strlen($file)-3, 3) == 'php') + if (substr($file, 0, 24) == 'mod_facture_fournisseur_' && substr($file, dol_strlen($file) - 3, 3) == 'php') { - $file = substr($file, 0, dol_strlen($file)-4); + $file = substr($file, 0, dol_strlen($file) - 4); require_once $dir.$file.'.php'; @@ -250,7 +250,7 @@ foreach ($dirmodels as $reldir) if ($module->isEnabled()) { // Show modules according to features level - if ($module->version == 'development' && $conf->global->MAIN_FEATURES_LEVEL < 2) continue; + if ($module->version == 'development' && $conf->global->MAIN_FEATURES_LEVEL < 2) continue; if ($module->version == 'experimental' && $conf->global->MAIN_FEATURES_LEVEL < 1) continue; @@ -260,11 +260,11 @@ foreach ($dirmodels as $reldir) // Show example of numbering model print ''."\n"; @@ -279,21 +279,21 @@ foreach ($dirmodels as $reldir) } print ''; - $invoice=new FactureFournisseur($db); + $invoice = new FactureFournisseur($db); $invoice->initAsSpecimen(); // Info - $htmltooltip=''; - $htmltooltip.=''.$langs->trans("Version").': '.$module->getVersion().'
'; - $nextval=$module->getNextValue($mysoc, $invoice); + $htmltooltip = ''; + $htmltooltip .= ''.$langs->trans("Version").': '.$module->getVersion().'
'; + $nextval = $module->getNextValue($mysoc, $invoice); if ("$nextval" != $langs->trans("NotAvailable")) { // Keep " on nextval - $htmltooltip.=''.$langs->trans("NextValue").': '; + $htmltooltip .= ''.$langs->trans("NextValue").': '; if ($nextval) { - if (preg_match('/^Error/', $nextval) || $nextval=='NotConfigured') + if (preg_match('/^Error/', $nextval) || $nextval == 'NotConfigured') $nextval = $langs->trans($nextval); - $htmltooltip.=$nextval.'
'; + $htmltooltip .= $nextval.'
'; } else { - $htmltooltip.=$langs->trans($module->error).'
'; + $htmltooltip .= $langs->trans($module->error).'
'; } } @@ -325,15 +325,15 @@ print load_fiche_titre($langs->trans("BillsPDFModules"), '', ''); $def = array(); $sql = "SELECT nom"; -$sql.= " FROM ".MAIN_DB_PREFIX."document_model"; -$sql.= " WHERE type = 'invoice_supplier'"; -$sql.= " AND entity = ".$conf->entity; +$sql .= " FROM ".MAIN_DB_PREFIX."document_model"; +$sql .= " WHERE type = 'invoice_supplier'"; +$sql .= " AND entity = ".$conf->entity; -$resql=$db->query($sql); +$resql = $db->query($sql); if ($resql) { $i = 0; - $num_rows=$db->num_rows($resql); + $num_rows = $db->num_rows($resql); while ($i < $num_rows) { $array = $db->fetch_array($resql); @@ -346,7 +346,7 @@ else dol_print_error($db); } -print '
'.$langs->trans("Name").''.$langs->trans("Description").''; - $tmp=$module->getExample(); + $tmp = $module->getExample(); if (preg_match('/^Error/', $tmp)) { $langs->load("errors"); print '
'.$langs->trans($tmp).'
'; } - elseif ($tmp=='NotConfigured') print $langs->trans($tmp); + elseif ($tmp == 'NotConfigured') print $langs->trans($tmp); else print $tmp; print '
'."\n"; +print '
'."\n"; print ''."\n"; print ''."\n"; print ''."\n"; @@ -364,17 +364,17 @@ foreach ($dirmodels as $reldir) if (is_dir($dir)) { - $handle=opendir($dir); + $handle = opendir($dir); if (is_resource($handle)) { - while (($file = readdir($handle))!==false) + while (($file = readdir($handle)) !== false) { if (preg_match('/\.modules\.php$/i', $file) && preg_match('/^(pdf_|doc_)/', $file)) { - $name = substr($file, 4, dol_strlen($file) -16); - $classname = substr($file, 0, dol_strlen($file) -12); + $name = substr($file, 4, dol_strlen($file) - 16); + $classname = substr($file, 0, dol_strlen($file) - 12); require_once $dir.'/'.$file; $module = new $classname($db, new FactureFournisseur($db)); @@ -382,7 +382,7 @@ foreach ($dirmodels as $reldir) print "\n"; print "\n"; print "'; // Info - $htmltooltip = ''.$langs->trans("Name").': '.$module->name; - $htmltooltip.='
'.$langs->trans("Type").': '.($module->type?$module->type:$langs->trans("Unknown")); - $htmltooltip.='
'.$langs->trans("Width").'/'.$langs->trans("Height").': '.$module->page_largeur.'/'.$module->page_hauteur; - $htmltooltip.='

'.$langs->trans("FeaturesSupported").':'; - $htmltooltip.='
'.$langs->trans("Logo").': '.yn($module->option_logo, 1, 1); - $htmltooltip.='
'.$langs->trans("PaymentMode").': '.yn($module->option_modereg, 1, 1); - $htmltooltip.='
'.$langs->trans("PaymentConditions").': '.yn($module->option_condreg, 1, 1); + $htmltooltip = ''.$langs->trans("Name").': '.$module->name; + $htmltooltip .= '
'.$langs->trans("Type").': '.($module->type ? $module->type : $langs->trans("Unknown")); + $htmltooltip .= '
'.$langs->trans("Width").'/'.$langs->trans("Height").': '.$module->page_largeur.'/'.$module->page_hauteur; + $htmltooltip .= '

'.$langs->trans("FeaturesSupported").':'; + $htmltooltip .= '
'.$langs->trans("Logo").': '.yn($module->option_logo, 1, 1); + $htmltooltip .= '
'.$langs->trans("PaymentMode").': '.yn($module->option_modereg, 1, 1); + $htmltooltip .= '
'.$langs->trans("PaymentConditions").': '.yn($module->option_condreg, 1, 1); print ''; @@ -465,22 +465,22 @@ print ''; print ''; print load_fiche_titre($langs->trans("OtherOptions"), '', ''); -print '
'.$langs->trans("Name").''.$langs->trans("Description").'
"; - print (empty($module->name)?$name:$module->name); + print (empty($module->name) ? $name : $module->name); print "\n"; require_once $dir.$file; @@ -431,13 +431,13 @@ foreach ($dirmodels as $reldir) print ''; print $form->textwithpicto('', $htmltooltip, 1, 0); print '
'; +print '
'; print ''; print ''; print ''; print ''; print "\n"; -$substitutionarray=pdf_getSubstitutionArray($langs, null, null, 2); -$substitutionarray['__(AnyTranslationKey)__']=$langs->trans("Translation"); +$substitutionarray = pdf_getSubstitutionArray($langs, null, null, 2); +$substitutionarray['__(AnyTranslationKey)__'] = $langs->trans("Translation"); $htmltext = ''.$langs->trans("AvailableVariables").':
'; -foreach($substitutionarray as $key => $val) $htmltext.=$key.'
'; -$htmltext.='
'; +foreach ($substitutionarray as $key => $val) $htmltext .= $key.'
'; +$htmltext .= ''; print '
'.$langs->trans("Parameter").''.$langs->trans("Value").' 
'; print $form->textwithpicto($langs->trans("FreeLegalTextOnInvoices"), $langs->trans("AddCRIfTooLong").'

'.$htmltext, 1, 'help', '', 0, 2, 'freetexttooltip').'
'; -$variablename='SUPPLIER_INVOICE_FREE_TEXT'; +$variablename = 'SUPPLIER_INVOICE_FREE_TEXT'; if (empty($conf->global->PDF_ALLOW_HTML_FOR_FREE_TEXT)) { print ''; @@ -488,7 +488,7 @@ if (empty($conf->global->PDF_ALLOW_HTML_FOR_FREE_TEXT)) else { include_once DOL_DOCUMENT_ROOT.'/core/class/doleditor.class.php'; - $doleditor=new DolEditor($variablename, $conf->global->$variablename, '', 80, 'dolibarr_notes'); + $doleditor = new DolEditor($variablename, $conf->global->$variablename, '', 80, 'dolibarr_notes'); print $doleditor->Create(); } print '
'; @@ -505,7 +505,7 @@ print ''; */ print load_fiche_titre($langs->trans("Notifications"), '', ''); -print ''; +print '
'; print ''; print ''; print ''; diff --git a/htdocs/admin/supplier_order.php b/htdocs/admin/supplier_order.php index c2a7a5d4077..fa87a7f5bb7 100644 --- a/htdocs/admin/supplier_order.php +++ b/htdocs/admin/supplier_order.php @@ -40,13 +40,13 @@ $langs->loadLangs(array("admin", "other", "orders", "stocks")); if (!$user->admin) accessforbidden(); -$type=GETPOST('type', 'alpha'); -$value=GETPOST('value', 'alpha'); +$type = GETPOST('type', 'alpha'); +$value = GETPOST('value', 'alpha'); $label = GETPOST('label', 'alpha'); -$action=GETPOST('action', 'alpha'); +$action = GETPOST('action', 'alpha'); $scandir = GETPOST('scan_dir', 'alpha'); -$specimenthirdparty=new Societe($db); +$specimenthirdparty = new Societe($db); $specimenthirdparty->initAsSpecimen(); @@ -56,14 +56,14 @@ $specimenthirdparty->initAsSpecimen(); if ($action == 'updateMask') { - $maskconstorder=GETPOST('maskconstorder', 'alpha'); - $maskvalue=GETPOST('maskorder', 'alpha'); + $maskconstorder = GETPOST('maskconstorder', 'alpha'); + $maskvalue = GETPOST('maskorder', 'alpha'); if ($maskconstorder) $res = dolibarr_set_const($db, $maskconstorder, $maskvalue, 'chaine', 0, '', $conf->entity); - if (! $res > 0) $error++; + if (!$res > 0) $error++; - if (! $error) + if (!$error) { setEventMessages($langs->trans("SetupSaved"), null, 'mesgs'); } @@ -75,21 +75,21 @@ if ($action == 'updateMask') elseif ($action == 'specimen') // For orders { - $modele=GETPOST('module', 'alpha'); + $modele = GETPOST('module', 'alpha'); $commande = new CommandeFournisseur($db); $commande->initAsSpecimen(); - $commande->thirdparty=$specimenthirdparty; + $commande->thirdparty = $specimenthirdparty; // Search template files - $file=''; $classname=''; $filefound=0; - $dirmodels=array_merge(array('/'), (array) $conf->modules_parts['models']); - foreach($dirmodels as $reldir) + $file = ''; $classname = ''; $filefound = 0; + $dirmodels = array_merge(array('/'), (array) $conf->modules_parts['models']); + foreach ($dirmodels as $reldir) { - $file=dol_buildpath($reldir."core/modules/supplier_order/pdf/pdf_".$modele.".modules.php", 0); + $file = dol_buildpath($reldir."core/modules/supplier_order/pdf/pdf_".$modele.".modules.php", 0); if (file_exists($file)) { - $filefound=1; + $filefound = 1; $classname = "pdf_".$modele; break; } @@ -168,7 +168,7 @@ elseif ($action == 'addcat') elseif ($action == 'set_SUPPLIER_ORDER_OTHER') { - $freetext = GETPOST('SUPPLIER_ORDER_FREE_TEXT', 'none'); // No alpha here, we want exact string + $freetext = GETPOST('SUPPLIER_ORDER_FREE_TEXT', 'none'); // No alpha here, we want exact string $doubleapproval = GETPOST('SUPPLIER_ORDER_3_STEPS_TO_BE_APPROVED', 'alpha'); $doubleapproval = price2num($doubleapproval); @@ -177,14 +177,14 @@ elseif ($action == 'set_SUPPLIER_ORDER_OTHER') // TODO We add/delete permission here until permission can have a condition on a global var include_once DOL_DOCUMENT_ROOT.'/core/modules/modFournisseur.class.php'; - $newmodule=new modFournisseur($db); + $newmodule = new modFournisseur($db); if ($conf->global->SUPPLIER_ORDER_3_STEPS_TO_BE_APPROVED) { // clear default rights array - $newmodule->rights=array(); + $newmodule->rights = array(); // add new right - $r=0; + $r = 0; $newmodule->rights[$r][0] = 1190; $newmodule->rights[$r][1] = $langs->trans("Permission1190"); $newmodule->rights[$r][2] = 'w'; @@ -210,9 +210,9 @@ elseif ($action == 'set_BANK_ASK_PAYMENT_BANK_DURING_SUPPLIER_ORDER') { $res = dolibarr_set_const($db, "BANK_ASK_PAYMENT_BANK_DURING_SUPPLIER_ORDER", $value, 'chaine', 0, '', $conf->entity); - if (! $res > 0) $error++; + if (!$res > 0) $error++; - if (! $error) + if (!$error) { setEventMessages($langs->trans("SetupSaved"), null, 'mesgs'); } @@ -227,13 +227,13 @@ elseif ($action == 'set_BANK_ASK_PAYMENT_BANK_DURING_SUPPLIER_ORDER') * View */ -$form=new Form($db); +$form = new Form($db); -$dirmodels=array_merge(array('/'), (array) $conf->modules_parts['models']); +$dirmodels = array_merge(array('/'), (array) $conf->modules_parts['models']); llxHeader("", ""); -$linkback=''.$langs->trans("BackToModuleList").''; +$linkback = ''.$langs->trans("BackToModuleList").''; print load_fiche_titre($langs->trans("SuppliersSetup"), $linkback, 'title_setup'); print "
"; @@ -247,7 +247,7 @@ dol_fiche_head($head, 'order', $langs->trans("Suppliers"), -1, 'company'); print load_fiche_titre($langs->trans("OrdersNumberingModules"), '', ''); -print '
'.$langs->trans("Parameter").'
'; +print '
'; print ''; print ''; print ''; @@ -267,11 +267,11 @@ foreach ($dirmodels as $reldir) $handle = opendir($dir); if (is_resource($handle)) { - while (($file = readdir($handle))!==false) + while (($file = readdir($handle)) !== false) { - if (substr($file, 0, 25) == 'mod_commande_fournisseur_' && substr($file, dol_strlen($file)-3, 3) == 'php') + if (substr($file, 0, 25) == 'mod_commande_fournisseur_' && substr($file, dol_strlen($file) - 3, 3) == 'php') { - $file = substr($file, 0, dol_strlen($file)-4); + $file = substr($file, 0, dol_strlen($file) - 4); require_once $dir.$file.'.php'; @@ -280,7 +280,7 @@ foreach ($dirmodels as $reldir) if ($module->isEnabled()) { // Show modules according to features level - if ($module->version == 'development' && $conf->global->MAIN_FEATURES_LEVEL < 2) continue; + if ($module->version == 'development' && $conf->global->MAIN_FEATURES_LEVEL < 2) continue; if ($module->version == 'experimental' && $conf->global->MAIN_FEATURES_LEVEL < 1) continue; @@ -290,11 +290,11 @@ foreach ($dirmodels as $reldir) // Show example of numbering module print ''."\n"; @@ -309,21 +309,21 @@ foreach ($dirmodels as $reldir) } print ''; - $commande=new CommandeFournisseur($db); + $commande = new CommandeFournisseur($db); $commande->initAsSpecimen(); // Info - $htmltooltip=''; - $htmltooltip.=''.$langs->trans("Version").': '.$module->getVersion().'
'; - $nextval=$module->getNextValue($mysoc, $commande); + $htmltooltip = ''; + $htmltooltip .= ''.$langs->trans("Version").': '.$module->getVersion().'
'; + $nextval = $module->getNextValue($mysoc, $commande); if ("$nextval" != $langs->trans("NotAvailable")) { // Keep " on nextval - $htmltooltip.=''.$langs->trans("NextValue").': '; + $htmltooltip .= ''.$langs->trans("NextValue").': '; if ($nextval) { - if (preg_match('/^Error/', $nextval) || $nextval=='NotConfigured') + if (preg_match('/^Error/', $nextval) || $nextval == 'NotConfigured') $nextval = $langs->trans($nextval); - $htmltooltip.=$nextval.'
'; + $htmltooltip .= $nextval.'
'; } else { - $htmltooltip.=$langs->trans($module->error).'
'; + $htmltooltip .= $langs->trans($module->error).'
'; } } @@ -353,15 +353,15 @@ print load_fiche_titre($langs->trans("OrdersModelModule"), '', ''); $def = array(); $sql = "SELECT nom"; -$sql.= " FROM ".MAIN_DB_PREFIX."document_model"; -$sql.= " WHERE type = 'order_supplier'"; -$sql.= " AND entity = ".$conf->entity; +$sql .= " FROM ".MAIN_DB_PREFIX."document_model"; +$sql .= " WHERE type = 'order_supplier'"; +$sql .= " AND entity = ".$conf->entity; -$resql=$db->query($sql); +$resql = $db->query($sql); if ($resql) { $i = 0; - $num_rows=$db->num_rows($resql); + $num_rows = $db->num_rows($resql); while ($i < $num_rows) { $array = $db->fetch_array($resql); @@ -374,7 +374,7 @@ else dol_print_error($db); } -print '
'.$langs->trans("Name").''.$langs->trans("Description").''; - $tmp=$module->getExample(); + $tmp = $module->getExample(); if (preg_match('/^Error/', $tmp)) { $langs->load("errors"); print '
'.$langs->trans($tmp).'
'; } - elseif ($tmp=='NotConfigured') print $langs->trans($tmp); + elseif ($tmp == 'NotConfigured') print $langs->trans($tmp); else print $tmp; print '
'."\n"; +print '
'."\n"; print ''."\n"; print ''."\n"; print ''."\n"; @@ -392,15 +392,15 @@ foreach ($dirmodels as $reldir) if (is_dir($dir)) { - $handle=opendir($dir); + $handle = opendir($dir); if (is_resource($handle)) { - while (($file = readdir($handle))!==false) + while (($file = readdir($handle)) !== false) { if (preg_match('/\.modules\.php$/i', $file) && preg_match('/^(pdf_|doc_)/', $file)) { - $name = substr($file, 4, dol_strlen($file) -16); - $classname = substr($file, 0, dol_strlen($file) -12); + $name = substr($file, 4, dol_strlen($file) - 16); + $classname = substr($file, 0, dol_strlen($file) - 12); require_once $dir.'/'.$file; $module = new $classname($db, new CommandeFournisseur($db)); @@ -408,7 +408,7 @@ foreach ($dirmodels as $reldir) print "\n"; print "\n"; print "'; // Info - $htmltooltip = ''.$langs->trans("Name").': '.$module->name; - $htmltooltip.='
'.$langs->trans("Type").': '.($module->type?$module->type:$langs->trans("Unknown")); - $htmltooltip.='
'.$langs->trans("Width").'/'.$langs->trans("Height").': '.$module->page_largeur.'/'.$module->page_hauteur; - $htmltooltip.='

'.$langs->trans("FeaturesSupported").':'; - $htmltooltip.='
'.$langs->trans("Logo").': '.yn($module->option_logo, 1, 1); - $htmltooltip.='
'.$langs->trans("PaymentMode").': '.yn($module->option_modereg, 1, 1); - $htmltooltip.='
'.$langs->trans("PaymentConditions").': '.yn($module->option_condreg, 1, 1); + $htmltooltip = ''.$langs->trans("Name").': '.$module->name; + $htmltooltip .= '
'.$langs->trans("Type").': '.($module->type ? $module->type : $langs->trans("Unknown")); + $htmltooltip .= '
'.$langs->trans("Width").'/'.$langs->trans("Height").': '.$module->page_largeur.'/'.$module->page_hauteur; + $htmltooltip .= '

'.$langs->trans("FeaturesSupported").':'; + $htmltooltip .= '
'.$langs->trans("Logo").': '.yn($module->option_logo, 1, 1); + $htmltooltip .= '
'.$langs->trans("PaymentMode").': '.yn($module->option_modereg, 1, 1); + $htmltooltip .= '
'.$langs->trans("PaymentConditions").': '.yn($module->option_condreg, 1, 1); print ''; @@ -487,7 +487,7 @@ print ''; print ''; print load_fiche_titre($langs->trans("OtherOptions"), '', ''); -print '
'.$langs->trans("Name").''.$langs->trans("Description").'
"; - print (empty($module->name)?$name:$module->name); + print (empty($module->name) ? $name : $module->name); print "\n"; require_once $dir.$file; @@ -453,13 +453,13 @@ foreach ($dirmodels as $reldir) print ''; print $form->textwithpicto('', $htmltooltip, 1, 0); print '
'; +print '
'; print ''; print ''; print ''; @@ -536,15 +536,15 @@ else } */ -$substitutionarray=pdf_getSubstitutionArray($langs, null, null, 2); -$substitutionarray['__(AnyTranslationKey)__']=$langs->trans("Translation"); +$substitutionarray = pdf_getSubstitutionArray($langs, null, null, 2); +$substitutionarray['__(AnyTranslationKey)__'] = $langs->trans("Translation"); $htmltext = ''.$langs->trans("AvailableVariables").':
'; -foreach($substitutionarray as $key => $val) $htmltext.=$key.'
'; -$htmltext.='
'; +foreach ($substitutionarray as $key => $val) $htmltext .= $key.'
'; +$htmltext .= ''; print '
'.$langs->trans("Parameter").''.$langs->trans("Value").'
'; print $form->textwithpicto($langs->trans("FreeLegalTextOnOrders"), $langs->trans("AddCRIfTooLong").'

'.$htmltext, 1, 'help', '', 0, 2, 'freetexttooltip').'
'; -$variablename='SUPPLIER_ORDER_FREE_TEXT'; +$variablename = 'SUPPLIER_ORDER_FREE_TEXT'; if (empty($conf->global->PDF_ALLOW_HTML_FOR_FREE_TEXT)) { print ''; @@ -552,7 +552,7 @@ if (empty($conf->global->PDF_ALLOW_HTML_FOR_FREE_TEXT)) else { include_once DOL_DOCUMENT_ROOT.'/core/class/doleditor.class.php'; - $doleditor=new DolEditor($variablename, $conf->global->$variablename, '', 80, 'dolibarr_notes'); + $doleditor = new DolEditor($variablename, $conf->global->$variablename, '', 80, 'dolibarr_notes'); print $doleditor->Create(); } print '
'; @@ -590,7 +590,7 @@ print ''; */ print load_fiche_titre($langs->trans("Notifications"), '', ''); -print ''; +print '
'; print ''; print ''; print ''; diff --git a/htdocs/admin/supplier_payment.php b/htdocs/admin/supplier_payment.php index 8da430a9fa1..e184e98a4b1 100644 --- a/htdocs/admin/supplier_payment.php +++ b/htdocs/admin/supplier_payment.php @@ -30,13 +30,13 @@ require_once DOL_DOCUMENT_ROOT.'/fourn/class/paiementfourn.class.php'; // Load translation files required by the page $langs->loadLangs(array("admin", "errors", "other", "bills", "orders")); -if (! $user->admin) accessforbidden(); +if (!$user->admin) accessforbidden(); $action = GETPOST('action', 'alpha'); $value = GETPOST('value', 'alpha'); $label = GETPOST('label', 'alpha'); $scandir = GETPOST('scan_dir', 'alpha'); -$type='supplier_payment'; +$type = 'supplier_payment'; /* @@ -47,13 +47,13 @@ include DOL_DOCUMENT_ROOT.'/core/actions_setmoduleoptions.inc.php'; if ($action == 'updateMask') { - $maskconstsupplierpayment=GETPOST('maskconstsupplierpayment', 'alpha'); - $masksupplierpayment=GETPOST('masksupplierpayment', 'alpha'); + $maskconstsupplierpayment = GETPOST('maskconstsupplierpayment', 'alpha'); + $masksupplierpayment = GETPOST('masksupplierpayment', 'alpha'); if ($maskconstsupplierpayment) $res = dolibarr_set_const($db, $maskconstsupplierpayment, $masksupplierpayment, 'chaine', 0, '', $conf->entity); - if (! $res > 0) $error++; + if (!$res > 0) $error++; - if (! $error) + if (!$error) { setEventMessages($langs->trans("SetupSaved"), null, 'mesgs'); } @@ -101,20 +101,20 @@ elseif ($action == 'setdoc') elseif ($action == 'specimen') { - $modele=GETPOST('module', 'alpha'); + $modele = GETPOST('module', 'alpha'); $paiementFourn = new PaiementFourn($db); $paiementFourn->initAsSpecimen(); // Search template files - $file=''; $classname=''; $filefound=0; - $dirmodels=array_merge(array('/'), (array) $conf->modules_parts['models']); - foreach($dirmodels as $reldir) + $file = ''; $classname = ''; $filefound = 0; + $dirmodels = array_merge(array('/'), (array) $conf->modules_parts['models']); + foreach ($dirmodels as $reldir) { - $file=dol_buildpath($reldir."core/modules/supplier_payment/doc/pdf_".$modele.".modules.php", 0); + $file = dol_buildpath($reldir."core/modules/supplier_payment/doc/pdf_".$modele.".modules.php", 0); if (file_exists($file)) { - $filefound=1; + $filefound = 1; $classname = "pdf_".$modele; break; } @@ -148,14 +148,14 @@ elseif ($action == 'specimen') * View */ -$dirmodels=array_merge(array('/'), (array) $conf->modules_parts['models']); +$dirmodels = array_merge(array('/'), (array) $conf->modules_parts['models']); llxHeader("", $langs->trans("SupplierPaymentSetup"), 'EN:Supplier_Payment_Configuration|FR:Configuration_module_paiement_fournisseur'); -$form=new Form($db); +$form = new Form($db); -$linkback=''.$langs->trans("BackToModuleList").''; +$linkback = ''.$langs->trans("BackToModuleList").''; print load_fiche_titre($langs->trans("SupplierPaymentSetup"), $linkback, 'title_setup'); print "
"; @@ -174,14 +174,14 @@ print load_fiche_titre($langs->trans("PaymentsNumberingModule"), '', ''); // Load array def with activated templates $def = array(); $sql = "SELECT nom"; -$sql.= " FROM ".MAIN_DB_PREFIX."document_model"; -$sql.= " WHERE type = '".$type."'"; -$sql.= " AND entity = ".$conf->entity; -$resql=$db->query($sql); +$sql .= " FROM ".MAIN_DB_PREFIX."document_model"; +$sql .= " WHERE type = '".$type."'"; +$sql .= " AND entity = ".$conf->entity; +$resql = $db->query($sql); if ($resql) { $i = 0; - $num_rows=$db->num_rows($resql); + $num_rows = $db->num_rows($resql); while ($i < $num_rows) { $array = $db->fetch_array($resql); @@ -194,7 +194,7 @@ else dol_print_error($db); } -print '
'.$langs->trans("Parameter").'
'; +print '
'; print ''; print ''; print ''; @@ -213,24 +213,24 @@ foreach ($dirmodels as $reldir) $handle = opendir($dir); if (is_resource($handle)) { - while (($file = readdir($handle))!==false) + while (($file = readdir($handle)) !== false) { - if (! is_dir($dir.$file) || (substr($file, 0, 1) <> '.' && substr($file, 0, 3) <> 'CVS')) + if (!is_dir($dir.$file) || (substr($file, 0, 1) <> '.' && substr($file, 0, 3) <> 'CVS')) { $filebis = $file; $classname = preg_replace('/\.php$/', '', $file); // For compatibility - if (! is_file($dir.$filebis)) + if (!is_file($dir.$filebis)) { $filebis = $file."/".$file.".modules.php"; $classname = "mod_supplier_payment_".$file; } // Check if there is a filter on country preg_match('/\-(.*)_(.*)$/', $classname, $reg); - if (! empty($reg[2]) && $reg[2] != strtoupper($mysoc->country_code)) continue; + if (!empty($reg[2]) && $reg[2] != strtoupper($mysoc->country_code)) continue; $classname = preg_replace('/\-.*$/', '', $classname); - if (! class_exists($classname) && is_readable($dir.$filebis) && (preg_match('/mod_/', $filebis) || preg_match('/mod_/', $classname)) && substr($filebis, dol_strlen($filebis)-3, 3) == 'php') + if (!class_exists($classname) && is_readable($dir.$filebis) && (preg_match('/mod_/', $filebis) || preg_match('/mod_/', $classname)) && substr($filebis, dol_strlen($filebis) - 3, 3) == 'php') { // Charging the numbering class require_once $dir.$filebis; @@ -238,7 +238,7 @@ foreach ($dirmodels as $reldir) $module = new $classname($db); // Show modules according to features level - if ($module->version == 'development' && $conf->global->MAIN_FEATURES_LEVEL < 2) continue; + if ($module->version == 'development' && $conf->global->MAIN_FEATURES_LEVEL < 2) continue; if ($module->version == 'experimental' && $conf->global->MAIN_FEATURES_LEVEL < 1) continue; if ($module->isEnabled()) @@ -253,9 +253,9 @@ foreach ($dirmodels as $reldir) // Show example of numbering module print ''."\n"; @@ -271,21 +271,21 @@ foreach ($dirmodels as $reldir) } print ''; - $payment=new PaiementFourn($db); + $payment = new PaiementFourn($db); $payment->initAsSpecimen(); // Example - $htmltooltip=''; - $htmltooltip.=''.$langs->trans("Version").': '.$module->getVersion().'
'; - $nextval=$module->getNextValue($mysoc, $payment); + $htmltooltip = ''; + $htmltooltip .= ''.$langs->trans("Version").': '.$module->getVersion().'
'; + $nextval = $module->getNextValue($mysoc, $payment); if ("$nextval" != $langs->trans("NotAvailable")) { // Keep " on nextval - $htmltooltip.=$langs->trans("NextValue").': '; + $htmltooltip .= $langs->trans("NextValue").': '; if ($nextval) { - if (preg_match('/^Error/', $nextval) || $nextval=='NotConfigured') + if (preg_match('/^Error/', $nextval) || $nextval == 'NotConfigured') $nextval = $langs->trans($nextval); - $htmltooltip.=$nextval.'
'; + $htmltooltip .= $nextval.'
'; } else { - $htmltooltip.=$langs->trans($module->error).'
'; + $htmltooltip .= $langs->trans($module->error).'
'; } } @@ -294,7 +294,7 @@ foreach ($dirmodels as $reldir) if ($conf->global->PAYMENT_ADDON.'.php' == $file) // If module is the one used, we show existing errors { - if (! empty($module->error)) dol_htmloutput_mesg($module->error, '', 'error', 1); + if (!empty($module->error)) dol_htmloutput_mesg($module->error, '', 'error', 1); } print ''; @@ -318,7 +318,7 @@ print '
'.$langs->trans("Name").''.$langs->trans("Description").''; - $tmp=$module->getExample(); + $tmp = $module->getExample(); if (preg_match('/^Error/', $tmp)) print '
'.$langs->trans($tmp).'
'; - elseif ($tmp=='NotConfigured') print $langs->trans($tmp); + elseif ($tmp == 'NotConfigured') print $langs->trans($tmp); else print $tmp; print '
'; print '
'; print load_fiche_titre($langs->trans("PaymentsPDFModules"), '', ''); -print ''."\n"; +print '
'."\n"; print ''."\n"; print ''."\n"; print ''."\n"; @@ -336,24 +336,24 @@ foreach ($dirmodels as $reldir) if (is_dir($dir)) { - $handle=opendir($dir); + $handle = opendir($dir); if (is_resource($handle)) { - while (($file = readdir($handle))!==false) + while (($file = readdir($handle)) !== false) { if (preg_match('/\.modules\.php$/i', $file) && preg_match('/^(pdf_|doc_)/', $file)) { - $name = substr($file, 4, dol_strlen($file) -16); - $classname = substr($file, 0, dol_strlen($file) -12); + $name = substr($file, 4, dol_strlen($file) - 16); + $classname = substr($file, 0, dol_strlen($file) - 12); require_once $dir.'/'.$file; $module = new $classname($db, new PaiementFourn($db)); print "\n"; print "\n"; print "'; // Info - $htmltooltip = ''.$langs->trans("Name").': '.$module->name; - $htmltooltip.='
'.$langs->trans("Type").': '.($module->type?$module->type:$langs->trans("Unknown")); - $htmltooltip.='
'.$langs->trans("Width").'/'.$langs->trans("Height").': '.$module->page_largeur.'/'.$module->page_hauteur; - $htmltooltip.='

'.$langs->trans("FeaturesSupported").':'; - $htmltooltip.='
'.$langs->trans("Logo").': '.yn($module->option_logo, 1, 1); + $htmltooltip = ''.$langs->trans("Name").': '.$module->name; + $htmltooltip .= '
'.$langs->trans("Type").': '.($module->type ? $module->type : $langs->trans("Unknown")); + $htmltooltip .= '
'.$langs->trans("Width").'/'.$langs->trans("Height").': '.$module->page_largeur.'/'.$module->page_hauteur; + $htmltooltip .= '

'.$langs->trans("FeaturesSupported").':'; + $htmltooltip .= '
'.$langs->trans("Logo").': '.yn($module->option_logo, 1, 1); print ''; diff --git a/htdocs/admin/supplier_proposal.php b/htdocs/admin/supplier_proposal.php index 30a85f2af3b..03f144ecd38 100644 --- a/htdocs/admin/supplier_proposal.php +++ b/htdocs/admin/supplier_proposal.php @@ -32,15 +32,15 @@ require_once DOL_DOCUMENT_ROOT.'/core/lib/supplier_proposal.lib.php'; // Load translation files required by the page $langs->loadLangs(array("admin", "errors", "other", "supplier_proposal")); -if (! $user->admin) accessforbidden(); +if (!$user->admin) accessforbidden(); $action = GETPOST('action', 'alpha'); $value = GETPOST('value', 'alpha'); $label = GETPOST('label', 'alpha'); $scandir = GETPOST('scan_dir', 'alpha'); -$type='supplier_proposal'; +$type = 'supplier_proposal'; -$error=0; +$error = 0; /* @@ -51,13 +51,13 @@ include DOL_DOCUMENT_ROOT.'/core/actions_setmoduleoptions.inc.php'; if ($action == 'updateMask') { - $maskconstsupplier_proposal=GETPOST('maskconstsupplier_proposal', 'alpha'); - $masksupplier_proposal=GETPOST('masksupplier_proposal', 'alpha'); + $maskconstsupplier_proposal = GETPOST('maskconstsupplier_proposal', 'alpha'); + $masksupplier_proposal = GETPOST('masksupplier_proposal', 'alpha'); if ($maskconstsupplier_proposal) $res = dolibarr_set_const($db, $maskconstsupplier_proposal, $masksupplier_proposal, 'chaine', 0, '', $conf->entity); - if (! $res > 0) $error++; + if (!$res > 0) $error++; - if (! $error) + if (!$error) { setEventMessages($langs->trans("SetupSaved"), null, 'mesgs'); } @@ -69,20 +69,20 @@ if ($action == 'updateMask') if ($action == 'specimen') { - $modele=GETPOST('module', 'alpha'); + $modele = GETPOST('module', 'alpha'); $supplier_proposal = new SupplierProposal($db); $supplier_proposal->initAsSpecimen(); // Search template files - $file=''; $classname=''; $filefound=0; - $dirmodels=array_merge(array('/'), (array) $conf->modules_parts['models']); - foreach($dirmodels as $reldir) + $file = ''; $classname = ''; $filefound = 0; + $dirmodels = array_merge(array('/'), (array) $conf->modules_parts['models']); + foreach ($dirmodels as $reldir) { - $file=dol_buildpath($reldir."core/modules/supplier_proposal/doc/pdf_".$modele.".modules.php"); + $file = dol_buildpath($reldir."core/modules/supplier_proposal/doc/pdf_".$modele.".modules.php"); if (file_exists($file)) { - $filefound=1; + $filefound = 1; $classname = "pdf_".$modele; break; } @@ -117,9 +117,9 @@ if ($action == 'set_SUPPLIER_PROPOSAL_DRAFT_WATERMARK') $draft = GETPOST('SUPPLIER_PROPOSAL_DRAFT_WATERMARK', 'alpha'); $res = dolibarr_set_const($db, "SUPPLIER_PROPOSAL_DRAFT_WATERMARK", trim($draft), 'chaine', 0, '', $conf->entity); - if (! $res > 0) $error++; + if (!$res > 0) $error++; - if (! $error) + if (!$error) { setEventMessages($langs->trans("SetupSaved"), null, 'mesgs'); } @@ -131,13 +131,13 @@ if ($action == 'set_SUPPLIER_PROPOSAL_DRAFT_WATERMARK') if ($action == 'set_SUPPLIER_PROPOSAL_FREE_TEXT') { - $freetext = GETPOST('SUPPLIER_PROPOSAL_FREE_TEXT', 'none'); // No alpha here, we want exact string + $freetext = GETPOST('SUPPLIER_PROPOSAL_FREE_TEXT', 'none'); // No alpha here, we want exact string $res = dolibarr_set_const($db, "SUPPLIER_PROPOSAL_FREE_TEXT", $freetext, 'chaine', 0, '', $conf->entity); - if (! $res > 0) $error++; + if (!$res > 0) $error++; - if (! $error) + if (!$error) { setEventMessages($langs->trans("SetupSaved"), null, 'mesgs'); } @@ -151,9 +151,9 @@ if ($action == 'set_BANK_ASK_PAYMENT_BANK_DURING_SUPPLIER_PROPOSAL') { $res = dolibarr_set_const($db, "BANK_ASK_PAYMENT_BANK_DURING_SUPPLIER_PROPOSAL", $value, 'chaine', 0, '', $conf->entity); - if (! $res > 0) $error++; + if (!$res > 0) $error++; - if (! $error) + if (!$error) { setEventMessages($langs->trans("SetupSaved"), null, 'mesgs'); } @@ -206,16 +206,16 @@ elseif ($action == 'setmod') * Affiche page */ -$dirmodels=array_merge(array('/'), (array) $conf->modules_parts['models']); +$dirmodels = array_merge(array('/'), (array) $conf->modules_parts['models']); llxHeader('', $langs->trans("SupplierProposalSetup")); -$form=new Form($db); +$form = new Form($db); //if ($mesg) print $mesg; -$linkback=''.$langs->trans("BackToModuleList").''; +$linkback = ''.$langs->trans("BackToModuleList").''; print load_fiche_titre($langs->trans("SupplierProposalSetup"), $linkback, 'title_setup'); $head = supplier_proposal_admin_prepare_head(); @@ -227,7 +227,7 @@ dol_fiche_head($head, 'general', $langs->trans("CommRequests"), -1, 'supplier_pr */ print load_fiche_titre($langs->trans("SupplierProposalNumberingModules"), '', ''); -print '
'.$langs->trans("Name").''.$langs->trans("Description").'
"; - print (empty($module->name)?$name:$module->name); + print (empty($module->name) ? $name : $module->name); print "\n"; require_once $dir.$file; @@ -402,11 +402,11 @@ foreach ($dirmodels as $reldir) print ''; print $form->textwithpicto('', $htmltooltip, 1, 0); print '
'; +print '
'; print ''; print '\n"; print '\n"; @@ -246,18 +246,18 @@ foreach ($dirmodels as $reldir) $handle = opendir($dir); if (is_resource($handle)) { - while (($file = readdir($handle))!==false) + while (($file = readdir($handle)) !== false) { - if (substr($file, 0, 22) == 'mod_supplier_proposal_' && substr($file, dol_strlen($file)-3, 3) == 'php') + if (substr($file, 0, 22) == 'mod_supplier_proposal_' && substr($file, dol_strlen($file) - 3, 3) == 'php') { - $file = substr($file, 0, dol_strlen($file)-4); + $file = substr($file, 0, dol_strlen($file) - 4); require_once $dir.$file.'.php'; $module = new $file; // Show modules according to features level - if ($module->version == 'development' && $conf->global->MAIN_FEATURES_LEVEL < 2) continue; + if ($module->version == 'development' && $conf->global->MAIN_FEATURES_LEVEL < 2) continue; if ($module->version == 'experimental' && $conf->global->MAIN_FEATURES_LEVEL < 1) continue; if ($module->isEnabled()) @@ -268,9 +268,9 @@ foreach ($dirmodels as $reldir) // Show example of numbering module print ''."\n"; @@ -287,21 +287,21 @@ foreach ($dirmodels as $reldir) } print ''; - $supplier_proposal=new SupplierProposal($db); + $supplier_proposal = new SupplierProposal($db); $supplier_proposal->initAsSpecimen(); // Info - $htmltooltip=''; - $htmltooltip.=''.$langs->trans("Version").': '.$module->getVersion().'
'; - $nextval=$module->getNextValue($mysoc, $supplier_proposal); + $htmltooltip = ''; + $htmltooltip .= ''.$langs->trans("Version").': '.$module->getVersion().'
'; + $nextval = $module->getNextValue($mysoc, $supplier_proposal); if ("$nextval" != $langs->trans("NotAvailable")) { // Keep " on nextval - $htmltooltip.=''.$langs->trans("NextValue").': '; + $htmltooltip .= ''.$langs->trans("NextValue").': '; if ($nextval) { - if (preg_match('/^Error/', $nextval) || $nextval=='NotConfigured') + if (preg_match('/^Error/', $nextval) || $nextval == 'NotConfigured') $nextval = $langs->trans($nextval); - $htmltooltip.=$nextval.'
'; + $htmltooltip .= $nextval.'
'; } else { - $htmltooltip.=$langs->trans($module->error).'
'; + $htmltooltip .= $langs->trans($module->error).'
'; } } @@ -329,14 +329,14 @@ print load_fiche_titre($langs->trans("SupplierProposalPDFModules"), '', ''); // Load array def with activated templates $def = array(); $sql = "SELECT nom"; -$sql.= " FROM ".MAIN_DB_PREFIX."document_model"; -$sql.= " WHERE type = '".$type."'"; -$sql.= " AND entity = ".$conf->entity; -$resql=$db->query($sql); +$sql .= " FROM ".MAIN_DB_PREFIX."document_model"; +$sql .= " WHERE type = '".$type."'"; +$sql .= " AND entity = ".$conf->entity; +$resql = $db->query($sql); if ($resql) { $i = 0; - $num_rows=$db->num_rows($resql); + $num_rows = $db->num_rows($resql); while ($i < $num_rows) { $array = $db->fetch_array($resql); @@ -364,42 +364,42 @@ clearstatcache(); foreach ($dirmodels as $reldir) { - foreach (array('','/doc') as $valdir) + foreach (array('', '/doc') as $valdir) { $dir = dol_buildpath($reldir."core/modules/supplier_proposal".$valdir); if (is_dir($dir)) { - $handle=opendir($dir); + $handle = opendir($dir); if (is_resource($handle)) { - while (($file = readdir($handle))!==false) + while (($file = readdir($handle)) !== false) { - $filelist[]=$file; + $filelist[] = $file; } closedir($handle); arsort($filelist); - foreach($filelist as $file) + foreach ($filelist as $file) { if (preg_match('/\.modules\.php$/i', $file) && preg_match('/^(pdf_|doc_)/', $file)) { if (file_exists($dir.'/'.$file)) { - $name = substr($file, 4, dol_strlen($file) -16); - $classname = substr($file, 0, dol_strlen($file) -12); + $name = substr($file, 4, dol_strlen($file) - 16); + $classname = substr($file, 0, dol_strlen($file) - 12); require_once $dir.'/'.$file; $module = new $classname($db); - $modulequalified=1; - if ($module->version == 'development' && $conf->global->MAIN_FEATURES_LEVEL < 2) $modulequalified=0; - if ($module->version == 'experimental' && $conf->global->MAIN_FEATURES_LEVEL < 1) $modulequalified=0; + $modulequalified = 1; + if ($module->version == 'development' && $conf->global->MAIN_FEATURES_LEVEL < 2) $modulequalified = 0; + if ($module->version == 'experimental' && $conf->global->MAIN_FEATURES_LEVEL < 1) $modulequalified = 0; if ($modulequalified) { print '\n"; print "\n"; print ""; -$substitutionarray=pdf_getSubstitutionArray($langs, null, null, 2); -$substitutionarray['__(AnyTranslationKey)__']=$langs->trans("Translation"); +$substitutionarray = pdf_getSubstitutionArray($langs, null, null, 2); +$substitutionarray['__(AnyTranslationKey)__'] = $langs->trans("Translation"); $htmltext = ''.$langs->trans("AvailableVariables").':
'; -foreach($substitutionarray as $key => $val) $htmltext.=$key.'
'; -$htmltext.='
'; +foreach ($substitutionarray as $key => $val) $htmltext .= $key.'
'; +$htmltext .= ''; print ''; print ''; print ''; print '
'.$langs->trans("Name")."'.$langs->trans("Description")."'; - $tmp=$module->getExample(); + $tmp = $module->getExample(); if (preg_match('/^Error/', $tmp)) print '
'.$langs->trans($tmp).'
'; - elseif ($tmp=='NotConfigured') print $langs->trans($tmp); + elseif ($tmp == 'NotConfigured') print $langs->trans($tmp); else print $tmp; print '
'; - print (empty($module->name)?$name:$module->name); + print (empty($module->name) ? $name : $module->name); print "\n"; if (method_exists($module, 'info')) print $module->info($langs); else print $module->description; @@ -493,18 +493,18 @@ print ''.$langs->trans("Value")." 
'; print $form->textwithpicto($langs->trans("FreeLegalTextOnSupplierProposal"), $langs->trans("AddCRIfTooLong").'

'.$htmltext, 1, 'help', '', 0, 2, 'freetexttooltip').'
'; -$variablename='SUPPLIER_PROPOSAL_FREE_TEXT'; +$variablename = 'SUPPLIER_PROPOSAL_FREE_TEXT'; if (empty($conf->global->PDF_ALLOW_HTML_FOR_FREE_TEXT)) { print ''; @@ -512,7 +512,7 @@ if (empty($conf->global->PDF_ALLOW_HTML_FOR_FREE_TEXT)) else { include_once DOL_DOCUMENT_ROOT.'/core/class/doleditor.class.php'; - $doleditor=new DolEditor($variablename, $conf->global->$variablename, '', 80, 'dolibarr_notes'); + $doleditor = new DolEditor($variablename, $conf->global->$variablename, '', 80, 'dolibarr_notes'); print $doleditor->Create(); } print '
'; @@ -537,7 +537,7 @@ if ($conf->banque->enabled) { print '
'; print $langs->trans("BANK_ASK_PAYMENT_BANK_DURING_SUPPLIER_PROPOSAL").' '; - if (! empty($conf->use_javascript_ajax)) + if (!empty($conf->use_javascript_ajax)) { print ajax_constantonoff('BANK_ASK_PAYMENT_BANK_DURING_SUPPLIER_PROPOSAL'); } diff --git a/htdocs/admin/syslog.php b/htdocs/admin/syslog.php index bd93d7a9fc5..96dd3d456b7 100644 --- a/htdocs/admin/syslog.php +++ b/htdocs/admin/syslog.php @@ -198,7 +198,7 @@ print load_fiche_titre($langs->trans("SyslogOutput")); print ''; print ''; print ''; -print ''; +print '
'; print ''; print ''; print ''; @@ -271,7 +271,7 @@ print load_fiche_titre($langs->trans("SyslogLevel")); print ''; print ''; print ''; -print '
'.$langs->trans("Type").''.$langs->trans("Value").'
'; +print '
'; print ''; print ''; print ''; diff --git a/htdocs/admin/system/browser.php b/htdocs/admin/system/browser.php index ef5ec419c8f..5035c6c4a7d 100644 --- a/htdocs/admin/system/browser.php +++ b/htdocs/admin/system/browser.php @@ -47,7 +47,7 @@ $tmp=getBrowserInfo($_SERVER["HTTP_USER_AGENT"]); // Browser print '
'; -print '
'.$langs->trans("Parameter").''.$langs->trans("Value").'
'; +print '
'; print ''."\n"; print ''."\n"; print ''."\n"; diff --git a/htdocs/admin/system/constall.php b/htdocs/admin/system/constall.php index 4e203a770f7..194c871958d 100644 --- a/htdocs/admin/system/constall.php +++ b/htdocs/admin/system/constall.php @@ -140,7 +140,7 @@ $configfilelib=array( 'Strict mode is on/off' ); -print '
'.$langs->trans("Parameter").''.$langs->trans("Value").'
'.$langs->trans("UserAgent").''.$_SERVER['HTTP_USER_AGENT'].'
'.$langs->trans("BrowserName").''.$tmp['browsername'].'
'; +print '
'; print ''; print ''; print ''; diff --git a/htdocs/admin/system/database-tables.php b/htdocs/admin/system/database-tables.php index 01fc5ff5fc1..323d9b4c115 100644 --- a/htdocs/admin/system/database-tables.php +++ b/htdocs/admin/system/database-tables.php @@ -28,20 +28,20 @@ require '../../main.inc.php'; $langs->load("admin"); -if (! $user->admin) +if (!$user->admin) accessforbidden(); -$action=GETPOST('action', 'alpha'); +$action = GETPOST('action', 'alpha'); if ($action == 'convert') { - $sql="ALTER TABLE ".$db->escape(GETPOST("table", "aZ09"))." ENGINE=INNODB"; + $sql = "ALTER TABLE ".$db->escape(GETPOST("table", "aZ09"))." ENGINE=INNODB"; $db->query($sql); } if ($action == 'convertutf8') { - $sql="ALTER TABLE ".$db->escape(GETPOST("table", "aZ09"))." CHARACTER SET utf8 COLLATE utf8_unicode_ci"; + $sql = "ALTER TABLE ".$db->escape(GETPOST("table", "aZ09"))." CHARACTER SET utf8 COLLATE utf8_unicode_ci"; $db->query($sql); } @@ -56,16 +56,16 @@ print load_fiche_titre($langs->trans("Tables")." ".ucfirst($conf->db->type), '', // Define request to get table description -$base=0; +$base = 0; if (preg_match('/mysql/i', $conf->db->type)) { $sql = "SHOW TABLE STATUS"; - $base=1; + $base = 1; } elseif ($conf->db->type == 'pgsql') { $sql = "SELECT conname, contype FROM pg_constraint;"; - $base=2; + $base = 2; } elseif ($conf->db->type == 'mssql') { @@ -79,7 +79,7 @@ elseif ($conf->db->type == 'sqlite' || $conf->db->type == 'sqlite3') } -if (! $base) +if (!$base) { print $langs->trans("FeatureNotAvailableWithThisDatabaseDriver"); } @@ -109,7 +109,7 @@ else if ($resql) { $num = $db->num_rows($resql); - $i=0; + $i = 0; while ($i < $num) { $obj = $db->fetch_object($resql); @@ -161,13 +161,13 @@ else print "\n"; $sql = "SELECT relname, seq_tup_read, idx_tup_fetch, n_tup_ins, n_tup_upd, n_tup_del"; - $sql.= " FROM pg_stat_user_tables"; + $sql .= " FROM pg_stat_user_tables"; $resql = $db->query($sql); if ($resql) { $num = $db->num_rows($resql); - $i=0; + $i = 0; while ($i < $num) { $row = $db->fetch_row($resql); @@ -202,7 +202,7 @@ else if ($resql) { while ($row = $db->fetch_row($resql)) { - $rescount = $db->query("SELECT COUNT(*) FROM " . $row[0]); + $rescount = $db->query("SELECT COUNT(*) FROM ".$row[0]); if ($rescount) { $row_count = $db->fetch_row($rescount); $count = $row_count[0]; diff --git a/htdocs/admin/system/database.php b/htdocs/admin/system/database.php index 6ed657ba8cd..dfd05a7694e 100644 --- a/htdocs/admin/system/database.php +++ b/htdocs/admin/system/database.php @@ -43,7 +43,7 @@ print load_fiche_titre($langs->trans("InfoDatabase"), '', 'title_setup'); // Database print '
'; -print '
'.$langs->trans("Label").''.$langs->trans("Parameter").''.$langs->trans("Value").'
'; +print '
'; print ''."\n"; print ''."\n"; print ''."\n"; @@ -60,7 +60,7 @@ print ''; // Tables print '
'; print '
'; -print '
'.$langs->trans("Database").'
'.$langs->trans("Version").''.$db::LABEL.' '.$db->getVersion().'
'.$langs->trans("DatabaseServer").''.$conf->db->host.'
'; +print '
'; print ''."\n"; print ''."\n"; print '
'.$langs->trans("Tables").'
'.$langs->trans("List").'
'; @@ -80,7 +80,7 @@ else { print '
'; print '
'; - print ''; + print '
'; print ''; print ''; print ''; diff --git a/htdocs/admin/system/dolibarr.php b/htdocs/admin/system/dolibarr.php index 5c55c668b1a..695d5363f78 100644 --- a/htdocs/admin/system/dolibarr.php +++ b/htdocs/admin/system/dolibarr.php @@ -30,15 +30,15 @@ require_once DOL_DOCUMENT_ROOT.'/core/lib/admin.lib.php'; require_once DOL_DOCUMENT_ROOT.'/core/lib/files.lib.php'; // Load translation files required by the page -$langs->loadLangs(array("install","other","admin")); +$langs->loadLangs(array("install", "other", "admin")); -$action=GETPOST('action', 'alpha'); +$action = GETPOST('action', 'alpha'); -if (! $user->admin) +if (!$user->admin) accessforbidden(); $sfurl = ''; -$version='0.0'; +$version = '0.0'; @@ -58,9 +58,9 @@ if ($action == 'getlastversion') * View */ -$form=new Form($db); +$form = new Form($db); -$title=$langs->trans("InfoDolibarr"); +$title = $langs->trans("InfoDolibarr"); llxHeader('', $title); @@ -68,7 +68,7 @@ print load_fiche_titre($title, '', 'title_setup'); // Version print '
'; -print '
'.$langs->trans("Parameters").''.$langs->trans("Value").'
'; +print '
'; print ''."\n"; print ''."\n"; @@ -135,7 +135,7 @@ print '
'; // Session print '
'; -print '
'.$langs->trans("Version").''.$langs->trans("Value").'
'.$langs->trans("CurrentVersion").' ('.$langs->trans("Programs").')'.DOL_VERSION; // If current version differs from last upgrade @@ -91,39 +91,39 @@ if (function_exists('curl_init')) { if ($sfurl) { - while (! empty($sfurl->channel[0]->item[$i]->title) && $i < 10000) + while (!empty($sfurl->channel[0]->item[$i]->title) && $i < 10000) { - $title=$sfurl->channel[0]->item[$i]->title; + $title = $sfurl->channel[0]->item[$i]->title; if (preg_match('/([0-9]+\.([0-9\.]+))/', $title, $reg)) { - $newversion=$reg[1]; - $newversionarray=explode('.', $newversion); - $versionarray=explode('.', $version); + $newversion = $reg[1]; + $newversionarray = explode('.', $newversion); + $versionarray = explode('.', $version); //var_dump($newversionarray);var_dump($versionarray); - if (versioncompare($newversionarray, $versionarray) > 0) $version=$newversion; + if (versioncompare($newversionarray, $versionarray) > 0) $version = $newversion; } $i++; } // Show version - print $langs->trans("LastStableVersion").' : '. (($version != '0.0')?$version:$langs->trans("Unknown")) .''; + print $langs->trans("LastStableVersion").' : '.(($version != '0.0') ? $version : $langs->trans("Unknown")).''; } else { - print $langs->trans("LastStableVersion").' : ' .$langs->trans("UpdateServerOffline").''; + print $langs->trans("LastStableVersion").' : '.$langs->trans("UpdateServerOffline").''; } } else { - print $langs->trans("LastStableVersion").' : ' .$langs->trans("Check").''; + print $langs->trans("LastStableVersion").' : '.$langs->trans("Check").''; } } // Now show link to the changelog print '     -     '; -$version=DOL_VERSION; -if (preg_match('/[a-z]+/i', $version)) $version='develop'; // If version contains text, it is not an official tagged version, so we use the full change log. +$version = DOL_VERSION; +if (preg_match('/[a-z]+/i', $version)) $version = 'develop'; // If version contains text, it is not an official tagged version, so we use the full change log. print ''.$langs->trans("SeeChangeLog").''; print '
'; +print '
'; print ''."\n"; print ''."\n"; print ''."\n"; @@ -155,8 +155,8 @@ print ''."\n"; print '
'.$langs->trans("Session").''.$langs->trans("Value").'
'.$langs->trans("SessionSavePath").''.session_save_path().'
'.$langs->trans("SessionName").''.session_name().'
'.$langs->trans("Screen").'' print $_SESSION['dol_screenwidth'].' x '.$_SESSION['dol_screenheight']; print '
'.$langs->trans("Session").''; -$i=0; -foreach($_SESSION as $key => $val) +$i = 0; +foreach ($_SESSION as $key => $val) { if ($i > 0) print ', '; if (is_array($val)) print $key.' => array(...)'; @@ -172,17 +172,17 @@ print '
'; // Shmop if (isset($conf->global->MAIN_OPTIMIZE_SPEED) && ($conf->global->MAIN_OPTIMIZE_SPEED & 0x02)) { - $shmoparray=dol_listshmop(); + $shmoparray = dol_listshmop(); print '
'; - print ''; + print '
'; print ''; print ''; print ''; print ''; print ''."\n"; - foreach($shmoparray as $key => $val) + foreach ($shmoparray as $key => $val) { print ''; print ''; @@ -198,20 +198,20 @@ if (isset($conf->global->MAIN_OPTIMIZE_SPEED) && ($conf->global->MAIN_OPTIMIZE_S // Localisation print '
'; -print '
'.$langs->trans("LanguageFilesCachedIntoShmopSharedMemory").''.$langs->trans("NbOfEntries").''.$langs->trans("Address").'
'.$key.''.count($val).'
'; +print '
'; print ''."\n"; print ''."\n"; print ''."\n"; // Thousands -$thousand=$langs->transnoentitiesnoconv("SeparatorThousand"); -if ($thousand == 'SeparatorThousand') $thousand=' '; // ' ' does not work on trans method -if ($thousand == 'None') $thousand=''; -print ''."\n"; +$thousand = $langs->transnoentitiesnoconv("SeparatorThousand"); +if ($thousand == 'SeparatorThousand') $thousand = ' '; // ' ' does not work on trans method +if ($thousand == 'None') $thousand = ''; +print ''."\n"; // Decimals -$dec=$langs->transnoentitiesnoconv("SeparatorDecimal"); +$dec = $langs->transnoentitiesnoconv("SeparatorDecimal"); print ''."\n"; // Show results of functions to see if everything works -print ''."\n"; +print ''."\n"; print '\n"; if (($thousand != ',' && $thousand != '.') || ($thousand != ' ')) { @@ -220,21 +220,21 @@ if (($thousand != ',' && $thousand != '.') || ($thousand != ' ')) } print ''."\n"; // Timezone -$txt =$langs->trans("OSTZ").' (variable system TZ): '.(! empty($_ENV["TZ"])?$_ENV["TZ"]:$langs->trans("NotDefined")).'
'."\n"; -$txt.=$langs->trans("PHPTZ").' (php.ini date.timezone): '.(ini_get("date.timezone")?ini_get("date.timezone"):$langs->trans("NotDefined")).''."
\n"; // date.timezone must be in valued defined in http://fr3.php.net/manual/en/timezones.europe.php -$txt.=$langs->trans("Dolibarr constant MAIN_SERVER_TZ").': '.(empty($conf->global->MAIN_SERVER_TZ)?$langs->trans("NotDefined"):$conf->global->MAIN_SERVER_TZ); -print ''."\n"; // value defined in http://fr3.php.net/manual/en/timezones.europe.php +print ''."\n"; // value defined in http://fr3.php.net/manual/en/timezones.europe.php print ''."\n"; print ''; print ''; @@ -242,8 +242,8 @@ print ''."\n"; } // Client -$tz=(int) $_SESSION['dol_tz'] + (int) $_SESSION['dol_dst']; -print ''."\n"; print ''."\n"; print ''."\n"; -$filesystemencoding=ini_get("unicode.filesystem_encoding"); // Disponible avec PHP 6.0 +$filesystemencoding = ini_get("unicode.filesystem_encoding"); // Disponible avec PHP 6.0 print ''."\n"; -$tmp=ini_get("unicode.filesystem_encoding"); // Disponible avec PHP 6.0 -if (empty($tmp) && ! empty($_SERVER["WINDIR"])) $tmp='iso-8859-1'; // By default for windows -if (empty($tmp)) $tmp='utf-8'; // By default for other -if (! empty($conf->global->MAIN_FILESYSTEM_ENCODING)) $tmp=$conf->global->MAIN_FILESYSTEM_ENCODING; -print ''."\n"; // date.timezone must be in valued defined in http://fr3.php.net/manual/en/timezones.europe.php +$tmp = ini_get("unicode.filesystem_encoding"); // Disponible avec PHP 6.0 +if (empty($tmp) && !empty($_SERVER["WINDIR"])) $tmp = 'iso-8859-1'; // By default for windows +if (empty($tmp)) $tmp = 'utf-8'; // By default for other +if (!empty($conf->global->MAIN_FILESYSTEM_ENCODING)) $tmp = $conf->global->MAIN_FILESYSTEM_ENCODING; +print ''."\n"; // date.timezone must be in valued defined in http://fr3.php.net/manual/en/timezones.europe.php print '
'.$langs->trans("LocalisationDolibarrParameters").''.$langs->trans("Value").'
'.$langs->trans("LanguageBrowserParameter", "HTTP_ACCEPT_LANGUAGE").''.$_SERVER["HTTP_ACCEPT_LANGUAGE"].'
'.$langs->trans("CurrentUserLanguage").''.$langs->getDefaultLang().'
'.$langs->trans("CurrentValueSeparatorThousand").''.($thousand==' '?$langs->transnoentitiesnoconv("Space"):$thousand).'
'.$langs->trans("CurrentValueSeparatorThousand").''.($thousand == ' ' ? $langs->transnoentitiesnoconv("Space") : $thousand).'
'.$langs->trans("CurrentValueSeparatorDecimal").''.$dec.'
  => price2num(1233.56+1)'.price2num(1233.56+1, '2').'
  => price2num(1233.56+1)'.price2num(1233.56 + 1, '2').'
  => price2num('."'1".$thousand."234".$dec."56')".price2num("1".$thousand."234".$dec."56", '2')."
  => price(1234.56)'.price(1234.56).'
'.$langs->trans("CurrentTimeZone").''; // Timezone server PHP -$a=getServerTimeZoneInt('now'); -$b=getServerTimeZoneInt('winter'); -$c=getServerTimeZoneInt('summer'); -$daylight=(is_numeric($c) && is_numeric($b))?round($c-$b):'unknown'; +$txt = $langs->trans("OSTZ").' (variable system TZ): '.(!empty($_ENV["TZ"]) ? $_ENV["TZ"] : $langs->trans("NotDefined")).'
'."\n"; +$txt .= $langs->trans("PHPTZ").' (php.ini date.timezone): '.(ini_get("date.timezone") ?ini_get("date.timezone") : $langs->trans("NotDefined")).''."
\n"; // date.timezone must be in valued defined in http://fr3.php.net/manual/en/timezones.europe.php +$txt .= $langs->trans("Dolibarr constant MAIN_SERVER_TZ").': '.(empty($conf->global->MAIN_SERVER_TZ) ? $langs->trans("NotDefined") : $conf->global->MAIN_SERVER_TZ); +print '
'.$langs->trans("CurrentTimeZone").''; // Timezone server PHP +$a = getServerTimeZoneInt('now'); +$b = getServerTimeZoneInt('winter'); +$c = getServerTimeZoneInt('summer'); +$daylight = (is_numeric($c) && is_numeric($b)) ?round($c - $b) : 'unknown'; //print $a." ".$b." ".$c." ".$daylight; -$val=($a>=0?'+':'').$a; -$val.=' ('.($a=='unknown'?'unknown':($a>=0?'+':'').($a*3600)).')'; -$val.='       '.getServerTimeZoneString(); -$val.='       '.$langs->trans("DaylingSavingTime").': '.($daylight==='unknown'?'unknown':($a==$c?yn($daylight):yn(0).($daylight?'     ('.$langs->trans('YesInSummer').')':''))); +$val = ($a >= 0 ? '+' : '').$a; +$val .= ' ('.($a == 'unknown' ? 'unknown' : ($a >= 0 ? '+' : '').($a * 3600)).')'; +$val .= '       '.getServerTimeZoneString(); +$val .= '       '.$langs->trans("DaylingSavingTime").': '.($daylight === 'unknown' ? 'unknown' : ($a == $c ?yn($daylight) : yn(0).($daylight ? '     ('.$langs->trans('YesInSummer').')' : ''))); print $form->textwithtooltip($val, $txt, 2, 1, img_info('')); -print '
  => '.$langs->trans("CurrentHour").''.dol_print_date(dol_now(), 'dayhour', 'tzserver').'
  => dol_print_date(0,"dayhourtext")'.dol_print_date(0, "dayhourtext").'
  => dol_get_first_day(1970,1,false)'.dol_get_first_day(1970, 1, false).'     (=> dol_print_date() or idate() of this value = '.dol_print_date(dol_get_first_day(1970, 1, false), 'dayhour').')
  => dol_get_first_day(1970,1,true) // Database timezone if ($conf->db->type == 'mysql' || $conf->db->type == 'mysqli') { - print '
'.$langs->trans("MySQLTimeZone").' (database)'; // Timezone server base - $sql="SHOW VARIABLES where variable_name = 'system_time_zone'"; + print '
'.$langs->trans("MySQLTimeZone").' (database)'; // Timezone server base + $sql = "SHOW VARIABLES where variable_name = 'system_time_zone'"; $resql = $db->query($sql); if ($resql) { @@ -253,25 +253,25 @@ if ($conf->db->type == 'mysql' || $conf->db->type == 'mysqli') print '
'.$langs->trans("ClientTZ").''.($tz?($tz>=0?'+':'').$tz:'').' ('.($tz>=0?'+':'').($tz*60*60).')'; +$tz = (int) $_SESSION['dol_tz'] + (int) $_SESSION['dol_dst']; +print '
'.$langs->trans("ClientTZ").''.($tz ? ($tz >= 0 ? '+' : '').$tz : '').' ('.($tz >= 0 ? '+' : '').($tz * 60 * 60).')'; print '       '.$_SESSION['dol_tz_string']; print '       '.$langs->trans("DaylingSavingTime").': '; -if ($_SESSION['dol_dst']>0) print yn(1); +if ($_SESSION['dol_dst'] > 0) print yn(1); else print yn(0); -if (! empty($_SESSION['dol_dst_first'])) print '     ('.dol_print_date(dol_stringtotime($_SESSION['dol_dst_first']), 'dayhour', 'gmt').' - '.dol_print_date(dol_stringtotime($_SESSION['dol_dst_second']), 'dayhour', 'gmt').')'; +if (!empty($_SESSION['dol_dst_first'])) print '     ('.dol_print_date(dol_stringtotime($_SESSION['dol_dst_first']), 'dayhour', 'gmt').' - '.dol_print_date(dol_stringtotime($_SESSION['dol_dst_second']), 'dayhour', 'gmt').')'; print '
  => '.$langs->trans("ClientHour").''.dol_print_date(dol_now(), 'dayhour', 'tzuser').'
'.$langs->trans("File encoding").' (php.ini unicode.filesystem_encoding)'.$filesystemencoding.'
  => '.$langs->trans("File encoding").''.$tmp.'
  => '.$langs->trans("File encoding").''.$tmp.'
'; print '
'; @@ -280,7 +280,7 @@ print '
'; // Parameters in conf.php file (when a parameter start with ?, it is shown only if defined) -$configfileparameters=array( +$configfileparameters = array( 'dolibarr_main_url_root' => $langs->trans("URLRoot"), '?dolibarr_main_url_root_alt' => $langs->trans("URLRoot").' (alt)', 'dolibarr_main_document_root'=> $langs->trans("DocumentRootServer"), @@ -337,7 +337,7 @@ $configfileparameters=array( ); print '
'; -print ''; +print '
'; print ''; print ''; print ''; print ''."\n"; -foreach($configfileparameters as $key => $value) +foreach ($configfileparameters as $key => $value) { - $ignore=0; + $ignore = 0; if (empty($ignore)) { @@ -357,7 +357,7 @@ foreach($configfileparameters as $key => $value) if (preg_match('/^\?/', $key) && empty(${$newkey})) { if ($newkey != 'multicompany_transverse_mode' || empty($conf->multicompany->enabled)) - continue; // We discard parameters starting with ? + continue; // We discard parameters starting with ? } if (strpos($newkey, 'separator') !== false && $lastkeyshown == 'separator') continue; @@ -378,13 +378,13 @@ foreach($configfileparameters as $key => $value) elseif ($newkey == 'dolibarr_main_url_root' && preg_match('/__auto__/', ${$newkey})) print ${$newkey}.' => '.constant('DOL_MAIN_URL_ROOT'); elseif ($newkey == 'dolibarr_main_document_root_alt') { - $tmparray=explode(',', ${$newkey}); - $i=0; - foreach($tmparray as $value2) + $tmparray = explode(',', ${$newkey}); + $i = 0; + foreach ($tmparray as $value2) { if ($i > 0) print ', '; print $value2; - if (! is_readable($value2)) + if (!is_readable($value2)) { $langs->load("errors"); print ' '.img_warning($langs->trans("ErrorCantReadDir", $value2)); @@ -410,7 +410,7 @@ foreach($configfileparameters as $key => $value) print ""; } print "\n"; - $lastkeyshown=$newkey; + $lastkeyshown = $newkey; } } print '
'.$langs->trans("Parameters").' '; print $langs->trans("ConfigurationFile").' ('.$conffiletoshowshort.')'; @@ -346,9 +346,9 @@ print ''.$langs->trans("Parameter").''.$langs->trans("Value").'
'; @@ -425,28 +425,28 @@ print ''; print ''; print ''; print ''; -if (empty($conf->multicompany->enabled) || !$user->entity) print ''; // If superadmin or multicompany disabled +if (empty($conf->multicompany->enabled) || !$user->entity) print ''; // If superadmin or multicompany disabled print "\n"; $sql = "SELECT"; -$sql.= " rowid"; -$sql.= ", ".$db->decrypt('name')." as name"; -$sql.= ", ".$db->decrypt('value')." as value"; -$sql.= ", type"; -$sql.= ", note"; -$sql.= ", entity"; -$sql.= " FROM ".MAIN_DB_PREFIX."const"; +$sql .= " rowid"; +$sql .= ", ".$db->decrypt('name')." as name"; +$sql .= ", ".$db->decrypt('value')." as value"; +$sql .= ", type"; +$sql .= ", note"; +$sql .= ", entity"; +$sql .= " FROM ".MAIN_DB_PREFIX."const"; if (empty($conf->multicompany->enabled)) { // If no multicompany mode, admins can see global and their constantes - $sql.= " WHERE entity IN (0,".$conf->entity.")"; + $sql .= " WHERE entity IN (0,".$conf->entity.")"; } else { // If multicompany mode, superadmin (user->entity=0) can see everything, admin are limited to their entities. - if ($user->entity) $sql.= " WHERE entity IN (".$user->entity.",".$conf->entity.")"; + if ($user->entity) $sql .= " WHERE entity IN (".$user->entity.",".$conf->entity.")"; } -$sql.= " ORDER BY entity, name ASC"; +$sql .= " ORDER BY entity, name ASC"; $resql = $db->query($sql); if ($resql) { @@ -460,7 +460,7 @@ if ($resql) print ''; print ''."\n"; print ''."\n"; - if (empty($conf->multicompany->enabled) || !$user->entity) print ''."\n"; // If superadmin or multicompany disabled + if (empty($conf->multicompany->enabled) || !$user->entity) print ''."\n"; // If superadmin or multicompany disabled print "\n"; $i++; diff --git a/htdocs/admin/system/filecheck.php b/htdocs/admin/system/filecheck.php index 3fa0905ee42..7f2ae92851b 100644 --- a/htdocs/admin/system/filecheck.php +++ b/htdocs/admin/system/filecheck.php @@ -33,7 +33,7 @@ $langs->load("admin"); if (!$user->admin) accessforbidden(); -$error=0; +$error = 0; /* @@ -50,7 +50,7 @@ print ''.$langs->trans("FileCheckDesc").'
// Version print '
'; -print '
'.$langs->trans("Parameters").' '.$langs->trans("Database").''.$langs->trans("Value").''.$langs->trans("Entity").''.$langs->trans("Entity").'
'.$obj->name.''.dol_escape_htmltag($obj->value).''.$obj->entity.''.$obj->entity.'
'; +print '
'; print ''."\n"; print ''."\n"; print ''."\n"; @@ -75,19 +75,19 @@ print '
'; $file_list = array('missing' => array(), 'updated' => array()); // Local file to compare to -$xmlshortfile = GETPOST('xmlshortfile', 'alpha')?GETPOST('xmlshortfile', 'alpha'):'/install/filelist-'.DOL_VERSION.(empty($conf->global->MAIN_FILECHECK_LOCAL_SUFFIX)?'':$conf->global->MAIN_FILECHECK_LOCAL_SUFFIX).'.xml'; +$xmlshortfile = GETPOST('xmlshortfile', 'alpha') ?GETPOST('xmlshortfile', 'alpha') : '/install/filelist-'.DOL_VERSION.(empty($conf->global->MAIN_FILECHECK_LOCAL_SUFFIX) ? '' : $conf->global->MAIN_FILECHECK_LOCAL_SUFFIX).'.xml'; $xmlfile = DOL_DOCUMENT_ROOT.$xmlshortfile; // Remote file to compare to $xmlremote = GETPOST('xmlremote'); -if (empty($xmlremote) && ! empty($conf->global->MAIN_FILECHECK_URL)) $xmlremote = $conf->global->MAIN_FILECHECK_URL; -$param='MAIN_FILECHECK_URL_'.DOL_VERSION; -if (empty($xmlremote) && ! empty($conf->global->$param)) $xmlremote = $conf->global->$param; +if (empty($xmlremote) && !empty($conf->global->MAIN_FILECHECK_URL)) $xmlremote = $conf->global->MAIN_FILECHECK_URL; +$param = 'MAIN_FILECHECK_URL_'.DOL_VERSION; +if (empty($xmlremote) && !empty($conf->global->$param)) $xmlremote = $conf->global->$param; if (empty($xmlremote)) $xmlremote = 'https://www.dolibarr.org/files/stable/signatures/filelist-'.DOL_VERSION.'.xml'; // Test if remote test is ok $enableremotecheck = true; -if (preg_match('/beta|alpha|rc/i', DOL_VERSION) || ! empty($conf->global->MAIN_ALLOW_INTEGRITY_CHECK_ON_UNSTABLE)) $enableremotecheck=false; +if (preg_match('/beta|alpha|rc/i', DOL_VERSION) || !empty($conf->global->MAIN_ALLOW_INTEGRITY_CHECK_ON_UNSTABLE)) $enableremotecheck = false; $enableremotecheck = true; print ''; @@ -95,7 +95,7 @@ print $langs->trans("MakeIntegrityAnalysisFrom").':
'; print ''."\n"; if (dol_is_file($xmlfile)) { - print ' '.$langs->trans("LocalSignature").' = '; + print ' '.$langs->trans("LocalSignature").' = '; print ''; print '
'; } @@ -109,13 +109,13 @@ else print ''."\n"; if ($enableremotecheck) { - print ' '.$langs->trans("RemoteSignature").' = '; + print ' '.$langs->trans("RemoteSignature").' = '; print '
'; } else { print ' '.$langs->trans("RemoteSignature").' = '.$xmlremote; - if (! GETPOST('xmlremote')) print ' ('.$langs->trans("FeatureAvailableOnlyOnStable").')'; + if (!GETPOST('xmlremote')) print ' ('.$langs->trans("FeatureAvailableOnlyOnStable").')'; print '
'; } print '
'; @@ -131,7 +131,7 @@ if (GETPOST('target') == 'local') } else { - print $langs->trans('XmlNotFound') . ': ' . $xmlfile; + print $langs->trans('XmlNotFound').': '.$xmlfile; $error++; } } @@ -140,7 +140,7 @@ if (GETPOST('target') == 'remote') $xmlarray = getURLContent($xmlremote); // Return array('content'=>response,'curl_error_no'=>errno,'curl_error_msg'=>errmsg...) - if (! $xmlarray['curl_error_no'] && $xmlarray['http_code'] != '404') + if (!$xmlarray['curl_error_no'] && $xmlarray['http_code'] != '404') { $xmlfile = $xmlarray['content']; //print "xmlfilestart".$xmlfile."xmlfileend"; @@ -148,14 +148,14 @@ if (GETPOST('target') == 'remote') } else { - $errormsg=$langs->trans('XmlNotFound') . ': ' . $xmlremote.' - '.$xmlarray['http_code'].' '.$xmlarray['curl_error_no'].' '.$xmlarray['curl_error_msg']; + $errormsg = $langs->trans('XmlNotFound').': '.$xmlremote.' - '.$xmlarray['http_code'].' '.$xmlarray['curl_error_no'].' '.$xmlarray['curl_error_msg']; setEventMessages($errormsg, null, 'errors'); $error++; } } -if (! $error && $xml) +if (!$error && $xml) { $checksumconcat = array(); $file_list = array(); @@ -164,84 +164,84 @@ if (! $error && $xml) // Forced constants if (is_object($xml->dolibarr_constants[0])) { - $out.=load_fiche_titre($langs->trans("ForcedConstants")); + $out .= load_fiche_titre($langs->trans("ForcedConstants")); - $out.='
'; - $out.='
'.$langs->trans("Version").''.$langs->trans("Value").'
'.$langs->trans("VersionLastInstall").''.$conf->global->MAIN_VERSION_LAST_INSTALL.'
'.$langs->trans("VersionLastUpgrade").''.$conf->global->MAIN_VERSION_LAST_UPGRADE.'
'; - $out.=''; - $out.=''; - $out.=''; - $out.=''; - $out.=''; - $out.=''."\n"; + $out .= '
'; + $out .= '
#' . $langs->trans("Constant") . '' . $langs->trans("ExpectedValue") . '' . $langs->trans("Value") . '
'; + $out .= ''; + $out .= ''; + $out .= ''; + $out .= ''; + $out .= ''; + $out .= ''."\n"; $i = 0; foreach ($xml->dolibarr_constants[0]->constant as $constant) // $constant is a simpleXMLElement { - $constname=$constant['name']; - $constvalue=(string) $constant; - $constvalue = (empty($constvalue)?'0':$constvalue); + $constname = $constant['name']; + $constvalue = (string) $constant; + $constvalue = (empty($constvalue) ? '0' : $constvalue); // Value found - $value=''; - if ($constname && $conf->global->$constname != '') $value=$conf->global->$constname; - $valueforchecksum=(empty($value)?'0':$value); + $value = ''; + if ($constname && $conf->global->$constname != '') $value = $conf->global->$constname; + $valueforchecksum = (empty($value) ? '0' : $value); - $checksumconcat[]=$valueforchecksum; + $checksumconcat[] = $valueforchecksum; $i++; - $out.=''; - $out.='' . "\n"; - $out.='' . "\n"; - $out.='' . "\n"; - $out.='' . "\n"; - $out.="\n"; + $out .= ''; + $out .= ''."\n"; + $out .= ''."\n"; + $out .= ''."\n"; + $out .= ''."\n"; + $out .= "\n"; } - if ($i==0) + if ($i == 0) { - $out.=''; + $out .= ''; } - $out.='
#'.$langs->trans("Constant").''.$langs->trans("ExpectedValue").''.$langs->trans("Value").'
'.$i.''.$constname.''.$constvalue.''.$valueforchecksum.'
'.$i.''.$constname.''.$constvalue.''.$valueforchecksum.'
'.$langs->trans("None").'
'.$langs->trans("None").'
'; - $out.='
'; + $out .= '
'; + $out .= '
'; - $out.='
'; + $out .= '
'; } // Scan htdocs if (is_object($xml->dolibarr_htdocs_dir[0])) { //var_dump($xml->dolibarr_htdocs_dir[0]['includecustom']);exit; - $includecustom=(empty($xml->dolibarr_htdocs_dir[0]['includecustom'])?0:$xml->dolibarr_htdocs_dir[0]['includecustom']); + $includecustom = (empty($xml->dolibarr_htdocs_dir[0]['includecustom']) ? 0 : $xml->dolibarr_htdocs_dir[0]['includecustom']); // Defined qualified files (must be same than into generate_filelist_xml.php) - $regextoinclude='\.(php|css|html|js|json|tpl|jpg|png|gif|sql|lang)$'; - $regextoexclude='('.($includecustom?'':'custom|').'documents|conf|install|public\/test|Shared\/PCLZip|nusoap\/lib\/Mail|php\/example|php\/test|geoip\/sample.*\.php|ckeditor\/samples|ckeditor\/adapters)$'; // Exclude dirs + $regextoinclude = '\.(php|css|html|js|json|tpl|jpg|png|gif|sql|lang)$'; + $regextoexclude = '('.($includecustom ? '' : 'custom|').'documents|conf|install|public\/test|Shared\/PCLZip|nusoap\/lib\/Mail|php\/example|php\/test|geoip\/sample.*\.php|ckeditor\/samples|ckeditor\/adapters)$'; // Exclude dirs $scanfiles = dol_dir_list(DOL_DOCUMENT_ROOT, 'files', 1, $regextoinclude, $regextoexclude); // Fill file_list with files in signature, new files, modified files - $ret = getFilesUpdated($file_list, $xml->dolibarr_htdocs_dir[0], '', DOL_DOCUMENT_ROOT, $checksumconcat); // Fill array $file_list + $ret = getFilesUpdated($file_list, $xml->dolibarr_htdocs_dir[0], '', DOL_DOCUMENT_ROOT, $checksumconcat); // Fill array $file_list // Complete with list of new files foreach ($scanfiles as $keyfile => $valfile) { - $tmprelativefilename=preg_replace('/^'.preg_quote(DOL_DOCUMENT_ROOT, '/').'/', '', $valfile['fullname']); - if (! in_array($tmprelativefilename, $file_list['insignature'])) + $tmprelativefilename = preg_replace('/^'.preg_quote(DOL_DOCUMENT_ROOT, '/').'/', '', $valfile['fullname']); + if (!in_array($tmprelativefilename, $file_list['insignature'])) { - $md5newfile=@md5_file($valfile['fullname']); // Can fails if we don't have permission to open/read file - $file_list['added'][]=array('filename'=>$tmprelativefilename, 'md5'=>$md5newfile); + $md5newfile = @md5_file($valfile['fullname']); // Can fails if we don't have permission to open/read file + $file_list['added'][] = array('filename'=>$tmprelativefilename, 'md5'=>$md5newfile); } } // Files missings - $out.=load_fiche_titre($langs->trans("FilesMissing")); + $out .= load_fiche_titre($langs->trans("FilesMissing")); - $out.='
'; - $out.=''; - $out.=''; - $out.=''; - $out.=''; - $out.=''; - $out.=''; - $out.=''."\n"; + $out .= '
'; + $out .= '
#' . $langs->trans("Filename") . '' . $langs->trans("ExpectedSize") . '' . $langs->trans("ExpectedChecksum") . '
'; + $out .= ''; + $out .= ''; + $out .= ''; + $out .= ''; + $out .= ''; + $out .= ''."\n"; $tmpfilelist = dol_sort_array($file_list['missing'], 'filename'); if (is_array($tmpfilelist) && count($tmpfilelist)) { @@ -249,40 +249,40 @@ if (! $error && $xml) foreach ($tmpfilelist as $file) { $i++; - $out.=''; - $out.='' . "\n"; - $out.='' . "\n"; - $out.='' . "\n"; - $out.='' . "\n"; - $out.="\n"; + $out .= ''; + $out .= ''."\n"; + $out .= ''."\n"; + $out .= ''."\n"; + $out .= ''."\n"; + $out .= "\n"; } } else { - $out.=''; + $out .= ''; } - $out.='
#'.$langs->trans("Filename").''.$langs->trans("ExpectedSize").''.$langs->trans("ExpectedChecksum").'
'.$i.''.$file['filename'].''; - if (! empty($file['expectedsize'])) $out.=dol_print_size($file['expectedsize']); - $out.=''.$file['expectedmd5'].'
'.$i.''.$file['filename'].''; + if (!empty($file['expectedsize'])) $out .= dol_print_size($file['expectedsize']); + $out .= ''.$file['expectedmd5'].'
'.$langs->trans("None").'
'.$langs->trans("None").'
'; - $out.='
'; + $out .= '
'; + $out .= ''; - $out.='
'; + $out .= '
'; // Files modified - $out.=load_fiche_titre($langs->trans("FilesModified")); + $out .= load_fiche_titre($langs->trans("FilesModified")); - $totalsize=0; - $out.='
'; - $out.=''; - $out.=''; - $out.=''; - $out.=''; - $out.=''; - $out.=''; - $out.=''; - $out.=''; - $out.=''; - $out.=''."\n"; + $totalsize = 0; + $out .= '
'; + $out .= '
#' . $langs->trans("Filename") . '' . $langs->trans("ExpectedChecksum") . '' . $langs->trans("CurrentChecksum") . '' . $langs->trans("ExpectedSize") . '' . $langs->trans("CurrentSize") . '' . $langs->trans("DateModification") . '
'; + $out .= ''; + $out .= ''; + $out .= ''; + $out .= ''; + $out .= ''; + $out .= ''; + $out .= ''; + $out .= ''; + $out .= ''."\n"; $tmpfilelist2 = dol_sort_array($file_list['updated'], 'filename'); if (is_array($tmpfilelist2) && count($tmpfilelist2)) { @@ -290,53 +290,53 @@ if (! $error && $xml) foreach ($tmpfilelist2 as $file) { $i++; - $out.=''; - $out.='' . "\n"; - $out.='' . "\n"; - $out.='' . "\n"; - $out.='' . "\n"; - $out.='' . "\n"; + $out .= ''; + $out .= ''."\n"; + $out .= ''."\n"; + $out .= ''."\n"; + $out .= ''."\n"; + $out .= ''."\n"; $size = dol_filesize(DOL_DOCUMENT_ROOT.'/'.$file['filename']); $totalsize += $size; - $out.='' . "\n"; - $out.='' . "\n"; - $out.="\n"; + $out .= ''."\n"; + $out .= ''."\n"; + $out .= "\n"; } - $out.=''; - $out.='' . "\n"; - $out.='' . "\n"; - $out.='' . "\n"; - $out.='' . "\n"; - $out.='' . "\n"; - $out.='' . "\n"; - $out.='' . "\n"; - $out.="\n"; + $out .= ''; + $out .= ''."\n"; + $out .= ''."\n"; + $out .= ''."\n"; + $out .= ''."\n"; + $out .= ''."\n"; + $out .= ''."\n"; + $out .= ''."\n"; + $out .= "\n"; } else { - $out.=''; + $out .= ''; } - $out.='
#'.$langs->trans("Filename").''.$langs->trans("ExpectedChecksum").''.$langs->trans("CurrentChecksum").''.$langs->trans("ExpectedSize").''.$langs->trans("CurrentSize").''.$langs->trans("DateModification").'
'.$i.''.$file['filename'].''.$file['expectedmd5'].''.$file['md5'].''; - if ($file['expectedsize']) $out.=dol_print_size($file['expectedsize']); - $out.='
'.$i.''.$file['filename'].''.$file['expectedmd5'].''.$file['md5'].''; + if ($file['expectedsize']) $out .= dol_print_size($file['expectedsize']); + $out .= ''.dol_print_size($size).''.dol_print_date(dol_filemtime(DOL_DOCUMENT_ROOT.'/'.$file['filename']), 'dayhour').'
'.dol_print_size($size).''.dol_print_date(dol_filemtime(DOL_DOCUMENT_ROOT.'/'.$file['filename']), 'dayhour').'
'.$langs->trans("Total").''.dol_print_size($totalsize).'
'.$langs->trans("Total").''.dol_print_size($totalsize).'
'.$langs->trans("None").'
'.$langs->trans("None").'
'; - $out.='
'; + $out .= '
'; + $out .= ''; - $out.='
'; + $out .= '
'; // Files added - $out.=load_fiche_titre($langs->trans("FilesAdded")); + $out .= load_fiche_titre($langs->trans("FilesAdded")); $totalsize = 0; - $out.='
'; - $out.=''; - $out.=''; - $out.=''; - $out.=''; - $out.=''; - $out.=''; - $out.=''; - $out.=''; - $out.=''."\n"; + $out .= '
'; + $out .= '
#' . $langs->trans("Filename") . '' . $langs->trans("ExpectedChecksum") . '' . $langs->trans("CurrentChecksum") . '' . $langs->trans("Size") . '' . $langs->trans("DateModification") . '
'; + $out .= ''; + $out .= ''; + $out .= ''; + $out .= ''; + $out .= ''; + $out .= ''; + $out .= ''; + $out .= ''."\n"; $tmpfilelist3 = dol_sort_array($file_list['added'], 'filename'); if (is_array($tmpfilelist3) && count($tmpfilelist3)) { @@ -344,37 +344,37 @@ if (! $error && $xml) foreach ($tmpfilelist3 as $file) { $i++; - $out.=''; - $out.='' . "\n"; - $out.=''; + $out .= ''."\n"; + $out .= '' . "\n"; - $out.='' . "\n"; - $out.='' . "\n"; + $out .= ''."\n"; + $out .= ''."\n"; + $out .= ''."\n"; $size = dol_filesize(DOL_DOCUMENT_ROOT.'/'.$file['filename']); $totalsize += $size; - $out.='' . "\n"; - $out.='' . "\n"; - $out.="\n"; + $out .= ''."\n"; + $out .= ''."\n"; + $out .= "\n"; } - $out.=''; - $out.='' . "\n"; - $out.='' . "\n"; - $out.='' . "\n"; - $out.='' . "\n"; - $out.='' . "\n"; - $out.='' . "\n"; - $out.="\n"; + $out .= ''; + $out .= ''."\n"; + $out .= ''."\n"; + $out .= ''."\n"; + $out .= ''."\n"; + $out .= ''."\n"; + $out .= ''."\n"; + $out .= "\n"; } else { - $out.=''; + $out .= ''; } - $out.='
#'.$langs->trans("Filename").''.$langs->trans("ExpectedChecksum").''.$langs->trans("CurrentChecksum").''.$langs->trans("Size").''.$langs->trans("DateModification").'
'.$i.''.$file['filename']; - if (! preg_match('/^win/i', PHP_OS)) { - $htmltext=$langs->trans("YouCanDeleteFileOnServerWith", 'rm '.DOL_DOCUMENT_ROOT.$file['filename']); // The slash is included int file['filename'] - $out.=' '.$form->textwithpicto('', $htmltext, 1, 'help', '', 0, 2, 'helprm'.$i); + $out .= '
'.$i.''.$file['filename']; + if (!preg_match('/^win/i', PHP_OS)) { + $htmltext = $langs->trans("YouCanDeleteFileOnServerWith", 'rm '.DOL_DOCUMENT_ROOT.$file['filename']); // The slash is included int file['filename'] + $out .= ' '.$form->textwithpicto('', $htmltext, 1, 'help', '', 0, 2, 'helprm'.$i); } - $out.=''.$file['expectedmd5'].''.$file['md5'].''.$file['expectedmd5'].''.$file['md5'].''.dol_print_size($size).''.dol_print_date(dol_filemtime(DOL_DOCUMENT_ROOT.'/'.$file['filename']), 'dayhour').'
'.dol_print_size($size).''.dol_print_date(dol_filemtime(DOL_DOCUMENT_ROOT.'/'.$file['filename']), 'dayhour').'
'.$langs->trans("Total").''.dol_print_size($totalsize).'
'.$langs->trans("Total").''.dol_print_size($totalsize).'
'.$langs->trans("None").'
'.$langs->trans("None").'
'; - $out.='
'; + $out .= '
'; + $out .= '
'; // Show warning @@ -419,26 +419,26 @@ if (! $error && $xml) if (count($file_list['added'])) { $resultcode = 'warning'; - $resultcomment='FileIntegrityIsOkButFilesWereAdded'; - $outcurrentchecksum = $checksumget.' - '.$langs->trans("FileIntegrityIsOkButFilesWereAdded").''; + $resultcomment = 'FileIntegrityIsOkButFilesWereAdded'; + $outcurrentchecksum = $checksumget.' - '.$langs->trans("FileIntegrityIsOkButFilesWereAdded").''; } else { $resultcode = 'ok'; - $resultcomment='Success'; + $resultcomment = 'Success'; $outcurrentchecksum = ''.$checksumget.''; } } else { $resultcode = 'error'; - $resultcomment='Error'; + $resultcomment = 'Error'; $outcurrentchecksum = ''.$checksumget.''; } print load_fiche_titre($langs->trans("GlobalChecksum")).'
'; - print $langs->trans("ExpectedChecksum").' = '. $outexpectedchecksum .'
'; - print $langs->trans("CurrentChecksum").' = '. $outcurrentchecksum; + print $langs->trans("ExpectedChecksum").' = '.$outexpectedchecksum.'
'; + print $langs->trans("CurrentChecksum").' = '.$outcurrentchecksum; print '
'; print '
'; diff --git a/htdocs/admin/system/index.php b/htdocs/admin/system/index.php index 928b193b1ee..06003068bb2 100644 --- a/htdocs/admin/system/index.php +++ b/htdocs/admin/system/index.php @@ -28,7 +28,7 @@ require_once DOL_DOCUMENT_ROOT.'/core/lib/functions2.lib.php'; // Load translation files required by the page $langs->loadLangs(array("admin", "user", "install")); -if (! $user->admin) accessforbidden(); +if (!$user->admin) accessforbidden(); /* @@ -47,35 +47,35 @@ llxHeader(); print load_fiche_titre($langs->trans("SummarySystem"), '', 'title_setup'); -print ''; +print '
'; print "\n"; -$dolversion=version_dolibarr(); +$dolversion = version_dolibarr(); print "\n"; print '
Dolibarr
".$langs->trans("Version")."".$dolversion."
'; print "
\n"; -print ''; +print '
'; print "\n"; -$osversion=version_os(); +$osversion = version_os(); print "\n"; print '
".$langs->trans("OS")."
".$langs->trans("Version")."".$osversion."
'; print "
\n"; // Serveur web -print ''; +print '
'; print "\n"; -$apacheversion=version_webserver(); +$apacheversion = version_webserver(); print "\n"; print '
".$langs->trans("WebServer")."
".$langs->trans("Version")."".$apacheversion."
'; print "
\n"; // Php -print ''; +print '
'; print "\n"; -$phpversion=version_php(); +$phpversion = version_php(); print "\n"; print "\n"; print '
".$langs->trans("PHP")."
".$langs->trans("Version")."".$phpversion."
".$langs->trans("PhpWebLink")."".php_sapi_name()."
'; @@ -83,17 +83,17 @@ print '
'; print "
\n"; // Database -print ''; +print '
'; print "\n"; -$dblabel=$db::LABEL; -$dbversion=$db->getVersion(); -print "\n"; +$dblabel = $db::LABEL; +$dbversion = $db->getVersion(); +print "\n"; print '
".$langs->trans("Database")."
".$langs->trans("Version")."" .$dblabel." ".$dbversion."
".$langs->trans("Version")."".$dblabel." ".$dbversion."
'; // Add checks on database options if ($db->type == 'pgsql') { // Check option standard_conforming_strings is on - $paramarray=$db->getServerParametersValues('standard_conforming_strings'); + $paramarray = $db->getServerParametersValues('standard_conforming_strings'); // if ($paramarray['standard_conforming_strings'] != 'on' && $paramarray['standard_conforming_strings'] != 1) // { // $langs->load("errors"); @@ -102,10 +102,10 @@ if ($db->type == 'pgsql') print '
'; // Browser -print ''; +print '
'; print "\n"; -print "\n"; -print "\n"; +print "\n"; +print "\n"; print '
".$langs->trans("Browser")."
".$langs->trans("UserAgent")."" .$_SERVER["HTTP_USER_AGENT"]."
".$langs->trans("Smartphone")."".(($conf->browser->layout != 'phone')?$langs->trans("No"):$langs->trans("Yes"))."
".$langs->trans("UserAgent")."".$_SERVER["HTTP_USER_AGENT"]."
".$langs->trans("Smartphone")."".(($conf->browser->layout != 'phone') ? $langs->trans("No") : $langs->trans("Yes"))."
'; print '
'; diff --git a/htdocs/admin/system/modules.php b/htdocs/admin/system/modules.php index a3891dc1c46..7a53b95fcf2 100644 --- a/htdocs/admin/system/modules.php +++ b/htdocs/admin/system/modules.php @@ -103,7 +103,7 @@ foreach($modulesdir as $dir) } print '
'; -print ''; +print '
'; print ''; print ''; print ''; diff --git a/htdocs/admin/system/os.php b/htdocs/admin/system/os.php index 33587f3c1c6..7399a218e9c 100644 --- a/htdocs/admin/system/os.php +++ b/htdocs/admin/system/os.php @@ -37,7 +37,7 @@ llxHeader(); print load_fiche_titre($langs->trans("InfoOS"), '', 'title_setup'); -print '
'.$langs->trans("Modules").''.$langs->trans("Version").'
'; +print '
'; print ''; print "\n"; diff --git a/htdocs/admin/system/phpinfo.php b/htdocs/admin/system/phpinfo.php index afed312cdbd..bcc3aba20d4 100644 --- a/htdocs/admin/system/phpinfo.php +++ b/htdocs/admin/system/phpinfo.php @@ -67,7 +67,7 @@ if ($maxphp > 0 && $maxphp2 > 0 && $maxphp > $maxphp2) } -print '
'.$langs->trans("Parameter").''.$langs->trans("Value").'
'; +print '
'; print ''; print "\n"; diff --git a/htdocs/admin/system/web.php b/htdocs/admin/system/web.php index b5e8e2c3866..1fb98a3b42f 100644 --- a/htdocs/admin/system/web.php +++ b/htdocs/admin/system/web.php @@ -45,23 +45,23 @@ llxHeader('', $langs->trans("InfoWebServer")); print load_fiche_titre($langs->trans("InfoWebServer"), '', 'title_setup'); print '
'; -print '
'.$langs->trans("Parameter").''.$langs->trans("Value").'
'; +print '
'; print '\n"; print '\n"; -print '\n"; +print '\n"; print '\n"; -print '\n"; +print '\n"; print '\n"; -print '\n"; +print '\n"; // Web user group by default -$labeluser=dol_getwebuser('user'); -$labelgroup=dol_getwebuser('group'); +$labeluser = dol_getwebuser('user'); +$labelgroup = dol_getwebuser('group'); if ($labeluser && $labelgroup) { print '\n"; } // Web user group real (detected by 'id' external command) -$arrayout=array(); $varout=0; +$arrayout = array(); $varout = 0; exec('id', $arrayout, $varout); if (empty($varout)) // Test command is ok. Work only on Linux OS. { diff --git a/htdocs/admin/system/xcache.php b/htdocs/admin/system/xcache.php index 0cca1b94fc4..5061305f2e2 100644 --- a/htdocs/admin/system/xcache.php +++ b/htdocs/admin/system/xcache.php @@ -41,7 +41,7 @@ print "
\n"; if (!function_exists('xcache_info')) { - print 'XCache seems to be not installed. Function xcache_info not found.'; + print 'XCache seems to be not installed. Function xcache_info not found.'; llxFooter(); exit; } diff --git a/htdocs/admin/taxes.php b/htdocs/admin/taxes.php index 99c67b038ae..8bab3b94ff5 100644 --- a/htdocs/admin/taxes.php +++ b/htdocs/admin/taxes.php @@ -137,7 +137,7 @@ else print ''; print ''; - print '
'.$langs->trans("Parameter")."".$langs->trans("Value")."
'.$langs->trans("Version")."".$_SERVER["SERVER_SOFTWARE"]."
'.$langs->trans("VirtualServerName")."" . $_SERVER["SERVER_NAME"] . "
'.$langs->trans("VirtualServerName")."".$_SERVER["SERVER_NAME"]."
'.$langs->trans("IP")."".$_SERVER["SERVER_ADDR"]."
'.$langs->trans("Port")."" . $_SERVER["SERVER_PORT"] . "
'.$langs->trans("Port")."".$_SERVER["SERVER_PORT"]."
'.$langs->trans("DocumentRootServer")."".$_SERVER["DOCUMENT_ROOT"]."
'.$langs->trans("DataRootServer")."" . DOL_DATA_ROOT . "
'.$langs->trans("DataRootServer")."".DOL_DATA_ROOT."
'.$langs->trans("WebUserGroup")." (env vars)".$labeluser.'/'.$labelgroup."
'; + print '
'; print ''; print '
'.$langs->trans("CompanyIds").''.$langs->trans("Value").'
'; @@ -169,7 +169,7 @@ else print '
'; - print ''; + print '
'; // Cas des parametres TAX_MODE_SELL/BUY_SERVICE/PRODUCT print ''; @@ -195,7 +195,7 @@ else //print ' ('.$langs->trans("CanBeChangedWhenMakingInvoice").')'; - print '
'; + print '
'; print ''; // Products diff --git a/htdocs/admin/ticket.php b/htdocs/admin/ticket.php index 8bb39f0056b..98d77d47118 100644 --- a/htdocs/admin/ticket.php +++ b/htdocs/admin/ticket.php @@ -74,7 +74,7 @@ if ($action == 'updateMask') { dolibarr_set_const($db, "TICKET_ADDON", $value, 'chaine', 0, '', $conf->entity); } elseif ($action == 'setvar') { - include_once DOL_DOCUMENT_ROOT . "/core/lib/files.lib.php"; + include_once DOL_DOCUMENT_ROOT."/core/lib/files.lib.php"; $notification_email = GETPOST('TICKET_NOTIFICATION_EMAIL_FROM', 'alpha'); if (!empty($notification_email)) { @@ -177,7 +177,7 @@ $page_name = "TicketSetup"; llxHeader('', $langs->trans($page_name), $help_url); // Subheader -$linkback = '' . $langs->trans("BackToModuleList") . ''; +$linkback = ''.$langs->trans("BackToModuleList").''; print load_fiche_titre($langs->trans($page_name), $linkback, 'title_setup'); @@ -186,7 +186,7 @@ $head = ticketAdminPrepareHead(); dol_fiche_head($head, 'settings', $langs->trans("Module56000Name"), -1, "ticket"); -print ''.$langs->trans("TicketSetupDictionaries") . ' : '.$langs->trans("ClickHereToGoTo", $langs->transnoentitiesnoconv("DictionarySetup")).'
'; +print ''.$langs->trans("TicketSetupDictionaries").' : '.$langs->trans("ClickHereToGoTo", $langs->transnoentitiesnoconv("DictionarySetup")).'
'; dol_fiche_end(); @@ -197,19 +197,19 @@ dol_fiche_end(); print load_fiche_titre($langs->trans("TicketNumberingModules")); -print '
 '.$langs->trans("Buy").''.$langs->trans("Sell").'
'; +print '
'; print ''; -print ''; -print ''; -print ''; -print ''; -print ''; +print ''; +print ''; +print ''; +print ''; +print ''; print "\n"; clearstatcache(); foreach ($dirmodels as $reldir) { - $dir = dol_buildpath($reldir . "core/modules/ticket/"); + $dir = dol_buildpath($reldir."core/modules/ticket/"); if (is_dir($dir)) { $handle = opendir($dir); @@ -219,7 +219,7 @@ foreach ($dirmodels as $reldir) { $file = $reg[1]; $classname = substr($file, 4); - include_once $dir . $file . '.php'; + include_once $dir.$file.'.php'; $module = new $file; @@ -233,7 +233,7 @@ foreach ($dirmodels as $reldir) { } if ($module->isEnabled()) { - print ''; @@ -241,20 +241,20 @@ foreach ($dirmodels as $reldir) { print '' . "\n"; + print ''."\n"; print ''; @@ -263,14 +263,14 @@ foreach ($dirmodels as $reldir) { // Info $htmltooltip = ''; - $htmltooltip .= '' . $langs->trans("Version") . ': ' . $module->getVersion() . '
'; + $htmltooltip .= ''.$langs->trans("Version").': '.$module->getVersion().'
'; $nextval = $module->getNextValue($mysoc, $ticket); if ("$nextval" != $langs->trans("NotAvailable")) { // Keep " on nextval - $htmltooltip .= '' . $langs->trans("NextValue") . ': '; + $htmltooltip .= ''.$langs->trans("NextValue").': '; if ($nextval) { - $htmltooltip .= $nextval . '
'; + $htmltooltip .= $nextval.'
'; } else { - $htmltooltip .= $langs->trans($module->error) . '
'; + $htmltooltip .= $langs->trans($module->error).'
'; } } @@ -290,16 +290,16 @@ foreach ($dirmodels as $reldir) { print '
' . $langs->trans("Name") . '' . $langs->trans("Description") . '' . $langs->trans("Example") . '' . $langs->trans("Activated") . '' . $langs->trans("ShortInfo") . ''.$langs->trans("Name").''.$langs->trans("Description").''.$langs->trans("Example").''.$langs->trans("Activated").''.$langs->trans("ShortInfo").'
' . $module->name . "\n"; + print '
'.$module->name."\n"; print $module->info(); print ''; $tmp = $module->getExample(); if (preg_match('/^Error/', $tmp)) { - print '
' . $langs->trans($tmp) . '
'; + print '
'.$langs->trans($tmp).'
'; } elseif ($tmp == 'NotConfigured') { print $langs->trans($tmp); } else { print $tmp; } - print '
'; - if ($conf->global->TICKET_ADDON == 'mod_' . $classname) { + if ($conf->global->TICKET_ADDON == 'mod_'.$classname) { print img_picto($langs->trans("Activated"), 'switch_on'); } else { - print '' . img_picto($langs->trans("Disabled"), 'switch_off') . ''; + print ''.img_picto($langs->trans("Disabled"), 'switch_off').''; } print '

'; if (!$conf->use_javascript_ajax) { - print ''; - print ''; + print ''; + print ''; print ''; } print load_fiche_titre($langs->trans("TicketParams")); -print ''; +print '
'; print ''; -print ''; +print ''; print ''; print ''; print "\n"; @@ -339,7 +339,7 @@ print ''; // Also send to main email address if ($conf->global->MAIN_FEATURES_LEVEL >= 2) { - print ''; + print ''; print ''; }*/ // Auto assign ticket at user who created it -print ''; +print ''; print '
' . $langs->trans("Parameter") . ''.$langs->trans("Parameter").'
' . $langs->trans("TicketsEmailAlsoSendToMainAddress") . '
'.$langs->trans("TicketsEmailAlsoSendToMainAddress").''; if ($conf->use_javascript_ajax) { print ajax_constantonoff('TICKET_NOTIFICATION_ALSO_MAIN_ADDRESS'); @@ -377,7 +377,7 @@ print '
' . $langs->trans("TicketsAutoAssignTicket") . '
'.$langs->trans("TicketsAutoAssignTicket").''; if ($conf->use_javascript_ajax) { print ajax_constantonoff('TICKET_AUTO_ASSIGN_USER_CREATE'); @@ -400,19 +400,19 @@ if (!$conf->use_javascript_ajax) { // Admin var of module print load_fiche_titre($langs->trans("Notification")); -print ''; +print '
'; -print ''; -print ''; +print ''; +print ''; print ''; print ''; -print ''; +print ''; print "\n"; if (empty($conf->global->FCKEDITOR_ENABLE_MAIL)) { print ''; - print ''; + print ''; print "\n"; } @@ -435,18 +435,18 @@ print ''; // @TODO Use module notification instead... // Email de réception des notifications -print ''; +print ''; print ''; +print ''; print ''; print ''; // Email d'envoi des notifications -print ''; +print ''; print ''; +print ''; print ''; @@ -454,9 +454,9 @@ print ''; // Texte d'introduction $mail_intro = $conf->global->TICKET_MESSAGE_MAIL_INTRO ? $conf->global->TICKET_MESSAGE_MAIL_INTRO : $langs->trans('TicketMessageMailIntroText'); -print ''; @@ -466,9 +466,9 @@ print ''; // Texte de signature $mail_signature = $conf->global->TICKET_MESSAGE_MAIL_SIGNATURE ? $conf->global->TICKET_MESSAGE_MAIL_SIGNATURE : $langs->trans('TicketMessageMailSignatureText'); -print ''; @@ -479,7 +479,7 @@ print ''; print '
' . $langs->trans("Email") . ''.$langs->trans("Email").'
' . $langs->trans("TicketCkEditorEmailNotActivated") . '
'.$langs->trans("TicketCkEditorEmailNotActivated").'
' . $langs->trans("TicketEmailNotificationTo") . '
'.$langs->trans("TicketEmailNotificationTo").''; -print ''; print $form->textwithpicto('', $langs->trans("TicketEmailNotificationToHelp"), 1, 'help'); print '
' . $langs->trans("TicketEmailNotificationFrom") . '
'.$langs->trans("TicketEmailNotificationFrom").''; -print ''; print $form->textwithpicto('', $langs->trans("TicketEmailNotificationFromHelp"), 1, 'help'); print '
' . $langs->trans("TicketMessageMailIntroLabelAdmin") . ''; +print '
'.$langs->trans("TicketMessageMailIntroLabelAdmin").''; print ''; -require_once DOL_DOCUMENT_ROOT . '/core/class/doleditor.class.php'; +require_once DOL_DOCUMENT_ROOT.'/core/class/doleditor.class.php'; $doleditor = new DolEditor('TICKET_MESSAGE_MAIL_INTRO', $mail_intro, '100%', 120, 'dolibarr_mailings', '', false, true, $conf->global->FCKEDITOR_ENABLE_MAIL, ROWS_2, 70); $doleditor->Create(); print '
' . $langs->trans("TicketMessageMailSignatureLabelAdmin") . ''; +print '
'.$langs->trans("TicketMessageMailSignatureLabelAdmin").''; print ''; -require_once DOL_DOCUMENT_ROOT . '/core/class/doleditor.class.php'; +require_once DOL_DOCUMENT_ROOT.'/core/class/doleditor.class.php'; $doleditor = new DolEditor('TICKET_MESSAGE_MAIL_SIGNATURE', $mail_signature, '100%', 120, 'dolibarr_mailings', '', false, true, $conf->global->FCKEDITOR_ENABLE_MAIL, ROWS_2, 70); $doleditor->Create(); print '
'; print '
'; -print ''; +print ''; print '
'; print ''; diff --git a/htdocs/admin/ticket_public.php b/htdocs/admin/ticket_public.php index c5cadac11c1..d216252c329 100644 --- a/htdocs/admin/ticket_public.php +++ b/htdocs/admin/ticket_public.php @@ -55,7 +55,7 @@ if ($action == 'setTICKET_ENABLE_PUBLIC_INTERFACE') } if ($action == 'setvar') { - include_once DOL_DOCUMENT_ROOT . "/core/lib/files.lib.php"; + include_once DOL_DOCUMENT_ROOT."/core/lib/files.lib.php"; $topic_interface = GETPOST('TICKET_PUBLIC_INTERFACE_TOPIC', 'nohtml'); if (!empty($topic_interface)) { @@ -158,7 +158,7 @@ $page_name = "TicketSetup"; llxHeader('', $langs->trans($page_name), $help_url); // Subheader -$linkback = '' . $langs->trans("BackToModuleList") . ''; +$linkback = ''.$langs->trans("BackToModuleList").''; print load_fiche_titre($langs->trans($page_name), $linkback, 'title_setup'); @@ -167,7 +167,7 @@ $head = ticketAdminPrepareHead(); dol_fiche_head($head, 'public', $langs->trans("Module56000Name"), -1, "ticket"); -print ''.$langs->trans("TicketPublicAccess") . ' : ' . dol_buildpath('/public/ticket/index.php', 2) . ''; +print ''.$langs->trans("TicketPublicAccess").' : '.dol_buildpath('/public/ticket/index.php', 2).''; dol_fiche_end(); @@ -176,32 +176,32 @@ $enabledisablehtml = $langs->trans("TicketsActivatePublicInterface").' '; if (empty($conf->global->TICKET_ENABLE_PUBLIC_INTERFACE)) { // Button off, click to enable - $enabledisablehtml.=''; - $enabledisablehtml.=img_picto($langs->trans("Disabled"), 'switch_off'); - $enabledisablehtml.=''; + $enabledisablehtml .= ''; + $enabledisablehtml .= img_picto($langs->trans("Disabled"), 'switch_off'); + $enabledisablehtml .= ''; } else { // Button on, click to disable - $enabledisablehtml.=''; - $enabledisablehtml.=img_picto($langs->trans("Activated"), 'switch_on'); - $enabledisablehtml.=''; + $enabledisablehtml .= ''; + $enabledisablehtml .= img_picto($langs->trans("Activated"), 'switch_on'); + $enabledisablehtml .= ''; } print $enabledisablehtml; -print ''; +print ''; print '

'; -if (! empty($conf->global->TICKET_ENABLE_PUBLIC_INTERFACE)) +if (!empty($conf->global->TICKET_ENABLE_PUBLIC_INTERFACE)) { if (empty($conf->use_javascript_ajax)) { - print '
'; - print ''; + print ''; + print ''; print ''; } - print ''; - print ''; + print '
' . $langs->trans("Parameters") . '
'; + print ''; print ''; print ''; // Check if email exists - print ''; + print ''; print ''; + print ''; print ''; + print ''; print ''; + print ''; print ''; } @@ -288,27 +288,27 @@ if (! empty($conf->global->TICKET_ENABLE_PUBLIC_INTERFACE)) // Admin var of module print load_fiche_titre($langs->trans("TicketParamMail")); - print '
'.$langs->trans("Parameters").''; print ''; @@ -209,7 +209,7 @@ if (! empty($conf->global->TICKET_ENABLE_PUBLIC_INTERFACE)) print '
' . $langs->trans("TicketsEmailMustExist") . '
'.$langs->trans("TicketsEmailMustExist").''; if ($conf->use_javascript_ajax) { print ajax_constantonoff('TICKET_EMAIL_MUST_EXISTS'); @@ -242,7 +242,7 @@ if (! empty($conf->global->TICKET_ENABLE_PUBLIC_INTERFACE)) }*/ // Show logo for company - print '
' . $langs->trans("TicketsShowCompanyLogo") . '
'.$langs->trans("TicketsShowCompanyLogo").''; if ($conf->use_javascript_ajax) { print ajax_constantonoff('TICKET_SHOW_COMPANY_LOGO'); @@ -259,7 +259,7 @@ if (! empty($conf->global->TICKET_ENABLE_PUBLIC_INTERFACE)) // Also send to main email address if ($conf->global->MAIN_FEATURES_LEVEL >= 2) { - print '
' . $langs->trans("TicketsEmailAlsoSendToMainAddress") . '
'.$langs->trans("TicketsEmailAlsoSendToMainAddress").''; if ($conf->use_javascript_ajax) { print ajax_constantonoff('TICKET_NOTIFICATION_ALSO_MAIN_ADDRESS'); @@ -275,7 +275,7 @@ if (! empty($conf->global->TICKET_ENABLE_PUBLIC_INTERFACE)) } if (!$conf->use_javascript_ajax) { - print '
'; + print '
'; - print ''; - print ''; + print ''; + print ''; print ''; print ''; - print ''; + print ''; print "\n"; if (empty($conf->global->FCKEDITOR_ENABLE_MAIL)) { print ''; - print ''; + print ''; print "\n"; } // Interface topic $url_interface = $conf->global->TICKET_PUBLIC_INTERFACE_TOPIC; - print ''; + print ''; print ''; print ''; @@ -328,9 +328,9 @@ if (! empty($conf->global->TICKET_ENABLE_PUBLIC_INTERFACE)) // Texte d'aide à la saisie du message $public_text_help_message = $conf->global->TICKET_PUBLIC_TEXT_HELP_MESSAGE ? $conf->global->TICKET_PUBLIC_TEXT_HELP_MESSAGE : $langs->trans('TicketPublicPleaseBeAccuratelyDescribe'); - print ''; @@ -339,7 +339,7 @@ if (! empty($conf->global->TICKET_ENABLE_PUBLIC_INTERFACE)) print ''; // Activate email creation to user - print ''; + print ''; print ''; @@ -367,9 +367,9 @@ if (! empty($conf->global->TICKET_ENABLE_PUBLIC_INTERFACE)) // Url public interface $url_interface = $conf->global->TICKET_URL_PUBLIC_INTERFACE; - print ''; + print ''; print ''; print '
' . $langs->trans("Parameter") . ''.$langs->trans("Parameter").'
' . $langs->trans("TicketCkEditorEmailNotActivated") . '
'.$langs->trans("TicketCkEditorEmailNotActivated").'
' . $langs->trans("TicketPublicInterfaceTopicLabelAdmin") . ''; + print '
'.$langs->trans("TicketPublicInterfaceTopicLabelAdmin").''; print ''; - print ''; print $form->textwithpicto('', $langs->trans("TicketPublicInterfaceTopicHelp"), 1, 'help'); @@ -316,9 +316,9 @@ if (! empty($conf->global->TICKET_ENABLE_PUBLIC_INTERFACE)) // Texte d'accueil homepage $public_text_home = $conf->global->TICKET_PUBLIC_TEXT_HOME ? $conf->global->TICKET_PUBLIC_TEXT_HOME : $langs->trans('TicketPublicInterfaceTextHome'); - print '
' . $langs->trans("TicketPublicInterfaceTextHomeLabelAdmin") . ''; + print '
'.$langs->trans("TicketPublicInterfaceTextHomeLabelAdmin").''; print ''; - require_once DOL_DOCUMENT_ROOT . '/core/class/doleditor.class.php'; + require_once DOL_DOCUMENT_ROOT.'/core/class/doleditor.class.php'; $doleditor = new DolEditor('TICKET_PUBLIC_TEXT_HOME', $public_text_home, '100%', 180, 'dolibarr_notes', '', false, true, $conf->global->FCKEDITOR_ENABLE_SOCIETE, ROWS_2, 70); $doleditor->Create(); print '
' . $langs->trans("TicketPublicInterfaceTextHelpMessageLabelAdmin") . ''; + print '
'.$langs->trans("TicketPublicInterfaceTextHelpMessageLabelAdmin").''; print ''; - require_once DOL_DOCUMENT_ROOT . '/core/class/doleditor.class.php'; + require_once DOL_DOCUMENT_ROOT.'/core/class/doleditor.class.php'; $doleditor = new DolEditor('TICKET_PUBLIC_TEXT_HELP_MESSAGE', $public_text_help_message, '100%', 180, 'dolibarr_notes', '', false, true, $conf->global->FCKEDITOR_ENABLE_SOCIETE, ROWS_2, 70); $doleditor->Create(); print '
' . $langs->trans("TicketsDisableCustomerEmail") . '
'.$langs->trans("TicketsDisableCustomerEmail").''; if ($conf->use_javascript_ajax) { print ajax_constantonoff('TICKET_DISABLE_CUSTOMER_MAILS'); @@ -355,9 +355,9 @@ if (! empty($conf->global->TICKET_ENABLE_PUBLIC_INTERFACE)) // Texte de création d'un ticket $mail_mesg_new = $conf->global->TICKET_MESSAGE_MAIL_NEW ? $conf->global->TICKET_MESSAGE_MAIL_NEW : $langs->trans('TicketNewEmailBody'); - print '
' . $langs->trans("TicketNewEmailBodyLabel") . ''; + print '
'.$langs->trans("TicketNewEmailBodyLabel").''; print ''; - require_once DOL_DOCUMENT_ROOT . '/core/class/doleditor.class.php'; + require_once DOL_DOCUMENT_ROOT.'/core/class/doleditor.class.php'; $doleditor = new DolEditor('TICKET_MESSAGE_MAIL_NEW', $mail_mesg_new, '100%', 120, 'dolibarr_mailings', '', false, true, $conf->global->FCKEDITOR_ENABLE_MAIL, ROWS_2, 70); $doleditor->Create(); print '
' . $langs->trans("TicketUrlPublicInterfaceLabelAdmin") . ''; + print '
'.$langs->trans("TicketUrlPublicInterfaceLabelAdmin").''; print ''; - print ''; print $form->textwithpicto('', $langs->trans("TicketUrlPublicInterfaceHelpAdmin"), 1, 'help'); @@ -377,7 +377,7 @@ if (! empty($conf->global->TICKET_ENABLE_PUBLIC_INTERFACE)) print '
'; - print '
'; + print '
'; print '
'; } diff --git a/htdocs/admin/tools/listevents.php b/htdocs/admin/tools/listevents.php index c0d08f4b505..f2625104fd8 100644 --- a/htdocs/admin/tools/listevents.php +++ b/htdocs/admin/tools/listevents.php @@ -238,7 +238,7 @@ if ($result) } print '
'; - print ''; + print '
'; // Fields title search print ''; diff --git a/htdocs/admin/tools/listsessions.php b/htdocs/admin/tools/listsessions.php index 06bed7a3f3a..d909dc8610b 100644 --- a/htdocs/admin/tools/listsessions.php +++ b/htdocs/admin/tools/listsessions.php @@ -123,7 +123,7 @@ elseif ($action == 'lock') if ($savehandler == 'files') { - print '
'; + print '
'; print ''; print_liste_field_titre("Login", $_SERVER["PHP_SELF"], "login", "", "", 'align="left"', $sortfield, $sortorder); print_liste_field_titre("SessionId", $_SERVER["PHP_SELF"], "id", "", "", 'align="left"', $sortfield, $sortorder); diff --git a/htdocs/admin/tools/purge.php b/htdocs/admin/tools/purge.php index f991bb5752e..91a03387f9c 100644 --- a/htdocs/admin/tools/purge.php +++ b/htdocs/admin/tools/purge.php @@ -86,7 +86,7 @@ print ''; print ''; print ''; -print '
'; +print '
'; print '
'; diff --git a/htdocs/admin/translation.php b/htdocs/admin/translation.php index 52ef490ceae..99a198df394 100644 --- a/htdocs/admin/translation.php +++ b/htdocs/admin/translation.php @@ -28,21 +28,21 @@ require_once DOL_DOCUMENT_ROOT.'/core/lib/files.lib.php'; require_once DOL_DOCUMENT_ROOT.'/core/class/html.formadmin.class.php'; // Load translation files required by the page -$langs->loadLangs(array("companies","products","admin","sms","other","errors")); +$langs->loadLangs(array("companies", "products", "admin", "sms", "other", "errors")); if (!$user->admin) accessforbidden(); -$id=GETPOST('rowid', 'int'); -$action=GETPOST('action', 'alpha'); +$id = GETPOST('rowid', 'int'); +$action = GETPOST('action', 'alpha'); -$langcode=GETPOST('langcode', 'alpha'); -$transkey=GETPOST('transkey', 'alpha'); -$transvalue=GETPOST('transvalue', 'alpha'); +$langcode = GETPOST('langcode', 'alpha'); +$transkey = GETPOST('transkey', 'alpha'); +$transvalue = GETPOST('transvalue', 'alpha'); -$mode = GETPOST('mode', 'aZ09')?GETPOST('mode', 'aZ09'):'overwrite'; +$mode = GETPOST('mode', 'aZ09') ?GETPOST('mode', 'aZ09') : 'overwrite'; -$limit = GETPOST('limit', 'int')?GETPOST('limit', 'int'):$conf->liste_limit; +$limit = GETPOST('limit', 'int') ?GETPOST('limit', 'int') : $conf->liste_limit; $sortfield = GETPOST("sortfield", 'alpha'); $sortorder = GETPOST("sortorder", 'alpha'); $page = GETPOST("page", 'int'); @@ -50,22 +50,22 @@ if (empty($page) || $page == -1) { $page = 0; } // If $page is not defined, $offset = $limit * $page; $pageprev = $page - 1; $pagenext = $page + 1; -if (! $sortfield) $sortfield='lang,transkey'; -if (! $sortorder) $sortorder='ASC'; +if (!$sortfield) $sortfield = 'lang,transkey'; +if (!$sortorder) $sortorder = 'ASC'; // Initialize technical object to manage hooks of page. Note that conf->hooks_modules contains array of hook context -$hookmanager->initHooks(array('admintranslation','globaladmin')); +$hookmanager->initHooks(array('admintranslation', 'globaladmin')); /* * 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 +$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'); include DOL_DOCUMENT_ROOT.'/core/actions_changeselectedfields.inc.php'; @@ -73,10 +73,10 @@ include DOL_DOCUMENT_ROOT.'/core/actions_changeselectedfields.inc.php'; // Purge search criteria if (GETPOST('button_removefilter_x', 'alpha') || GETPOST('button_removefilter.x', 'alpha') || GETPOST('button_removefilter', 'alpha')) // All tests are required to be compatible with all browsers { - $transkey=''; - $transvalue=''; - $toselect=''; - $search_array_options=array(); + $transkey = ''; + $transvalue = ''; + $toselect = ''; + $search_array_options = array(); } if ($action == 'setMAIN_ENABLE_OVERWRITE_TRANSLATION') @@ -92,7 +92,7 @@ if ($action == 'update') setEventMessages($langs->trans("ErrorFieldRequired", $langs->transnoentitiesnoconv("NewTranslationStringToShow")), null, 'errors'); $error++; } - if (! $error) + if (!$error) { $db->begin(); @@ -102,9 +102,9 @@ if ($action == 'update') { $db->commit(); setEventMessages($langs->trans("RecordSaved"), null, 'mesgs'); - $action=""; - $transkey=""; - $transvalue=""; + $action = ""; + $transkey = ""; + $transvalue = ""; } else { @@ -117,14 +117,14 @@ if ($action == 'update') { setEventMessages($db->lasterror(), null, 'errors'); } - $action=''; + $action = ''; } } } if ($action == 'add') { - $error=0; + $error = 0; if (empty($langcode)) { @@ -141,7 +141,7 @@ if ($action == 'add') setEventMessages($langs->trans("ErrorFieldRequired", $langs->transnoentitiesnoconv("NewTranslationStringToShow")), null, 'errors'); $error++; } - if (! $error) + if (!$error) { $db->begin(); @@ -151,9 +151,9 @@ if ($action == 'add') { $db->commit(); setEventMessages($langs->trans("RecordSaved"), null, 'mesgs'); - $action=""; - $transkey=""; - $transvalue=""; + $action = ""; + $transkey = ""; + $transvalue = ""; } else { @@ -166,7 +166,7 @@ if ($action == 'add') { setEventMessages($db->lasterror(), null, 'errors'); } - $action=''; + $action = ''; } } } @@ -198,26 +198,26 @@ if ($action == 'delete') $form = new Form($db); $formadmin = new FormAdmin($db); -$wikihelp='EN:Setup|FR:Paramétrage|ES:Configuración'; +$wikihelp = 'EN:Setup|FR:Paramétrage|ES:Configuración'; llxHeader('', $langs->trans("Setup"), $wikihelp); -$param='&mode='.$mode; +$param = '&mode='.$mode; -$enabledisablehtml=''; -$enabledisablehtml.= $langs->trans("EnableOverwriteTranslation").' '; +$enabledisablehtml = ''; +$enabledisablehtml .= $langs->trans("EnableOverwriteTranslation").' '; if (empty($conf->global->MAIN_ENABLE_OVERWRITE_TRANSLATION)) { // Button off, click to enable - $enabledisablehtml.=''; - $enabledisablehtml.=img_picto($langs->trans("Disabled"), 'switch_off'); - $enabledisablehtml.=''; + $enabledisablehtml .= ''; + $enabledisablehtml .= img_picto($langs->trans("Disabled"), 'switch_off'); + $enabledisablehtml .= ''; } else { // Button on, click to disable - $enabledisablehtml.=''; - $enabledisablehtml.=img_picto($langs->trans("Activated"), 'switch_on'); - $enabledisablehtml.=''; + $enabledisablehtml .= ''; + $enabledisablehtml .= img_picto($langs->trans("Activated"), 'switch_on'); + $enabledisablehtml .= ''; } print load_fiche_titre($langs->trans("Translation"), $enabledisablehtml, 'title_setup'); @@ -247,7 +247,7 @@ print ''; print ''; print ''; -$head=translation_prepare_head(); +$head = translation_prepare_head(); dol_fiche_head($head, $mode, '', -1, ''); @@ -255,14 +255,14 @@ if ($mode == 'overwrite') { //print load_fiche_titre($langs->trans("TranslationOverwriteKey"), '', '')."\n"; - $disabled=''; - if ($action == 'edit' || empty($conf->global->MAIN_ENABLE_OVERWRITE_TRANSLATION)) $disabled=' disabled="disabled"'; - $disablededit=''; - if ($action == 'edit' || empty($conf->global->MAIN_ENABLE_OVERWRITE_TRANSLATION)) $disablededit=' disabled'; + $disabled = ''; + if ($action == 'edit' || empty($conf->global->MAIN_ENABLE_OVERWRITE_TRANSLATION)) $disabled = ' disabled="disabled"'; + $disablededit = ''; + if ($action == 'edit' || empty($conf->global->MAIN_ENABLE_OVERWRITE_TRANSLATION)) $disablededit = ' disabled'; print '
'; print img_info().' '.$langs->trans("SomeTranslationAreUncomplete"); - $urlwikitranslatordoc='https://wiki.dolibarr.org/index.php/Translator_documentation'; + $urlwikitranslatordoc = 'https://wiki.dolibarr.org/index.php/Translator_documentation'; print ' ('.$langs->trans("SeeAlso", ''.$langs->trans("Here").'').')
'; print $langs->trans("TranslationOverwriteDesc", $langs->transnoentitiesnoconv("Language"), $langs->transnoentitiesnoconv("Key"), $langs->transnoentitiesnoconv("NewTranslationStringToShow"))."\n"; print ' ('.$langs->trans("TranslationOverwriteDesc2").').'."
\n"; @@ -271,11 +271,11 @@ if ($mode == 'overwrite') print '
'; - print ''; + print ''; print ''; print '
'; - print ''; + print '
'; print ''; print_liste_field_titre("Language_en_US_es_MX_etc", $_SERVER["PHP_SELF"], 'lang,transkey', '', $param, '', $sortfield, $sortorder); print_liste_field_titre("Key", $_SERVER["PHP_SELF"], 'transkey', '', $param, '', $sortfield, $sortorder); @@ -289,12 +289,12 @@ if ($mode == 'overwrite') print "\n"; print ''."\n"; print ''; // Limit to superadmin /*if (! empty($conf->multicompany->enabled) && !$user->entity) @@ -316,10 +316,10 @@ if ($mode == 'overwrite') // Show constants $sql = "SELECT rowid, entity, lang, transkey, transvalue"; - $sql.= " FROM ".MAIN_DB_PREFIX."overwrite_trans"; - $sql.= " WHERE 1 = 1"; - $sql.= " AND entity IN (".getEntity('overwrite_trans').")"; - $sql.= $db->order($sortfield, $sortorder); + $sql .= " FROM ".MAIN_DB_PREFIX."overwrite_trans"; + $sql .= " WHERE 1 = 1"; + $sql .= " AND entity IN (".getEntity('overwrite_trans').")"; + $sql .= $db->order($sortfield, $sortorder); dol_syslog("translation::select from table", LOG_DEBUG); $result = $db->query($sql); @@ -366,9 +366,9 @@ if ($mode == 'overwrite') } else { - print ''.img_edit().''; + print ''.img_edit().''; print '   '; - print ''.img_delete().''; + print ''.img_delete().''; } print ''; @@ -384,21 +384,21 @@ if ($mode == 'overwrite') if ($mode == 'searchkey') { - $langcode=GETPOST('langcode')?GETPOST('langcode'):$langs->defaultlang; + $langcode = GETPOST('langcode') ?GETPOST('langcode') : $langs->defaultlang; - $newlang=new Translate('', $conf); + $newlang = new Translate('', $conf); $newlang->setDefaultLang($langcode); - $newlangfileonly=new Translate('', $conf); + $newlangfileonly = new Translate('', $conf); $newlangfileonly->setDefaultLang($langcode); - $recordtoshow=array(); + $recordtoshow = array(); // Search modules dirs $modulesdir = dolGetModulesDirs(); - $nbtotaloffiles=0; - $nbempty=0; + $nbtotaloffiles = 0; + $nbempty = 0; /*var_dump($langcode); var_dump($transkey); var_dump($transvalue);*/ @@ -412,27 +412,27 @@ if ($mode == 'searchkey') else { // Search into dir of modules (the $modulesdir is already a list that loop on $conf->file->dol_document_root) - $i=0; - foreach($modulesdir as $keydir => $tmpsearchdir) + $i = 0; + foreach ($modulesdir as $keydir => $tmpsearchdir) { - $searchdir = $tmpsearchdir; // $searchdir can be '.../htdocs/core/modules/' or '.../htdocs/custom/mymodule/core/modules/' + $searchdir = $tmpsearchdir; // $searchdir can be '.../htdocs/core/modules/' or '.../htdocs/custom/mymodule/core/modules/' // Directory of translation files - $dir_lang = dirname(dirname($searchdir))."/langs/".$langcode; // The 2 dirname is to go up in dir for 2 levels - $dir_lang_osencoded=dol_osencode($dir_lang); + $dir_lang = dirname(dirname($searchdir))."/langs/".$langcode; // The 2 dirname is to go up in dir for 2 levels + $dir_lang_osencoded = dol_osencode($dir_lang); - $filearray=dol_dir_list($dir_lang_osencoded, 'files', 0, '', '', $sortfield, (strtolower($sortorder)=='asc'?SORT_ASC:SORT_DESC), 1); - foreach($filearray as $file) + $filearray = dol_dir_list($dir_lang_osencoded, 'files', 0, '', '', $sortfield, (strtolower($sortorder) == 'asc' ?SORT_ASC:SORT_DESC), 1); + foreach ($filearray as $file) { - $tmpfile=preg_replace('/.lang/i', '', basename($file['name'])); - $moduledirname =(basename(dirname(dirname($dir_lang)))); + $tmpfile = preg_replace('/.lang/i', '', basename($file['name'])); + $moduledirname = (basename(dirname(dirname($dir_lang)))); - $langkey=$tmpfile; - if ($i > 0) $langkey.='@'.$moduledirname; + $langkey = $tmpfile; + if ($i > 0) $langkey .= '@'.$moduledirname; //var_dump($i.' - '.$keydir.' - '.$dir_lang_osencoded.' -> '.$moduledirname . ' / ' . $tmpfile.' -> '.$langkey); - $result = $newlang->load($langkey, 0, 0, '', 0); // Load translation files + database overwrite - $result = $newlangfileonly->load($langkey, 0, 0, '', 1); // Load translation files only + $result = $newlang->load($langkey, 0, 0, '', 0); // Load translation files + database overwrite + $result = $newlangfileonly->load($langkey, 0, 0, '', 1); // Load translation files only if ($result < 0) print 'Failed to load language file '.$tmpfile.'
'."\n"; else $nbtotaloffiles++; //print 'After loading lang '.$langkey.', newlang has '.count($newlang->tab_translate).' records
'."\n"; @@ -441,11 +441,11 @@ if ($mode == 'searchkey') } // Now search into translation array - foreach($newlang->tab_translate as $key => $val) + foreach ($newlang->tab_translate as $key => $val) { - if ($transkey && ! preg_match('/'.preg_quote($transkey, '/').'/i', $key)) continue; - if ($transvalue && ! preg_match('/'.preg_quote($transvalue, '/').'/i', $val)) continue; - $recordtoshow[$key]=$val; + if ($transkey && !preg_match('/'.preg_quote($transkey, '/').'/i', $key)) continue; + if ($transvalue && !preg_match('/'.preg_quote($transvalue, '/').'/i', $val)) continue; + $recordtoshow[$key] = $val; } } @@ -464,7 +464,7 @@ if ($mode == 'searchkey') print ''; print '
'; - print '
'; - print $formadmin->select_language(GETPOST('langcode'), 'langcode', 0, null, 1, 0, $disablededit?1:0, 'maxwidthonsmartphone', 1); + print $formadmin->select_language(GETPOST('langcode'), 'langcode', 0, null, 1, 0, $disablededit ? 1 : 0, 'maxwidthonsmartphone', 1); print ''; - print ''; + print ''; print ''; - print ''; + print ''; print '
'; + print '
'; print ''; print_liste_field_titre("Language_en_US_es_MX_etc", $_SERVER["PHP_SELF"], 'lang,transkey', '', $param, '', $sortfield, $sortorder); print_liste_field_titre("Key", $_SERVER["PHP_SELF"], 'transkey', '', $param, '', $sortfield, $sortorder); @@ -497,7 +497,7 @@ if ($mode == 'searchkey') print ''; // Action column print ''; print ''; @@ -508,8 +508,8 @@ if ($mode == 'searchkey') if ($sortfield == 'transvalue' && strtolower($sortorder) == 'desc') arsort($recordtoshow); // Show result - $i=0; - foreach($recordtoshow as $key => $val) + $i = 0; + foreach ($recordtoshow as $key => $val) { $i++; if ($i <= $offset) continue; @@ -517,24 +517,24 @@ if ($mode == 'searchkey') print '
'; - $searchpicto=$form->showFilterAndCheckAddButtons($massactionbutton?1:0, 'checkforselect', 1); + $searchpicto = $form->showFilterAndCheckAddButtons($massactionbutton ? 1 : 0, 'checkforselect', 1); print $searchpicto; print '
'.$langcode.''.$key.''; print dol_escape_htmltag($val); print ''; - if (! empty($newlangfileonly->tab_translate[$key])) + if (!empty($newlangfileonly->tab_translate[$key])) { if ($val != $newlangfileonly->tab_translate[$key]) { // retrieve rowid $sql = "SELECT rowid"; - $sql.= " FROM " . MAIN_DB_PREFIX . "overwrite_trans"; - $sql.= " WHERE transkey = '".$key."'"; - $sql.= " AND entity IN (" . getEntity('overwrite_trans') . ")"; + $sql .= " FROM ".MAIN_DB_PREFIX."overwrite_trans"; + $sql .= " WHERE transkey = '".$key."'"; + $sql .= " AND entity IN (".getEntity('overwrite_trans').")"; dol_syslog("translation::select from table", LOG_DEBUG); $result = $db->query($sql); if ($result) { $obj = $db->fetch_object($result); } - print '' . img_edit() . ''; + print ''.img_edit().''; print '  '; - print '' . img_delete() . ''; + print ''.img_delete().''; print '  '; $htmltext = $langs->trans("OriginalValueWas", $newlangfileonly->tab_translate[$key]); print $form->textwithpicto('', $htmltext, 1, 'info'); @@ -542,12 +542,12 @@ if ($mode == 'searchkey') elseif (!empty($conf->global->MAIN_ENABLE_OVERWRITE_TRANSLATION)) { //print $key.'-'.$val; - print '' . img_edit_add($langs->trans("Overwrite")) . ''; + print ''.img_edit_add($langs->trans("Overwrite")).''; } - if (! empty($conf->global->MAIN_FEATURES_LEVEL)) + if (!empty($conf->global->MAIN_FEATURES_LEVEL)) { - $transifexlangfile='$'; // $ means 'All' + $transifexlangfile = '$'; // $ means 'All' //$transifexurl = 'https://www.transifex.com/dolibarr-association/dolibarr/translate/#'.$langcode.'/'.$transifexlangfile.'?key='.$key; $transifexurl = 'https://www.transifex.com/dolibarr-association/dolibarr/translate/#'.$langcode.'/'.$transifexlangfile.'?q=key%3A'.$key; @@ -574,7 +574,7 @@ dol_fiche_end(); print "\n"; -if (! empty($langcode)) +if (!empty($langcode)) { dol_set_focus('#transvalue'); } diff --git a/htdocs/admin/triggers.php b/htdocs/admin/triggers.php index bdc5ee5961d..ce7f525e8b3 100644 --- a/htdocs/admin/triggers.php +++ b/htdocs/admin/triggers.php @@ -28,8 +28,8 @@ $langs->load("admin"); if (!$user->admin) accessforbidden(); -$sortfield='file'; -$sortorder='ASC'; +$sortfield = 'file'; +$sortorder = 'ASC'; /* @@ -61,9 +61,9 @@ print '
'; print ''; print ''; print getTitleFieldOfList('', 0, $_SERVER["PHP_SELF"], 'none', "", $param, '', $sortfield, $sortorder, '', 1)."\n"; -print getTitleFieldOfList($langs->trans("File"), 0, $_SERVER["PHP_SELF"], 'file', "", $param, ($align?'align="'.$align.'"':''), $sortfield, $sortorder, '', 1)."\n"; +print getTitleFieldOfList($langs->trans("File"), 0, $_SERVER["PHP_SELF"], 'file', "", $param, ($align ? 'align="'.$align.'"' : ''), $sortfield, $sortorder, '', 1)."\n"; print getTitleFieldOfList($langs->trans("Active"), 0, $_SERVER["PHP_SELF"], 'active', "", $param, 'align="center"', $sortfield, $sortorder, '', 1)."\n"; -print getTitleFieldOfList('', 0, $_SERVER["PHP_SELF"], 'none', "", $param, ($align?'align="'.$align.'"':''), $sortfield, $sortorder, '', 1)."\n"; +print getTitleFieldOfList('', 0, $_SERVER["PHP_SELF"], 'none', "", $param, ($align ? 'align="'.$align.'"' : ''), $sortfield, $sortorder, '', 1)."\n"; print ''; foreach ($triggers as $trigger) @@ -73,8 +73,8 @@ foreach ($triggers as $trigger) print ''; print ''; print ''; diff --git a/htdocs/admin/user.php b/htdocs/admin/user.php index 1b4c59505db..cfc5a65cc54 100644 --- a/htdocs/admin/user.php +++ b/htdocs/admin/user.php @@ -145,7 +145,7 @@ $head=user_admin_prepare_head(); dol_fiche_head($head, 'card', $langs->trans("MenuUsersAndGroups"), -1, 'user'); -print '
'.$trigger['file'].''.$trigger['status'].''; - $text=$trigger['info']; - $text.="
\n".$langs->trans("File").":
\n".$trigger['relpath']; + $text = $trigger['info']; + $text .= "
\n".$langs->trans("File").":
\n".$trigger['relpath']; //$text.="\n".$langs->trans("ExternalModule",$trigger['isocreorexternal']); print $form->textwithpicto('', $text); print '
'; +print '
'; print ''; print ''; print ''; @@ -206,7 +206,7 @@ else dol_print_error($db); } -print '
'.$langs->trans("Description").' 
'; +print '
'; print ''; print ''; print ''; diff --git a/htdocs/admin/usergroup.php b/htdocs/admin/usergroup.php index bd8ae3d5e92..fd7348bc603 100644 --- a/htdocs/admin/usergroup.php +++ b/htdocs/admin/usergroup.php @@ -153,7 +153,7 @@ else dol_print_error($db); } -print '
'.$langs->trans("Name").''.$langs->trans("Description").'
'; +print '
'; print ''; print ''; print ''; diff --git a/htdocs/admin/website.php b/htdocs/admin/website.php index 5ea6ee66dd9..c759b0a8d8c 100644 --- a/htdocs/admin/website.php +++ b/htdocs/admin/website.php @@ -447,7 +447,7 @@ if ($id) print ''; print ''; - print '
'.$langs->trans("Name").''.$langs->trans("Description").'
'; + print '
'; // Form to add a new line if ($tabname[$id]) @@ -532,7 +532,7 @@ if ($id) print ''; print ''; - print '
'; + print '
'; // Title of lines print ''; diff --git a/htdocs/admin/website_options.php b/htdocs/admin/website_options.php index 610a83f302d..31995f2d90e 100644 --- a/htdocs/admin/website_options.php +++ b/htdocs/admin/website_options.php @@ -34,18 +34,18 @@ require_once DOL_DOCUMENT_ROOT.'/website/class/website.class.php'; // Load translation files required by the page $langs->loadLangs(array('errors', 'admin', 'companies', 'website')); -$action=GETPOST('action', 'alpha')?GETPOST('action', 'alpha'):'view'; -$confirm=GETPOST('confirm', 'alpha'); +$action = GETPOST('action', 'alpha') ?GETPOST('action', 'alpha') : 'view'; +$confirm = GETPOST('confirm', 'alpha'); $backtopage = GETPOST('backtopage', 'alpha'); -$rowid=GETPOST('rowid', 'alpha'); +$rowid = GETPOST('rowid', 'alpha'); if (!$user->admin) accessforbidden(); $status = 1; // Load variable for pagination -$limit = GETPOST('limit', 'int')?GETPOST('limit', 'int'):$conf->liste_limit; +$limit = GETPOST('limit', 'int') ?GETPOST('limit', 'int') : $conf->liste_limit; $sortfield = GETPOST('sortfield', 'alpha'); $sortorder = GETPOST('sortorder', 'alpha'); $page = GETPOST('page', 'int'); @@ -57,7 +57,7 @@ $pagenext = $page + 1; // Initialize technical object to manage hooks of page. Note that conf->hooks_modules contains array of hook context $hookmanager->initHooks(array('admin')); -$arrayofparameters=array('WEBSITE_USE_WEBSITE_ACCOUNTS'=>array('css'=>'minwidth200')); +$arrayofparameters = array('WEBSITE_USE_WEBSITE_ACCOUNTS'=>array('css'=>'minwidth200')); /* @@ -72,16 +72,16 @@ include DOL_DOCUMENT_ROOT.'/core/actions_setmoduleoptions.inc.php'; */ $form = new Form($db); -$formadmin=new FormAdmin($db); +$formadmin = new FormAdmin($db); llxHeader('', $langs->trans("WebsiteSetup")); -$titre=$langs->trans("WebsiteSetup"); -$linkback=''.$langs->trans("BackToModuleList").''; +$titre = $langs->trans("WebsiteSetup"); +$linkback = ''.$langs->trans("BackToModuleList").''; print load_fiche_titre($titre, $linkback, 'title_setup'); // Onglets -$head=array(); +$head = array(); $h = 0; $head[$h][0] = DOL_URL_ROOT."/admin/website.php"; @@ -103,14 +103,14 @@ if ($action == 'edit') print ''; print ''; - print '
'; + print '
'; print ''; - foreach($arrayofparameters as $key => $val) + foreach ($arrayofparameters as $key => $val) { print ''; + print ''; } print '
'.$langs->trans("Parameter").''.$langs->trans("Value").'
'; print $form->textwithpicto($langs->trans($key), $langs->trans($key.'Tooltip')); - print '
'; @@ -124,14 +124,14 @@ if ($action == 'edit') } else { - print ''; + print '
'; print ''; - foreach($arrayofparameters as $key => $val) + foreach ($arrayofparameters as $key => $val) { print ''; + print ''; } print '
'.$langs->trans("Parameter").''.$langs->trans("Value").'
'; print $form->textwithpicto($langs->trans($key), $langs->trans($key.'Tooltip')); - print '' . $conf->global->$key . '
'.$conf->global->$key.'
'; diff --git a/htdocs/admin/workflow.php b/htdocs/admin/workflow.php index 3c4232cbc0a..81899fee0f0 100644 --- a/htdocs/admin/workflow.php +++ b/htdocs/admin/workflow.php @@ -28,9 +28,9 @@ require '../main.inc.php'; require_once DOL_DOCUMENT_ROOT.'/core/lib/admin.lib.php'; // Load translation files required by the page -$langs->loadLangs(array("admin","workflow","propal","workflow","orders","supplier_proposals","receptions")); +$langs->loadLangs(array("admin", "workflow", "propal", "workflow", "orders", "supplier_proposals", "receptions")); -if (! $user->admin) accessforbidden(); +if (!$user->admin) accessforbidden(); $action = GETPOST('action', 'alpha'); @@ -41,7 +41,7 @@ $action = GETPOST('action', 'alpha'); if (preg_match('/set(.*)/', $action, $reg)) { - if (! dolibarr_set_const($db, $reg[1], '1', 'chaine', 0, '', $conf->entity) > 0) + if (!dolibarr_set_const($db, $reg[1], '1', 'chaine', 0, '', $conf->entity) > 0) { dol_print_error($db); } @@ -49,7 +49,7 @@ if (preg_match('/set(.*)/', $action, $reg)) if (preg_match('/del(.*)/', $action, $reg)) { - if (! dolibarr_set_const($db, $reg[1], '0', 'chaine', 0, '', $conf->entity) > 0) + if (!dolibarr_set_const($db, $reg[1], '0', 'chaine', 0, '', $conf->entity) > 0) { dol_print_error($db); } @@ -62,7 +62,7 @@ if (preg_match('/del(.*)/', $action, $reg)) llxHeader('', $langs->trans("WorkflowSetup"), ''); -$linkback=''.$langs->trans("BackToModuleList").''; +$linkback = ''.$langs->trans("BackToModuleList").''; print load_fiche_titre($langs->trans("WorkflowSetup"), $linkback, 'title_setup'); print ''.$langs->trans("WorkflowDesc").'
'; @@ -72,29 +72,29 @@ print "
"; clearstatcache(); -$workflowcodes=array( +$workflowcodes = array( // Automatic creation 'WORKFLOW_PROPAL_AUTOCREATE_ORDER'=>array('family'=>'create', 'position'=>10, 'enabled'=>'! empty($conf->propal->enabled) && ! empty($conf->commande->enabled)', 'picto'=>'order'), 'WORKFLOW_ORDER_AUTOCREATE_INVOICE'=>array('family'=>'create', 'position'=>20, 'enabled'=>'! empty($conf->commande->enabled) && ! empty($conf->facture->enabled)', 'picto'=>'bill'), 'separator1'=>array('family'=>'separator', 'position'=>25), // Automatic classification of proposal - 'WORKFLOW_ORDER_CLASSIFY_BILLED_PROPAL'=>array('family'=>'classify_proposal', 'position'=>30, 'enabled'=>'! empty($conf->propal->enabled) && ! empty($conf->commande->enabled)', 'picto'=>'propal','warning'=>''), - 'WORKFLOW_INVOICE_CLASSIFY_BILLED_PROPAL'=>array('family'=>'classify_proposal', 'position'=>31, 'enabled'=>'! empty($conf->propal->enabled) && ! empty($conf->facture->enabled)', 'picto'=>'propal','warning'=>''), + 'WORKFLOW_ORDER_CLASSIFY_BILLED_PROPAL'=>array('family'=>'classify_proposal', 'position'=>30, 'enabled'=>'! empty($conf->propal->enabled) && ! empty($conf->commande->enabled)', 'picto'=>'propal', 'warning'=>''), + 'WORKFLOW_INVOICE_CLASSIFY_BILLED_PROPAL'=>array('family'=>'classify_proposal', 'position'=>31, 'enabled'=>'! empty($conf->propal->enabled) && ! empty($conf->facture->enabled)', 'picto'=>'propal', 'warning'=>''), // Automatic classification of order 'WORKFLOW_ORDER_CLASSIFY_SHIPPED_SHIPPING'=>array('family'=>'classify_order', 'position'=>40, 'enabled'=>'! empty($conf->expedition->enabled) && ! empty($conf->commande->enabled)', 'picto'=>'order'), - 'WORKFLOW_INVOICE_AMOUNT_CLASSIFY_BILLED_ORDER'=>array('family'=>'classify_order', 'position'=>41, 'enabled'=>'! empty($conf->facture->enabled) && ! empty($conf->commande->enabled)', 'picto'=>'order','warning'=>''), // For this option, if module invoice is disabled, it does not exists, so "Classify billed" for order must be done manually from order card. + 'WORKFLOW_INVOICE_AMOUNT_CLASSIFY_BILLED_ORDER'=>array('family'=>'classify_order', 'position'=>41, 'enabled'=>'! empty($conf->facture->enabled) && ! empty($conf->commande->enabled)', 'picto'=>'order', 'warning'=>''), // For this option, if module invoice is disabled, it does not exists, so "Classify billed" for order must be done manually from order card. 'separator2'=>array('family'=>'separator', 'position'=>50), // Automatic classification supplier proposal - 'WORKFLOW_ORDER_CLASSIFY_BILLED_SUPPLIER_PROPOSAL'=>array('family'=>'classify_supplier_proposal', 'position'=>60, 'enabled'=>'! empty($conf->supplier_proposal->enabled) && ! empty($conf->fournisseur->enabled)', 'picto'=>'propal','warning'=>''), + 'WORKFLOW_ORDER_CLASSIFY_BILLED_SUPPLIER_PROPOSAL'=>array('family'=>'classify_supplier_proposal', 'position'=>60, 'enabled'=>'! empty($conf->supplier_proposal->enabled) && ! empty($conf->fournisseur->enabled)', 'picto'=>'propal', 'warning'=>''), // Automatic classification supplier order - 'WORKFLOW_INVOICE_AMOUNT_CLASSIFY_BILLED_SUPPLIER_ORDER'=>array('family'=>'classify_supplier_order', 'position'=>62, 'enabled'=>'! empty($conf->fournisseur->enabled)', 'picto'=>'order','warning'=>''), + 'WORKFLOW_INVOICE_AMOUNT_CLASSIFY_BILLED_SUPPLIER_ORDER'=>array('family'=>'classify_supplier_order', 'position'=>62, 'enabled'=>'! empty($conf->fournisseur->enabled)', 'picto'=>'order', 'warning'=>''), //Automatic classification reception 'WORKFLOW_BILL_ON_RECEPTION'=>array('family'=>'classify_reception', 'position'=>64, 'enabled'=>'! empty($conf->reception->enabled) && ! empty($conf->fournisseur->enabled)', 'picto'=>'bill'), ); -if (! empty($conf->modules_parts['workflow']) && is_array($conf->modules_parts['workflow'])) +if (!empty($conf->modules_parts['workflow']) && is_array($conf->modules_parts['workflow'])) { - foreach($conf->modules_parts['workflow'] as $workflow) + foreach ($conf->modules_parts['workflow'] as $workflow) { $workflowcodes = array_merge($workflowcodes, $workflow); } @@ -103,26 +103,26 @@ if (! empty($conf->modules_parts['workflow']) && is_array($conf->modules_parts[' // Sort on position $workflowcodes = dol_sort_array($workflowcodes, 'position'); -$nbqualified=0; -$oldfamily=''; +$nbqualified = 0; +$oldfamily = ''; -print ''."\n"; +print '
'."\n"; -foreach($workflowcodes as $key => $params) +foreach ($workflowcodes as $key => $params) { - $picto=$params['picto']; - $enabled=$params['enabled']; - $family=$params['family']; + $picto = $params['picto']; + $enabled = $params['enabled']; + $family = $params['family']; if ($family == 'separator') { print '

'; - print ''."\n"; + print '
'."\n"; continue; } - if (! verifCond($enabled)) continue; + if (!verifCond($enabled)) continue; $nbqualified++; @@ -156,20 +156,20 @@ foreach($workflowcodes as $key => $params) print "\n"; print "\n"; print '
".img_object('', $picto).$langs->trans('desc'.$key); - if (! empty($params['warning'])) + if (!empty($params['warning'])) { $langs->load("errors"); print ' '.img_warning($langs->transnoentitiesnoconv($params['warning'])); } print "'; - if (! empty($conf->use_javascript_ajax)) + if (!empty($conf->use_javascript_ajax)) { print ajax_constantonoff($key); } else { - if (! empty($conf->global->$key)) + if (!empty($conf->global->$key)) { print ''; print img_picto($langs->trans("Activated"), 'switch_on'); diff --git a/htdocs/api/admin/explorer.php b/htdocs/api/admin/explorer.php index 0fd34788adf..4e92873c384 100644 --- a/htdocs/api/admin/explorer.php +++ b/htdocs/api/admin/explorer.php @@ -64,18 +64,18 @@ foreach ($modulesdir as $dir) */ //dol_syslog("Scan directory ".$dir." for API modules"); - $handle=@opendir(dol_osencode($dir)); + $handle = @opendir(dol_osencode($dir)); if (is_resource($handle)) { - while (($file = readdir($handle))!==false) + while (($file = readdir($handle)) !== false) { if (is_readable($dir.$file) && preg_match("/^(mod.*)\.class\.php$/i", $file, $reg)) { - $modulename=$reg[1]; + $modulename = $reg[1]; // Defined if module is enabled - $enabled=true; - $module=$part=$obj=strtolower(preg_replace('/^mod/i', '', $modulename)); + $enabled = true; + $module = $part = $obj = strtolower(preg_replace('/^mod/i', '', $modulename)); //if ($part == 'propale') $part='propal'; if ($module == 'societe') { $obj = 'thirdparty'; @@ -91,10 +91,10 @@ foreach ($modulesdir as $dir) if ($module == 'ficheinter') { $obj = 'fichinter'; $part = 'fichinter'; - $module='fichinter'; + $module = 'fichinter'; } - if (empty($conf->$module->enabled)) $enabled=false; + if (empty($conf->$module->enabled)) $enabled = false; if ($enabled) { /* @@ -107,10 +107,10 @@ foreach ($modulesdir as $dir) */ $dir_part = DOL_DOCUMENT_ROOT.'/'.$part.'/class/'; - $handle_part=@opendir(dol_osencode($dir_part)); + $handle_part = @opendir(dol_osencode($dir_part)); if (is_resource($handle_part)) { - while (($file_searched = readdir($handle_part))!==false) + while (($file_searched = readdir($handle_part)) !== false) { if (is_readable($dir_part.$file_searched) && preg_match("/^api_(.*)\.class\.php$/i", $file_searched, $reg)) { @@ -160,43 +160,43 @@ foreach ($modulesdir as $dir) } //var_dump($listofapis); -$listofapis=Routes::toArray(); // TODO api for "status" is lost here +$listofapis = Routes::toArray(); // TODO api for "status" is lost here //var_dump($listofapis); llxHeader(); -$linkback=''.$langs->trans("BackToModuleList").''; +$linkback = ''.$langs->trans("BackToModuleList").''; print load_fiche_titre($langs->trans("ApiSetup"), $linkback, 'title_setup'); // Define $urlwithroot -$urlwithouturlroot=preg_replace('/'.preg_quote(DOL_URL_ROOT, '/').'$/i', '', trim($dolibarr_main_url_root)); -$urlwithroot=$urlwithouturlroot.DOL_URL_ROOT; // This is to use external domain name found into config file +$urlwithouturlroot = preg_replace('/'.preg_quote(DOL_URL_ROOT, '/').'$/i', '', trim($dolibarr_main_url_root)); +$urlwithroot = $urlwithouturlroot.DOL_URL_ROOT; // This is to use external domain name found into config file //$urlwithroot=DOL_MAIN_URL_ROOT; // This is to use same domain name than current // Show message print '
'; -$message=''; -$url=''.$urlwithroot.'/api/index.php/login?login='.urlencode($user->login).'&password=yourpassword[&reset=1]'; -$message.=$langs->trans("UrlToGetKeyToUseAPIs").':
'; -$message.=img_picto('', 'globe').' '.$url; +$message = ''; +$url = ''.$urlwithroot.'/api/index.php/login?login='.urlencode($user->login).'&password=yourpassword[&reset=1]'; +$message .= $langs->trans("UrlToGetKeyToUseAPIs").':
'; +$message .= img_picto('', 'globe').' '.$url; print $message; print '
'; print '
'; -$oldclass=''; +$oldclass = ''; print $langs->trans("ListOfAvailableAPIs").':
'; -foreach($listofapis['v1'] as $key => $val) +foreach ($listofapis['v1'] as $key => $val) { if ($key == 'login') continue; if ($key == 'index') continue; if ($key) { - foreach($val as $method => $val2) + foreach ($val as $method => $val2) { - $newclass=$val2['className']; + $newclass = $val2['className']; if (preg_match('/restler/i', $newclass)) continue; @@ -206,8 +206,8 @@ foreach($listofapis['v1'] as $key => $val) $oldclass = $newclass; } //print $key.' - '.$val['classname'].' - '.$val['fullpath']." - ".DOL_MAIN_URL_ROOT.'/api/index.php/'.strtolower(preg_replace('/Api$/','',$val['classname']))."/xxx
\n"; - $url=$urlwithroot.'/api/index.php/'.$key; - $url.='?api_key=token'; + $url = $urlwithroot.'/api/index.php/'.$key; + $url .= '?api_key=token'; print img_picto('', 'globe').' '.$method.' '.$url."
\n"; } } diff --git a/htdocs/api/admin/index.php b/htdocs/api/admin/index.php index f8a354683e0..00e804dec06 100644 --- a/htdocs/api/admin/index.php +++ b/htdocs/api/admin/index.php @@ -32,10 +32,10 @@ require_once DOL_DOCUMENT_ROOT.'/core/lib/files.lib.php'; // Load translation files required by the page $langs->load("admin"); -if (! $user->admin) +if (!$user->admin) accessforbidden(); -$action=GETPOST('action', 'aZ09'); +$action = GETPOST('action', 'aZ09'); //Activate ProfId if ($action == 'setproductionmode') @@ -44,7 +44,7 @@ if ($action == 'setproductionmode') if (dolibarr_set_const($db, 'API_PRODUCTION_MODE', $status, 'chaine', 0, '', 0) > 0) { - $error=0; + $error = 0; if ($status == 1) { @@ -84,7 +84,7 @@ if ($action == 'save') } -dol_mkdir(DOL_DATA_ROOT.'/api/temp'); // May have been deleted by a purge +dol_mkdir(DOL_DATA_ROOT.'/api/temp'); // May have been deleted by a purge /* @@ -93,7 +93,7 @@ dol_mkdir(DOL_DATA_ROOT.'/api/temp'); // May have been deleted by a purge llxHeader(); -$linkback=''.$langs->trans("BackToModuleList").''; +$linkback = ''.$langs->trans("BackToModuleList").''; print load_fiche_titre($langs->trans("ApiSetup"), $linkback, 'title_setup'); print $langs->trans("ApiDesc")."
\n"; @@ -103,7 +103,7 @@ print ''; print ''; print ''; -print ''; +print '
'; print ''; print ""; @@ -113,16 +113,16 @@ print ""; print ''; print ''; -$production_mode=(empty($conf->global->API_PRODUCTION_MODE)?false:true); +$production_mode = (empty($conf->global->API_PRODUCTION_MODE) ?false:true); if ($production_mode) { - print ''; } else { - print ''; } @@ -144,15 +144,15 @@ print ''; // Define $urlwithroot -$urlwithouturlroot=preg_replace('/'.preg_quote(DOL_URL_ROOT, '/').'$/i', '', trim($dolibarr_main_url_root)); -$urlwithroot=$urlwithouturlroot.DOL_URL_ROOT; // This is to use external domain name found into config file +$urlwithouturlroot = preg_replace('/'.preg_quote(DOL_URL_ROOT, '/').'$/i', '', trim($dolibarr_main_url_root)); +$urlwithroot = $urlwithouturlroot.DOL_URL_ROOT; // This is to use external domain name found into config file //$urlwithroot=DOL_MAIN_URL_ROOT; // This is to use same domain name than current // Show message -$message=''; -$url=$urlwithroot.'/api/index.php/login?login=auserlogin&password=thepassword[&reset=1]'; -$message.=$langs->trans("UrlToGetKeyToUseAPIs").':
'; -$message.=img_picto('', 'globe').' '.$url; +$message = ''; +$url = $urlwithroot.'/api/index.php/login?login=auserlogin&password=thepassword[&reset=1]'; +$message .= $langs->trans("UrlToGetKeyToUseAPIs").':
'; +$message .= img_picto('', 'globe').' '.$url; print $message; print '
'; print '
'; @@ -161,7 +161,7 @@ print '
'; print ''.$langs->trans("ApiExporerIs").':
'; if (dol_is_dir(DOL_DOCUMENT_ROOT.'/includes/restler/framework/Luracast/Restler/explorer')) { - $url=DOL_MAIN_URL_ROOT.'/api/index.php/explorer'; + $url = DOL_MAIN_URL_ROOT.'/api/index.php/explorer'; print img_picto('', 'globe').' '.$url."
\n"; } else diff --git a/htdocs/api/class/api_documents.class.php b/htdocs/api/class/api_documents.class.php index 1360d2657b7..448f5d15ed9 100644 --- a/htdocs/api/class/api_documents.class.php +++ b/htdocs/api/class/api_documents.class.php @@ -505,6 +505,11 @@ class Documents extends DolibarrApi throw new RestException(500, 'Error while fetching Task '.$ref); } } + 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); + } // TODO Implement additional moduleparts else { @@ -558,6 +563,11 @@ class Documents extends DolibarrApi $upload_dir = dol_sanitizePathName($upload_dir); + if (dol_mkdir($upload_dir) < 0) // needed by products + { + throw new RestException(500, 'Error while trying to create directory.'); + } + $destfile = $upload_dir . '/' . $original_file; $destfiletmp = DOL_DATA_ROOT.'/admin/temp/' . $original_file; dol_delete_file($destfiletmp); @@ -593,6 +603,67 @@ class Documents extends DolibarrApi return dol_basename($destfile); } + /** + * Delete a document. + * + * @param string $modulepart Name of module or area concerned by file download ('product', ...) + * @param string $original_file Relative path with filename, relative to modulepart (for example: PRODUCT-REF-999/IMAGE-999.jpg) + * @return array List of documents + * + * @throws 400 + * @throws 401 + * @throws 404 + * @throws 200 + * + * @url DELETE / + */ + public function delete($modulepart, $original_file) + { + global $conf, $langs; + + if (empty($modulepart)) { + throw new RestException(400, 'bad value for parameter modulepart'); + } + if (empty($original_file)) { + throw new RestException(400, 'bad value for parameter original_file'); + } + + //--- Finds and returns the document + $entity=$conf->entity; + + $check_access = dol_check_secure_access_document($modulepart, $original_file, $entity, DolibarrApiAccess::$user, '', 'read'); + $accessallowed = $check_access['accessallowed']; + $sqlprotectagainstexternals = $check_access['sqlprotectagainstexternals']; + $original_file = $check_access['original_file']; + + if (preg_match('/\.\./', $original_file) || preg_match('/[<>|]/', $original_file)) { + throw new RestException(401); + } + if (!$accessallowed) { + throw new RestException(401); + } + + $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)) + { + dol_syslog("Try to download not found file ".$original_file_osencoded, LOG_WARNING); + throw new RestException(404, 'File not found'); + } + + if (@unlink($original_file_osencoded)) { + return array( + 'success' => array( + 'code' => 200, + 'message' => 'Document deleted' + ) + ); + } + + throw new RestException(401); + } + // phpcs:disable PEAR.NamingConventions.ValidFunctionName /** * Validate fields before create or update object diff --git a/htdocs/api/class/api_setup.class.php b/htdocs/api/class/api_setup.class.php index b32eea1f57f..72ad45921d5 100644 --- a/htdocs/api/class/api_setup.class.php +++ b/htdocs/api/class/api_setup.class.php @@ -129,22 +129,22 @@ class Setup extends DolibarrApi $list = array(); $sql = "SELECT id, code, type, libelle as label, module"; - $sql.= " FROM ".MAIN_DB_PREFIX."c_paiement as t"; - $sql.= " WHERE t.entity IN (".getEntity('c_paiement').")"; - $sql.= " AND t.active = ".$active; + $sql .= " FROM ".MAIN_DB_PREFIX."c_paiement as t"; + $sql .= " WHERE t.entity IN (".getEntity('c_paiement').")"; + $sql .= " AND t.active = ".$active; // Add sql filters if ($sqlfilters) { - if (! DolibarrApi::_checkFilters($sqlfilters)) + if (!DolibarrApi::_checkFilters($sqlfilters)) { throw new RestException(400, 'error when validating parameter sqlfilters '.$sqlfilters); } - $regexstring='\(([^:\'\(\)]+:[^:\'\(\)]+:[^:\(\)]+)\)'; - $sql.=" AND (".preg_replace_callback('/'.$regexstring.'/', 'DolibarrApi::_forge_criteria_callback', $sqlfilters).")"; + $regexstring = '\(([^:\'\(\)]+:[^:\'\(\)]+:[^:\(\)]+)\)'; + $sql .= " AND (".preg_replace_callback('/'.$regexstring.'/', 'DolibarrApi::_forge_criteria_callback', $sqlfilters).")"; } - $sql.= $this->db->order($sortfield, $sortorder); + $sql .= $this->db->order($sortfield, $sortorder); if ($limit) { if ($page < 0) { @@ -198,19 +198,19 @@ class Setup extends DolibarrApi // Note: The filter is not applied in the SQL request because it must // be applied to the translated names, not to the names in database. $sql = "SELECT rowid FROM ".MAIN_DB_PREFIX."c_country as t"; - $sql.=" WHERE 1 = 1"; + $sql .= " WHERE 1 = 1"; // Add sql filters if ($sqlfilters) { - if (! DolibarrApi::_checkFilters($sqlfilters)) + if (!DolibarrApi::_checkFilters($sqlfilters)) { throw new RestException(503, 'Error when validating parameter sqlfilters '.$sqlfilters); } - $regexstring='\(([^:\'\(\)]+:[^:\'\(\)]+:[^:\(\)]+)\)'; - $sql.=" AND (".preg_replace_callback('/'.$regexstring.'/', 'DolibarrApi::_forge_criteria_callback', $sqlfilters).")"; + $regexstring = '\(([^:\'\(\)]+:[^:\'\(\)]+:[^:\(\)]+)\)'; + $sql .= " AND (".preg_replace_callback('/'.$regexstring.'/', 'DolibarrApi::_forge_criteria_callback', $sqlfilters).")"; } - $sql.= $this->db->order($sortfield, $sortorder); + $sql .= $this->db->order($sortfield, $sortorder); if ($limit) { if ($page < 0) { @@ -347,21 +347,21 @@ class Setup extends DolibarrApi $list = array(); $sql = "SELECT rowid, code, label"; - $sql.= " FROM ".MAIN_DB_PREFIX."c_availability as t"; - $sql.= " WHERE t.active = ".$active; + $sql .= " FROM ".MAIN_DB_PREFIX."c_availability as t"; + $sql .= " WHERE t.active = ".$active; // Add sql filters if ($sqlfilters) { - if (! DolibarrApi::_checkFilters($sqlfilters)) + if (!DolibarrApi::_checkFilters($sqlfilters)) { throw new RestException(400, 'error when validating parameter sqlfilters '.$sqlfilters); } - $regexstring='\(([^:\'\(\)]+:[^:\'\(\)]+:[^:\(\)]+)\)'; - $sql.=" AND (".preg_replace_callback('/'.$regexstring.'/', 'DolibarrApi::_forge_criteria_callback', $sqlfilters).")"; + $regexstring = '\(([^:\'\(\)]+:[^:\'\(\)]+:[^:\(\)]+)\)'; + $sql .= " AND (".preg_replace_callback('/'.$regexstring.'/', 'DolibarrApi::_forge_criteria_callback', $sqlfilters).")"; } - $sql.= $this->db->order($sortfield, $sortorder); + $sql .= $this->db->order($sortfield, $sortorder); if ($limit) { if ($page < 0) { @@ -515,23 +515,23 @@ class Setup extends DolibarrApi $list = array(); $sql = "SELECT id, code, type, libelle as label, module"; - $sql.= " FROM ".MAIN_DB_PREFIX."c_actioncomm as t"; - $sql.= " WHERE t.active = ".$active; - if ($type) $sql.=" AND t.type LIKE '%" . $this->db->escape($type) . "%'"; - if ($module) $sql.=" AND t.module LIKE '%" . $this->db->escape($module) . "%'"; + $sql .= " FROM ".MAIN_DB_PREFIX."c_actioncomm as t"; + $sql .= " WHERE t.active = ".$active; + if ($type) $sql .= " AND t.type LIKE '%".$this->db->escape($type)."%'"; + if ($module) $sql .= " AND t.module LIKE '%".$this->db->escape($module)."%'"; // Add sql filters if ($sqlfilters) { - if (! DolibarrApi::_checkFilters($sqlfilters)) + if (!DolibarrApi::_checkFilters($sqlfilters)) { throw new RestException(503, 'Error when validating parameter sqlfilters '.$sqlfilters); } - $regexstring='\(([^:\'\(\)]+:[^:\'\(\)]+:[^:\(\)]+)\)'; - $sql.=" AND (".preg_replace_callback('/'.$regexstring.'/', 'DolibarrApi::_forge_criteria_callback', $sqlfilters).")"; + $regexstring = '\(([^:\'\(\)]+:[^:\'\(\)]+:[^:\(\)]+)\)'; + $sql .= " AND (".preg_replace_callback('/'.$regexstring.'/', 'DolibarrApi::_forge_criteria_callback', $sqlfilters).")"; } - $sql.= $this->db->order($sortfield, $sortorder); + $sql .= $this->db->order($sortfield, $sortorder); if ($limit) { if ($page < 0) { @@ -579,23 +579,23 @@ class Setup extends DolibarrApi $list = array(); $sql = "SELECT rowid, code, element as type, libelle as label, source, module, position"; - $sql.= " FROM ".MAIN_DB_PREFIX."c_type_contact as t"; - $sql.= " WHERE t.active = ".$active; - if ($type) $sql.=" AND type LIKE '%" . $this->db->escape($type) . "%'"; - if ($module) $sql.=" AND t.module LIKE '%" . $this->db->escape($module) . "%'"; + $sql .= " FROM ".MAIN_DB_PREFIX."c_type_contact as t"; + $sql .= " WHERE t.active = ".$active; + if ($type) $sql .= " AND type LIKE '%".$this->db->escape($type)."%'"; + if ($module) $sql .= " AND t.module LIKE '%".$this->db->escape($module)."%'"; // Add sql filters if ($sqlfilters) { - if (! DolibarrApi::_checkFilters($sqlfilters)) + if (!DolibarrApi::_checkFilters($sqlfilters)) { throw new RestException(503, 'Error when validating parameter sqlfilters '.$sqlfilters); } - $regexstring='\(([^:\'\(\)]+:[^:\'\(\)]+:[^:\(\)]+)\)'; - $sql.=" AND (".preg_replace_callback('/'.$regexstring.'/', 'DolibarrApi::_forge_criteria_callback', $sqlfilters).")"; + $regexstring = '\(([^:\'\(\)]+:[^:\'\(\)]+:[^:\(\)]+)\)'; + $sql .= " AND (".preg_replace_callback('/'.$regexstring.'/', 'DolibarrApi::_forge_criteria_callback', $sqlfilters).")"; } - $sql.= $this->db->order($sortfield, $sortorder); + $sql .= $this->db->order($sortfield, $sortorder); if ($limit) { if ($page < 0) { @@ -642,22 +642,22 @@ class Setup extends DolibarrApi $list = array(); $sql = "SELECT rowid, code, label, module"; - $sql.= " FROM ".MAIN_DB_PREFIX."c_civility as t"; - $sql.= " WHERE t.active = ".$active; - if ($module) $sql.=" AND t.module LIKE '%" . $this->db->escape($module) . "%'"; + $sql .= " FROM ".MAIN_DB_PREFIX."c_civility as t"; + $sql .= " WHERE t.active = ".$active; + if ($module) $sql .= " AND t.module LIKE '%".$this->db->escape($module)."%'"; // Add sql filters if ($sqlfilters) { - if (! DolibarrApi::_checkFilters($sqlfilters)) + if (!DolibarrApi::_checkFilters($sqlfilters)) { throw new RestException(503, 'Error when validating parameter sqlfilters '.$sqlfilters); } - $regexstring='\(([^:\'\(\)]+:[^:\'\(\)]+:[^:\(\)]+)\)'; - $sql.=" AND (".preg_replace_callback('/'.$regexstring.'/', 'DolibarrApi::_forge_criteria_callback', $sqlfilters).")"; + $regexstring = '\(([^:\'\(\)]+:[^:\'\(\)]+:[^:\(\)]+)\)'; + $sql .= " AND (".preg_replace_callback('/'.$regexstring.'/', 'DolibarrApi::_forge_criteria_callback', $sqlfilters).")"; } - $sql.= $this->db->order($sortfield, $sortorder); + $sql .= $this->db->order($sortfield, $sortorder); if ($limit) { if ($page < 0) { @@ -703,33 +703,33 @@ class Setup extends DolibarrApi { $list = array(); $sql = "SELECT t.code_iso, t.label, t.unicode"; - if (!empty($multicurrency)) $sql.= " , cr.date_sync, cr.rate "; - $sql.= " FROM ".MAIN_DB_PREFIX."c_currencies as t"; + if (!empty($multicurrency)) $sql .= " , cr.date_sync, cr.rate "; + $sql .= " FROM ".MAIN_DB_PREFIX."c_currencies as t"; if (!empty($multicurrency)) { - $sql.= " JOIN ".MAIN_DB_PREFIX."multicurrency as m ON m.code=t.code_iso"; - $sql.= " JOIN ".MAIN_DB_PREFIX."multicurrency_rate as cr ON (m.rowid = cr.fk_multicurrency)"; + $sql .= " JOIN ".MAIN_DB_PREFIX."multicurrency as m ON m.code=t.code_iso"; + $sql .= " JOIN ".MAIN_DB_PREFIX."multicurrency_rate as cr ON (m.rowid = cr.fk_multicurrency)"; } - $sql.= " WHERE t.active = ".$active; + $sql .= " WHERE t.active = ".$active; if (!empty($multicurrency)) { - $sql.= " AND m.entity IN (".getEntity('multicurrency').")"; + $sql .= " AND m.entity IN (".getEntity('multicurrency').")"; if (!empty($multicurrency) && $multicurrency != 2) { - $sql.= " AND cr.date_sync = (SELECT MAX(cr2.date_sync) FROM ".MAIN_DB_PREFIX."multicurrency_rate AS cr2 WHERE cr2.fk_multicurrency = m.rowid)"; + $sql .= " AND cr.date_sync = (SELECT MAX(cr2.date_sync) FROM ".MAIN_DB_PREFIX."multicurrency_rate AS cr2 WHERE cr2.fk_multicurrency = m.rowid)"; } } // Add sql filters if ($sqlfilters) { - if (! DolibarrApi::_checkFilters($sqlfilters)) + if (!DolibarrApi::_checkFilters($sqlfilters)) { throw new RestException(503, 'Error when validating parameter sqlfilters '.$sqlfilters); } - $regexstring='\(([^:\'\(\)]+:[^:\'\(\)]+:[^:\(\)]+)\)'; - $sql.=" AND (".preg_replace_callback('/'.$regexstring.'/', 'DolibarrApi::_forge_criteria_callback', $sqlfilters).")"; + $regexstring = '\(([^:\'\(\)]+:[^:\'\(\)]+:[^:\(\)]+)\)'; + $sql .= " AND (".preg_replace_callback('/'.$regexstring.'/', 'DolibarrApi::_forge_criteria_callback', $sqlfilters).")"; } - $sql.= $this->db->order($sortfield, $sortorder); + $sql .= $this->db->order($sortfield, $sortorder); if ($limit) { if ($page < 0) { @@ -772,27 +772,27 @@ class Setup extends DolibarrApi { $list = array(); - if ($type == 'thirdparty') $type='societe'; - if ($type == 'contact') $type='socpeople'; + if ($type == 'thirdparty') $type = 'societe'; + if ($type == 'contact') $type = 'socpeople'; $sql = "SELECT t.rowid, t.name, t.label, t.type, t.size, t.elementtype, t.fieldunique, t.fieldrequired, t.param, t.pos, t.alwayseditable, t.perms, t.list, t.fielddefault, t.fieldcomputed"; - $sql.= " FROM ".MAIN_DB_PREFIX."extrafields as t"; - $sql.= " WHERE t.entity IN (".getEntity('extrafields').")"; - if (! empty($type)) $sql.= " AND t.elementtype = '".$this->db->escape($type)."'"; + $sql .= " FROM ".MAIN_DB_PREFIX."extrafields as t"; + $sql .= " WHERE t.entity IN (".getEntity('extrafields').")"; + if (!empty($type)) $sql .= " AND t.elementtype = '".$this->db->escape($type)."'"; // Add sql filters if ($sqlfilters) { - if (! DolibarrApi::_checkFilters($sqlfilters)) + if (!DolibarrApi::_checkFilters($sqlfilters)) { throw new RestException(503, 'Error when validating parameter sqlfilters '.$sqlfilters); } - $regexstring='\(([^:\'\(\)]+:[^:\'\(\)]+:[^:\(\)]+)\)'; - $sql.=" AND (".preg_replace_callback('/'.$regexstring.'/', 'DolibarrApi::_forge_criteria_callback', $sqlfilters).")"; + $regexstring = '\(([^:\'\(\)]+:[^:\'\(\)]+:[^:\(\)]+)\)'; + $sql .= " AND (".preg_replace_callback('/'.$regexstring.'/', 'DolibarrApi::_forge_criteria_callback', $sqlfilters).")"; } - $sql.= $this->db->order($sortfield, $sortorder); + $sql .= $this->db->order($sortfield, $sortorder); - $resql=$this->db->query($sql); + $resql = $this->db->query($sql); if ($resql) { if ($this->db->num_rows($resql)) @@ -800,19 +800,19 @@ class Setup extends DolibarrApi while ($tab = $this->db->fetch_object($resql)) { // New usage - $list[$tab->elementtype][$tab->name]['type']=$tab->type; - $list[$tab->elementtype][$tab->name]['label']=$tab->label; - $list[$tab->elementtype][$tab->name]['size']=$tab->size; - $list[$tab->elementtype][$tab->name]['elementtype']=$tab->elementtype; - $list[$tab->elementtype][$tab->name]['default']=$tab->fielddefault; - $list[$tab->elementtype][$tab->name]['computed']=$tab->fieldcomputed; - $list[$tab->elementtype][$tab->name]['unique']=$tab->fieldunique; - $list[$tab->elementtype][$tab->name]['required']=$tab->fieldrequired; - $list[$tab->elementtype][$tab->name]['param']=($tab->param ? unserialize($tab->param) : ''); - $list[$tab->elementtype][$tab->name]['pos']=$tab->pos; - $list[$tab->elementtype][$tab->name]['alwayseditable']=$tab->alwayseditable; - $list[$tab->elementtype][$tab->name]['perms']=$tab->perms; - $list[$tab->elementtype][$tab->name]['list']=$tab->list; + $list[$tab->elementtype][$tab->name]['type'] = $tab->type; + $list[$tab->elementtype][$tab->name]['label'] = $tab->label; + $list[$tab->elementtype][$tab->name]['size'] = $tab->size; + $list[$tab->elementtype][$tab->name]['elementtype'] = $tab->elementtype; + $list[$tab->elementtype][$tab->name]['default'] = $tab->fielddefault; + $list[$tab->elementtype][$tab->name]['computed'] = $tab->fieldcomputed; + $list[$tab->elementtype][$tab->name]['unique'] = $tab->fieldunique; + $list[$tab->elementtype][$tab->name]['required'] = $tab->fieldrequired; + $list[$tab->elementtype][$tab->name]['param'] = ($tab->param ? unserialize($tab->param) : ''); + $list[$tab->elementtype][$tab->name]['pos'] = $tab->pos; + $list[$tab->elementtype][$tab->name]['alwayseditable'] = $tab->alwayseditable; + $list[$tab->elementtype][$tab->name]['perms'] = $tab->perms; + $list[$tab->elementtype][$tab->name]['list'] = $tab->list; } } } @@ -821,7 +821,7 @@ class Setup extends DolibarrApi throw new RestException(503, 'Error when retrieving list of extra fields : '.$this->db->lasterror()); } - if (! count($list)) + if (!count($list)) { throw new RestException(404, 'No extrafield found'); } @@ -852,23 +852,23 @@ class Setup extends DolibarrApi $list = array(); $sql = "SELECT rowid AS id, zip, town, fk_county, fk_pays AS fk_country"; - $sql.= " FROM ".MAIN_DB_PREFIX."c_ziptown as t"; - $sql.= " AND t.active = ".$active; - if ($zipcode) $sql.=" AND t.zip LIKE '%" . $this->db->escape($zipcode) . "%'"; - if ($town) $sql.=" AND t.town LIKE '%" . $this->db->escape($town) . "%'"; + $sql .= " FROM ".MAIN_DB_PREFIX."c_ziptown as t"; + $sql .= " AND t.active = ".$active; + if ($zipcode) $sql .= " AND t.zip LIKE '%".$this->db->escape($zipcode)."%'"; + if ($town) $sql .= " AND t.town LIKE '%".$this->db->escape($town)."%'"; // Add sql filters if ($sqlfilters) { - if (! DolibarrApi::_checkFilters($sqlfilters)) + if (!DolibarrApi::_checkFilters($sqlfilters)) { throw new RestException(503, 'Error when validating parameter sqlfilters '.$sqlfilters); } - $regexstring='\(([^:\'\(\)]+:[^:\'\(\)]+:[^:\(\)]+)\)'; - $sql.=" AND (".preg_replace_callback('/'.$regexstring.'/', 'DolibarrApi::_forge_criteria_callback', $sqlfilters).")"; + $regexstring = '\(([^:\'\(\)]+:[^:\'\(\)]+:[^:\(\)]+)\)'; + $sql .= " AND (".preg_replace_callback('/'.$regexstring.'/', 'DolibarrApi::_forge_criteria_callback', $sqlfilters).")"; } - $sql.= $this->db->order($sortfield, $sortorder); + $sql .= $this->db->order($sortfield, $sortorder); if ($limit) { if ($page < 0) { @@ -916,22 +916,22 @@ class Setup extends DolibarrApi $list = array(); $sql = "SELECT rowid as id, code, sortorder, libelle as label, libelle_facture as descr, type_cdr, nbjour, decalage, module"; - $sql.= " FROM ".MAIN_DB_PREFIX."c_payment_term as t"; - $sql.= " WHERE t.entity IN (".getEntity('c_payment_term').")"; - $sql.= " AND t.active = ".$active; + $sql .= " FROM ".MAIN_DB_PREFIX."c_payment_term as t"; + $sql .= " WHERE t.entity IN (".getEntity('c_payment_term').")"; + $sql .= " AND t.active = ".$active; // Add sql filters if ($sqlfilters) { - if (! DolibarrApi::_checkFilters($sqlfilters)) + if (!DolibarrApi::_checkFilters($sqlfilters)) { throw new RestException(400, 'Error when validating parameter sqlfilters '.$sqlfilters); } - $regexstring='\(([^:\'\(\)]+:[^:\'\(\)]+:[^:\(\)]+)\)'; - $sql.=" AND (".preg_replace_callback('/'.$regexstring.'/', 'DolibarrApi::_forge_criteria_callback', $sqlfilters).")"; + $regexstring = '\(([^:\'\(\)]+:[^:\'\(\)]+:[^:\(\)]+)\)'; + $sql .= " AND (".preg_replace_callback('/'.$regexstring.'/', 'DolibarrApi::_forge_criteria_callback', $sqlfilters).")"; } - $sql.= $this->db->order($sortfield, $sortorder); + $sql .= $this->db->order($sortfield, $sortorder); if ($limit) { if ($page < 0) { @@ -977,18 +977,18 @@ class Setup extends DolibarrApi $list = array(); $sql = "SELECT rowid as id, code, libelle as label, description, tracking, module"; - $sql.= " FROM ".MAIN_DB_PREFIX."c_shipment_mode as t"; - $sql.= " WHERE t.entity IN (".getEntity('c_shipment_mode').")"; - $sql.= " AND t.active = ".$active; + $sql .= " FROM ".MAIN_DB_PREFIX."c_shipment_mode as t"; + $sql .= " WHERE t.entity IN (".getEntity('c_shipment_mode').")"; + $sql .= " AND t.active = ".$active; // Add sql filters if ($sqlfilters) { - if (! DolibarrApi::_checkFilters($sqlfilters)) + if (!DolibarrApi::_checkFilters($sqlfilters)) { throw new RestException(400, 'Error when validating parameter sqlfilters '.$sqlfilters); } - $regexstring='\(([^:\'\(\)]+:[^:\'\(\)]+:[^:\(\)]+)\)'; - $sql.=" AND (".preg_replace_callback('/'.$regexstring.'/', 'DolibarrApi::_forge_criteria_callback', $sqlfilters).")"; + $regexstring = '\(([^:\'\(\)]+:[^:\'\(\)]+:[^:\(\)]+)\)'; + $sql .= " AND (".preg_replace_callback('/'.$regexstring.'/', 'DolibarrApi::_forge_criteria_callback', $sqlfilters).")"; } @@ -1038,21 +1038,21 @@ class Setup extends DolibarrApi $list = array(); //TODO link with multicurrency module $sql = "SELECT t.rowid, t.code, t.label,t.short_label, t.active, t.scale, t.unit_type"; - $sql.= " FROM ".MAIN_DB_PREFIX."c_units as t"; - $sql.= " WHERE t.active = ".$active; + $sql .= " FROM ".MAIN_DB_PREFIX."c_units as t"; + $sql .= " WHERE t.active = ".$active; // Add sql filters if ($sqlfilters) { - if (! DolibarrApi::_checkFilters($sqlfilters)) + if (!DolibarrApi::_checkFilters($sqlfilters)) { throw new RestException(503, 'Error when validating parameter sqlfilters '.$sqlfilters); } - $regexstring='\(([^:\'\(\)]+:[^:\'\(\)]+:[^:\(\)]+)\)'; - $sql.=" AND (".preg_replace_callback('/'.$regexstring.'/', 'DolibarrApi::_forge_criteria_callback', $sqlfilters).")"; + $regexstring = '\(([^:\'\(\)]+:[^:\'\(\)]+:[^:\(\)]+)\)'; + $sql .= " AND (".preg_replace_callback('/'.$regexstring.'/', 'DolibarrApi::_forge_criteria_callback', $sqlfilters).")"; } - $sql.= $this->db->order($sortfield, $sortorder); + $sql .= $this->db->order($sortfield, $sortorder); if ($limit) { if ($page < 0) { @@ -1095,7 +1095,13 @@ class Setup extends DolibarrApi */ public function getListOfsocialNetworks($sortfield = "rowid", $sortorder = 'ASC', $limit = 100, $page = 0, $active = 1, $sqlfilters = '') { - $list = array(); + global $conf; + + if (empty($conf->socialnetworks->enabled)) { + throw new RestException(400, 'API not available: this dictionary is not enabled by setup'); + } + + $list = array(); //TODO link with multicurrency module $sql = "SELECT t.rowid, t.entity, t.code, t.label, t.url, t.icon, t.active"; $sql.= " FROM ".MAIN_DB_PREFIX."c_socialnetworks as t"; @@ -1159,21 +1165,21 @@ class Setup extends DolibarrApi $list = array(); $sql = "SELECT rowid, code, pos, label, use_default, description"; - $sql.= " FROM ".MAIN_DB_PREFIX."c_ticket_category as t"; - $sql.= " WHERE t.active = ".$active; + $sql .= " FROM ".MAIN_DB_PREFIX."c_ticket_category as t"; + $sql .= " WHERE t.active = ".$active; // Add sql filters if ($sqlfilters) { - if (! DolibarrApi::_checkFilters($sqlfilters)) + if (!DolibarrApi::_checkFilters($sqlfilters)) { throw new RestException(503, 'Error when validating parameter sqlfilters '.$sqlfilters); } - $regexstring='\(([^:\'\(\)]+:[^:\'\(\)]+:[^:\(\)]+)\)'; - $sql.=" AND (".preg_replace_callback('/'.$regexstring.'/', 'DolibarrApi::_forge_criteria_callback', $sqlfilters).")"; + $regexstring = '\(([^:\'\(\)]+:[^:\'\(\)]+:[^:\(\)]+)\)'; + $sql .= " AND (".preg_replace_callback('/'.$regexstring.'/', 'DolibarrApi::_forge_criteria_callback', $sqlfilters).")"; } - $sql.= $this->db->order($sortfield, $sortorder); + $sql .= $this->db->order($sortfield, $sortorder); if ($limit) { if ($page < 0) { @@ -1219,21 +1225,21 @@ class Setup extends DolibarrApi $list = array(); $sql = "SELECT rowid, code, pos, label, use_default, color, description"; - $sql.= " FROM ".MAIN_DB_PREFIX."c_ticket_severity as t"; - $sql.= " WHERE t.active = ".$active; + $sql .= " FROM ".MAIN_DB_PREFIX."c_ticket_severity as t"; + $sql .= " WHERE t.active = ".$active; // Add sql filters if ($sqlfilters) { - if (! DolibarrApi::_checkFilters($sqlfilters)) + if (!DolibarrApi::_checkFilters($sqlfilters)) { throw new RestException(503, 'Error when validating parameter sqlfilters '.$sqlfilters); } - $regexstring='\(([^:\'\(\)]+:[^:\'\(\)]+:[^:\(\)]+)\)'; - $sql.=" AND (".preg_replace_callback('/'.$regexstring.'/', 'DolibarrApi::_forge_criteria_callback', $sqlfilters).")"; + $regexstring = '\(([^:\'\(\)]+:[^:\'\(\)]+:[^:\(\)]+)\)'; + $sql .= " AND (".preg_replace_callback('/'.$regexstring.'/', 'DolibarrApi::_forge_criteria_callback', $sqlfilters).")"; } - $sql.= $this->db->order($sortfield, $sortorder); + $sql .= $this->db->order($sortfield, $sortorder); if ($limit) { if ($page < 0) { @@ -1279,23 +1285,23 @@ class Setup extends DolibarrApi $list = array(); $sql = "SELECT rowid, code, pos, label, use_default, description"; - $sql.= " FROM ".MAIN_DB_PREFIX."c_ticket_type as t"; - $sql.= " WHERE t.active = ".$active; - if ($type) $sql.=" AND t.type LIKE '%" . $this->db->escape($type) . "%'"; - if ($module) $sql.=" AND t.module LIKE '%" . $this->db->escape($module) . "%'"; + $sql .= " FROM ".MAIN_DB_PREFIX."c_ticket_type as t"; + $sql .= " WHERE t.active = ".$active; + if ($type) $sql .= " AND t.type LIKE '%".$this->db->escape($type)."%'"; + if ($module) $sql .= " AND t.module LIKE '%".$this->db->escape($module)."%'"; // Add sql filters if ($sqlfilters) { - if (! DolibarrApi::_checkFilters($sqlfilters)) + if (!DolibarrApi::_checkFilters($sqlfilters)) { throw new RestException(503, 'Error when validating parameter sqlfilters '.$sqlfilters); } - $regexstring='\(([^:\'\(\)]+:[^:\'\(\)]+:[^:\(\)]+)\)'; - $sql.=" AND (".preg_replace_callback('/'.$regexstring.'/', 'DolibarrApi::_forge_criteria_callback', $sqlfilters).")"; + $regexstring = '\(([^:\'\(\)]+:[^:\'\(\)]+:[^:\(\)]+)\)'; + $sql .= " AND (".preg_replace_callback('/'.$regexstring.'/', 'DolibarrApi::_forge_criteria_callback', $sqlfilters).")"; } - $sql.= $this->db->order($sortfield, $sortorder); + $sql .= $this->db->order($sortfield, $sortorder); if ($limit) { if ($page < 0) { @@ -1336,7 +1342,7 @@ class Setup extends DolibarrApi { global $langs, $conf; - if (! DolibarrApiAccess::$user->admin + if (!DolibarrApiAccess::$user->admin && (empty($conf->global->API_LOGIN_ALLOWED_FOR_INTEGRITY_CHECK) || DolibarrApiAccess::$user->login != $conf->global->API_LOGIN_ALLOWED_FOR_INTEGRITY_CHECK)) { throw new RestException(503, 'Error API open to admin users only or to login user defined with constant API_LOGIN_ALLOWED_FOR_INTEGRITY_CHECK'); @@ -1354,13 +1360,13 @@ class Setup extends DolibarrApi $file_list = array('missing' => array(), 'updated' => array()); // Local file to compare to - $xmlshortfile = GETPOST('xmlshortfile')?GETPOST('xmlshortfile'):'/install/filelist-'.DOL_VERSION.'.xml'; + $xmlshortfile = GETPOST('xmlshortfile') ?GETPOST('xmlshortfile') : '/install/filelist-'.DOL_VERSION.'.xml'; $xmlfile = DOL_DOCUMENT_ROOT.$xmlshortfile; // Remote file to compare to $xmlremote = ($target == 'default' ? '' : $target); - if (empty($xmlremote) && ! empty($conf->global->MAIN_FILECHECK_URL)) $xmlremote = $conf->global->MAIN_FILECHECK_URL; - $param='MAIN_FILECHECK_URL_'.DOL_VERSION; - if (empty($xmlremote) && ! empty($conf->global->$param)) $xmlremote = $conf->global->$param; + if (empty($xmlremote) && !empty($conf->global->MAIN_FILECHECK_URL)) $xmlremote = $conf->global->MAIN_FILECHECK_URL; + $param = 'MAIN_FILECHECK_URL_'.DOL_VERSION; + if (empty($xmlremote) && !empty($conf->global->$param)) $xmlremote = $conf->global->$param; if (empty($xmlremote)) $xmlremote = 'https://www.dolibarr.org/files/stable/signatures/filelist-'.DOL_VERSION.'.xml'; if ($target == 'local') @@ -1371,7 +1377,7 @@ class Setup extends DolibarrApi } else { - throw new RestException(500, $langs->trans('XmlNotFound') . ': ' . $xmlfile); + throw new RestException(500, $langs->trans('XmlNotFound').': '.$xmlfile); } } else @@ -1379,7 +1385,7 @@ class Setup extends DolibarrApi $xmlarray = getURLContent($xmlremote); // Return array('content'=>response,'curl_error_no'=>errno,'curl_error_msg'=>errmsg...) - if (! $xmlarray['curl_error_no'] && $xmlarray['http_code'] != '404') + if (!$xmlarray['curl_error_no'] && $xmlarray['http_code'] != '404') { $xmlfile = $xmlarray['content']; //print "xmlfilestart".$xmlfile."endxmlfile"; @@ -1387,7 +1393,7 @@ class Setup extends DolibarrApi } else { - $errormsg=$langs->trans('XmlNotFound') . ': ' . $xmlremote.' - '.$xmlarray['http_code'].' '.$xmlarray['curl_error_no'].' '.$xmlarray['curl_error_msg']; + $errormsg = $langs->trans('XmlNotFound').': '.$xmlremote.' - '.$xmlarray['http_code'].' '.$xmlarray['curl_error_no'].' '.$xmlarray['curl_error_msg']; throw new RestException(500, $errormsg); } } @@ -1403,83 +1409,83 @@ class Setup extends DolibarrApi // Forced constants if (is_object($xml->dolibarr_constants[0])) { - $out.=load_fiche_titre($langs->trans("ForcedConstants")); + $out .= load_fiche_titre($langs->trans("ForcedConstants")); - $out.='
'; - $out.='
".$langs->trans("Parameter")."
'.$langs->trans("ApiProductionMode").''; + print ''; print img_picto($langs->trans("Activated"), 'switch_on'); print ''; + print ''; print img_picto($langs->trans("Disabled"), 'switch_off'); print '
'; - $out.=''; - $out.=''; - $out.=''; - $out.=''; - $out.=''; - $out.=''."\n"; + $out .= '
'; + $out .= '
#' . $langs->trans("Constant") . '' . $langs->trans("ExpectedValue") . '' . $langs->trans("Value") . '
'; + $out .= ''; + $out .= ''; + $out .= ''; + $out .= ''; + $out .= ''; + $out .= ''."\n"; $i = 0; foreach ($xml->dolibarr_constants[0]->constant as $constant) // $constant is a simpleXMLElement { - $constname=$constant['name']; - $constvalue=(string) $constant; - $constvalue = (empty($constvalue)?'0':$constvalue); + $constname = $constant['name']; + $constvalue = (string) $constant; + $constvalue = (empty($constvalue) ? '0' : $constvalue); // Value found - $value=''; - if ($constname && $conf->global->$constname != '') $value=$conf->global->$constname; - $valueforchecksum=(empty($value)?'0':$value); + $value = ''; + if ($constname && $conf->global->$constname != '') $value = $conf->global->$constname; + $valueforchecksum = (empty($value) ? '0' : $value); - $checksumconcat[]=$valueforchecksum; + $checksumconcat[] = $valueforchecksum; $i++; - $out.=''; - $out.='' . "\n"; - $out.='' . "\n"; - $out.='' . "\n"; - $out.='' . "\n"; - $out.="\n"; + $out .= ''; + $out .= ''."\n"; + $out .= ''."\n"; + $out .= ''."\n"; + $out .= ''."\n"; + $out .= "\n"; } - if ($i==0) + if ($i == 0) { - $out.=''; + $out .= ''; } - $out.='
#'.$langs->trans("Constant").''.$langs->trans("ExpectedValue").''.$langs->trans("Value").'
'.$i.''.$constname.''.$constvalue.''.$valueforchecksum.'
'.$i.''.$constname.''.$constvalue.''.$valueforchecksum.'
'.$langs->trans("None").'
'.$langs->trans("None").'
'; - $out.=''; + $out .= '
'; + $out .= '
'; - $out.='
'; + $out .= '
'; } // Scan htdocs if (is_object($xml->dolibarr_htdocs_dir[0])) { //var_dump($xml->dolibarr_htdocs_dir[0]['includecustom']);exit; - $includecustom=(empty($xml->dolibarr_htdocs_dir[0]['includecustom'])?0:$xml->dolibarr_htdocs_dir[0]['includecustom']); + $includecustom = (empty($xml->dolibarr_htdocs_dir[0]['includecustom']) ? 0 : $xml->dolibarr_htdocs_dir[0]['includecustom']); // Defined qualified files (must be same than into generate_filelist_xml.php) - $regextoinclude='\.(php|css|html|js|json|tpl|jpg|png|gif|sql|lang)$'; - $regextoexclude='('.($includecustom?'':'custom|').'documents|conf|install|public\/test|Shared\/PCLZip|nusoap\/lib\/Mail|php\/example|php\/test|geoip\/sample.*\.php|ckeditor\/samples|ckeditor\/adapters)$'; // Exclude dirs + $regextoinclude = '\.(php|css|html|js|json|tpl|jpg|png|gif|sql|lang)$'; + $regextoexclude = '('.($includecustom ? '' : 'custom|').'documents|conf|install|public\/test|Shared\/PCLZip|nusoap\/lib\/Mail|php\/example|php\/test|geoip\/sample.*\.php|ckeditor\/samples|ckeditor\/adapters)$'; // Exclude dirs $scanfiles = dol_dir_list(DOL_DOCUMENT_ROOT, 'files', 1, $regextoinclude, $regextoexclude); // Fill file_list with files in signature, new files, modified files - $ret = getFilesUpdated($file_list, $xml->dolibarr_htdocs_dir[0], '', DOL_DOCUMENT_ROOT, $checksumconcat); // Fill array $file_list + $ret = getFilesUpdated($file_list, $xml->dolibarr_htdocs_dir[0], '', DOL_DOCUMENT_ROOT, $checksumconcat); // Fill array $file_list // Complete with list of new files foreach ($scanfiles as $keyfile => $valfile) { - $tmprelativefilename=preg_replace('/^'.preg_quote(DOL_DOCUMENT_ROOT, '/').'/', '', $valfile['fullname']); - if (! in_array($tmprelativefilename, $file_list['insignature'])) + $tmprelativefilename = preg_replace('/^'.preg_quote(DOL_DOCUMENT_ROOT, '/').'/', '', $valfile['fullname']); + if (!in_array($tmprelativefilename, $file_list['insignature'])) { - $md5newfile=@md5_file($valfile['fullname']); // Can fails if we don't have permission to open/read file - $file_list['added'][]=array('filename'=>$tmprelativefilename, 'md5'=>$md5newfile); + $md5newfile = @md5_file($valfile['fullname']); // Can fails if we don't have permission to open/read file + $file_list['added'][] = array('filename'=>$tmprelativefilename, 'md5'=>$md5newfile); } } // Files missings - $out.=load_fiche_titre($langs->trans("FilesMissing")); + $out .= load_fiche_titre($langs->trans("FilesMissing")); - $out.='
'; - $out.=''; - $out.=''; - $out.=''; - $out.=''; - $out.=''; - $out.=''."\n"; + $out .= '
'; + $out .= '
#' . $langs->trans("Filename") . '' . $langs->trans("ExpectedChecksum") . '
'; + $out .= ''; + $out .= ''; + $out .= ''; + $out .= ''; + $out .= ''."\n"; $tmpfilelist = dol_sort_array($file_list['missing'], 'filename'); if (is_array($tmpfilelist) && count($tmpfilelist)) { @@ -1487,36 +1493,36 @@ class Setup extends DolibarrApi foreach ($tmpfilelist as $file) { $i++; - $out.=''; - $out.='' . "\n"; - $out.='' . "\n"; - $out.='' . "\n"; - $out.="\n"; + $out .= ''; + $out .= ''."\n"; + $out .= ''."\n"; + $out .= ''."\n"; + $out .= "\n"; } } else { - $out.=''; + $out .= ''; } - $out.='
#'.$langs->trans("Filename").''.$langs->trans("ExpectedChecksum").'
'.$i.''.$file['filename'].''.$file['expectedmd5'].'
'.$i.''.$file['filename'].''.$file['expectedmd5'].'
'.$langs->trans("None").'
'.$langs->trans("None").'
'; - $out.='
'; + $out .= '
'; + $out .= '
'; - $out.='
'; + $out .= '
'; // Files modified - $out.=load_fiche_titre($langs->trans("FilesModified")); + $out .= load_fiche_titre($langs->trans("FilesModified")); - $totalsize=0; - $out.='
'; - $out.=''; - $out.=''; - $out.=''; - $out.=''; - $out.=''; - $out.=''; - $out.=''; - $out.=''; - $out.=''."\n"; + $totalsize = 0; + $out .= '
'; + $out .= '
#' . $langs->trans("Filename") . '' . $langs->trans("ExpectedChecksum") . '' . $langs->trans("CurrentChecksum") . '' . $langs->trans("Size") . '' . $langs->trans("DateModification") . '
'; + $out .= ''; + $out .= ''; + $out .= ''; + $out .= ''; + $out .= ''; + $out .= ''; + $out .= ''; + $out .= ''."\n"; $tmpfilelist2 = dol_sort_array($file_list['updated'], 'filename'); if (is_array($tmpfilelist2) && count($tmpfilelist2)) { @@ -1524,49 +1530,49 @@ class Setup extends DolibarrApi foreach ($tmpfilelist2 as $file) { $i++; - $out.=''; - $out.='' . "\n"; - $out.='' . "\n"; - $out.='' . "\n"; - $out.='' . "\n"; + $out .= ''; + $out .= ''."\n"; + $out .= ''."\n"; + $out .= ''."\n"; + $out .= ''."\n"; $size = dol_filesize(DOL_DOCUMENT_ROOT.'/'.$file['filename']); $totalsize += $size; - $out.='' . "\n"; - $out.='' . "\n"; - $out.="\n"; + $out .= ''."\n"; + $out .= ''."\n"; + $out .= "\n"; } - $out.=''; - $out.='' . "\n"; - $out.='' . "\n"; - $out.='' . "\n"; - $out.='' . "\n"; - $out.='' . "\n"; - $out.='' . "\n"; - $out.="\n"; + $out .= ''; + $out .= ''."\n"; + $out .= ''."\n"; + $out .= ''."\n"; + $out .= ''."\n"; + $out .= ''."\n"; + $out .= ''."\n"; + $out .= "\n"; } else { - $out.=''; + $out .= ''; } - $out.='
#'.$langs->trans("Filename").''.$langs->trans("ExpectedChecksum").''.$langs->trans("CurrentChecksum").''.$langs->trans("Size").''.$langs->trans("DateModification").'
'.$i.''.$file['filename'].''.$file['expectedmd5'].''.$file['md5'].'
'.$i.''.$file['filename'].''.$file['expectedmd5'].''.$file['md5'].''.dol_print_size($size).''.dol_print_date(dol_filemtime(DOL_DOCUMENT_ROOT.'/'.$file['filename']), 'dayhour').'
'.dol_print_size($size).''.dol_print_date(dol_filemtime(DOL_DOCUMENT_ROOT.'/'.$file['filename']), 'dayhour').'
'.$langs->trans("Total").''.dol_print_size($totalsize).'
'.$langs->trans("Total").''.dol_print_size($totalsize).'
'.$langs->trans("None").'
'.$langs->trans("None").'
'; - $out.='
'; + $out .= '
'; + $out .= '
'; - $out.='
'; + $out .= '
'; // Files added - $out.=load_fiche_titre($langs->trans("FilesAdded")); + $out .= load_fiche_titre($langs->trans("FilesAdded")); $totalsize = 0; - $out.='
'; - $out.=''; - $out.=''; - $out.=''; - $out.=''; - $out.=''; - $out.=''; - $out.=''; - $out.=''; - $out.=''."\n"; + $out .= '
'; + $out .= '
#' . $langs->trans("Filename") . '' . $langs->trans("ExpectedChecksum") . '' . $langs->trans("CurrentChecksum") . '' . $langs->trans("Size") . '' . $langs->trans("DateModification") . '
'; + $out .= ''; + $out .= ''; + $out .= ''; + $out .= ''; + $out .= ''; + $out .= ''; + $out .= ''; + $out .= ''."\n"; $tmpfilelist3 = dol_sort_array($file_list['added'], 'filename'); if (is_array($tmpfilelist3) && count($tmpfilelist3)) { @@ -1574,32 +1580,32 @@ class Setup extends DolibarrApi foreach ($tmpfilelist3 as $file) { $i++; - $out.=''; - $out.='' . "\n"; - $out.='' . "\n"; - $out.='' . "\n"; - $out.='' . "\n"; + $out .= ''; + $out .= ''."\n"; + $out .= ''."\n"; + $out .= ''."\n"; + $out .= ''."\n"; $size = dol_filesize(DOL_DOCUMENT_ROOT.'/'.$file['filename']); $totalsize += $size; - $out.='' . "\n"; - $out.='' . "\n"; - $out.="\n"; + $out .= ''."\n"; + $out .= ''."\n"; + $out .= "\n"; } - $out.=''; - $out.='' . "\n"; - $out.='' . "\n"; - $out.='' . "\n"; - $out.='' . "\n"; - $out.='' . "\n"; - $out.='' . "\n"; - $out.="\n"; + $out .= ''; + $out .= ''."\n"; + $out .= ''."\n"; + $out .= ''."\n"; + $out .= ''."\n"; + $out .= ''."\n"; + $out .= ''."\n"; + $out .= "\n"; } else { - $out.=''; + $out .= ''; } - $out.='
#'.$langs->trans("Filename").''.$langs->trans("ExpectedChecksum").''.$langs->trans("CurrentChecksum").''.$langs->trans("Size").''.$langs->trans("DateModification").'
'.$i.''.$file['filename'].''.$file['expectedmd5'].''.$file['md5'].'
'.$i.''.$file['filename'].''.$file['expectedmd5'].''.$file['md5'].''.dol_print_size($size).''.dol_print_date(dol_filemtime(DOL_DOCUMENT_ROOT.'/'.$file['filename']), 'dayhour').'
'.dol_print_size($size).''.dol_print_date(dol_filemtime(DOL_DOCUMENT_ROOT.'/'.$file['filename']), 'dayhour').'
'.$langs->trans("Total").''.dol_print_size($totalsize).'
'.$langs->trans("Total").''.dol_print_size($totalsize).'
'.$langs->trans("None").'
'.$langs->trans("None").'
'; - $out.='
'; + $out .= '
'; + $out .= ''; // Show warning @@ -1632,24 +1638,24 @@ class Setup extends DolibarrApi if (count($file_list['added'])) { $resultcode = 'warning'; - $resultcomment='FileIntegrityIsOkButFilesWereAdded'; + $resultcomment = 'FileIntegrityIsOkButFilesWereAdded'; //$outcurrentchecksum = $checksumget.' - '.$langs->trans("FileIntegrityIsOkButFilesWereAdded").''; - $outcurrentchecksum = $checksumget; + $outcurrentchecksum = $checksumget; } else { $resultcode = 'ok'; - $resultcomment='Success'; + $resultcomment = 'Success'; //$outcurrentchecksum = ''.$checksumget.''; - $outcurrentchecksum = $checksumget; + $outcurrentchecksum = $checksumget; } } else { $resultcode = 'error'; - $resultcomment='Error'; + $resultcomment = 'Error'; //$outcurrentchecksum = ''.$checksumget.''; - $outcurrentchecksum = $checksumget; + $outcurrentchecksum = $checksumget; } } else { diff --git a/htdocs/asset/admin/setup.php b/htdocs/asset/admin/setup.php index 77d16820a43..1aee94fb715 100644 --- a/htdocs/asset/admin/setup.php +++ b/htdocs/asset/admin/setup.php @@ -24,7 +24,7 @@ require '../../main.inc.php'; require_once DOL_DOCUMENT_ROOT.'/core/lib/asset.lib.php'; -require_once DOL_DOCUMENT_ROOT . "/core/lib/admin.lib.php"; +require_once DOL_DOCUMENT_ROOT."/core/lib/admin.lib.php"; global $langs, $user; @@ -32,13 +32,13 @@ global $langs, $user; $langs->loadLangs(array("admin", "assets")); // Access control -if (! $user->admin) accessforbidden(); +if (!$user->admin) accessforbidden(); // Parameters $action = GETPOST('action', 'alpha'); $backtopage = GETPOST('backtopage', 'alpha'); -$arrayofparameters=array('FIXEDASSETS_MYPARAM1'=>array('css'=>'minwidth200'), 'FIXEDASSETS_MYPARAM2'=>array('css'=>'minwidth500')); +$arrayofparameters = array('FIXEDASSETS_MYPARAM1'=>array('css'=>'minwidth200'), 'FIXEDASSETS_MYPARAM2'=>array('css'=>'minwidth500')); /* @@ -54,7 +54,7 @@ include DOL_DOCUMENT_ROOT.'/core/actions_setmoduleoptions.inc.php'; llxHeader('', $langs->trans("AssetsSetup")); -$linkback=''.$langs->trans("BackToModuleList").''; +$linkback = ''.$langs->trans("BackToModuleList").''; print load_fiche_titre($langs->trans("AssetsSetup"), $linkback, 'title_setup'); @@ -69,14 +69,14 @@ if ($action == 'edit') print ''; print ''; - print ''; + print '
'; print ''; - foreach($arrayofparameters as $key => $val) + foreach ($arrayofparameters as $key => $val) { print ''; + print ''; } print '
'.$langs->trans("Parameter").''.$langs->trans("Value").'
'; print $form->textwithpicto($langs->trans($key), $langs->trans($key.'Tooltip')); - print '
'; @@ -90,14 +90,14 @@ if ($action == 'edit') } else { - print ''; + print '
'; print ''; - foreach($arrayofparameters as $key => $val) + foreach ($arrayofparameters as $key => $val) { print ''; + print ''; } print '
'.$langs->trans("Parameter").''.$langs->trans("Value").'
'; print $form->textwithpicto($langs->trans($key), $langs->trans($key.'Tooltip')); - print '' . $conf->global->$key . '
'.$conf->global->$key.'
'; diff --git a/htdocs/asset/card.php b/htdocs/asset/card.php index ddde75ee463..1f6966fcd15 100644 --- a/htdocs/asset/card.php +++ b/htdocs/asset/card.php @@ -39,25 +39,25 @@ $cancel = GETPOST('cancel', 'aZ09'); $backtopage = GETPOST('backtopage', 'alpha'); // Initialize technical objects -$object=new Asset($db); +$object = new Asset($db); $extrafields = new ExtraFields($db); -$diroutputmassaction=$conf->asset->dir_output . '/temp/massgeneration/'.$user->id; -$hookmanager->initHooks(array('assetcard')); // Note that conf->hooks_modules contains array +$diroutputmassaction = $conf->asset->dir_output.'/temp/massgeneration/'.$user->id; +$hookmanager->initHooks(array('assetcard')); // 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_'); +$search_array_options = $extrafields->getOptionalsFromPost($object->table_element, '', 'search_'); // Initialize array of search criterias -$search_all=trim(GETPOST("search_all", 'alpha')); -$search=array(); -foreach($object->fields as $key => $val) +$search_all = trim(GETPOST("search_all", 'alpha')); +$search = array(); +foreach ($object->fields as $key => $val) { - if (GETPOST('search_'.$key, 'alpha')) $search[$key]=GETPOST('search_'.$key, 'alpha'); + 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) access_forbidden(); @@ -65,11 +65,11 @@ if (empty($action) && empty($id) && empty($ref)) $action='view'; //$result = restrictedArea($user, 'asset', $id); // Load object -include DOL_DOCUMENT_ROOT.'/core/actions_fetchobject.inc.php'; // Must be include, not include_once. +include DOL_DOCUMENT_ROOT.'/core/actions_fetchobject.inc.php'; // Must be include, not include_once. -$permissionnote=$user->rights->asset->write; // Used by the include of actions_setnotes.inc.php -$permissiondellink=$user->rights->asset->write; // Used by the include of actions_dellink.inc.php -$permissiontoadd=$user->rights->asset->write; // Used by the include of actions_addupdatedelete.inc.php and actions_lineupdown.inc.php +$permissionnote = $user->rights->asset->write; // Used by the include of actions_setnotes.inc.php +$permissiondellink = $user->rights->asset->write; // Used by the include of actions_dellink.inc.php +$permissiontoadd = $user->rights->asset->write; // Used by the include of actions_addupdatedelete.inc.php and actions_lineupdown.inc.php /* @@ -78,13 +78,13 @@ $permissiontoadd=$user->rights->asset->write; // Used by the include of actions * Put here all code to do according to value of "action" parameter */ -$parameters=array(); -$reshook=$hookmanager->executeHooks('doActions', $parameters, $object, $action); // Note that $action and $object may have been modified by some hooks +$parameters = array(); +$reshook = $hookmanager->executeHooks('doActions', $parameters, $object, $action); // Note that $action and $object may have been modified by some hooks if ($reshook < 0) setEventMessages($hookmanager->error, $hookmanager->errors, 'errors'); if (empty($reshook)) { - $error=0; + $error = 0; $permissiontoadd = $user->rights->asset->create; $permissiontodelete = $user->rights->asset->delete; @@ -97,9 +97,9 @@ if (empty($reshook)) include DOL_DOCUMENT_ROOT.'/core/actions_printing.inc.php'; // Actions to send emails - $trigger_name='ASSET_SENTBYMAIL'; - $autocopy='MAIN_MAIL_AUTOCOPY_ASSET_TO'; - $trackid='asset'.$object->id; + $trigger_name = 'ASSET_SENTBYMAIL'; + $autocopy = 'MAIN_MAIL_AUTOCOPY_ASSET_TO'; + $trackid = 'asset'.$object->id; include DOL_DOCUMENT_ROOT.'/core/actions_sendmails.inc.php'; } @@ -112,11 +112,11 @@ if (empty($reshook)) * Put here all code to build page */ -$form=new Form($db); -$formfile=new FormFile($db); +$form = new Form($db); +$formfile = new FormFile($db); -$title=$langs->trans("Assets").' - '.$langs->trans("Card"); -$help_url=''; +$title = $langs->trans("Assets").' - '.$langs->trans("Card"); +$help_url = ''; llxHeader('', $title, $help_url); // Example : Adding jquery code @@ -150,10 +150,10 @@ if ($action == 'create') print ''."\n"; // Common attributes - include DOL_DOCUMENT_ROOT . '/core/tpl/commonfields_add.tpl.php'; + include DOL_DOCUMENT_ROOT.'/core/tpl/commonfields_add.tpl.php'; // Other attributes - include DOL_DOCUMENT_ROOT . '/core/tpl/extrafields_add.tpl.php'; + include DOL_DOCUMENT_ROOT.'/core/tpl/extrafields_add.tpl.php'; print '
'."\n"; @@ -162,7 +162,7 @@ if ($action == 'create') print '
'; print ''; print '  '; - print ''; // Cancel for create does not post form if we don't know the backtopage + print ''; // Cancel for create does not post form if we don't know the backtopage print '
'; print ''; @@ -184,10 +184,10 @@ if (($id || $ref) && $action == 'edit') print ''."\n"; // Common attributes - include DOL_DOCUMENT_ROOT . '/core/tpl/commonfields_edit.tpl.php'; + include DOL_DOCUMENT_ROOT.'/core/tpl/commonfields_edit.tpl.php'; // Other attributes - include DOL_DOCUMENT_ROOT . '/core/tpl/extrafields_edit.tpl.php'; + include DOL_DOCUMENT_ROOT.'/core/tpl/extrafields_edit.tpl.php'; print '
'; @@ -213,21 +213,21 @@ if ($object->id > 0 && (empty($action) || ($action != 'edit' && $action != 'crea // Confirmation to delete if ($action == 'delete') { - $formconfirm = $form->formconfirm($_SERVER["PHP_SELF"] . '?id=' . $object->id, $langs->trans('DeleteAssets'), $langs->trans('ConfirmDeleteAssets'), 'confirm_delete', '', 0, 1); + $formconfirm = $form->formconfirm($_SERVER["PHP_SELF"].'?id='.$object->id, $langs->trans('DeleteAssets'), $langs->trans('ConfirmDeleteAssets'), 'confirm_delete', '', 0, 1); } // Confirmation of action xxxx if ($action == 'xxx') { - $formquestion=array(); - $formconfirm = $form->formconfirm($_SERVER["PHP_SELF"] . '?id=' . $object->id, $langs->trans('XXX'), $text, 'confirm_xxx', $formquestion, 0, 1, 220); + $formquestion = array(); + $formconfirm = $form->formconfirm($_SERVER["PHP_SELF"].'?id='.$object->id, $langs->trans('XXX'), $text, 'confirm_xxx', $formquestion, 0, 1, 220); } // Call Hook formConfirm $parameters = array('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; @@ -235,9 +235,9 @@ if ($object->id > 0 && (empty($action) || ($action != 'edit' && $action != 'crea // Object card // ------------------------------------------------------------ - $linkback = '' . $langs->trans("BackToList") . ''; + $linkback = ''.$langs->trans("BackToList").''; - $morehtmlref='
'; + $morehtmlref = '
'; /* // Ref bis $morehtmlref.=$form->editfieldkey("RefBis", 'ref_client', $object->ref_client, $object, $user->rights->asset->creer, 'string', '', 0, 1); @@ -245,7 +245,7 @@ if ($object->id > 0 && (empty($action) || ($action != 'edit' && $action != 'crea // Thirdparty $morehtmlref.='
'.$langs->trans('ThirdParty') . ' : ' . $soc->getNomUrl(1); */ - $morehtmlref.='
'; + $morehtmlref .= '
'; dol_banner_tab($object, 'ref', $linkback, 1, 'ref', 'ref', $morehtmlref); @@ -256,10 +256,10 @@ if ($object->id > 0 && (empty($action) || ($action != 'edit' && $action != 'crea // Common attributes //$keyforbreak='fieldkeytoswithonsecondcolumn'; - include DOL_DOCUMENT_ROOT . '/core/tpl/commonfields_view.tpl.php'; + include DOL_DOCUMENT_ROOT.'/core/tpl/commonfields_view.tpl.php'; // Other attributes - include DOL_DOCUMENT_ROOT . '/core/tpl/extrafields_view.tpl.php'; + include DOL_DOCUMENT_ROOT.'/core/tpl/extrafields_view.tpl.php'; print '
'; print '
'; @@ -274,14 +274,14 @@ if ($object->id > 0 && (empty($action) || ($action != 'edit' && $action != 'crea // Buttons for actions if ($action != 'presend' && $action != 'editline') { print '
'."\n"; - $parameters=array(); - $reshook=$hookmanager->executeHooks('addMoreActionsButtons', $parameters, $object, $action); // Note that $action and $object may have been modified by hook + $parameters = array(); + $reshook = $hookmanager->executeHooks('addMoreActionsButtons', $parameters, $object, $action); // Note that $action and $object may have been modified by hook if ($reshook < 0) setEventMessages($hookmanager->error, $hookmanager->errors, 'errors'); if (empty($reshook)) { // Send - print '' . $langs->trans('SendMail') . ''."\n"; + print ''.$langs->trans('SendMail').''."\n"; if ($user->rights->asset->write) { @@ -335,11 +335,11 @@ if ($object->id > 0 && (empty($action) || ($action != 'edit' && $action != 'crea $MAXEVENT = 10; $morehtmlright = ''; - $morehtmlright.= $langs->trans("SeeAll"); - $morehtmlright.= ''; + $morehtmlright .= $langs->trans("SeeAll"); + $morehtmlright .= ''; // List of actions on element - include_once DOL_DOCUMENT_ROOT . '/core/class/html.formactions.class.php'; + include_once DOL_DOCUMENT_ROOT.'/core/class/html.formactions.class.php'; $formactions = new FormActions($db); $somethingshown = $formactions->showactions($object, 'asset', $socid, 1, '', $MAXEVENT, '', $morehtmlright); diff --git a/htdocs/asset/document.php b/htdocs/asset/document.php index 976b8974f5a..3c91c91a675 100644 --- a/htdocs/asset/document.php +++ b/htdocs/asset/document.php @@ -31,12 +31,12 @@ require_once DOL_DOCUMENT_ROOT.'/core/lib/images.lib.php'; require_once DOL_DOCUMENT_ROOT.'/core/class/html.formfile.class.php'; // Load translation files required by the page -$langs->loadLangs(array("assets","companies")); +$langs->loadLangs(array("assets", "companies")); -$action=GETPOST('action', 'aZ09'); -$confirm=GETPOST('confirm'); -$id=(GETPOST('socid', 'int') ? GETPOST('socid', 'int') : GETPOST('id', 'int')); +$action = GETPOST('action', 'aZ09'); +$confirm = GETPOST('confirm'); +$id = (GETPOST('socid', 'int') ? GETPOST('socid', 'int') : GETPOST('id', 'int')); $ref = GETPOST('ref', 'alpha'); // Security check - Protection if external user @@ -52,23 +52,23 @@ if (empty($page) || $page == -1) { $page = 0; } // If $page is not defined, $offset = $conf->liste_limit * $page; $pageprev = $page - 1; $pagenext = $page + 1; -if (! $sortorder) $sortorder="ASC"; -if (! $sortfield) $sortfield="name"; +if (!$sortorder) $sortorder = "ASC"; +if (!$sortfield) $sortfield = "name"; // Initialize technical objects -$object=new Asset($db); +$object = new Asset($db); $extrafields = new ExtraFields($db); -$diroutputmassaction=$conf->assets->dir_output . '/temp/massgeneration/'.$user->id; -$hookmanager->initHooks(array('assetdocument')); // Note that conf->hooks_modules contains array +$diroutputmassaction = $conf->assets->dir_output.'/temp/massgeneration/'.$user->id; +$hookmanager->initHooks(array('assetdocument')); // Note that conf->hooks_modules contains array // 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 // Must be include, not include_once. Include fetch and fetch_thirdparty but not fetch_optionals +include DOL_DOCUMENT_ROOT.'/core/actions_fetchobject.inc.php'; // Must be include, not include_once // Must be include, not include_once. Include fetch and fetch_thirdparty but not fetch_optionals //if ($id > 0 || ! empty($ref)) $upload_dir = $conf->sellyoursaas->multidir_output[$object->entity] . "/packages/" . dol_sanitizeFileName($object->id); -if ($id > 0 || ! empty($ref)) $upload_dir = $conf->sellyoursaas->multidir_output[$object->entity] . "/packages/" . dol_sanitizeFileName($object->ref); +if ($id > 0 || !empty($ref)) $upload_dir = $conf->sellyoursaas->multidir_output[$object->entity]."/packages/".dol_sanitizeFileName($object->ref); @@ -76,7 +76,7 @@ if ($id > 0 || ! empty($ref)) $upload_dir = $conf->sellyoursaas->multidir_output * Actions */ -include_once DOL_DOCUMENT_ROOT . '/core/actions_linkedfiles.inc.php'; +include_once DOL_DOCUMENT_ROOT.'/core/actions_linkedfiles.inc.php'; /* @@ -85,8 +85,8 @@ include_once DOL_DOCUMENT_ROOT . '/core/actions_linkedfiles.inc.php'; $form = new Form($db); -$title=$langs->trans("Assets").' - '.$langs->trans("Files"); -$help_url=''; +$title = $langs->trans("Assets").' - '.$langs->trans("Files"); +$help_url = ''; //$help_url='EN:Module_Third_Parties|FR:Module_Tiers|ES:Empresas'; llxHeader('', $title, $help_url); @@ -95,23 +95,23 @@ if ($object->id) /* * Show tabs */ - if (! empty($conf->notification->enabled)) $langs->load("mails"); + if (!empty($conf->notification->enabled)) $langs->load("mails"); $head = asset_prepare_head($object); dol_fiche_head($head, 'document', $langs->trans("Asset"), -1, 'generic'); // 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) + $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) { - $totalsize+=$file['size']; + $totalsize += $file['size']; } // Object card // ------------------------------------------------------------ - $linkback = '' . $langs->trans("BackToList") . ''; + $linkback = ''.$langs->trans("BackToList").''; dol_banner_tab($object, 'ref', $linkback, 1, 'ref', 'ref', $morehtmlref); @@ -137,12 +137,12 @@ if ($object->id) $permission = 1; //$permtoedit = $user->rights->asset->create; $permtoedit = 1; - $param = '&id=' . $object->id; + $param = '&id='.$object->id; //$relativepathwithnofile='asset/' . dol_sanitizeFileName($object->id).'/'; - $relativepathwithnofile='asset/' . dol_sanitizeFileName($object->ref).'/'; + $relativepathwithnofile = 'asset/'.dol_sanitizeFileName($object->ref).'/'; - include_once DOL_DOCUMENT_ROOT . '/core/tpl/document_actions_post_headers.tpl.php'; + include_once DOL_DOCUMENT_ROOT.'/core/tpl/document_actions_post_headers.tpl.php'; } else { diff --git a/htdocs/asset/list.php b/htdocs/asset/list.php index c43bd73eae8..9d480eccebe 100644 --- a/htdocs/asset/list.php +++ b/htdocs/asset/list.php @@ -33,20 +33,20 @@ require_once DOL_DOCUMENT_ROOT.'/asset/class/asset.class.php'; // Load translation files required by the page $langs->loadLangs(array("assets")); -$action = GETPOST('action', 'alpha')?GETPOST('action', 'alpha'):'view'; // The action 'add', 'create', 'edit', 'update', 'view', ... -$massaction = GETPOST('massaction', 'alpha'); // The bulk action (combo box choice into lists) -$show_files = GETPOST('show_files', 'int'); // Show files area generated by bulk actions ? -$confirm = GETPOST('confirm', 'alpha'); // Result of a confirmation -$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'):'assetslist'; // 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') +$action = GETPOST('action', 'alpha') ?GETPOST('action', 'alpha') : 'view'; // The action 'add', 'create', 'edit', 'update', 'view', ... +$massaction = GETPOST('massaction', 'alpha'); // The bulk action (combo box choice into lists) +$show_files = GETPOST('show_files', 'int'); // Show files area generated by bulk actions ? +$confirm = GETPOST('confirm', 'alpha'); // Result of a confirmation +$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') : 'assetslist'; // 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') -$id = GETPOST('id', 'int'); +$id = GETPOST('id', 'int'); // Load variable for pagination -$limit = GETPOST('limit', 'int')?GETPOST('limit', 'int'):$conf->liste_limit; +$limit = GETPOST('limit', 'int') ?GETPOST('limit', 'int') : $conf->liste_limit; $sortfield = GETPOST('sortfield', 'alpha'); $sortorder = GETPOST('sortorder', 'alpha'); $page = GETPOST('page', 'int'); @@ -56,22 +56,22 @@ $pageprev = $page - 1; $pagenext = $page + 1; // Initialize technical objects -$object=new Asset($db); +$object = new Asset($db); $extrafields = new ExtraFields($db); -$diroutputmassaction=$conf->asset->dir_output . '/temp/massgeneration/'.$user->id; -$hookmanager->initHooks(array('assetlist')); // Note that conf->hooks_modules contains array +$diroutputmassaction = $conf->asset->dir_output.'/temp/massgeneration/'.$user->id; +$hookmanager->initHooks(array('assetlist')); // 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_'); +$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"; // Protection if external user -$socid=0; +$socid = 0; if ($user->socid > 0) { //$socid = $user->socid; @@ -80,34 +80,34 @@ if ($user->socid > 0) //$result = restrictedArea($user, 'asset', $id,''); // Initialize array of search criterias -$search_all=trim(GETPOST("search_all", 'alpha')); -$search=array(); -foreach($object->fields as $key => $val) +$search_all = trim(GETPOST("search_all", 'alpha')); +$search = array(); +foreach ($object->fields as $key => $val) { - if (GETPOST('search_'.$key, 'alpha')) $search[$key]=GETPOST('search_'.$key, 'alpha'); + 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) +foreach ($object->fields as $key => $val) { - if ($val['searchall']) $fieldstosearchall['t.'.$key]=$val['label']; + if ($val['searchall']) $fieldstosearchall['t.'.$key] = $val['label']; } // Definition of fields for list -$arrayfields=array(); -foreach($object->fields as $key => $val) +$arrayfields = array(); +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'], 'position'=>$val['position']); + if (!empty($val['visible'])) $arrayfields['t.'.$key] = array('label'=>$val['label'], 'checked'=>(($val['visible'] < 0) ? 0 : 1), 'enabled'=>$val['enabled'], '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) + 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], 'checked'=>(($extrafields->attributes[$object->table_element]['list'][$key]<0)?0:1), 'position'=>$extrafields->attributes[$object->table_element]['pos'][$key], 'enabled'=>(abs($extrafields->attributes[$object->table_element]['list'][$key])!=3 && $extrafields->attributes[$object->table_element]['perms'][$key])); + if (!empty($extrafields->attributes[$object->table_element]['list'][$key])) + $arrayfields["ef.".$key] = array('label'=>$extrafields->attributes[$object->table_element]['label'][$key], 'checked'=>(($extrafields->attributes[$object->table_element]['list'][$key] < 0) ? 0 : 1), 'position'=>$extrafields->attributes[$object->table_element]['pos'][$key], 'enabled'=>(abs($extrafields->attributes[$object->table_element]['list'][$key]) != 3 && $extrafields->attributes[$object->table_element]['perms'][$key])); } } $object->fields = dol_sort_array($object->fields, 'position'); @@ -121,11 +121,11 @@ $arrayfields = dol_sort_array($arrayfields, 'position'); * 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 +$parameters = array(); +$reshook = $hookmanager->executeHooks('doActions', $parameters, $object, $action); // Note that $action and $object may have been modified by some hooks if ($reshook < 0) setEventMessages($hookmanager->error, $hookmanager->errors, 'errors'); if (empty($reshook)) @@ -134,24 +134,24 @@ if (empty($reshook)) 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 { - foreach($object->fields as $key => $val) + foreach ($object->fields as $key => $val) { - $search[$key]=''; + $search[$key] = ''; } - $toselect=''; - $search_array_options=array(); + $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')) { - $massaction=''; // Protection to avoid mass action if we force a new search during a mass action confirmation + $massaction = ''; // Protection to avoid mass action if we force a new search during a mass action confirmation } // Mass actions - $objectclass='Asset'; - $objectlabel='Asset'; + $objectclass = 'Asset'; + $objectlabel = 'Asset'; $permissiontoread = $user->rights->asset->read; $permissiontodelete = $user->rights->asset->delete; $uploaddir = $conf->asset->dir_output; @@ -166,46 +166,46 @@ if (empty($reshook)) * Put here all code to render page */ -$form=new Form($db); +$form = new Form($db); -$now=dol_now(); +$now = dol_now(); //$help_url="EN:Module_Asset|FR:Module_Asset_FR|ES:Módulo_Asset"; -$help_url=''; +$help_url = ''; $title = $langs->trans('ListOf', $langs->transnoentitiesnoconv("Assets")); // Build and execute select // -------------------------------------------------------------------- $sql = 'SELECT '; -foreach($object->fields as $key => $val) +foreach ($object->fields as $key => $val) { - $sql.='t.'.$key.', '; + $sql .= 't.'.$key.', '; } // Add fields from extrafields -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.', ' : ''); +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.', ' : ''); // Add fields from hooks -$parameters=array(); -$reshook=$hookmanager->executeHooks('printFieldListSelect', $parameters, $object); // Note that $action and $object may have been modified by hook -$sql.=$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('assets').")"; -else $sql.=" WHERE 1 = 1"; -foreach($search as $key => $val) +$parameters = array(); +$reshook = $hookmanager->executeHooks('printFieldListSelect', $parameters, $object); // Note that $action and $object may have been modified by hook +$sql .= $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('assets').")"; +else $sql .= " WHERE 1 = 1"; +foreach ($search as $key => $val) { - $mode_search=(($object->isInt($object->fields[$key]) || $object->isFloat($object->fields[$key]))?1:0); - if ($search[$key] != '') $sql.=natural_search($key, $search[$key], (($key == 'status')?2:$mode_search)); + $mode_search = (($object->isInt($object->fields[$key]) || $object->isFloat($object->fields[$key])) ? 1 : 0); + 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 -$parameters=array(); -$reshook=$hookmanager->executeHooks('printFieldListWhere', $parameters, $object); // Note that $action and $object may have been modified by hook -$sql.=$hookmanager->resPrint; +$parameters = array(); +$reshook = $hookmanager->executeHooks('printFieldListWhere', $parameters, $object); // Note that $action and $object may have been modified by hook +$sql .= $hookmanager->resPrint; /* If a group by is required $sql.= " GROUP BY " @@ -222,7 +222,7 @@ $reshook=$hookmanager->executeHooks('printFieldListGroupBy',$parameters); // $sql.=$hookmanager->resPrint; */ -$sql.=$db->order($sortfield, $sortorder); +$sql .= $db->order($sortfield, $sortorder); // Count total nb of records $nbtotalofrecords = ''; @@ -237,10 +237,10 @@ if (empty($conf->global->MAIN_DISABLE_FULL_SCANLIST)) } } -$sql.= $db->plimit($limit+1, $offset); +$sql .= $db->plimit($limit + 1, $offset); -$resql=$db->query($sql); -if (! $resql) +$resql = $db->query($sql); +if (!$resql) { dol_print_error($db); exit; @@ -249,7 +249,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) && $search_all) +if ($num == 1 && !empty($conf->global->MAIN_SEARCH_DIRECT_OPEN_IF_ONLY_ONE) && $search_all) { $obj = $db->fetch_object($resql); $id = $obj->rowid; @@ -278,34 +278,34 @@ jQuery(document).ready(function() { }); '; -$arrayofselected=is_array($toselect)?$toselect:array(); +$arrayofselected = is_array($toselect) ? $toselect : array(); -$param=''; -if (! empty($contextpage) && $contextpage != $_SERVER["PHP_SELF"]) $param.='&contextpage='.urlencode($contextpage); -if ($limit > 0 && $limit != $conf->liste_limit) $param.='&limit='.urlencode($limit); -foreach($search as $key => $val) +$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) { - $param.= '&search_'.$key.'='.urlencode($search[$key]); + $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'; // List of mass actions available -$arrayofmassactions = array( +$arrayofmassactions = array( //'presend'=>$langs->trans("SendByMail"), //'builddoc'=>$langs->trans("PDFMerge"), ); -if ($user->rights->asset->delete) $arrayofmassactions['predelete']=''.$langs->trans("Delete"); -if (in_array($massaction, array('presend','predelete'))) $arrayofmassactions=array(); -$massactionbutton=$form->selectMassAction('', $arrayofmassactions); +if ($user->rights->asset->delete) $arrayofmassactions['predelete'] = ''.$langs->trans("Delete"); +if (in_array($massaction, array('presend', 'predelete'))) $arrayofmassactions = array(); +$massactionbutton = $form->selectMassAction('', $arrayofmassactions); -$newcardbutton=''; +$newcardbutton = ''; if ($user->rights->asset->write) { - $newcardbutton=''.$langs->trans('NewAsset').''; - $newcardbutton.= ''; - $newcardbutton.= ''; + $newcardbutton = ''.$langs->trans('NewAsset').''; + $newcardbutton .= ''; + $newcardbutton .= ''; } print '
'; @@ -321,16 +321,16 @@ print ''; print_barre_liste($title, $page, $_SERVER["PHP_SELF"], $param, $sortfield, $sortorder, $massactionbutton, $num, $nbtotalofrecords, 'accountancy', 0, $newcardbutton, '', $limit); // Add code for pre mass action (confirmation or email presend form) -$topicmail="SendAssetsRef"; -$modelmail="asset"; -$objecttmp=new Asset($db); -$trackid='xxxx'.$object->id; +$topicmail = "SendAssetsRef"; +$modelmail = "asset"; +$objecttmp = new Asset($db); +$trackid = 'xxxx'.$object->id; include DOL_DOCUMENT_ROOT.'/core/tpl/massactions_pre.tpl.php'; if ($sall) { - foreach($fieldstosearchall as $key => $val) $fieldstosearchall[$key]=$langs->trans($val); - print '
'.$langs->trans("FilterOnInto", $sall) . join(', ', $fieldstosearchall).'
'; + foreach ($fieldstosearchall as $key => $val) $fieldstosearchall[$key] = $langs->trans($val); + print '
'.$langs->trans("FilterOnInto", $sall).join(', ', $fieldstosearchall).'
'; } $moreforfilter = ''; @@ -338,47 +338,47 @@ $moreforfilter = ''; $moreforfilter.= $langs->trans('MyFilter') . ': '; $moreforfilter.= '
';*/ -$parameters=array(); -$reshook=$hookmanager->executeHooks('printFieldPreListTitle', $parameters, $object); // Note that $action and $object may have been modified by hook +$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($moreforfilter)) +if (!empty($moreforfilter)) { print '
'; print $moreforfilter; print '
'; } -$varpage=empty($contextpage)?$_SERVER["PHP_SELF"]:$contextpage; -$selectedfields=$form->multiSelectArrayWithCheckbox('selectedfields', $arrayfields, $varpage); // This also change content of $arrayfields -$selectedfields.=(count($arrayofmassactions) ? $form->showCheckAddButtons('checkforselect', 1) : ''); +$varpage = empty($contextpage) ? $_SERVER["PHP_SELF"] : $contextpage; +$selectedfields = $form->multiSelectArrayWithCheckbox('selectedfields', $arrayfields, $varpage); // This also change content of $arrayfields +$selectedfields .= (count($arrayofmassactions) ? $form->showCheckAddButtons('checkforselect', 1) : ''); -print '
'; // You can use div-table-responsive-no-min if you dont need reserved height for your table -print ''."\n"; +print '
'; // You can use div-table-responsive-no-min if you dont need reserved height for your table +print '
'."\n"; // Fields title search // -------------------------------------------------------------------- print ''; -foreach($object->fields as $key => $val) +foreach ($object->fields as $key => $val) { - $align=''; - if (in_array($val['type'], array('date','datetime','timestamp'))) $align.=($align?' ':'').'center'; - if (in_array($val['type'], array('timestamp'))) $align.=($align?' ':'').'nowrap'; - if ($key == 'status') $align.=($align?' ':'').'center'; - if (! empty($arrayfields['t.'.$key]['checked'])) print ''; + $align = ''; + if (in_array($val['type'], array('date', 'datetime', 'timestamp'))) $align .= ($align ? ' ' : '').'center'; + if (in_array($val['type'], array('timestamp'))) $align .= ($align ? ' ' : '').'nowrap'; + if ($key == 'status') $align .= ($align ? ' ' : '').'center'; + if (!empty($arrayfields['t.'.$key]['checked'])) print ''; } // Extra fields include DOL_DOCUMENT_ROOT.'/core/tpl/extrafields_list_search_input.tpl.php'; // Fields from hook -$parameters=array('arrayfields'=>$arrayfields); -$reshook=$hookmanager->executeHooks('printFieldListOption', $parameters, $object); // Note that $action and $object may have been modified by hook +$parameters = array('arrayfields'=>$arrayfields); +$reshook = $hookmanager->executeHooks('printFieldListOption', $parameters, $object); // Note that $action and $object may have been modified by hook print $hookmanager->resPrint; // Action column print ''; print ''."\n"; @@ -459,19 +459,19 @@ while ($i < min($num, $limit)) // Extra fields include DOL_DOCUMENT_ROOT.'/core/tpl/extrafields_list_print_fields.tpl.php'; // Fields from hook - $parameters=array('arrayfields'=>$arrayfields, 'obj'=>$obj); - $reshook=$hookmanager->executeHooks('printFieldListValue', $parameters, $object); // Note that $action and $object may have been modified by hook + $parameters = array('arrayfields'=>$arrayfields, 'obj'=>$obj); + $reshook = $hookmanager->executeHooks('printFieldListValue', $parameters, $object); // Note that $action and $object may have been modified by hook print $hookmanager->resPrint; // Action column print ''; - if (! $i) $totalarray['nbfield']++; + if (!$i) $totalarray['nbfield']++; print ''; @@ -482,11 +482,11 @@ while ($i < min($num, $limit)) if (isset($totalarray['pos'])) { print ''; - $i=0; + $i = 0; while ($i < $totalarray['nbfield']) { $i++; - if (! empty($totalarray['pos'][$i])) print ''; + if (!empty($totalarray['pos'][$i])) print ''; else { if ($i == 1) @@ -503,16 +503,16 @@ if (isset($totalarray['pos'])) // If no record found if ($num == 0) { - $colspan=1; - foreach($arrayfields as $key => $val) { if (! empty($val['checked'])) $colspan++; } + $colspan = 1; + foreach ($arrayfields as $key => $val) { if (!empty($val['checked'])) $colspan++; } print ''; } $db->free($resql); -$parameters=array('arrayfields'=>$arrayfields, 'sql'=>$sql); -$reshook=$hookmanager->executeHooks('printFieldListFooter', $parameters, $object); // Note that $action and $object may have been modified by hook +$parameters = array('arrayfields'=>$arrayfields, 'sql'=>$sql); +$reshook = $hookmanager->executeHooks('printFieldListFooter', $parameters, $object); // Note that $action and $object may have been modified by hook print $hookmanager->resPrint; print '
'; -$searchpicto=$form->showFilterButtons(); +$searchpicto = $form->showFilterButtons(); print $searchpicto; print '
'; if ($massactionbutton || $massaction) // If we are in select mode (massactionbutton defined) or if we have already selected and sent an action ($massaction) defined { - $selected=0; - if (in_array($obj->rowid, $arrayofselected)) $selected=1; - print ''; + $selected = 0; + if (in_array($obj->rowid, $arrayofselected)) $selected = 1; + print ''; } print '
'.price($totalarray['val'][$totalarray['pos'][$i]]).''.price($totalarray['val'][$totalarray['pos'][$i]]).'
'.$langs->trans("NoRecordFound").'
'."\n"; @@ -528,12 +528,12 @@ if (in_array('builddoc', $arrayofmassactions) && ($nbtotalofrecords === '' || $n $formfile = new FormFile($db); // Show list of available documents - $urlsource=$_SERVER['PHP_SELF'].'?sortfield='.$sortfield.'&sortorder='.$sortorder; - $urlsource.=str_replace('&', '&', $param); + $urlsource = $_SERVER['PHP_SELF'].'?sortfield='.$sortfield.'&sortorder='.$sortorder; + $urlsource .= str_replace('&', '&', $param); - $filedir=$diroutputmassaction; - $genallowed=$user->rights->asset->read; - $delallowed=$user->rights->asset->create; + $filedir = $diroutputmassaction; + $genallowed = $user->rights->asset->read; + $delallowed = $user->rights->asset->create; print $formfile->showdocuments('massfilesarea_asset', '', $filedir, $urlsource, 0, $delallowed, '', 1, 1, 0, 48, 1, $param, $title, ''); } diff --git a/htdocs/asset/note.php b/htdocs/asset/note.php index dce1daaa3ca..79e80518557 100644 --- a/htdocs/asset/note.php +++ b/htdocs/asset/note.php @@ -27,20 +27,20 @@ require_once DOL_DOCUMENT_ROOT.'/core/lib/asset.lib.php'; require_once DOL_DOCUMENT_ROOT.'/asset/class/asset.class.php'; // Load translation files required by the page -$langs->loadLangs(array("asset","companies")); +$langs->loadLangs(array("asset", "companies")); // Get parameters -$id = GETPOST('id', 'int'); +$id = GETPOST('id', 'int'); $ref = GETPOST('ref', 'alpha'); -$action = GETPOST('action', 'alpha'); +$action = GETPOST('action', 'alpha'); $cancel = GETPOST('cancel', 'aZ09'); $backtopage = GETPOST('backtopage', 'alpha'); // Initialize technical objects -$object=new Asset($db); +$object = new Asset($db); $extrafields = new ExtraFields($db); -$diroutputmassaction=$conf->asset->dir_output . '/temp/massgeneration/'.$user->id; -$hookmanager->initHooks(array('assetnote')); // Note that conf->hooks_modules contains array +$diroutputmassaction = $conf->asset->dir_output.'/temp/massgeneration/'.$user->id; +$hookmanager->initHooks(array('assetnote')); // Note that conf->hooks_modules contains array // Fetch optionals attributes and labels $extrafields->fetch_name_optionals_label($object->table_element); @@ -51,10 +51,10 @@ $extrafields->fetch_name_optionals_label($object->table_element); //$result = restrictedArea($user, 'asset', $id); // 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->asset->multidir_output[$object->entity] . "/" . $object->id; +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->asset->multidir_output[$object->entity]."/".$object->id; -$permissionnote=1; +$permissionnote = 1; //$permissionnote=$user->rights->asset->creer; // Used by the include of actions_setnotes.inc.php @@ -62,7 +62,7 @@ $permissionnote=1; * Actions */ -include DOL_DOCUMENT_ROOT.'/core/actions_setnotes.inc.php'; // Must be include, not include_once +include DOL_DOCUMENT_ROOT.'/core/actions_setnotes.inc.php'; // Must be include, not include_once /* @@ -72,10 +72,10 @@ include DOL_DOCUMENT_ROOT.'/core/actions_setnotes.inc.php'; // Must be include, $form = new Form($db); //$help_url='EN:Customers_Orders|FR:Commandes_Clients|ES:Pedidos de clientes'; -$help_url=''; +$help_url = ''; llxHeader('', $langs->trans('Assets'), $help_url); -if ($id > 0 || ! empty($ref)) +if ($id > 0 || !empty($ref)) { $object->fetch_thirdparty(); @@ -85,9 +85,9 @@ if ($id > 0 || ! empty($ref)) // Object card // ------------------------------------------------------------ - $linkback = '' . $langs->trans("BackToList") . ''; + $linkback = ''.$langs->trans("BackToList").''; - $morehtmlref='
'; + $morehtmlref = '
'; /* // Ref customer $morehtmlref.=$form->editfieldkey("RefCustomer", 'ref_client', $object->ref_client, $object, 0, 'string', '', 0, 1); @@ -127,7 +127,7 @@ if ($id > 0 || ! empty($ref)) } } }*/ - $morehtmlref.='
'; + $morehtmlref .= '
'; dol_banner_tab($object, 'ref', $linkback, 1, 'ref', 'ref', $morehtmlref); @@ -137,7 +137,7 @@ if ($id > 0 || ! empty($ref)) print '
'; - $cssclass="titlefield"; + $cssclass = "titlefield"; include DOL_DOCUMENT_ROOT.'/core/tpl/notes.tpl.php'; print '
'; diff --git a/htdocs/asset/type.php b/htdocs/asset/type.php index 916939b378e..1ca019f5988 100644 --- a/htdocs/asset/type.php +++ b/htdocs/asset/type.php @@ -26,9 +26,9 @@ require_once DOL_DOCUMENT_ROOT.'/core/lib/asset.lib.php'; require_once DOL_DOCUMENT_ROOT.'/asset/class/asset.class.php'; require_once DOL_DOCUMENT_ROOT.'/asset/class/asset_type.class.php'; require_once DOL_DOCUMENT_ROOT.'/core/class/extrafields.class.php'; -if (! empty($conf->accounting->enabled)) require_once DOL_DOCUMENT_ROOT.'/core/lib/accounting.lib.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/lib/accounting.lib.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'; // Load translation files required by the page $langs->load("assets"); @@ -40,25 +40,25 @@ $backtopage = GETPOST('backtopage', 'alpha'); $type = GETPOST('type', 'alpha'); -$limit = GETPOST('limit', 'int')?GETPOST('limit', 'int'):$conf->liste_limit; +$limit = GETPOST('limit', 'int') ?GETPOST('limit', 'int') : $conf->liste_limit; $sortfield = GETPOST("sortfield", 'alpha'); $sortorder = GETPOST("sortorder", 'alpha'); $page = GETPOST("page", 'int'); if (empty($page) || $page == -1) { $page = 0; } // If $page is not defined, or '' or -1 -$offset = $limit * $page ; +$offset = $limit * $page; $pageprev = $page - 1; $pagenext = $page + 1; -if (! $sortorder) { $sortorder="DESC"; } -if (! $sortfield) { $sortfield="a.label"; } +if (!$sortorder) { $sortorder = "DESC"; } +if (!$sortfield) { $sortfield = "a.label"; } -$label=GETPOST("label", "alpha"); -$accountancy_code_asset=GETPOST('accountancy_code_asset', 'string'); -$accountancy_code_depreciation_asset=GETPOST('accountancy_code_depreciation_asset', 'string'); -$accountancy_code_depreciation_expense=GETPOST('accountancy_code_depreciation_expense', 'string'); -$comment=GETPOST('comment', 'string'); +$label = GETPOST("label", "alpha"); +$accountancy_code_asset = GETPOST('accountancy_code_asset', 'string'); +$accountancy_code_depreciation_asset = GETPOST('accountancy_code_depreciation_asset', 'string'); +$accountancy_code_depreciation_expense = GETPOST('accountancy_code_depreciation_expense', 'string'); +$comment = GETPOST('comment', 'string'); // Security check -$result=restrictedArea($user, 'asset', $rowid, 'asset_type'); +$result = restrictedArea($user, 'asset', $rowid, 'asset_type'); $object = new AssetType($db); @@ -69,13 +69,13 @@ $extrafields->fetch_name_optionals_label($object->table_element); 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 { - $type=""; - $sall=""; + $type = ""; + $sall = ""; } // Initialize technical object to manage hooks of page. Note that conf->hooks_modules contains array of hook context -$hookmanager->initHooks(array('assettypecard','globalcard')); +$hookmanager->initHooks(array('assettypecard', 'globalcard')); /* @@ -83,9 +83,9 @@ $hookmanager->initHooks(array('assettypecard','globalcard')); */ if ($cancel) { - $action=''; + $action = ''; - if (! empty($backtopage)) + if (!empty($backtopage)) { header("Location: ".$backtopage); exit; @@ -94,11 +94,11 @@ if ($cancel) { if ($action == 'add' && $user->rights->asset->write) { - $object->label = trim($label); - $object->accountancy_code_asset = trim($accountancy_code_asset); - $object->accountancy_code_depreciation_asset = trim($accountancy_code_depreciation_asset); - $object->accountancy_code_depreciation_expense = trim($accountancy_code_depreciation_expense); - $object->note = trim($comment); + $object->label = trim($label); + $object->accountancy_code_asset = trim($accountancy_code_asset); + $object->accountancy_code_depreciation_asset = trim($accountancy_code_depreciation_asset); + $object->accountancy_code_depreciation_expense = trim($accountancy_code_depreciation_expense); + $object->note = trim($comment); // Fill array 'array_options' with data from add form $ret = $extrafields->setOptionalsFromPost(null, $object); @@ -121,9 +121,9 @@ if ($action == 'add' && $user->rights->asset->write) } } - if (! $error) + if (!$error) { - $id=$object->create($user); + $id = $object->create($user); if ($id > 0) { header("Location: ".$_SERVER["PHP_SELF"]); @@ -147,19 +147,19 @@ if ($action == 'update' && $user->rights->asset->write) $object->oldcopy = clone $object; - $object->label = trim($label); - $object->accountancy_code_asset = trim($accountancy_code_asset); - $object->accountancy_code_depreciation_asset = trim($accountancy_code_depreciation_asset); - $object->accountancy_code_depreciation_expense = trim($accountancy_code_depreciation_expense); - $object->note = trim($comment); + $object->label = trim($label); + $object->accountancy_code_asset = trim($accountancy_code_asset); + $object->accountancy_code_depreciation_asset = trim($accountancy_code_depreciation_asset); + $object->accountancy_code_depreciation_expense = trim($accountancy_code_depreciation_expense); + $object->note = trim($comment); // Fill array 'array_options' with data from add form $ret = $extrafields->setOptionalsFromPost(null, $object); if ($ret < 0) $error++; - $ret=$object->update($user); + $ret = $object->update($user); - if ($ret >= 0 && ! count($object->errors)) + if ($ret >= 0 && !count($object->errors)) { setEventMessages($langs->trans("AssetsTypeModified"), null, 'mesgs'); } @@ -175,7 +175,7 @@ if ($action == 'update' && $user->rights->asset->write) if ($action == 'confirm_delete' && $user->rights->asset->write) { $object->fetch($rowid); - $res=$object->delete(); + $res = $object->delete(); if ($res > 0) { @@ -186,7 +186,7 @@ if ($action == 'confirm_delete' && $user->rights->asset->write) else { setEventMessages($langs->trans("AssetsTypeCanNotBeDeleted"), null, 'errors'); - $action=''; + $action = ''; } } @@ -195,20 +195,20 @@ if ($action == 'confirm_delete' && $user->rights->asset->write) * View */ -$form=new Form($db); +$form = new Form($db); -$helpurl=''; +$helpurl = ''; llxHeader('', $langs->trans("AssetsTypeSetup"), $helpurl); // List of asset type -if (! $rowid && $action != 'create' && $action != 'edit') +if (!$rowid && $action != 'create' && $action != 'edit') { //dol_fiche_head(''); $sql = "SELECT d.rowid, d.label as label, d.accountancy_code_asset, d.accountancy_code_depreciation_asset, d.accountancy_code_depreciation_expense, d.note"; - $sql.= " FROM ".MAIN_DB_PREFIX."asset_type as d"; - $sql.= " WHERE d.entity IN (".getEntity('asset_type').")"; + $sql .= " FROM ".MAIN_DB_PREFIX."asset_type as d"; + $sql .= " WHERE d.entity IN (".getEntity('asset_type').")"; $result = $db->query($sql); if ($result) @@ -220,12 +220,12 @@ if (! $rowid && $action != 'create' && $action != 'edit') $param = ''; - $newcardbutton=''; + $newcardbutton = ''; if ($user->rights->asset->configurer) { - $newcardbutton=''.$langs->trans('NewAssetType').''; - $newcardbutton.= ''; - $newcardbutton.= ''; + $newcardbutton = ''.$langs->trans('NewAssetType').''; + $newcardbutton .= ''; + $newcardbutton .= ''; } print ''; @@ -242,7 +242,7 @@ if (! $rowid && $action != 'create' && $action != 'edit') $moreforfilter = ''; print '
'; - print ''."\n"; + print '
'."\n"; print ''; print ''; @@ -271,7 +271,7 @@ if (! $rowid && $action != 'create' && $action != 'edit') print ''; print ''; print ''; print ''; @@ -2576,16 +2576,16 @@ else print $form->editfieldkey('CurrencyRate', 'multicurrency_tx', '', $object, 0); print ''; if ($action != 'editmulticurrencyrate' && $object->statut == $object::STATUS_DRAFT && $object->multicurrency_code && $object->multicurrency_code != $conf->currency) - print ''; + print ''; print '
'.$langs->trans("Ref").''.dol_escape_htmltag($objp->label).''; - if (! empty($conf->accounting->enabled)) + if (!empty($conf->accounting->enabled)) { $accountingaccount = new AccountingAccount($db); $accountingaccount->fetch('', $objp->accountancy_code_asset, 1); @@ -283,7 +283,7 @@ if (! $rowid && $action != 'create' && $action != 'edit') print ''; - if (! empty($conf->accounting->enabled)) + if (!empty($conf->accounting->enabled)) { $accountingaccount2 = new AccountingAccount($db); $accountingaccount2->fetch('', $objp->accountancy_code_depreciation_asset, 1); @@ -295,7 +295,7 @@ if (! $rowid && $action != 'create' && $action != 'edit') print ''; - if (! empty($conf->accounting->enabled)) + if (!empty($conf->accounting->enabled)) { $accountingaccount3 = new AccountingAccount($db); $accountingaccount3->fetch('', $objp->accountancy_code_depreciation_expense, 1); @@ -333,7 +333,7 @@ if (! $rowid && $action != 'create' && $action != 'edit') if ($action == 'create') { $object = new AssetType($db); - if (! empty($conf->accounting->enabled)) $formaccounting = new FormAccounting($db); + if (!empty($conf->accounting->enabled)) $formaccounting = new FormAccounting($db); print load_fiche_titre($langs->trans("NewAssetType")); @@ -343,12 +343,12 @@ if ($action == 'create') dol_fiche_head(''); - print ''; + print '
'; print ''; print ''; - if (! empty($conf->accounting->enabled)) + if (!empty($conf->accounting->enabled)) { // Accountancy_code_asset print ''; @@ -390,12 +390,12 @@ if ($action == 'create') print ''; // Other attributes - $parameters=array(); - $reshook=$hookmanager->executeHooks('formObjectOptions', $parameters, $act, $action); // Note that $action and $object may have been modified by hook + $parameters = array(); + $reshook = $hookmanager->executeHooks('formObjectOptions', $parameters, $object, $action); // Note that $action and $object may have been modified by hook print $hookmanager->resPrint; if (empty($reshook)) { - print $object->showOptionals($extrafields, 'edit'); + print $object->showOptionals($extrafields, 'edit', $parameters); } print ''; print "
'.$langs->trans("Label").'
'.$langs->trans("AccountancyCodeAsset").'
\n"; @@ -438,24 +438,24 @@ if ($rowid > 0) $linkback = ''.$langs->trans("BackToList").''; - $morehtmlref='
'; + $morehtmlref = '
'; // Ref asset type - $morehtmlref.=$form->editfieldkey("Label", 'label', $object->label, $object, $user->rights->asset->write, 'string', '', 0, 1); - $morehtmlref.=$form->editfieldval("Label", 'label', $object->label, $object, $user->rights->asset->write, 'string', '', null, null, '', 1); - $morehtmlref.='
'; + $morehtmlref .= $form->editfieldkey("Label", 'label', $object->label, $object, $user->rights->asset->write, 'string', '', 0, 1); + $morehtmlref .= $form->editfieldval("Label", 'label', $object->label, $object, $user->rights->asset->write, 'string', '', null, null, '', 1); + $morehtmlref .= '
'; dol_banner_tab($object, 'rowid', $linkback, 1, 'rowid', 'ref', $morehtmlref, '', 0, '', $morehtmlright); print '
'; print '
'; - print ''; + print '
'; print ''; print '"; // Other attributes - include DOL_DOCUMENT_ROOT . '/core/tpl/extrafields_view.tpl.php'; + include DOL_DOCUMENT_ROOT.'/core/tpl/extrafields_view.tpl.php'; print '
'; print $langs->trans("AccountancyCodeAsset"); print ''; - if (! empty($conf->accounting->enabled)) + if (!empty($conf->accounting->enabled)) { $accountingaccount = new AccountingAccount($db); $accountingaccount->fetch('', $object->accountancy_code_asset, 1); @@ -471,7 +471,7 @@ if ($rowid > 0) print ''; print $langs->trans("AccountancyCodeDepreciationAsset"); print ''; - if (! empty($conf->accounting->enabled)) + if (!empty($conf->accounting->enabled)) { $accountingaccount2 = new AccountingAccount($db); $accountingaccount2->fetch('', $object->accountancy_code_depreciation_asset, 1); @@ -487,7 +487,7 @@ if ($rowid > 0) print ''; print $langs->trans("AccountancyCodeDepreciationExpense"); print ''; - if (! empty($conf->accounting->enabled)) + if (!empty($conf->accounting->enabled)) { $accountingaccount3 = new AccountingAccount($db); $accountingaccount3->fetch('', $object->accountancy_code_depreciation_expense, 1); @@ -503,7 +503,7 @@ if ($rowid > 0) print nl2br($object->note)."
'; print '
'; @@ -542,7 +542,7 @@ if ($rowid > 0) $object = new AssetType($db); $object->fetch($rowid); $object->fetch_optionals(); - if (! empty($conf->accounting->enabled)) $formaccounting = new FormAccounting($db); + if (!empty($conf->accounting->enabled)) $formaccounting = new FormAccounting($db); $head = asset_type_prepare_head($object); @@ -553,13 +553,13 @@ if ($rowid > 0) dol_fiche_head($head, 'card', $langs->trans("AssetsType"), -1, 'setup'); - print ''; + print '
'; print ''; print ''; - if (! empty($conf->accounting->enabled)) + if (!empty($conf->accounting->enabled)) { // Accountancy_code_asset print ''; @@ -601,12 +601,12 @@ if ($rowid > 0) print ''; // Other attributes - $parameters=array(); - $reshook=$hookmanager->executeHooks('formObjectOptions', $parameters, $act, $action); // Note that $action and $object may have been modified by hook + $parameters = array(); + $reshook = $hookmanager->executeHooks('formObjectOptions', $parameters, $act, $action); // Note that $action and $object may have been modified by hook print $hookmanager->resPrint; if (empty($reshook)) { - print $object->showOptionals($extrafields, 'edit'); + print $object->showOptionals($extrafields, 'edit', $parameters); } print '
'.$langs->trans("Ref").''.$object->id.'
'.$langs->trans("Label").'
'.$langs->trans("AccountancyCodeAsset").'
'; @@ -614,18 +614,18 @@ if ($rowid > 0) // Extra field if (empty($reshook)) { - print '

'; - foreach($extrafields->attributes[$object->element]['label'] as $key=>$label) + print '

'; + foreach ($extrafields->attributes[$object->element]['label'] as $key=>$label) { - if (isset($_POST["options_" . $key])) { - if (is_array($_POST["options_" . $key])) { + if (isset($_POST["options_".$key])) { + if (is_array($_POST["options_".$key])) { // $_POST["options"] is an array but following code expects a comma separated string - $value = implode(",", $_POST["options_" . $key]); + $value = implode(",", $_POST["options_".$key]); } else { - $value = $_POST["options_" . $key]; + $value = $_POST["options_".$key]; } } else { - $value = $adht->array_options["options_" . $key]; + $value = $adht->array_options["options_".$key]; } print ''; + echo ''; } $coldisplay++; -print ''; if($conf->global->PRODUCT_USE_UNITS) @@ -121,27 +121,27 @@ if($conf->global->PRODUCT_USE_UNITS) } $coldisplay++; -print ''; $coldisplay++; -print ''; -$coldisplay++; -print ''; +//$coldisplay++; +//print ''; $coldisplay += $colspan; -print ''; print ''; if (is_object($objectline)) { - print $objectline->showOptionals($extrafields, 'edit', array('style'=>$bcnd[$var], 'colspan'=>$coldisplay), '', '', empty($conf->global->MAIN_EXTRAFIELDS_IN_ONE_TD)?0:1); + print $objectline->showOptionals($extrafields, 'edit', array('style'=>$bcnd[$var], 'colspan'=>$coldisplay), '', '', empty($conf->global->MAIN_EXTRAFIELDS_IN_ONE_TD) ? 0 : 1); } ?> diff --git a/htdocs/bom/tpl/objectline_edit.tpl.php b/htdocs/bom/tpl/objectline_edit.tpl.php index c7fc4f73cd7..17d01e07fd9 100644 --- a/htdocs/bom/tpl/objectline_edit.tpl.php +++ b/htdocs/bom/tpl/objectline_edit.tpl.php @@ -32,7 +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,11 +41,11 @@ if (empty($object) || ! is_object($object)) global $forceall; -if (empty($forceall)) $forceall=0; +if (empty($forceall)) $forceall = 0; // Define colspan for the button 'Add' -$colspan = 3; // Columns: total ht + col edit + col delete +$colspan = 3; // Columns: total ht + col edit + col delete // Lines for extrafield $objectline = new BOMLine($this->db); @@ -67,7 +67,7 @@ $coldisplay++; - + @@ -124,9 +124,9 @@ $coldisplay++; print ''; -$coldisplay++; -print ''; +//$coldisplay++; +//print ''; $coldisplay+=$colspan; print ''; print ''; if (is_object($objectline)) { - print $objectline->showOptionals($extrafields, 'edit', array('style'=>$bcnd[$var], 'colspan'=>$coldisplay), '', '', empty($conf->global->MAIN_EXTRAFIELDS_IN_ONE_TD)?0:1); + print $objectline->showOptionals($extrafields, 'edit', array('style'=>$bcnd[$var], 'colspan'=>$coldisplay), '', '', empty($conf->global->MAIN_EXTRAFIELDS_IN_ONE_TD) ? 0 : 1); } print "\n"; diff --git a/htdocs/bom/tpl/objectline_title.tpl.php b/htdocs/bom/tpl/objectline_title.tpl.php index 138a0b9aa58..706f71af7ec 100644 --- a/htdocs/bom/tpl/objectline_title.tpl.php +++ b/htdocs/bom/tpl/objectline_title.tpl.php @@ -66,7 +66,7 @@ print ''; // Efficiency -print ''; +//print ''; print ''; // No width to allow autodim diff --git a/htdocs/bom/tpl/objectline_view.tpl.php b/htdocs/bom/tpl/objectline_view.tpl.php index 330f8ef8a33..f2c78827b2d 100644 --- a/htdocs/bom/tpl/objectline_view.tpl.php +++ b/htdocs/bom/tpl/objectline_view.tpl.php @@ -35,7 +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 +44,11 @@ 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.'"'; @@ -59,11 +59,11 @@ $domData .= ' data-product_type="'.$line->product_type.'"'; // Lines for extrafield $objectline = new BOMLine($object->db); -$coldisplay=0; +$coldisplay = 0; print "\n"; print ''; -if (! empty($conf->global->MAIN_VIEW_LINE_NUMBER)) { - print ''; +if (!empty($conf->global->MAIN_VIEW_LINE_NUMBER)) { + print ''; $coldisplay++; } print ''; print ''; -if($conf->global->PRODUCT_USE_UNITS) +if ($conf->global->PRODUCT_USE_UNITS) { print ''; -print ''; +//print ''; -if ($this->status == 0 && ($object_rights->write) && $action != 'selectlines' ) { +if ($this->status == 0 && ($object_rights->write) && $action != 'selectlines' ) { print ''; } else { - print ''; + print ''; $coldisplay++; } } else { print ''; - $coldisplay=$coldisplay+3; + $coldisplay = $coldisplay + 3; } if ($action == 'selectlines') { print ''; } @@ -155,7 +155,7 @@ print ''; //Line extrafield if (!empty($extrafields)) { - print $line->showOptionals($extrafields, 'view', array('style'=>'class="drag drop oddeven"','colspan'=>$coldisplay), '', '', empty($conf->global->MAIN_EXTRAFIELDS_IN_ONE_TD)?0:1); + print $line->showOptionals($extrafields, 'view', array('style'=>'class="drag drop oddeven"', 'colspan'=>$coldisplay), '', '', empty($conf->global->MAIN_EXTRAFIELDS_IN_ONE_TD) ? 0 : 1); } print "\n"; diff --git a/htdocs/bookmarks/admin/bookmark.php b/htdocs/bookmarks/admin/bookmark.php index 1f227d7316f..5486a4887d1 100644 --- a/htdocs/bookmarks/admin/bookmark.php +++ b/htdocs/bookmarks/admin/bookmark.php @@ -69,7 +69,7 @@ print ''; print ''; print ''; -print '
'.$label.''; print $extrafields->showInputField($key, $value); diff --git a/htdocs/barcode/printsheet.php b/htdocs/barcode/printsheet.php index 1ed7c449868..4a6e32684fd 100644 --- a/htdocs/barcode/printsheet.php +++ b/htdocs/barcode/printsheet.php @@ -33,21 +33,21 @@ $langs->loadLangs(array('admin', 'members', 'errors')); // Choice of print year or current year. $now = dol_now(); -$year=dol_print_date($now, '%Y'); -$month=dol_print_date($now, '%m'); -$day=dol_print_date($now, '%d'); -$forbarcode=GETPOST('forbarcode'); -$fk_barcode_type=GETPOST('fk_barcode_type'); -$mode=GETPOST('mode'); -$modellabel=GETPOST("modellabel"); // Doc template to use -$numberofsticker=GETPOST('numberofsticker', 'int'); +$year = dol_print_date($now, '%Y'); +$month = dol_print_date($now, '%m'); +$day = dol_print_date($now, '%d'); +$forbarcode = GETPOST('forbarcode'); +$fk_barcode_type = GETPOST('fk_barcode_type'); +$mode = GETPOST('mode'); +$modellabel = GETPOST("modellabel"); // Doc template to use +$numberofsticker = GETPOST('numberofsticker', 'int'); -$mesg=''; +$mesg = ''; -$action=GETPOST('action', 'aZ09'); +$action = GETPOST('action', 'aZ09'); -$producttmp=new Product($db); -$thirdpartytmp=new Societe($db); +$producttmp = new Product($db); +$thirdpartytmp = new Societe($db); /* @@ -56,14 +56,14 @@ $thirdpartytmp=new Societe($db); if (GETPOST('submitproduct') && GETPOST('submitproduct')) { - $action=''; // We reset because we don't want to build doc + $action = ''; // We reset because we don't want to build doc if (GETPOST('productid') > 0) { $producttmp->fetch(GETPOST('productid')); - $forbarcode=$producttmp->barcode; - $fk_barcode_type=$producttmp->barcode_type; + $forbarcode = $producttmp->barcode; + $fk_barcode_type = $producttmp->barcode_type; - if (empty($fk_barcode_type) && ! empty($conf->global->PRODUIT_DEFAULT_BARCODE_TYPE)) $fk_barcode_type = $conf->global->PRODUIT_DEFAULT_BARCODE_TYPE; + if (empty($fk_barcode_type) && !empty($conf->global->PRODUIT_DEFAULT_BARCODE_TYPE)) $fk_barcode_type = $conf->global->PRODUIT_DEFAULT_BARCODE_TYPE; if (empty($forbarcode) || empty($fk_barcode_type)) { @@ -73,14 +73,14 @@ if (GETPOST('submitproduct') && GETPOST('submitproduct')) } if (GETPOST('submitthirdparty') && GETPOST('submitthirdparty')) { - $action=''; // We reset because we don't want to build doc + $action = ''; // We reset because we don't want to build doc if (GETPOST('socid') > 0) { $thirdpartytmp->fetch(GETPOST('socid')); - $forbarcode=$thirdpartytmp->barcode; - $fk_barcode_type=$thirdpartytmp->barcode_type_code; + $forbarcode = $thirdpartytmp->barcode; + $fk_barcode_type = $thirdpartytmp->barcode_type_code; - if (empty($fk_barcode_type) && ! empty($conf->global->GENBARCODE_BARCODETYPE_THIRDPARTY)) $fk_barcode_type = $conf->global->GENBARCODE_BARCODETYPE_THIRDPARTY; + if (empty($fk_barcode_type) && !empty($conf->global->GENBARCODE_BARCODETYPE_THIRDPARTY)) $fk_barcode_type = $conf->global->GENBARCODE_BARCODETYPE_THIRDPARTY; if (empty($forbarcode) || empty($fk_barcode_type)) { @@ -91,7 +91,7 @@ if (GETPOST('submitthirdparty') && GETPOST('submitthirdparty')) if ($action == 'builddoc') { - $result=0; $error=0; + $result = 0; $error = 0; if (empty($forbarcode)) // barcode value { @@ -104,12 +104,12 @@ if ($action == 'builddoc') $error++; } - if (! $error) + if (!$error) { // Get encoder (barcode_type_coder) from barcode type id (barcode_type) - $stdobject=new GenericObject($db); - $stdobject->barcode_type=$fk_barcode_type; - $result=$stdobject->fetch_barcode(); + $stdobject = new GenericObject($db); + $stdobject->barcode_type = $fk_barcode_type; + $result = $stdobject->fetch_barcode(); if ($result <= 0) { $error++; @@ -117,27 +117,27 @@ if ($action == 'builddoc') } } - if (! $error) + if (!$error) { - $code=$forbarcode; - $generator=$stdobject->barcode_type_coder; // coder (loaded by fetch_barcode). Engine. - $encoding=strtoupper($stdobject->barcode_type_code); // code (loaded by fetch_barcode). Example 'ean', 'isbn', ... + $code = $forbarcode; + $generator = $stdobject->barcode_type_coder; // coder (loaded by fetch_barcode). Engine. + $encoding = strtoupper($stdobject->barcode_type_code); // code (loaded by fetch_barcode). Example 'ean', 'isbn', ... - $diroutput=$conf->barcode->dir_temp; + $diroutput = $conf->barcode->dir_temp; dol_mkdir($diroutput); // Generate barcode - $dirbarcode=array_merge(array("/core/modules/barcode/doc/"), $conf->modules_parts['barcode']); + $dirbarcode = array_merge(array("/core/modules/barcode/doc/"), $conf->modules_parts['barcode']); - foreach($dirbarcode as $reldir) + foreach ($dirbarcode as $reldir) { - $dir=dol_buildpath($reldir, 0); - $newdir=dol_osencode($dir); + $dir = dol_buildpath($reldir, 0); + $newdir = dol_osencode($dir); // Check if directory exists (we do not use dol_is_dir to avoid loading files.lib.php) - if (! is_dir($newdir)) continue; + if (!is_dir($newdir)) continue; - $result=@include_once $newdir.$generator.'.modules.php'; + $result = @include_once $newdir.$generator.'.modules.php'; if ($result) break; } @@ -151,11 +151,11 @@ if ($action == 'builddoc') $is2d = false; if ($module->encodingIsSupported($encoding)) { - $barcodeimage=$conf->barcode->dir_temp.'/barcode_'.$code.'_'.$encoding.'.png'; + $barcodeimage = $conf->barcode->dir_temp.'/barcode_'.$code.'_'.$encoding.'.png'; dol_delete_file($barcodeimage); // File is created with full name $barcodeimage = $conf->barcode->dir_temp.'/barcode_'.$code.'_'.$encoding.'.png'; - $result=$module->writeBarCode($code, $encoding, 'Y', 4, 1); - if ($result <= 0 || ! dol_is_file($barcodeimage)) + $result = $module->writeBarCode($code, $encoding, 'Y', 4, 1); + if ($result <= 0 || !dol_is_file($barcodeimage)) { $error++; setEventMessages('Failed to generate image file of barcode for code='.$code.' encoding='.$encoding.' file='.basename($barcodeimage), null, 'errors'); @@ -174,10 +174,10 @@ if ($action == 'builddoc') } } - if (! $error) + if (!$error) { // List of values to scan for a replacement - $substitutionarray = array ( + $substitutionarray = array( '%LOGIN%' => $user->login, '%COMPANY%' => $mysoc->name, '%ADDRESS%' => $mysoc->address, @@ -197,17 +197,17 @@ if ($action == 'builddoc') // For labels if ($mode == 'label') { - $txtforsticker="%PHOTO%"; // Photo will be barcode image, %BARCODE% posible when using TCPDF generator - $textleft=make_substitutions((empty($conf->global->BARCODE_LABEL_LEFT_TEXT)?$txtforsticker:$conf->global->BARCODE_LABEL_LEFT_TEXT), $substitutionarray); - $textheader=make_substitutions((empty($conf->global->BARCODE_LABEL_HEADER_TEXT)?'':$conf->global->BARCODE_LABEL_HEADER_TEXT), $substitutionarray); - $textfooter=make_substitutions((empty($conf->global->BARCODE_LABEL_FOOTER_TEXT)?'':$conf->global->BARCODE_LABEL_FOOTER_TEXT), $substitutionarray); - $textright=make_substitutions((empty($conf->global->BARCODE_LABEL_RIGHT_TEXT)?'':$conf->global->BARCODE_LABEL_RIGHT_TEXT), $substitutionarray); - $forceimgscalewidth=(empty($conf->global->BARCODE_FORCEIMGSCALEWIDTH)?1:$conf->global->BARCODE_FORCEIMGSCALEWIDTH); - $forceimgscaleheight=(empty($conf->global->BARCODE_FORCEIMGSCALEHEIGHT)?1:$conf->global->BARCODE_FORCEIMGSCALEHEIGHT); + $txtforsticker = "%PHOTO%"; // Photo will be barcode image, %BARCODE% posible when using TCPDF generator + $textleft = make_substitutions((empty($conf->global->BARCODE_LABEL_LEFT_TEXT) ? $txtforsticker : $conf->global->BARCODE_LABEL_LEFT_TEXT), $substitutionarray); + $textheader = make_substitutions((empty($conf->global->BARCODE_LABEL_HEADER_TEXT) ? '' : $conf->global->BARCODE_LABEL_HEADER_TEXT), $substitutionarray); + $textfooter = make_substitutions((empty($conf->global->BARCODE_LABEL_FOOTER_TEXT) ? '' : $conf->global->BARCODE_LABEL_FOOTER_TEXT), $substitutionarray); + $textright = make_substitutions((empty($conf->global->BARCODE_LABEL_RIGHT_TEXT) ? '' : $conf->global->BARCODE_LABEL_RIGHT_TEXT), $substitutionarray); + $forceimgscalewidth = (empty($conf->global->BARCODE_FORCEIMGSCALEWIDTH) ? 1 : $conf->global->BARCODE_FORCEIMGSCALEWIDTH); + $forceimgscaleheight = (empty($conf->global->BARCODE_FORCEIMGSCALEHEIGHT) ? 1 : $conf->global->BARCODE_FORCEIMGSCALEHEIGHT); - for ($i=0; $i < $numberofsticker; $i++) + for ($i = 0; $i < $numberofsticker; $i++) { - $arrayofrecords[]=array( + $arrayofrecords[] = array( 'textleft'=>$textleft, 'textheader'=>$textheader, 'textfooter'=>$textfooter, @@ -221,23 +221,23 @@ if ($action == 'builddoc') } $i++; - $mesg=''; + $mesg = ''; // Build and output PDF if ($mode == 'label') { - if (! count($arrayofrecords)) + if (!count($arrayofrecords)) { - $mesg=$langs->trans("ErrorRecordNotFound"); + $mesg = $langs->trans("ErrorRecordNotFound"); } if (empty($modellabel) || $modellabel == '-1') { - $mesg=$langs->trans("ErrorFieldRequired", $langs->transnoentitiesnoconv("DescADHERENT_ETIQUETTE_TYPE")); + $mesg = $langs->trans("ErrorFieldRequired", $langs->transnoentitiesnoconv("DescADHERENT_ETIQUETTE_TYPE")); } $outfile = $langs->trans("BarCode").'_sheets_'.dol_print_date(dol_now(), 'dayhourlog').'.pdf'; - if (! $mesg) $result=doc_label_pdf_create($db, $arrayofrecords, $modellabel, $outputlangs, $diroutput, $template, dol_sanitizeFileName($outfile)); + if (!$mesg) $result = doc_label_pdf_create($db, $arrayofrecords, $modellabel, $outputlangs, $diroutput, $template, dol_sanitizeFileName($outfile)); } if ($result <= 0) @@ -245,7 +245,7 @@ if ($action == 'builddoc') dol_print_error('', $result); } - if (! $mesg) + if (!$mesg) { $db->close(); exit; @@ -260,7 +260,7 @@ if ($action == 'builddoc') if (empty($conf->barcode->enabled)) accessforbidden(); -$form=new Form($db); +$form = new Form($db); llxHeader('', $langs->trans("BarCodePrintsheet")); @@ -287,15 +287,15 @@ print '
'; // List of possible labels (defined into $_Avery_Labels variable set into core/lib/format_cards.lib.php) -$arrayoflabels=array(); -foreach(array_keys($_Avery_Labels) as $codecards) +$arrayoflabels = array(); +foreach (array_keys($_Avery_Labels) as $codecards) { - $labeltoshow=$_Avery_Labels[$codecards]['name']; + $labeltoshow = $_Avery_Labels[$codecards]['name']; //$labeltoshow.=' ('.$_Avery_Labels[$row['code']]['paper-size'].')'; - $arrayoflabels[$codecards]=$labeltoshow; + $arrayoflabels[$codecards] = $labeltoshow; } asort($arrayoflabels); -print $form->selectarray('modellabel', $arrayoflabels, (GETPOST('modellabel')?GETPOST('modellabel'):$conf->global->ADHERENT_ETIQUETTE_TYPE), 1, 0, 0, '', 0, 0, 0, '', '', 1); +print $form->selectarray('modellabel', $arrayoflabels, (GETPOST('modellabel') ?GETPOST('modellabel') : $conf->global->ADHERENT_ETIQUETTE_TYPE), 1, 0, 0, '', 0, 0, 0, '', '', 1); print '
'; // Number of stickers to print @@ -303,7 +303,7 @@ print '
'; print '
'; print $langs->trans("NumberOfStickers").'   '; print '
'; -print ''; +print ''; print '
'; print ''; @@ -372,22 +372,22 @@ jQuery(document).ready(function() { '; // Checkbox to select from free text -print ' '.$langs->trans("FillBarCodeTypeAndValueManually").'   '; +print ' '.$langs->trans("FillBarCodeTypeAndValueManually").'   '; print '
'; -if (! empty($user->rights->produit->lire) || ! empty($user->rights->service->lire)) +if (!empty($user->rights->produit->lire) || !empty($user->rights->service->lire)) { - print ' '.$langs->trans("FillBarCodeTypeAndValueFromProduct").'   '; + print ' '.$langs->trans("FillBarCodeTypeAndValueFromProduct").'   '; print '
'; print '
'; - $form->select_produits(GETPOST('productid'), 'productid', ''); + $form->select_produits(GETPOST('productid'), 'productid', '', '', 0, -1, 2, '', 0, array(), 0, '1', 0, 'minwidth400imp', 1); print '   '; print '
'; } -if (! empty($user->rights->societe->lire)) +if (!empty($user->rights->societe->lire)) { - print ' '.$langs->trans("FillBarCodeTypeAndValueFromThirdParty").'   '; + print ' '.$langs->trans("FillBarCodeTypeAndValueFromThirdParty").'   '; print '
'; print '
'; print $form->select_company(GETPOST('socid'), 'socid', '', 'SelectThirdParty', 0, 0, array(), 0, 'minwidth300'); @@ -435,7 +435,7 @@ print '
'; print '
'; -print '
'; +print '
'; print ''; print '
'; diff --git a/htdocs/blockedlog/admin/blockedlog.php b/htdocs/blockedlog/admin/blockedlog.php index a0260cc6682..e5c089061eb 100644 --- a/htdocs/blockedlog/admin/blockedlog.php +++ b/htdocs/blockedlog/admin/blockedlog.php @@ -100,7 +100,7 @@ print ''.$langs->trans("BlockedLogDesc")."
'; -print ''; +print '
'; print ''; print ''; print ''; diff --git a/htdocs/blockedlog/admin/blockedlog_list.php b/htdocs/blockedlog/admin/blockedlog_list.php index 6ce788a5790..63e94d00a47 100644 --- a/htdocs/blockedlog/admin/blockedlog_list.php +++ b/htdocs/blockedlog/admin/blockedlog_list.php @@ -361,7 +361,7 @@ print ''; print ''; print ''; -print '
'.$langs->trans("Key").''.$langs->trans("Value").'
'; +print '
'; // Line of filters print ''; diff --git a/htdocs/blockedlog/class/authority.class.php b/htdocs/blockedlog/class/authority.class.php index cec6410b7b6..234aeceb2a6 100644 --- a/htdocs/blockedlog/class/authority.class.php +++ b/htdocs/blockedlog/class/authority.class.php @@ -67,12 +67,12 @@ class BlockedLogAuthority $this->signature = $block_static->getSignature(); - $blocks = $block_static->getLog('all', 0, 0, 'rowid', 'ASC') ; + $blocks = $block_static->getLog('all', 0, 0, 'rowid', 'ASC'); $this->blockchain = ''; - foreach($blocks as &$b) { - $this->blockchain.=$b->signature; + foreach ($blocks as &$b) { + $this->blockchain .= $b->signature; } return $this->blockchain; @@ -98,7 +98,7 @@ class BlockedLogAuthority public function checkBlockchain($hash) { - return ($hash === $this->getBlockchainHash() ); + return ($hash === $this->getBlockchainHash()); } /** @@ -110,7 +110,7 @@ class BlockedLogAuthority public function addBlock($block) { - $this->blockchain.=$block; + $this->blockchain .= $block; } /** @@ -122,14 +122,14 @@ class BlockedLogAuthority public function checkBlock($block) { - if(strlen($block)!=64) return false; + if (strlen($block) != 64) return false; $blocks = str_split($this->blockchain, 64); - if(!in_array($block, $blocks)) { + if (!in_array($block, $blocks)) { return true; } - else{ + else { return false; } } @@ -151,44 +151,44 @@ class BlockedLogAuthority if (empty($id) && empty($signature)) { - $this->error='BadParameter'; + $this->error = 'BadParameter'; return -1; } $langs->load("blockedlog"); $sql = "SELECT b.rowid, b.signature, b.blockchain, b.tms"; - $sql.= " FROM ".MAIN_DB_PREFIX."blockedlog_authority as b"; + $sql .= " FROM ".MAIN_DB_PREFIX."blockedlog_authority as b"; - if ($id) $sql.= " WHERE b.rowid = ". $id; - elseif($signature)$sql.= " WHERE b.signature = '". $this->db->escape($signature) ."'" ; + if ($id) $sql .= " WHERE b.rowid = ".$id; + elseif ($signature)$sql .= " WHERE b.signature = '".$this->db->escape($signature)."'"; - $resql=$this->db->query($sql); + $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->signature = $obj->signature; - $this->blockchain = $obj->blockchain; + $this->signature = $obj->signature; + $this->blockchain = $obj->blockchain; - $this->tms = $this->db->jdate($obj->tms); + $this->tms = $this->db->jdate($obj->tms); return 1; } else { - $this->error=$langs->trans("RecordNotFound"); + $this->error = $langs->trans("RecordNotFound"); return 0; } } else { - $this->error=$this->db->error(); + $this->error = $this->db->error(); return -1; } } @@ -202,23 +202,23 @@ class BlockedLogAuthority public function create($user) { - global $conf,$langs,$hookmanager; + global $conf, $langs, $hookmanager; $langs->load('blockedlog'); - $error=0; + $error = 0; dol_syslog(get_class($this).'::create', LOG_DEBUG); $this->db->begin(); $sql = "INSERT INTO ".MAIN_DB_PREFIX."blockedlog_authority ("; - $sql.= " signature,"; - $sql.= " blockchain"; - $sql.= ") VALUES ("; - $sql.= "'".$this->db->escape($this->signature)."',"; - $sql.= "'".$this->db->escape($this->blockchain)."'"; - $sql.= ")"; + $sql .= " signature,"; + $sql .= " blockchain"; + $sql .= ") VALUES ("; + $sql .= "'".$this->db->escape($this->signature)."',"; + $sql .= "'".$this->db->escape($this->blockchain)."'"; + $sql .= ")"; $res = $this->db->query($sql); if ($res) @@ -241,7 +241,7 @@ class BlockedLogAuthority } else { - $this->error=$this->db->error(); + $this->error = $this->db->error(); $this->db->rollback(); return -1; } @@ -256,19 +256,19 @@ class BlockedLogAuthority public function update($user) { - global $conf,$langs,$hookmanager; + global $conf, $langs, $hookmanager; $langs->load('blockedlog'); - $error=0; + $error = 0; dol_syslog(get_class($this).'::create', LOG_DEBUG); $this->db->begin(); $sql = "UPDATE ".MAIN_DB_PREFIX."blockedlog_authority SET "; - $sql.= " blockchain='".$this->db->escape($this->blockchain)."'"; - $sql.= " WHERE rowid=".$this->id; + $sql .= " blockchain='".$this->db->escape($this->blockchain)."'"; + $sql .= " WHERE rowid=".$this->id; $res = $this->db->query($sql); if ($res) @@ -279,7 +279,7 @@ class BlockedLogAuthority } else { - $this->error=$this->db->error(); + $this->error = $this->db->error(); $this->db->rollback(); return -1; } @@ -296,7 +296,7 @@ class BlockedLogAuthority //TODO create cron task on activation - if(empty($conf->global->BLOCKEDLOG_AUTHORITY_URL) || empty($conf->global->BLOCKEDLOG_USE_REMOTE_AUTHORITY)) { + if (empty($conf->global->BLOCKEDLOG_AUTHORITY_URL) || empty($conf->global->BLOCKEDLOG_USE_REMOTE_AUTHORITY)) { $this->error = $langs->trans('NoAuthorityURLDefined'); return -2; } @@ -307,14 +307,14 @@ class BlockedLogAuthority $blocks = $block_static->getLog('not_certified', 0, 0, 'rowid', 'ASC'); - $signature=$block_static->getSignature(); + $signature = $block_static->getSignature(); - foreach($blocks as &$block) { + foreach ($blocks as &$block) { $url = $conf->global->BLOCKEDLOG_AUTHORITY_URL.'/blockedlog/ajax/authority.php?s='.$signature.'&b='.$block->signature; $res = file_get_contents($url); - echo $block->signature.' '.$url. ' '.$res.'
'; - if($res === 'blockalreadyadded' || $res === 'blockadded') { + echo $block->signature.' '.$url.' '.$res.'
'; + if ($res === 'blockalreadyadded' || $res === 'blockadded') { $block->setCertified(); } else { diff --git a/htdocs/blockedlog/class/blockedlog.class.php b/htdocs/blockedlog/class/blockedlog.class.php index 4981c05afd7..3c6f7563590 100644 --- a/htdocs/blockedlog/class/blockedlog.class.php +++ b/htdocs/blockedlog/class/blockedlog.class.php @@ -105,7 +105,9 @@ class BlockedLog */ public $date_creation; - + /** + * @var integer|string $date_modification; + */ public $date_modification; public $date_object = 0; @@ -113,7 +115,7 @@ class BlockedLog public $ref_object = ''; public $object_data = null; - public $user_fullname=''; + public $user_fullname = ''; /** * Array of tracked event codes @@ -136,14 +138,14 @@ class BlockedLog $this->trackedevents = array(); - if ($conf->facture->enabled) $this->trackedevents['BILL_VALIDATE']='logBILL_VALIDATE'; - if ($conf->facture->enabled) $this->trackedevents['BILL_DELETE']='logBILL_DELETE'; - if ($conf->facture->enabled) $this->trackedevents['BILL_SENTBYMAIL']='logBILL_SENTBYMAIL'; - if ($conf->facture->enabled) $this->trackedevents['DOC_DOWNLOAD']='BlockedLogBillDownload'; - if ($conf->facture->enabled) $this->trackedevents['DOC_PREVIEW']='BlockedLogBillPreview'; + if ($conf->facture->enabled) $this->trackedevents['BILL_VALIDATE'] = 'logBILL_VALIDATE'; + if ($conf->facture->enabled) $this->trackedevents['BILL_DELETE'] = 'logBILL_DELETE'; + if ($conf->facture->enabled) $this->trackedevents['BILL_SENTBYMAIL'] = 'logBILL_SENTBYMAIL'; + if ($conf->facture->enabled) $this->trackedevents['DOC_DOWNLOAD'] = 'BlockedLogBillDownload'; + if ($conf->facture->enabled) $this->trackedevents['DOC_PREVIEW'] = 'BlockedLogBillPreview'; - if ($conf->facture->enabled) $this->trackedevents['PAYMENT_CUSTOMER_CREATE']='logPAYMENT_CUSTOMER_CREATE'; - if ($conf->facture->enabled) $this->trackedevents['PAYMENT_CUSTOMER_DELETE']='logPAYMENT_CUSTOMER_DELETE'; + if ($conf->facture->enabled) $this->trackedevents['PAYMENT_CUSTOMER_CREATE'] = 'logPAYMENT_CUSTOMER_CREATE'; + if ($conf->facture->enabled) $this->trackedevents['PAYMENT_CUSTOMER_DELETE'] = 'logPAYMENT_CUSTOMER_DELETE'; /* Supplier if ($conf->fournisseur->enabled) $this->trackedevents['BILL_SUPPLIER_VALIDATE']='BlockedLogSupplierBillValidate'; @@ -156,12 +158,12 @@ class BlockedLog if ($conf->fournisseur->enabled) $this->trackedevents['PAYMENT_SUPPLIER_DELETE']='BlockedLogsupplierBillPaymentCreate'; */ - if ($conf->don->enabled) $this->trackedevents['DON_VALIDATE']='logDON_VALIDATE'; - if ($conf->don->enabled) $this->trackedevents['DON_DELETE']='logDON_DELETE'; + if ($conf->don->enabled) $this->trackedevents['DON_VALIDATE'] = 'logDON_VALIDATE'; + if ($conf->don->enabled) $this->trackedevents['DON_DELETE'] = 'logDON_DELETE'; //if ($conf->don->enabled) $this->trackedevents['DON_SENTBYMAIL']='logDON_SENTBYMAIL'; - if ($conf->don->enabled) $this->trackedevents['DONATION_PAYMENT_CREATE']='logDONATION_PAYMENT_CREATE'; - if ($conf->don->enabled) $this->trackedevents['DONATION_PAYMENT_DELETE']='logDONATION_PAYMENT_DELETE'; + if ($conf->don->enabled) $this->trackedevents['DONATION_PAYMENT_CREATE'] = 'logDONATION_PAYMENT_CREATE'; + if ($conf->don->enabled) $this->trackedevents['DONATION_PAYMENT_DELETE'] = 'logDONATION_PAYMENT_DELETE'; /* if ($conf->salary->enabled) $this->trackedevents['PAYMENT_SALARY_CREATE']='BlockedLogSalaryPaymentCreate'; @@ -169,18 +171,18 @@ class BlockedLog if ($conf->salary->enabled) $this->trackedevents['PAYMENT_SALARY_DELETE']='BlockedLogSalaryPaymentCreate'; */ - if ($conf->adherent->enabled) $this->trackedevents['MEMBER_SUBSCRIPTION_CREATE']='logMEMBER_SUBSCRIPTION_CREATE'; - if ($conf->adherent->enabled) $this->trackedevents['MEMBER_SUBSCRIPTION_MODIFY']='logMEMBER_SUBSCRIPTION_MODIFY'; - if ($conf->adherent->enabled) $this->trackedevents['MEMBER_SUBSCRIPTION_DELETE']='logMEMBER_SUBSCRIPTION_DELETE'; + if ($conf->adherent->enabled) $this->trackedevents['MEMBER_SUBSCRIPTION_CREATE'] = 'logMEMBER_SUBSCRIPTION_CREATE'; + if ($conf->adherent->enabled) $this->trackedevents['MEMBER_SUBSCRIPTION_MODIFY'] = 'logMEMBER_SUBSCRIPTION_MODIFY'; + if ($conf->adherent->enabled) $this->trackedevents['MEMBER_SUBSCRIPTION_DELETE'] = 'logMEMBER_SUBSCRIPTION_DELETE'; - if ($conf->banque->enabled) $this->trackedevents['PAYMENT_VARIOUS_CREATE']='logPAYMENT_VARIOUS_CREATE'; - if ($conf->banque->enabled) $this->trackedevents['PAYMENT_VARIOUS_MODIFY']='logPAYMENT_VARIOUS_MODIFY'; - if ($conf->banque->enabled) $this->trackedevents['PAYMENT_VARIOUS_DELETE']='logPAYMENT_VARIOUS_DELETE'; + if ($conf->banque->enabled) $this->trackedevents['PAYMENT_VARIOUS_CREATE'] = 'logPAYMENT_VARIOUS_CREATE'; + if ($conf->banque->enabled) $this->trackedevents['PAYMENT_VARIOUS_MODIFY'] = 'logPAYMENT_VARIOUS_MODIFY'; + if ($conf->banque->enabled) $this->trackedevents['PAYMENT_VARIOUS_DELETE'] = 'logPAYMENT_VARIOUS_DELETE'; // $conf->global->BANK_ENABLE_POS_CASHCONTROL must be set to 1 by all POS modules - $moduleposenabled = ($conf->cashdesk->enabled || $conf->takepos->enabled || ! empty($conf->global->BANK_ENABLE_POS_CASHCONTROL)); - if ($moduleposenabled) $this->trackedevents['CASHCONTROL_VALIDATE']='logCASHCONTROL_VALIDATE'; + $moduleposenabled = ($conf->cashdesk->enabled || $conf->takepos->enabled || !empty($conf->global->BANK_ENABLE_POS_CASHCONTROL)); + if ($moduleposenabled) $this->trackedevents['CASHCONTROL_VALIDATE'] = 'logCASHCONTROL_VALIDATE'; } /** @@ -191,102 +193,102 @@ class BlockedLog { global $langs; - if($this->element === 'facture') { + if ($this->element === 'facture') { require_once DOL_DOCUMENT_ROOT.'/compta/facture/class/facture.class.php'; $object = new Facture($this->db); - if ($object->fetch($this->fk_object)>0) { + if ($object->fetch($this->fk_object) > 0) { return $object->getNomUrl(1); } - else{ + else { $this->error++; } } - if($this->element === 'invoice_supplier') { + if ($this->element === 'invoice_supplier') { require_once DOL_DOCUMENT_ROOT.'/fourn/class/fournisseur.facture.class.php'; $object = new FactureFournisseur($this->db); - if ($object->fetch($this->fk_object)>0) { + if ($object->fetch($this->fk_object) > 0) { return $object->getNomUrl(1); } - else{ + else { $this->error++; } } - elseif($this->element === 'payment') { + elseif ($this->element === 'payment') { require_once DOL_DOCUMENT_ROOT.'/compta/paiement/class/paiement.class.php'; $object = new Paiement($this->db); - if ($object->fetch($this->fk_object)>0) { + if ($object->fetch($this->fk_object) > 0) { return $object->getNomUrl(1); } - else{ + else { $this->error++; } } - elseif($this->element === 'payment_supplier') { + elseif ($this->element === 'payment_supplier') { require_once DOL_DOCUMENT_ROOT.'/fourn/class/paiementfourn.class.php'; $object = new PaiementFourn($this->db); - if ($object->fetch($this->fk_object)>0) { + if ($object->fetch($this->fk_object) > 0) { return $object->getNomUrl(1); } - else{ + else { $this->error++; } } - elseif($this->element === 'payment_donation') { + elseif ($this->element === 'payment_donation') { require_once DOL_DOCUMENT_ROOT.'/don/class/paymentdonation.class.php'; $object = new PaymentDonation($this->db); - if ($object->fetch($this->fk_object)>0) { + if ($object->fetch($this->fk_object) > 0) { return $object->getNomUrl(1); } - else{ + else { $this->error++; } } - elseif($this->element === 'payment_various') { + elseif ($this->element === 'payment_various') { require_once DOL_DOCUMENT_ROOT.'/compta/bank/class/paymentvarious.class.php'; $object = new PaymentVarious($this->db); - if ($object->fetch($this->fk_object)>0) { + if ($object->fetch($this->fk_object) > 0) { return $object->getNomUrl(1); } - else{ + else { $this->error++; } } - elseif($this->element === 'don' || $this->element === 'donation') { + elseif ($this->element === 'don' || $this->element === 'donation') { require_once DOL_DOCUMENT_ROOT.'/don/class/don.class.php'; $object = new Don($this->db); - if ($object->fetch($this->fk_object)>0) { + if ($object->fetch($this->fk_object) > 0) { return $object->getNomUrl(1); } - else{ + else { $this->error++; } } - elseif($this->element === 'subscription') { + elseif ($this->element === 'subscription') { require_once DOL_DOCUMENT_ROOT.'/adherents/class/subscription.class.php'; $object = new Subscription($this->db); - if ($object->fetch($this->fk_object)>0) { + if ($object->fetch($this->fk_object) > 0) { return $object->getNomUrl(1); } - else{ + else { $this->error++; } } - elseif($this->element === 'cashcontrol') { + elseif ($this->element === 'cashcontrol') { require_once DOL_DOCUMENT_ROOT.'/compta/cashcontrol/class/cashcontrol.class.php'; $object = new CashControl($this->db); - if ($object->fetch($this->fk_object)>0) { + if ($object->fetch($this->fk_object) > 0) { return $object->getNomUrl(1); } - else{ + else { $this->error++; } } @@ -316,16 +318,16 @@ class BlockedLog { global $langs, $cachedUser; - if(empty($cachedUser))$cachedUser=array(); + if (empty($cachedUser))$cachedUser = array(); - if(empty($cachedUser[$this->fk_user])) { - $u=new User($this->db); - if($u->fetch($this->fk_user)>0) { + if (empty($cachedUser[$this->fk_user])) { + $u = new User($this->db); + if ($u->fetch($this->fk_user) > 0) { $cachedUser[$this->fk_user] = $u; } } - if(!empty($cachedUser[$this->fk_user])) { + if (!empty($cachedUser[$this->fk_user])) { return $cachedUser[$this->fk_user]->getNomUrl(1); } @@ -352,25 +354,25 @@ class BlockedLog // action $this->action = $action; // amount - $this->amounts= $amounts; + $this->amounts = $amounts; // date if ($object->element == 'payment' || $object->element == 'payment_supplier') { $this->date_object = $object->datepaye; } - elseif ($object->element=='payment_salary') + elseif ($object->element == 'payment_salary') { $this->date_object = $object->datev; } elseif ($object->element == 'payment_donation' || $object->element == 'payment_various') { - $this->date_object = $object->datepaid?$object->datepaid:$object->datep; + $this->date_object = $object->datepaid ? $object->datepaid : $object->datep; } - elseif ($object->element=='subscription') + elseif ($object->element == 'subscription') { $this->date_object = $object->dateh; } - elseif ($object->element=='cashcontrol') + elseif ($object->element == 'cashcontrol') { $this->date_object = $object->date_creation; } @@ -378,7 +380,7 @@ class BlockedLog $this->date_object = $object->date; } // ref - $this->ref_object = ((! empty($object->newref)) ? $object->newref : $object->ref); // newref is set when validating a draft, ref is set in other cases + $this->ref_object = ((!empty($object->newref)) ? $object->newref : $object->ref); // newref is set when validating a draft, ref is set in other cases // type of object $this->element = $object->element; // id of object @@ -386,11 +388,11 @@ class BlockedLog // Set object_data - $this->object_data=new stdClass(); + $this->object_data = new stdClass(); // Add fields to exclude $arrayoffieldstoexclude = array( - 'table_element','fields','ref_previous','ref_next','origin','origin_id','oldcopy','picto','error','errors','modelpdf','last_main_doc','civility_id','contact','contact_id', - 'table_element_line','ismultientitymanaged','isextrafieldmanaged', + 'table_element', 'fields', 'ref_previous', 'ref_next', 'origin', 'origin_id', 'oldcopy', 'picto', 'error', 'errors', 'modelpdf', 'last_main_doc', 'civility_id', 'contact', 'contact_id', + 'table_element_line', 'ismultientitymanaged', 'isextrafieldmanaged', 'linkedObjectsIds', 'linkedObjects', 'fk_delivery_address', @@ -400,48 +402,48 @@ class BlockedLog // Add more fields to exclude depending on object type if ($this->element == 'cashcontrol') { $arrayoffieldstoexclude = array_merge($arrayoffieldstoexclude, array( - 'name','lastname','firstname','region','region_id','region_code','state','state_id','state_code','country','country_id','country_code', - 'total_ht','total_tva','total_ttc','total_localtax1','total_localtax2', - 'barcode_type','barcode_type_code','barcode_type_label','barcode_type_coder','mode_reglement_id','cond_reglement_id','mode_reglement','cond_reglement','shipping_method_id', - 'fk_incoterms','label_incoterms','location_incoterms','lines') + 'name', 'lastname', 'firstname', 'region', 'region_id', 'region_code', 'state', 'state_id', 'state_code', 'country', 'country_id', 'country_code', + 'total_ht', 'total_tva', 'total_ttc', 'total_localtax1', 'total_localtax2', + 'barcode_type', 'barcode_type_code', 'barcode_type_label', 'barcode_type_coder', 'mode_reglement_id', 'cond_reglement_id', 'mode_reglement', 'cond_reglement', 'shipping_method_id', + 'fk_incoterms', 'label_incoterms', 'location_incoterms', 'lines') ); } // Add thirdparty info if (empty($object->thirdparty) && method_exists($object, 'fetch_thirdparty')) $object->fetch_thirdparty(); - if (! empty($object->thirdparty)) + if (!empty($object->thirdparty)) { $this->object_data->thirdparty = new stdClass(); - foreach($object->thirdparty as $key=>$value) + foreach ($object->thirdparty as $key=>$value) { - if (in_array($key, $arrayoffieldstoexclude)) continue; // Discard some properties - if (! in_array($key, array( - 'name','name_alias','ref_ext','address','zip','town','state_code','country_code','idprof1','idprof2','idprof3','idprof4','idprof5','idprof6','phone','fax','email','barcode', + if (in_array($key, $arrayoffieldstoexclude)) continue; // Discard some properties + if (!in_array($key, array( + 'name', 'name_alias', 'ref_ext', 'address', 'zip', 'town', 'state_code', 'country_code', 'idprof1', 'idprof2', 'idprof3', 'idprof4', 'idprof5', 'idprof6', 'phone', 'fax', 'email', 'barcode', 'tva_intra', 'localtax1_assuj', 'localtax1_value', 'localtax2_assuj', 'localtax2_value', 'managers', 'capital', 'typent_code', 'forme_juridique_code', 'code_client', 'code_fournisseur' - ))) continue; // Discard if not into a dedicated list + ))) continue; // Discard if not into a dedicated list if (!is_object($value)) $this->object_data->thirdparty->{$key} = $value; } } // Add company info - if (! empty($mysoc)) + if (!empty($mysoc)) { $this->object_data->mycompany = new stdClass(); - foreach($mysoc as $key=>$value) + foreach ($mysoc as $key=>$value) { - if (in_array($key, $arrayoffieldstoexclude)) continue; // Discard some properties - if (! in_array($key, array( - 'name','name_alias','ref_ext','address','zip','town','state_code','country_code','idprof1','idprof2','idprof3','idprof4','idprof5','idprof6','phone','fax','email','barcode', + if (in_array($key, $arrayoffieldstoexclude)) continue; // Discard some properties + if (!in_array($key, array( + 'name', 'name_alias', 'ref_ext', 'address', 'zip', 'town', 'state_code', 'country_code', 'idprof1', 'idprof2', 'idprof3', 'idprof4', 'idprof5', 'idprof6', 'phone', 'fax', 'email', 'barcode', 'tva_intra', 'localtax1_assuj', 'localtax1_value', 'localtax2_assuj', 'localtax2_value', 'managers', 'capital', 'typent_code', 'forme_juridique_code', 'code_client', 'code_fournisseur' - ))) continue; // Discard if not into a dedicated list + ))) continue; // Discard if not into a dedicated list if (!is_object($value)) $this->object_data->mycompany->{$key} = $value; } } // Add user info - if (! empty($user)) + if (!empty($user)) { $this->fk_user = $user->id; $this->user_fullname = $user->getFullName($langs); @@ -450,25 +452,25 @@ class BlockedLog // Field specific to object if ($this->element == 'facture') { - foreach($object as $key=>$value) + foreach ($object as $key=>$value) { - if (in_array($key, $arrayoffieldstoexclude)) continue; // Discard some properties - if (! in_array($key, array( - 'ref','ref_client','ref_supplier','date','datef','datev','type','total_ht','total_tva','total_ttc','localtax1','localtax2','revenuestamp','datepointoftax','note_public','lines' - ))) continue; // Discard if not into a dedicated list + if (in_array($key, $arrayoffieldstoexclude)) continue; // Discard some properties + if (!in_array($key, array( + 'ref', 'ref_client', 'ref_supplier', 'date', 'datef', 'datev', 'type', 'total_ht', 'total_tva', 'total_ttc', 'localtax1', 'localtax2', 'revenuestamp', 'datepointoftax', 'note_public', 'lines' + ))) continue; // Discard if not into a dedicated list if ($key == 'lines') { - $lineid=0; - foreach($value as $tmpline) // $tmpline is object FactureLine + $lineid = 0; + foreach ($value as $tmpline) // $tmpline is object FactureLine { $lineid++; - foreach($tmpline as $keyline => $valueline) + foreach ($tmpline as $keyline => $valueline) { - if (! in_array($keyline, array( - 'ref','multicurrency_code','multicurrency_total_ht','multicurrency_total_tva','multicurrency_total_ttc','qty','product_type','vat_src_code','tva_tx','info_bits','localtax1_tx','localtax2_tx','total_ht','total_tva','total_ttc','total_localtax1','total_localtax2' - ))) continue; // Discard if not into a dedicated list + if (!in_array($keyline, array( + 'ref', 'multicurrency_code', 'multicurrency_total_ht', 'multicurrency_total_tva', 'multicurrency_total_ttc', 'qty', 'product_type', 'vat_src_code', 'tva_tx', 'info_bits', 'localtax1_tx', 'localtax2_tx', 'total_ht', 'total_tva', 'total_ttc', 'total_localtax1', 'total_localtax2' + ))) continue; // Discard if not into a dedicated list - if (! is_object($this->object_data->invoiceline[$lineid])) $this->object_data->invoiceline[$lineid] = new stdClass(); + if (!is_object($this->object_data->invoiceline[$lineid])) $this->object_data->invoiceline[$lineid] = new stdClass(); $this->object_data->invoiceline[$lineid]->{$keyline} = $valueline; } @@ -477,43 +479,43 @@ class BlockedLog elseif (!is_object($value)) $this->object_data->{$key} = $value; } - if (! empty($object->newref)) $this->object_data->ref = $object->newref; + if (!empty($object->newref)) $this->object_data->ref = $object->newref; } elseif ($this->element == 'invoice_supplier') { - foreach($object as $key=>$value) + foreach ($object as $key=>$value) { - if (in_array($key, $arrayoffieldstoexclude)) continue; // Discard some properties - if (! in_array($key, array( - 'ref','ref_client','ref_supplier','date','datef','type','total_ht','total_tva','total_ttc','localtax1','localtax2','revenuestamp','datepointoftax','note_public' - ))) continue; // Discard if not into a dedicated list + if (in_array($key, $arrayoffieldstoexclude)) continue; // Discard some properties + if (!in_array($key, array( + 'ref', 'ref_client', 'ref_supplier', 'date', 'datef', 'type', 'total_ht', 'total_tva', 'total_ttc', 'localtax1', 'localtax2', 'revenuestamp', 'datepointoftax', 'note_public' + ))) continue; // Discard if not into a dedicated list if (!is_object($value)) $this->object_data->{$key} = $value; } - if (! empty($object->newref)) $this->object_data->ref = $object->newref; + if (!empty($object->newref)) $this->object_data->ref = $object->newref; } elseif ($this->element == 'payment' || $this->element == 'payment_supplier' || $this->element == 'payment_donation' || $this->element == 'payment_various') { - $datepayment = $object->datepaye?$object->datepaye:($object->datepaid?$object->datepaid:$object->datep); - $paymenttypeid = $object->paiementid?$object->paiementid:($object->paymenttype?$object->paymenttype:$object->type_payment); + $datepayment = $object->datepaye ? $object->datepaye : ($object->datepaid ? $object->datepaid : $object->datep); + $paymenttypeid = $object->paiementid ? $object->paiementid : ($object->paymenttype ? $object->paymenttype : $object->type_payment); $this->object_data->ref = $object->ref; $this->object_data->date = $datepayment; $this->object_data->type_code = dol_getIdFromCode($this->db, $paymenttypeid, 'c_paiement', 'id', 'code'); - $this->object_data->payment_num = ($object->num_paiement?$object->num_paiement:$object->num_payment); + $this->object_data->payment_num = ($object->num_paiement ? $object->num_paiement : $object->num_payment); //$this->object_data->fk_account = $object->fk_account; $this->object_data->note = $object->note; //var_dump($this->object_data);exit; - $totalamount=0; + $totalamount = 0; - if (! is_array($object->amounts) && $object->amount) + if (!is_array($object->amounts) && $object->amount) { - $object->amounts=array($object->id => $object->amount); + $object->amounts = array($object->id => $object->amount); } - $paymentpartnumber=0; - foreach($object->amounts as $objid => $amount) + $paymentpartnumber = 0; + foreach ($object->amounts as $objid => $amount) { if (empty($amount)) continue; @@ -541,7 +543,7 @@ class BlockedLog $tmpobject = new PaymentVarious($this->db); } - if (! is_object($tmpobject)) + if (!is_object($tmpobject)) { continue; } @@ -559,12 +561,12 @@ class BlockedLog $paymentpart = new stdClass(); $paymentpart->amount = $amount; - if (! in_array($this->element, array('payment_donation', 'payment_various'))) + if (!in_array($this->element, array('payment_donation', 'payment_various'))) { $result = $tmpobject->fetch_thirdparty(); if ($result == 0) { - $this->error='Failed to fetch thirdparty for object with id '.$tmpobject->id; + $this->error = 'Failed to fetch thirdparty for object with id '.$tmpobject->id; $this->errors[] = $this->error; dol_syslog("Failed to fetch thirdparty for object with id ".$tmpobject->id, LOG_ERR); return -1; @@ -608,43 +610,43 @@ class BlockedLog } } - $paymentpartnumber++; // first payment will be 1 + $paymentpartnumber++; // first payment will be 1 $this->object_data->payment_part[$paymentpartnumber] = $paymentpart; } } $this->object_data->amount = $totalamount; - if (! empty($object->newref)) $this->object_data->ref = $object->newref; + if (!empty($object->newref)) $this->object_data->ref = $object->newref; } - elseif($this->element == 'payment_salary') + elseif ($this->element == 'payment_salary') { $this->object_data->amounts = array($object->amount); - if (! empty($object->newref)) $this->object_data->ref = $object->newref; + if (!empty($object->newref)) $this->object_data->ref = $object->newref; } - elseif($this->element == 'subscription') + elseif ($this->element == 'subscription') { - foreach($object as $key=>$value) + foreach ($object as $key=>$value) { - if (in_array($key, $arrayoffieldstoexclude)) continue; // Discard some properties - if (! in_array($key, array( - 'id','datec','dateh','datef','fk_adherent','amount','import_key','statut','note' - ))) continue; // Discard if not into a dedicated list + if (in_array($key, $arrayoffieldstoexclude)) continue; // Discard some properties + if (!in_array($key, array( + 'id', 'datec', 'dateh', 'datef', 'fk_adherent', 'amount', 'import_key', 'statut', 'note' + ))) continue; // Discard if not into a dedicated list if (!is_object($value)) $this->object_data->{$key} = $value; } - if (! empty($object->newref)) $this->object_data->ref = $object->newref; + if (!empty($object->newref)) $this->object_data->ref = $object->newref; } else // Generic case { - foreach($object as $key=>$value) + foreach ($object as $key=>$value) { - if (in_array($key, $arrayoffieldstoexclude)) continue; // Discard some properties + if (in_array($key, $arrayoffieldstoexclude)) continue; // Discard some properties if (!is_object($value)) $this->object_data->{$key} = $value; } - if (! empty($object->newref)) $this->object_data->ref = $object->newref; + if (!empty($object->newref)) $this->object_data->ref = $object->newref; } return 1; @@ -665,59 +667,59 @@ class BlockedLog if (empty($id)) { - $this->error='BadParameter'; + $this->error = 'BadParameter'; return -1; } $langs->load("blockedlog"); $sql = "SELECT b.rowid, b.date_creation, b.signature, b.signature_line, b.amounts, b.action, b.element, b.fk_object, b.entity,"; - $sql.= " b.certified, b.tms, b.fk_user, b.user_fullname, b.date_object, b.ref_object, b.object_data"; - $sql.= " FROM ".MAIN_DB_PREFIX."blockedlog as b"; - if ($id) $sql.= " WHERE b.rowid = ". $id; + $sql .= " b.certified, b.tms, b.fk_user, b.user_fullname, b.date_object, b.ref_object, b.object_data"; + $sql .= " FROM ".MAIN_DB_PREFIX."blockedlog as b"; + if ($id) $sql .= " WHERE b.rowid = ".$id; - $resql=$this->db->query($sql); + $resql = $this->db->query($sql); if ($resql) { if ($this->db->num_rows($resql)) { $obj = $this->db->fetch_object($resql); - $this->id = $obj->rowid; - $this->entity = $obj->entity; + $this->id = $obj->rowid; + $this->entity = $obj->entity; $this->ref = $obj->rowid; - $this->date_creation = $this->db->jdate($obj->date_creation); + $this->date_creation = $this->db->jdate($obj->date_creation); $this->tms = $this->db->jdate($obj->tms); $this->amounts = (double) $obj->amounts; - $this->action = $obj->action; + $this->action = $obj->action; $this->element = $obj->element; - $this->fk_object = $obj->fk_object; - $this->date_object = $this->db->jdate($obj->date_object); - $this->ref_object = $obj->ref_object; + $this->fk_object = $obj->fk_object; + $this->date_object = $this->db->jdate($obj->date_object); + $this->ref_object = $obj->ref_object; - $this->fk_user = $obj->fk_user; - $this->user_fullname = $obj->user_fullname; + $this->fk_user = $obj->fk_user; + $this->user_fullname = $obj->user_fullname; - $this->object_data = $this->dolDecodeBlockedData($obj->object_data); + $this->object_data = $this->dolDecodeBlockedData($obj->object_data); $this->signature = $obj->signature; - $this->signature_line = $obj->signature_line; + $this->signature_line = $obj->signature_line; $this->certified = ($obj->certified == 1); return 1; } else { - $this->error=$langs->trans("RecordNotFound"); + $this->error = $langs->trans("RecordNotFound"); return 0; } } else { - $this->error=$this->db->error(); + $this->error = $this->db->error(); return -1; } } @@ -737,7 +739,7 @@ class BlockedLog //include_once DOL_DOCUMENT_ROOT.'/compta/facture/class/facture.class.php'; $aaa = unserialize($data); //$aaa = unserialize($data); - } catch(Exception $e) { + } catch (Exception $e) { //print $e->getErrs); } return $aaa; @@ -753,7 +755,7 @@ class BlockedLog { $res = $this->db->query("UPDATE ".MAIN_DB_PREFIX."blockedlog SET certified=1 WHERE rowid=".$this->id); - if($res===false) return false; + if ($res === false) return false; return true; } @@ -768,82 +770,82 @@ class BlockedLog public function create($user, $forcesignature = '') { - global $conf,$langs,$hookmanager; + global $conf, $langs, $hookmanager; $langs->load('blockedlog'); - $error=0; + $error = 0; // Clean data - $this->amounts=(double) $this->amounts; + $this->amounts = (double) $this->amounts; dol_syslog(get_class($this).'::create action='.$this->action.' fk_user='.$this->fk_user.' user_fullname='.$this->user_fullname, LOG_DEBUG); // Check parameters/properties - if (! isset($this->amounts)) // amount can be 0 for some events (like when module is disabled) + if (!isset($this->amounts)) // amount can be 0 for some events (like when module is disabled) { - $this->error=$langs->trans("BlockLogNeedAmountsValue"); + $this->error = $langs->trans("BlockLogNeedAmountsValue"); dol_syslog($this->error, LOG_WARNING); return -1; } if (empty($this->element)) { - $this->error=$langs->trans("BlockLogNeedElement"); + $this->error = $langs->trans("BlockLogNeedElement"); dol_syslog($this->error, LOG_WARNING); return -2; } if (empty($this->action)) { - $this->error=$langs->trans("BadParameterWhenCallingCreateOfBlockedLog"); + $this->error = $langs->trans("BadParameterWhenCallingCreateOfBlockedLog"); dol_syslog($this->error, LOG_WARNING); return -3; } - if (empty($this->fk_user)) $this->user_fullname='(Anonymous)'; + if (empty($this->fk_user)) $this->user_fullname = '(Anonymous)'; $this->date_creation = dol_now(); $this->db->begin(); - $previoushash = $this->getPreviousHash(1, 0); // This get last record and lock database until insert is done + $previoushash = $this->getPreviousHash(1, 0); // This get last record and lock database until insert is done $keyforsignature = $this->buildKeyForSignature(); - $this->signature_line = dol_hash($keyforsignature, '5'); // Not really usefull - $this->signature = dol_hash($previoushash . $keyforsignature, '5'); + $this->signature_line = dol_hash($keyforsignature, '5'); // Not really usefull + $this->signature = dol_hash($previoushash.$keyforsignature, '5'); if ($forcesignature) $this->signature = $forcesignature; //var_dump($keyforsignature);var_dump($previoushash);var_dump($this->signature_line);var_dump($this->signature); $sql = "INSERT INTO ".MAIN_DB_PREFIX."blockedlog ("; - $sql.= " date_creation,"; - $sql.= " action,"; - $sql.= " amounts,"; - $sql.= " signature,"; - $sql.= " signature_line,"; - $sql.= " element,"; - $sql.= " fk_object,"; - $sql.= " date_object,"; - $sql.= " ref_object,"; - $sql.= " object_data,"; - $sql.= " certified,"; - $sql.= " fk_user,"; - $sql.= " user_fullname,"; - $sql.= " entity"; - $sql.= ") VALUES ("; - $sql.= "'".$this->db->idate($this->date_creation)."',"; - $sql.= "'".$this->db->escape($this->action)."',"; - $sql.= $this->amounts.","; - $sql.= "'".$this->db->escape($this->signature)."',"; - $sql.= "'".$this->db->escape($this->signature_line)."',"; - $sql.= "'".$this->db->escape($this->element)."',"; - $sql.= $this->fk_object.","; - $sql.= "'".$this->db->idate($this->date_object)."',"; - $sql.= "'".$this->db->escape($this->ref_object)."',"; - $sql.= "'".$this->db->escape(serialize($this->object_data))."',"; - $sql.= "0,"; - $sql.= $this->fk_user.","; - $sql.= "'".$this->db->escape($this->user_fullname)."',"; - $sql.= ($this->entity ? $this->entity : $conf->entity); - $sql.= ")"; + $sql .= " date_creation,"; + $sql .= " action,"; + $sql .= " amounts,"; + $sql .= " signature,"; + $sql .= " signature_line,"; + $sql .= " element,"; + $sql .= " fk_object,"; + $sql .= " date_object,"; + $sql .= " ref_object,"; + $sql .= " object_data,"; + $sql .= " certified,"; + $sql .= " fk_user,"; + $sql .= " user_fullname,"; + $sql .= " entity"; + $sql .= ") VALUES ("; + $sql .= "'".$this->db->idate($this->date_creation)."',"; + $sql .= "'".$this->db->escape($this->action)."',"; + $sql .= $this->amounts.","; + $sql .= "'".$this->db->escape($this->signature)."',"; + $sql .= "'".$this->db->escape($this->signature_line)."',"; + $sql .= "'".$this->db->escape($this->element)."',"; + $sql .= $this->fk_object.","; + $sql .= "'".$this->db->idate($this->date_object)."',"; + $sql .= "'".$this->db->escape($this->ref_object)."',"; + $sql .= "'".$this->db->escape(serialize($this->object_data))."',"; + $sql .= "0,"; + $sql .= $this->fk_user.","; + $sql .= "'".$this->db->escape($this->user_fullname)."',"; + $sql .= ($this->entity ? $this->entity : $conf->entity); + $sql .= ")"; $res = $this->db->query($sql); if ($res) @@ -866,7 +868,7 @@ class BlockedLog } else { - $this->error=$this->db->error(); + $this->error = $this->db->error(); $this->db->rollback(); return -1; } @@ -889,8 +891,8 @@ class BlockedLog // Recalculate hash $keyforsignature = $this->buildKeyForSignature(); - $signature_line = dol_hash($keyforsignature, '5'); // Not really usefull - $signature = dol_hash($previoushash . $keyforsignature, '5'); + $signature_line = dol_hash($keyforsignature, '5'); // Not really usefull + $signature = dol_hash($previoushash.$keyforsignature, '5'); //var_dump($previoushash); var_dump($keyforsignature); var_dump($signature_line); var_dump($signature); $res = ($signature === $this->signature); @@ -927,13 +929,13 @@ class BlockedLog { global $conf; - $previoussignature=''; + $previoussignature = ''; $sql = "SELECT rowid, signature FROM ".MAIN_DB_PREFIX."blockedlog"; - $sql.= " WHERE entity=".$conf->entity; - if ($beforeid) $sql.= " AND rowid < ".(int) $beforeid; - $sql.=" ORDER BY rowid DESC LIMIT 1"; - $sql.=($withlock ? " FOR UPDATE ": ""); + $sql .= " WHERE entity=".$conf->entity; + if ($beforeid) $sql .= " AND rowid < ".(int) $beforeid; + $sql .= " ORDER BY rowid DESC LIMIT 1"; + $sql .= ($withlock ? " FOR UPDATE " : ""); $resql = $this->db->query($sql); if ($resql) { @@ -979,38 +981,38 @@ class BlockedLog global $conf, $cachedlogs; /* $cachedlogs allow fastest search */ - if (empty($cachedlogs)) $cachedlogs=array(); + if (empty($cachedlogs)) $cachedlogs = array(); - if ($element=='all') { - $sql="SELECT rowid FROM ".MAIN_DB_PREFIX."blockedlog + if ($element == 'all') { + $sql = "SELECT rowid FROM ".MAIN_DB_PREFIX."blockedlog WHERE entity=".$conf->entity; } - elseif ($element=='not_certified') { - $sql="SELECT rowid FROM ".MAIN_DB_PREFIX."blockedlog + elseif ($element == 'not_certified') { + $sql = "SELECT rowid FROM ".MAIN_DB_PREFIX."blockedlog WHERE entity=".$conf->entity." AND certified = 0"; } - elseif ($element=='just_certified') { - $sql="SELECT rowid FROM ".MAIN_DB_PREFIX."blockedlog + elseif ($element == 'just_certified') { + $sql = "SELECT rowid FROM ".MAIN_DB_PREFIX."blockedlog WHERE entity=".$conf->entity." AND certified = 1"; } - else{ - $sql="SELECT rowid FROM ".MAIN_DB_PREFIX."blockedlog + else { + $sql = "SELECT rowid FROM ".MAIN_DB_PREFIX."blockedlog WHERE entity=".$conf->entity." AND element='".$element."' AND fk_object=".(int) $fk_object; } - if ($search_fk_user > 0) $sql.=natural_search("fk_user", $search_fk_user, 2); - if ($search_start > 0) $sql.=" AND date_creation >= '".$this->db->idate($search_start)."'"; - if ($search_end > 0) $sql.=" AND date_creation <= '".$this->db->idate($search_end)."'"; - if ($search_ref != '') $sql.=natural_search("ref_object", $search_ref); - if ($search_amount != '') $sql.=natural_search("amounts", $search_amount, 1); - if ($search_code != '' && $search_code != '-1') $sql.=natural_search("action", $search_code, 3); + if ($search_fk_user > 0) $sql .= natural_search("fk_user", $search_fk_user, 2); + if ($search_start > 0) $sql .= " AND date_creation >= '".$this->db->idate($search_start)."'"; + if ($search_end > 0) $sql .= " AND date_creation <= '".$this->db->idate($search_end)."'"; + if ($search_ref != '') $sql .= natural_search("ref_object", $search_ref); + if ($search_amount != '') $sql .= natural_search("amounts", $search_amount, 1); + if ($search_code != '' && $search_code != '-1') $sql .= natural_search("action", $search_code, 3); - $sql.=$this->db->order($sortfield, $sortorder); - $sql.=$this->db->plimit($limit+1); // We want more, because we will stop into loop later with error if we reach max + $sql .= $this->db->order($sortfield, $sortorder); + $sql .= $this->db->plimit($limit + 1); // We want more, because we will stop into loop later with error if we reach max $res = $this->db->query($sql); - if($res) { - $results=array(); + if ($res) { + $results = array(); $i = 0; while ($obj = $this->db->fetch_object($res)) @@ -1024,7 +1026,7 @@ class BlockedLog if (!isset($cachedlogs[$obj->rowid])) { - $b=new BlockedLog($this->db); + $b = new BlockedLog($this->db); $b->fetch($obj->rowid); $cachedlogs[$obj->rowid] = $b; @@ -1046,7 +1048,7 @@ class BlockedLog */ public function getSignature() { - global $db,$conf,$mysoc; + global $db, $conf, $mysoc; if (empty($conf->global->BLOCKEDLOG_ENTITY_FINGERPRINT)) { // creation of a unique fingerprint require_once DOL_DOCUMENT_ROOT.'/core/lib/admin.lib.php'; @@ -1057,7 +1059,7 @@ class BlockedLog dolibarr_set_const($db, 'BLOCKEDLOG_ENTITY_FINGERPRINT', $fingerprint, 'chaine', 0, 'Numeric Unique Fingerprint', $conf->entity); - $conf->global->BLOCKEDLOG_ENTITY_FINGERPRINT=$fingerprint; + $conf->global->BLOCKEDLOG_ENTITY_FINGERPRINT = $fingerprint; } return $conf->global->BLOCKEDLOG_ENTITY_FINGERPRINT; @@ -1077,12 +1079,12 @@ class BlockedLog $result = false; $sql = "SELECT rowid FROM ".MAIN_DB_PREFIX."blockedlog"; - $sql.= " WHERE entity = ".$conf->entity; - if ($ignoresystem) $sql.=" AND action not in ('MODULE_SET','MODULE_RESET')"; - $sql.= $this->db->plimit(1); + $sql .= " WHERE entity = ".$conf->entity; + if ($ignoresystem) $sql .= " AND action not in ('MODULE_SET','MODULE_RESET')"; + $sql .= $this->db->plimit(1); $res = $this->db->query($sql); - if ($res!==false) + if ($res !== false) { $obj = $this->db->fetch_object($res); if ($obj) $result = true; diff --git a/htdocs/bom/admin/setup.php b/htdocs/bom/admin/setup.php index 3bcdd0cbd79..3e3a03e139c 100644 --- a/htdocs/bom/admin/setup.php +++ b/htdocs/bom/admin/setup.php @@ -26,7 +26,7 @@ // Load Dolibarr environment require '../../main.inc.php'; // Libraries -require_once DOL_DOCUMENT_ROOT . "/core/lib/admin.lib.php"; +require_once DOL_DOCUMENT_ROOT."/core/lib/admin.lib.php"; require_once '../lib/bom.lib.php'; //require_once "../class/myclass.class.php"; @@ -34,15 +34,15 @@ require_once '../lib/bom.lib.php'; $langs->loadLangs(array("admin", "mrp")); // Access control -if (! $user->admin) accessforbidden(); +if (!$user->admin) accessforbidden(); // Parameters $action = GETPOST('action', 'alpha'); $backtopage = GETPOST('backtopage', 'alpha'); -$arrayofparameters=array( - 'BILLOFMATERIALS_MYPARAM1'=>array('css'=>'minwidth200','enabled'=>1), - 'BILLOFMATERIALS_MYPARAM2'=>array('css'=>'minwidth500','enabled'=>1) +$arrayofparameters = array( + 'BILLOFMATERIALS_MYPARAM1'=>array('css'=>'minwidth200', 'enabled'=>1), + 'BILLOFMATERIALS_MYPARAM2'=>array('css'=>'minwidth500', 'enabled'=>1) ); @@ -59,7 +59,7 @@ $page_name = "BomSetup"; llxHeader('', $langs->trans($page_name)); // Subheader -$linkback = ''.$langs->trans("BackToModuleList").''; +$linkback = ''.$langs->trans("BackToModuleList").''; print load_fiche_titre($langs->trans($page_name), $linkback, 'object_bom'); @@ -77,14 +77,14 @@ if ($action == 'edit') print ''; print ''; - print '
'; + print '
'; print ''; - foreach($arrayofparameters as $key => $val) + foreach ($arrayofparameters as $key => $val) { print ''; + print ''; } print '
'.$langs->trans("Parameter").''.$langs->trans("Value").'
'; print $form->textwithpicto($langs->trans($key), $langs->trans($key.'Tooltip')); - print '
'; @@ -97,16 +97,16 @@ if ($action == 'edit') } else { - if (! empty($arrayofparameters)) + if (!empty($arrayofparameters)) { - print ''; + print '
'; print ''; - foreach($arrayofparameters as $key => $val) + foreach ($arrayofparameters as $key => $val) { print ''; + print ''; } print '
'.$langs->trans("Parameter").''.$langs->trans("Value").'
'; print $form->textwithpicto($langs->trans($key), $langs->trans($key.'Tooltip')); - print '' . $conf->global->$key . '
'.$conf->global->$key.'
'; diff --git a/htdocs/bom/bom_agenda.php b/htdocs/bom/bom_agenda.php index c38d0a82a69..d0cf2995081 100644 --- a/htdocs/bom/bom_agenda.php +++ b/htdocs/bom/bom_agenda.php @@ -65,20 +65,20 @@ if (empty($page) || $page == -1) { $page = 0; } // If $page is not defined, $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); +$object = new BOM($db); $extrafields = new ExtraFields($db); -$diroutputmassaction=$conf->bom->dir_output . '/temp/massgeneration/'.$user->id; -$hookmanager->initHooks(array('bomagenda','globalcard')); // Note that conf->hooks_modules contains array +$diroutputmassaction = $conf->bom->dir_output.'/temp/massgeneration/'.$user->id; +$hookmanager->initHooks(array('bomagenda', 'globalcard')); // Note that conf->hooks_modules contains array // 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 // 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; +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; @@ -86,14 +86,14 @@ if ($id > 0 || ! empty($ref)) $upload_dir = $conf->bom->multidir_output[$object- * Actions */ -$parameters=array('id'=>$socid); -$reshook=$hookmanager->executeHooks('doActions', $parameters, $object, $action); // Note that $action and $object may have been modified by some hooks +$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 (empty($reshook)) { // Cancel - if (GETPOST('cancel', 'alpha') && ! empty($backtopage)) + if (GETPOST('cancel', 'alpha') && !empty($backtopage)) { header("Location: ".$backtopage); exit; @@ -102,8 +102,8 @@ if (empty($reshook)) // Purge search criteria if (GETPOST('button_removefilter_x', 'alpha') || GETPOST('button_removefilter.x', 'alpha') || GETPOST('button_removefilter', 'alpha')) // All tests are required to be compatible with all browsers { - $actioncode=''; - $search_agenda_label=''; + $actioncode = ''; + $search_agenda_label = ''; } } @@ -119,12 +119,12 @@ $form = new Form($db); if ($object->id > 0) { - $title=$langs->trans("Agenda"); + $title = $langs->trans("Agenda"); //if (! empty($conf->global->MAIN_HTML_TITLE) && preg_match('/thirdpartynameonly/',$conf->global->MAIN_HTML_TITLE) && $object->name) $title=$object->name." - ".$title; $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); @@ -132,9 +132,9 @@ if ($object->id > 0) // Object card // ------------------------------------------------------------ - $linkback = '' . $langs->trans("BackToList") . ''; + $linkback = ''.$langs->trans("BackToList").''; - $morehtmlref='
'; + $morehtmlref = '
'; /* // Ref customer $morehtmlref.=$form->editfieldkey("RefCustomer", 'ref_client', $object->ref_client, $object, 0, 'string', '', 0, 1); @@ -174,7 +174,7 @@ if ($object->id > 0) } } }*/ - $morehtmlref.='
'; + $morehtmlref .= '
'; dol_banner_tab($object, 'ref', $linkback, 1, 'ref', 'ref', $morehtmlref); @@ -193,16 +193,16 @@ if ($object->id > 0) // Actions buttons - $objthirdparty=$object; - $objcon=new stdClass(); + $objthirdparty = $object; + $objcon = new stdClass(); - $out='&origin='.$object->element.'&originid='.$object->id; - $permok=$user->rights->agenda->myactions->create; - if ((! empty($objthirdparty->id) || ! empty($objcon->id)) && $permok) + $out = '&origin='.$object->element.'&originid='.$object->id; + $permok = $user->rights->agenda->myactions->create; + if ((!empty($objthirdparty->id) || !empty($objcon->id)) && $permok) { //$out.='trans("AddAnAction"),'filenew'); //$out.=""; @@ -211,9 +211,9 @@ if ($object->id > 0) print '
'; - if (! empty($conf->agenda->enabled)) + if (!empty($conf->agenda->enabled)) { - if (! empty($user->rights->agenda->myactions->create) || ! empty($user->rights->agenda->allactions->create)) + if (!empty($user->rights->agenda->myactions->create) || !empty($user->rights->agenda->allactions->create)) { print ''.$langs->trans("AddAction").''; } @@ -225,18 +225,18 @@ 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); + $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); //print load_fiche_titre($langs->trans("ActionsOnBom"), '', ''); // List of all actions - $filters=array(); - $filters['search_agenda_label']=$search_agenda_label; + $filters = array(); + $filters['search_agenda_label'] = $search_agenda_label; // TODO Replace this with same code than into list.php show_actions_done($conf, $langs, $db, $object, null, 0, $actioncode, '', $filters, $sortfield, $sortorder); diff --git a/htdocs/bom/bom_card.php b/htdocs/bom/bom_card.php index 941eb621e7c..38ccb13b6b5 100644 --- a/htdocs/bom/bom_card.php +++ b/htdocs/bom/bom_card.php @@ -30,44 +30,44 @@ require_once DOL_DOCUMENT_ROOT.'/bom/class/bom.class.php'; require_once DOL_DOCUMENT_ROOT.'/bom/lib/bom.lib.php'; // Load translation files required by the page -$langs->loadLangs(array("mrp","other")); +$langs->loadLangs(array("mrp", "other")); // Get parameters -$id = GETPOST('id', 'int'); +$id = GETPOST('id', 'int'); $ref = GETPOST('ref', 'alpha'); -$action = GETPOST('action', 'aZ09'); +$action = GETPOST('action', 'aZ09'); $confirm = GETPOST('confirm', 'alpha'); $cancel = GETPOST('cancel', 'aZ09'); -$contextpage= GETPOST('contextpage', 'aZ')?GETPOST('contextpage', 'aZ'):'bomcard'; // To manage different context of search +$contextpage = GETPOST('contextpage', 'aZ') ?GETPOST('contextpage', 'aZ') : 'bomcard'; // To manage different context of search $backtopage = GETPOST('backtopage', 'alpha'); $lineid = GETPOST('lineid', 'int'); // PDF -$hidedetails = (GETPOST('hidedetails', 'int') ? GETPOST('hidedetails', 'int') : (! empty($conf->global->MAIN_GENERATE_DOCUMENTS_HIDE_DETAILS) ? 1 : 0)); -$hidedesc = (GETPOST('hidedesc', 'int') ? GETPOST('hidedesc', 'int') : (! empty($conf->global->MAIN_GENERATE_DOCUMENTS_HIDE_DESC) ? 1 : 0)); -$hideref = (GETPOST('hideref', 'int') ? GETPOST('hideref', 'int') : (! empty($conf->global->MAIN_GENERATE_DOCUMENTS_HIDE_REF) ? 1 : 0)); +$hidedetails = (GETPOST('hidedetails', 'int') ? GETPOST('hidedetails', 'int') : (!empty($conf->global->MAIN_GENERATE_DOCUMENTS_HIDE_DETAILS) ? 1 : 0)); +$hidedesc = (GETPOST('hidedesc', 'int') ? GETPOST('hidedesc', 'int') : (!empty($conf->global->MAIN_GENERATE_DOCUMENTS_HIDE_DESC) ? 1 : 0)); +$hideref = (GETPOST('hideref', 'int') ? GETPOST('hideref', 'int') : (!empty($conf->global->MAIN_GENERATE_DOCUMENTS_HIDE_REF) ? 1 : 0)); // Initialize technical objects -$object=new BOM($db); +$object = new BOM($db); $extrafields = new ExtraFields($db); -$diroutputmassaction=$conf->bom->dir_output . '/temp/massgeneration/'.$user->id; -$hookmanager->initHooks(array('bomcard', 'globalcard')); // Note that conf->hooks_modules contains array +$diroutputmassaction = $conf->bom->dir_output.'/temp/massgeneration/'.$user->id; +$hookmanager->initHooks(array('bomcard', '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_'); +$search_array_options = $extrafields->getOptionalsFromPost($object->table_element, '', 'search_'); // Initialize array of search criterias -$search_all=trim(GETPOST("search_all", 'alpha')); -$search=array(); -foreach($object->fields as $key => $val) +$search_all = trim(GETPOST("search_all", 'alpha')); +$search = array(); +foreach ($object->fields as $key => $val) { - if (GETPOST('search_'.$key, 'alpha')) $search[$key]=GETPOST('search_'.$key, 'alpha'); + 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. +include DOL_DOCUMENT_ROOT.'/core/actions_fetchobject.inc.php'; // Must be include, not include_once. // Security check - Protection if external user //if ($user->socid > 0) access_forbidden(); @@ -79,19 +79,20 @@ $permissionnote=$user->rights->bom->write; // Used by the include of actions_set $permissiondellink=$user->rights->bom->write; // Used by the include of actions_dellink.inc.php $permissiontoadd=$user->rights->bom->write; // Used by the include of actions_addupdatedelete.inc.php and actions_lineupdown.inc.php $permissiontodelete = $user->rights->bom->delete || ($permissiontoadd && isset($object->status) && $object->status == $object::STATUS_DRAFT); +$upload_dir = $conf->bom->multidir_output[isset($object->entity)?$object->entity:1]; /* * Actions */ -$parameters=array(); -$reshook=$hookmanager->executeHooks('doActions', $parameters, $object, $action); // Note that $action and $object may have been modified by some hooks +$parameters = array(); +$reshook = $hookmanager->executeHooks('doActions', $parameters, $object, $action); // Note that $action and $object may have been modified by some hooks if ($reshook < 0) setEventMessages($hookmanager->error, $hookmanager->errors, 'errors'); if (empty($reshook)) { - $error=0; + $error = 0; $backurlforlist = DOL_URL_ROOT.'/bom/bom_list.php'; @@ -100,7 +101,7 @@ if (empty($reshook)) if (empty($id) && (($action != 'add' && $action != 'create') || $cancel)) $backtopage = $backurlforlist; else $backtopage = DOL_URL_ROOT.'/bom/bom_card.php?id='.($id > 0 ? $id : '__ID__'); } - $triggermodname = 'BOM_MODIFY'; // Name of trigger action code to execute when we modify record + $triggermodname = 'BOM_MODIFY'; // Name of trigger action code to execute when we modify record // Actions cancel, add, update, delete or clone include DOL_DOCUMENT_ROOT.'/core/actions_addupdatedelete.inc.php'; @@ -118,9 +119,9 @@ if (empty($reshook)) include DOL_DOCUMENT_ROOT.'/core/actions_builddoc.inc.php'; // Actions to send emails - $trigger_name='BOM_SENTBYMAIL'; - $autocopy='MAIN_MAIL_AUTOCOPY_BOM_TO'; - $trackid='bom'.$object->id; + $trigger_name = 'BOM_SENTBYMAIL'; + $autocopy = 'MAIN_MAIL_AUTOCOPY_BOM_TO'; + $trackid = 'bom'.$object->id; include DOL_DOCUMENT_ROOT.'/core/actions_sendmails.inc.php'; // Add line @@ -140,12 +141,12 @@ if (empty($reshook)) setEventMessages($langs->trans('ErrorFieldRequired', $langs->transnoentitiesnoconv('Qty')), null, 'errors'); $error++; } - if (! ($idprod > 0)) { + if (!($idprod > 0)) { setEventMessages($langs->trans('ErrorFieldRequired', $langs->transnoentitiesnoconv('Product')), null, 'errors'); $error++; } - if (! $error) + if (!$error) { $bomline = new BOMLine($db); $bomline->fk_bom = $id; @@ -176,10 +177,10 @@ if (empty($reshook)) $error = 0; // Set if we used free entry or predefined product - $qty=GETPOST('qty', 'int'); + $qty = GETPOST('qty', 'int'); $qty_frozen = GETPOST('qty_frozen', 'int'); $disable_stock_change = GETPOST('disable_stock_change', 'int'); - $efficiency=GETPOST('efficiency', 'int'); + $efficiency = GETPOST('efficiency', 'int'); if ($qty == '') { setEventMessages($langs->trans('ErrorFieldRequired', $langs->transnoentitiesnoconv('Qty')), null, 'errors'); @@ -212,8 +213,8 @@ if (empty($reshook)) * View */ -$form=new Form($db); -$formfile=new FormFile($db); +$form = new Form($db); +$formfile = new FormFile($db); llxHeader('', $langs->trans("BOM"), ''); @@ -248,10 +249,10 @@ if ($action == 'create') print ''."\n"; // Common attributes - include DOL_DOCUMENT_ROOT . '/core/tpl/commonfields_add.tpl.php'; + include DOL_DOCUMENT_ROOT.'/core/tpl/commonfields_add.tpl.php'; // Other attributes - include DOL_DOCUMENT_ROOT . '/core/tpl/extrafields_add.tpl.php'; + include DOL_DOCUMENT_ROOT.'/core/tpl/extrafields_add.tpl.php'; print '
'."\n"; @@ -260,7 +261,7 @@ if ($action == 'create') print '
'; print ''; print '  '; - print ''; // Cancel for create does not post form if we don't know the backtopage + print ''; // Cancel for create does not post form if we don't know the backtopage print '
'; print ''; @@ -284,10 +285,10 @@ if (($id || $ref) && $action == 'edit') print ''."\n"; // Common attributes - include DOL_DOCUMENT_ROOT . '/core/tpl/commonfields_edit.tpl.php'; + include DOL_DOCUMENT_ROOT.'/core/tpl/commonfields_edit.tpl.php'; // Other attributes - include DOL_DOCUMENT_ROOT . '/core/tpl/extrafields_edit.tpl.php'; + include DOL_DOCUMENT_ROOT.'/core/tpl/extrafields_edit.tpl.php'; print '
'; @@ -313,7 +314,7 @@ if ($object->id > 0 && (empty($action) || ($action != 'edit' && $action != 'crea // Confirmation to delete if ($action == 'delete') { - $formconfirm = $form->formconfirm($_SERVER["PHP_SELF"] . '?id=' . $object->id, $langs->trans('DeleteBillOfMaterials'), $langs->trans('ConfirmDeleteBillOfMaterials'), 'confirm_delete', '', 0, 1); + $formconfirm = $form->formconfirm($_SERVER["PHP_SELF"].'?id='.$object->id, $langs->trans('DeleteBillOfMaterials'), $langs->trans('ConfirmDeleteBillOfMaterials'), 'confirm_delete', '', 0, 1); } // Confirmation to delete line if ($action == 'deleteline') @@ -342,14 +343,14 @@ if ($object->id > 0 && (empty($action) || ($action != 'edit' && $action != 'crea $text .= $notify->confirmMessage('BOM_VALIDATE', $object->socid, $object); }*/ - $formquestion=array(); - if (! empty($conf->bom->enabled)) + $formquestion = array(); + if (!empty($conf->bom->enabled)) { $langs->load("mrp"); - require_once DOL_DOCUMENT_ROOT . '/product/class/html.formproduct.class.php'; + require_once DOL_DOCUMENT_ROOT.'/product/class/html.formproduct.class.php'; $formproduct = new FormProduct($db); - $forcecombo=0; - if ($conf->browser->name == 'ie') $forcecombo = 1; // There is a bug in IE10 that make combo inside popup crazy + $forcecombo = 0; + 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), @@ -357,7 +358,7 @@ if ($object->id > 0 && (empty($action) || ($action != 'edit' && $action != 'crea ); } - $formconfirm = $form->formconfirm($_SERVER["PHP_SELF"] . '?id=' . $object->id, $langs->trans('Validate'), $text, 'confirm_validate', $formquestion, 0, 1, 220); + $formconfirm = $form->formconfirm($_SERVER["PHP_SELF"].'?id='.$object->id, $langs->trans('Validate'), $text, 'confirm_validate', $formquestion, 0, 1, 220); } // Confirmation of closing @@ -372,14 +373,14 @@ if ($object->id > 0 && (empty($action) || ($action != 'edit' && $action != 'crea $text .= $notify->confirmMessage('BOM_CLOSE', $object->socid, $object); }*/ - $formquestion=array(); - if (! empty($conf->bom->enabled)) + $formquestion = array(); + if (!empty($conf->bom->enabled)) { $langs->load("mrp"); - require_once DOL_DOCUMENT_ROOT . '/product/class/html.formproduct.class.php'; + require_once DOL_DOCUMENT_ROOT.'/product/class/html.formproduct.class.php'; $formproduct = new FormProduct($db); - $forcecombo=0; - if ($conf->browser->name == 'ie') $forcecombo = 1; // There is a bug in IE10 that make combo inside popup crazy + $forcecombo = 0; + 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), @@ -387,7 +388,7 @@ if ($object->id > 0 && (empty($action) || ($action != 'edit' && $action != 'crea ); } - $formconfirm = $form->formconfirm($_SERVER["PHP_SELF"] . '?id=' . $object->id, $langs->trans('Close'), $text, 'confirm_close', $formquestion, 0, 1, 220); + $formconfirm = $form->formconfirm($_SERVER["PHP_SELF"].'?id='.$object->id, $langs->trans('Close'), $text, 'confirm_close', $formquestion, 0, 1, 220); } // Confirmation of reopen @@ -402,14 +403,14 @@ if ($object->id > 0 && (empty($action) || ($action != 'edit' && $action != 'crea $text .= $notify->confirmMessage('BOM_CLOSE', $object->socid, $object); }*/ - $formquestion=array(); - if (! empty($conf->bom->enabled)) + $formquestion = array(); + if (!empty($conf->bom->enabled)) { $langs->load("mrp"); - require_once DOL_DOCUMENT_ROOT . '/product/class/html.formproduct.class.php'; + require_once DOL_DOCUMENT_ROOT.'/product/class/html.formproduct.class.php'; $formproduct = new FormProduct($db); - $forcecombo=0; - if ($conf->browser->name == 'ie') $forcecombo = 1; // There is a bug in IE10 that make combo inside popup crazy + $forcecombo = 0; + 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), @@ -417,14 +418,14 @@ if ($object->id > 0 && (empty($action) || ($action != 'edit' && $action != 'crea ); } - $formconfirm = $form->formconfirm($_SERVER["PHP_SELF"] . '?id=' . $object->id, $langs->trans('ReOpen'), $text, 'confirm_reopen', $formquestion, 0, 1, 220); + $formconfirm = $form->formconfirm($_SERVER["PHP_SELF"].'?id='.$object->id, $langs->trans('ReOpen'), $text, 'confirm_reopen', $formquestion, 0, 1, 220); } // Clone confirmation if ($action == 'clone') { // Create an array for form $formquestion = array(); - $formconfirm = $form->formconfirm($_SERVER["PHP_SELF"] . '?id=' . $object->id, $langs->trans('ToClone'), $langs->trans('ConfirmCloneBillOfMaterials', $object->ref), 'confirm_clone', $formquestion, 'yes', 1); + $formconfirm = $form->formconfirm($_SERVER["PHP_SELF"].'?id='.$object->id, $langs->trans('ToClone'), $langs->trans('ConfirmCloneBillOfMaterials', $object->ref), 'confirm_clone', $formquestion, 'yes', 1); } // Confirmation of action xxxx @@ -432,15 +433,15 @@ if ($object->id > 0 && (empty($action) || ($action != 'edit' && $action != 'crea { $text = $langs->trans('ConfirmSetToDraft', $object->ref); - $formquestion=array(); - $formconfirm = $form->formconfirm($_SERVER["PHP_SELF"] . '?id=' . $object->id, $langs->trans('SetToDraft'), $text, 'confirm_setdraft', $formquestion, 0, 1, 220); + $formquestion = array(); + $formconfirm = $form->formconfirm($_SERVER["PHP_SELF"].'?id='.$object->id, $langs->trans('SetToDraft'), $text, 'confirm_setdraft', $formquestion, 0, 1, 220); } // Call Hook formConfirm $parameters = array('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; @@ -448,9 +449,9 @@ if ($object->id > 0 && (empty($action) || ($action != 'edit' && $action != 'crea // Object card // ------------------------------------------------------------ - $linkback = '' . $langs->trans("BackToList") . ''; + $linkback = ''.$langs->trans("BackToList").''; - $morehtmlref='
'; + $morehtmlref = '
'; /* // Ref bis $morehtmlref.=$form->editfieldkey("RefBis", 'ref_client', $object->ref_client, $object, $user->rights->bom->creer, 'string', '', 0, 1); @@ -488,7 +489,7 @@ if ($object->id > 0 && (empty($action) || ($action != 'edit' && $action != 'crea } } */ - $morehtmlref.='
'; + $morehtmlref .= '
'; dol_banner_tab($object, 'ref', $linkback, 1, 'ref', 'ref', $morehtmlref); @@ -500,11 +501,11 @@ if ($object->id > 0 && (empty($action) || ($action != 'edit' && $action != 'crea print ''."\n"; // Common attributes - $keyforbreak='description'; - include DOL_DOCUMENT_ROOT . '/core/tpl/commonfields_view.tpl.php'; + $keyforbreak = 'description'; + include DOL_DOCUMENT_ROOT.'/core/tpl/commonfields_view.tpl.php'; // Other attributes - include DOL_DOCUMENT_ROOT . '/core/tpl/extrafields_view.tpl.php'; + include DOL_DOCUMENT_ROOT.'/core/tpl/extrafields_view.tpl.php'; print '
'; print ''; @@ -574,8 +575,8 @@ if ($object->id > 0 && (empty($action) || ($action != 'edit' && $action != 'crea if ($action != 'presend' && $action != 'editline') { print '
'."\n"; - $parameters=array(); - $reshook=$hookmanager->executeHooks('addMoreActionsButtons', $parameters, $object, $action); // Note that $action and $object may have been modified by hook + $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)) @@ -583,46 +584,65 @@ if ($object->id > 0 && (empty($action) || ($action != 'edit' && $action != 'crea // Send //print '' . $langs->trans('SendMail') . ''."\n"; - if ($user->rights->bom->write && $object->status == BOM::STATUS_VALIDATED) + // Back to draft + if ($object->status == $object::STATUS_VALIDATED) { - print '' . $langs->trans("SetToDraft") . ''; + if ($permissiontoadd) + { + print ''.$langs->trans("SetToDraft").''; + } } // Modify - if ($permissiontoadd) + if ($object->status == $object::STATUS_DRAFT) { - print ''.$langs->trans("Modify").''."\n"; - } - else - { - print ''.$langs->trans('Modify').''."\n"; + if ($permissiontoadd) + { + print ''.$langs->trans("Modify").''."\n"; + } + else + { + print ''.$langs->trans('Modify').''."\n"; + } } // Validate - if ($user->rights->bom->write && $object->status == BOM::STATUS_DRAFT) + if ($object->status == $object::STATUS_DRAFT) { - if (is_array($object->lines) && count($object->lines) > 0) - { - print '' . $langs->trans("Validate") . ''; - } - else - { - print '' . $langs->trans("Validate") . ''; - } + if ($permissiontoadd) + { + if (is_array($object->lines) && count($object->lines) > 0) + { + print '' . $langs->trans("Validate") . ''; + } + else + { + print '' . $langs->trans("Validate") . ''; + } + } } // Close / Cancel - if ($user->rights->bom->write && $object->status == BOM::STATUS_VALIDATED) + if ($permissiontoadd && $object->status == $object::STATUS_VALIDATED) { print '' . $langs->trans("Disable") . ''; } // Re-open - if ($user->rights->bom->write && $object->status == BOM::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)) + { + print '' . $langs->trans("CreateMO") . ''; + } + } + // Clone if ($permissiontoadd) { @@ -668,11 +688,11 @@ if ($object->id > 0 && (empty($action) || ($action != 'edit' && $action != 'crea // Documents $objref = dol_sanitizeFileName($object->ref); - $relativepath = $objref . '/' . $objref . '.pdf'; - $filedir = $conf->bom->dir_output . '/' . $objref; - $urlsource = $_SERVER["PHP_SELF"] . "?id=" . $object->id; - $genallowed = $user->rights->bom->read; // If you can read, you can build the PDF to read content - $delallowed = $user->rights->bom->write; // If you can create/edit, you can remove a file on card + $relativepath = $objref.'/'.$objref.'.pdf'; + $filedir = $conf->bom->dir_output.'/'.$objref; + $urlsource = $_SERVER["PHP_SELF"]."?id=".$object->id; + $genallowed = $user->rights->bom->read; // If you can read, you can build the PDF to read content + $delallowed = $user->rights->bom->write; // If you can create/edit, you can remove a file on card print $formfile->showdocuments('bom', $objref, $filedir, $urlsource, $genallowed, $delallowed, $object->modelpdf, 1, 0, 0, 28, 0, '', '', '', $mysoc->default_lang); // Show links to link elements @@ -685,11 +705,11 @@ if ($object->id > 0 && (empty($action) || ($action != 'edit' && $action != 'crea $MAXEVENT = 10; $morehtmlright = ''; - $morehtmlright.= $langs->trans("SeeAll"); - $morehtmlright.= ''; + $morehtmlright .= $langs->trans("SeeAll"); + $morehtmlright .= ''; // List of actions on element - include_once DOL_DOCUMENT_ROOT . '/core/class/html.formactions.class.php'; + include_once DOL_DOCUMENT_ROOT.'/core/class/html.formactions.class.php'; $formactions = new FormActions($db); $somethingshown = $formactions->showactions($object, 'bom', $socid, 1, '', $MAXEVENT, '', $morehtmlright); @@ -700,8 +720,8 @@ if ($object->id > 0 && (empty($action) || ($action != 'edit' && $action != 'crea if (GETPOST('modelselected')) $action = 'presend'; // Presend form - $modelmail='bom'; - $defaulttopic='InformationMessage'; + $modelmail = 'bom'; + $defaulttopic = 'InformationMessage'; $diroutput = $conf->bom->dir_output; $trackid = 'bom'.$object->id; diff --git a/htdocs/bom/bom_document.php b/htdocs/bom/bom_document.php index f0dac37a5a0..9c2280e889b 100644 --- a/htdocs/bom/bom_document.php +++ b/htdocs/bom/bom_document.php @@ -32,12 +32,12 @@ require_once DOL_DOCUMENT_ROOT.'/bom/class/bom.class.php'; require_once DOL_DOCUMENT_ROOT.'/bom/lib/bom.lib.php'; // Load translation files required by the page -$langs->loadLangs(array("mrp","companies","other","mails")); +$langs->loadLangs(array("mrp", "companies", "other", "mails")); -$action=GETPOST('action', 'aZ09'); -$confirm=GETPOST('confirm', 'alpha'); -$id=(GETPOST('socid', 'int') ? GETPOST('socid', 'int') : GETPOST('id', 'int')); +$action = GETPOST('action', 'aZ09'); +$confirm = GETPOST('confirm', 'alpha'); +$id = (GETPOST('socid', 'int') ? GETPOST('socid', 'int') : GETPOST('id', 'int')); $ref = GETPOST('ref', 'alpha'); // Security check - Protection if external user @@ -53,30 +53,30 @@ if (empty($page) || $page == -1) { $page = 0; } // If $page is not defined, $offset = $conf->liste_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 -$object=new BOM($db); +$object = new BOM($db); $extrafields = new ExtraFields($db); -$diroutputmassaction=$conf->bom->dir_output . '/temp/massgeneration/'.$user->id; -$hookmanager->initHooks(array('bomdocument', 'globalcard')); // Note that conf->hooks_modules contains array +$diroutputmassaction = $conf->bom->dir_output.'/temp/massgeneration/'.$user->id; +$hookmanager->initHooks(array('bomdocument', 'globalcard')); // Note that conf->hooks_modules contains array // 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 // Must be include, not include_once. Include fetch and fetch_thirdparty but not fetch_optionals +include DOL_DOCUMENT_ROOT.'/core/actions_fetchobject.inc.php'; // Must be include, not include_once // Must be include, not include_once. Include fetch and fetch_thirdparty but not fetch_optionals //if ($id > 0 || ! empty($ref)) $upload_dir = $conf->bom->multidir_output[$object->entity?$object->entity:1] . "/bom/" . dol_sanitizeFileName($object->id); -if ($id > 0 || ! empty($ref)) $upload_dir = $conf->bom->multidir_output[$object->entity?$object->entity:1] . "/bom/" . dol_sanitizeFileName($object->ref); +if ($id > 0 || !empty($ref)) $upload_dir = $conf->bom->multidir_output[$object->entity ? $object->entity : 1]."/bom/".dol_sanitizeFileName($object->ref); /* * Actions */ -include_once DOL_DOCUMENT_ROOT . '/core/actions_linkedfiles.inc.php'; +include_once DOL_DOCUMENT_ROOT.'/core/actions_linkedfiles.inc.php'; /* @@ -85,8 +85,8 @@ include_once DOL_DOCUMENT_ROOT . '/core/actions_linkedfiles.inc.php'; $form = new Form($db); -$title=$langs->trans("BillOfMaterials").' - '.$langs->trans("Files"); -$help_url=''; +$title = $langs->trans("BillOfMaterials").' - '.$langs->trans("Files"); +$help_url = ''; //$help_url='EN:Module_Third_Parties|FR:Module_Tiers|ES:Empresas'; llxHeader('', $title, $help_url); @@ -101,16 +101,16 @@ 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) + $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) { - $totalsize+=$file['size']; + $totalsize += $file['size']; } // Object card // ------------------------------------------------------------ - $linkback = '' . $langs->trans("BackToList") . ''; + $linkback = ''.$langs->trans("BackToList").''; dol_banner_tab($object, 'ref', $linkback, 1, 'ref', 'ref', $morehtmlref); @@ -134,12 +134,12 @@ if ($object->id) $modulepart = 'bom'; $permission = $user->rights->bom->write; $permtoedit = $user->rights->bom->write; - $param = '&id=' . $object->id; + $param = '&id='.$object->id; //$relativepathwithnofile='bom/' . dol_sanitizeFileName($object->id).'/'; - $relativepathwithnofile='bom/' . dol_sanitizeFileName($object->ref).'/'; + $relativepathwithnofile = 'bom/'.dol_sanitizeFileName($object->ref).'/'; - include_once DOL_DOCUMENT_ROOT . '/core/tpl/document_actions_post_headers.tpl.php'; + include_once DOL_DOCUMENT_ROOT.'/core/tpl/document_actions_post_headers.tpl.php'; } else { diff --git a/htdocs/bom/bom_list.php b/htdocs/bom/bom_list.php index c61efc84591..0ff7ed8c672 100644 --- a/htdocs/bom/bom_list.php +++ b/htdocs/bom/bom_list.php @@ -31,20 +31,20 @@ require_once DOL_DOCUMENT_ROOT.'/bom/class/bom.class.php'; // Load translation files required by the page $langs->loadLangs(array("mrp", "other")); -$action = GETPOST('action', 'aZ09')?GETPOST('action', 'aZ09'):'view'; // The action 'add', 'create', 'edit', 'update', 'view', ... -$massaction = GETPOST('massaction', 'alpha'); // The bulk action (combo box choice into lists) -$show_files = GETPOST('show_files', 'int'); // Show files area generated by bulk actions ? -$confirm = GETPOST('confirm', 'alpha'); // Result of a confirmation -$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'):'bomlist'; // 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') +$action = GETPOST('action', 'aZ09') ?GETPOST('action', 'aZ09') : 'view'; // The action 'add', 'create', 'edit', 'update', 'view', ... +$massaction = GETPOST('massaction', 'alpha'); // The bulk action (combo box choice into lists) +$show_files = GETPOST('show_files', 'int'); // Show files area generated by bulk actions ? +$confirm = GETPOST('confirm', 'alpha'); // Result of a confirmation +$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') : 'bomlist'; // 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') -$id = GETPOST('id', 'int'); +$id = GETPOST('id', 'int'); // Load variable for pagination -$limit = GETPOST('limit', 'int')?GETPOST('limit', 'int'):$conf->liste_limit; +$limit = GETPOST('limit', 'int') ?GETPOST('limit', 'int') : $conf->liste_limit; $sortfield = GETPOST('sortfield', 'alpha'); $sortorder = GETPOST('sortorder', 'alpha'); $page = GETPOST('page', 'int'); @@ -58,8 +58,8 @@ $pagenext = $page + 1; // Initialize technical objects $object = new BOM($db); $extrafields = new ExtraFields($db); -$diroutputmassaction = $conf->bom->dir_output . '/temp/massgeneration/'.$user->id; -$hookmanager->initHooks(array('bomlist')); // Note that conf->hooks_modules contains array +$diroutputmassaction = $conf->bom->dir_output.'/temp/massgeneration/'.$user->id; +$hookmanager->initHooks(array('bomlist')); // Note that conf->hooks_modules contains array // Fetch optionals attributes and labels $extrafields->fetch_name_optionals_label($object->table_element); @@ -67,11 +67,11 @@ $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 -$socid=0; +$socid = 0; if ($user->socid > 0) // Protection if external user { //$socid = $user->socid; @@ -80,34 +80,34 @@ if ($user->socid > 0) // Protection if external user //$result = restrictedArea($user, 'bom', $id, ''); // Initialize array of search criterias -$search_all=trim(GETPOST("search_all", 'alpha')); -$search=array(); -foreach($object->fields as $key => $val) +$search_all = trim(GETPOST("search_all", 'alpha')); +$search = array(); +foreach ($object->fields as $key => $val) { - if (GETPOST('search_'.$key, 'alpha')) $search[$key]=GETPOST('search_'.$key, 'alpha'); + 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) +foreach ($object->fields as $key => $val) { - if ($val['searchall']) $fieldstosearchall['t.'.$key]=$val['label']; + if ($val['searchall']) $fieldstosearchall['t.'.$key] = $val['label']; } // Definition of fields for list -$arrayfields=array(); -foreach($object->fields as $key => $val) +$arrayfields = array(); +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) + 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], 'checked'=>(($extrafields->attributes[$object->table_element]['list'][$key]<0)?0:1), 'position'=>$extrafields->attributes[$object->table_element]['pos'][$key], 'enabled'=>(abs($extrafields->attributes[$object->table_element]['list'][$key])!=3 && $extrafields->attributes[$object->table_element]['perms'][$key])); + if (!empty($extrafields->attributes[$object->table_element]['list'][$key])) + $arrayfields["ef.".$key] = array('label'=>$extrafields->attributes[$object->table_element]['label'][$key], 'checked'=>(($extrafields->attributes[$object->table_element]['list'][$key] < 0) ? 0 : 1), 'position'=>$extrafields->attributes[$object->table_element]['pos'][$key], 'enabled'=>(abs($extrafields->attributes[$object->table_element]['list'][$key]) != 3 && $extrafields->attributes[$object->table_element]['perms'][$key])); } } $object->fields = dol_sort_array($object->fields, 'position'); @@ -122,11 +122,11 @@ $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 +$parameters = array(); +$reshook = $hookmanager->executeHooks('doActions', $parameters, $object, $action); // Note that $action and $object may have been modified by some hooks if ($reshook < 0) setEventMessages($hookmanager->error, $hookmanager->errors, 'errors'); if (empty($reshook)) @@ -135,24 +135,24 @@ if (empty($reshook)) 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 { - foreach($object->fields as $key => $val) + foreach ($object->fields as $key => $val) { - $search[$key]=''; + $search[$key] = ''; } - $toselect=''; - $search_array_options=array(); + $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')) { - $massaction=''; // Protection to avoid mass action if we force a new search during a mass action confirmation + $massaction = ''; // Protection to avoid mass action if we force a new search during a mass action confirmation } // Mass actions - $objectclass='BOM'; - $objectlabel='BillOfMaterials'; + $objectclass = 'BOM'; + $objectlabel = 'BillOfMaterials'; $permissiontoread = $user->rights->bom->read; $permissiontodelete = $user->rights->bom->delete; $uploaddir = $conf->bom->dir_output; @@ -160,18 +160,18 @@ if (empty($reshook)) // Validate records - if (! $error && $massaction == 'disable' && $permissiontoadd) + if (!$error && $massaction == 'disable' && $permissiontoadd) { - $objecttmp=new $objectclass($db); + $objecttmp = new $objectclass($db); - if (! $error) + if (!$error) { $db->begin(); $nbok = 0; - foreach($toselect as $toselectid) + foreach ($toselect as $toselectid) { - $result=$objecttmp->fetch($toselectid); + $result = $objecttmp->fetch($toselectid); if ($result > 0) { if ($objecttmp->status != $objecttmp::STATUS_VALIDATED) @@ -200,7 +200,7 @@ if (empty($reshook)) } } - if (! $error) + if (!$error) { if ($nbok > 1) setEventMessages($langs->trans("RecordsModified", $nbok), null, 'mesgs'); else setEventMessages($langs->trans("RecordsModified", $nbok), null, 'mesgs'); @@ -275,48 +275,48 @@ if (empty($reshook)) * View */ -$form=new Form($db); +$form = new Form($db); -$now=dol_now(); +$now = dol_now(); //$help_url="EN:Module_BillOfMaterials|FR:Module_BillOfMaterials_FR|ES:Módulo_BillOfMaterials"; -$help_url=''; +$help_url = ''; $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.', '; + $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.', ' : ''); +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.', ' : ''); } // Add fields from hooks -$parameters=array(); -$reshook=$hookmanager->executeHooks('printFieldListSelect', $parameters, $object); // Note that $action and $object may have been modified by hook -$sql.=$hookmanager->resPrint; -$sql=preg_replace('/, $/', '', $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) +$parameters = array(); +$reshook = $hookmanager->executeHooks('printFieldListSelect', $parameters, $object); // Note that $action and $object may have been modified by hook +$sql .= $hookmanager->resPrint; +$sql = preg_replace('/, $/', '', $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; - $mode_search=(($object->isInt($object->fields[$key]) || $object->isFloat($object->fields[$key]))?1:0); - if ($search[$key] != '') $sql.=natural_search($key, $search[$key], (($key == 'status')?2:$mode_search)); + $mode_search = (($object->isInt($object->fields[$key]) || $object->isFloat($object->fields[$key])) ? 1 : 0); + 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 -$parameters=array(); -$reshook=$hookmanager->executeHooks('printFieldListWhere', $parameters, $object); // Note that $action and $object may have been modified by hook -$sql.=$hookmanager->resPrint; +$parameters = array(); +$reshook = $hookmanager->executeHooks('printFieldListWhere', $parameters, $object); // Note that $action and $object may have been modified by hook +$sql .= $hookmanager->resPrint; /* If a group by is required $sql.= " GROUP BY " @@ -335,7 +335,7 @@ $sql.=$hookmanager->resPrint; $sql=preg_replace('/, $/','', $sql); */ -$sql.=$db->order($sortfield, $sortorder); +$sql .= $db->order($sortfield, $sortorder); // Count total nb of records $nbtotalofrecords = ''; @@ -356,10 +356,10 @@ if (is_numeric($nbtotalofrecords) && $limit > $nbtotalofrecords) } else { - $sql.= $db->plimit($limit+1, $offset); + $sql .= $db->plimit($limit + 1, $offset); - $resql=$db->query($sql); - if (! $resql) + $resql = $db->query($sql); + if (!$resql) { dol_print_error($db); exit; @@ -369,7 +369,7 @@ else } // Direct jump if only one record found -if ($num == 1 && ! empty($conf->global->MAIN_SEARCH_DIRECT_OPEN_IF_ONLY_ONE) && $search_all) +if ($num == 1 && !empty($conf->global->MAIN_SEARCH_DIRECT_OPEN_IF_ONLY_ONE) && $search_all) { $obj = $db->fetch_object($resql); $id = $obj->rowid; @@ -437,16 +437,16 @@ $newcardbutton = dolGetButtonTitle($langs->trans('New'), '', 'fa fa-plus-circle' print_barre_liste($title, $page, $_SERVER["PHP_SELF"], $param, $sortfield, $sortorder, $massactionbutton, $num, $nbtotalofrecords, 'cubes', 0, $newcardbutton, '', $limit); // Add code for pre mass action (confirmation or email presend form) -$topicmail="SendBillOfMaterialsRef"; -$modelmail="bom"; -$objecttmp=new BOM($db); -$trackid='xxxx'.$object->id; +$topicmail = "SendBillOfMaterialsRef"; +$modelmail = "bom"; +$objecttmp = new BOM($db); +$trackid = 'xxxx'.$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); - print '
'.$langs->trans("FilterOnInto", $search_all) . join(', ', $fieldstosearchall).'
'; + foreach ($fieldstosearchall as $key => $val) $fieldstosearchall[$key] = $langs->trans($val); + print '
'.$langs->trans("FilterOnInto", $search_all).join(', ', $fieldstosearchall).'
'; } $moreforfilter = ''; @@ -454,39 +454,39 @@ $moreforfilter = ''; $moreforfilter.= $langs->trans('MyFilter') . ': '; $moreforfilter.= '
';*/ -$parameters=array(); -$reshook=$hookmanager->executeHooks('printFieldPreListTitle', $parameters, $object); // Note that $action and $object may have been modified by hook +$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($moreforfilter)) +if (!empty($moreforfilter)) { print '
'; print $moreforfilter; print '
'; } -$varpage=empty($contextpage)?$_SERVER["PHP_SELF"]:$contextpage; -$selectedfields=$form->multiSelectArrayWithCheckbox('selectedfields', $arrayfields, $varpage); // This also change content of $arrayfields -$selectedfields.=(count($arrayofmassactions) ? $form->showCheckAddButtons('checkforselect', 1) : ''); +$varpage = empty($contextpage) ? $_SERVER["PHP_SELF"] : $contextpage; +$selectedfields = $form->multiSelectArrayWithCheckbox('selectedfields', $arrayfields, $varpage); // This also change content of $arrayfields +$selectedfields .= (count($arrayofmassactions) ? $form->showCheckAddButtons('checkforselect', 1) : ''); -print '
'; // You can use div-table-responsive-no-min if you dont need reserved height for your table -print ''."\n"; +print '
'; // You can use div-table-responsive-no-min if you dont need reserved height for your table +print '
'."\n"; // Fields title search // -------------------------------------------------------------------- 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'])) + $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'])) { - print ''; @@ -496,12 +496,12 @@ foreach($object->fields as $key => $val) include DOL_DOCUMENT_ROOT.'/core/tpl/extrafields_list_search_input.tpl.php'; // Fields from hook -$parameters=array('arrayfields'=>$arrayfields); -$reshook=$hookmanager->executeHooks('printFieldListOption', $parameters, $object); // Note that $action and $object may have been modified by hook +$parameters = array('arrayfields'=>$arrayfields); +$reshook = $hookmanager->executeHooks('printFieldListOption', $parameters, $object); // Note that $action and $object may have been modified by hook print $hookmanager->resPrint; // Action column print ''; print ''."\n"; @@ -510,23 +510,23 @@ 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'])) + $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'])) { - print getTitleFieldOfList($arrayfields['t.'.$key]['label'], 0, $_SERVER['PHP_SELF'], 't.'.$key, '', $param, ($cssforfield?'class="'.$cssforfield.'"':''), $sortfield, $sortorder, ($cssforfield?$cssforfield.' ':''))."\n"; + print getTitleFieldOfList($arrayfields['t.'.$key]['label'], 0, $_SERVER['PHP_SELF'], 't.'.$key, '', $param, ($cssforfield ? 'class="'.$cssforfield.'"' : ''), $sortfield, $sortorder, ($cssforfield ? $cssforfield.' ' : ''))."\n"; } } // 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, $object); // Note that $action and $object may have been modified by hook +$parameters = array('arrayfields'=>$arrayfields, 'param'=>$param, 'sortfield'=>$sortfield, 'sortorder'=>$sortorder); +$reshook = $hookmanager->executeHooks('printFieldListTitle', $parameters, $object); // Note that $action and $object may have been modified by hook print $hookmanager->resPrint; // Action column print getTitleFieldOfList($selectedfields, 0, $_SERVER["PHP_SELF"], '', '', '', '', $sortfield, $sortorder, 'center maxwidthsearch ')."\n"; @@ -534,56 +534,56 @@ print ''."\n"; // Detect if we need a fetch on each output line -$needToFetchEachLine=0; +$needToFetchEachLine = 0; if (is_array($extrafields->attributes[$object->table_element]['computed']) && count($extrafields->attributes[$object->table_element]['computed']) > 0) { foreach ($extrafields->attributes[$object->table_element]['computed'] as $key => $val) { - if (preg_match('/\$object/', $val)) $needToFetchEachLine++; // There is at least one compute field that use $object + if (preg_match('/\$object/', $val)) $needToFetchEachLine++; // There is at least one compute field that use $object } } // Loop on record // -------------------------------------------------------------------- -$i=0; -$totalarray=array(); +$i = 0; +$totalarray = array(); while ($i < min($num, $limit)) { $obj = $db->fetch_object($resql); - if (empty($obj)) break; // Should not happen + if (empty($obj)) break; // Should not happen // Store properties in $object $object->id = $obj->rowid; - foreach($object->fields as $key => $val) + foreach ($object->fields as $key => $val) { if (property_exists($obj, $key)) $object->$key = $obj->$key; } // 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'; + $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('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($val['type'], array('double(24,8)', 'double(6,3)', 'integer', 'real', 'price')) && $key != 'status') $cssforfield .= ($cssforfield ? ' ' : '').'right'; - if (! empty($arrayfields['t.'.$key]['checked'])) + if (!empty($arrayfields['t.'.$key]['checked'])) { print ''; if ($key == 'status') print $object->getLibStatut(5); - elseif (in_array($val['type'], array('date','datetime','timestamp'))) print $object->showOutputField($val, $key, $db->jdate($obj->$key), ''); + elseif (in_array($val['type'], array('date', 'datetime', 'timestamp'))) print $object->showOutputField($val, $key, $db->jdate($obj->$key), ''); else print $object->showOutputField($val, $key, $obj->$key, ''); print ''; - if (! $i) $totalarray['nbfield']++; - if (! empty($val['isameasure'])) + if (!$i) $totalarray['nbfield']++; + if (!empty($val['isameasure'])) { - if (! $i) $totalarray['pos'][$totalarray['nbfield']]='t.'.$key; + if (!$i) $totalarray['pos'][$totalarray['nbfield']] = 't.'.$key; $totalarray['val']['t.'.$key] += $obj->$key; } } @@ -591,19 +591,19 @@ while ($i < min($num, $limit)) // Extra fields include DOL_DOCUMENT_ROOT.'/core/tpl/extrafields_list_print_fields.tpl.php'; // Fields from hook - $parameters=array('arrayfields'=>$arrayfields, 'obj'=>$obj); - $reshook=$hookmanager->executeHooks('printFieldListValue', $parameters, $object); // Note that $action and $object may have been modified by hook + $parameters = array('arrayfields'=>$arrayfields, 'obj'=>$obj); + $reshook = $hookmanager->executeHooks('printFieldListValue', $parameters, $object); // Note that $action and $object may have been modified by hook print $hookmanager->resPrint; // Action column print ''; - if (! $i) $totalarray['nbfield']++; + if (!$i) $totalarray['nbfield']++; print ''; @@ -617,16 +617,16 @@ include DOL_DOCUMENT_ROOT.'/core/tpl/list_print_total.tpl.php'; // If no record found if ($num == 0) { - $colspan=1; - foreach($arrayfields as $key => $val) { if (! empty($val['checked'])) $colspan++; } + $colspan = 1; + foreach ($arrayfields as $key => $val) { if (!empty($val['checked'])) $colspan++; } print ''; } $db->free($resql); -$parameters=array('arrayfields'=>$arrayfields, 'sql'=>$sql); -$reshook=$hookmanager->executeHooks('printFieldListFooter', $parameters, $object); // Note that $action and $object may have been modified by hook +$parameters = array('arrayfields'=>$arrayfields, 'sql'=>$sql); +$reshook = $hookmanager->executeHooks('printFieldListFooter', $parameters, $object); // Note that $action and $object may have been modified by hook print $hookmanager->resPrint; print '
'; + print ''; if (is_array($val['arrayofkeyval'])) print $form->selectarray('search_'.$key, $val['arrayofkeyval'], $search[$key], $val['notnull'], 0, 0, '', 1, 0, 0, '', 'maxwidth75'); else print ''; print ''; -$searchpicto=$form->showFilterButtons(); +$searchpicto = $form->showFilterButtons(); print $searchpicto; print '
'; if ($massactionbutton || $massaction) // If we are in select mode (massactionbutton defined) or if we have already selected and sent an action ($massaction) defined { - $selected=0; - if (in_array($obj->rowid, $arrayofselected)) $selected=1; - print ''; + $selected = 0; + if (in_array($obj->rowid, $arrayofselected)) $selected = 1; + print ''; } print '
'.$langs->trans("NoRecordFound").'
'."\n"; @@ -637,19 +637,19 @@ print ''."\n"; if (in_array('builddoc', $arrayofmassactions) && ($nbtotalofrecords === '' || $nbtotalofrecords)) { - $hidegeneratedfilelistifempty=1; - if ($massaction == 'builddoc' || $action == 'remove_file' || $show_files) $hidegeneratedfilelistifempty=0; + $hidegeneratedfilelistifempty = 1; + 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); // Show list of available documents - $urlsource=$_SERVER['PHP_SELF'].'?sortfield='.$sortfield.'&sortorder='.$sortorder; - $urlsource.=str_replace('&', '&', $param); + $urlsource = $_SERVER['PHP_SELF'].'?sortfield='.$sortfield.'&sortorder='.$sortorder; + $urlsource .= str_replace('&', '&', $param); - $filedir=$diroutputmassaction; - $genallowed=$user->rights->bom->read; - $delallowed=$user->rights->bom->create; + $filedir = $diroutputmassaction; + $genallowed = $user->rights->bom->read; + $delallowed = $user->rights->bom->create; print $formfile->showdocuments('massfilesarea_bom', '', $filedir, $urlsource, 0, $delallowed, '', 1, 1, 0, 48, 1, $param, $title, '', '', '', null, $hidegeneratedfilelistifempty); } diff --git a/htdocs/bom/bom_note.php b/htdocs/bom/bom_note.php index e733b96d12b..e37a64d0f28 100644 --- a/htdocs/bom/bom_note.php +++ b/htdocs/bom/bom_note.php @@ -28,20 +28,20 @@ require_once DOL_DOCUMENT_ROOT.'/bom/class/bom.class.php'; require_once DOL_DOCUMENT_ROOT.'/bom/lib/bom.lib.php'; // Load translation files required by the page -$langs->loadLangs(array("mrp","companies")); +$langs->loadLangs(array("mrp", "companies")); // Get parameters -$id = GETPOST('id', 'int'); +$id = GETPOST('id', 'int'); $ref = GETPOST('ref', 'alpha'); -$action = GETPOST('action', 'alpha'); +$action = GETPOST('action', 'alpha'); $cancel = GETPOST('cancel', 'aZ09'); $backtopage = GETPOST('backtopage', 'alpha'); // Initialize technical objects -$object=new BOM($db); +$object = new BOM($db); $extrafields = new ExtraFields($db); -$diroutputmassaction=$conf->bom->dir_output . '/temp/massgeneration/'.$user->id; -$hookmanager->initHooks(array('bomnote','globalcard')); // Note that conf->hooks_modules contains array +$diroutputmassaction = $conf->bom->dir_output.'/temp/massgeneration/'.$user->id; +$hookmanager->initHooks(array('bomnote', 'globalcard')); // Note that conf->hooks_modules contains array // Fetch optionals attributes and labels $extrafields->fetch_name_optionals_label($object->table_element); @@ -52,10 +52,10 @@ $extrafields->fetch_name_optionals_label($object->table_element); //$result = restrictedArea($user, 'bom', $id); // 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; +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; -$permissionnote=1; +$permissionnote = 1; //$permissionnote=$user->rights->bom->creer; // Used by the include of actions_setnotes.inc.php @@ -64,7 +64,7 @@ $permissionnote=1; * Actions */ -include DOL_DOCUMENT_ROOT.'/core/actions_setnotes.inc.php'; // Must be include, not include_once +include DOL_DOCUMENT_ROOT.'/core/actions_setnotes.inc.php'; // Must be include, not include_once /* @@ -74,10 +74,10 @@ include DOL_DOCUMENT_ROOT.'/core/actions_setnotes.inc.php'; // Must be include, $form = new Form($db); //$help_url='EN:Customers_Orders|FR:Commandes_Clients|ES:Pedidos de clientes'; -$help_url=''; +$help_url = ''; llxHeader('', $langs->trans('BillOfMaterials'), $help_url); -if ($id > 0 || ! empty($ref)) +if ($id > 0 || !empty($ref)) { $object->fetch_thirdparty(); @@ -87,9 +87,9 @@ if ($id > 0 || ! empty($ref)) // Object card // ------------------------------------------------------------ - $linkback = '' . $langs->trans("BackToList") . ''; + $linkback = ''.$langs->trans("BackToList").''; - $morehtmlref='
'; + $morehtmlref = '
'; /* // Ref customer $morehtmlref.=$form->editfieldkey("RefCustomer", 'ref_client', $object->ref_client, $object, 0, 'string', '', 0, 1); @@ -129,7 +129,7 @@ if ($id > 0 || ! empty($ref)) } } }*/ - $morehtmlref.='
'; + $morehtmlref .= '
'; dol_banner_tab($object, 'ref', $linkback, 1, 'ref', 'ref', $morehtmlref); @@ -139,7 +139,7 @@ if ($id > 0 || ! empty($ref)) print '
'; - $cssclass="titlefield"; + $cssclass = "titlefield"; include DOL_DOCUMENT_ROOT.'/core/tpl/notes.tpl.php'; print '
'; diff --git a/htdocs/bom/class/bom.class.php b/htdocs/bom/class/bom.class.php index a95b6612d99..be4e9eed510 100644 --- a/htdocs/bom/class/bom.class.php +++ b/htdocs/bom/class/bom.class.php @@ -22,7 +22,7 @@ */ // Put here all includes required by your class file -require_once DOL_DOCUMENT_ROOT . '/core/class/commonobject.class.php'; +require_once DOL_DOCUMENT_ROOT.'/core/class/commonobject.class.php'; //require_once DOL_DOCUMENT_ROOT . '/societe/class/societe.class.php'; //require_once DOL_DOCUMENT_ROOT . '/product/class/product.class.php'; @@ -86,15 +86,17 @@ class BOM extends CommonObject /** * @var array Array with all fields and their property. Do not use it as a static var. It may be modified by constructor. */ - public $fields=array( + public $fields = array( 'rowid' => array('type'=>'integer', 'label'=>'TechnicalID', 'enabled'=>1, 'visible'=>-1, 'position'=>1, 'notnull'=>1, 'index'=>1, 'comment'=>"Id",), - 'ref' => array('type'=>'varchar(128)', 'label'=>'Ref', 'enabled'=>1, 'noteditable'=>1, 'visible'=>4, 'position'=>10, 'notnull'=>1, 'default'=>'(PROV)', 'index'=>1, 'searchall'=>1, 'comment'=>"Reference of BOM", 'showoncombobox'=>'1',), + 'entity' => array('type'=>'integer', 'label'=>'Entity', 'enabled'=>1, 'visible'=>0, 'notnull'=> 1, 'default'=>1, 'index'=>1, 'position'=>5), + 'ref' => array('type'=>'varchar(128)', 'label'=>'Ref', 'enabled'=>1, 'noteditable'=>1, 'visible'=>4, 'position'=>10, 'notnull'=>1, 'default'=>'(PROV)', 'index'=>1, 'searchall'=>1, 'comment'=>"Reference of BOM", 'showoncombobox'=>'1',), 'label' => array('type'=>'varchar(255)', 'label'=>'Label', 'enabled'=>1, 'visible'=>1, 'position'=>30, 'notnull'=>1, 'searchall'=>1, 'showoncombobox'=>'1',), 'description' => array('type'=>'text', 'label'=>'Description', 'enabled'=>1, 'visible'=>-1, 'position'=>60, 'notnull'=>-1,), 'fk_product' => array('type'=>'integer:Product:product/class/product.class.php:1:(finished IS NULL or finished <> 0)', 'label'=>'Product', 'enabled'=>1, 'visible'=>1, 'position'=>35, 'notnull'=>1, 'index'=>1, 'help'=>'ProductBOMHelp'), 'qty' => array('type'=>'real', 'label'=>'Quantity', 'enabled'=>1, 'visible'=>1, 'default'=>1, 'position'=>55, 'notnull'=>1, 'isameasure'=>'1', 'css'=>'maxwidth75imp'), 'efficiency' => array('type'=>'real', 'label'=>'ManufacturingEfficiency', 'enabled'=>1, 'visible'=>-1, 'default'=>1, 'position'=>100, 'notnull'=>0, 'css'=>'maxwidth50imp', 'help'=>'ValueOfMeansLoss'), - 'duration' => array('type'=>'real', 'label'=>'EstimatedDuration', 'enabled'=>1, 'visible'=>-1, 'position'=>101, 'notnull'=>-1, 'css'=>'maxwidth50imp', 'help'=>'EstimatedDurationDesc'), + 'duration' => array('type'=>'duration', 'label'=>'EstimatedDuration', 'enabled'=>1, 'visible'=>-1, 'position'=>101, 'notnull'=>-1, 'css'=>'maxwidth50imp', 'help'=>'EstimatedDurationDesc'), + 'fk_warehouse' => array('type'=>'integer:Entrepot:product/stock/class/entrepot.class.php:0', 'label'=>'WarehouseForProduction', 'enabled'=>1, 'visible'=>-1, 'position'=>102), 'note_public' => array('type'=>'html', 'label'=>'NotePublic', 'enabled'=>1, 'visible'=>-2, 'position'=>161, 'notnull'=>-1,), 'note_private' => array('type'=>'html', 'label'=>'NotePrivate', 'enabled'=>1, 'visible'=>-2, 'position'=>162, 'notnull'=>-1,), 'date_creation' => array('type'=>'datetime', 'label'=>'DateCreation', 'enabled'=>1, 'visible'=>-2, 'position'=>300, 'notnull'=>1,), @@ -156,7 +158,7 @@ class BOM extends CommonObject /** * @var array List of child tables. To know object to delete on cascade. */ - protected $childtablesoncascade=array('bom_bomline'); + protected $childtablesoncascade = array('bom_bomline'); /** * @var BOMLine[] Array of subtable lines @@ -176,11 +178,11 @@ 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) + foreach ($this->fields as $key => $val) { if (isset($val['enabled']) && empty($val['enabled'])) { @@ -189,13 +191,13 @@ class BOM extends CommonObject } // Translate some data of arrayofkeyval - foreach($this->fields as $key => $val) + foreach ($this->fields as $key => $val) { if (is_array($val['arrayofkeyval'])) { - foreach($val['arrayofkeyval'] as $key2 => $val2) + foreach ($val['arrayofkeyval'] as $key2 => $val2) { - $this->fields[$key]['arrayofkeyval'][$key2]=$langs->trans($val2); + $this->fields[$key]['arrayofkeyval'][$key2] = $langs->trans($val2); } } } @@ -235,7 +237,7 @@ 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) @@ -247,18 +249,18 @@ class BOM extends CommonObject unset($object->import_key); // Clear fields - $object->ref = empty($this->fields['ref']['default']) ? $langs->trans("copy_of_").$object->ref: $this->fields['ref']['default']; - $object->label = empty($this->fields['label']['default']) ? $langs->trans("CopyOf")." ".$object->label: $this->fields['label']['default']; + $object->ref = empty($this->fields['ref']['default']) ? $langs->trans("copy_of_").$object->ref : $this->fields['ref']['default']; + $object->label = empty($this->fields['label']['default']) ? $langs->trans("CopyOf")." ".$object->label : $this->fields['label']['default']; $object->status = self::STATUS_DRAFT; // ... // Clear extrafields that are unique 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]); @@ -275,7 +277,7 @@ class BOM extends CommonObject $this->errors = $object->errors; } - if (! $error) + if (!$error) { // copy internal contacts if ($this->copy_linked_contact($object, 'internal') < 0) @@ -284,7 +286,7 @@ class BOM extends CommonObject } } - if (! $error) + if (!$error) { // copy external contacts if same company if (property_exists($this, 'socid') && $this->socid == $object->socid) @@ -320,7 +322,7 @@ class BOM extends CommonObject public function fetch($id, $ref = null) { $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(); return $result; } @@ -331,7 +333,7 @@ class BOM extends CommonObject */ public function fetchLines() { - $this->lines=array(); + $this->lines = array(); $result = $this->fetchLinesCommon(); return $result; @@ -354,40 +356,40 @@ class BOM extends CommonObject dol_syslog(__METHOD__, LOG_DEBUG); - $records=array(); + $records = array(); $sql = 'SELECT '; $sql .= $this->getFieldList(); - $sql .= ' FROM ' . MAIN_DB_PREFIX . $this->table_element. ' as t'; + $sql .= ' FROM '.MAIN_DB_PREFIX.$this->table_element.' as t'; if ($this->ismultientitymanaged) $sql .= ' WHERE t.entity IN ('.getEntity($this->table_element).')'; else $sql .= ' WHERE 1 = 1'; // Manage filter $sqlwhere = array(); if (count($filter) > 0) { foreach ($filter as $key => $value) { - if ($key=='t.rowid') { - $sqlwhere[] = $key . '='. $value; + if ($key == 't.rowid') { + $sqlwhere[] = $key.'='.$value; } elseif (strpos($key, 'date') !== false) { $sqlwhere[] = $key.' = \''.$this->db->idate($value).'\''; } - elseif ($key=='customsql') { + elseif ($key == 'customsql') { $sqlwhere[] = $value; } else { - $sqlwhere[] = $key . ' LIKE \'%' . $this->db->escape($value) . '%\''; + $sqlwhere[] = $key.' LIKE \'%'.$this->db->escape($value).'%\''; } } } if (count($sqlwhere) > 0) { - $sql .= ' AND (' . implode(' '.$filtermode.' ', $sqlwhere).')'; + $sql .= ' AND ('.implode(' '.$filtermode.' ', $sqlwhere).')'; } if (!empty($sortfield)) { $sql .= $this->db->order($sortfield, $sortorder); } if (!empty($limit)) { - $sql .= ' ' . $this->db->plimit($limit, $offset); + $sql .= ' '.$this->db->plimit($limit, $offset); } $resql = $this->db->query($sql); @@ -405,8 +407,8 @@ class BOM extends CommonObject return $records; } else { - $this->errors[] = 'Error ' . $this->db->lasterror(); - dol_syslog(__METHOD__ . ' ' . join(',', $this->errors), LOG_ERR); + $this->errors[] = 'Error '.$this->db->lasterror(); + dol_syslog(__METHOD__.' '.join(',', $this->errors), LOG_ERR); return -1; } @@ -470,21 +472,21 @@ class BOM extends CommonObject global $langs, $conf; $langs->load("mrp"); - if (! empty($conf->global->BOM_ADDON)) + if (!empty($conf->global->BOM_ADDON)) { - $mybool=false; + $mybool = false; $file = $conf->global->BOM_ADDON.".php"; $classname = $conf->global->BOM_ADDON; // Include file with class - $dirmodels=array_merge(array('/'), (array) $conf->modules_parts['models']); + $dirmodels = array_merge(array('/'), (array) $conf->modules_parts['models']); foreach ($dirmodels as $reldir) { $dir = dol_buildpath($reldir."core/modules/bom/"); // Load file with numbering class (if found) - $mybool|=@include_once $dir.$file; + $mybool |= @include_once $dir.$file; } if ($mybool === false) @@ -502,7 +504,7 @@ class BOM extends CommonObject } else { - $this->error=$obj->error; + $this->error = $obj->error; //dol_print_error($this->db,get_class($this)."::getNextNumRef ".$obj->error); return ""; } @@ -527,7 +529,7 @@ class BOM extends CommonObject require_once DOL_DOCUMENT_ROOT.'/core/lib/files.lib.php'; - $error=0; + $error = 0; // Protection if ($this->statut == self::STATUS_VALIDATED) @@ -544,12 +546,12 @@ class BOM extends CommonObject return -1; }*/ - $now=dol_now(); + $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); @@ -562,30 +564,30 @@ class BOM extends CommonObject // Validate $sql = "UPDATE ".MAIN_DB_PREFIX.$this->table_element; - $sql.= " SET ref = '".$this->db->escape($num)."',"; - $sql.= " status = ".self::STATUS_VALIDATED.","; - $sql.= " date_valid='".$this->db->idate($now)."',"; - $sql.= " fk_user_valid = ".$user->id; - $sql.= " WHERE rowid = ".$this->id; + $sql .= " SET ref = '".$this->db->escape($num)."',"; + $sql .= " status = ".self::STATUS_VALIDATED.","; + $sql .= " date_valid='".$this->db->idate($now)."',"; + $sql .= " fk_user_valid = ".$user->id; + $sql .= " WHERE rowid = ".$this->id; dol_syslog(get_class($this)."::validate()", LOG_DEBUG); - $resql=$this->db->query($sql); - if (! $resql) + $resql = $this->db->query($sql); + if (!$resql) { dol_print_error($this->db); - $this->error=$this->db->lasterror(); + $this->error = $this->db->lasterror(); $error++; } - if (! $error && ! $notrigger) + if (!$error && !$notrigger) { // Call trigger - $result=$this->call_trigger('BOM_VALIDATE', $user); + $result = $this->call_trigger('BOM_VALIDATE', $user); if ($result < 0) $error++; // End call triggers } - if (! $error) + if (!$error) { $this->oldref = $this->ref; @@ -593,17 +595,17 @@ class BOM extends CommonObject 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; + $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); @@ -611,13 +613,13 @@ class BOM extends CommonObject { 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) + $listoffiles = dol_dir_list($conf->bom->dir_output.'/'.$newref, 'files', 1, '^'.preg_quote($oldref, '/')); + foreach ($listoffiles as $fileentry) { - $dirsource=$fileentry['name']; - $dirdest=preg_replace('/^'.preg_quote($oldref, '/').'/', $newref, $dirsource); - $dirsource=$fileentry['path'].'/'.$dirsource; - $dirdest=$fileentry['path'].'/'.$dirdest; + $dirsource = $fileentry['name']; + $dirdest = preg_replace('/^'.preg_quote($oldref, '/').'/', $newref, $dirsource); + $dirsource = $fileentry['path'].'/'.$dirsource; + $dirdest = $fileentry['path'].'/'.$dirdest; @rename($dirsource, $dirdest); } } @@ -626,13 +628,13 @@ 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; @@ -736,34 +738,34 @@ class BOM extends CommonObject global $dolibarr_main_authentication, $dolibarr_main_demo; global $menumanager; - 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("BillOfMaterials") . ''; - $label.= '
'; - $label.= '' . $langs->trans('Ref') . ': ' . $this->ref; + $label = ''.$langs->trans("BillOfMaterials").''; + $label .= '
'; + $label .= ''.$langs->trans('Ref').': '.$this->ref; $url = dol_buildpath('/bom/bom_card.php', 1).'?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'; + $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=''; + $linkclose = ''; if (empty($notooltip)) { - if (! empty($conf->global->MAIN_OPTIMIZEFORTEXTBROWSER)) + if (!empty($conf->global->MAIN_OPTIMIZEFORTEXTBROWSER)) { - $label=$langs->trans("ShowBillOfMaterials"); - $linkclose.=' alt="'.dol_escape_htmltag($label, 1).'"'; + $label = $langs->trans("ShowBillOfMaterials"); + $linkclose .= ' alt="'.dol_escape_htmltag($label, 1).'"'; } - $linkclose.=' title="'.dol_escape_htmltag($label, 1).'"'; - $linkclose.=' class="classfortooltip'.($morecss?' '.$morecss:'').'"'; + $linkclose .= ' title="'.dol_escape_htmltag($label, 1).'"'; + $linkclose .= ' class="classfortooltip'.($morecss ? ' '.$morecss : '').'"'; /* $hookmanager->initHooks(array('bomdao')); @@ -772,22 +774,22 @@ class BOM extends CommonObject if ($reshook > 0) $linkclose = $hookmanager->resPrint; */ } - else $linkclose = ($morecss?' class="'.$morecss.'"':''); + else $linkclose = ($morecss ? ' class="'.$morecss.'"' : ''); $linkstart = ''; - $linkend=''; + $linkstart .= $linkclose.'>'; + $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)) : ''); - global $action,$hookmanager; + global $action, $hookmanager; $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 + $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; @@ -840,10 +842,10 @@ class BOM extends CommonObject public function info($id) { $sql = 'SELECT rowid, date_creation as datec, tms as datem,'; - $sql.= ' fk_user_creat, fk_user_modif'; - $sql.= ' FROM '.MAIN_DB_PREFIX.$this->table_element.' as t'; - $sql.= ' WHERE t.rowid = '.$id; - $result=$this->db->query($sql); + $sql .= ' fk_user_creat, fk_user_modif'; + $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)) @@ -854,7 +856,7 @@ class BOM extends CommonObject { $cuser = new User($this->db); $cuser->fetch($obj->fk_user_author); - $this->user_creation = $cuser; + $this->user_creation = $cuser; } if ($obj->fk_user_valid) @@ -868,7 +870,7 @@ class BOM extends CommonObject { $cluser = new User($this->db); $cluser->fetch($obj->fk_user_cloture); - $this->user_cloture = $cluser; + $this->user_cloture = $cluser; } $this->date_creation = $this->db->jdate($obj->datec); @@ -891,7 +893,7 @@ class BOM extends CommonObject */ public function getLinesArray() { - $this->lines=array(); + $this->lines = array(); $objectline = new BOMLine($this->db); $result = $objectline->fetchAll('ASC', 'position', 0, 0, array('customsql'=>'fk_bom = '.$this->id)); @@ -922,16 +924,16 @@ class BOM extends CommonObject */ public function generateDocument($modele, $outputlangs, $hidedetails = 0, $hidedesc = 0, $hideref = 0, $moreparams = null) { - global $conf,$langs; + global $conf, $langs; $langs->load("mrp"); - if (! dol_strlen($modele)) { + if (!dol_strlen($modele)) { $modele = 'standard'; if ($this->modelpdf) { $modele = $this->modelpdf; - } elseif (! empty($conf->global->BOM_ADDON_PDF)) { + } elseif (!empty($conf->global->BOM_ADDON_PDF)) { $modele = $conf->global->BOM_ADDON_PDF; } } @@ -970,7 +972,7 @@ class BOM extends CommonObject $error = 0; $this->output = ''; - $this->error=''; + $this->error = ''; dol_syslog(__METHOD__, LOG_DEBUG); @@ -1041,7 +1043,7 @@ class BOMLine extends CommonObject /** * @var array Array with all fields and their property. Do not use it as a static var. It may be modified by constructor. */ - public $fields=array( + public $fields = array( 'rowid' => array('type'=>'integer', 'label'=>'LineID', 'enabled'=>1, 'visible'=>-1, 'position'=>1, 'notnull'=>1, 'index'=>1, 'comment'=>"Id",), 'fk_bom' => array('type'=>'integer:BillOfMaterials:societe/class/bom.class.php', 'label'=>'BillOfMaterials', 'enabled'=>1, 'visible'=>1, 'position'=>10, 'notnull'=>1, 'index'=>1,), 'fk_product' => array('type'=>'integer:Product:product/class/product.class.php', 'label'=>'Product', 'enabled'=>1, 'visible'=>1, 'position'=>20, 'notnull'=>1, 'index'=>1,), @@ -1049,7 +1051,7 @@ class BOMLine extends CommonObject 'qty' => array('type'=>'double(24,8)', 'label'=>'Quantity', 'enabled'=>1, 'visible'=>1, 'position'=>100, 'notnull'=>1, 'isameasure'=>'1',), 'qty_frozen' => array('type'=>'smallint', 'label'=>'QuantityFrozen', 'enabled'=>1, 'visible'=>1, 'default'=>0, 'position'=>105, 'css'=>'maxwidth50imp', 'help'=>'QuantityConsumedInvariable'), 'disable_stock_change' => array('type'=>'smallint', 'label'=>'DisableStockChange', 'enabled'=>1, 'visible'=>1, 'default'=>0, 'position'=>108, 'css'=>'maxwidth50imp', 'help'=>'DisableStockChangeHelp'), - 'efficiency' => array('type'=>'double(8,4)', 'label'=>'ManufacturingEfficiency', 'enabled'=>1, 'visible'=>1, 'default'=>1, 'position'=>110, 'notnull'=>1, 'css'=>'maxwidth50imp', 'help'=>'ValueOfMeansLoss'), + //'efficiency' => array('type'=>'double(8,4)', 'label'=>'ManufacturingEfficiency', 'enabled'=>1, 'visible'=>0, 'default'=>1, 'position'=>110, 'notnull'=>1, 'css'=>'maxwidth50imp', 'help'=>'ValueOfEfficiencyConsumedMeans'), 'position' => array('type'=>'integer', 'label'=>'Rank', 'enabled'=>1, 'visible'=>0, 'default'=>0, 'position'=>200, 'notnull'=>1,), 'import_key' => array('type'=>'varchar(14)', 'label'=>'ImportId', 'enabled'=>1, 'visible'=>-2, 'position'=>1000, 'notnull'=>-1,), ); @@ -1077,11 +1079,11 @@ class BOMLine 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) + foreach ($this->fields as $key => $val) { if (isset($val['enabled']) && empty($val['enabled'])) { @@ -1090,13 +1092,13 @@ class BOMLine extends CommonObject } // Translate some data of arrayofkeyval - foreach($this->fields as $key => $val) + foreach ($this->fields as $key => $val) { if (is_array($val['arrayofkeyval'])) { - foreach($val['arrayofkeyval'] as $key2 => $val2) + foreach ($val['arrayofkeyval'] as $key2 => $val2) { - $this->fields[$key]['arrayofkeyval'][$key2]=$langs->trans($val2); + $this->fields[$key]['arrayofkeyval'][$key2] = $langs->trans($val2); } } } @@ -1147,40 +1149,40 @@ class BOMLine extends CommonObject dol_syslog(__METHOD__, LOG_DEBUG); - $records=array(); + $records = array(); $sql = 'SELECT '; $sql .= $this->getFieldList(); - $sql .= ' FROM ' . MAIN_DB_PREFIX . $this->table_element. ' as t'; + $sql .= ' FROM '.MAIN_DB_PREFIX.$this->table_element.' as t'; if ($this->ismultientitymanaged) $sql .= ' WHERE t.entity IN ('.getEntity($this->table_element).')'; else $sql .= ' WHERE 1 = 1'; // Manage filter $sqlwhere = array(); if (count($filter) > 0) { foreach ($filter as $key => $value) { - if ($key=='t.rowid') { - $sqlwhere[] = $key . '='. $value; + if ($key == 't.rowid') { + $sqlwhere[] = $key.'='.$value; } elseif (strpos($key, 'date') !== false) { $sqlwhere[] = $key.' = \''.$this->db->idate($value).'\''; } - elseif ($key=='customsql') { + elseif ($key == 'customsql') { $sqlwhere[] = $value; } else { - $sqlwhere[] = $key . ' LIKE \'%' . $this->db->escape($value) . '%\''; + $sqlwhere[] = $key.' LIKE \'%'.$this->db->escape($value).'%\''; } } } if (count($sqlwhere) > 0) { - $sql .= ' AND (' . implode(' '.$filtermode.' ', $sqlwhere).')'; + $sql .= ' AND ('.implode(' '.$filtermode.' ', $sqlwhere).')'; } if (!empty($sortfield)) { $sql .= $this->db->order($sortfield, $sortorder); } if (!empty($limit)) { - $sql .= ' ' . $this->db->plimit($limit, $offset); + $sql .= ' '.$this->db->plimit($limit, $offset); } $resql = $this->db->query($sql); @@ -1198,8 +1200,8 @@ class BOMLine extends CommonObject return $records; } else { - $this->errors[] = 'Error ' . $this->db->lasterror(); - dol_syslog(__METHOD__ . ' ' . join(',', $this->errors), LOG_ERR); + $this->errors[] = 'Error '.$this->db->lasterror(); + dol_syslog(__METHOD__.' '.join(',', $this->errors), LOG_ERR); return -1; } @@ -1246,34 +1248,34 @@ class BOMLine 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 = ''; - $label = '' . $langs->trans("BillOfMaterialsLine") . ''; - $label.= '
'; - $label.= '' . $langs->trans('Ref') . ': ' . $this->ref; + $label = ''.$langs->trans("BillOfMaterialsLine").''; + $label .= '
'; + $label .= ''.$langs->trans('Ref').': '.$this->ref; $url = dol_buildpath('/bom/bomline_card.php', 1).'?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'; + $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=''; + $linkclose = ''; if (empty($notooltip)) { - if (! empty($conf->global->MAIN_OPTIMIZEFORTEXTBROWSER)) + if (!empty($conf->global->MAIN_OPTIMIZEFORTEXTBROWSER)) { - $label=$langs->trans("ShowBillOfMaterialsLine"); - $linkclose.=' alt="'.dol_escape_htmltag($label, 1).'"'; + $label = $langs->trans("ShowBillOfMaterialsLine"); + $linkclose .= ' alt="'.dol_escape_htmltag($label, 1).'"'; } - $linkclose.=' title="'.dol_escape_htmltag($label, 1).'"'; - $linkclose.=' class="classfortooltip'.($morecss?' '.$morecss:'').'"'; + $linkclose .= ' title="'.dol_escape_htmltag($label, 1).'"'; + $linkclose .= ' class="classfortooltip'.($morecss ? ' '.$morecss : '').'"'; /* $hookmanager->initHooks(array('bomlinedao')); @@ -1282,22 +1284,22 @@ class BOMLine extends CommonObject if ($reshook > 0) $linkclose = $hookmanager->resPrint; */ } - else $linkclose = ($morecss?' class="'.$morecss.'"':''); + else $linkclose = ($morecss ? ' class="'.$morecss.'"' : ''); $linkstart = ''; - $linkend=''; + $linkstart .= $linkclose.'>'; + $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)) : ''); - global $action,$hookmanager; + global $action, $hookmanager; $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 + $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; @@ -1338,10 +1340,10 @@ class BOMLine extends CommonObject public function info($id) { $sql = 'SELECT rowid, date_creation as datec, tms as datem,'; - $sql.= ' fk_user_creat, fk_user_modif'; - $sql.= ' FROM '.MAIN_DB_PREFIX.$this->table_element.' as t'; - $sql.= ' WHERE t.rowid = '.$id; - $result=$this->db->query($sql); + $sql .= ' fk_user_creat, fk_user_modif'; + $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)) @@ -1352,7 +1354,7 @@ class BOMLine extends CommonObject { $cuser = new User($this->db); $cuser->fetch($obj->fk_user_author); - $this->user_creation = $cuser; + $this->user_creation = $cuser; } if ($obj->fk_user_valid) @@ -1366,7 +1368,7 @@ class BOMLine extends CommonObject { $cluser = new User($this->db); $cluser->fetch($obj->fk_user_cloture); - $this->user_cloture = $cluser; + $this->user_cloture = $cluser; } $this->date_creation = $this->db->jdate($obj->datec); diff --git a/htdocs/bom/tpl/objectline_create.tpl.php b/htdocs/bom/tpl/objectline_create.tpl.php index 9f6bfee98f2..0e6ef2b8fbd 100644 --- a/htdocs/bom/tpl/objectline_create.tpl.php +++ b/htdocs/bom/tpl/objectline_create.tpl.php @@ -30,7 +30,7 @@ */ // Protection to avoid direct call of template -if (empty($object) || ! is_object($object)) { +if (empty($object) || !is_object($object)) { print "Error: this template page cannot be called directly as an URL"; exit; } @@ -38,11 +38,11 @@ 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' -$colspan = 3; // Columns: total ht + col edit + col delete +$colspan = 3; // Columns: total ht + col edit + col delete //print $object->element; // Lines for extrafield @@ -80,11 +80,11 @@ $coldisplay=0; // Adds a line numbering column if (! empty($conf->global->MAIN_VIEW_LINE_NUMBER)) { $coldisplay++; - echo '
'; +print ''; // Predefined product/service if (! empty($conf->product->enabled) || ! empty($conf->service->enabled)) @@ -109,7 +109,7 @@ if (! empty($conf->product->enabled) || ! empty($conf->service->enabled)) } $coldisplay++; -print ''; +print ''; print ''; +print ''; print ''; +print ''; print ''; -print ''; -print ''; +//print ''; +//print ''; +print ''; print ''; print '
disable_stock_change?' checked="checked"':'')).'">'; print ''; -print ''; +//print ''; @@ -138,7 +138,7 @@ print '
'.$form->textwithpicto($langs->trans('QtyFro print ''.$form->textwithpicto($langs->trans('DisableStockChange'), $langs->trans('DisableStockChangeHelp')).''.$form->textwithpicto($langs->trans('ManufacturingEfficiency'), $langs->trans('ValueOfMeansLoss')).''.$form->textwithpicto($langs->trans('ManufacturingEfficiency'), $langs->trans('XXX')).'
'.($i+1).''.($i + 1).''; @@ -75,10 +75,10 @@ print $tmpproduct->getNomUrl(1); print ''; $coldisplay++; -echo price($line->qty, 0, '', 0, 0); // Yes, it is a quantity, not a price, but we just want the formating role of function price +echo price($line->qty, 0, '', 0, 0); // Yes, it is a quantity, not a price, but we just want the formating role of function price print ''; $label = $line->getLabelOfUnit('short'); @@ -97,12 +97,12 @@ $coldisplay++; echo $line->disable_stock_change ? yn($line->disable_stock_change) : ''; // Yes, it is a quantity, not a price, but we just want the formating role of function price print ''; -$coldisplay++; -echo $line->efficiency; -print ''; +//$coldisplay++; +//echo $line->efficiency; +//print ''; $coldisplay++; if (($line->info_bits & 2) == 2 || ! empty($disableedit)) { @@ -113,9 +113,9 @@ if ($this->status == 0 && ($object_rights->write) && $action != 'selectlines' ) print ''; $coldisplay++; - if (($line->fk_prev_id == null ) && empty($disableremove)) { + if (($line->fk_prev_id == null) && empty($disableremove)) { //La suppression n'est autorisée que si il n'y a pas de ligne dans une précédente situation - print 'id . '">'; + print 'id.'">'; print img_delete(); print ''; } @@ -129,24 +129,24 @@ if ($this->status == 0 && ($object_rights->write) && $action != 'selectlines' ) echo img_up('default', 0, 'imgupforline'); print ''; } - if ($i < $num-1) { + if ($i < $num - 1) { print 'id.'">'; echo img_down('default', 0, 'imgdownforline'); print ''; } print 'browser->layout != 'phone' && empty($disablemove)) ?' class="linecolmove tdlineupdown center"':' class="linecolmove center"').'>browser->layout != 'phone' && empty($disablemove)) ? ' class="linecolmove tdlineupdown center"' : ' class="linecolmove center"').'>'; - print ''; + print ''; print '
'; +print '
'; print ''; print ''; print ''; diff --git a/htdocs/bookmarks/list.php b/htdocs/bookmarks/list.php index 2b34f673107..351f50438ed 100644 --- a/htdocs/bookmarks/list.php +++ b/htdocs/bookmarks/list.php @@ -49,8 +49,8 @@ if (empty($page) || $page == -1 || GETPOST('button_search', 'alpha') || GETPOST( $offset = $limit * $page; $pageprev = $page - 1; $pagenext = $page + 1; -if (! $sortfield) $sortfield='position'; -if (! $sortorder) $sortorder='ASC'; +if (!$sortfield) $sortfield = 'position'; +if (!$sortorder) $sortorder = 'ASC'; $id = GETPOST("id", 'int'); diff --git a/htdocs/cashdesk/admin/cashdesk.php b/htdocs/cashdesk/admin/cashdesk.php index 9f76343a69e..d66b57deaf3 100644 --- a/htdocs/cashdesk/admin/cashdesk.php +++ b/htdocs/cashdesk/admin/cashdesk.php @@ -27,7 +27,7 @@ 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'); @@ -49,7 +49,7 @@ 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,9 +62,9 @@ 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'); @@ -80,12 +80,12 @@ if (GETPOST('action', 'alpha') == 'set') * View */ -$form=new Form($db); -$formproduct=new FormProduct($db); +$form = new Form($db); +$formproduct = new FormProduct($db); llxHeader('', $langs->trans("CashDeskSetup")); -$linkback=''.$langs->trans("BackToModuleList").''; +$linkback = ''.$langs->trans("BackToModuleList").''; print load_fiche_titre($langs->trans("CashDeskSetup").' (SimplePOS)', $linkback, 'title_setup'); print '
'; @@ -95,9 +95,9 @@ print ''; print ''; print ''; -if (! empty($conf->service->enabled)) +if (!empty($conf->service->enabled)) { - print '
'.$langs->trans("Name").''.$langs->trans("Value").'
'; + print '
'; print ''; print ''; print "\n"; @@ -114,7 +114,7 @@ if (! empty($conf->service->enabled)) } -print '
'.$langs->trans("Parameters").''.$langs->trans("Value").'
'; +print '
'; print ''; print ''; print "\n"; @@ -123,7 +123,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 ''; - $disabled=$conf->global->CASHDESK_NO_DECREASE_STOCK; + $disabled = $conf->global->CASHDESK_NO_DECREASE_STOCK; - print ''; // Force warehouse (this is not a default value) + print ''; // Force warehouse (this is not a default value) print ''; - print ''; + print ''; // Order date print ''; // Statut - print ''; + print ''; // Checkbox print ''; print ''; $total = $total + $objp->price; $subtotal = $subtotal + $objp->price; - $i ++; + $i++; } print '
'.$langs->trans("Terminal").' 0'.$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").''; @@ -143,9 +143,9 @@ if (! empty($conf->banque->enabled)) print '
'.$langs->trans("CashDeskDoNotDecreaseStock").'
'.$langs->trans("CashDeskDoNotDecreaseStock").''; if (empty($conf->productbatch->enabled)) { print $form->selectyesno('CASHDESK_NO_DECREASE_STOCK', $conf->global->CASHDESK_NO_DECREASE_STOCK, 1); @@ -160,12 +160,12 @@ if (! empty($conf->stock->enabled)) } print '
'.$langs->trans("CashDeskIdWareHouse").'
'.$langs->trans("CashDeskIdWareHouse").''; - if (! $disabled) + if (!$disabled) { print $formproduct->selectWarehouses($conf->global->CASHDESK_ID_WAREHOUSE, 'CASHDESK_ID_WAREHOUSE', '', 1, $disabled); print ' ('.$langs->trans("Create").')'; @@ -178,7 +178,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").')'; diff --git a/htdocs/cashdesk/class/Facturation.class.php b/htdocs/cashdesk/class/Facturation.class.php index a8119225db9..782280e6d2b 100644 --- a/htdocs/cashdesk/class/Facturation.class.php +++ b/htdocs/cashdesk/class/Facturation.class.php @@ -94,7 +94,7 @@ class Facturation */ public function ajoutArticle() { - global $conf,$db,$mysoc; + global $conf, $db, $mysoc; $thirdpartyid = $_SESSION['CASHDESK_ID_THIRDPARTY']; @@ -108,21 +108,21 @@ class Facturation $vatrowid = $this->tva(); $tmp = getTaxesFromId($vatrowid); - $txtva = $tmp['rate'].(empty($tmp['code'])?'':' ('.$tmp['code'].')'); + $txtva = $tmp['rate'].(empty($tmp['code']) ? '' : ' ('.$tmp['code'].')'); $vat_npr = $tmp['npr']; $localtaxarray = getLocalTaxesFromRate($vatrowid, 0, $societe, $mysoc, 1); // Clean vat code - $vat_src_code=''; + $vat_src_code = ''; if (preg_match('/\((.*)\)/', $txtva, $reg)) { $vat_src_code = $reg[1]; - $txtva = preg_replace('/\s*\(.*\)/', '', $txtva); // Remove code into vatrate. + $txtva = preg_replace('/\s*\(.*\)/', '', $txtva); // Remove code into vatrate. } // Define part of HT, VAT, TTC - $resultarray=calcul_price_total($this->qte, $this->prix(), $this->remisePercent(), $txtva, -1, -1, 0, 'HT', $vat_npr, $product->type, $mysoc, $localtaxarray); + $resultarray = calcul_price_total($this->qte, $this->prix(), $this->remisePercent(), $txtva, -1, -1, 0, 'HT', $vat_npr, $product->type, $mysoc, $localtaxarray); // Calculation of total HT without discount $total_ht = $resultarray[0]; @@ -141,20 +141,20 @@ class Facturation $montant_remise_ht = ($resultarray[6] - $resultarray[0]); $this->montantRemise($montant_remise_ht); - $newcartarray=$_SESSION['poscart']; + $newcartarray = $_SESSION['poscart']; $i = 0; if (!is_null($newcartarray) && !empty($newcartarray)) { - $i=count($newcartarray); + $i = count($newcartarray); } - $newcartarray[$i]['id']=$i; - $newcartarray[$i]['ref']=$product->ref; - $newcartarray[$i]['label']=$product->label; - $newcartarray[$i]['price']=$product->price; - $newcartarray[$i]['price_ttc']=$product->price_ttc; + $newcartarray[$i]['id'] = $i; + $newcartarray[$i]['ref'] = $product->ref; + $newcartarray[$i]['label'] = $product->label; + $newcartarray[$i]['price'] = $product->price; + $newcartarray[$i]['price_ttc'] = $product->price_ttc; - if (! empty($conf->global->PRODUIT_MULTIPRICES)) + if (!empty($conf->global->PRODUIT_MULTIPRICES)) { if (isset($product->multiprices[$societe->price_level])) { @@ -163,17 +163,17 @@ class Facturation } } - $newcartarray[$i]['fk_article']=$this->id; - $newcartarray[$i]['qte']=$this->qte(); - $newcartarray[$i]['fk_tva']=$this->tva(); // Vat rowid - $newcartarray[$i]['remise_percent']=$remise_percent; - $newcartarray[$i]['remise']=price2num($montant_remise_ht); - $newcartarray[$i]['total_ht']=price2num($total_ht, 'MT'); - $newcartarray[$i]['total_ttc']=price2num($total_ttc, 'MT'); - $newcartarray[$i]['total_vat']=price2num($total_vat, 'MT'); - $newcartarray[$i]['total_localtax1']=price2num($total_localtax1, 'MT'); - $newcartarray[$i]['total_localtax2']=price2num($total_localtax2, 'MT'); - $_SESSION['poscart']=$newcartarray; + $newcartarray[$i]['fk_article'] = $this->id; + $newcartarray[$i]['qte'] = $this->qte(); + $newcartarray[$i]['fk_tva'] = $this->tva(); // Vat rowid + $newcartarray[$i]['remise_percent'] = $remise_percent; + $newcartarray[$i]['remise'] = price2num($montant_remise_ht); + $newcartarray[$i]['total_ht'] = price2num($total_ht, 'MT'); + $newcartarray[$i]['total_ttc'] = price2num($total_ttc, 'MT'); + $newcartarray[$i]['total_vat'] = price2num($total_vat, 'MT'); + $newcartarray[$i]['total_localtax1'] = price2num($total_localtax1, 'MT'); + $newcartarray[$i]['total_localtax2'] = price2num($total_localtax2, 'MT'); + $_SESSION['poscart'] = $newcartarray; $this->raz(); } @@ -213,16 +213,16 @@ class Facturation { global $db; - $total_ht=0; - $total_ttc=0; + $total_ht = 0; + $total_ttc = 0; $total_vat = 0; $total_localtax1 = 0; $total_localtax2 = 0; - $tab = (! empty($_SESSION['poscart'])?$_SESSION['poscart']:array()); + $tab = (!empty($_SESSION['poscart']) ? $_SESSION['poscart'] : array()); - $tab_size=count($tab); - for($i=0;$i < $tab_size;$i++) + $tab_size = count($tab); + for ($i = 0; $i < $tab_size; $i++) { // Total HT $remise = $tab[$i]['remise']; @@ -290,11 +290,11 @@ class Facturation public function id($aId = null) { - if ( !$aId ) + if (!$aId) { return $this->id; } - elseif ( $aId == 'RESET' ) + elseif ($aId == 'RESET') { $this->id = null; } @@ -317,7 +317,7 @@ class Facturation { return $this->ref; } - elseif ( $aRef == 'RESET' ) + elseif ($aRef == 'RESET') { $this->ref = null; } @@ -339,7 +339,7 @@ class Facturation { return $this->qte; } - elseif ( $aQte == 'RESET' ) + elseif ($aQte == 'RESET') { $this->qte = null; } @@ -362,7 +362,7 @@ class Facturation { return $this->stock; } - elseif ( $aStock == 'RESET' ) + elseif ($aStock == 'RESET') { $this->stock = null; } @@ -582,7 +582,7 @@ class Facturation { return $this->prix_total_ttc; } - elseif ( $aTotalTtc == 'RESET' ) + elseif ($aTotalTtc == 'RESET') { $this->prix_total_ttc = null; } diff --git a/htdocs/cashdesk/tpl/liste_articles.tpl.php b/htdocs/cashdesk/tpl/liste_articles.tpl.php index d892c1df0e6..6fffbd3ed52 100644 --- a/htdocs/cashdesk/tpl/liste_articles.tpl.php +++ b/htdocs/cashdesk/tpl/liste_articles.tpl.php @@ -18,7 +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; @@ -29,7 +29,7 @@ require_once DOL_DOCUMENT_ROOT.'/societe/class/societe.class.php'; require_once DOL_DOCUMENT_ROOT.'/product/class/product.class.php'; // Load translation files required by the page -$langs->loadLangs(array("main","bills","cashdesk")); +$langs->loadLangs(array("main", "bills", "cashdesk")); ?> @@ -45,18 +45,18 @@ $societe = new Societe($db); $societe->fetch($thirdpartyid); /** end add Ditto */ -$tab = (! empty($_SESSION['poscart'])?$_SESSION['poscart']:array()); +$tab = (!empty($_SESSION['poscart']) ? $_SESSION['poscart'] : array()); -$tab_size=count($tab); +$tab_size = count($tab); if ($tab_size <= 0) print '
'.$langs->trans("NoArticle").'

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

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

'."\n"); - if ( $tab[$i]['remise_percent'] > 0 ) { + if ($tab[$i]['remise_percent'] > 0) { $remise_percent = ' -'.$tab[$i]['remise_percent'].'%'; } else { $remise_percent = ''; diff --git a/htdocs/cashdesk/tpl/validation1.tpl.php b/htdocs/cashdesk/tpl/validation1.tpl.php index fcbd95e8f29..4bc66eff4ad 100644 --- a/htdocs/cashdesk/tpl/validation1.tpl.php +++ b/htdocs/cashdesk/tpl/validation1.tpl.php @@ -17,14 +17,14 @@ */ // 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; } // Load translation files required by the page -$langs->loadLangs(array("main","bills","banks")); +$langs->loadLangs(array("main", "bills", "banks")); // Object $form must de defined @@ -53,30 +53,30 @@ else { case 'ESP': echo $langs->trans("Cash"); - $filtre='courant=2'; + $filtre = 'courant=2'; if (!empty($_SESSION["CASHDESK_ID_BANKACCOUNT_CASH"])) $selected = $_SESSION["CASHDESK_ID_BANKACCOUNT_CASH"]; break; case 'CB': echo $langs->trans("CreditCard"); - $filtre='courant=1'; + $filtre = 'courant=1'; if (!empty($_SESSION["CASHDESK_ID_BANKACCOUNT_CB"])) $selected = $_SESSION["CASHDESK_ID_BANKACCOUNT_CB"]; break; case 'CHQ': echo $langs->trans("Cheque"); - $filtre='courant=1'; + $filtre = 'courant=1'; if (!empty($_SESSION["CASHDESK_ID_BANKACCOUNT_CHEQUE"])) $selected = $_SESSION["CASHDESK_ID_BANKACCOUNT_CHEQUE"]; break; case 'DIF': echo $langs->trans("Reported"); - $filtre='courant=1 OR courant=2'; - $selected=''; + $filtre = 'courant=1 OR courant=2'; + $selected = ''; break; default: - $filtre='courant=1 OR courant=2'; - $selected=''; + $filtre = 'courant=1 OR courant=2'; + $selected = ''; } ?> @@ -103,7 +103,7 @@ if ( $obj_facturation->montantRendu() ) {

trans("BankToPay"). "
"; + echo $langs->trans("BankToPay")."
"; $form->select_comptes($selected, 'cashdeskbank', 0, $filtre); ?>

diff --git a/htdocs/categories/admin/categorie.php b/htdocs/categories/admin/categorie.php index ece7ed2fa5b..7d47724ddd3 100644 --- a/htdocs/categories/admin/categorie.php +++ b/htdocs/categories/admin/categorie.php @@ -87,7 +87,7 @@ $head=categoriesadmin_prepare_head(); dol_fiche_head($head, 'setup', $langs->trans("Categories"), -1, 'category'); -print ''; +print '
'; print ''; print ''; print ''; diff --git a/htdocs/categories/card.php b/htdocs/categories/card.php index 68e2ff5e1d0..d252171b38f 100644 --- a/htdocs/categories/card.php +++ b/htdocs/categories/card.php @@ -35,23 +35,23 @@ require_once DOL_DOCUMENT_ROOT.'/core/class/html.formother.class.php'; $langs->load("categories"); // Security check -$socid=GETPOST('socid', 'int'); +$socid = GETPOST('socid', 'int'); if (!$user->rights->categorie->lire) accessforbidden(); $action = GETPOST('action', 'alpha'); $cancel = GETPOST('cancel', 'alpha'); $origin = GETPOST('origin', 'alpha'); -$catorigin = GETPOST('catorigin', 'int'); -$type = GETPOST('type', 'alpha'); +$catorigin = GETPOST('catorigin', 'int'); +$type = GETPOST('type', 'alpha'); $urlfrom = GETPOST('urlfrom', 'alpha'); $backtopage = GETPOST('backtopage', 'alpha'); -$socid=GETPOST('socid', 'int'); -$label=GETPOST('label'); -$description=GETPOST('description'); -$color=GETPOST('color'); -$visible=GETPOST('visible'); -$parent=GETPOST('parent'); +$socid = GETPOST('socid', 'int'); +$label = GETPOST('label'); +$description = GETPOST('description'); +$color = GETPOST('color'); +$visible = GETPOST('visible'); +$parent = GETPOST('parent'); if ($origin) { @@ -130,17 +130,17 @@ if ($action == 'add' && $user->rights->categorie->creer) $object->label = $label; $object->color = $color; - $object->description = dol_htmlcleanlastbr($description); + $object->description = dol_htmlcleanlastbr($description); $object->socid = ($socid ? $socid : 'null'); - $object->visible = $visible; - $object->type = $type; + $object->visible = $visible; + $object->type = $type; if ($parent != "-1") $object->fk_parent = $parent; $ret = $extrafields->setOptionalsFromPost(null, $object); if ($ret < 0) $error++; - if (! $object->label) + if (!$object->label) { $error++; setEventMessages($langs->trans("ErrorFieldRequired", $langs->transnoentities("Ref")), null, 'errors'); @@ -148,7 +148,7 @@ if ($action == 'add' && $user->rights->categorie->creer) } // Create category in database - if (! $error) + if (!$error) { $result = $object->create($user); if ($result > 0) @@ -223,7 +223,7 @@ if (($action == 'add' || $action == 'confirmed') && $user->rights->categorie->cr $form = new Form($db); $formother = new FormOther($db); -$helpurl=''; +$helpurl = ''; llxHeader("", $langs->trans("Categories"), $helpurl); if ($user->rights->categorie->creer) @@ -258,7 +258,7 @@ if ($user->rights->categorie->creer) // Description print ''; @@ -273,12 +273,12 @@ if ($user->rights->categorie->creer) print ajax_combobox('parent'); print ''; - $parameters=array(); - $reshook=$hookmanager->executeHooks('formObjectOptions', $parameters, $object, $action); // Note that $action and $object may have been modified by hook + $parameters = array(); + $reshook = $hookmanager->executeHooks('formObjectOptions', $parameters, $object, $action); // Note that $action and $object may have been modified by hook print $hookmanager->resPrint; if (empty($reshook)) { - print $object->showOptionals($extrafields, 'edit'); + print $object->showOptionals($extrafields, 'edit', $parameters); } print '
'.$langs->trans("Description").' 
'.$langs->trans("Description").''; require_once DOL_DOCUMENT_ROOT.'/core/class/doleditor.class.php'; - $doleditor=new DolEditor('description', $description, '', 200, 'dolibarr_notes', '', false, true, $conf->global->FCKEDITOR_ENABLE_PRODUCTDESC, ROWS_6, '90%'); + $doleditor = new DolEditor('description', $description, '', 200, 'dolibarr_notes', '', false, true, $conf->global->FCKEDITOR_ENABLE_PRODUCTDESC, ROWS_6, '90%'); $doleditor->Create(); print '
'; diff --git a/htdocs/categories/class/api_categories.class.php b/htdocs/categories/class/api_categories.class.php index d289874d1ee..459b61ba740 100644 --- a/htdocs/categories/class/api_categories.class.php +++ b/htdocs/categories/class/api_categories.class.php @@ -71,25 +71,37 @@ class Categories extends DolibarrApi * Return an array with category informations * * @param int $id ID of category + * @param bool $include_childs Include child categories list (true or false) * @return array|mixed data without useless information * * @throws RestException */ - public function get($id) + public function get($id, $include_childs = false) { - if (! DolibarrApiAccess::$user->rights->categorie->lire) { + if (!DolibarrApiAccess::$user->rights->categorie->lire) { throw new RestException(401); } $result = $this->category->fetch($id); - if ( ! $result ) { + if (!$result) { throw new RestException(404, 'category not found'); } - if ( ! DolibarrApi::_checkAccessToResource('categorie', $this->category->id)) { + if (!DolibarrApi::_checkAccessToResource('categorie', $this->category->id)) { throw new RestException(401, 'Access not allowed for login '.DolibarrApiAccess::$user->login); } + if ($include_childs) { + $cats = $this->category->get_filles(); + if (!is_array($cats)) { + throw new RestException(500, 'Error when fetching child categories', array_merge(array($this->category->error), $this->category->errors)); + } + $this->category->childs = []; + foreach ($cats as $cat) { + $this->category->childs[] = $this->_cleanObjectDatas($cat); + } + } + return $this->_cleanObjectDatas($this->category); } @@ -114,50 +126,50 @@ class Categories extends DolibarrApi $obj_ret = array(); - if(! DolibarrApiAccess::$user->rights->categorie->lire) { + if (!DolibarrApiAccess::$user->rights->categorie->lire) { throw new RestException(401); } $sql = "SELECT t.rowid"; - $sql.= " FROM ".MAIN_DB_PREFIX."categorie as t"; - $sql.= ' WHERE t.entity IN ('.getEntity('category').')'; + $sql .= " FROM ".MAIN_DB_PREFIX."categorie as t"; + $sql .= ' WHERE t.entity IN ('.getEntity('category').')'; if (!empty($type)) { - $sql.= ' AND t.type='.array_search($type, Categories::$TYPES); + $sql .= ' AND t.type='.array_search($type, Categories::$TYPES); } // Add sql filters if ($sqlfilters) { - if (! DolibarrApi::_checkFilters($sqlfilters)) + if (!DolibarrApi::_checkFilters($sqlfilters)) { throw new RestException(503, 'Error when validating parameter sqlfilters '.$sqlfilters); } - $regexstring='\(([^:\'\(\)]+:[^:\'\(\)]+:[^:\(\)]+)\)'; - $sql.=" AND (".preg_replace_callback('/'.$regexstring.'/', 'DolibarrApi::_forge_criteria_callback', $sqlfilters).")"; + $regexstring = '\(([^:\'\(\)]+:[^:\'\(\)]+:[^:\(\)]+)\)'; + $sql .= " AND (".preg_replace_callback('/'.$regexstring.'/', 'DolibarrApi::_forge_criteria_callback', $sqlfilters).")"; } - $sql.= $db->order($sortfield, $sortorder); - if ($limit) { + $sql .= $db->order($sortfield, $sortorder); + if ($limit) { if ($page < 0) { $page = 0; } $offset = $limit * $page; - $sql.= $db->plimit($limit + 1, $offset); + $sql .= $db->plimit($limit + 1, $offset); } $result = $db->query($sql); if ($result) { - $i=0; + $i = 0; $num = $db->num_rows($result); $min = min($num, ($limit <= 0 ? $num : $limit)); while ($i < $min) { $obj = $db->fetch_object($result); $category_static = new Categorie($db); - if($category_static->fetch($obj->rowid)) { + if ($category_static->fetch($obj->rowid)) { $obj_ret[] = $this->_cleanObjectDatas($category_static); } $i++; @@ -166,7 +178,7 @@ class Categories extends DolibarrApi else { throw new RestException(503, 'Error when retrieve category list : '.$db->lasterror()); } - if( ! count($obj_ret)) { + if (!count($obj_ret)) { throw new RestException(404, 'No category found'); } return $obj_ret; @@ -180,14 +192,14 @@ class Categories extends DolibarrApi */ public function post($request_data = null) { - if(! DolibarrApiAccess::$user->rights->categorie->creer) { + if (!DolibarrApiAccess::$user->rights->categorie->creer) { throw new RestException(401); } // Check mandatory fields $result = $this->_validate($request_data); - foreach($request_data as $field => $value) { + foreach ($request_data as $field => $value) { $this->category->$field = $value; } if ($this->category->create(DolibarrApiAccess::$user) < 0) { @@ -205,20 +217,20 @@ class Categories extends DolibarrApi */ public function put($id, $request_data = null) { - if(! DolibarrApiAccess::$user->rights->categorie->creer) { + if (!DolibarrApiAccess::$user->rights->categorie->creer) { throw new RestException(401); } $result = $this->category->fetch($id); - if( ! $result ) { + if (!$result) { throw new RestException(404, 'category not found'); } - if ( ! DolibarrApi::_checkAccessToResource('category', $this->category->id)) { + if (!DolibarrApi::_checkAccessToResource('category', $this->category->id)) { throw new RestException(401, 'Access not allowed for login '.DolibarrApiAccess::$user->login); } - foreach($request_data as $field => $value) { + foreach ($request_data as $field => $value) { if ($field == 'id') continue; $this->category->$field = $value; } @@ -241,19 +253,19 @@ class Categories extends DolibarrApi */ public function delete($id) { - if(! DolibarrApiAccess::$user->rights->categorie->supprimer) { + if (!DolibarrApiAccess::$user->rights->categorie->supprimer) { throw new RestException(401); } $result = $this->category->fetch($id); - if( ! $result ) { + if (!$result) { throw new RestException(404, 'category not found'); } - if ( ! DolibarrApi::_checkAccessToResource('category', $this->category->id)) { + if (!DolibarrApi::_checkAccessToResource('category', $this->category->id)) { throw new RestException(401, 'Access not allowed for login '.DolibarrApiAccess::$user->login); } - if (! $this->category->delete(DolibarrApiAccess::$user)) { + if (!$this->category->delete(DolibarrApiAccess::$user)) { throw new RestException(401, 'error when delete category'); } @@ -265,6 +277,374 @@ class Categories extends DolibarrApi ); } + /** + * List categories of an object + * + * Get the list of categories linked to an object + * + * @param int $id Object ID + * @param string $type Type of category ('member', 'customer', 'supplier', 'product', 'contact') + * @param string $sortfield Sort field + * @param string $sortorder Sort order + * @param int $limit Limit for list + * @param int $page Page number + * @return array Array of category objects + * + * @throws RestException + * + * @url GET /object/{type}/{id} + */ + public function getListForObject($id, $type, $sortfield = "s.rowid", $sortorder = 'ASC', $limit = 0, $page = 0) + { + if (!in_array($type, [ + Categorie::TYPE_PRODUCT, + Categorie::TYPE_CONTACT, + Categorie::TYPE_CUSTOMER, + Categorie::TYPE_SUPPLIER, + Categorie::TYPE_MEMBER + ])) { + throw new RestException(401); + } + + if ($type == Categorie::TYPE_PRODUCT && !(DolibarrApiAccess::$user->rights->produit->lire || DolibarrApiAccess::$user->rights->service->lire)) { + throw new RestException(401); + } elseif ($type == Categorie::TYPE_CONTACT && !DolibarrApiAccess::$user->rights->contact->lire) { + throw new RestException(401); + } elseif ($type == Categorie::TYPE_CUSTOMER && !DolibarrApiAccess::$user->rights->societe->lire) { + throw new RestException(401); + } elseif ($type == Categorie::TYPE_SUPPLIER && !DolibarrApiAccess::$user->rights->fournisseur->lire) { + throw new RestException(401); + } elseif ($type == Categorie::TYPE_MEMBER && !DolibarrApiAccess::$user->rights->adherent->lire) { + throw new RestException(401); + } + + $categories = $this->category->getListForItem($id, $type, $sortfield, $sortorder, $limit, $page); + + if (!is_array($categories)) { + if ($categories == 0) { + throw new RestException(404, 'No category found for this object'); + } + throw new RestException(500, 'Error when fetching object categories', array_merge(array($this->category->error), $this->category->errors)); + } + return $categories; + } + + /** + * Link an object to a category by id + * + * @param int $id ID of category + * @param string $type Type of category ('member', 'customer', 'supplier', 'product', 'contact') + * @param int $object_id ID of object + * + * @return array + * @throws RestException + * + * @url POST {id}/objects/{type}/{object_id} + */ + public function linkObjectById($id, $type, $object_id) + { + if (empty($type) || empty($object_id)) { + throw new RestException(401); + } + + if (!DolibarrApiAccess::$user->rights->categorie->lire) { + throw new RestException(401); + } + + $result = $this->category->fetch($id); + if (!$result) { + throw new RestException(404, 'category not found'); + } + + if ($type === Categorie::TYPE_PRODUCT) { + if (!(DolibarrApiAccess::$user->rights->produit->creer || DolibarrApiAccess::$user->rights->service->creer)) { + throw new RestException(401); + } + $object = new Product($this->db); + } elseif ($type === Categorie::TYPE_CUSTOMER) { + if (!DolibarrApiAccess::$user->rights->societe->creer) { + throw new RestException(401); + } + $object = new Societe($this->db); + } elseif ($type === Categorie::TYPE_SUPPLIER) { + if (!DolibarrApiAccess::$user->rights->societe->creer) { + throw new RestException(401); + } + $object = new Societe($this->db); + } elseif ($type === Categorie::TYPE_CONTACT) { + if (!DolibarrApiAccess::$user->rights->societe->contact->creer) { + throw new RestException(401); + } + $object = new Contact($this->db); + } elseif ($type === Categorie::TYPE_MEMBER) { + if (!DolibarrApiAccess::$user->rights->adherent->creer) { + throw new RestException(401); + } + $object = new Adherent($this->db); + } else { + throw new RestException(401, "this type is not recognized yet."); + } + + if (!empty($object)) { + $result = $object->fetch($object_id); + if ($result > 0) { + $result = $this->category->add_type($object, $type); + if ($result < 0) { + if ($this->category->error != 'DB_ERROR_RECORD_ALREADY_EXISTS') { + throw new RestException(500, 'Error when linking object', array_merge(array($this->category->error), $this->category->errors)); + } + } + } else { + throw new RestException(500, 'Error when fetching object', array_merge(array($object->error), $object->errors)); + } + + return array( + 'success' => array( + 'code' => 200, + 'message' => 'Objects succefully linked to the category' + ) + ); + } + + throw new RestException(401); + } + + /** + * Link an object to a category by ref + * + * @param int $id ID of category + * @param string $type Type of category ('member', 'customer', 'supplier', 'product', 'contact') + * @param string $object_ref Reference of object + * + * @return array + * @throws RestException + * + * @url POST {id}/objects/{type}/ref/{object_ref} + */ + public function linkObjectByRef($id, $type, $object_ref) + { + if (empty($type) || empty($object_ref)) { + throw new RestException(401); + } + + if (!DolibarrApiAccess::$user->rights->categorie->lire) { + throw new RestException(401); + } + + $result = $this->category->fetch($id); + if (!$result) { + throw new RestException(404, 'category not found'); + } + + if ($type === Categorie::TYPE_PRODUCT) { + if (!(DolibarrApiAccess::$user->rights->produit->creer || DolibarrApiAccess::$user->rights->service->creer)) { + throw new RestException(401); + } + $object = new Product($this->db); + } elseif ($type === Categorie::TYPE_CUSTOMER) { + if (!DolibarrApiAccess::$user->rights->societe->creer) { + throw new RestException(401); + } + $object = new Societe($this->db); + } elseif ($type === Categorie::TYPE_SUPPLIER) { + if (!DolibarrApiAccess::$user->rights->societe->creer) { + throw new RestException(401); + } + $object = new Societe($this->db); + } elseif ($type === Categorie::TYPE_CONTACT) { + if (!DolibarrApiAccess::$user->rights->societe->contact->creer) { + throw new RestException(401); + } + $object = new Contact($this->db); + } elseif ($type === Categorie::TYPE_MEMBER) { + if (!DolibarrApiAccess::$user->rights->adherent->creer) { + throw new RestException(401); + } + $object = new Adherent($this->db); + } else { + throw new RestException(401, "this type is not recognized yet."); + } + + if (!empty($object)) { + $result = $object->fetch('', $object_ref); + if ($result > 0) { + $result = $this->category->add_type($object, $type); + if ($result < 0) { + if ($this->category->error != 'DB_ERROR_RECORD_ALREADY_EXISTS') { + throw new RestException(500, 'Error when linking object', array_merge(array($this->category->error), $this->category->errors)); + } + } + } else { + throw new RestException(500, 'Error when fetching object', array_merge(array($object->error), $object->errors)); + } + + return array( + 'success' => array( + 'code' => 200, + 'message' => 'Objects succefully linked to the category' + ) + ); + } + + throw new RestException(401); + } + + /** + * Unlink an object from a category by id + * + * @param int $id ID of category + * @param string $type Type of category ('member', 'customer', 'supplier', 'product', 'contact') + * @param int $object_id ID of the object + * + * @return array + * @throws RestException + * + * @url DELETE {id}/objects/{type}/{object_id} + */ + public function unlinkObjectById($id, $type, $object_id) + { + if (empty($type) || empty($object_id)) { + throw new RestException(401); + } + + if (!DolibarrApiAccess::$user->rights->categorie->lire) { + throw new RestException(401); + } + + $result = $this->category->fetch($id); + if (!$result) { + throw new RestException(404, 'category not found'); + } + + if ($type === Categorie::TYPE_PRODUCT) { + if (!(DolibarrApiAccess::$user->rights->produit->creer || DolibarrApiAccess::$user->rights->service->creer)) { + throw new RestException(401); + } + $object = new Product($this->db); + } elseif ($type === Categorie::TYPE_CUSTOMER) { + if (!DolibarrApiAccess::$user->rights->societe->creer) { + throw new RestException(401); + } + $object = new Societe($this->db); + } elseif ($type === Categorie::TYPE_SUPPLIER) { + if (!DolibarrApiAccess::$user->rights->societe->creer) { + throw new RestException(401); + } + $object = new Societe($this->db); + } elseif ($type === Categorie::TYPE_CONTACT) { + if (!DolibarrApiAccess::$user->rights->societe->contact->creer) { + throw new RestException(401); + } + $object = new Contact($this->db); + } elseif ($type === Categorie::TYPE_MEMBER) { + if (!DolibarrApiAccess::$user->rights->adherent->creer) { + throw new RestException(401); + } + $object = new Adherent($this->db); + } else { + throw new RestException(401, "this type is not recognized yet."); + } + + if (!empty($object)) { + $result = $object->fetch((int) $object_id); + if ($result > 0) { + $result = $this->category->del_type($object, $type); + if ($result < 0) { + throw new RestException(500, 'Error when unlinking object', array_merge(array($this->category->error), $this->category->errors)); + } + } else { + throw new RestException(500, 'Error when fetching object', array_merge(array($object->error), $object->errors)); + } + + return array( + 'success' => array( + 'code' => 200, + 'message' => 'Objects succefully unlinked from the category' + ) + ); + } + + throw new RestException(401); + } + + /** + * Unlink an object from a category by ref + * + * @param int $id ID of category + * @param string $type Type of category ('member', 'customer', 'supplier', 'product', 'contact') + * @param string $object_ref Reference of the object + * + * @return array + * @throws RestException + * + * @url DELETE {id}/objects/{type}/ref/{object_ref} + */ + public function unlinkObjectByRef($id, $type, $object_ref) + { + if (empty($type) || empty($object_ref)) { + throw new RestException(401); + } + + if (!DolibarrApiAccess::$user->rights->categorie->lire) { + throw new RestException(401); + } + + $result = $this->category->fetch($id); + if (!$result) { + throw new RestException(404, 'category not found'); + } + + if ($type === Categorie::TYPE_PRODUCT) { + if (!(DolibarrApiAccess::$user->rights->produit->creer || DolibarrApiAccess::$user->rights->service->creer)) { + throw new RestException(401); + } + $object = new Product($this->db); + } elseif ($type === Categorie::TYPE_CUSTOMER) { + if (!DolibarrApiAccess::$user->rights->societe->creer) { + throw new RestException(401); + } + $object = new Societe($this->db); + } elseif ($type === Categorie::TYPE_SUPPLIER) { + if (!DolibarrApiAccess::$user->rights->societe->creer) { + throw new RestException(401); + } + $object = new Societe($this->db); + } elseif ($type === Categorie::TYPE_CONTACT) { + if (!DolibarrApiAccess::$user->rights->societe->contact->creer) { + throw new RestException(401); + } + $object = new Contact($this->db); + } elseif ($type === Categorie::TYPE_MEMBER) { + if (!DolibarrApiAccess::$user->rights->adherent->creer) { + throw new RestException(401); + } + $object = new Adherent($this->db); + } else { + throw new RestException(401, "this type is not recognized yet."); + } + + if (!empty($object)) { + $result = $object->fetch('', (string) $object_ref); + if ($result > 0) { + $result = $this->category->del_type($object, $type); + if ($result < 0) { + throw new RestException(500, 'Error when unlinking object', array_merge(array($this->category->error), $this->category->errors)); + } + } else { + throw new RestException(500, 'Error when fetching object', array_merge(array($object->error), $object->errors)); + } + + return array( + 'success' => array( + 'code' => 200, + 'message' => 'Objects succefully unlinked from the category' + ) + ); + } + + throw new RestException(401); + } + // phpcs:disable PEAR.NamingConventions.ValidFunctionName.PublicUnderscore /** @@ -356,7 +736,7 @@ class Categories extends DolibarrApi { dol_syslog("getObjects($id, $type, $onlyids)", LOG_DEBUG); - if (! DolibarrApiAccess::$user->rights->categorie->lire) { + if (!DolibarrApiAccess::$user->rights->categorie->lire) { throw new RestException(401); } @@ -366,11 +746,11 @@ class Categories extends DolibarrApi } $result = $this->category->fetch($id); - if (! $result) { + if (!$result) { throw new RestException(404, 'category not found'); } - if (! DolibarrApi::_checkAccessToResource('category', $this->category->id)) { + if (!DolibarrApi::_checkAccessToResource('category', $this->category->id)) { throw new RestException(401, 'Access not allowed for login '.DolibarrApiAccess::$user->login); } diff --git a/htdocs/categories/class/categorie.class.php b/htdocs/categories/class/categorie.class.php index f184f1b433f..56f26eb2dd9 100644 --- a/htdocs/categories/class/categorie.class.php +++ b/htdocs/categories/class/categorie.class.php @@ -107,7 +107,7 @@ class Categorie extends CommonObject 'member' => 'member', 'contact' => 'socpeople', 'user' => 'user', - 'account' => 'account', // old key for bank_account + 'account' => 'account', // old key for bank_account 'bank_account' => 'account', 'project' => 'project', 'warehouse'=> 'warehouse', @@ -125,7 +125,7 @@ class Categorie extends CommonObject 'member' => 'member', 'contact' => 'contact', 'user' => 'user', - 'account' => 'account', // old key for bank_account + 'account' => 'account', // old key for bank_account 'bank_account'=> 'account', 'project' => 'project', 'warehouse'=> 'warehouse', @@ -143,7 +143,7 @@ class Categorie extends CommonObject 'member' => 'Adherent', 'contact' => 'Contact', 'user' => 'User', - 'account' => 'Account', // old for bank account + 'account' => 'Account', // old for bank account 'bank_account' => 'Account', 'project' => 'Project', 'warehouse'=> 'Entrepot', @@ -169,12 +169,12 @@ class Categorie extends CommonObject /** * @var string ID to identify managed object */ - public $element='category'; + public $element = 'category'; /** * @var string Name of table without prefix where object is stored */ - public $table_element='categorie'; + public $table_element = 'categorie'; /** * @var int ID @@ -240,29 +240,34 @@ class Categorie extends CommonObject /** * Load category into memory from database * - * @param int $id Id of category - * @param string $label Label of category - * @param string $type Type of category ('product', '...') or (0, 1, ...) + * @param int $id Id of category + * @param string $label Label of category + * @param string $type Type of category ('product', '...') or (0, 1, ...) + * @param string $ref_ext External reference of object * @return int <0 if KO, >0 if OK */ - public function fetch($id, $label = '', $type = null) + public function fetch($id, $label = '', $type = null, $ref_ext = '') { global $conf; // Check parameters - if (empty($id) && empty($label)) return -1; - if (! is_numeric($type)) $type=$this->MAP_ID[$type]; + if (empty($id) && empty($label) && empty($ref_ext)) return -1; + if (!is_numeric($type)) $type = $this->MAP_ID[$type]; - $sql = "SELECT rowid, fk_parent, entity, label, description, color, fk_soc, visible, type"; - $sql.= " FROM ".MAIN_DB_PREFIX."categorie"; + $sql = "SELECT rowid, fk_parent, entity, label, description, color, fk_soc, visible, type, ref_ext"; + $sql .= " FROM ".MAIN_DB_PREFIX."categorie"; if ($id > 0) { - $sql.= " WHERE rowid = ".$id; + $sql .= " WHERE rowid = ".$id; + } + elseif (!empty($ref_ext)) + { + $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 = ".$this->db->escape($type); + $sql .= " WHERE label = '".$this->db->escape($label)."' AND entity IN (".getEntity('category').")"; + if (!is_null($type)) $sql .= " AND type = ".$this->db->escape($type); } dol_syslog(get_class($this)."::fetch", LOG_DEBUG); @@ -273,16 +278,17 @@ class Categorie extends CommonObject { $res = $this->db->fetch_array($resql); - $this->id = $res['rowid']; + $this->id = $res['rowid']; //$this->ref = $res['rowid']; $this->fk_parent = $res['fk_parent']; $this->label = $res['label']; - $this->description = $res['description']; + $this->description = $res['description']; $this->color = $res['color']; $this->socid = $res['fk_soc']; - $this->visible = $res['visible']; + $this->visible = $res['visible']; $this->type = $res['type']; - $this->entity = $res['entity']; + $this->ref_ext = $res['ref_ext']; + $this->entity = $res['entity']; // Retreive all extrafield // fetch optionals attributes and labels @@ -291,7 +297,7 @@ 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; } @@ -318,14 +324,14 @@ class Categorie extends CommonObject */ public function create($user) { - global $conf,$langs,$hookmanager; + global $conf, $langs, $hookmanager; $langs->load('categories'); - $type=$this->type; + $type = $this->type; - if (! is_numeric($type)) $type=$this->MAP_ID[$type]; + if (!is_numeric($type)) $type = $this->MAP_ID[$type]; - $error=0; + $error = 0; dol_syslog(get_class($this).'::create', LOG_DEBUG); @@ -334,13 +340,14 @@ class Categorie extends CommonObject $this->description = trim($this->description); $this->color = trim($this->color); $this->import_key = trim($this->import_key); - if (empty($this->visible)) $this->visible=0; + $this->ref_ext = trim($this->ref_ext); + if (empty($this->visible)) $this->visible = 0; $this->fk_parent = ($this->fk_parent != "" ? intval($this->fk_parent) : 0); if ($this->already_exists()) { - $this->error=$langs->trans("ImpossibleAddCat", $this->label); - $this->error.=" : ".$langs->trans("CategoryExistsAtSameLevel"); + $this->error = $langs->trans("ImpossibleAddCat", $this->label); + $this->error .= " : ".$langs->trans("CategoryExistsAtSameLevel"); dol_syslog($this->error, LOG_WARNING); return -4; } @@ -348,32 +355,34 @@ class Categorie extends CommonObject $this->db->begin(); $sql = "INSERT INTO ".MAIN_DB_PREFIX."categorie ("; - $sql.= "fk_parent,"; - $sql.= " label,"; - $sql.= " description,"; - $sql.= " color,"; - if (! empty($conf->global->CATEGORY_ASSIGNED_TO_A_CUSTOMER)) + $sql .= "fk_parent,"; + $sql .= " label,"; + $sql .= " description,"; + $sql .= " color,"; + if (!empty($conf->global->CATEGORY_ASSIGNED_TO_A_CUSTOMER)) { - $sql.= "fk_soc,"; + $sql .= "fk_soc,"; } - $sql.= " visible,"; - $sql.= " type,"; - $sql.= " import_key,"; - $sql.= " entity"; - $sql.= ") VALUES ("; - $sql.= $this->db->escape($this->fk_parent).","; - $sql.= "'".$this->db->escape($this->label)."',"; - $sql.= "'".$this->db->escape($this->description)."',"; - $sql.= "'".$this->db->escape($this->color)."',"; - if (! empty($conf->global->CATEGORY_ASSIGNED_TO_A_CUSTOMER)) + $sql .= " visible,"; + $sql .= " type,"; + $sql .= " import_key,"; + $sql .= " ref_ext,"; + $sql .= " entity"; + $sql .= ") VALUES ("; + $sql .= $this->db->escape($this->fk_parent).","; + $sql .= "'".$this->db->escape($this->label)."',"; + $sql .= "'".$this->db->escape($this->description)."',"; + $sql .= "'".$this->db->escape($this->color)."',"; + if (!empty($conf->global->CATEGORY_ASSIGNED_TO_A_CUSTOMER)) { - $sql.= ($this->socid != -1 ? $this->socid : 'null').","; + $sql .= ($this->socid != -1 ? $this->socid : 'null').","; } - $sql.= "'".$this->db->escape($this->visible)."',"; - $sql.= $this->db->escape($type).","; - $sql.= (! empty($this->import_key)?"'".$this->db->escape($this->import_key)."'":'null').","; - $sql.= $this->db->escape($conf->entity); - $sql.= ")"; + $sql .= "'".$this->db->escape($this->visible)."',"; + $sql .= $this->db->escape($type).","; + $sql .= (!empty($this->import_key) ? "'".$this->db->escape($this->import_key)."'" : 'null').","; + $sql .= (!empty($this->ref_ext) ? "'".$this->db->escape($this->ref_ext)."'" : 'null').","; + $sql .= $this->db->escape($conf->entity); + $sql .= ")"; $res = $this->db->query($sql); if ($res) @@ -384,27 +393,27 @@ class Categorie extends CommonObject { $this->id = $id; - $action='create'; + $action = 'create'; // Actions on extra fields if (empty($conf->global->MAIN_EXTRAFIELDS_DISABLED)) // For avoid conflicts if trigger used { - $result=$this->insertExtraFields(); + $result = $this->insertExtraFields(); if ($result < 0) { $error++; } } - if (! $error) + if (!$error) { // Call trigger - $result=$this->call_trigger('CATEGORY_CREATE', $user); + $result = $this->call_trigger('CATEGORY_CREATE', $user); if ($result < 0) { $error++; } // End call triggers } - if ( ! $error ) + if (!$error) { $this->db->commit(); return $id; @@ -423,7 +432,7 @@ class Categorie extends CommonObject } else { - $this->error=$this->db->error(); + $this->error = $this->db->error(); $this->db->rollback(); return -1; } @@ -439,30 +448,32 @@ class Categorie extends CommonObject */ public function update(User $user) { - global $conf, $langs,$hookmanager; + global $conf, $langs, $hookmanager; - $error=0; + $error = 0; // Clean parameters - $this->label=trim($this->label); - $this->description=trim($this->description); + $this->label = trim($this->label); + $this->description = trim($this->description); + $this->ref_ext = trim($this->ref_ext); $this->fk_parent = ($this->fk_parent != "" ? intval($this->fk_parent) : 0); $this->visible = ($this->visible != "" ? intval($this->visible) : 0); if ($this->already_exists()) { - $this->error=$langs->trans("ImpossibleUpdateCat"); - $this->error.=" : ".$langs->trans("CategoryExistsAtSameLevel"); + $this->error = $langs->trans("ImpossibleUpdateCat"); + $this->error .= " : ".$langs->trans("CategoryExistsAtSameLevel"); return -1; } $this->db->begin(); $sql = "UPDATE ".MAIN_DB_PREFIX."categorie"; - $sql.= " SET label = '".$this->db->escape($this->label)."',"; - $sql.= " description = '".$this->db->escape($this->description)."',"; - $sql.= " color = '".$this->db->escape($this->color)."'"; - if (! empty($conf->global->CATEGORY_ASSIGNED_TO_A_CUSTOMER)) + $sql .= " SET label = '".$this->db->escape($this->label)."',"; + $sql .= " description = '".$this->db->escape($this->description)."',"; + $sql .= " ref_ext = '".$this->db->escape($this->ref_ext)."',"; + $sql .= " color = '".$this->db->escape($this->color)."'"; + if (!empty($conf->global->CATEGORY_ASSIGNED_TO_A_CUSTOMER)) { $sql .= ", fk_soc = ".($this->socid != -1 ? $this->socid : 'null'); } @@ -473,22 +484,22 @@ class Categorie extends CommonObject dol_syslog(get_class($this)."::update", LOG_DEBUG); if ($this->db->query($sql)) { - $action='update'; + $action = 'update'; // Actions on extra fields if (empty($conf->global->MAIN_EXTRAFIELDS_DISABLED)) // For avoid conflicts if trigger used { - $result=$this->insertExtraFields(); + $result = $this->insertExtraFields(); if ($result < 0) { $error++; } } - if (! $error) + if (!$error) { // Call trigger - $result=$this->call_trigger('CATEGORY_MODIFY', $user); + $result = $this->call_trigger('CATEGORY_MODIFY', $user); if ($result < 0) { $error++; $this->db->rollback(); return -1; } // End call triggers } @@ -514,9 +525,9 @@ class Categorie extends CommonObject */ public function delete($user, $notrigger = 0) { - global $conf,$langs; + global $conf, $langs; - $error=0; + $error = 0; // Clean parameters $this->fk_parent = ($this->fk_parent != "" ? intval($this->fk_parent) : 0); @@ -525,24 +536,24 @@ class Categorie extends CommonObject $this->db->begin(); - if (! $error && ! $notrigger) + if (!$error && !$notrigger) { // Call trigger - $result=$this->call_trigger('CATEGORY_DELETE', $user); + $result = $this->call_trigger('CATEGORY_DELETE', $user); if ($result < 0) $error++; // End call triggers } /* FIX #1317 : Check for child category and move up 1 level*/ - if (! $error) + if (!$error) { $sql = "UPDATE ".MAIN_DB_PREFIX."categorie"; - $sql.= " SET fk_parent = ".$this->fk_parent; - $sql.= " WHERE fk_parent = ".$this->id; + $sql .= " SET fk_parent = ".$this->fk_parent; + $sql .= " WHERE fk_parent = ".$this->id; if (!$this->db->query($sql)) { - $this->error=$this->db->lasterror(); + $this->error = $this->db->lasterror(); $error++; } } @@ -559,7 +570,7 @@ class Categorie extends CommonObject 'categorie' => 'rowid', ); foreach ($arraydelete as $key => $value) { - $sql = "DELETE FROM " . MAIN_DB_PREFIX . $key; + $sql = "DELETE FROM ".MAIN_DB_PREFIX.$key; $sql .= " WHERE ".$value." = ".$this->id; if (!$this->db->query($sql)) { $this->errors[] = $this->db->lasterror(); @@ -569,9 +580,9 @@ class Categorie extends CommonObject } // Removed extrafields - if (! $error && empty($conf->global->MAIN_EXTRAFIELDS_DISABLED)) // For avoid conflicts if trigger used + if (!$error && empty($conf->global->MAIN_EXTRAFIELDS_DISABLED)) // For avoid conflicts if trigger used { - $result=$this->deleteExtraFields(); + $result = $this->deleteExtraFields(); if ($result < 0) { $error++; @@ -579,7 +590,7 @@ class Categorie extends CommonObject } } - if (! $error) + if (!$error) { $this->db->commit(); return 1; @@ -602,28 +613,28 @@ class Categorie extends CommonObject public function add_type($obj, $type) { // phpcs:enable - global $user,$langs,$conf; + global $user, $langs, $conf; - $error=0; + $error = 0; if ($this->id == -1) return -2; $this->db->begin(); - $sql = "INSERT INTO " . MAIN_DB_PREFIX . "categorie_" . $this->MAP_CAT_TABLE[$type]; - $sql .= " (fk_categorie, fk_" . $this->MAP_CAT_FK[$type] . ")"; - $sql .= " VALUES (" . $this->id . ", " . $obj->id . ")"; + $sql = "INSERT INTO ".MAIN_DB_PREFIX."categorie_".$this->MAP_CAT_TABLE[$type]; + $sql .= " (fk_categorie, fk_".$this->MAP_CAT_FK[$type].")"; + $sql .= " VALUES (".$this->id.", ".$obj->id.")"; dol_syslog(get_class($this).'::add_type', LOG_DEBUG); if ($this->db->query($sql)) { - if (! empty($conf->global->CATEGORIE_RECURSIV_ADD)) + if (!empty($conf->global->CATEGORIE_RECURSIV_ADD)) { $sql = 'SELECT fk_parent FROM '.MAIN_DB_PREFIX.'categorie'; - $sql.= " WHERE rowid = ".$this->id; + $sql .= " WHERE rowid = ".$this->id; dol_syslog(get_class($this)."::add_type", LOG_DEBUG); - $resql=$this->db->query($sql); + $resql = $this->db->query($sql); if ($resql) { if ($this->db->num_rows($resql) > 0) @@ -648,7 +659,7 @@ class Categorie extends CommonObject else { $error++; - $this->error=$this->db->lasterror(); + $this->error = $this->db->lasterror(); } if ($error) @@ -661,12 +672,12 @@ 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); + $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++; } // End call triggers - if (! $error) + if (!$error) { $this->db->commit(); return 1; @@ -682,12 +693,12 @@ class Categorie extends CommonObject $this->db->rollback(); if ($this->db->lasterrno() == 'DB_ERROR_RECORD_ALREADY_EXISTS') { - $this->error=$this->db->lasterrno(); + $this->error = $this->db->lasterrno(); return -3; } else { - $this->error=$this->db->lasterror(); + $this->error = $this->db->lasterror(); } return -1; } @@ -705,35 +716,35 @@ class Categorie extends CommonObject public function del_type($obj, $type) { // phpcs:enable - global $user,$langs,$conf; + global $user, $langs, $conf; - $error=0; + $error = 0; // For backward compatibility if ($type == 'societe') { $type = 'customer'; - dol_syslog(get_class($this) . "::del_type(): type 'societe' is deprecated, please use 'customer' instead", LOG_WARNING); + dol_syslog(get_class($this)."::del_type(): type 'societe' is deprecated, please use 'customer' instead", LOG_WARNING); } elseif ($type == 'fournisseur') { $type = 'supplier'; - dol_syslog(get_class($this) . "::del_type(): type 'fournisseur' is deprecated, please use 'supplier' instead", LOG_WARNING); + dol_syslog(get_class($this)."::del_type(): type 'fournisseur' is deprecated, please use 'supplier' instead", LOG_WARNING); } $this->db->begin(); - $sql = "DELETE FROM " . MAIN_DB_PREFIX . "categorie_" . $this->MAP_CAT_TABLE[$type]; - $sql .= " WHERE fk_categorie = " . $this->id; - $sql .= " AND fk_" . $this->MAP_CAT_FK[$type] . " = " . $obj->id; + $sql = "DELETE FROM ".MAIN_DB_PREFIX."categorie_".$this->MAP_CAT_TABLE[$type]; + $sql .= " WHERE fk_categorie = ".$this->id; + $sql .= " AND fk_".$this->MAP_CAT_FK[$type]." = ".$obj->id; dol_syslog(get_class($this).'::del_type', LOG_DEBUG); if ($this->db->query($sql)) { // 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); + $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++; } // End call triggers - if (! $error) + if (!$error) { $this->db->commit(); return 1; @@ -747,7 +758,7 @@ class Categorie extends CommonObject else { $this->db->rollback(); - $this->error=$this->db->lasterror(); + $this->error = $this->db->lasterror(); return -1; } } @@ -770,18 +781,19 @@ class Categorie extends CommonObject $objs = array(); - $obj = new $this->MAP_OBJ_CLASS[$type]( $this->db ); + $tmpclass = $this->MAP_OBJ_CLASS[$type]; + $obj = new $tmpclass($this->db); - $sql = "SELECT c.fk_" . $this->MAP_CAT_FK[$type]; - $sql .= " FROM " . MAIN_DB_PREFIX . "categorie_" . $this->MAP_CAT_TABLE[$type] . " as c"; - $sql .= ", " . MAIN_DB_PREFIX . $this->MAP_OBJ_TABLE[$type] . " as o"; - $sql .= " WHERE o.entity IN (" . getEntity($obj->element).")"; + $sql = "SELECT c.fk_".$this->MAP_CAT_FK[$type]; + $sql .= " FROM ".MAIN_DB_PREFIX."categorie_".$this->MAP_CAT_TABLE[$type]." as c"; + $sql .= ", ".MAIN_DB_PREFIX.$this->MAP_OBJ_TABLE[$type]." as o"; + $sql .= " WHERE o.entity IN (".getEntity($obj->element).")"; $sql .= " AND c.fk_categorie = ".$this->id; - $sql .= " AND c.fk_" . $this->MAP_CAT_FK[$type] . " = o.rowid"; + $sql .= " AND c.fk_".$this->MAP_CAT_FK[$type]." = o.rowid"; // Protection for external users if (($type == 'customer' || $type == 'supplier') && $user->socid > 0) { - $sql.= " AND o.rowid = ".$user->socid; + $sql .= " AND o.rowid = ".$user->socid; } if ($limit > 0 || $offset > 0) $sql .= $this->db->plimit($limit + 1, $offset); $sql .= $this->db->order($sortfield, $sortorder); @@ -794,12 +806,12 @@ class Categorie extends CommonObject { if ($onlyids) { - $objs[] = $rec['fk_' . $this->MAP_CAT_FK[$type]]; + $objs[] = $rec['fk_'.$this->MAP_CAT_FK[$type]]; } else { - $obj = new $this->MAP_OBJ_CLASS[$type]( $this->db ); - $obj->fetch($rec['fk_' . $this->MAP_CAT_FK[$type]]); + $obj = new $this->MAP_OBJ_CLASS[$type]($this->db); + $obj->fetch($rec['fk_'.$this->MAP_CAT_FK[$type]]); $objs[] = $obj; } } @@ -807,7 +819,7 @@ class Categorie extends CommonObject } else { - $this->error=$this->db->error().' sql='.$sql; + $this->error = $this->db->error().' sql='.$sql; return -1; } } @@ -822,14 +834,14 @@ class Categorie extends CommonObject */ public function containsObject($type, $object_id) { - $sql = "SELECT COUNT(*) as nb FROM " . MAIN_DB_PREFIX . "categorie_" . $this->MAP_CAT_TABLE[$type]; - $sql .= " WHERE fk_categorie = " . $this->id . " AND fk_" . $this->MAP_CAT_FK[$type] . " = " . $object_id; + $sql = "SELECT COUNT(*) as nb FROM ".MAIN_DB_PREFIX."categorie_".$this->MAP_CAT_TABLE[$type]; + $sql .= " WHERE fk_categorie = ".$this->id." AND fk_".$this->MAP_CAT_FK[$type]." = ".$object_id; dol_syslog(get_class($this)."::containsObject", LOG_DEBUG); $resql = $this->db->query($sql); if ($resql) { return $this->db->fetch_object($resql)->nb; } else { - $this->error=$this->db->error().' sql='.$sql; + $this->error = $this->db->error().' sql='.$sql; return -1; } } @@ -853,29 +865,29 @@ class Categorie extends CommonObject $sub_type = $type; $subcol_name = "fk_".$type; - if ($type=="customer") { - $sub_type="societe"; - $subcol_name="fk_soc"; + if ($type == "customer") { + $sub_type = "societe"; + $subcol_name = "fk_soc"; } - if ($type=="supplier") { - $sub_type="fournisseur"; - $subcol_name="fk_soc"; + if ($type == "supplier") { + $sub_type = "fournisseur"; + $subcol_name = "fk_soc"; } - if ($type=="contact") { - $subcol_name="fk_socpeople"; + if ($type == "contact") { + $subcol_name = "fk_socpeople"; } $idoftype = array_search($type, self::$MAP_ID_TO_CODE); $sql = "SELECT s.rowid"; - $sql.= " FROM ".MAIN_DB_PREFIX."categorie as s"; - $sql.= " , ".MAIN_DB_PREFIX."categorie_".$sub_type." as sub "; - $sql.= ' WHERE s.entity IN ('.getEntity('category').')'; - $sql.= ' AND s.type='.$idoftype; - $sql.= ' AND s.rowid = sub.fk_categorie'; - $sql.= ' AND sub.'.$subcol_name.' = '.$id; + $sql .= " FROM ".MAIN_DB_PREFIX."categorie as s"; + $sql .= " , ".MAIN_DB_PREFIX."categorie_".$sub_type." as sub "; + $sql .= ' WHERE s.entity IN ('.getEntity('category').')'; + $sql .= ' AND s.type='.$idoftype; + $sql .= ' AND s.rowid = sub.fk_categorie'; + $sql .= ' AND sub.'.$subcol_name.' = '.$id; - $sql.= $this->db->order($sortfield, $sortorder); + $sql .= $this->db->order($sortfield, $sortorder); $offset = 0; $nbtotalofrecords = ''; @@ -897,13 +909,13 @@ class Categorie extends CommonObject } $offset = $limit * $page; - $sql.= $this->db->plimit($limit + 1, $offset); + $sql .= $this->db->plimit($limit + 1, $offset); } $result = $this->db->query($sql); if ($result) { - $i=0; + $i = 0; $num = $this->db->num_rows($result); $min = min($num, ($limit <= 0 ? $num : $limit)); while ($i < $min) @@ -912,20 +924,21 @@ class Categorie extends CommonObject $category_static = new Categorie($this->db); if ($category_static->fetch($obj->rowid)) { - $categories[$i]['id'] = $category_static->id; + $categories[$i]['id'] = $category_static->id; $categories[$i]['fk_parent'] = $category_static->fk_parent; $categories[$i]['label'] = $category_static->label; - $categories[$i]['description'] = $category_static->description; + $categories[$i]['description'] = $category_static->description; $categories[$i]['color'] = $category_static->color; $categories[$i]['socid'] = $category_static->socid; - $categories[$i]['visible'] = $category_static->visible; - $categories[$i]['type'] = $category_static->type; - $categories[$i]['entity'] = $category_static->entity; - $categories[$i]['array_options'] = $category_static->array_options; + $categories[$i]['ref_ext'] = $category_static->ref_ext; + $categories[$i]['visible'] = $category_static->visible; + $categories[$i]['type'] = $category_static->type; + $categories[$i]['entity'] = $category_static->entity; + $categories[$i]['array_options'] = $category_static->array_options; // multilangs - if (! empty($conf->global->MAIN_MULTILANGS)) { - $categories[$i]['multilangs'] = $category_static->multilangs; + if (!empty($conf->global->MAIN_MULTILANGS)) { + $categories[$i]['multilangs'] = $category_static->multilangs; } } $i++; @@ -935,7 +948,7 @@ class Categorie extends CommonObject $this->error = $this->db->lasterror(); return -1; } - if ( ! count($categories)) { + if (!count($categories)) { return 0; } @@ -952,9 +965,9 @@ class Categorie extends CommonObject { // phpcs:enable $sql = "SELECT rowid FROM ".MAIN_DB_PREFIX."categorie"; - $sql.= " WHERE fk_parent = ".$this->id; + $sql .= " WHERE fk_parent = ".$this->id; - $res = $this->db->query($sql); + $res = $this->db->query($sql); if ($res) { $cats = array(); @@ -982,21 +995,21 @@ class Categorie extends CommonObject protected function load_motherof() { // phpcs:enable - $this->motherof=array(); + $this->motherof = array(); // Load array[child]=parent $sql = "SELECT fk_parent as id_parent, rowid as id_son"; - $sql.= " FROM ".MAIN_DB_PREFIX."categorie"; - $sql.= " WHERE fk_parent != 0"; - $sql.= " AND entity IN (".getEntity('category').")"; + $sql .= " FROM ".MAIN_DB_PREFIX."categorie"; + $sql .= " WHERE fk_parent != 0"; + $sql .= " AND entity IN (".getEntity('category').")"; dol_syslog(get_class($this)."::load_motherof", LOG_DEBUG); $resql = $this->db->query($sql); if ($resql) { - while ($obj= $this->db->fetch_object($resql)) + while ($obj = $this->db->fetch_object($resql)) { - $this->motherof[$obj->id_son]=$obj->id_parent; + $this->motherof[$obj->id_son] = $obj->id_parent; } return 1; } @@ -1032,7 +1045,7 @@ 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_string($markafterid)) { @@ -1061,27 +1074,28 @@ class Categorie extends CommonObject $current_lang = $langs->getDefaultLang(); // Init $this->cats array - $sql = "SELECT DISTINCT c.rowid, c.label, 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"; - $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)."'"; - $sql .= " WHERE c.entity IN (" . getEntity('category') . ")"; - $sql .= " AND c.type = " . (int) $type; + $sql = "SELECT DISTINCT c.rowid, c.label, 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"; + $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)."'"; + $sql .= " WHERE c.entity IN (".getEntity('category').")"; + $sql .= " AND c.type = ".(int) $type; dol_syslog(get_class($this)."::get_full_arbo get category list", LOG_DEBUG); $resql = $this->db->query($sql); if ($resql) { - $i=0; + $i = 0; while ($obj = $this->db->fetch_object($resql)) { $this->cats[$obj->rowid]['rowid'] = $obj->rowid; $this->cats[$obj->rowid]['id'] = $obj->rowid; $this->cats[$obj->rowid]['fk_parent'] = $obj->fk_parent; - $this->cats[$obj->rowid]['label'] = ! empty($obj->label_trans) ? $obj->label_trans : $obj->label; - $this->cats[$obj->rowid]['description'] = ! empty($obj->description_trans) ? $obj->description_trans : $obj->description; + $this->cats[$obj->rowid]['label'] = !empty($obj->label_trans) ? $obj->label_trans : $obj->label; + $this->cats[$obj->rowid]['description'] = !empty($obj->description_trans) ? $obj->description_trans : $obj->description; $this->cats[$obj->rowid]['color'] = $obj->color; $this->cats[$obj->rowid]['visible'] = $obj->visible; + $this->cats[$obj->rowid]['ref_ext'] = $obj->ref_ext; $i++; } } @@ -1093,10 +1107,10 @@ class Categorie extends CommonObject // We add the fullpath property to each elements of first level (no parent exists) dol_syslog(get_class($this)."::get_full_arbo call to build_path_from_id_categ", LOG_DEBUG); - foreach($this->cats as $key => $val) + foreach ($this->cats as $key => $val) { //print 'key='.$key.'
'."\n"; - $this->build_path_from_id_categ($key, 0); // Process a branch from the root category key (this category has no parent) + $this->build_path_from_id_categ($key, 0); // Process a branch from the root category key (this category has no parent) } // Include or exclude leaf including $markafterid from tree @@ -1105,14 +1119,14 @@ class Categorie extends CommonObject $keyfiltercatid = implode('|', $markafterid); //print "Look to discard category ".$markafterid."\n"; - $keyfilter1 = '^' . $keyfiltercatid . '$'; - $keyfilter2 = '_' . $keyfiltercatid . '$'; - $keyfilter3 = '^' . $keyfiltercatid . '_'; - $keyfilter4 = '_' . $keyfiltercatid . '_'; - foreach($this->cats as $key => $val) + $keyfilter1 = '^'.$keyfiltercatid.'$'; + $keyfilter2 = '_'.$keyfiltercatid.'$'; + $keyfilter3 = '^'.$keyfiltercatid.'_'; + $keyfilter4 = '_'.$keyfiltercatid.'_'; + foreach ($this->cats as $key => $val) { - $test = (preg_match('/' . $keyfilter1 . '/', $val['fullpath']) || preg_match('/' . $keyfilter2 . '/', $val['fullpath']) - || preg_match('/' . $keyfilter3 . '/', $val['fullpath']) || preg_match('/' . $keyfilter4 . '/', $val['fullpath'])); + $test = (preg_match('/'.$keyfilter1.'/', $val['fullpath']) || preg_match('/'.$keyfilter2.'/', $val['fullpath']) + || preg_match('/'.$keyfilter3.'/', $val['fullpath']) || preg_match('/'.$keyfilter4.'/', $val['fullpath'])); if (($test && !$include) || (!$test && $include)) { @@ -1122,7 +1136,7 @@ class Categorie extends CommonObject } dol_syslog(get_class($this)."::get_full_arbo dol_sort_array", LOG_DEBUG); - $this->cats=dol_sort_array($this->cats, 'fulllabel', 'asc', true, false); + $this->cats = dol_sort_array($this->cats, 'fulllabel', 'asc', true, false); //$this->debug_cats(); @@ -1143,7 +1157,7 @@ class Categorie extends CommonObject // phpcs:enable dol_syslog(get_class($this)."::build_path_from_id_categ id_categ=".$id_categ." protection=".$protection, LOG_DEBUG); - if (! empty($this->cats[$id_categ]['fullpath'])) + if (!empty($this->cats[$id_categ]['fullpath'])) { // Already defined dol_syslog(get_class($this)."::build_path_from_id_categ fullpath and fulllabel already defined", LOG_WARNING); @@ -1156,20 +1170,20 @@ class Categorie extends CommonObject // Define fullpath and fulllabel $this->cats[$id_categ]['fullpath'] = '_'.$id_categ; $this->cats[$id_categ]['fulllabel'] = $this->cats[$id_categ]['label']; - $i=0; $cursor_categ=$id_categ; + $i = 0; $cursor_categ = $id_categ; //print 'Work for id_categ='.$id_categ.'
'."\n"; - while ((empty($protection) || $i < $protection) && ! empty($this->motherof[$cursor_categ])) + while ((empty($protection) || $i < $protection) && !empty($this->motherof[$cursor_categ])) { //print '  cursor_categ='.$cursor_categ.' i='.$i.' '.$this->motherof[$cursor_categ].'
'."\n"; $this->cats[$id_categ]['fullpath'] = '_'.$this->motherof[$cursor_categ].$this->cats[$id_categ]['fullpath']; $this->cats[$id_categ]['fulllabel'] = $this->cats[$this->motherof[$cursor_categ]]['label'].' >> '.$this->cats[$id_categ]['fulllabel']; //print '  Result for id_categ='.$id_categ.' : '.$this->cats[$id_categ]['fullpath'].' '.$this->cats[$id_categ]['fulllabel'].'
'."\n"; - $i++; $cursor_categ=$this->motherof[$cursor_categ]; + $i++; $cursor_categ = $this->motherof[$cursor_categ]; } //print 'Result for id_categ='.$id_categ.' : '.$this->cats[$id_categ]['fullpath'].'
'."\n"; // We count number of _ to have level - $this->cats[$id_categ]['level']=dol_strlen(preg_replace('/[^_]/i', '', $this->cats[$id_categ]['fullpath'])); + $this->cats[$id_categ]['level'] = dol_strlen(preg_replace('/[^_]/i', '', $this->cats[$id_categ]['fullpath'])); return; } @@ -1184,7 +1198,7 @@ class Categorie extends CommonObject { // phpcs:enable // Display $this->cats - foreach($this->cats as $key => $val) + foreach ($this->cats as $key => $val) { print 'id: '.$this->cats[$key]['id']; print ' label: '.$this->cats[$key]['label']; @@ -1208,19 +1222,19 @@ 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)) - $sql.= " AND type = ".$type; + $sql .= " WHERE entity IN (".getEntity('category').")"; + if (!is_null($type)) + $sql .= " AND type = ".$type; if ($parent) - $sql.= " AND fk_parent = 0"; + $sql .= " AND fk_parent = 0"; $res = $this->db->query($sql); if ($res) { - $cats = array (); + $cats = array(); while ($rec = $this->db->fetch_array($res)) { $cat = new Categorie($this->db); @@ -1258,19 +1272,19 @@ class Categorie extends CommonObject public function already_exists() { // phpcs:enable - $type=$this->type; + $type = $this->type; - if (! is_numeric($type)) $type=$this->MAP_ID[$type]; + if (!is_numeric($type)) $type = $this->MAP_ID[$type]; /* We have to select any rowid from llx_categorie which category's mother and label * are equals to those of the calling category */ $sql = "SELECT c.rowid"; - $sql.= " FROM ".MAIN_DB_PREFIX."categorie as c "; - $sql.= " WHERE c.entity IN (".getEntity('category').")"; - $sql.= " AND c.type = ".$type; - $sql.= " AND c.fk_parent = ".$this->fk_parent; - $sql.= " AND c.label = '".$this->db->escape($this->label)."'"; + $sql .= " FROM ".MAIN_DB_PREFIX."categorie as c "; + $sql .= " WHERE c.entity IN (".getEntity('category').")"; + $sql .= " AND c.type = ".$type; + $sql .= " AND c.fk_parent = ".$this->fk_parent; + $sql .= " AND c.label = '".$this->db->escape($this->label)."'"; dol_syslog(get_class($this)."::already_exists", LOG_DEBUG); $resql = $this->db->query($sql); @@ -1284,7 +1298,7 @@ class Categorie extends CommonObject * So if the result have the same id, update is not for label, and if result have an other one, * update may be for label. */ - if($obj[0] > 0 && $obj[0] != $this->id) + if ($obj[0] > 0 && $obj[0] != $this->id) { dol_syslog(get_class($this)."::already_exists category with name=".$this->label." and parent ".$this->fk_parent." exists: rowid=".$obj[0]." current_id=".$this->id, LOG_DEBUG); return 1; @@ -1295,7 +1309,7 @@ class Categorie extends CommonObject } else { - $this->error=$this->db->error(); + $this->error = $this->db->error(); return -1; } } @@ -1321,29 +1335,29 @@ class Categorie extends CommonObject { $w = array(); $i = 0; - $forced_color=''; + $forced_color = ''; foreach ($way as $cat) { $i++; if (empty($nocolor)) { - $forced_color='toreplace'; + $forced_color = 'toreplace'; if ($i == count($way)) { // Check contrast with background and correct text color - $forced_color='categtextwhite'; + $forced_color = 'categtextwhite'; if ($cat->color) { - if (colorIsLight($cat->color)) $forced_color='categtextblack'; + if (colorIsLight($cat->color)) $forced_color = 'categtextblack'; } } } if ($url == '') { - $link = ''; - $linkend=''; + $link = ''; + $linkend = ''; $w[] = $link.$cat->label.$linkend; } else @@ -1372,9 +1386,9 @@ class Categorie extends CommonObject $parents = array(); $sql = "SELECT fk_parent FROM ".MAIN_DB_PREFIX."categorie"; - $sql.= " WHERE rowid = ".$this->id; + $sql .= " WHERE rowid = ".$this->id; - $res = $this->db->query($sql); + $res = $this->db->query($sql); if ($res) { @@ -1408,17 +1422,17 @@ class Categorie extends CommonObject // phpcs:enable $ways = array(); - $parents=$this->get_meres(); - if (! empty($parents)) + $parents = $this->get_meres(); + if (!empty($parents)) { foreach ($parents as $parent) { - $allways=$parent->get_all_ways(); + $allways = $parent->get_all_ways(); foreach ($allways as $way) { - $w = $way; - $w[] = $this; - $ways[] = $w; + $w = $way; + $w[] = $this; + $ways[] = $w; } } } @@ -1449,9 +1463,9 @@ class Categorie extends CommonObject { // Load bank groups $sql = "SELECT c.label, c.rowid"; - $sql.= " FROM ".MAIN_DB_PREFIX."bank_class as a, ".MAIN_DB_PREFIX."bank_categ as c"; - $sql.= " WHERE a.lineid=".$id." AND a.fk_categ = c.rowid"; - $sql.= " ORDER BY c.label"; + $sql .= " FROM ".MAIN_DB_PREFIX."bank_class as a, ".MAIN_DB_PREFIX."bank_categ as c"; + $sql .= " WHERE a.lineid=".$id." AND a.fk_categ = c.rowid"; + $sql .= " ORDER BY c.label"; $res = $this->db->query($sql); if ($res) @@ -1479,9 +1493,9 @@ class Categorie extends CommonObject else { $sql = "SELECT ct.fk_categorie, c.label, c.rowid"; - $sql .= " FROM " . MAIN_DB_PREFIX . "categorie_" . $this->MAP_CAT_TABLE[$type] . " as ct, " . MAIN_DB_PREFIX . "categorie as c"; - $sql .= " WHERE ct.fk_categorie = c.rowid AND ct.fk_" . $this->MAP_CAT_FK[$type] . " = " . (int) $id . " AND c.type = " . $this->MAP_ID[$type]; - $sql .= " AND c.entity IN (" . getEntity('category') . ")"; + $sql .= " FROM ".MAIN_DB_PREFIX."categorie_".$this->MAP_CAT_TABLE[$type]." as ct, ".MAIN_DB_PREFIX."categorie as c"; + $sql .= " WHERE ct.fk_categorie = c.rowid AND ct.fk_".$this->MAP_CAT_FK[$type]." = ".(int) $id." AND c.type = ".$this->MAP_ID[$type]; + $sql .= " AND c.entity IN (".getEntity('category').")"; $res = $this->db->query($sql); if ($res) @@ -1525,7 +1539,7 @@ class Categorie extends CommonObject { // Deprecation warning if (is_numeric($type)) { - dol_syslog(__METHOD__ . ': using numeric types is deprecated.', LOG_WARNING); + dol_syslog(__METHOD__.': using numeric types is deprecated.', LOG_WARNING); } $cats = array(); @@ -1535,28 +1549,28 @@ class Categorie extends CommonObject // We want to reverse lookup $map_type = array_flip($this->MAP_ID); $type = $map_type[$type]; - dol_syslog(get_class($this) . "::rechercher(): numeric types are deprecated, please use string instead", LOG_WARNING); + dol_syslog(get_class($this)."::rechercher(): numeric types are deprecated, please use string instead", LOG_WARNING); } // Generation requete recherche - $sql = "SELECT rowid FROM " . MAIN_DB_PREFIX . "categorie"; - $sql .= " WHERE type = " . $this->MAP_ID[$type]; - $sql .= " AND entity IN (" . getEntity('category') . ")"; + $sql = "SELECT rowid FROM ".MAIN_DB_PREFIX."categorie"; + $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) - $sql.= " AND label LIKE '".$this->db->escape($nom)."'"; + if (!$case) + $sql .= " AND label LIKE '".$this->db->escape($nom)."'"; else - $sql.= " AND label LIKE BINARY '".$this->db->escape($nom)."'"; + $sql .= " AND label LIKE BINARY '".$this->db->escape($nom)."'"; } if ($id) { - $sql.=" AND rowid = '".$id."'"; + $sql .= " AND rowid = '".$id."'"; } - $res = $this->db->query($sql); + $res = $this->db->query($sql); if ($res) { while ($rec = $this->db->fetch_array($res)) @@ -1570,7 +1584,7 @@ class Categorie extends CommonObject } else { - $this->error=$this->db->error().' sql='.$sql; + $this->error = $this->db->error().' sql='.$sql; return -1; } } @@ -1588,25 +1602,25 @@ class Categorie extends CommonObject { global $langs; - $result=''; - $label=$langs->trans("ShowCategory").': '. ($this->ref?$this->ref:$this->label); + $result = ''; + $label = $langs->trans("ShowCategory").': '.($this->ref ? $this->ref : $this->label); // Check contrast with background and correct text color - $forced_color='categtextwhite'; + $forced_color = 'categtextwhite'; if ($this->color) { - if (colorIsLight($this->color)) $forced_color='categtextblack'; + if (colorIsLight($this->color)) $forced_color = 'categtextblack'; } - $link = ''; - $linkend=''; + $link = ''; + $linkend = ''; - $picto='category'; + $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; } @@ -1624,10 +1638,10 @@ class Categorie extends CommonObject // phpcs:enable require_once DOL_DOCUMENT_ROOT.'/core/lib/files.lib.php'; - $dir = $sdir .'/'. get_exdir($this->id, 2, 0, 0, $this, 'category') . $this->id ."/"; + $dir = $sdir.'/'.get_exdir($this->id, 2, 0, 0, $this, 'category').$this->id."/"; $dir .= "photos/"; - if (! file_exists($dir)) + if (!file_exists($dir)) { dol_mkdir($dir); } @@ -1636,8 +1650,8 @@ class Categorie extends CommonObject if (is_array($file['name']) && count($file['name']) > 0) { $nbfile = count($file['name']); - for ($i = 0; $i <= $nbfile; $i ++) { - $originImage = $dir . $file['name'][$i]; + for ($i = 0; $i <= $nbfile; $i++) { + $originImage = $dir.$file['name'][$i]; // Cree fichier en taille origine dol_move_uploaded_file($file['tmp_name'][$i], $originImage, 1, 0, 0); @@ -1648,7 +1662,7 @@ class Categorie extends CommonObject } } } else { - $originImage = $dir . $file['name']; + $originImage = $dir.$file['name']; // Cree fichier en taille origine dol_move_uploaded_file($file['tmp_name'], $originImage, 1, 0, 0); @@ -1672,16 +1686,16 @@ class Categorie extends CommonObject public function liste_photos($dir, $nbmax = 0) { // phpcs:enable - include_once DOL_DOCUMENT_ROOT .'/core/lib/files.lib.php'; + include_once DOL_DOCUMENT_ROOT.'/core/lib/files.lib.php'; - $nbphoto=0; - $tabobj=array(); + $nbphoto = 0; + $tabobj = array(); $dirthumb = $dir.'thumbs/'; if (file_exists($dir)) { - $handle=opendir($dir); + $handle = opendir($dir); if (is_resource($handle)) { while (($file = readdir($handle)) !== false) @@ -1692,19 +1706,19 @@ class Categorie extends CommonObject $photo = $file; // On determine nom du fichier vignette - $photo_vignette=''; + $photo_vignette = ''; if (preg_match('/(\.jpeg|\.jpg|\.bmp|\.gif|\.png|\.tiff)$/i', $photo, $regs)) { - $photo_vignette=preg_replace('/'.$regs[0].'/i', '', $photo).'_small'.$regs[0]; + $photo_vignette = preg_replace('/'.$regs[0].'/i', '', $photo).'_small'.$regs[0]; } // Objet - $obj=array(); - $obj['photo']=$photo; - if ($photo_vignette && is_file($dirthumb.$photo_vignette)) $obj['photo_vignette']='thumbs/' . $photo_vignette; - else $obj['photo_vignette']=""; + $obj = array(); + $obj['photo'] = $photo; + if ($photo_vignette && is_file($dirthumb.$photo_vignette)) $obj['photo_vignette'] = 'thumbs/'.$photo_vignette; + else $obj['photo_vignette'] = ""; - $tabobj[$nbphoto-1]=$obj; + $tabobj[$nbphoto - 1] = $obj; // On continue ou on arrete de boucler if ($nbmax && $nbphoto >= $nbmax) break; @@ -1740,7 +1754,7 @@ class Categorie extends CommonObject // Si elle existe, on efface la vignette if (preg_match('/(\.jpeg|\.jpg|\.bmp|\.gif|\.png|\.tiff)$/i', $filename, $regs)) { - $photo_vignette=preg_replace('/'.$regs[0].'/i', '', $filename).'_small'.$regs[0]; + $photo_vignette = preg_replace('/'.$regs[0].'/i', '', $filename).'_small'.$regs[0]; if (file_exists($dirthumb.$photo_vignette)) { dol_delete_file($dirthumb.$photo_vignette, 1); @@ -1780,9 +1794,9 @@ class Categorie extends CommonObject foreach ($langs_available as $key => $value) { $sql = "SELECT rowid"; - $sql.= " FROM ".MAIN_DB_PREFIX."categorie_lang"; - $sql.= " WHERE fk_category=".$this->id; - $sql.= " AND lang='".$key."'"; + $sql .= " FROM ".MAIN_DB_PREFIX."categorie_lang"; + $sql .= " WHERE fk_category=".$this->id; + $sql .= " AND lang='".$key."'"; $result = $this->db->query($sql); @@ -1791,20 +1805,20 @@ class Categorie extends CommonObject if ($this->db->num_rows($result)) // si aucune ligne dans la base { $sql2 = "UPDATE ".MAIN_DB_PREFIX."categorie_lang"; - $sql2.= " SET label='".$this->db->escape($this->label)."',"; - $sql2.= " description='".$this->db->escape($this->description)."'"; - $sql2.= " WHERE fk_category=".$this->id." AND lang='".$this->db->escape($key)."'"; + $sql2 .= " SET label='".$this->db->escape($this->label)."',"; + $sql2 .= " description='".$this->db->escape($this->description)."'"; + $sql2 .= " WHERE fk_category=".$this->id." AND lang='".$this->db->escape($key)."'"; } else { $sql2 = "INSERT INTO ".MAIN_DB_PREFIX."categorie_lang (fk_category, lang, label, description)"; - $sql2.= " VALUES(".$this->id.",'".$key."','". $this->db->escape($this->label); - $sql2.= "','".$this->db->escape($this->multilangs["$key"]["description"])."')"; + $sql2 .= " VALUES(".$this->id.",'".$key."','".$this->db->escape($this->label); + $sql2 .= "','".$this->db->escape($this->multilangs["$key"]["description"])."')"; } dol_syslog(get_class($this).'::setMultiLangs', LOG_DEBUG); - if (! $this->db->query($sql2)) + if (!$this->db->query($sql2)) { - $this->error=$this->db->lasterror(); + $this->error = $this->db->lasterror(); return -1; } } @@ -1813,23 +1827,23 @@ class Categorie extends CommonObject if ($this->db->num_rows($result)) // si aucune ligne dans la base { $sql2 = "UPDATE ".MAIN_DB_PREFIX."categorie_lang"; - $sql2.= " SET label='".$this->db->escape($this->multilangs["$key"]["label"])."',"; - $sql2.= " description='".$this->db->escape($this->multilangs["$key"]["description"])."'"; - $sql2.= " WHERE fk_category=".$this->id." AND lang='".$this->db->escape($key)."'"; + $sql2 .= " SET label='".$this->db->escape($this->multilangs["$key"]["label"])."',"; + $sql2 .= " description='".$this->db->escape($this->multilangs["$key"]["description"])."'"; + $sql2 .= " WHERE fk_category=".$this->id." AND lang='".$this->db->escape($key)."'"; } else { $sql2 = "INSERT INTO ".MAIN_DB_PREFIX."categorie_lang (fk_category, lang, label, description)"; - $sql2.= " VALUES(".$this->id.",'".$key."','". $this->db->escape($this->multilangs["$key"]["label"]); - $sql2.= "','".$this->db->escape($this->multilangs["$key"]["description"])."')"; + $sql2 .= " VALUES(".$this->id.",'".$key."','".$this->db->escape($this->multilangs["$key"]["label"]); + $sql2 .= "','".$this->db->escape($this->multilangs["$key"]["description"])."')"; } // 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)) + if (!$this->db->query($sql2)) { - $this->error=$this->db->lasterror(); + $this->error = $this->db->lasterror(); return -1; } } @@ -1858,28 +1872,28 @@ class Categorie extends CommonObject $current_lang = $langs->getDefaultLang(); $sql = "SELECT lang, label, description"; - $sql.= " FROM ".MAIN_DB_PREFIX."categorie_lang"; - $sql.= " WHERE fk_category=".$this->id; + $sql .= " FROM ".MAIN_DB_PREFIX."categorie_lang"; + $sql .= " WHERE fk_category=".$this->id; $result = $this->db->query($sql); if ($result) { - while ( $obj = $this->db->fetch_object($result) ) + while ($obj = $this->db->fetch_object($result)) { //print 'lang='.$obj->lang.' current='.$current_lang.'
'; - if( $obj->lang == $current_lang ) // si on a les traduct. dans la langue courante on les charge en infos principales. + if ($obj->lang == $current_lang) // si on a les traduct. dans la langue courante on les charge en infos principales. { - $this->label = $obj->label; - $this->description = $obj->description; + $this->label = $obj->label; + $this->description = $obj->description; } - $this->multilangs["$obj->lang"]["label"] = $obj->label; - $this->multilangs["$obj->lang"]["description"] = $obj->description; + $this->multilangs["$obj->lang"]["label"] = $obj->label; + $this->multilangs["$obj->lang"]["description"] = $obj->description; } return 1; } else { - $this->error=$langs->trans("Error")." : ".$this->db->error()." - ".$sql; + $this->error = $langs->trans("Error")." : ".$this->db->error()." - ".$sql; return -1; } } @@ -1908,10 +1922,10 @@ class Categorie extends CommonObject dol_syslog(get_class($this)."::initAsSpecimen"); // Initialise parametres - $this->id=0; - $this->fk_parent=0; + $this->id = 0; + $this->fk_parent = 0; $this->label = 'SPECIMEN'; - $this->specimen=1; + $this->specimen = 1; $this->description = 'This is a description'; $this->socid = 1; $this->type = self::TYPE_PRODUCT; diff --git a/htdocs/categories/edit.php b/htdocs/categories/edit.php index 39db14a9613..9c653decdff 100644 --- a/htdocs/categories/edit.php +++ b/htdocs/categories/edit.php @@ -32,19 +32,19 @@ require_once DOL_DOCUMENT_ROOT.'/core/class/html.formother.class.php'; // Load translation files required by the page $langs->load("categories"); -$id=GETPOST('id', 'int'); -$ref=GETPOST('ref'); -$type=GETPOST('type'); -$action=(GETPOST('action', 'aZ09')?GETPOST('action', 'aZ09'):'edit'); -$confirm=GETPOST('confirm'); -$cancel=GETPOST('cancel', 'alpha'); +$id = GETPOST('id', 'int'); +$ref = GETPOST('ref'); +$type = GETPOST('type'); +$action = (GETPOST('action', 'aZ09') ?GETPOST('action', 'aZ09') : 'edit'); +$confirm = GETPOST('confirm'); +$cancel = GETPOST('cancel', 'alpha'); -$socid=GETPOST('socid', 'int'); -$label=GETPOST('label'); -$description=GETPOST('description'); -$color=GETPOST('color', 'alpha'); -$visible=GETPOST('visible'); -$parent=GETPOST('parent'); +$socid = GETPOST('socid', 'int'); +$label = GETPOST('label'); +$description = GETPOST('description'); +$color = GETPOST('color', 'alpha'); +$visible = GETPOST('visible'); +$parent = GETPOST('parent'); if ($id == "") { @@ -58,7 +58,7 @@ $result = restrictedArea($user, 'categorie', $id, '&category'); $object = new Categorie($db); if ($id > 0) { - $result=$object->fetch($id); + $result = $object->fetch($id); } $extrafields = new ExtraFields($db); @@ -100,12 +100,12 @@ if ($action == 'update' && $user->rights->categorie->creer) $action = 'edit'; setEventMessages($langs->trans("ErrorFieldRequired", $langs->transnoentities("Label")), null, 'errors'); } - if (! $error && empty($object->error)) + if (!$error && empty($object->error)) { $ret = $extrafields->setOptionalsFromPost(null, $object); if ($ret < 0) $error++; - if (! $error && $object->update($user) > 0) + if (!$error && $object->update($user) > 0) { header('Location: '.DOL_URL_ROOT.'/categories/viewcat.php?id='.$object->id.'&type='.$type); exit; @@ -146,7 +146,7 @@ print ''; dol_fiche_head(''); -print ''; +print '
'; // Ref print ''; print ''; print ''; @@ -175,12 +175,12 @@ print ''; -$parameters=array(); -$reshook=$hookmanager->executeHooks('formObjectOptions', $parameters, $object, $action); // Note that $action and $object may have been modified by hook +$parameters = array(); +$reshook = $hookmanager->executeHooks('formObjectOptions', $parameters, $object, $action); // Note that $action and $object may have been modified by hook print $hookmanager->resPrint; if (empty($reshook)) { - print $object->showOptionals($extrafields, 'edit'); + print $object->showOptionals($extrafields, 'edit', $parameters); } print '
'; @@ -159,7 +159,7 @@ print '
'.$langs->trans("Description").''; require_once DOL_DOCUMENT_ROOT.'/core/class/doleditor.class.php'; -$doleditor=new DolEditor('description', $object->description, '', 200, 'dolibarr_notes', '', false, true, $conf->fckeditor->enabled, ROWS_6, '90%'); +$doleditor = new DolEditor('description', $object->description, '', 200, 'dolibarr_notes', '', false, true, $conf->fckeditor->enabled, ROWS_6, '90%'); $doleditor->Create(); print '
'.$langs->trans("In").''; print $form->select_all_categories($type, $object->fk_parent, 'parent', 64, $object->id); print '
'; diff --git a/htdocs/categories/index.php b/htdocs/categories/index.php index 2ef44c51f4f..61e3e4a09df 100644 --- a/htdocs/categories/index.php +++ b/htdocs/categories/index.php @@ -34,13 +34,13 @@ 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); -$catname=GETPOST('catname', 'alpha'); +$id = GETPOST('id', 'int'); +$type = (GETPOST('type', 'aZ09') ? GETPOST('type', 'aZ09') : Categorie::TYPE_PRODUCT); +$catname = GETPOST('catname', 'alpha'); -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 /* @@ -87,12 +87,12 @@ print ''; print ''; -print ''; +print '
'; print ''; print ''; print ''; print ''; +print $langs->trans("Name").':'; /* // faire une rech dans une sous categorie uniquement print ''; @@ -441,22 +439,22 @@ if (($action != 'create' && $action != 'add') && !$error) { $sql = 'SELECT s.nom, s.rowid as socid, s.client, c.rowid, c.ref, c.total_ht, c.ref_supplier,'; $sql .= ' c.date_valid, c.date_commande, c.date_livraison, c.fk_statut'; - $sql .= ' FROM ' . MAIN_DB_PREFIX . 'societe as s'; - $sql .= ', ' . MAIN_DB_PREFIX . 'commande_fournisseur as c'; - if (! $user->rights->societe->client->voir && ! $socid) - $sql .= ", " . MAIN_DB_PREFIX . "societe_commerciaux as sc"; - $sql .= ' WHERE c.entity = ' . $conf->entity; + $sql .= ' FROM '.MAIN_DB_PREFIX.'societe as s'; + $sql .= ', '.MAIN_DB_PREFIX.'commande_fournisseur as c'; + if (!$user->rights->societe->client->voir && !$socid) + $sql .= ", ".MAIN_DB_PREFIX."societe_commerciaux as sc"; + $sql .= ' WHERE c.entity = '.$conf->entity; $sql .= ' AND c.fk_soc = s.rowid'; // Show orders we can bill if (empty($conf->global->SUPPLIER_ORDER_TO_INVOICE_STATUS)) { - $sql.= " AND c.fk_statut IN (".CommandeFournisseur::STATUS_RECEIVED_COMPLETELY.")"; // Must match filter in htdocs/fourn/card.php + $sql .= " AND c.fk_statut IN (".CommandeFournisseur::STATUS_RECEIVED_COMPLETELY.")"; // Must match filter in htdocs/fourn/card.php } else { // CommandeFournisseur::STATUS_ORDERSENT.", ".CommandeFournisseur::STATUS_RECEIVED_PARTIALLY.", ".CommandeFournisseur::STATUS_RECEIVED_COMPLETELY - $sql.= " AND c.fk_statut IN (".$db->escape($conf->global->SUPPLIER_ORDER_TO_INVOICE_STATUS).")"; + $sql .= " AND c.fk_statut IN (".$db->escape($conf->global->SUPPLIER_ORDER_TO_INVOICE_STATUS).")"; } $sql .= " AND c.billed = 0"; @@ -466,33 +464,33 @@ if (($action != 'create' && $action != 'add') && !$error) { //$sql .= " AND c.rowid NOT IN (SELECT fk_source FROM " . MAIN_DB_PREFIX . "element_element WHERE targettype='invoice_supplier')"; 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; + $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 ($sref) { $sql .= natural_search("c.ref", $sref); } if ($sall) { - $sql .= natural_search(array("c.ref","c.note"), $sall); + $sql .= natural_search(array("c.ref", "c.note"), $sall); } // Date filter //$sql.= dolSqlDateFilter("c.date_commande", GETPOST("date_startday", 'int'), GETPOST("date_startmonth", 'int'), GETPOST("date_startyear", 'int')); //$sql.= dolSqlDateFilter("c.date_livraison", $search_deliveryday, $search_deliverymonth, $search_deliveryyear); if ($date_start) - $sql .= " AND c.date_commande >= '" . $db->idate($date_start) . "'"; + $sql .= " AND c.date_commande >= '".$db->idate($date_start)."'"; if ($date_end) - $sql .= " AND c.date_commande <= '" . $db->idate($date_end) . "'"; + $sql .= " AND c.date_commande <= '".$db->idate($date_end)."'"; if ($date_starty) - $sql .= " AND c.date_livraison >= '" . $db->idate($date_starty) . "'"; + $sql .= " AND c.date_livraison >= '".$db->idate($date_starty)."'"; if ($date_endy) - $sql .= " AND c.date_livraison <= '" . $db->idate($date_endy) . "'"; + $sql .= " AND c.date_livraison <= '".$db->idate($date_endy)."'"; - if (! empty($sref_client)) { + if (!empty($sref_client)) { $sql .= natural_search('c.ref_supplier', $sref_client); } - $sql .= ' ORDER BY ' . $sortfield . ' ' . $sortorder; - dol_syslog('fourn/commande/ordertoinvoice.php sql=' . $sql); + $sql .= ' ORDER BY '.$sortfield.' '.$sortorder; + dol_syslog('fourn/commande/ordertoinvoice.php sql='.$sql); $resql = $db->query($sql); if ($resql) { @@ -501,28 +499,28 @@ if (($action != 'create' && $action != 'add') && !$error) { $soc->fetch($socid); } $title = $langs->trans('ListOfSupplierOrders'); - $title .= ' - ' . $langs->trans('StatusOrderReceivedAllShort'); - $title .= ' - ' . $soc->getNomUrl(1, 'supplier'); + $title .= ' - '.$langs->trans('StatusOrderReceivedAllShort'); + $title .= ' - '.$soc->getNomUrl(1, 'supplier'); $num = $db->num_rows($resql); print load_fiche_titre($title); $i = 0; - $period = $html->selectDate($date_start, 'date_start', 0, 0, 1, '', 1, 0) . ' - ' . $html->selectDate($date_end, 'date_end', 0, 0, 1, '', 1, 0); - $periodely = $html->selectDate($date_starty, 'date_start_dely', 0, 0, 1, '', 1, 0) . ' - ' . $html->selectDate($date_endy, 'date_end_dely', 0, 0, 1, '', 1, 0); + $period = $html->selectDate($date_start, 'date_start', 0, 0, 1, '', 1, 0).' - '.$html->selectDate($date_end, 'date_end', 0, 0, 1, '', 1, 0); + $periodely = $html->selectDate($date_starty, 'date_start_dely', 0, 0, 1, '', 1, 0).' - '.$html->selectDate($date_endy, 'date_end_dely', 0, 0, 1, '', 1, 0); print ''; - print ''; - print ''; + print ''; + print ''; - print '
'.$langs->trans("Search").'
'; -print $langs->trans("Name").':
'; @@ -117,19 +117,19 @@ if ($catname || $id > 0) { $cats = $categstatic->rechercher($id, $catname, $typetext); - print ''; + print '
'; print ''; foreach ($cats as $cat) { print "\t".''."\n"; print "\t\t\n"; @@ -153,24 +153,24 @@ print '

'; $cate_arbo = $categstatic->get_full_arbo($typetext); // Define fulltree array -$fulltree=$cate_arbo; +$fulltree = $cate_arbo; // 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) +$data = array(); +$data[] = array('rowid'=>0, 'fk_menu'=>-1, 'title'=>"racine", 'mainmenu'=>'', 'leftmenu'=>'', 'fk_mainmenu'=>'', 'fk_leftmenu'=>''); +foreach ($fulltree as $key => $val) { - $categstatic->id=$val['id']; - $categstatic->ref=$val['label']; - $categstatic->color=$val['color']; - $categstatic->type=$type; - $li=$categstatic->getNomUrl(1, '', 60); - $desc=dol_htmlcleanlastbr($val['description']); + $categstatic->id = $val['id']; + $categstatic->ref = $val['label']; + $categstatic->color = $val['color']; + $categstatic->type = $type; + $li = $categstatic->getNomUrl(1, '', 60); + $desc = dol_htmlcleanlastbr($val['description']); $data[] = array( 'rowid'=>$val['rowid'], 'fk_menu'=>$val['fk_parent'], - 'entry'=>'
'.$langs->trans("FoundCats").'
"; - $categstatic->id=$cat->id; - $categstatic->ref=$cat->label; - $categstatic->label=$cat->label; - $categstatic->type=$cat->type; - $categstatic->color=$cat->color; - print 'color?' style="background: #'.$categstatic->color.';"':' style="background: #aaa"').'>'; + $categstatic->id = $cat->id; + $categstatic->ref = $cat->label; + $categstatic->label = $cat->label; + $categstatic->type = $cat->type; + $categstatic->color = $cat->color; + print 'color ? ' style="background: #'.$categstatic->color.';"' : ' style="background: #aaa"').'>'; print $categstatic->getNomUrl(1, ''); print ''; print "
'. + 'entry'=>'
color?' style="background: #'.$categstatic->color.';"':' style="background: #aaa"').'>'.$li.'
'. //''. ''. '
color ? ' style="background: #'.$categstatic->color.';"' : ' style="background: #aaa"').'>'.$li.''.dolGetFirstLineOfText($desc).''.img_view().'
' @@ -182,13 +182,13 @@ foreach($fulltree as $key => $val) print ''; print ''; -$nbofentries=(count($data) - 1); +$nbofentries = (count($data) - 1); if ($nbofentries > 0) { diff --git a/htdocs/categories/photos.php b/htdocs/categories/photos.php index 754b846576d..2556c2d2084 100644 --- a/htdocs/categories/photos.php +++ b/htdocs/categories/photos.php @@ -36,13 +36,13 @@ require_once DOL_DOCUMENT_ROOT.'/core/lib/categories.lib.php'; $langs->loadlangs(array('categories', 'bills')); -$id=GETPOST('id', 'int'); -$ref=GETPOST('ref'); -$type=GETPOST('type'); -$action=GETPOST('action', 'aZ09'); -$confirm=GETPOST('confirm'); +$id = GETPOST('id', 'int'); +$ref = GETPOST('ref'); +$type = GETPOST('type'); +$action = GETPOST('action', 'aZ09'); +$confirm = GETPOST('confirm'); -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 if ($id == "") { @@ -66,7 +66,7 @@ if ($id > 0) * 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']; @@ -74,15 +74,15 @@ if (isset($_FILES['userfile']) && $_FILES['userfile']['size'] > 0 && $_POST["sen { foreach ($file['name'] as $i => $name) { - if(empty($file['tmp_name'][$i]) || intval($conf->global->MAIN_UPLOAD_DOC) * 1000 <= filesize($file['tmp_name'][$i]) ) + if (empty($file['tmp_name'][$i]) || intval($conf->global->MAIN_UPLOAD_DOC) * 1000 <= filesize($file['tmp_name'][$i])) { - setEventMessage($file['name'][$i] .' : '. $langs->trans(empty($file['tmp_name'][$i])? 'ErrorFailedToSaveFile' : 'MaxSizeForUploadedFiles')); + setEventMessage($file['name'][$i].' : '.$langs->trans(empty($file['tmp_name'][$i]) ? 'ErrorFailedToSaveFile' : 'MaxSizeForUploadedFiles')); unset($file['name'][$i], $file['type'][$i], $file['tmp_name'][$i], $file['error'][$i], $file['size'][$i]); } } } - if(!empty($file['tmp_name'])) { + if (!empty($file['tmp_name'])) { $object->add_photo($upload_dir, $file); } } @@ -110,15 +110,15 @@ $formother = new FormOther($db); if ($object->id) { - if ($type == Categorie::TYPE_PRODUCT) $title=$langs->trans("ProductsCategoryShort"); - elseif ($type == Categorie::TYPE_SUPPLIER) $title=$langs->trans("SuppliersCategoryShort"); - elseif ($type == Categorie::TYPE_CUSTOMER) $title=$langs->trans("CustomersCategoryShort"); - elseif ($type == Categorie::TYPE_MEMBER) $title=$langs->trans("MembersCategoryShort"); - elseif ($type == Categorie::TYPE_CONTACT) $title=$langs->trans("ContactCategoriesShort"); - elseif ($type == Categorie::TYPE_ACCOUNT) $title=$langs->trans("AccountsCategoriesShort"); - elseif ($type == Categorie::TYPE_PROJECT) $title=$langs->trans("ProjectsCategoriesShort"); - elseif ($type == Categorie::TYPE_USER) $title=$langs->trans("UsersCategoriesShort"); - else $title=$langs->trans("Category"); + if ($type == Categorie::TYPE_PRODUCT) $title = $langs->trans("ProductsCategoryShort"); + elseif ($type == Categorie::TYPE_SUPPLIER) $title = $langs->trans("SuppliersCategoryShort"); + elseif ($type == Categorie::TYPE_CUSTOMER) $title = $langs->trans("CustomersCategoryShort"); + elseif ($type == Categorie::TYPE_MEMBER) $title = $langs->trans("MembersCategoryShort"); + elseif ($type == Categorie::TYPE_CONTACT) $title = $langs->trans("ContactCategoriesShort"); + elseif ($type == Categorie::TYPE_ACCOUNT) $title = $langs->trans("AccountsCategoriesShort"); + elseif ($type == Categorie::TYPE_PROJECT) $title = $langs->trans("ProjectsCategoriesShort"); + elseif ($type == Categorie::TYPE_USER) $title = $langs->trans("UsersCategoriesShort"); + else $title = $langs->trans("Category"); $head = categories_prepare_head($object, $type); @@ -150,7 +150,7 @@ if ($object->id) print '
'; print '
'; - print '
'.$langs->trans("Categories").''; -if (! empty($conf->use_javascript_ajax)) +if (!empty($conf->use_javascript_ajax)) { print ''; } print '
'; + print '
'; // Description print ''; - if ($nbbyrow) print ''; + print ''; $nbphoto++; } diff --git a/htdocs/categories/traduction.php b/htdocs/categories/traduction.php index 1c082dfe332..56363870dd7 100644 --- a/htdocs/categories/traduction.php +++ b/htdocs/categories/traduction.php @@ -41,11 +41,11 @@ $action = GETPOST('action', 'alpha'); $cancel = GETPOST('cancel', 'alpha'); $type = GETPOST('type', 'aZ09'); -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 // Security check -$fieldvalue = (! empty($id) ? $id : (! empty($ref) ? $ref : '')); -$fieldtype = (! empty($ref) ? 'ref' : 'rowid'); +$fieldvalue = (!empty($id) ? $id : (!empty($ref) ? $ref : '')); +$fieldtype = (!empty($ref) ? 'ref' : 'rowid'); if ($id == "") { @@ -74,7 +74,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(); @@ -92,7 +92,7 @@ $cancel != $langs->trans("Cancel") && if (!$error) { if (empty($libelle)) { $error++; - $object->errors[] = $langs->trans('Language_' . $forcelangprod) . ' : ' . $langs->trans('ErrorFieldRequired', $langs->transnoentitiesnoconv('Label')); + $object->errors[] = $langs->trans('Language_'.$forcelangprod).' : '.$langs->trans('ErrorFieldRequired', $langs->transnoentitiesnoconv('Label')); } if (!$error) { @@ -129,15 +129,15 @@ $cancel != $langs->trans("Cancel") && foreach ($object->multilangs as $key => $value) // enregistrement des nouvelles valeurs dans l'objet { - $libelle = GETPOST('libelle-'. $key, 'alpha'); - $desc = GETPOST('desc-' . $key); + $libelle = GETPOST('libelle-'.$key, 'alpha'); + $desc = GETPOST('desc-'.$key); if (empty($libelle)) { $error++; - $object->errors[] = $langs->trans('Language_' . $key) . ' : ' . $langs->trans('ErrorFieldRequired', $langs->transnoentitiesnoconv('Label')); + $object->errors[] = $langs->trans('Language_'.$key).' : '.$langs->trans('ErrorFieldRequired', $langs->transnoentitiesnoconv('Label')); } - if ( $key == $current_lang ) { + if ($key == $current_lang) { $object->label = $libelle; $object->description = dol_htmlcleanlastbr($desc); } else { @@ -169,24 +169,24 @@ $result = $object->fetch($id, $ref); llxHeader("", "", $langs->trans("Translation")); $form = new Form($db); -$formadmin=new FormAdmin($db); +$formadmin = new FormAdmin($db); $formother = new FormOther($db); -if ($type == Categorie::TYPE_PRODUCT) $title=$langs->trans("ProductsCategoryShort"); -elseif ($type == Categorie::TYPE_SUPPLIER) $title=$langs->trans("SuppliersCategoryShort"); -elseif ($type == Categorie::TYPE_CUSTOMER) $title=$langs->trans("CustomersCategoryShort"); -elseif ($type == Categorie::TYPE_MEMBER) $title=$langs->trans("MembersCategoryShort"); -elseif ($type == Categorie::TYPE_CONTACT) $title=$langs->trans("ContactCategoriesShort"); -elseif ($type == Categorie::TYPE_ACCOUNT) $title=$langs->trans("AccountsCategoriesShort"); -elseif ($type == Categorie::TYPE_PROJECT) $title=$langs->trans("ProjectsCategoriesShort"); -elseif ($type == Categorie::TYPE_USER) $title=$langs->trans("UsersCategoriesShort"); -else $title=$langs->trans("Category"); +if ($type == Categorie::TYPE_PRODUCT) $title = $langs->trans("ProductsCategoryShort"); +elseif ($type == Categorie::TYPE_SUPPLIER) $title = $langs->trans("SuppliersCategoryShort"); +elseif ($type == Categorie::TYPE_CUSTOMER) $title = $langs->trans("CustomersCategoryShort"); +elseif ($type == Categorie::TYPE_MEMBER) $title = $langs->trans("MembersCategoryShort"); +elseif ($type == Categorie::TYPE_CONTACT) $title = $langs->trans("ContactCategoriesShort"); +elseif ($type == Categorie::TYPE_ACCOUNT) $title = $langs->trans("AccountsCategoriesShort"); +elseif ($type == Categorie::TYPE_PROJECT) $title = $langs->trans("ProjectsCategoriesShort"); +elseif ($type == Categorie::TYPE_USER) $title = $langs->trans("UsersCategoriesShort"); +else $title = $langs->trans("Category"); $head = categories_prepare_head($object, $type); // Calculate $cnt_trans $cnt_trans = 0; -if (! empty($object->multilangs)) +if (!empty($object->multilangs)) { foreach ($object->multilangs as $key => $value) { @@ -199,22 +199,22 @@ dol_fiche_head($head, 'translation', $title, -1, 'category'); $linkback = ''.$langs->trans("BackToList").''; $object->ref = $object->label; -$morehtmlref='
'.$langs->trans("Root").' >> '; +$morehtmlref = '
'.$langs->trans("Root").' >> '; $ways = $object->print_all_ways(" >> ", '', 1); foreach ($ways as $way) { - $morehtmlref.=$way."
\n"; + $morehtmlref .= $way."
\n"; } -$morehtmlref.='
'; +$morehtmlref .= '
'; -dol_banner_tab($object, 'ref', $linkback, ($user->socid?0:1), 'ref', 'ref', $morehtmlref, '', 0, '', '', 1); +dol_banner_tab($object, 'ref', $linkback, ($user->socid ? 0 : 1), 'ref', 'ref', $morehtmlref, '', 0, '', '', 1); print '
'; print '
'; print '
'; -print '
'; @@ -181,7 +181,7 @@ if ($object->id) if ($action != 'ajout_photo' && $user->rights->categorie->creer) { - if (! empty($conf->global->MAIN_UPLOAD_DOC)) + if (!empty($conf->global->MAIN_UPLOAD_DOC)) { print ''; print $langs->trans("AddPhoto").''; @@ -198,23 +198,23 @@ 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 = 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') { - $nbphoto=0; - $nbbyrow=5; + $nbphoto = 0; + $nbbyrow = 5; $maxWidth = 160; $maxHeight = 120; - $pdir = get_exdir($object->id, 2, 0, 0, $object, 'category') . $object->id ."/photos/"; + $pdir = get_exdir($object->id, 2, 0, 0, $object, 'category').$object->id."/photos/"; $dir = $upload_dir.'/'.$pdir; $listofphoto = $object->liste_photos($dir); @@ -229,22 +229,22 @@ if ($object->id) $nbphoto++; if ($nbbyrow && ($nbphoto % $nbbyrow == 1)) print '
'; + if ($nbbyrow) print ''; print ''; // Si fichier vignette disponible, on l'utilise, sinon on utilise photo origine if ($obj['photo_vignette']) { - $filename=$obj['photo_vignette']; + $filename = $obj['photo_vignette']; } else { - $filename=$obj['photo']; + $filename = $obj['photo']; } // Nom affiche - $viewfilename=$obj['photo']; + $viewfilename = $obj['photo']; // Taille de l'image $object->get_image_size($dir.$filename); @@ -274,7 +274,7 @@ if ($object->id) // Ferme tableau while ($nbphoto % $nbbyrow) { - print '  
'; +print '
'; // Description print ''; @@ -707,7 +707,7 @@ if (($action != 'create' && $action != 'add') || ($action == 'create' && $error) // Checkbox print '' ; + print ''; print ''; @@ -719,7 +719,7 @@ if (($action != 'create' && $action != 'add') || ($action == 'create' && $error) print ''; // Buttons actions - print '
global->INVOICE_CLOSE_ORDERS_OFF_BY_DEFAULT_FORMASSINVOICE)?' checked="checked"':'').' name="autocloseorders"> '.$langs->trans("CloseProcessedOrdersAutomatically"); + print '
global->INVOICE_CLOSE_ORDERS_OFF_BY_DEFAULT_FORMASSINVOICE) ? ' checked="checked"' : '').' name="autocloseorders"> '.$langs->trans("CloseProcessedOrdersAutomatically"); print '
'; print ''; print ''; diff --git a/htdocs/commande/stats/index.php b/htdocs/commande/stats/index.php index bdf277bc375..e3413f5b927 100644 --- a/htdocs/commande/stats/index.php +++ b/htdocs/commande/stats/index.php @@ -256,7 +256,7 @@ print '
'; // Show filter box print ''; print ''; -print '
'; @@ -266,14 +266,14 @@ if ($action == 'edit') print ''; print ''; print ''; - print ''; + print ''; - if (! empty($object->multilangs)) + if (!empty($object->multilangs)) { foreach ($object->multilangs as $key => $value) { print "
".$langs->trans('Language_'.$key)." :
"; - print ''; + print '
'; // Label $libelle = (GETPOST('libelle-'.$key, 'alpha') ? GETPOST('libelle-'.$key, 'alpha') : $object->multilangs[$key]['label']); @@ -304,23 +304,23 @@ elseif ($action != 'add') { if ($cnt_trans) print '
'; - if (! empty($object->multilangs)) + if (!empty($object->multilangs)) { foreach ($object->multilangs as $key => $value) { - $s=picto_from_langcode($key); - print '
'; - print ''; + $s = picto_from_langcode($key); + print '
'.($s?$s.' ':'')." ".$langs->trans('Language_'.$key).": ".''.img_delete('', '').'
'; + 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').'
'; } @@ -338,14 +338,14 @@ if ($action == 'add' && ($user->rights->produit->creer || $user->rights->service print ''; print ''; print ''; - print ''; + print ''; - print ''; + print '
'; print ''; - print ''; - print ''; + print ''; + print ''; print ''; // Other attributes -include DOL_DOCUMENT_ROOT . '/core/tpl/extrafields_view.tpl.php'; +include DOL_DOCUMENT_ROOT.'/core/tpl/extrafields_view.tpl.php'; print '
'.$langs->trans('Translation').''; print $formadmin->select_language(GETPOST('forcelangprod', 'alpha'), 'forcelangprod', 0, $object->multilangs); print '
' . $langs->trans('Label') . '
'.$langs->trans('Label').'
'.$langs->trans('Description').''; $doleditor = new DolEditor('desc', GETPOST('desc', 'none'), '', 160, 'dolibarr_notes', '', false, true, $conf->global->FCKEDITOR_ENABLE_PRODUCTDESC, ROWS_3, '90%'); $doleditor->Create(); diff --git a/htdocs/categories/viewcat.php b/htdocs/categories/viewcat.php index 45926847df4..789490a605c 100644 --- a/htdocs/categories/viewcat.php +++ b/htdocs/categories/viewcat.php @@ -40,19 +40,19 @@ $type = GETPOST('type', 'aZ09'); $removeelem = GETPOST('removeelem', 'int'); $elemid = GETPOST('elemid', 'int'); -$action = GETPOST('action', 'aZ09')?GETPOST('action', 'aZ09'):'view'; // The action 'add', 'create', 'edit', 'update', 'view', ... -$massaction = GETPOST('massaction', 'alpha'); // The bulk action (combo box choice into lists) -$show_files = GETPOST('show_files', 'int'); // Show files area generated by bulk actions ? -$confirm = GETPOST('confirm', 'alpha'); // Result of a confirmation -$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'):'myobjectlist'; // 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') +$action = GETPOST('action', 'aZ09') ?GETPOST('action', 'aZ09') : 'view'; // The action 'add', 'create', 'edit', 'update', 'view', ... +$massaction = GETPOST('massaction', 'alpha'); // The bulk action (combo box choice into lists) +$show_files = GETPOST('show_files', 'int'); // Show files area generated by bulk actions ? +$confirm = GETPOST('confirm', 'alpha'); // Result of a confirmation +$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') : 'myobjectlist'; // 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') // Load variable for pagination -$limit = GETPOST('limit', 'int')?GETPOST('limit', 'int'):$conf->liste_limit; +$limit = GETPOST('limit', 'int') ?GETPOST('limit', 'int') : $conf->liste_limit; $sortfield = GETPOST('sortfield', 'alpha'); $sortorder = GETPOST('sortorder', 'alpha'); $page = GETPOST('page', 'int'); @@ -71,7 +71,7 @@ if ($id == "" && $label == "") $result = restrictedArea($user, 'categorie', $id, '&category'); $object = new Categorie($db); -$result=$object->fetch($id, $label); +$result = $object->fetch($id, $label); if ($result <= 0) { dol_print_error($db, $object->error); exit; } @@ -80,21 +80,21 @@ if ($result <= 0) { dol_print_error($db, $object->error); exit; } -$type=$object->type; -if (is_numeric($type)) $type=Categorie::$MAP_ID_TO_CODE[$type]; // For backward compatibility +$type = $object->type; +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); // Initialize technical object to manage hooks. Note that conf->hooks_modules contains array array -$hookmanager->initHooks(array('categorycard','globalcard')); +$hookmanager->initHooks(array('categorycard', 'globalcard')); /* * Actions */ -$parameters=array(); -$reshook=$hookmanager->executeHooks('doActions', $parameters, $object, $action); // Note that $action and $object may have been modified by some hooks +$parameters = array(); +$reshook = $hookmanager->executeHooks('doActions', $parameters, $object, $action); // Note that $action and $object may have been modified by some hooks // Remove element from category if ($id > 0 && $removeelem > 0) { @@ -145,7 +145,7 @@ if ($id > 0 && $removeelem > 0) $elementtype = 'project'; } - $result=$object->del_type($tmpobject, $elementtype); + $result = $object->del_type($tmpobject, $elementtype); if ($result < 0) dol_print_error('', $object->error); } @@ -170,7 +170,7 @@ if ($type == Categorie::TYPE_PRODUCT && $elemid && $action == 'addintocategory' $elementtype = 'product'; // TODO Add into categ - $result=$object->add_type($newobject, $elementtype); + $result = $object->add_type($newobject, $elementtype); if ($result >= 0) { setEventMessages($langs->trans("WasAddedSuccessfully", $newobject->ref), null, 'mesgs'); @@ -197,18 +197,18 @@ if ($type == Categorie::TYPE_PRODUCT && $elemid && $action == 'addintocategory' $form = new Form($db); $formother = new FormOther($db); -$helpurl=''; +$helpurl = ''; llxHeader("", $langs->trans("Categories"), $helpurl); -if ($type == Categorie::TYPE_PRODUCT) $title=$langs->trans("ProductsCategoryShort"); -elseif ($type == Categorie::TYPE_SUPPLIER) $title=$langs->trans("SuppliersCategoryShort"); -elseif ($type == Categorie::TYPE_CUSTOMER) $title=$langs->trans("CustomersCategoryShort"); -elseif ($type == Categorie::TYPE_MEMBER) $title=$langs->trans("MembersCategoryShort"); -elseif ($type == Categorie::TYPE_CONTACT) $title=$langs->trans("ContactCategoriesShort"); -elseif ($type == Categorie::TYPE_ACCOUNT) $title=$langs->trans("AccountsCategoriesShort"); -elseif ($type == Categorie::TYPE_PROJECT) $title=$langs->trans("ProjectsCategoriesShort"); -elseif ($type == Categorie::TYPE_USER) $title=$langs->trans("ProjectsCategoriesShort"); -else $title=$langs->trans("Category"); +if ($type == Categorie::TYPE_PRODUCT) $title = $langs->trans("ProductsCategoryShort"); +elseif ($type == Categorie::TYPE_SUPPLIER) $title = $langs->trans("SuppliersCategoryShort"); +elseif ($type == Categorie::TYPE_CUSTOMER) $title = $langs->trans("CustomersCategoryShort"); +elseif ($type == Categorie::TYPE_MEMBER) $title = $langs->trans("MembersCategoryShort"); +elseif ($type == Categorie::TYPE_CONTACT) $title = $langs->trans("ContactCategoriesShort"); +elseif ($type == Categorie::TYPE_ACCOUNT) $title = $langs->trans("AccountsCategoriesShort"); +elseif ($type == Categorie::TYPE_PROJECT) $title = $langs->trans("ProjectsCategoriesShort"); +elseif ($type == Categorie::TYPE_USER) $title = $langs->trans("ProjectsCategoriesShort"); +else $title = $langs->trans("Category"); $head = categories_prepare_head($object, $type); @@ -257,7 +257,7 @@ print $formother->showColor($object->color); print '
'; print ''; @@ -338,13 +338,13 @@ else // List of mass actions available -$arrayofmassactions = array( +$arrayofmassactions = array( //'validate'=>$langs->trans("Validate"), //'generate_doc'=>$langs->trans("ReGeneratePDF"), //'builddoc'=>$langs->trans("PDFMerge"), //'presend'=>$langs->trans("SendByMail"), ); -$massactionbutton=$form->selectMassAction('', $arrayofmassactions); +$massactionbutton = $form->selectMassAction('', $arrayofmassactions); // List of products or services (type is type of category) @@ -357,7 +357,7 @@ if ($type == Categorie::TYPE_PRODUCT) } else { - $showclassifyform=1; $typeid=Categorie::TYPE_PRODUCT; + $showclassifyform = 1; $typeid = Categorie::TYPE_PRODUCT; // Form to add record into a category if ($showclassifyform) @@ -369,7 +369,7 @@ if ($type == Categorie::TYPE_PRODUCT) print ''; print ''; print ''; - print ''; + print '
'; print '\n"; // Link to delete from category print ''; // Payment term print ''; // Payment mode print ''; // Project - if (! empty($conf->projet->enabled)) + if (!empty($conf->projet->enabled)) { - $formproject=new FormProjets($db); + $formproject = new FormProjets($db); $langs->load('projects'); print ''; print '"; @@ -550,36 +550,36 @@ if (($action != 'create' && $action != 'add') || ($action == 'create' && $error) rights->societe->client->voir && !$socid) $sql.= ", ".MAIN_DB_PREFIX."societe_commerciaux as sc"; - $sql.= ' WHERE c.entity IN ('.getEntity('commande').')'; - $sql.= ' AND c.fk_soc = s.rowid'; + $sql .= ' c.date_valid, c.date_commande, c.date_livraison, c.fk_statut, c.facture as billed'; + $sql .= ' FROM '.MAIN_DB_PREFIX.'societe as s'; + $sql .= ', '.MAIN_DB_PREFIX.'commande as c'; + if (!$user->rights->societe->client->voir && !$socid) $sql .= ", ".MAIN_DB_PREFIX."societe_commerciaux as sc"; + $sql .= ' WHERE c.entity IN ('.getEntity('commande').')'; + $sql .= ' AND c.fk_soc = s.rowid'; // Show orders with status validated, shipping started and delivered (well any order we can bill) - $sql.= " AND ((c.fk_statut IN (1,2)) OR (c.fk_statut = 3 AND c.facture = 0))"; + $sql .= " AND ((c.fk_statut IN (1,2)) OR (c.fk_statut = 3 AND c.facture = 0))"; - 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; + if (!$user->rights->societe->client->voir && !$socid) $sql .= " AND s.rowid = sc.fk_soc AND sc.fk_user = ".$user->id; if ($sref) { - $sql.= " AND c.ref LIKE '%".$db->escape($sref)."%'"; + $sql .= " AND c.ref LIKE '%".$db->escape($sref)."%'"; } if ($sall) { - $sql.= " AND (c.ref LIKE '%".$db->escape($sall)."%' OR c.note LIKE '%".$db->escape($sall)."%')"; + $sql .= " AND (c.ref LIKE '%".$db->escape($sall)."%' OR c.note LIKE '%".$db->escape($sall)."%')"; } //Date filter - if ($date_start && $date_end) $sql.= " AND c.date_commande >= '".$db->idate($date_start)."' AND c.date_commande <= '".$db->idate($date_end)."'"; - if ($date_starty && $date_endy) $sql.= " AND c.date_livraison >= '".$db->idate($date_starty)."' AND c.date_livraison <= '".$db->idate($date_endy)."'"; + if ($date_start && $date_end) $sql .= " AND c.date_commande >= '".$db->idate($date_start)."' AND c.date_commande <= '".$db->idate($date_end)."'"; + if ($date_starty && $date_endy) $sql .= " AND c.date_livraison >= '".$db->idate($date_starty)."' AND c.date_livraison <= '".$db->idate($date_endy)."'"; if (!empty($sref_client)) { - $sql.= ' AND c.ref_client LIKE \'%'.$db->escape($sref_client).'%\''; + $sql .= ' AND c.ref_client LIKE \'%'.$db->escape($sref_client).'%\''; } - $sql.= $db->order($sortfield, $sortorder); + $sql .= $db->order($sortfield, $sortorder); $resql = $db->query($sql); if ($resql) @@ -590,23 +590,23 @@ if (($action != 'create' && $action != 'add') || ($action == 'create' && $error) $soc->fetch($socid); } $title = $langs->trans('ListOfOrders'); - $title.=' - '.$langs->trans('StatusOrderValidated').', '.$langs->trans("StatusOrderSent").', '.$langs->trans('StatusOrderToBill'); + $title .= ' - '.$langs->trans('StatusOrderValidated').', '.$langs->trans("StatusOrderSent").', '.$langs->trans('StatusOrderToBill'); $num = $db->num_rows($resql); print load_fiche_titre($title); $i = 0; - $period=$html->selectDate($date_start, 'date_start', 0, 0, 1, '', 1, 0).' - '.$html->selectDate($date_end, 'date_end', 0, 0, 1, '', 1, 0); - $periodely=$html->selectDate($date_starty, 'date_start_dely', 0, 0, 1, '', 1, 0).' - '.$html->selectDate($date_endy, 'date_end_dely', 0, 0, 1, '', 1, 0); + $period = $html->selectDate($date_start, 'date_start', 0, 0, 1, '', 1, 0).' - '.$html->selectDate($date_end, 'date_end', 0, 0, 1, '', 1, 0); + $periodely = $html->selectDate($date_starty, 'date_start_dely', 0, 0, 1, '', 1, 0).' - '.$html->selectDate($date_endy, 'date_end_dely', 0, 0, 1, '', 1, 0); - if (! empty($socid)) + if (!empty($socid)) { // Company - $companystatic->id=$socid; - $companystatic->name=$soc->name; + $companystatic->id = $socid; + $companystatic->name = $soc->name; print '

'.$companystatic->getNomUrl(1, 'customer').'

'; } print '
'; - print '
'; print $langs->trans("AddProductServiceIntoCategory").'  '; print $form->select_produits('', 'elemid', '', 0, 0, -1, 2, '', 1); @@ -408,15 +408,15 @@ if ($type == Categorie::TYPE_PRODUCT) print ''.$prod->label."'; - $permission=0; - if ($type == Categorie::TYPE_PRODUCT) $permission=($user->rights->produit->creer || $user->rights->service->creer); - if ($type == Categorie::TYPE_SUPPLIER) $permission=$user->rights->societe->creer; - if ($type == Categorie::TYPE_CUSTOMER) $permission=$user->rights->societe->creer; - if ($type == Categorie::TYPE_MEMBER) $permission=$user->rights->adherent->creer; - if ($type == Categorie::TYPE_PROJECT) $permission=$user->rights->projet->creer; + $permission = 0; + if ($type == Categorie::TYPE_PRODUCT) $permission = ($user->rights->produit->creer || $user->rights->service->creer); + if ($type == Categorie::TYPE_SUPPLIER) $permission = $user->rights->societe->creer; + if ($type == Categorie::TYPE_CUSTOMER) $permission = $user->rights->societe->creer; + if ($type == Categorie::TYPE_MEMBER) $permission = $user->rights->adherent->creer; + if ($type == Categorie::TYPE_PROJECT) $permission = $user->rights->projet->creer; if ($permission) { - print ""; + print ""; print $langs->trans("DeleteFromCat"); print img_picto($langs->trans("DeleteFromCat"), 'unlink'); print ""; @@ -455,7 +455,7 @@ if ($type == Categorie::TYPE_SUPPLIER) $param = '&limit='.$limit.'&id='.$id.'&type='.$type; $num = count($socs); $nbtotalofrecords = ''; $newcardbutton = ''; print_barre_liste($langs->trans("Suppliers"), $page, $_SERVER["PHP_SELF"], $param, $sortfield, $sortorder, $massactionbutton, $num, $nbtotalofrecords, '', 0, $newcardbutton, '', $limit); - print ''."\n"; + print '
'."\n"; print '\n"; if (count($socs) > 0) @@ -472,15 +472,15 @@ if ($type == Categorie::TYPE_SUPPLIER) print "\n"; // Link to delete from category print ''; print ''; print ''; @@ -431,7 +431,7 @@ if ($object->id > 0) if ($object->client) { - if (! empty($conf->commande->enabled) && ! empty($conf->global->ORDER_MANAGE_MIN_AMOUNT)) + if (!empty($conf->commande->enabled) && !empty($conf->global->ORDER_MANAGE_MIN_AMOUNT)) { print ''."\n"; print ''; @@ -446,7 +446,7 @@ if ($object->id > 0) // Multiprice level - if (! empty($conf->global->PRODUIT_MULTIPRICES) || ! empty($conf->global->PRODUIT_CUSTOMER_PRICES_BY_QTY_MULTIPRICES)) + if (!empty($conf->global->PRODUIT_MULTIPRICES) || !empty($conf->global->PRODUIT_CUSTOMER_PRICES_BY_QTY_MULTIPRICES)) { print '"; print ''; } // Preferred shipping Method - if (! empty($conf->global->SOCIETE_ASK_FOR_SHIPPING_METHOD)) { + if (!empty($conf->global->SOCIETE_ASK_FOR_SHIPPING_METHOD)) { print ''; print ''; print ''; @@ -526,155 +526,155 @@ if ($resql) if ($sall) { - foreach($fieldstosearchall as $key => $val) $fieldstosearchall[$key]=$langs->trans($val); - print '
'.$langs->trans("FilterOnInto", $sall) . join(', ', $fieldstosearchall).'
'; + foreach ($fieldstosearchall as $key => $val) $fieldstosearchall[$key] = $langs->trans($val); + print '
'.$langs->trans("FilterOnInto", $sall).join(', ', $fieldstosearchall).'
'; } - $moreforfilter=''; + $moreforfilter = ''; // If the user can view prospects other than his' 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.='
'; + $moreforfilter .= '
'; + $moreforfilter .= $langs->trans('ThirdPartiesOfSaleRepresentative').': '; + $moreforfilter .= $formother->select_salesrepresentatives($search_sale, 'search_sale', $user, 0, 1, 'maxwidth200'); + $moreforfilter .= '
'; } // If the user can view other users 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 .= '
'; + $moreforfilter .= $langs->trans('LinkedToSpecificUsers').': '; + $moreforfilter .= $form->select_dolusers($search_user, 'search_user', 1, '', 0, '', '', 0, 0, 0, '', 0, '', 'maxwidth200'); + $moreforfilter .= '
'; } // If the user can view prospects other than his' 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'). ': '; + $moreforfilter .= '
'; + $moreforfilter .= $langs->trans('IncludingProductWithTag').': '; $cate_arbo = $form->select_all_categories(Categorie::TYPE_PRODUCT, null, 'parent', null, null, 1); - $moreforfilter.=$form->selectarray('search_product_category', $cate_arbo, $search_product_category, 1, 0, 0, '', 0, 0, 0, 0, 'maxwidth300', 1); - $moreforfilter.='
'; + $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)) + if (!empty($conf->categorie->enabled)) { - require_once DOL_DOCUMENT_ROOT . '/categories/class/categorie.class.php'; - $moreforfilter.='
'; - $moreforfilter.=$langs->trans('CustomersProspectsCategoriesShort').': '; - $moreforfilter.=$formother->select_categories('customer', $search_categ_cus, 'search_categ_cus', 1); - $moreforfilter.='
'; + require_once DOL_DOCUMENT_ROOT.'/categories/class/categorie.class.php'; + $moreforfilter .= '
'; + $moreforfilter .= $langs->trans('CustomersProspectsCategoriesShort').': '; + $moreforfilter .= $formother->select_categories('customer', $search_categ_cus, 'search_categ_cus', 1); + $moreforfilter .= '
'; } - $parameters=array(); - $reshook=$hookmanager->executeHooks('printFieldPreListTitle', $parameters); // Note that $action and $object may have been modified by hook + $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($moreforfilter)) + if (!empty($moreforfilter)) { print '
'; print $moreforfilter; print '
'; } - $varpage=empty($contextpage)?$_SERVER["PHP_SELF"]:$contextpage; - $selectedfields=$form->multiSelectArrayWithCheckbox('selectedfields', $arrayfields, $varpage); // This also change content of $arrayfields - $selectedfields.=$form->showCheckAddButtons('checkforselect', 1); + $varpage = empty($contextpage) ? $_SERVER["PHP_SELF"] : $contextpage; + $selectedfields = $form->multiSelectArrayWithCheckbox('selectedfields', $arrayfields, $varpage); // This also change content of $arrayfields + $selectedfields .= $form->showCheckAddButtons('checkforselect', 1); print '
'; - print '
'.$langs->trans("Name")."
'; - $permission=0; - if ($type == Categorie::TYPE_PRODUCT) $permission=($user->rights->produit->creer || $user->rights->service->creer); - if ($type == Categorie::TYPE_SUPPLIER) $permission=$user->rights->societe->creer; - if ($type == Categorie::TYPE_CUSTOMER) $permission=$user->rights->societe->creer; - if ($type == Categorie::TYPE_MEMBER) $permission=$user->rights->adherent->creer; - if ($type == Categorie::TYPE_PROJECT) $permission=$user->rights->projet->creer; + $permission = 0; + if ($type == Categorie::TYPE_PRODUCT) $permission = ($user->rights->produit->creer || $user->rights->service->creer); + if ($type == Categorie::TYPE_SUPPLIER) $permission = $user->rights->societe->creer; + if ($type == Categorie::TYPE_CUSTOMER) $permission = $user->rights->societe->creer; + if ($type == Categorie::TYPE_MEMBER) $permission = $user->rights->adherent->creer; + if ($type == Categorie::TYPE_PROJECT) $permission = $user->rights->projet->creer; if ($permission) { - print ""; + print ""; print $langs->trans("DeleteFromCat"); print img_picto($langs->trans("DeleteFromCat"), 'unlink'); print ""; @@ -500,7 +500,7 @@ if ($type == Categorie::TYPE_SUPPLIER) } } -if($type == Categorie::TYPE_CUSTOMER) +if ($type == Categorie::TYPE_CUSTOMER) { $socs = $object->getObjectsInCateg("customer", 0, $limit, $offset); if ($socs < 0) @@ -520,7 +520,7 @@ if($type == Categorie::TYPE_CUSTOMER) $param = '&limit='.$limit.'&id='.$id.'&type='.$type; $num = count($socs); $nbtotalofrecords = ''; $newcardbutton = ''; print_barre_liste($langs->trans("Customers"), $page, $_SERVER["PHP_SELF"], $param, $sortfield, $sortorder, $massactionbutton, $num, $nbtotalofrecords, '', 0, $newcardbutton, '', $limit); - print ''."\n"; + print '
'."\n"; print ''."\n"; if (count($socs) > 0) @@ -537,15 +537,15 @@ if($type == Categorie::TYPE_CUSTOMER) print "\n"; // Link to delete from category print ''."\n"; print '\n"; print '\n"; print '\n"; // Link to delete from category print ''; + print ''; print ''; // Absolute discounts (Discounts-Drawbacks-Rebates) @@ -408,7 +408,7 @@ if ($object->id > 0) print '
'.$langs->trans("Name").'
'; - $permission=0; - if ($type == Categorie::TYPE_PRODUCT) $permission=($user->rights->produit->creer || $user->rights->service->creer); - if ($type == Categorie::TYPE_SUPPLIER) $permission=$user->rights->societe->creer; - if ($type == Categorie::TYPE_CUSTOMER) $permission=$user->rights->societe->creer; - if ($type == Categorie::TYPE_MEMBER) $permission=$user->rights->adherent->creer; - if ($type == Categorie::TYPE_PROJECT) $permission=$user->rights->projet->creer; + $permission = 0; + if ($type == Categorie::TYPE_PRODUCT) $permission = ($user->rights->produit->creer || $user->rights->service->creer); + if ($type == Categorie::TYPE_SUPPLIER) $permission = $user->rights->societe->creer; + if ($type == Categorie::TYPE_CUSTOMER) $permission = $user->rights->societe->creer; + if ($type == Categorie::TYPE_MEMBER) $permission = $user->rights->adherent->creer; + if ($type == Categorie::TYPE_PROJECT) $permission = $user->rights->projet->creer; if ($permission) { - print ""; + print ""; print $langs->trans("DeleteFromCat"); print img_picto($langs->trans("DeleteFromCat"), 'unlink'); print ""; @@ -600,22 +600,22 @@ if ($type == Categorie::TYPE_MEMBER) print "\t".'
'; - $member->ref=$member->login; + $member->ref = $member->login; print $member->getNomUrl(1, 0); print "'.$member->lastname."'.$member->firstname."'; - $permission=0; - if ($type == Categorie::TYPE_PRODUCT) $permission=($user->rights->produit->creer || $user->rights->service->creer); - if ($type == Categorie::TYPE_SUPPLIER) $permission=$user->rights->societe->creer; - if ($type == Categorie::TYPE_CUSTOMER) $permission=$user->rights->societe->creer; - if ($type == Categorie::TYPE_MEMBER) $permission=$user->rights->adherent->creer; - if ($type == Categorie::TYPE_PROJECT) $permission=$user->rights->projet->creer; + $permission = 0; + if ($type == Categorie::TYPE_PRODUCT) $permission = ($user->rights->produit->creer || $user->rights->service->creer); + if ($type == Categorie::TYPE_SUPPLIER) $permission = $user->rights->societe->creer; + if ($type == Categorie::TYPE_CUSTOMER) $permission = $user->rights->societe->creer; + if ($type == Categorie::TYPE_MEMBER) $permission = $user->rights->adherent->creer; + if ($type == Categorie::TYPE_PROJECT) $permission = $user->rights->projet->creer; if ($permission) { - print ""; + print ""; print $langs->trans("DeleteFromCat"); print img_picto($langs->trans("DeleteFromCat"), 'unlink'); print ""; @@ -654,7 +654,7 @@ if ($type == Categorie::TYPE_CONTACT) $param = '&limit='.$limit.'&id='.$id.'&type='.$type; $num = count($contacts); $nbtotalofrecords = ''; $newcardbutton = ''; print_barre_liste($langs->trans("Contact"), $page, $_SERVER["PHP_SELF"], $param, $sortfield, $sortorder, $massactionbutton, $num, $nbtotalofrecords, '', 0, $newcardbutton, '', $limit); - print ''."\n"; + print '
'."\n"; print ''."\n"; if (count($contacts) > 0) @@ -671,15 +671,15 @@ if ($type == Categorie::TYPE_CONTACT) print "\n"; // Link to delete from category print '\n"; // Link to delete from category print '\n"; // Link to delete from category print ''; @@ -1509,17 +1509,17 @@ if ($id > 0) print ''; // Other attributes - $parameters=array(); - $reshook=$hookmanager->executeHooks('formObjectOptions', $parameters, $object, $action); // Note that $action and $object may have been modified by hook + $parameters = array(); + $reshook = $hookmanager->executeHooks('formObjectOptions', $parameters, $object, $action); // Note that $action and $object may have been modified by hook print $hookmanager->resPrint; if (empty($reshook)) { - print $object->showOptionals($extrafields, 'edit'); + print $object->showOptionals($extrafields, 'edit', $parameters); } print '
'.$langs->trans("Ref").'
'; - $permission=0; - if ($type == Categorie::TYPE_PRODUCT) $permission=($user->rights->produit->creer || $user->rights->service->creer); - if ($type == Categorie::TYPE_SUPPLIER) $permission=$user->rights->societe->creer; - if ($type == Categorie::TYPE_CUSTOMER) $permission=$user->rights->societe->creer; - if ($type == Categorie::TYPE_MEMBER) $permission=$user->rights->adherent->creer; - if ($type == Categorie::TYPE_PROJECT) $permission=$user->rights->projet->creer; + $permission = 0; + if ($type == Categorie::TYPE_PRODUCT) $permission = ($user->rights->produit->creer || $user->rights->service->creer); + if ($type == Categorie::TYPE_SUPPLIER) $permission = $user->rights->societe->creer; + if ($type == Categorie::TYPE_CUSTOMER) $permission = $user->rights->societe->creer; + if ($type == Categorie::TYPE_MEMBER) $permission = $user->rights->adherent->creer; + if ($type == Categorie::TYPE_PROJECT) $permission = $user->rights->projet->creer; if ($permission) { - print ""; + print ""; print $langs->trans("DeleteFromCat"); print img_picto($langs->trans("DeleteFromCat"), 'unlink'); print ""; @@ -740,15 +740,15 @@ if ($type == Categorie::TYPE_ACCOUNT) print ''.$account->number."'; - $permission=0; - if ($type == Categorie::TYPE_PRODUCT) $permission=($user->rights->produit->creer || $user->rights->service->creer); - if ($type == Categorie::TYPE_SUPPLIER) $permission=$user->rights->societe->creer; - if ($type == Categorie::TYPE_CUSTOMER) $permission=$user->rights->societe->creer; - if ($type == Categorie::TYPE_MEMBER) $permission=$user->rights->adherent->creer; - if ($type == Categorie::TYPE_PROJECT) $permission=$user->rights->projet->creer; + $permission = 0; + if ($type == Categorie::TYPE_PRODUCT) $permission = ($user->rights->produit->creer || $user->rights->service->creer); + if ($type == Categorie::TYPE_SUPPLIER) $permission = $user->rights->societe->creer; + if ($type == Categorie::TYPE_CUSTOMER) $permission = $user->rights->societe->creer; + if ($type == Categorie::TYPE_MEMBER) $permission = $user->rights->adherent->creer; + if ($type == Categorie::TYPE_PROJECT) $permission = $user->rights->projet->creer; if ($permission) { - print ""; + print ""; print $langs->trans("DeleteFromCat"); print img_picto($langs->trans("DeleteFromCat"), 'unlink'); print ""; @@ -808,15 +808,15 @@ if ($type == Categorie::TYPE_PROJECT) print ''.$project->title."'; - $permission=0; - if ($type == Categorie::TYPE_PRODUCT) $permission=($user->rights->produit->creer || $user->rights->service->creer); - if ($type == Categorie::TYPE_SUPPLIER) $permission=$user->rights->societe->creer; - if ($type == Categorie::TYPE_CUSTOMER) $permission=$user->rights->societe->creer; - if ($type == Categorie::TYPE_MEMBER) $permission=$user->rights->adherent->creer; - if ($type == Categorie::TYPE_PROJECT) $permission=$user->rights->projet->creer; + $permission = 0; + if ($type == Categorie::TYPE_PRODUCT) $permission = ($user->rights->produit->creer || $user->rights->service->creer); + if ($type == Categorie::TYPE_SUPPLIER) $permission = $user->rights->societe->creer; + if ($type == Categorie::TYPE_CUSTOMER) $permission = $user->rights->societe->creer; + if ($type == Categorie::TYPE_MEMBER) $permission = $user->rights->adherent->creer; + if ($type == Categorie::TYPE_PROJECT) $permission = $user->rights->projet->creer; if ($permission) { - print ""; + print ""; print $langs->trans("DeleteFromCat"); print img_picto($langs->trans("DeleteFromCat"), 'unlink'); print ""; diff --git a/htdocs/collab/index.php b/htdocs/collab/index.php index 3e30164409b..d295daefdd4 100644 --- a/htdocs/collab/index.php +++ b/htdocs/collab/index.php @@ -29,29 +29,29 @@ require_once DOL_DOCUMENT_ROOT.'/core/lib/admin.lib.php'; require_once DOL_DOCUMENT_ROOT.'/core/lib/files.lib.php'; // Load translation files required by the page -$langs->loadLangs(array("admin","other","website")); +$langs->loadLangs(array("admin", "other", "website")); -if (! $user->admin) accessforbidden(); +if (!$user->admin) accessforbidden(); -$conf->dol_hide_leftmenu = 1; // Force hide of left menu. +$conf->dol_hide_leftmenu = 1; // Force hide of left menu. -$error=0; -$website=GETPOST('website', 'alpha'); -$page=GETPOST('page', 'alpha'); -$pageid=GETPOST('pageid', 'int'); -$action=GETPOST('action', 'alpha'); +$error = 0; +$website = GETPOST('website', 'alpha'); +$page = GETPOST('page', 'alpha'); +$pageid = GETPOST('pageid', 'int'); +$action = GETPOST('action', 'alpha'); -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,8 +60,8 @@ 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 @@ -80,7 +80,7 @@ if ($action == 'add') $error++; } - if (! $error) + if (!$error) { $res = $objectpage->create($user); if ($res <= 0) @@ -89,11 +89,11 @@ if ($action == 'add') setEventMessages($objectpage->error, $objectpage->errors, 'errors'); } } - if (! $error) + if (!$error) { $db->commit(); setEventMessages($langs->trans("PageAdded", $objectpage->pageurl), null, 'mesgs'); - $action=''; + $action = ''; } else { @@ -116,13 +116,13 @@ if ($action == 'delete') 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,7 +149,7 @@ if ($action == 'delete') $form = new Form($db); -$help_url=''; +$help_url = ''; llxHeader('', $langs->trans("WebsiteSetup"), $help_url, '', 0, '', '', '', '', '', ''."\n".'
'); @@ -162,8 +162,8 @@ if ($action == 'create') // Add a margin under toolbar ? -$style=''; -if ($action != 'preview' && $action != 'editcontent') $style=' margin-bottom: 5px;'; +$style = ''; +if ($action != 'preview' && $action != 'editcontent') $style = ' margin-bottom: 5px;'; //var_dump($objectpage);exit; print '
'; diff --git a/htdocs/comm/action/card.php b/htdocs/comm/action/card.php index 09c8e344794..73408beefb0 100644 --- a/htdocs/comm/action/card.php +++ b/htdocs/comm/action/card.php @@ -87,7 +87,7 @@ $formfile = new FormFile($db); $formactions = new FormActions($db); // Load object -if ($id > 0 && $action!='add') { +if ($id > 0 && $action != 'add') { $ret = $object->fetch($id); if ($ret > 0) { $ret = $object->fetch_optionals(); @@ -104,7 +104,7 @@ $extrafields->fetch_name_optionals_label($object->table_element); //var_dump($_POST); // Initialize technical object to manage hooks of page. Note that conf->hooks_modules contains array of hook context -$hookmanager->initHooks(array('actioncard','globalcard')); +$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 @@ -118,18 +118,18 @@ $listUserAssignedUpdated = false; // Remove user to assigned list if (empty($reshook) && (GETPOST('removedassigned') || GETPOST('removedassigned') == '0')) { - $idtoremove=GETPOST('removedassigned'); + $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]); } //var_dump($_POST['removedassigned']);exit; - $_SESSION['assignedtouser']=json_encode($tmpassigneduserids); - $donotclearsession=1; + $_SESSION['assignedtouser'] = json_encode($tmpassigneduserids); + $donotclearsession = 1; if ($action == 'add') $action = 'create'; if ($action == 'update') $action = 'edit'; @@ -142,15 +142,15 @@ if (empty($reshook) && (GETPOST('addassignedtouser') || GETPOST('updateassignedt // Add a new user if (GETPOST('assignedtouser') > 0) { - $assignedtouser=array(); - if (! empty($_SESSION['assignedtouser'])) + $assignedtouser = array(); + if (!empty($_SESSION['assignedtouser'])) { - $assignedtouser=json_decode($_SESSION['assignedtouser'], true); + $assignedtouser = json_decode($_SESSION['assignedtouser'], true); } - $assignedtouser[GETPOST('assignedtouser')]=array('id'=>GETPOST('assignedtouser'), 'transparency'=>GETPOST('transparency'), 'mandatory'=>1); - $_SESSION['assignedtouser']=json_encode($assignedtouser); + $assignedtouser[GETPOST('assignedtouser')] = array('id'=>GETPOST('assignedtouser'), 'transparency'=>GETPOST('transparency'), 'mandatory'=>1); + $_SESSION['assignedtouser'] = json_encode($assignedtouser); } - $donotclearsession=1; + $donotclearsession = 1; if ($action == 'add') $action = 'create'; if ($action == 'update') $action = 'edit'; @@ -168,7 +168,7 @@ if (empty($reshook) && $action == 'classin' && ($user->rights->agenda->allaction // Action clone object if (empty($reshook) && $action == 'confirm_clone' && $confirm == 'yes') { - if (1 == 0 && ! GETPOST('clone_content') && ! GETPOST('clone_receivers')) + if (1 == 0 && !GETPOST('clone_content') && !GETPOST('clone_receivers')) { setEventMessages($langs->trans("NoCloneOptionsSpecified"), null, 'errors'); } @@ -182,7 +182,7 @@ if (empty($reshook) && $action == 'confirm_clone' && $confirm == 'yes') } $result = $object->createFromClone($user, GETPOST('socid', 'int')); if ($result > 0) { - header("Location: " . $_SERVER['PHP_SELF'] . '?id=' . $result); + header("Location: ".$_SERVER['PHP_SELF'].'?id='.$result); exit(); } else { setEventMessages($object->error, $object->errors, 'errors'); @@ -195,17 +195,17 @@ if (empty($reshook) && $action == 'confirm_clone' && $confirm == 'yes') // Add event if (empty($reshook) && $action == 'add') { - $error=0; + $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'; + else $backtopage = DOL_URL_ROOT.'/comm/action/index.php'; } if (!empty($socpeopleassigned[0])) { - $result=$contact->fetch($socpeopleassigned[0]); + $result = $contact->fetch($socpeopleassigned[0]); } if ($cancel) @@ -214,31 +214,31 @@ if (empty($reshook) && $action == 'add') exit; } - $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 + $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 - $datep=dol_mktime($fulldayevent?'00':GETPOST("aphour", 'int'), $fulldayevent?'00':GETPOST("apmin", 'int'), $fulldayevent?'00':GETPOST("apsec", 'int'), GETPOST("apmonth", 'int'), GETPOST("apday", 'int'), GETPOST("apyear", 'int')); - $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')); + $datep = dol_mktime($fulldayevent ? '00' : GETPOST("aphour", 'int'), $fulldayevent ? '00' : GETPOST("apmin", 'int'), $fulldayevent ? '00' : GETPOST("apsec", 'int'), GETPOST("apmonth", 'int'), GETPOST("apday", 'int'), GETPOST("apyear", 'int')); + $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')); // Check parameters - if (! $datef && $percentage == 100) + if (!$datef && $percentage == 100) { - $error++; $donotclearsession=1; + $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; + $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; + $error++; $donotclearsession = 1; $action = 'create'; setEventMessages($langs->trans("ErrorFieldRequired", $langs->transnoentitiesnoconv("Type")), null, 'errors'); } @@ -247,16 +247,16 @@ if (empty($reshook) && $action == 'add') $object->type_code = GETPOST('actioncode', 'aZ09'); } - if (! $error) + if (!$error) { // Initialisation objet actioncomm - $object->priority = GETPOST("priority")?GETPOST("priority"):0; - $object->fulldayevent = (! empty($fulldayevent)?1:0); + $object->priority = GETPOST("priority") ?GETPOST("priority") : 0; + $object->fulldayevent = (!empty($fulldayevent) ? 1 : 0); $object->location = GETPOST("location"); $object->label = trim(GETPOST('label')); $object->fk_element = GETPOST("fk_element", 'int'); $object->elementtype = GETPOST("elementtype", 'alpha'); - if (! GETPOST('label')) + if (!GETPOST('label')) { if (GETPOST('actioncode', 'aZ09') == 'AC_RDV' && $contact->getFullName($langs)) { @@ -290,28 +290,28 @@ if (empty($reshook) && $action == 'add') $object->datep = $datep; $object->datef = $datef; $object->percentage = $percentage; - $object->duree=(((int) GETPOST('dureehour') * 60) + (int) GETPOST('dureemin')) * 60; + $object->duree = (((int) GETPOST('dureehour') * 60) + (int) GETPOST('dureemin')) * 60; - $transparency=(GETPOST("transparency")=='on'?1:0); + $transparency = (GETPOST("transparency") == 'on' ? 1 : 0); - $listofuserid=array(); - if (! empty($_SESSION['assignedtouser'])) $listofuserid=json_decode($_SESSION['assignedtouser'], true); - $i=0; - foreach($listofuserid as $key => $value) + $listofuserid = array(); + 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']; + if ($value['id'] > 0) $object->userownerid = $value['id']; $object->transparency = $transparency; } - $object->userassigned[$value['id']]=array('id'=>$value['id'], 'transparency'=>$transparency); + $object->userassigned[$value['id']] = array('id'=>$value['id'], 'transparency'=>$transparency); $i++; } } - if (! $error && ! empty($conf->global->AGENDA_ENABLE_DONEBY)) + if (!$error && !empty($conf->global->AGENDA_ENABLE_DONEBY)) { if (GETPOST("doneby") > 0) $object->userdoneid = GETPOST("doneby", "int"); } @@ -322,29 +322,29 @@ if (empty($reshook) && $action == 'add') if (GETPOST('socid', 'int') > 0) { - $object->socid=GETPOST('socid', 'int'); + $object->socid = GETPOST('socid', 'int'); $object->fetch_thirdparty(); - $object->societe = $object->thirdparty; // For backward compatibility + $object->societe = $object->thirdparty; // For backward compatibility } // Check parameters if (empty($object->userownerid) && empty($_SESSION['assignedtouser'])) { - $error++; $donotclearsession=1; + $error++; $donotclearsession = 1; $action = 'create'; setEventMessages($langs->trans("ErrorFieldRequired", $langs->transnoentitiesnoconv("ActionsOwnedBy")), null, 'errors'); } if ($object->type_code == 'AC_RDV' && ($datep == '' || ($datef == '' && empty($fulldayevent)))) { - $error++; $donotclearsession=1; + $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; + $error++; $donotclearsession = 1; $action = 'create'; setEventMessages($langs->trans("ErrorFieldRequired", $langs->transnoentitiesnoconv("Date")), null, 'errors'); } @@ -363,35 +363,35 @@ if (empty($reshook) && $action == 'add') $ret = $extrafields->setOptionalsFromPost(null, $object); if ($ret < 0) $error++; - if (! $error) + if (!$error) { $db->begin(); // Creation of action/event - $idaction=$object->create($user); + $idaction = $object->create($user); if ($idaction > 0) { - if (! $object->error) + if (!$object->error) { 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. + $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. $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):'')); + 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:'')); + 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:'')); + header("Location: ".DOL_URL_ROOT.'/comm/action/index.php'.($moreparam ? '?'.$moreparam : '')); } exit; } @@ -400,16 +400,16 @@ if (empty($reshook) && $action == 'add') // If error $db->rollback(); $langs->load("errors"); - $error=$langs->trans($object->error); + $error = $langs->trans($object->error); setEventMessages($error, null, 'errors'); - $action = 'create'; $donotclearsession=1; + $action = 'create'; $donotclearsession = 1; } } else { $db->rollback(); setEventMessages($object->error, $object->errors, 'errors'); - $action = 'create'; $donotclearsession=1; + $action = 'create'; $donotclearsession = 1; } } } @@ -421,26 +421,26 @@ if (empty($reshook) && $action == 'update') { if (empty($cancel)) { - $fulldayevent=GETPOST('fullday'); - $aphour=GETPOST('aphour'); - $apmin=GETPOST('apmin'); - $p2hour=GETPOST('p2hour'); - $p2min=GETPOST('p2min'); - $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 + $fulldayevent = GETPOST('fullday'); + $aphour = GETPOST('aphour'); + $apmin = GETPOST('apmin'); + $p2hour = GETPOST('p2hour'); + $p2min = GETPOST('p2min'); + $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(); $object->fetch_userassigned(); $object->oldcopy = clone $object; - $datep=dol_mktime($fulldayevent?'00':$aphour, $fulldayevent?'00':$apmin, 0, $_POST["apmonth"], $_POST["apday"], $_POST["apyear"]); - $datef=dol_mktime($fulldayevent?'23':$p2hour, $fulldayevent?'59':$p2min, $fulldayevent?'59':'0', $_POST["p2month"], $_POST["p2day"], $_POST["p2year"]); + $datep = dol_mktime($fulldayevent ? '00' : $aphour, $fulldayevent ? '00' : $apmin, 0, $_POST["apmonth"], $_POST["apday"], $_POST["apyear"]); + $datef = dol_mktime($fulldayevent ? '23' : $p2hour, $fulldayevent ? '59' : $p2min, $fulldayevent ? '59' : '0', $_POST["p2month"], $_POST["p2day"], $_POST["p2year"]); $object->type_id = dol_getIdFromCode($db, GETPOST("actioncode", 'aZ09'), 'c_actioncomm'); $object->label = GETPOST("label", "alphanohtml"); @@ -448,7 +448,7 @@ if (empty($reshook) && $action == 'update') $object->datef = $datef; $object->percentage = $percentage; $object->priority = GETPOST("priority", "alphanohtml"); - $object->fulldayevent= GETPOST("fullday")?1:0; + $object->fulldayevent = GETPOST("fullday") ? 1 : 0; $object->location = GETPOST('location', "alphanohtml"); $object->socid = GETPOST("socid", "int"); $socpeopleassigned = GETPOST("socpeopleassigned", 'array'); @@ -460,66 +460,66 @@ if (empty($reshook) && $action == 'update') $object->contactid = key($object->socpeopleassigned); } $object->fk_project = GETPOST("projectid", 'int'); - $object->note = GETPOST("note", "none"); // deprecated - $object->note_private= GETPOST("note", "none"); + $object->note = GETPOST("note", "none"); // deprecated + $object->note_private = GETPOST("note", "none"); $object->fk_element = GETPOST("fk_element", "int"); $object->elementtype = GETPOST("elementtype", "alphanohtml"); - if (! $datef && $percentage == 100) + if (!$datef && $percentage == 100) { - $error++; $donotclearsession=1; + $error++; $donotclearsession = 1; setEventMessages($langs->transnoentitiesnoconv("ErrorFieldRequired", $langs->transnoentitiesnoconv("DateEnd")), $object->errors, 'errors'); $action = 'edit'; } - $transparency=(GETPOST("transparency")=='on'?1:0); + $transparency = (GETPOST("transparency") == 'on' ? 1 : 0); // Users - $listofuserid=array(); - if (! empty($_SESSION['assignedtouser'])) // Now concat assigned users + $listofuserid = array(); + 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) + $tmplist1 = json_decode($_SESSION['assignedtouser'], true); + foreach ($tmplist1 as $key => $val) { - if ($val['id'] > 0 && $val['id'] != $assignedtouser) $listofuserid[$val['id']]=$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 + $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 } - $object->userassigned=array(); $object->userownerid=0; // Clear old content - $i=0; - foreach($listofuserid as $key => $val) + $object->userassigned = array(); $object->userownerid = 0; // Clear old content + $i = 0; + 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 : '')); + $object->userassigned[$val['id']] = array('id'=>$val['id'], 'mandatory'=>0, 'transparency'=>($user->id == $val['id'] ? $transparency : '')); $i++; } - $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) + $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 (!empty($conf->global->AGENDA_ENABLE_DONEBY)) { - if (GETPOST("doneby")) $object->userdoneid=GETPOST("doneby", "int"); + 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; + $error++; $donotclearsession = 1; $action = 'edit'; setEventMessages($langs->trans("ErrorFieldRequired", $langs->transnoentitiesnoconv("Type")), null, 'errors'); } else { - $result=$cactioncomm->fetch(GETPOST('actioncode', 'aZ09')); + $result = $cactioncomm->fetch(GETPOST('actioncode', 'aZ09')); } if (empty($object->userownerid)) { - $error++; $donotclearsession=1; + $error++; $donotclearsession = 1; $action = 'edit'; setEventMessages($langs->trans("ErrorFieldRequired", $langs->transnoentitiesnoconv("ActionsOwnedBy")), null, 'errors'); } @@ -535,30 +535,30 @@ if (empty($reshook) && $action == 'update') $eventDateEnd = $object->datef; $sql = "SELECT er.rowid, r.ref as r_ref, ac.id as ac_id, ac.label as ac_label"; - $sql .= " FROM " . MAIN_DB_PREFIX . "element_resources as er"; - $sql .= " INNER JOIN " . MAIN_DB_PREFIX . "resource as r ON r.rowid = er.resource_id AND er.resource_type = 'dolresource'"; - $sql .= " INNER JOIN " . MAIN_DB_PREFIX . "actioncomm as ac ON ac.id = er.element_id AND er.element_type = '" . $db->escape($object->element) . "'"; - $sql .= " WHERE ac.id != " . $object->id; + $sql .= " FROM ".MAIN_DB_PREFIX."element_resources as er"; + $sql .= " INNER JOIN ".MAIN_DB_PREFIX."resource as r ON r.rowid = er.resource_id AND er.resource_type = 'dolresource'"; + $sql .= " INNER JOIN ".MAIN_DB_PREFIX."actioncomm as ac ON ac.id = er.element_id AND er.element_type = '".$db->escape($object->element)."'"; + $sql .= " WHERE ac.id != ".$object->id; $sql .= " AND er.resource_id IN ("; - $sql .= " SELECT resource_id FROM " . MAIN_DB_PREFIX . "element_resources"; - $sql .= " WHERE element_id = " . $object->id; - $sql .= " AND element_type = '" . $db->escape($object->element) . "'"; + $sql .= " SELECT resource_id FROM ".MAIN_DB_PREFIX."element_resources"; + $sql .= " WHERE element_id = ".$object->id; + $sql .= " AND element_type = '".$db->escape($object->element)."'"; $sql .= " AND busy = 1"; $sql .= ")"; $sql .= " AND er.busy = 1"; $sql .= " AND ("; // event date start between ac.datep and ac.datep2 (if datep2 is null we consider there is no end) - $sql .= " (ac.datep <= '" . $db->idate($eventDateStart) . "' AND (ac.datep2 IS NULL OR ac.datep2 >= '" . $db->idate($eventDateStart) . "'))"; + $sql .= " (ac.datep <= '".$db->idate($eventDateStart)."' AND (ac.datep2 IS NULL OR ac.datep2 >= '".$db->idate($eventDateStart)."'))"; // event date end between ac.datep and ac.datep2 if (!empty($eventDateEnd)) { - $sql .= " OR (ac.datep <= '" . $db->idate($eventDateEnd) . "' AND (ac.datep2 >= '" . $db->idate($eventDateEnd) . "'))"; + $sql .= " OR (ac.datep <= '".$db->idate($eventDateEnd)."' AND (ac.datep2 >= '".$db->idate($eventDateEnd)."'))"; } // event date start before ac.datep and event date end after ac.datep2 $sql .= " OR ("; - $sql .= "ac.datep >= '" . $db->idate($eventDateStart) . "'"; + $sql .= "ac.datep >= '".$db->idate($eventDateStart)."'"; if (!empty($eventDateEnd)) { - $sql .= " AND (ac.datep2 IS NOT NULL AND ac.datep2 <= '" . $db->idate($eventDateEnd) . "')"; + $sql .= " AND (ac.datep2 IS NOT NULL AND ac.datep2 <= '".$db->idate($eventDateEnd)."')"; } $sql .= ")"; @@ -572,9 +572,9 @@ if (empty($reshook) && $action == 'update') if ($db->num_rows($resql) > 0) { // already in use $error++; - $object->error = $langs->trans('ErrorResourcesAlreadyInUse') . ' : '; + $object->error = $langs->trans('ErrorResourcesAlreadyInUse').' : '; while ($obj = $db->fetch_object($resql)) { - $object->error .= '
- ' . $langs->trans('ErrorResourceUseInEvent', $obj->r_ref, $obj->ac_label . ' [' . $obj->ac_id . ']'); + $object->error .= '
- '.$langs->trans('ErrorResourceUseInEvent', $obj->r_ref, $obj->ac_label.' ['.$obj->ac_id.']'); } $object->errors[] = $object->error; } @@ -587,11 +587,11 @@ if (empty($reshook) && $action == 'update') } } - if (! $error) + if (!$error) { $db->begin(); - $result=$object->update($user); + $result = $object->update($user); if ($result > 0) { @@ -607,9 +607,9 @@ if (empty($reshook) && $action == 'update') } } - if (! $error) + if (!$error) { - if (! empty($backtopage)) + if (!empty($backtopage)) { unset($_SESSION['assignedtouser']); header("Location: ".$backtopage); @@ -631,7 +631,7 @@ if (empty($reshook) && $action == 'confirm_delete' && GETPOST("confirm") == 'yes if ($user->rights->agenda->myactions->delete || $user->rights->agenda->allactions->delete) { - $result=$object->delete(); + $result = $object->delete(); if ($result >= 0) { @@ -656,21 +656,21 @@ if (empty($reshook) && GETPOST('actionmove', 'alpha') == 'mupdate') $shour = dol_print_date($object->datep, "%H"); $smin = dol_print_date($object->datep, "%M"); - $newdate=GETPOST('newdate', 'alpha'); - if (empty($newdate) || strpos($newdate, 'dayevent_') != 0 ) + $newdate = GETPOST('newdate', 'alpha'); + if (empty($newdate) || strpos($newdate, 'dayevent_') != 0) { header("Location: ".$backtopage); exit; } - $datep=dol_mktime($shour, $smin, 0, substr($newdate, 13, 2), substr($newdate, 15, 2), substr($newdate, 9, 4)); - if ($datep!=$object->datep) + $datep = dol_mktime($shour, $smin, 0, substr($newdate, 13, 2), substr($newdate, 15, 2), substr($newdate, 9, 4)); + if ($datep != $object->datep) { if (!empty($object->datef)) { - $object->datef+=$datep-$object->datep; + $object->datef += $datep - $object->datep; } - $object->datep=$datep; + $object->datep = $datep; if (!$error) { // check if an event resource is already in use @@ -679,30 +679,30 @@ if (empty($reshook) && GETPOST('actionmove', 'alpha') == 'mupdate') $eventDateEnd = $object->datef; $sql = "SELECT er.rowid, r.ref as r_ref, ac.id as ac_id, ac.label as ac_label"; - $sql .= " FROM " . MAIN_DB_PREFIX . "element_resources as er"; - $sql .= " INNER JOIN " . MAIN_DB_PREFIX . "resource as r ON r.rowid = er.resource_id AND er.resource_type = 'dolresource'"; - $sql .= " INNER JOIN " . MAIN_DB_PREFIX . "actioncomm as ac ON ac.id = er.element_id AND er.element_type = '" . $db->escape($object->element) . "'"; - $sql .= " WHERE ac.id != " . $object->id; + $sql .= " FROM ".MAIN_DB_PREFIX."element_resources as er"; + $sql .= " INNER JOIN ".MAIN_DB_PREFIX."resource as r ON r.rowid = er.resource_id AND er.resource_type = 'dolresource'"; + $sql .= " INNER JOIN ".MAIN_DB_PREFIX."actioncomm as ac ON ac.id = er.element_id AND er.element_type = '".$db->escape($object->element)."'"; + $sql .= " WHERE ac.id != ".$object->id; $sql .= " AND er.resource_id IN ("; - $sql .= " SELECT resource_id FROM " . MAIN_DB_PREFIX . "element_resources"; - $sql .= " WHERE element_id = " . $object->id; - $sql .= " AND element_type = '" . $db->escape($object->element) . "'"; + $sql .= " SELECT resource_id FROM ".MAIN_DB_PREFIX."element_resources"; + $sql .= " WHERE element_id = ".$object->id; + $sql .= " AND element_type = '".$db->escape($object->element)."'"; $sql .= " AND busy = 1"; $sql .= ")"; $sql .= " AND er.busy = 1"; $sql .= " AND ("; // event date start between ac.datep and ac.datep2 (if datep2 is null we consider there is no end) - $sql .= " (ac.datep <= '" . $db->idate($eventDateStart) . "' AND (ac.datep2 IS NULL OR ac.datep2 >= '" . $db->idate($eventDateStart) . "'))"; + $sql .= " (ac.datep <= '".$db->idate($eventDateStart)."' AND (ac.datep2 IS NULL OR ac.datep2 >= '".$db->idate($eventDateStart)."'))"; // event date end between ac.datep and ac.datep2 if (!empty($eventDateEnd)) { - $sql .= " OR (ac.datep <= '" . $db->idate($eventDateEnd) . "' AND (ac.datep2 >= '" . $db->idate($eventDateEnd) . "'))"; + $sql .= " OR (ac.datep <= '".$db->idate($eventDateEnd)."' AND (ac.datep2 >= '".$db->idate($eventDateEnd)."'))"; } // event date start before ac.datep and event date end after ac.datep2 $sql .= " OR ("; - $sql .= "ac.datep >= '" . $db->idate($eventDateStart) . "'"; + $sql .= "ac.datep >= '".$db->idate($eventDateStart)."'"; if (!empty($eventDateEnd)) { - $sql .= " AND (ac.datep2 IS NOT NULL AND ac.datep2 <= '" . $db->idate($eventDateEnd) . "')"; + $sql .= " AND (ac.datep2 IS NOT NULL AND ac.datep2 <= '".$db->idate($eventDateEnd)."')"; } $sql .= ")"; @@ -716,9 +716,9 @@ if (empty($reshook) && GETPOST('actionmove', 'alpha') == 'mupdate') if ($db->num_rows($resql) > 0) { // already in use $error++; - $object->error = $langs->trans('ErrorResourcesAlreadyInUse') . ' : '; + $object->error = $langs->trans('ErrorResourcesAlreadyInUse').' : '; while ($obj = $db->fetch_object($resql)) { - $object->error .= '
- ' . $langs->trans('ErrorResourceUseInEvent', $obj->r_ref, $obj->ac_label . ' [' . $obj->ac_id . ']'); + $object->error .= '
- '.$langs->trans('ErrorResourceUseInEvent', $obj->r_ref, $obj->ac_label.' ['.$obj->ac_id.']'); } $object->errors[] = $object->error; } @@ -743,14 +743,14 @@ if (empty($reshook) && GETPOST('actionmove', 'alpha') == 'mupdate') } } } - if (! empty($backtopage)) + if (!empty($backtopage)) { header("Location: ".$backtopage); exit; } else { - $action=''; + $action = ''; } } @@ -766,10 +766,10 @@ if (empty($reshook)) { * View */ -$form=new Form($db); -$formproject=new FormProjets($db); +$form = new Form($db); +$formproject = new FormProjets($db); -$help_url='EN:Module_Agenda_En|FR:Module_Agenda|ES:M&omodulodulo_Agenda'; +$help_url = 'EN:Module_Agenda_En|FR:Module_Agenda|ES:M&omodulodulo_Agenda'; llxHeader('', $langs->trans("Agenda"), $help_url); if ($action == 'create') @@ -779,13 +779,13 @@ if ($action == 'create') $socpeopleassigned = GETPOST("socpeopleassigned", 'array'); if (!empty($socpeopleassigned[0])) { - $result=$contact->fetch($socpeopleassigned[0]); + $result = $contact->fetch($socpeopleassigned[0]); 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"; - $formproject->selectTasks((! empty($societe->id)?$societe->id:-1), $object->fk_element, 'fk_element', 24, 0, 0, 1, 0, 0, 'maxwidth500', $object->fk_project); + $formproject->selectTasks((!empty($societe->id) ? $societe->id : -1), $object->fk_element, 'fk_element', 24, 0, 0, 1, 0, 0, 'maxwidth500', $object->fk_project); print ''; print '
'.$langs->trans("Description").''; // Editeur wysiwyg require_once DOL_DOCUMENT_ROOT.'/core/class/doleditor.class.php'; - $doleditor=new DolEditor('note', $object->note, '', 200, 'dolibarr_notes', 'In', true, true, $conf->fckeditor->enabled, ROWS_5, '90%'); + $doleditor = new DolEditor('note', $object->note, '', 200, 'dolibarr_notes', 'In', true, true, $conf->fckeditor->enabled, ROWS_5, '90%'); $doleditor->Create(); print '
'; @@ -1622,7 +1622,7 @@ if ($id > 0) print ''; // Type - if (! empty($conf->global->AGENDA_USE_EVENT_TYPE)) + if (!empty($conf->global->AGENDA_USE_EVENT_TYPE)) { print ''; } @@ -1630,12 +1630,12 @@ if ($id > 0) // Full day event print ''; - $rowspan=4; + $rowspan = 4; if (empty($conf->global->AGENDA_DISABLE_LOCATION)) $rowspan++; // Date start print ''; @@ -1643,9 +1643,9 @@ if ($id > 0) // Date end print ''; // Location @@ -1656,41 +1656,41 @@ if ($id > 0) // Assigned to print ''; // Object linked (if link is for thirdparty, contact, project it is a recording error. We should not have links in link table // for such objects because there is already a dedicated field into table llx_actioncomm. - if (! empty($object->fk_element) && ! empty($object->elementtype) && ! in_array($object->elementtype, array('societe','contact','project'))) + if (!empty($object->fk_element) && !empty($object->elementtype) && !in_array($object->elementtype, array('societe', 'contact', 'project'))) { include_once DOL_DOCUMENT_ROOT.'/core/lib/functions2.lib.php'; print ''; - $link=dolGetElementUrl($object->fk_element, $object->elementtype, 1); + $link = dolGetElementUrl($object->fk_element, $object->elementtype, 1); print ''; // Other attributes - $cols=3; - include DOL_DOCUMENT_ROOT . '/core/tpl/extrafields_view.tpl.php'; + $cols = 3; + include DOL_DOCUMENT_ROOT.'/core/tpl/extrafields_view.tpl.php'; print '
'.$langs->trans("Type").''.$langs->trans($object->type).'
'.$langs->trans("EventOnFullDay").''.yn($object->fulldayevent, 3).'
'.$langs->trans("DateActionStart").''; - if (! $object->fulldayevent) print dol_print_date($object->datep, 'dayhour'); + if (!$object->fulldayevent) print dol_print_date($object->datep, 'dayhour'); else print dol_print_date($object->datep, 'day'); if ($object->percentage == 0 && $object->datep && $object->datep < ($now - $delay_warning)) print img_warning($langs->trans("Late")); print '
'.$langs->trans("DateActionEnd").''; - if (! $object->fulldayevent) print dol_print_date($object->datef, 'dayhour'); + if (!$object->fulldayevent) print dol_print_date($object->datef, 'dayhour'); else print dol_print_date($object->datef, 'day'); - if ($object->percentage > 0 && $object->percentage < 100 && $object->datef && $object->datef < ($now- $delay_warning)) print img_warning($langs->trans("Late")); + if ($object->percentage > 0 && $object->percentage < 100 && $object->datef && $object->datef < ($now - $delay_warning)) print img_warning($langs->trans("Late")); print '
'.$langs->trans("ActionAssignedTo").''; - $listofuserid=array(); + $listofuserid = array(); if (empty($donotclearsession)) { if ($object->userownerid > 0) { - $listofuserid[$object->userownerid]=array( + $listofuserid[$object->userownerid] = array( 'id'=>$object->userownerid, - 'transparency'=>$object->transparency, // Force transparency on onwer from preoperty of event + 'transparency'=>$object->transparency, // Force transparency on onwer from preoperty of event 'answer_status'=>$object->userassigned[$object->userownerid]['answer_status'], 'mandatory'=>$object->userassigned[$object->userownerid]['mandatory'] ); } - if (! empty($object->userassigned)) // Now concat assigned users + if (!empty($object->userassigned)) // Now concat assigned users { // Restore array with key with same value than param 'id' - $tmplist1=$object->userassigned; - foreach($tmplist1 as $key => $val) + $tmplist1 = $object->userassigned; + foreach ($tmplist1 as $key => $val) { - if ($val['id'] && $val['id'] != $object->userownerid) $listofuserid[$val['id']]=$val; + if ($val['id'] && $val['id'] != $object->userownerid) $listofuserid[$val['id']] = $val; } } - $_SESSION['assignedtouser']=json_encode($listofuserid); + $_SESSION['assignedtouser'] = json_encode($listofuserid); } else { if (!empty($_SESSION['assignedtouser'])) { - $listofuserid=json_decode($_SESSION['assignedtouser'], true); + $listofuserid = json_decode($_SESSION['assignedtouser'], true); } } - $listofcontactid=array(); // not used yet - $listofotherid=array(); // not used yet + $listofcontactid = array(); // not used yet + $listofotherid = array(); // not used yet print '
'; - print $form->select_dolusers_forevent('view', 'assignedtouser', 1, '', 0, '', '', 0, 0, 0, '', ($object->datep != $object->datef)?1:0, $listofuserid, $listofcontactid, $listofotherid); + print $form->select_dolusers_forevent('view', 'assignedtouser', 1, '', 0, '', '', 0, 0, 0, '', ($object->datep != $object->datef) ? 1 : 0, $listofuserid, $listofcontactid, $listofotherid); print '
'; /* if ($object->datep != $object->datef && in_array($user->id,array_keys($listofuserid))) @@ -1710,7 +1710,7 @@ if ($id > 0) print '
'.$langs->trans("ActionDoneBy").''; if ($object->userdoneid > 0) { - $tmpuser=new User($db); + $tmpuser = new User($db); $tmpuser->fetch($object->userdoneid); print $tmpuser->getNomUrl(1); } @@ -1727,7 +1727,7 @@ if ($id > 0) if ($conf->societe->enabled) { // Related company - print '
'.$langs->trans("ActionOnCompany").''.($object->thirdparty->id?$object->thirdparty->getNomUrl(1):(''.$langs->trans("None").'')); + print '
'.$langs->trans("ActionOnCompany").''.($object->thirdparty->id ? $object->thirdparty->getNomUrl(1) : (''.$langs->trans("None").'')); if (is_object($object->thirdparty) && $object->thirdparty->id > 0 && $object->type_code == 'AC_TEL') { if ($object->thirdparty->fetch($object->thirdparty->id)) @@ -1770,16 +1770,16 @@ if ($id > 0) // Priority print '
'.$langs->trans("Priority").''; - print ($object->priority?$object->priority:''); + print ($object->priority ? $object->priority : ''); print '
'.$langs->trans("LinkedObject").''; if (empty($link)) print ''.$langs->trans("ObjectDeleted").''; else print $link; @@ -1792,8 +1792,8 @@ if ($id > 0) print '
'; @@ -1809,8 +1809,8 @@ if ($id > 0) print '
'; - $parameters=array(); - $reshook=$hookmanager->executeHooks('addMoreActionsButtons', $parameters, $object, $action); // Note that $action and $object may have been modified by hook + $parameters = array(); + $reshook = $hookmanager->executeHooks('addMoreActionsButtons', $parameters, $object, $action); // Note that $action and $object may have been modified by hook if (empty($reshook)) { if ($action != 'edit') @@ -1860,11 +1860,11 @@ if ($id > 0) * Documents generes */ - $filedir=$conf->agenda->multidir_output[$conf->entity].'/'.$object->id; - $urlsource=$_SERVER["PHP_SELF"]."?id=".$object->id; + $filedir = $conf->agenda->multidir_output[$conf->entity].'/'.$object->id; + $urlsource = $_SERVER["PHP_SELF"]."?id=".$object->id; - $genallowed=$user->rights->agenda->myactions->read; - $delallowed=$user->rights->agenda->myactions->create; + $genallowed = $user->rights->agenda->myactions->read; + $delallowed = $user->rights->agenda->myactions->create; print $formfile->showdocuments('actions', $object->id, $filedir, $urlsource, $genallowed, $delallowed, '', 0, 0, 0, 0, 0, '', '', '', $object->default_lang); diff --git a/htdocs/comm/action/class/actioncomm.class.php b/htdocs/comm/action/class/actioncomm.class.php index a07e4ceba1a..69f748412a1 100644 --- a/htdocs/comm/action/class/actioncomm.class.php +++ b/htdocs/comm/action/class/actioncomm.class.php @@ -38,7 +38,7 @@ class ActionComm extends CommonObject /** * @var string ID to identify managed object */ - public $element='action'; + public $element = 'action'; /** * @var string Name of table without prefix where object is stored @@ -233,14 +233,14 @@ class ActionComm extends CommonObject /** * @var User Object user of owner * @deprecated - * @see userownerid + * @see $userownerid */ public $usertodo; /** * @var User Object user that did action * @deprecated - * @see userdoneid + * @see $userdoneid */ public $userdone; @@ -257,14 +257,14 @@ class ActionComm extends CommonObject /** * @var Societe|null Company linked to action (optional) * @deprecated - * @see socid + * @see $socid */ public $societe; /** * @var Contact|null Contact linked to action (optional) * @deprecated - * @see contactid + * @see $contactid */ public $contact; @@ -294,6 +294,11 @@ class ActionComm extends CommonObject */ public $icalcolor; + /** + * @var string Extraparam + */ + public $extraparams; + /** * @var array Actions */ @@ -359,174 +364,174 @@ class ActionComm extends CommonObject */ public function create(User $user, $notrigger = 0) { - global $langs,$conf,$hookmanager; + global $langs, $conf, $hookmanager; - $error=0; - $now=dol_now(); + $error = 0; + $now = dol_now(); // Check parameters - if (! isset($this->userownerid) || $this->userownerid === '') // $this->userownerid may be 0 (anonymous event) of > 0 + if (!isset($this->userownerid) || $this->userownerid === '') // $this->userownerid may be 0 (anonymous event) of > 0 { dol_syslog("You tried to create an event but mandatory property ownerid was not defined", LOG_WARNING); - $this->errors[]='ErrorPropertyUserowneridNotDefined'; + $this->errors[] = 'ErrorPropertyUserowneridNotDefined'; return -1; } // Clean parameters - $this->label=dol_trunc(trim($this->label), 128); - $this->location=dol_trunc(trim($this->location), 128); - $this->note=dol_htmlcleanlastbr(trim($this->note)); + $this->label = dol_trunc(trim($this->label), 128); + $this->location = dol_trunc(trim($this->location), 128); + $this->note = dol_htmlcleanlastbr(trim($this->note)); if (empty($this->percentage)) $this->percentage = 0; - if (empty($this->priority) || ! is_numeric($this->priority)) $this->priority = 0; + if (empty($this->priority) || !is_numeric($this->priority)) $this->priority = 0; if (empty($this->fulldayevent)) $this->fulldayevent = 0; if (empty($this->punctual)) $this->punctual = 0; if (empty($this->transparency)) $this->transparency = 0; if ($this->percentage > 100) $this->percentage = 100; //if ($this->percentage == 100 && ! $this->dateend) $this->dateend = $this->date; - if (! empty($this->datep) && ! empty($this->datef)) $this->durationp=($this->datef - $this->datep); // deprecated + if (!empty($this->datep) && !empty($this->datef)) $this->durationp = ($this->datef - $this->datep); // deprecated //if (! empty($this->date) && ! empty($this->dateend)) $this->durationa=($this->dateend - $this->date); - if (! empty($this->datep) && ! empty($this->datef) && $this->datep > $this->datef) $this->datef=$this->datep; + if (!empty($this->datep) && !empty($this->datef) && $this->datep > $this->datef) $this->datef = $this->datep; //if (! empty($this->date) && ! empty($this->dateend) && $this->date > $this->dateend) $this->dateend=$this->date; - if (! isset($this->fk_project) || $this->fk_project < 0) $this->fk_project = 0; + if (!isset($this->fk_project) || $this->fk_project < 0) $this->fk_project = 0; // For backward compatibility - if ($this->elementtype=='facture') $this->elementtype='invoice'; - if ($this->elementtype=='commande') $this->elementtype='order'; - if ($this->elementtype=='contrat') $this->elementtype='contract'; + if ($this->elementtype == 'facture') $this->elementtype = 'invoice'; + if ($this->elementtype == 'commande') $this->elementtype = 'order'; + if ($this->elementtype == 'contrat') $this->elementtype = 'contract'; - if (! is_array($this->userassigned) && ! empty($this->userassigned)) // For backward compatibility when userassigned was an int instead fo array + if (!is_array($this->userassigned) && !empty($this->userassigned)) // For backward compatibility when userassigned was an int instead fo array { - $tmpid=$this->userassigned; - $this->userassigned=array(); - $this->userassigned[$tmpid]=array('id'=>$tmpid, 'transparency'=>$this->transparency); + $tmpid = $this->userassigned; + $this->userassigned = array(); + $this->userassigned[$tmpid] = array('id'=>$tmpid, 'transparency'=>$this->transparency); } - $userownerid=$this->userownerid; - $userdoneid=$this->userdoneid; + $userownerid = $this->userownerid; + $userdoneid = $this->userdoneid; // Be sure assigned user is defined as an array of array('id'=>,'mandatory'=>,...). - if (empty($this->userassigned) || count($this->userassigned) == 0 || ! is_array($this->userassigned)) + if (empty($this->userassigned) || count($this->userassigned) == 0 || !is_array($this->userassigned)) $this->userassigned = array($userownerid=>array('id'=>$userownerid, 'transparency'=>$this->transparency)); - if (! $this->type_id || ! $this->type_code) + if (!$this->type_id || !$this->type_code) { - $key=empty($this->type_id)?$this->type_code:$this->type_id; + $key = empty($this->type_id) ? $this->type_code : $this->type_id; // Get id from code - $cactioncomm=new CActionComm($this->db); - $result=$cactioncomm->fetch($key); + $cactioncomm = new CActionComm($this->db); + $result = $cactioncomm->fetch($key); if ($result > 0) { - $this->type_id=$cactioncomm->id; - $this->type_code=$cactioncomm->code; + $this->type_id = $cactioncomm->id; + $this->type_code = $cactioncomm->code; } elseif ($result == 0) { - $this->error='Failed to get record with id '.$this->type_id.' code '.$this->type_code.' from dictionary "type of events"'; + $this->error = 'Failed to get record with id '.$this->type_id.' code '.$this->type_code.' from dictionary "type of events"'; return -1; } else { - $this->error=$cactioncomm->error; + $this->error = $cactioncomm->error; return -1; } } - $code = empty($this->code)?$this->type_code:$this->code; + $code = empty($this->code) ? $this->type_code : $this->code; // Check parameters - if (! $this->type_id) + if (!$this->type_id) { - $this->error="ErrorWrongParameters"; + $this->error = "ErrorWrongParameters"; return -1; } $this->db->begin(); $sql = "INSERT INTO ".MAIN_DB_PREFIX."actioncomm"; - $sql.= "(datec,"; - $sql.= "datep,"; - $sql.= "datep2,"; - $sql.= "durationp,"; // deprecated - $sql.= "fk_action,"; - $sql.= "code,"; - $sql.= "fk_soc,"; - $sql.= "fk_project,"; - $sql.= "note,"; - $sql.= "fk_contact,"; - $sql.= "fk_user_author,"; - $sql.= "fk_user_action,"; - $sql.= "fk_user_done,"; - $sql.= "label,percent,priority,fulldayevent,location,punctual,"; - $sql.= "transparency,"; - $sql.= "fk_element,"; - $sql.= "elementtype,"; - $sql.= "entity,"; - $sql.= "extraparams,"; + $sql .= "(datec,"; + $sql .= "datep,"; + $sql .= "datep2,"; + $sql .= "durationp,"; // deprecated + $sql .= "fk_action,"; + $sql .= "code,"; + $sql .= "fk_soc,"; + $sql .= "fk_project,"; + $sql .= "note,"; + $sql .= "fk_contact,"; + $sql .= "fk_user_author,"; + $sql .= "fk_user_action,"; + $sql .= "fk_user_done,"; + $sql .= "label,percent,priority,fulldayevent,location,punctual,"; + $sql .= "transparency,"; + $sql .= "fk_element,"; + $sql .= "elementtype,"; + $sql .= "entity,"; + $sql .= "extraparams,"; // Fields emails - $sql.= "email_msgid,"; - $sql.= "email_from,"; - $sql.= "email_sender,"; - $sql.= "email_to,"; - $sql.= "email_tocc,"; - $sql.= "email_tobcc,"; - $sql.= "email_subject,"; - $sql.= "errors_to"; - $sql.= ") VALUES ("; - $sql.= "'".$this->db->idate($now)."', "; - $sql.= (strval($this->datep)!=''?"'".$this->db->idate($this->datep)."'":"null").", "; - $sql.= (strval($this->datef)!=''?"'".$this->db->idate($this->datef)."'":"null").", "; - $sql.= ((isset($this->durationp) && $this->durationp >= 0 && $this->durationp != '')?"'".$this->db->escape($this->durationp)."'":"null").", "; // deprecated - $sql.= (isset($this->type_id)?$this->type_id:"null").","; - $sql.= ($code?("'".$code."'"):"null").", "; - $sql.= ((isset($this->socid) && $this->socid > 0) ? $this->socid:"null").", "; - $sql.= ((isset($this->fk_project) && $this->fk_project > 0) ? $this->fk_project:"null").", "; - $sql.= " '".$this->db->escape($this->note_private?$this->note_private:$this->note)."', "; - $sql.= ((isset($this->contactid) && $this->contactid > 0) ? $this->contactid:"null").", "; - $sql.= (isset($user->id) && $user->id > 0 ? $user->id:"null").", "; - $sql.= ($userownerid>0 ? $userownerid:"null").", "; - $sql.= ($userdoneid>0 ? $userdoneid:"null").", "; - $sql.= "'".$this->db->escape($this->label)."','".$this->db->escape($this->percentage)."','".$this->db->escape($this->priority)."','".$this->db->escape($this->fulldayevent)."','".$this->db->escape($this->location)."','".$this->db->escape($this->punctual)."', "; - $sql.= "'".$this->db->escape($this->transparency)."', "; - $sql.= (! empty($this->fk_element)?$this->fk_element:"null").", "; - $sql.= (! empty($this->elementtype)?"'".$this->db->escape($this->elementtype)."'":"null").", "; - $sql.= $conf->entity.","; - $sql.= (! empty($this->extraparams)?"'".$this->db->escape($this->extraparams)."'":"null").", "; + $sql .= "email_msgid,"; + $sql .= "email_from,"; + $sql .= "email_sender,"; + $sql .= "email_to,"; + $sql .= "email_tocc,"; + $sql .= "email_tobcc,"; + $sql .= "email_subject,"; + $sql .= "errors_to"; + $sql .= ") VALUES ("; + $sql .= "'".$this->db->idate($now)."', "; + $sql .= (strval($this->datep) != '' ? "'".$this->db->idate($this->datep)."'" : "null").", "; + $sql .= (strval($this->datef) != '' ? "'".$this->db->idate($this->datef)."'" : "null").", "; + $sql .= ((isset($this->durationp) && $this->durationp >= 0 && $this->durationp != '') ? "'".$this->db->escape($this->durationp)."'" : "null").", "; // deprecated + $sql .= (isset($this->type_id) ? $this->type_id : "null").","; + $sql .= ($code ? ("'".$code."'") : "null").", "; + $sql .= ((isset($this->socid) && $this->socid > 0) ? $this->socid : "null").", "; + $sql .= ((isset($this->fk_project) && $this->fk_project > 0) ? $this->fk_project : "null").", "; + $sql .= " '".$this->db->escape($this->note_private ? $this->note_private : $this->note)."', "; + $sql .= ((isset($this->contactid) && $this->contactid > 0) ? $this->contactid : "null").", "; + $sql .= (isset($user->id) && $user->id > 0 ? $user->id : "null").", "; + $sql .= ($userownerid > 0 ? $userownerid : "null").", "; + $sql .= ($userdoneid > 0 ? $userdoneid : "null").", "; + $sql .= "'".$this->db->escape($this->label)."','".$this->db->escape($this->percentage)."','".$this->db->escape($this->priority)."','".$this->db->escape($this->fulldayevent)."','".$this->db->escape($this->location)."','".$this->db->escape($this->punctual)."', "; + $sql .= "'".$this->db->escape($this->transparency)."', "; + $sql .= (!empty($this->fk_element) ? $this->fk_element : "null").", "; + $sql .= (!empty($this->elementtype) ? "'".$this->db->escape($this->elementtype)."'" : "null").", "; + $sql .= $conf->entity.","; + $sql .= (!empty($this->extraparams) ? "'".$this->db->escape($this->extraparams)."'" : "null").", "; // Fields emails - $sql.= (! empty($this->email_msgid)?"'".$this->db->escape($this->email_msgid)."'":"null").", "; - $sql.= (! empty($this->email_from)?"'".$this->db->escape($this->email_from)."'":"null").", "; - $sql.= (! empty($this->email_sender)?"'".$this->db->escape($this->email_sender)."'":"null").", "; - $sql.= (! empty($this->email_to)?"'".$this->db->escape($this->email_to)."'":"null").", "; - $sql.= (! empty($this->email_tocc)?"'".$this->db->escape($this->email_tocc)."'":"null").", "; - $sql.= (! empty($this->email_tobcc)?"'".$this->db->escape($this->email_tobcc)."'":"null").", "; - $sql.= (! empty($this->email_subject)?"'".$this->db->escape($this->email_subject)."'":"null").", "; - $sql.= (! empty($this->errors_to)?"'".$this->db->escape($this->errors_to)."'":"null"); - $sql.= ")"; + $sql .= (!empty($this->email_msgid) ? "'".$this->db->escape($this->email_msgid)."'" : "null").", "; + $sql .= (!empty($this->email_from) ? "'".$this->db->escape($this->email_from)."'" : "null").", "; + $sql .= (!empty($this->email_sender) ? "'".$this->db->escape($this->email_sender)."'" : "null").", "; + $sql .= (!empty($this->email_to) ? "'".$this->db->escape($this->email_to)."'" : "null").", "; + $sql .= (!empty($this->email_tocc) ? "'".$this->db->escape($this->email_tocc)."'" : "null").", "; + $sql .= (!empty($this->email_tobcc) ? "'".$this->db->escape($this->email_tobcc)."'" : "null").", "; + $sql .= (!empty($this->email_subject) ? "'".$this->db->escape($this->email_subject)."'" : "null").", "; + $sql .= (!empty($this->errors_to) ? "'".$this->db->escape($this->errors_to)."'" : "null"); + $sql .= ")"; dol_syslog(get_class($this)."::add", LOG_DEBUG); - $resql=$this->db->query($sql); + $resql = $this->db->query($sql); if ($resql) { $this->id = $this->db->last_insert_id(MAIN_DB_PREFIX."actioncomm", "id"); // Now insert assignedusers - if (! $error) + if (!$error) { - foreach($this->userassigned as $key => $val) + foreach ($this->userassigned as $key => $val) { - if (! is_array($val)) // For backward compatibility when val=id + if (!is_array($val)) // For backward compatibility when val=id { - $val=array('id'=>$val); + $val = array('id'=>$val); } - $sql ="INSERT INTO ".MAIN_DB_PREFIX."actioncomm_resources(fk_actioncomm, element_type, fk_element, mandatory, transparency, answer_status)"; - $sql.=" VALUES(".$this->id.", 'user', ".$val['id'].", ".(empty($val['mandatory'])?'0':$val['mandatory']).", ".(empty($val['transparency'])?'0':$val['transparency']).", ".(empty($val['answer_status'])?'0':$val['answer_status']).")"; + $sql = "INSERT INTO ".MAIN_DB_PREFIX."actioncomm_resources(fk_actioncomm, element_type, fk_element, mandatory, transparency, answer_status)"; + $sql .= " VALUES(".$this->id.", 'user', ".$val['id'].", ".(empty($val['mandatory']) ? '0' : $val['mandatory']).", ".(empty($val['transparency']) ? '0' : $val['transparency']).", ".(empty($val['answer_status']) ? '0' : $val['answer_status']).")"; $resql = $this->db->query($sql); - if (! $resql) + if (!$resql) { $error++; - $this->errors[]=$this->db->lasterror(); + $this->errors[] = $this->db->lasterror(); } //var_dump($sql);exit; } @@ -538,27 +543,27 @@ class ActionComm extends CommonObject { foreach ($this->socpeopleassigned as $id => $Tab) { - $sql ="INSERT INTO ".MAIN_DB_PREFIX."actioncomm_resources(fk_actioncomm, element_type, fk_element, mandatory, transparency, answer_status)"; - $sql.=" VALUES(".$this->id.", 'socpeople', ".$id.", 0, 0, 0)"; + $sql = "INSERT INTO ".MAIN_DB_PREFIX."actioncomm_resources(fk_actioncomm, element_type, fk_element, mandatory, transparency, answer_status)"; + $sql .= " VALUES(".$this->id.", 'socpeople', ".$id.", 0, 0, 0)"; $resql = $this->db->query($sql); - if (! $resql) + if (!$resql) { $error++; - $this->errors[]=$this->db->lasterror(); + $this->errors[] = $this->db->lasterror(); } } } } - if (! $error) + if (!$error) { - $action='create'; + $action = 'create'; // Actions on extra fields if (empty($conf->global->MAIN_EXTRAFIELDS_DISABLED)) // For avoid conflicts if trigger used { - $result=$this->insertExtraFields(); + $result = $this->insertExtraFields(); if ($result < 0) { $error++; @@ -566,15 +571,15 @@ class ActionComm extends CommonObject } } - if (! $error && ! $notrigger) + if (!$error && !$notrigger) { // Call trigger - $result=$this->call_trigger('ACTION_CREATE', $user); + $result = $this->call_trigger('ACTION_CREATE', $user); if ($result < 0) { $error++; } // End call triggers } - if (! $error) + if (!$error) { $this->db->commit(); return $this->id; @@ -588,7 +593,7 @@ class ActionComm extends CommonObject else { $this->db->rollback(); - $this->error=$this->db->lasterror(); + $this->error = $this->db->lasterror(); return -1; } } @@ -604,8 +609,8 @@ class ActionComm extends CommonObject { global $db, $conf, $hookmanager; - $error=0; - $now=dol_now(); + $error = 0; + $now = dol_now(); $this->db->begin(); @@ -619,26 +624,26 @@ class ActionComm extends CommonObject //$this->fetch_userassigned(); $this->fetchResources(); - $this->id=0; + $this->id = 0; // Create clone - $this->context['createfromclone']='createfromclone'; - $result=$this->create($fuser); + $this->context['createfromclone'] = 'createfromclone'; + $result = $this->create($fuser); if ($result < 0) $error++; - if (! $error) + if (!$error) { // Hook of thirdparty module if (is_object($hookmanager)) { - $parameters=array('objFrom'=>$objFrom); - $action=''; - $reshook=$hookmanager->executeHooks('createFrom', $parameters, $this, $action); // Note that $action and $object may have been modified by some hooks + $parameters = array('objFrom'=>$objFrom); + $action = ''; + $reshook = $hookmanager->executeHooks('createFrom', $parameters, $this, $action); // Note that $action and $object may have been modified by some hooks if ($reshook < 0) $error++; } // Call trigger - $result=$this->call_trigger('ACTION_CLONE', $fuser); + $result = $this->call_trigger('ACTION_CLONE', $fuser); if ($result < 0) { $error++; } // End call triggers } @@ -646,7 +651,7 @@ class ActionComm extends CommonObject unset($this->context['createfromclone']); // End - if (! $error) + if (!$error) { $this->db->commit(); return $this->id; @@ -671,38 +676,38 @@ class ActionComm extends CommonObject global $langs; $sql = "SELECT a.id,"; - $sql.= " a.id as ref,"; - $sql.= " a.ref_ext,"; - $sql.= " a.datep,"; - $sql.= " a.datep2,"; - $sql.= " a.durationp,"; // deprecated - $sql.= " a.datec,"; - $sql.= " a.tms as datem,"; - $sql.= " a.code, a.label, a.note,"; - $sql.= " a.fk_soc,"; - $sql.= " a.fk_project,"; - $sql.= " a.fk_user_author, a.fk_user_mod,"; - $sql.= " a.fk_user_action, a.fk_user_done,"; - $sql.= " a.fk_contact, a.percent as percentage,"; - $sql.= " a.fk_element as elementid, a.elementtype,"; - $sql.= " a.priority, a.fulldayevent, a.location, a.punctual, a.transparency,"; - $sql.= " c.id as type_id, c.code as type_code, c.libelle as type_label, c.color as type_color, c.picto as type_picto,"; - $sql.= " s.nom as socname,"; - $sql.= " u.firstname, u.lastname as lastname"; - $sql.= " FROM ".MAIN_DB_PREFIX."actioncomm as a "; - $sql.= " LEFT JOIN ".MAIN_DB_PREFIX."c_actioncomm as c ON a.fk_action=c.id "; - $sql.= " LEFT JOIN ".MAIN_DB_PREFIX."user as u on u.rowid = a.fk_user_author"; - $sql.= " LEFT JOIN ".MAIN_DB_PREFIX."societe as s on s.rowid = a.fk_soc"; - $sql.= " WHERE "; - if ($ref) $sql.= " a.id=".$ref; // No field ref, we use id - elseif ($ref_ext) $sql.= " a.ref_ext='".$this->db->escape($ref_ext)."'"; - else $sql.= " a.id=".$id; + $sql .= " a.id as ref,"; + $sql .= " a.ref_ext,"; + $sql .= " a.datep,"; + $sql .= " a.datep2,"; + $sql .= " a.durationp,"; // deprecated + $sql .= " a.datec,"; + $sql .= " a.tms as datem,"; + $sql .= " a.code, a.label, a.note,"; + $sql .= " a.fk_soc,"; + $sql .= " a.fk_project,"; + $sql .= " a.fk_user_author, a.fk_user_mod,"; + $sql .= " a.fk_user_action, a.fk_user_done,"; + $sql .= " a.fk_contact, a.percent as percentage,"; + $sql .= " a.fk_element as elementid, a.elementtype,"; + $sql .= " a.priority, a.fulldayevent, a.location, a.punctual, a.transparency,"; + $sql .= " c.id as type_id, c.code as type_code, c.libelle as type_label, c.color as type_color, c.picto as type_picto,"; + $sql .= " s.nom as socname,"; + $sql .= " u.firstname, u.lastname as lastname"; + $sql .= " FROM ".MAIN_DB_PREFIX."actioncomm as a "; + $sql .= " LEFT JOIN ".MAIN_DB_PREFIX."c_actioncomm as c ON a.fk_action=c.id "; + $sql .= " LEFT JOIN ".MAIN_DB_PREFIX."user as u on u.rowid = a.fk_user_author"; + $sql .= " LEFT JOIN ".MAIN_DB_PREFIX."societe as s on s.rowid = a.fk_soc"; + $sql .= " WHERE "; + if ($ref) $sql .= " a.id=".$ref; // No field ref, we use id + elseif ($ref_ext) $sql .= " a.ref_ext='".$this->db->escape($ref_ext)."'"; + else $sql .= " a.id=".$id; dol_syslog(get_class($this)."::fetch", LOG_DEBUG); - $resql=$this->db->query($sql); + $resql = $this->db->query($sql); if ($resql) { - $num=$this->db->num_rows($resql); + $num = $this->db->num_rows($resql); if ($num) { $obj = $this->db->fetch_object($resql); @@ -716,12 +721,12 @@ class ActionComm extends CommonObject $this->type_code = $obj->type_code; $this->type_color = $obj->type_color; $this->type_picto = $obj->type_picto; - $transcode=$langs->trans("Action".$obj->type_code); - $this->type = (($transcode!="Action".$obj->type_code) ? $transcode : $obj->type_label); - $transcode=$langs->trans("Action".$obj->type_code.'Short'); - $this->type_short = (($transcode!="Action".$obj->type_code.'Short') ? $transcode : ''); + $transcode = $langs->trans("Action".$obj->type_code); + $this->type = (($transcode != "Action".$obj->type_code) ? $transcode : $obj->type_label); + $transcode = $langs->trans("Action".$obj->type_code.'Short'); + $this->type_short = (($transcode != "Action".$obj->type_code.'Short') ? $transcode : ''); - $this->code = $obj->code; + $this->code = $obj->code; $this->label = $obj->label; $this->datep = $this->db->jdate($obj->datep); $this->datef = $this->db->jdate($obj->datep2); @@ -729,38 +734,38 @@ class ActionComm extends CommonObject $this->datec = $this->db->jdate($obj->datec); $this->datem = $this->db->jdate($obj->datem); - $this->note = $obj->note; - $this->note_private = $obj->note; - $this->percentage = $obj->percentage; + $this->note = $obj->note; + $this->note_private = $obj->note; + $this->percentage = $obj->percentage; - $this->authorid = $obj->fk_user_author; - $this->usermodid = $obj->fk_user_mod; + $this->authorid = $obj->fk_user_author; + $this->usermodid = $obj->fk_user_mod; if (!is_object($this->author)) $this->author = new stdClass(); // To avoid warning - $this->author->id = $obj->fk_user_author; // deprecated - $this->author->firstname = $obj->firstname; // deprecated - $this->author->lastname = $obj->lastname; // deprecated + $this->author->id = $obj->fk_user_author; // deprecated + $this->author->firstname = $obj->firstname; // deprecated + $this->author->lastname = $obj->lastname; // deprecated if (!is_object($this->usermod)) $this->usermod = new stdClass(); // To avoid warning - $this->usermod->id = $obj->fk_user_mod; // deprecated + $this->usermod->id = $obj->fk_user_mod; // deprecated - $this->userownerid = $obj->fk_user_action; - $this->userdoneid = $obj->fk_user_done; + $this->userownerid = $obj->fk_user_action; + $this->userdoneid = $obj->fk_user_done; $this->priority = $obj->priority; $this->fulldayevent = $obj->fulldayevent; $this->location = $obj->location; $this->transparency = $obj->transparency; - $this->punctual = $obj->punctual; // deprecated + $this->punctual = $obj->punctual; // deprecated - $this->socid = $obj->fk_soc; // To have fetch_thirdparty method working - $this->contactid = $obj->fk_contact; // To have fetch_contact method working - $this->fk_project = $obj->fk_project; // To have fetch_projet method working + $this->socid = $obj->fk_soc; // To have fetch_thirdparty method working + $this->contactid = $obj->fk_contact; // To have fetch_contact method working + $this->fk_project = $obj->fk_project; // To have fetch_projet method working //$this->societe->id = $obj->fk_soc; // deprecated //$this->contact->id = $obj->fk_contact; // deprecated - $this->fk_element = $obj->elementid; - $this->elementid = $obj->elementid; - $this->elementtype = $obj->elementtype; + $this->fk_element = $obj->elementid; + $this->elementid = $obj->elementid; + $this->elementtype = $obj->elementtype; $this->fetchResources(); } @@ -768,7 +773,7 @@ class ActionComm extends CommonObject } else { - $this->error=$this->db->lasterror(); + $this->error = $this->db->lasterror(); return -1; } @@ -782,18 +787,18 @@ class ActionComm extends CommonObject */ public function fetchResources() { - $sql ='SELECT fk_actioncomm, element_type, fk_element, answer_status, mandatory, transparency'; - $sql.=' FROM '.MAIN_DB_PREFIX.'actioncomm_resources'; - $sql.=' WHERE fk_actioncomm = '.$this->id; - $sql.=" AND element_type IN ('user', 'socpeople')"; - $resql=$this->db->query($sql); + $sql = 'SELECT fk_actioncomm, element_type, fk_element, answer_status, mandatory, transparency'; + $sql .= ' FROM '.MAIN_DB_PREFIX.'actioncomm_resources'; + $sql .= ' WHERE fk_actioncomm = '.$this->id; + $sql .= " AND element_type IN ('user', 'socpeople')"; + $resql = $this->db->query($sql); if ($resql) { - $this->userassigned=array(); - $this->socpeopleassigned=array(); + $this->userassigned = array(); + $this->socpeopleassigned = array(); // If owner is known, we must but id first into list - if ($this->userownerid > 0) $this->userassigned[$this->userownerid]=array('id'=>$this->userownerid); // Set first so will be first into list. + if ($this->userownerid > 0) $this->userassigned[$this->userownerid] = array('id'=>$this->userownerid); // Set first so will be first into list. while ($obj = $this->db->fetch_object($resql)) { @@ -801,11 +806,11 @@ class ActionComm extends CommonObject { switch ($obj->element_type) { case 'user': - $this->userassigned[$obj->fk_element]=array('id'=>$obj->fk_element, 'mandatory'=>$obj->mandatory, 'answer_status'=>$obj->answer_status, 'transparency'=>$obj->transparency); - if (empty($this->userownerid)) $this->userownerid=$obj->fk_element; // If not defined (should not happened, we fix this) + $this->userassigned[$obj->fk_element] = array('id'=>$obj->fk_element, 'mandatory'=>$obj->mandatory, 'answer_status'=>$obj->answer_status, 'transparency'=>$obj->transparency); + if (empty($this->userownerid)) $this->userownerid = $obj->fk_element; // If not defined (should not happened, we fix this) break; case 'socpeople': - $this->socpeopleassigned[$obj->fk_element]=array('id'=>$obj->fk_element, 'mandatory'=>$obj->mandatory, 'answer_status'=>$obj->answer_status, 'transparency'=>$obj->transparency); + $this->socpeopleassigned[$obj->fk_element] = array('id'=>$obj->fk_element, 'mandatory'=>$obj->mandatory, 'answer_status'=>$obj->answer_status, 'transparency'=>$obj->transparency); break; } } @@ -824,35 +829,55 @@ class ActionComm extends CommonObject /** * Initialize this->userassigned array with list of id of user assigned to event * - * @return int <0 if KO, >0 if OK + * @param bool $override Override $this->userownerid when empty. TODO This should be false by default. True is here to fix corrupted data. + * @return int <0 if KO, >0 if OK */ - public function fetch_userassigned() + public function fetch_userassigned($override = true) { // phpcs:enable $sql ="SELECT fk_actioncomm, element_type, fk_element, answer_status, mandatory, transparency"; - $sql.=" FROM ".MAIN_DB_PREFIX."actioncomm_resources"; - $sql.=" WHERE element_type = 'user' AND fk_actioncomm = ".$this->id; - $resql2=$this->db->query($sql); - if ($resql2) - { - $this->userassigned=array(); + $sql.=" FROM ".MAIN_DB_PREFIX."actioncomm_resources"; + $sql.=" WHERE element_type = 'user' AND fk_actioncomm = ".$this->id; - // If owner is known, we must but id first into list - if ($this->userownerid > 0) $this->userassigned[$this->userownerid]=array('id'=>$this->userownerid); // Set first so will be first into list. + $resql2=$this->db->query($sql); + if ($resql2) + { + $this->userassigned = array(); + + // If owner is known, we must but id first into list + if ($this->userownerid > 0) + { + // Set first so will be first into list. + $this->userassigned[$this->userownerid] = array('id'=>$this->userownerid); + } while ($obj = $this->db->fetch_object($resql2)) { - if ($obj->fk_element > 0) $this->userassigned[$obj->fk_element]=array('id'=>$obj->fk_element, 'mandatory'=>$obj->mandatory, 'answer_status'=>$obj->answer_status, 'transparency'=>$obj->transparency); - if (empty($this->userownerid)) $this->userownerid=$obj->fk_element; // If not defined (should not happened, we fix this) + if ($obj->fk_element > 0) + { + $this->userassigned[$obj->fk_element] = array('id'=>$obj->fk_element, + 'mandatory'=>$obj->mandatory, + 'answer_status'=>$obj->answer_status, + 'transparency'=>$obj->transparency); + } + + if ($override === true) + { + // If not defined (should not happened, we fix this) + if (empty($this->userownerid)) + { + $this->userownerid = $obj->fk_element; + } + } } - return 1; - } - else - { - dol_print_error($this->db); - return -1; - } + return 1; + } + else + { + dol_print_error($this->db); + return -1; + } } /** @@ -863,7 +888,7 @@ class ActionComm extends CommonObject */ public function delete($notrigger = 0) { - global $user,$langs,$conf; + global $user; $error=0; @@ -903,15 +928,15 @@ class ActionComm extends CommonObject if (!$error) { - if (! $notrigger) + if (!$notrigger) { // Call trigger - $result=$this->call_trigger('ACTION_DELETE', $user); + $result = $this->call_trigger('ACTION_DELETE', $user); if ($result < 0) { $error++; } // End call triggers } - if (! $error) + if (!$error) { $this->db->commit(); return 1; @@ -925,7 +950,7 @@ class ActionComm extends CommonObject else { $this->db->rollback(); - $this->error=$this->db->lasterror(); + $this->error = $this->db->lasterror(); return -1; } } @@ -940,70 +965,70 @@ class ActionComm extends CommonObject */ public function update($user, $notrigger = 0) { - global $langs,$conf,$hookmanager; + global $langs, $conf, $hookmanager; - $error=0; + $error = 0; // Clean parameters - $this->label=trim($this->label); - $this->note=trim($this->note); + $this->label = trim($this->label); + $this->note = trim($this->note); if (empty($this->percentage)) $this->percentage = 0; - if (empty($this->priority) || ! is_numeric($this->priority)) $this->priority = 0; + if (empty($this->priority) || !is_numeric($this->priority)) $this->priority = 0; if (empty($this->transparency)) $this->transparency = 0; if (empty($this->fulldayevent)) $this->fulldayevent = 0; if ($this->percentage > 100) $this->percentage = 100; //if ($this->percentage == 100 && ! $this->dateend) $this->dateend = $this->date; - if ($this->datep && $this->datef) $this->durationp=($this->datef - $this->datep); // deprecated + if ($this->datep && $this->datef) $this->durationp = ($this->datef - $this->datep); // deprecated //if ($this->date && $this->dateend) $this->durationa=($this->dateend - $this->date); - if ($this->datep && $this->datef && $this->datep > $this->datef) $this->datef=$this->datep; + if ($this->datep && $this->datef && $this->datep > $this->datef) $this->datef = $this->datep; //if ($this->date && $this->dateend && $this->date > $this->dateend) $this->dateend=$this->date; if ($this->fk_project < 0) $this->fk_project = 0; // Check parameters if ($this->percentage == 0 && $this->userdoneid > 0) { - $this->error="ErrorCantSaveADoneUserWithZeroPercentage"; + $this->error = "ErrorCantSaveADoneUserWithZeroPercentage"; return -1; } - $socid=(($this->socid > 0)?$this->socid:0); - $contactid=(($this->contactid > 0)?$this->contactid:0); - $userownerid=($this->userownerid?$this->userownerid:0); - $userdoneid=($this->userdoneid?$this->userdoneid:0); + $socid = (($this->socid > 0) ? $this->socid : 0); + $contactid = (($this->contactid > 0) ? $this->contactid : 0); + $userownerid = ($this->userownerid ? $this->userownerid : 0); + $userdoneid = ($this->userdoneid ? $this->userdoneid : 0); $this->db->begin(); $sql = "UPDATE ".MAIN_DB_PREFIX."actioncomm "; - $sql.= " SET percent = '".$this->db->escape($this->percentage)."'"; - if ($this->type_id > 0) $sql.= ", fk_action = '".$this->db->escape($this->type_id)."'"; - $sql.= ", label = ".($this->label ? "'".$this->db->escape($this->label)."'":"null"); - $sql.= ", datep = ".(strval($this->datep)!='' ? "'".$this->db->idate($this->datep)."'" : 'null'); - $sql.= ", datep2 = ".(strval($this->datef)!='' ? "'".$this->db->idate($this->datef)."'" : 'null'); - $sql.= ", durationp = ".(isset($this->durationp) && $this->durationp >= 0 && $this->durationp != ''?"'".$this->db->escape($this->durationp)."'":"null"); // deprecated - $sql.= ", note = '".$this->db->escape($this->note_private?$this->note_private:$this->note)."'"; - $sql.= ", fk_project =". ($this->fk_project > 0 ? $this->fk_project:"null"); - $sql.= ", fk_soc =". ($socid > 0 ? $socid:"null"); - $sql.= ", fk_contact =". ($contactid > 0 ? $contactid:"null"); - $sql.= ", priority = '".$this->db->escape($this->priority)."'"; - $sql.= ", fulldayevent = '".$this->db->escape($this->fulldayevent)."'"; - $sql.= ", location = ".($this->location ? "'".$this->db->escape($this->location)."'":"null"); - $sql.= ", transparency = '".$this->db->escape($this->transparency)."'"; - $sql.= ", fk_user_mod = ".$user->id; - $sql.= ", fk_user_action=".($userownerid > 0 ? "'".$userownerid."'":"null"); - $sql.= ", fk_user_done=".($userdoneid > 0 ? "'".$userdoneid."'":"null"); - if (! empty($this->fk_element)) $sql.= ", fk_element=".($this->fk_element?$this->db->escape($this->fk_element):"null"); - if (! empty($this->elementtype)) $sql.= ", elementtype=".($this->elementtype?"'".$this->db->escape($this->elementtype)."'":"null"); - $sql.= " WHERE id=".$this->id; + $sql .= " SET percent = '".$this->db->escape($this->percentage)."'"; + if ($this->type_id > 0) $sql .= ", fk_action = '".$this->db->escape($this->type_id)."'"; + $sql .= ", label = ".($this->label ? "'".$this->db->escape($this->label)."'" : "null"); + $sql .= ", datep = ".(strval($this->datep) != '' ? "'".$this->db->idate($this->datep)."'" : 'null'); + $sql .= ", datep2 = ".(strval($this->datef) != '' ? "'".$this->db->idate($this->datef)."'" : 'null'); + $sql .= ", durationp = ".(isset($this->durationp) && $this->durationp >= 0 && $this->durationp != '' ? "'".$this->db->escape($this->durationp)."'" : "null"); // deprecated + $sql .= ", note = '".$this->db->escape($this->note_private ? $this->note_private : $this->note)."'"; + $sql .= ", fk_project =".($this->fk_project > 0 ? $this->fk_project : "null"); + $sql .= ", fk_soc =".($socid > 0 ? $socid : "null"); + $sql .= ", fk_contact =".($contactid > 0 ? $contactid : "null"); + $sql .= ", priority = '".$this->db->escape($this->priority)."'"; + $sql .= ", fulldayevent = '".$this->db->escape($this->fulldayevent)."'"; + $sql .= ", location = ".($this->location ? "'".$this->db->escape($this->location)."'" : "null"); + $sql .= ", transparency = '".$this->db->escape($this->transparency)."'"; + $sql .= ", fk_user_mod = ".$user->id; + $sql .= ", fk_user_action=".($userownerid > 0 ? "'".$userownerid."'" : "null"); + $sql .= ", fk_user_done=".($userdoneid > 0 ? "'".$userdoneid."'" : "null"); + if (!empty($this->fk_element)) $sql .= ", fk_element=".($this->fk_element ? $this->db->escape($this->fk_element) : "null"); + if (!empty($this->elementtype)) $sql .= ", elementtype=".($this->elementtype ? "'".$this->db->escape($this->elementtype)."'" : "null"); + $sql .= " WHERE id=".$this->id; dol_syslog(get_class($this)."::update", LOG_DEBUG); if ($this->db->query($sql)) { - $action='update'; + $action = 'update'; // Actions on extra fields if (empty($conf->global->MAIN_EXTRAFIELDS_DISABLED)) // For avoid conflicts if trigger used { - $result=$this->insertExtraFields(); + $result = $this->insertExtraFields(); if ($result < 0) { $error++; @@ -1011,25 +1036,25 @@ class ActionComm extends CommonObject } // Now insert assignedusers - if (! $error) + if (!$error) { - $sql ="DELETE FROM ".MAIN_DB_PREFIX."actioncomm_resources where fk_actioncomm = ".$this->id." AND element_type = 'user'"; + $sql = "DELETE FROM ".MAIN_DB_PREFIX."actioncomm_resources where fk_actioncomm = ".$this->id." AND element_type = 'user'"; $resql = $this->db->query($sql); - foreach($this->userassigned as $key => $val) + foreach ($this->userassigned as $key => $val) { - if (! is_array($val)) // For backward compatibility when val=id + if (!is_array($val)) // For backward compatibility when val=id { - $val=array('id'=>$val); + $val = array('id'=>$val); } - $sql ="INSERT INTO ".MAIN_DB_PREFIX."actioncomm_resources(fk_actioncomm, element_type, fk_element, mandatory, transparency, answer_status)"; - $sql.=" VALUES(".$this->id.", 'user', ".$val['id'].", ".(empty($val['mandatory'])?'0':$val['mandatory']).", ".(empty($val['transparency'])?'0':$val['transparency']).", ".(empty($val['answer_status'])?'0':$val['answer_status']).")"; + $sql = "INSERT INTO ".MAIN_DB_PREFIX."actioncomm_resources(fk_actioncomm, element_type, fk_element, mandatory, transparency, answer_status)"; + $sql .= " VALUES(".$this->id.", 'user', ".$val['id'].", ".(empty($val['mandatory']) ? '0' : $val['mandatory']).", ".(empty($val['transparency']) ? '0' : $val['transparency']).", ".(empty($val['answer_status']) ? '0' : $val['answer_status']).")"; $resql = $this->db->query($sql); - if (! $resql) + if (!$resql) { $error++; - $this->errors[]=$this->db->lasterror(); + $this->errors[] = $this->db->lasterror(); } //var_dump($sql);exit; } @@ -1037,35 +1062,35 @@ class ActionComm extends CommonObject if (!$error) { - $sql ="DELETE FROM ".MAIN_DB_PREFIX."actioncomm_resources where fk_actioncomm = ".$this->id." AND element_type = 'socpeople'"; + $sql = "DELETE FROM ".MAIN_DB_PREFIX."actioncomm_resources where fk_actioncomm = ".$this->id." AND element_type = 'socpeople'"; $resql = $this->db->query($sql); if (!empty($this->socpeopleassigned)) { foreach (array_keys($this->socpeopleassigned) as $id) { - $sql ="INSERT INTO ".MAIN_DB_PREFIX."actioncomm_resources(fk_actioncomm, element_type, fk_element, mandatory, transparency, answer_status)"; - $sql.=" VALUES(".$this->id.", 'socpeople', ".$id.", 0, 0, 0)"; + $sql = "INSERT INTO ".MAIN_DB_PREFIX."actioncomm_resources(fk_actioncomm, element_type, fk_element, mandatory, transparency, answer_status)"; + $sql .= " VALUES(".$this->id.", 'socpeople', ".$id.", 0, 0, 0)"; $resql = $this->db->query($sql); - if (! $resql) + if (!$resql) { $error++; - $this->errors[]=$this->db->lasterror(); + $this->errors[] = $this->db->lasterror(); } } } } - if (! $error && ! $notrigger) + if (!$error && !$notrigger) { // Call trigger - $result=$this->call_trigger('ACTION_MODIFY', $user); + $result = $this->call_trigger('ACTION_MODIFY', $user); if ($result < 0) { $error++; } // End call triggers } - if (! $error) + if (!$error) { $this->db->commit(); return 1; @@ -1080,7 +1105,7 @@ class ActionComm extends CommonObject else { $this->db->rollback(); - $this->error=$this->db->lasterror(); + $this->error = $this->db->lasterror(); return -1; } } @@ -1103,31 +1128,31 @@ class ActionComm extends CommonObject { global $conf, $langs; - $resarray=array(); + $resarray = array(); dol_syslog(get_class()."::getActions", LOG_DEBUG); $sql = "SELECT a.id"; - $sql.= " FROM ".MAIN_DB_PREFIX."actioncomm as a"; - $sql.= " WHERE a.entity IN (".getEntity('agenda').")"; - if (! empty($socid)) $sql.= " AND a.fk_soc = ".$socid; - if (! empty($elementtype)) + $sql .= " FROM ".MAIN_DB_PREFIX."actioncomm as a"; + $sql .= " WHERE a.entity IN (".getEntity('agenda').")"; + if (!empty($socid)) $sql .= " AND a.fk_soc = ".$socid; + if (!empty($elementtype)) { - if ($elementtype == 'project') $sql.= ' AND a.fk_project = '.$fk_element; - else $sql.= " AND a.fk_element = ".(int) $fk_element." AND a.elementtype = '".$elementtype."'"; + if ($elementtype == 'project') $sql .= ' AND a.fk_project = '.$fk_element; + else $sql .= " AND a.fk_element = ".(int) $fk_element." AND a.elementtype = '".$elementtype."'"; } - if (! empty($filter)) $sql.= $filter; - if ($sortorder && $sortfield) $sql.=$db->order($sortfield, $sortorder); - $sql.=$db->plimit($limit, 0); + if (!empty($filter)) $sql .= $filter; + if ($sortorder && $sortfield) $sql .= $db->order($sortfield, $sortorder); + $sql .= $db->plimit($limit, 0); - $resql=$db->query($sql); + $resql = $db->query($sql); if ($resql) { $num = $db->num_rows($resql); if ($num) { - for($i=0;$i<$num;$i++) + for ($i = 0; $i < $num; $i++) { $obj = $db->fetch_object($resql); $actioncommstatic = new ActionComm($db); @@ -1217,16 +1242,16 @@ class ActionComm extends CommonObject public function info($id) { $sql = 'SELECT '; - $sql.= ' a.id,'; - $sql.= ' datec,'; - $sql.= ' tms as datem,'; - $sql.= ' fk_user_author,'; - $sql.= ' fk_user_mod'; - $sql.= ' FROM '.MAIN_DB_PREFIX.'actioncomm as a'; - $sql.= ' WHERE a.id = '.$id; + $sql .= ' a.id,'; + $sql .= ' datec,'; + $sql .= ' tms as datem,'; + $sql .= ' fk_user_author,'; + $sql .= ' fk_user_mod'; + $sql .= ' FROM '.MAIN_DB_PREFIX.'actioncomm as a'; + $sql .= ' WHERE a.id = '.$id; dol_syslog(get_class($this)."::info", LOG_DEBUG); - $result=$this->db->query($sql); + $result = $this->db->query($sql); if ($result) { if ($this->db->num_rows($result)) @@ -1237,7 +1262,7 @@ class ActionComm extends CommonObject { $cuser = new User($this->db); $cuser->fetch($obj->fk_user_author); - $this->user_creation = $cuser; + $this->user_creation = $cuser; } if ($obj->fk_user_mod) { @@ -1246,8 +1271,8 @@ class ActionComm extends CommonObject $this->user_modification = $muser; } - $this->date_creation = $this->db->jdate($obj->datec); - if (! empty($obj->fk_user_mod)) $this->date_modification = $this->db->jdate($obj->datem); + $this->date_creation = $this->db->jdate($obj->datec); + if (!empty($obj->fk_user_mod)) $this->date_modification = $this->db->jdate($obj->datem); } $this->db->free($result); } @@ -1287,57 +1312,57 @@ class ActionComm extends CommonObject if ($mode == 0) { - if ($percent==-1 && ! $hidenastatus) return $langs->trans('StatusNotApplicable'); - elseif ($percent==0) return $langs->trans('StatusActionToDo').' (0%)'; + if ($percent == -1 && !$hidenastatus) return $langs->trans('StatusNotApplicable'); + elseif ($percent == 0) return $langs->trans('StatusActionToDo').' (0%)'; elseif ($percent > 0 && $percent < 100) return $langs->trans('StatusActionInProcess').' ('.$percent.'%)'; elseif ($percent >= 100) return $langs->trans('StatusActionDone').' (100%)'; } elseif ($mode == 1) { - if ($percent==-1 && ! $hidenastatus) return $langs->trans('StatusNotApplicable'); - elseif ($percent==0) return $langs->trans('StatusActionToDo'); + if ($percent == -1 && !$hidenastatus) return $langs->trans('StatusNotApplicable'); + elseif ($percent == 0) return $langs->trans('StatusActionToDo'); elseif ($percent > 0 && $percent < 100) return $percent.'%'; elseif ($percent >= 100) return $langs->trans('StatusActionDone'); } elseif ($mode == 2) { - if ($percent==-1 && ! $hidenastatus) return img_picto($langs->trans('StatusNotApplicable'), 'statut9').' '.$langs->trans('StatusNotApplicable'); - elseif ($percent==0) return img_picto($langs->trans('StatusActionToDo'), 'statut1').' '.$langs->trans('StatusActionToDo'); - elseif ($percent > 0 && $percent < 100) return img_picto($langs->trans('StatusActionInProcess'), 'statut3').' '. $percent.'%'; + if ($percent == -1 && !$hidenastatus) return img_picto($langs->trans('StatusNotApplicable'), 'statut9').' '.$langs->trans('StatusNotApplicable'); + elseif ($percent == 0) return img_picto($langs->trans('StatusActionToDo'), 'statut1').' '.$langs->trans('StatusActionToDo'); + elseif ($percent > 0 && $percent < 100) return img_picto($langs->trans('StatusActionInProcess'), 'statut3').' '.$percent.'%'; elseif ($percent >= 100) return img_picto($langs->trans('StatusActionDone'), 'statut6').' '.$langs->trans('StatusActionDone'); } elseif ($mode == 3) { - if ($percent==-1 && ! $hidenastatus) return img_picto($langs->trans("Status").': '.$langs->trans('StatusNotApplicable'), 'statut9'); - elseif ($percent==0) return img_picto($langs->trans("Status").': '.$langs->trans('StatusActionToDo').' (0%)', 'statut1'); + if ($percent == -1 && !$hidenastatus) return img_picto($langs->trans("Status").': '.$langs->trans('StatusNotApplicable'), 'statut9'); + elseif ($percent == 0) return img_picto($langs->trans("Status").': '.$langs->trans('StatusActionToDo').' (0%)', 'statut1'); elseif ($percent > 0 && $percent < 100) return img_picto($langs->trans("Status").': '.$langs->trans('StatusActionInProcess').' ('.$percent.'%)', 'statut3'); elseif ($percent >= 100) return img_picto($langs->trans("Status").': '.$langs->trans('StatusActionDone').' (100%)', 'statut6'); } elseif ($mode == 4) { - if ($percent==-1 && ! $hidenastatus) return img_picto($langs->trans('StatusNotApplicable'), 'statut9').' '.$langs->trans('StatusNotApplicable'); - elseif ($percent==0) return img_picto($langs->trans('StatusActionToDo'), 'statut1').' '.$langs->trans('StatusActionToDo').' (0%)'; + if ($percent == -1 && !$hidenastatus) return img_picto($langs->trans('StatusNotApplicable'), 'statut9').' '.$langs->trans('StatusNotApplicable'); + elseif ($percent == 0) return img_picto($langs->trans('StatusActionToDo'), 'statut1').' '.$langs->trans('StatusActionToDo').' (0%)'; elseif ($percent > 0 && $percent < 100) return img_picto($langs->trans('StatusActionInProcess'), 'statut3').' '.$langs->trans('StatusActionInProcess').' ('.$percent.'%)'; elseif ($percent >= 100) return img_picto($langs->trans('StatusActionDone'), 'statut6').' '.$langs->trans('StatusActionDone').' (100%)'; } elseif ($mode == 5) { - if ($percent==-1 && ! $hidenastatus) return img_picto($langs->trans('StatusNotApplicable'), 'statut9'); - elseif ($percent==0) return '0% '.img_picto($langs->trans('StatusActionToDo'), 'statut1'); + if ($percent == -1 && !$hidenastatus) return img_picto($langs->trans('StatusNotApplicable'), 'statut9'); + elseif ($percent == 0) return '0% '.img_picto($langs->trans('StatusActionToDo'), 'statut1'); elseif ($percent > 0 && $percent < 100) return $percent.'% '.img_picto($langs->trans('StatusActionInProcess').' - '.$percent.'%', 'statut3'); elseif ($percent >= 100) return $langs->trans('StatusActionDone').' '.img_picto($langs->trans('StatusActionDone'), 'statut6'); } elseif ($mode == 6) { - if ($percent==-1 && ! $hidenastatus) return $langs->trans('StatusNotApplicable').' '.img_picto($langs->trans('StatusNotApplicable'), 'statut9'); - elseif ($percent==0) return $langs->trans('StatusActionToDo').' (0%) '.img_picto($langs->trans('StatusActionToDo'), 'statut1'); + if ($percent == -1 && !$hidenastatus) return $langs->trans('StatusNotApplicable').' '.img_picto($langs->trans('StatusNotApplicable'), 'statut9'); + elseif ($percent == 0) return $langs->trans('StatusActionToDo').' (0%) '.img_picto($langs->trans('StatusActionToDo'), 'statut1'); elseif ($percent > 0 && $percent < 100) return $langs->trans('StatusActionInProcess').' ('.$percent.'%) '.img_picto($langs->trans('StatusActionInProcess').' - '.$percent.'%', 'statut3'); elseif ($percent >= 100) return $langs->trans('StatusActionDone').' (100%) '.img_picto($langs->trans('StatusActionDone'), 'statut6'); } elseif ($mode == 7) { - if ($percent==-1 && ! $hidenastatus) return img_picto($langs->trans('StatusNotApplicable'), 'statut9'); - elseif ($percent==0) return '0% '.img_picto($langs->trans('StatusActionToDo'), 'statut1'); + if ($percent == -1 && !$hidenastatus) return img_picto($langs->trans('StatusNotApplicable'), 'statut9'); + elseif ($percent == 0) return '0% '.img_picto($langs->trans('StatusActionToDo'), 'statut1'); elseif ($percent > 0 && $percent < 100) return $percent.'% '.img_picto($langs->trans('StatusActionInProcess').' - '.$percent.'%', 'statut3'); elseif ($percent >= 100) return img_picto($langs->trans('StatusActionDone'), 'statut6'); } @@ -1362,7 +1387,7 @@ class ActionComm extends CommonObject { global $conf, $langs, $user, $hookmanager, $action; - if (! empty($conf->dol_no_mouse_hover)) $notooltip=1; // Force disable tooltips + if (!empty($conf->dol_no_mouse_hover)) $notooltip = 1; // Force disable tooltips if ((!$user->rights->agenda->allactions->read && $this->authorid != $user->id) || (!$user->rights->agenda->myactions->read && $this->authorid == $user->id)) { @@ -1370,45 +1395,45 @@ class ActionComm extends CommonObject } $label = $this->label; - if (empty($label)) $label=$this->libelle; // For backward compatibility + if (empty($label)) $label = $this->libelle; // For backward compatibility - $result=''; + $result = ''; // Set label of type $labeltype = ''; if ($this->type_code) { - $labeltype = ($langs->transnoentities("Action".$this->type_code) != "Action".$this->type_code)?$langs->transnoentities("Action".$this->type_code):$this->type_label; + $labeltype = ($langs->transnoentities("Action".$this->type_code) != "Action".$this->type_code) ? $langs->transnoentities("Action".$this->type_code) : $this->type_label; } if (empty($conf->global->AGENDA_USE_EVENT_TYPE)) { if ($this->type_code != 'AC_OTH_AUTO') $labeltype = $langs->trans('ActionAC_MANUAL'); } - $tooltip = '' . $langs->trans('ShowAction') . ''; - if (! empty($this->ref)) - $tooltip .= '
' . $langs->trans('Ref') . ': ' . $this->ref; - if (! empty($label)) - $tooltip .= '
' . $langs->trans('Title') . ': ' . $label; - if (! empty($labeltype)) - $tooltip .= '
' . $langs->trans('Type') . ': ' . $labeltype; - if (! empty($this->location)) - $tooltip .= '
' . $langs->trans('Location') . ': ' . $this->location; - if (! empty($this->note)) - $tooltip .= '
' . $langs->trans('Note') . ': ' . (dol_textishtml($this->note) ? str_replace(array("\r","\n"), "", $this->note) : str_replace(array("\r","\n"), '
', $this->note)); - $linkclose=''; - if (! empty($conf->global->AGENDA_USE_EVENT_TYPE) && $this->type_color) + $tooltip = ''.$langs->trans('ShowAction').''; + if (!empty($this->ref)) + $tooltip .= '
'.$langs->trans('Ref').': '.$this->ref; + if (!empty($label)) + $tooltip .= '
'.$langs->trans('Title').': '.$label; + if (!empty($labeltype)) + $tooltip .= '
'.$langs->trans('Type').': '.$labeltype; + if (!empty($this->location)) + $tooltip .= '
'.$langs->trans('Location').': '.$this->location; + if (!empty($this->note)) + $tooltip .= '
'.$langs->trans('Note').': '.(dol_textishtml($this->note) ? str_replace(array("\r", "\n"), "", $this->note) : str_replace(array("\r", "\n"), '
', $this->note)); + $linkclose = ''; + if (!empty($conf->global->AGENDA_USE_EVENT_TYPE) && $this->type_color) $linkclose = ' style="background-color:#'.$this->type_color.'"'; if (empty($notooltip)) { - if (! empty($conf->global->MAIN_OPTIMIZEFORTEXTBROWSER)) + if (!empty($conf->global->MAIN_OPTIMIZEFORTEXTBROWSER)) { - $label=$langs->trans("ShowAction"); - $linkclose.=' alt="'.dol_escape_htmltag($tooltip, 1).'"'; + $label = $langs->trans("ShowAction"); + $linkclose .= ' alt="'.dol_escape_htmltag($tooltip, 1).'"'; } - $linkclose.=' title="'.dol_escape_htmltag($tooltip, 1).'"'; - $linkclose.=' class="'.$classname.' classfortooltip"'; + $linkclose .= ' title="'.dol_escape_htmltag($tooltip, 1).'"'; + $linkclose .= ' class="'.$classname.' classfortooltip"'; /* $hookmanager->initHooks(array('actiondao')); @@ -1417,24 +1442,24 @@ class ActionComm extends CommonObject $linkclose = ($hookmanager->resPrint ? $hookmanager->resPrint : $linkclose); */ } - else $linkclose.=' class="'.$classname.'"'; + else $linkclose .= ' class="'.$classname.'"'; - $url=''; - if ($option=='birthday') + $url = ''; + if ($option == 'birthday') $url = DOL_URL_ROOT.'/contact/perso.php?id='.$this->id; else $url = DOL_URL_ROOT.'/comm/action/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'; + $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'; } $linkstart = ''; - $linkend=''; + $linkstart .= $linkclose.'>'; + $linkend = ''; if ($option == 'nolink') { $linkstart = ''; @@ -1443,38 +1468,38 @@ class ActionComm extends CommonObject if ($withpicto == 2) { - $libelle=$label; - if (! empty($conf->global->AGENDA_USE_EVENT_TYPE)) $libelle=$labeltype; - $libelleshort=''; + $libelle = $label; + if (!empty($conf->global->AGENDA_USE_EVENT_TYPE)) $libelle = $labeltype; + $libelleshort = ''; } else { - $libelle=(empty($this->libelle)?$label:$this->libelle.(($label && $label != $this->libelle)?' '.$label:'')); - if (! empty($conf->global->AGENDA_USE_EVENT_TYPE) && empty($libelle)) $libelle=$labeltype; - if ($maxlength < 0) $libelleshort=$this->ref; - else $libelleshort=dol_trunc($libelle, $maxlength); + $libelle = (empty($this->libelle) ? $label : $this->libelle.(($label && $label != $this->libelle) ? ' '.$label : '')); + if (!empty($conf->global->AGENDA_USE_EVENT_TYPE) && empty($libelle)) $libelle = $labeltype; + if ($maxlength < 0) $libelleshort = $this->ref; + else $libelleshort = dol_trunc($libelle, $maxlength); } if ($withpicto) { - if (! empty($conf->global->AGENDA_USE_EVENT_TYPE)) // Add code into () + if (!empty($conf->global->AGENDA_USE_EVENT_TYPE)) // Add code into () { if ($labeltype) { - $libelle.=(preg_match('/'.preg_quote($labeltype, '/').'/', $libelle)?'':' ('.$langs->transnoentities("Action".$this->type_code).')'); + $libelle .= (preg_match('/'.preg_quote($labeltype, '/').'/', $libelle) ? '' : ' ('.$langs->transnoentities("Action".$this->type_code).')'); } } } - $result.=$linkstart; - if ($withpicto) $result.=img_object(($notooltip?'':$langs->trans("ShowAction").': '.$libelle), ($overwritepicto?$overwritepicto:'action'), ($notooltip?'class="'.(($withpicto != 2) ? 'paddingright ' : '').'valigntextbottom"':'class="'.(($withpicto != 2) ? 'paddingright ' : '').'classfortooltip valigntextbottom"'), 0, 0, $notooltip?0:1); - $result.=$libelleshort; - $result.=$linkend; + $result .= $linkstart; + if ($withpicto) $result .= img_object(($notooltip ? '' : $langs->trans("ShowAction").': '.$libelle), ($overwritepicto ? $overwritepicto : 'action'), ($notooltip ? 'class="'.(($withpicto != 2) ? 'paddingright ' : '').'valigntextbottom"' : 'class="'.(($withpicto != 2) ? 'paddingright ' : '').'classfortooltip valigntextbottom"'), 0, 0, $notooltip ? 0 : 1); + $result .= $libelleshort; + $result .= $linkend; global $action; $hookmanager->initHooks(array('actiondao')); - $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 + $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; @@ -1498,11 +1523,11 @@ class ActionComm extends CommonObject global $hookmanager; // phpcs:enable - global $conf,$langs,$dolibarr_main_url_root,$mysoc; + global $conf, $langs, $dolibarr_main_url_root, $mysoc; - require_once DOL_DOCUMENT_ROOT ."/core/lib/xcal.lib.php"; - require_once DOL_DOCUMENT_ROOT ."/core/lib/date.lib.php"; - require_once DOL_DOCUMENT_ROOT ."/core/lib/files.lib.php"; + require_once DOL_DOCUMENT_ROOT."/core/lib/xcal.lib.php"; + require_once DOL_DOCUMENT_ROOT."/core/lib/date.lib.php"; + require_once DOL_DOCUMENT_ROOT."/core/lib/files.lib.php"; dol_syslog(get_class($this)."::build_exportfile Build export file format=".$format.", type=".$type.", cachedelay=".$cachedelay.", filename=".$filename.", filters size=".count($filters), LOG_DEBUG); @@ -1510,21 +1535,21 @@ class ActionComm extends CommonObject if (empty($format)) return -1; // Clean parameters - if (! $filename) + if (!$filename) { - $extension='vcs'; - if ($format == 'ical') $extension='ics'; - $filename=$format.'.'.$extension; + $extension = 'vcs'; + if ($format == 'ical') $extension = 'ics'; + $filename = $format.'.'.$extension; } // Create dir and define output file (definitive and temporary) - $result=dol_mkdir($conf->agenda->dir_temp); - $outputfile=$conf->agenda->dir_temp.'/'.$filename; + $result = dol_mkdir($conf->agenda->dir_temp); + $outputfile = $conf->agenda->dir_temp.'/'.$filename; - $result=0; + $result = 0; - $buildfile=true; - $login='';$logina='';$logind='';$logint=''; + $buildfile = true; + $login = ''; $logina = ''; $logind = ''; $logint = ''; $now = dol_now(); @@ -1676,7 +1701,7 @@ class ActionComm extends CommonObject // TODO: find a way to call "$this->fetch_userassigned();" without override "$this" properties $this->id = $obj->id; - $this->fetch_userassigned(); + $this->fetch_userassigned(false); $assignedUserArray = array(); @@ -1749,7 +1774,7 @@ class ActionComm extends CommonObject dol_syslog(get_class($this)."::build_exportfile build_xxxfile function fails to for format=".$format." outputfiletmp=".$outputfile, LOG_ERR); dol_delete_file($outputfiletmp, 0, 1); $langs->load("errors"); - $this->error=$langs->trans("ErrorFailToCreateFile", $outputfile); + $this->error = $langs->trans("ErrorFailToCreateFile", $outputfile); } } @@ -1767,32 +1792,32 @@ class ActionComm extends CommonObject { global $user; - $now=dol_now(); + $now = dol_now(); // Initialise parametres - $this->id=0; - $this->specimen=1; + $this->id = 0; + $this->specimen = 1; - $this->type_code='AC_OTH'; - $this->code='AC_SPECIMEN_CODE'; - $this->label='Label of event Specimen'; - $this->datec=$now; - $this->datem=$now; - $this->datep=$now; - $this->datef=$now; - $this->author=$user; - $this->usermod=$user; - $this->usertodo=$user; - $this->fulldayevent=0; - $this->punctual=0; - $this->percentage=0; - $this->location='Location'; - $this->transparency=1; // 1 means opaque - $this->priority=1; + $this->type_code = 'AC_OTH'; + $this->code = 'AC_SPECIMEN_CODE'; + $this->label = 'Label of event Specimen'; + $this->datec = $now; + $this->datem = $now; + $this->datep = $now; + $this->datef = $now; + $this->author = $user; + $this->usermod = $user; + $this->usertodo = $user; + $this->fulldayevent = 0; + $this->punctual = 0; + $this->percentage = 0; + $this->location = 'Location'; + $this->transparency = 1; // 1 means opaque + $this->priority = 1; $this->note = 'Note'; - $this->userownerid=$user->id; - $this->userassigned[$user->id]=array('id'=>$user->id, 'transparency'=> 1); + $this->userownerid = $user->id; + $this->userassigned[$user->id] = array('id'=>$user->id, 'transparency'=> 1); return 1; } @@ -1840,7 +1865,7 @@ class ActionComm extends CommonObject $error = 0; $this->output = ''; - $this->error=''; + $this->error = ''; if (empty($conf->agenda->enabled)) // Should not happen. If module disabled, cron job should not be visible. { diff --git a/htdocs/comm/action/index.php b/htdocs/comm/action/index.php index 031918b194b..47feb0e75ae 100644 --- a/htdocs/comm/action/index.php +++ b/htdocs/comm/action/index.php @@ -97,7 +97,7 @@ if (GETPOST('search_actioncode', 'array')) } else { - $actioncode=GETPOST("search_actioncode", "alpha", 3)?GETPOST("search_actioncode", "alpha", 3):(GETPOST("search_actioncode")=='0'?'0':(empty($conf->global->AGENDA_DEFAULT_FILTER_TYPE)?'':$conf->global->AGENDA_DEFAULT_FILTER_TYPE)); + $actioncode=GETPOST("search_actioncode", "alpha", 3)?GETPOST("search_actioncode", "alpha", 3):(GETPOST("search_actioncode")=='0'?'0':(empty($conf->global->AGENDA_DEFAULT_FILTER_TYPE)?'':$conf->global->AGENDA_DEFAULT_FILTER_TYPE)); } if ($actioncode == '' && empty($actioncodearray)) $actioncode=(empty($conf->global->AGENDA_DEFAULT_FILTER_TYPE)?'':$conf->global->AGENDA_DEFAULT_FILTER_TYPE); @@ -133,13 +133,13 @@ $hookmanager->initHooks(array('agenda')); if (GETPOST("viewlist", 'alpha') || $action == 'show_list') { - $param=''; + $param = ''; if (is_array($_POST)) { - foreach($_POST as $key => $val) + foreach ($_POST as $key => $val) { - if ($key=='token') continue; - $param.='&'.$key.'='.urlencode($val); + if ($key == 'token') continue; + $param .= '&'.$key.'='.urlencode($val); } } //print $param; @@ -149,13 +149,13 @@ if (GETPOST("viewlist", 'alpha') || $action == 'show_list') if (GETPOST("viewperuser", 'alpha') || $action == 'show_peruser') { - $param=''; + $param = ''; if (is_array($_POST)) { - foreach($_POST as $key => $val) + foreach ($_POST as $key => $val) { - if ($key=='token') continue; - $param.='&'.$key.'='.urlencode($val); + if ($key == 'token') continue; + $param .= '&'.$key.'='.urlencode($val); } } //print $param; @@ -163,11 +163,11 @@ if (GETPOST("viewperuser", 'alpha') || $action == 'show_peruser') exit; } -if ($action =='delete_action') +if ($action == 'delete_action') { $event = new ActionComm($db); $event->fetch($actionid); - $result=$event->delete(); + $result = $event->delete(); } @@ -195,62 +195,62 @@ $parameters = array( $reshook = $hookmanager->executeHooks('beforeAgenda', $parameters, $object, $action); // Note that $action and $object may have been modified by some hooks if ($reshook < 0) setEventMessages($hookmanager->error, $hookmanager->errors, 'errors'); -$help_url='EN:Module_Agenda_En|FR:Module_Agenda|ES:Módulo_Agenda'; +$help_url = 'EN:Module_Agenda_En|FR:Module_Agenda|ES:Módulo_Agenda'; llxHeader('', $langs->trans("Agenda"), $help_url); -$form=new Form($db); -$companystatic=new Societe($db); -$contactstatic=new Contact($db); +$form = new Form($db); +$companystatic = new Societe($db); +$contactstatic = new Contact($db); -$now=dol_now(); -$nowarray=dol_getdate($now); -$nowyear=$nowarray['year']; -$nowmonth=$nowarray['mon']; -$nowday=$nowarray['mday']; +$now = dol_now(); +$nowarray = dol_getdate($now); +$nowyear = $nowarray['year']; +$nowmonth = $nowarray['mon']; +$nowday = $nowarray['mday']; -$listofextcals=array(); +$listofextcals = array(); // Define list of external calendars (global admin setup) if (empty($conf->global->AGENDA_DISABLE_EXT)) { - $i=0; - while($i < $MAXAGENDA) + $i = 0; + while ($i < $MAXAGENDA) { $i++; - $source='AGENDA_EXT_SRC'.$i; - $name='AGENDA_EXT_NAME'.$i; - $offsettz='AGENDA_EXT_OFFSETTZ'.$i; - $color='AGENDA_EXT_COLOR'.$i; - $buggedfile='AGENDA_EXT_BUGGEDFILE'.$i; - if (! empty($conf->global->$source) && ! empty($conf->global->$name)) + $source = 'AGENDA_EXT_SRC'.$i; + $name = 'AGENDA_EXT_NAME'.$i; + $offsettz = 'AGENDA_EXT_OFFSETTZ'.$i; + $color = 'AGENDA_EXT_COLOR'.$i; + $buggedfile = 'AGENDA_EXT_BUGGEDFILE'.$i; + if (!empty($conf->global->$source) && !empty($conf->global->$name)) { // Note: $conf->global->buggedfile can be empty or 'uselocalandtznodaylight' or 'uselocalandtzdaylight' - $listofextcals[]=array('src'=>$conf->global->$source,'name'=>$conf->global->$name,'offsettz'=>$conf->global->$offsettz,'color'=>$conf->global->$color,'buggedfile'=>(isset($conf->global->buggedfile)?$conf->global->buggedfile:0)); + $listofextcals[] = array('src'=>$conf->global->$source, 'name'=>$conf->global->$name, 'offsettz'=>$conf->global->$offsettz, 'color'=>$conf->global->$color, 'buggedfile'=>(isset($conf->global->buggedfile) ? $conf->global->buggedfile : 0)); } } } // Define list of external calendars (user setup) if (empty($user->conf->AGENDA_DISABLE_EXT)) { - $i=0; - while($i < $MAXAGENDA) + $i = 0; + while ($i < $MAXAGENDA) { $i++; - $source='AGENDA_EXT_SRC_'.$user->id.'_'.$i; - $name='AGENDA_EXT_NAME_'.$user->id.'_'.$i; - $offsettz='AGENDA_EXT_OFFSETTZ_'.$user->id.'_'.$i; - $color='AGENDA_EXT_COLOR_'.$user->id.'_'.$i; - $enabled='AGENDA_EXT_ENABLED_'.$user->id.'_'.$i; - $buggedfile='AGENDA_EXT_BUGGEDFILE_'.$user->id.'_'.$i; - if (! empty($user->conf->$source) && ! empty($user->conf->$name)) + $source = 'AGENDA_EXT_SRC_'.$user->id.'_'.$i; + $name = 'AGENDA_EXT_NAME_'.$user->id.'_'.$i; + $offsettz = 'AGENDA_EXT_OFFSETTZ_'.$user->id.'_'.$i; + $color = 'AGENDA_EXT_COLOR_'.$user->id.'_'.$i; + $enabled = 'AGENDA_EXT_ENABLED_'.$user->id.'_'.$i; + $buggedfile = 'AGENDA_EXT_BUGGEDFILE_'.$user->id.'_'.$i; + if (!empty($user->conf->$source) && !empty($user->conf->$name)) { // Note: $conf->global->buggedfile can be empty or 'uselocalandtznodaylight' or 'uselocalandtzdaylight' - $listofextcals[]=array('src'=>$user->conf->$source,'name'=>$user->conf->$name,'offsettz'=>$user->conf->$offsettz,'color'=>$user->conf->$color,'buggedfile'=>(isset($user->conf->buggedfile)?$user->conf->buggedfile:0)); + $listofextcals[] = array('src'=>$user->conf->$source, 'name'=>$user->conf->$name, 'offsettz'=>$user->conf->$offsettz, 'color'=>$user->conf->$color, 'buggedfile'=>(isset($user->conf->buggedfile) ? $user->conf->buggedfile : 0)); } } } -if (empty($action) || $action=='show_month') +if (empty($action) || $action == 'show_month') { $prev = dol_get_prev_month($month, $year); $prev_year = $prev['year']; @@ -259,26 +259,26 @@ if (empty($action) || $action=='show_month') $next_year = $next['year']; $next_month = $next['month']; - $max_day_in_prev_month = date("t", dol_mktime(0, 0, 0, $prev_month, 1, $prev_year)); // Nb of days in previous month - $max_day_in_month = date("t", dol_mktime(0, 0, 0, $month, 1, $year)); // Nb of days in next month + $max_day_in_prev_month = date("t", dol_mktime(0, 0, 0, $prev_month, 1, $prev_year)); // Nb of days in previous month + $max_day_in_month = date("t", dol_mktime(0, 0, 0, $month, 1, $year)); // Nb of days in next month // tmpday is a negative or null cursor to know how many days before the 1st to show on month view (if tmpday=0, 1st is monday) - $tmpday = -date("w", dol_mktime(12, 0, 0, $month, 1, $year, true))+2; // date('w') is 0 fo sunday - $tmpday+=((isset($conf->global->MAIN_START_WEEK)?$conf->global->MAIN_START_WEEK:1)-1); - if ($tmpday >= 1) $tmpday -= 7; // If tmpday is 0 we start with sunday, if -6, we start with monday of previous week. + $tmpday = -date("w", dol_mktime(12, 0, 0, $month, 1, $year, true)) + 2; // date('w') is 0 fo sunday + $tmpday += ((isset($conf->global->MAIN_START_WEEK) ? $conf->global->MAIN_START_WEEK : 1) - 1); + if ($tmpday >= 1) $tmpday -= 7; // If tmpday is 0 we start with sunday, if -6, we start with monday of previous week. // Define firstdaytoshow and lastdaytoshow (warning: lastdaytoshow is last second to show + 1) - $firstdaytoshow=dol_mktime(0, 0, 0, $prev_month, $max_day_in_prev_month+$tmpday, $prev_year); - $next_day=7 - ($max_day_in_month+1-$tmpday) % 7; - if ($next_day < 6) $next_day+=7; - $lastdaytoshow=dol_mktime(0, 0, 0, $next_month, $next_day, $next_year); + $firstdaytoshow = dol_mktime(0, 0, 0, $prev_month, $max_day_in_prev_month + $tmpday, $prev_year); + $next_day = 7 - ($max_day_in_month + 1 - $tmpday) % 7; + if ($next_day < 6) $next_day += 7; + $lastdaytoshow = dol_mktime(0, 0, 0, $next_month, $next_day, $next_year); } -if ($action=='show_week') +if ($action == 'show_week') { $prev = dol_get_first_day_week($day, $month, $year); $prev_year = $prev['prev_year']; $prev_month = $prev['prev_month']; $prev_day = $prev['prev_day']; $first_day = $prev['first_day']; - $first_month= $prev['first_month']; + $first_month = $prev['first_month']; $first_year = $prev['first_year']; $week = $prev['week']; @@ -290,8 +290,8 @@ if ($action=='show_week') $next_day = $next['day']; // Define firstdaytoshow and lastdaytoshow (warning: lastdaytoshow is last second to show + 1) - $firstdaytoshow=dol_mktime(0, 0, 0, $first_month, $first_day, $first_year); - $lastdaytoshow=dol_time_plus_duree($firstdaytoshow, 7, 'd'); + $firstdaytoshow = dol_mktime(0, 0, 0, $first_month, $first_day, $first_year); + $lastdaytoshow = dol_time_plus_duree($firstdaytoshow, 7, 'd'); $max_day_in_month = date("t", dol_mktime(0, 0, 0, $month, 1, $year)); @@ -309,79 +309,79 @@ if ($action == 'show_day') $next_day = $next['day']; // Define firstdaytoshow and lastdaytoshow (warning: lastdaytoshow is last second to show + 1) - $firstdaytoshow=dol_mktime(0, 0, 0, $prev_month, $prev_day, $prev_year); - $lastdaytoshow=dol_mktime(0, 0, 0, $next_month, $next_day, $next_year); + $firstdaytoshow = dol_mktime(0, 0, 0, $prev_month, $prev_day, $prev_year); + $lastdaytoshow = dol_mktime(0, 0, 0, $next_month, $next_day, $next_year); } //print 'xx'.$prev_year.'-'.$prev_month.'-'.$prev_day; //print 'xx'.$next_year.'-'.$next_month.'-'.$next_day; //print dol_print_date($firstdaytoshow,'day'); //print dol_print_date($lastdaytoshow,'day'); -$title=$langs->trans("DoneAndToDoActions"); -if ($status == 'done') $title=$langs->trans("DoneActions"); -if ($status == 'todo') $title=$langs->trans("ToDoActions"); +$title = $langs->trans("DoneAndToDoActions"); +if ($status == 'done') $title = $langs->trans("DoneActions"); +if ($status == 'todo') $title = $langs->trans("ToDoActions"); -$param=''; +$param = ''; if ($actioncode || isset($_GET['search_actioncode']) || isset($_POST['search_actioncode'])) { - if(is_array($actioncode)) { - foreach($actioncode as $str_action) $param.="&search_actioncode[]=".urlencode($str_action); - } else $param.="&search_actioncode=".urlencode($actioncode); + if (is_array($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 || isset($_GET['status']) || isset($_POST['status'])) $param.="&search_status=".urlencode($status); -if ($filter) $param.="&search_filter=".urlencode($filter); -if ($filtert) $param.="&search_filtert=".urlencode($filtert); -if ($usergroup) $param.="&search_usergroup=".urlencode($usergroup); -if ($socid) $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') $param.='&action='.urlencode($action); -$param.="&maxprint=".urlencode($maxprint); +if ($resourceid > 0) $param .= "&search_resourceid=".urlencode($resourceid); +if ($status || isset($_GET['status']) || isset($_POST['status'])) $param .= "&search_status=".urlencode($status); +if ($filter) $param .= "&search_filter=".urlencode($filter); +if ($filtert) $param .= "&search_filtert=".urlencode($filtert); +if ($usergroup) $param .= "&search_usergroup=".urlencode($usergroup); +if ($socid) $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') $param .= '&action='.urlencode($action); +$param .= "&maxprint=".urlencode($maxprint); // Show navigation bar -if (empty($action) || $action=='show_month') +if (empty($action) || $action == 'show_month') { - $nav ="  \n"; - $nav.=" ".dol_print_date(dol_mktime(0, 0, 0, $month, 1, $year), "%b %Y"); - $nav.=" \n"; - $nav.="   \n"; - $nav.="   (".$langs->trans("Today").")"; - $picto='calendar'; + $nav = "  \n"; + $nav .= " ".dol_print_date(dol_mktime(0, 0, 0, $month, 1, $year), "%b %Y"); + $nav .= " \n"; + $nav .= "   \n"; + $nav .= "   (".$langs->trans("Today").")"; + $picto = 'calendar'; } -if ($action=='show_week') +if ($action == 'show_week') { - $nav ="trans("Previous"))."\">  \n"; - $nav.=" ".dol_print_date(dol_mktime(0, 0, 0, $first_month, $first_day, $first_year), "%Y").", ".$langs->trans("Week")." ".$week; - $nav.=" \n"; - $nav.="   trans("Next"))."\">\n"; - $nav.="   (".$langs->trans("Today").")"; - $picto='calendarweek'; + $nav = "trans("Previous"))."\">  \n"; + $nav .= " ".dol_print_date(dol_mktime(0, 0, 0, $first_month, $first_day, $first_year), "%Y").", ".$langs->trans("Week")." ".$week; + $nav .= " \n"; + $nav .= "   trans("Next"))."\">\n"; + $nav .= "   (".$langs->trans("Today").")"; + $picto = 'calendarweek'; } -if ($action=='show_day') +if ($action == 'show_day') { - $nav ="  \n"; - $nav.=" ".dol_print_date(dol_mktime(0, 0, 0, $month, $day, $year), "daytextshort"); - $nav.=" \n"; - $nav.="   \n"; - $nav.="   (".$langs->trans("Today").")"; - $picto='calendarday'; + $nav = "  \n"; + $nav .= " ".dol_print_date(dol_mktime(0, 0, 0, $month, $day, $year), "daytextshort"); + $nav .= " \n"; + $nav .= "   \n"; + $nav .= "   (".$langs->trans("Today").")"; + $picto = 'calendarday'; } // Must be after the nav definition -$param.='&year='.$year.'&month='.$month.($day?'&day='.$day:''); +$param .= '&year='.$year.'&month='.$month.($day ? '&day='.$day : ''); //print 'x'.$param; -$tabactive=''; -if ($action == 'show_month') $tabactive='cardmonth'; -if ($action == 'show_week') $tabactive='cardweek'; -if ($action == 'show_day') $tabactive='cardday'; -if ($action == 'show_list') $tabactive='cardlist'; +$tabactive = ''; +if ($action == 'show_month') $tabactive = 'cardmonth'; +if ($action == 'show_week') $tabactive = 'cardweek'; +if ($action == 'show_day') $tabactive = 'cardday'; +if ($action == 'show_list') $tabactive = 'cardlist'; -$paramnoaction=preg_replace('/action=[a-z_]+/', '', $param); +$paramnoaction = preg_replace('/action=[a-z_]+/', '', $param); $head = calendars_prepare_head($paramnoaction); @@ -395,66 +395,66 @@ dol_fiche_end(); // Define the legend/list of calendard to show -$s=''; $link=''; +$s = ''; $link = ''; -$showextcals=$listofextcals; +$showextcals = $listofextcals; -if (! empty($conf->use_javascript_ajax)) // If javascript on +if (!empty($conf->use_javascript_ajax)) // If javascript on { - $s.="\n".''."\n"; - $s.='' . "\n"; + $s .= '});'."\n"; + $s .= ''."\n"; // Local calendar - $s.='
' . $langs->trans("LocalAgenda").'  
'; + $s .= '
'.$langs->trans("LocalAgenda").'  
'; // External calendars if (is_array($showextcals) && count($showextcals) > 0) { - $s.='' . "\n"; + $s .= ''."\n"; foreach ($showextcals as $val) { $htmlname = md5($val['name']); - $s.='
' . $val['name'] . '  
'; + $s .= '
'.$val['name'].'  
'; } } // Birthdays - $s.='
'.$langs->trans("AgendaShowBirthdayEvents").'  
'; + $s .= '
'.$langs->trans("AgendaShowBirthdayEvents").'  
'; // Calendars from hooks - $parameters=array(); $object=null; - $reshook=$hookmanager->executeHooks('addCalendarChoice', $parameters, $object, $action); + $parameters = array(); $object = null; + $reshook = $hookmanager->executeHooks('addCalendarChoice', $parameters, $object, $action); if (empty($reshook)) { - $s.= $hookmanager->resPrint; + $s .= $hookmanager->resPrint; } elseif ($reshook > 1) { @@ -463,182 +463,182 @@ if (! empty($conf->use_javascript_ajax)) // If javascript on } else // If javascript off { - $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.=''; + $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 .= ''; } print load_fiche_titre($s, $link.'     '.$nav, '', 0, 0, 'tablelistofcalendars'); // Load events from database into $eventarray -$eventarray=array(); +$eventarray = array(); $sql = 'SELECT '; -if ($usergroup > 0) $sql.=" DISTINCT"; -$sql.= ' a.id, a.label,'; -$sql.= ' a.datep,'; -$sql.= ' a.datep2,'; -$sql.= ' a.percent,'; -$sql.= ' a.fk_user_author,a.fk_user_action,'; -$sql.= ' a.transparency, a.priority, a.fulldayevent, a.location,'; -$sql.= ' a.fk_soc, a.fk_contact,'; -$sql.= ' a.fk_element, a.elementtype,'; -$sql.= ' ca.code as type_code, ca.libelle as type_label, ca.color as type_color'; -$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 ($usergroup > 0) $sql .= " DISTINCT"; +$sql .= ' a.id, a.label,'; +$sql .= ' a.datep,'; +$sql .= ' a.datep2,'; +$sql .= ' a.percent,'; +$sql .= ' a.fk_user_author,a.fk_user_action,'; +$sql .= ' a.transparency, a.priority, a.fulldayevent, a.location,'; +$sql .= ' a.fk_soc, a.fk_contact,'; +$sql .= ' a.fk_element, a.elementtype,'; +$sql .= ' ca.code as type_code, ca.libelle as type_label, ca.color as type_color'; +$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"; // 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"; -$sql.= ' WHERE a.fk_action = ca.id'; -$sql.= ' AND a.entity IN ('.getEntity('agenda').')'; +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($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'"; + 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 ($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'"; + 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)."')"; + $sql .= " AND ca.code IN ('".implode("','", $actioncode)."')"; } else { - $sql.=" AND ca.code IN ('".implode("','", explode(',', $actioncode))."')"; + $sql .= " AND ca.code IN ('".implode("','", explode(',', $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'"; if ($action == 'show_day') { - $sql.= " AND ("; - $sql.= " (a.datep BETWEEN '".$db->idate(dol_mktime(0, 0, 0, $month, $day, $year))."'"; - $sql.= " AND '".$db->idate(dol_mktime(23, 59, 59, $month, $day, $year))."')"; - $sql.= " OR "; - $sql.= " (a.datep2 BETWEEN '".$db->idate(dol_mktime(0, 0, 0, $month, $day, $year))."'"; - $sql.= " AND '".$db->idate(dol_mktime(23, 59, 59, $month, $day, $year))."')"; - $sql.= " OR "; - $sql.= " (a.datep < '".$db->idate(dol_mktime(0, 0, 0, $month, $day, $year))."'"; - $sql.= " AND a.datep2 > '".$db->idate(dol_mktime(23, 59, 59, $month, $day, $year))."')"; - $sql.= ')'; + $sql .= " AND ("; + $sql .= " (a.datep BETWEEN '".$db->idate(dol_mktime(0, 0, 0, $month, $day, $year))."'"; + $sql .= " AND '".$db->idate(dol_mktime(23, 59, 59, $month, $day, $year))."')"; + $sql .= " OR "; + $sql .= " (a.datep2 BETWEEN '".$db->idate(dol_mktime(0, 0, 0, $month, $day, $year))."'"; + $sql .= " AND '".$db->idate(dol_mktime(23, 59, 59, $month, $day, $year))."')"; + $sql .= " OR "; + $sql .= " (a.datep < '".$db->idate(dol_mktime(0, 0, 0, $month, $day, $year))."'"; + $sql .= " AND a.datep2 > '".$db->idate(dol_mktime(23, 59, 59, $month, $day, $year))."')"; + $sql .= ')'; } else { // To limit array - $sql.= " AND ("; - $sql.= " (a.datep BETWEEN '".$db->idate(dol_mktime(0, 0, 0, $month, 1, $year)-(60*60*24*7))."'"; // Start 7 days before - $sql.= " AND '".$db->idate(dol_mktime(23, 59, 59, $month, 28, $year)+(60*60*24*10))."')"; // End 7 days after + 3 to go from 28 to 31 - $sql.= " OR "; - $sql.= " (a.datep2 BETWEEN '".$db->idate(dol_mktime(0, 0, 0, $month, 1, $year)-(60*60*24*7))."'"; - $sql.= " AND '".$db->idate(dol_mktime(23, 59, 59, $month, 28, $year)+(60*60*24*10))."')"; - $sql.= " OR "; - $sql.= " (a.datep < '".$db->idate(dol_mktime(0, 0, 0, $month, 1, $year)-(60*60*24*7))."'"; - $sql.= " AND a.datep2 > '".$db->idate(dol_mktime(23, 59, 59, $month, 28, $year)+(60*60*24*10))."')"; - $sql.= ')'; + $sql .= " AND ("; + $sql .= " (a.datep BETWEEN '".$db->idate(dol_mktime(0, 0, 0, $month, 1, $year) - (60 * 60 * 24 * 7))."'"; // Start 7 days before + $sql .= " AND '".$db->idate(dol_mktime(23, 59, 59, $month, 28, $year) + (60 * 60 * 24 * 10))."')"; // End 7 days after + 3 to go from 28 to 31 + $sql .= " OR "; + $sql .= " (a.datep2 BETWEEN '".$db->idate(dol_mktime(0, 0, 0, $month, 1, $year) - (60 * 60 * 24 * 7))."'"; + $sql .= " AND '".$db->idate(dol_mktime(23, 59, 59, $month, 28, $year) + (60 * 60 * 24 * 10))."')"; + $sql .= " OR "; + $sql .= " (a.datep < '".$db->idate(dol_mktime(0, 0, 0, $month, 1, $year) - (60 * 60 * 24 * 7))."'"; + $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) { - $sql.= " AND ("; - if ($filtert > 0) $sql.= "ar.fk_element = ".$filtert; - if ($usergroup > 0) $sql.= ($filtert>0?" OR ":"")." ugu.fk_usergroup = ".$usergroup; - $sql.= ")"; + $sql .= " AND ("; + if ($filtert > 0) $sql .= "ar.fk_element = ".$filtert; + if ($usergroup > 0) $sql .= ($filtert > 0 ? " OR " : "")." ugu.fk_usergroup = ".$usergroup; + $sql .= ")"; } // Sort on date -$sql.= ' ORDER BY datep'; +$sql .= ' ORDER BY datep'; //print $sql; dol_syslog("comm/action/index.php", LOG_DEBUG); -$resql=$db->query($sql); +$resql = $db->query($sql); 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; + $MAXONSAMEPAGE = 10000; // Useless to have more. Protection to avoid memory overload when high number of event (for example after a mass import) + $i = 0; while ($i < $num && $i < $MAXONSAMEPAGE) { $obj = $db->fetch_object($resql); // Discard auto action if option is on - if (! empty($conf->global->AGENDA_ALWAYS_HIDE_AUTO) && $obj->type_code == 'AC_OTH_AUTO') + if (!empty($conf->global->AGENDA_ALWAYS_HIDE_AUTO) && $obj->type_code == 'AC_OTH_AUTO') { $i++; continue; } // Create a new object action - $event=new ActionComm($db); - $event->id=$obj->id; + $event = new ActionComm($db); + $event->id = $obj->id; - $event->datep=$db->jdate($obj->datep); // datep and datef are GMT date. Example: 1970-01-01 01:00:00, jdate will return 0 if TZ of PHP server is Europe/Berlin - $event->datef=$db->jdate($obj->datep2); + $event->datep = $db->jdate($obj->datep); // datep and datef are GMT date. Example: 1970-01-01 01:00:00, jdate will return 0 if TZ of PHP server is Europe/Berlin + $event->datef = $db->jdate($obj->datep2); //var_dump($obj->datep); //var_dump($event->datep); - $event->type_code=$obj->type_code; - $event->type_label=$obj->type_label; - $event->type_color=$obj->type_color; + $event->type_code = $obj->type_code; + $event->type_label = $obj->type_label; + $event->type_color = $obj->type_color; - $event->libelle=$obj->label; // deprecated - $event->label=$obj->label; - $event->percentage=$obj->percent; - $event->authorid=$obj->fk_user_author; // user id of creator - $event->userownerid=$obj->fk_user_action; // user id of owner - $event->fetch_userassigned(); // This load $event->userassigned - $event->priority=$obj->priority; - $event->fulldayevent=$obj->fulldayevent; - $event->location=$obj->location; - $event->transparency=$obj->transparency; - $event->fk_element=$obj->fk_element; - $event->elementtype=$obj->elementtype; + $event->libelle = $obj->label; // deprecated + $event->label = $obj->label; + $event->percentage = $obj->percent; + $event->authorid = $obj->fk_user_author; // user id of creator + $event->userownerid = $obj->fk_user_action; // user id of owner + $event->fetch_userassigned(); // This load $event->userassigned + $event->priority = $obj->priority; + $event->fulldayevent = $obj->fulldayevent; + $event->location = $obj->location; + $event->transparency = $obj->transparency; + $event->fk_element = $obj->fk_element; + $event->elementtype = $obj->elementtype; - $event->thirdparty_id=$obj->fk_soc; - $event->contact_id=$obj->fk_contact; + $event->thirdparty_id = $obj->fk_soc; + $event->contact_id = $obj->fk_contact; // Defined date_start_in_calendar and date_end_in_calendar property // They are date start and end of action but modified to not be outside calendar view. - $event->date_start_in_calendar=$event->datep; - if ($event->datef != '' && $event->datef >= $event->datep) $event->date_end_in_calendar=$event->datef; - else $event->date_end_in_calendar=$event->datep; + $event->date_start_in_calendar = $event->datep; + if ($event->datef != '' && $event->datef >= $event->datep) $event->date_end_in_calendar = $event->datef; + else $event->date_end_in_calendar = $event->datep; // Define ponctual property if ($event->date_start_in_calendar == $event->date_end_in_calendar) { - $event->ponctuel=1; + $event->ponctuel = 1; } // Check values @@ -649,27 +649,27 @@ if ($resql) } 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; + $daycursor = $event->date_start_in_calendar; $annee = date('Y', $daycursor); $mois = date('m', $daycursor); $jour = date('d', $daycursor); // Loop on each day covered by action to prepare an index to show on calendar - $loop=true; $j=0; - $daykey=dol_mktime(0, 0, 0, $mois, $jour, $annee); + $loop = true; $j = 0; + $daykey = dol_mktime(0, 0, 0, $mois, $jour, $annee); do { //if ($event->id==408) print 'daykey='.$daykey.' '.$event->datep.' '.$event->datef.'
'; - $eventarray[$daykey][]=$event; + $eventarray[$daykey][] = $event; $j++; - $daykey+=60*60*24; - if ($daykey > $event->date_end_in_calendar) $loop=false; + $daykey += 60 * 60 * 24; + if ($daykey > $event->date_end_in_calendar) $loop = false; } while ($loop); @@ -689,58 +689,58 @@ 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').")"; + $sql .= ' FROM '.MAIN_DB_PREFIX.'socpeople as sp'; + $sql .= ' WHERE (priv=0 OR (priv=1 AND fk_user_creat='.$user->id.'))'; + $sql .= " AND sp.entity IN (".getEntity('socpeople').")"; if ($action == 'show_day') { - $sql.= ' AND MONTH(birthday) = '.$month; - $sql.= ' AND DAY(birthday) = '.$day; + $sql .= ' AND MONTH(birthday) = '.$month; + $sql .= ' AND DAY(birthday) = '.$day; } else { - $sql.= ' AND MONTH(birthday) = '.$month; + $sql .= ' AND MONTH(birthday) = '.$month; } - $sql.= ' ORDER BY birthday'; + $sql .= ' ORDER BY birthday'; dol_syslog("comm/action/index.php", LOG_DEBUG); - $resql=$db->query($sql); + $resql = $db->query($sql); if ($resql) { $num = $db->num_rows($resql); - $i=0; + $i = 0; while ($i < $num) { $obj = $db->fetch_object($resql); - $event=new ActionComm($db); - $event->id=$obj->rowid; // We put contact id in action id for birthdays events - $datebirth=dol_stringtotime($obj->birthday, 1); + $event = new ActionComm($db); + $event->id = $obj->rowid; // We put contact id in action id for birthdays events + $datebirth = dol_stringtotime($obj->birthday, 1); //print 'ee'.$obj->birthday.'-'.$datebirth; - $datearray=dol_getdate($datebirth, true); - $event->datep=dol_mktime(0, 0, 0, $datearray['mon'], $datearray['mday'], $year, true); // For full day events, date are also GMT but they wont but converted during output - $event->datef=$event->datep; - $event->type_code='BIRTHDAY'; - $event->label=$langs->trans("Birthday").' '.dolGetFirstLastname($obj->firstname, $obj->lastname); - $event->percentage=100; - $event->fulldayevent=1; + $datearray = dol_getdate($datebirth, true); + $event->datep = dol_mktime(0, 0, 0, $datearray['mon'], $datearray['mday'], $year, true); // For full day events, date are also GMT but they wont but converted during output + $event->datef = $event->datep; + $event->type_code = 'BIRTHDAY'; + $event->label = $langs->trans("Birthday").' '.dolGetFirstLastname($obj->firstname, $obj->lastname); + $event->percentage = 100; + $event->fulldayevent = 1; - $event->date_start_in_calendar=$event->datep; - $event->date_end_in_calendar=$event->datef; - $event->ponctuel=0; + $event->date_start_in_calendar = $event->datep; + $event->date_end_in_calendar = $event->datef; + $event->ponctuel = 0; // Add an entry in actionarray for each day - $daycursor=$event->date_start_in_calendar; + $daycursor = $event->date_start_in_calendar; $annee = date('Y', $daycursor); $mois = date('m', $daycursor); $jour = date('d', $daycursor); - $loop=true; - $daykey=dol_mktime(0, 0, 0, $mois, $jour, $annee); + $loop = true; + $daykey = dol_mktime(0, 0, 0, $mois, $jour, $annee); do { - $eventarray[$daykey][]=$event; - $daykey+=60*60*24; - if ($daykey > $event->date_end_in_calendar) $loop=false; + $eventarray[$daykey][] = $event; + $daykey += 60 * 60 * 24; + if ($daykey > $event->date_end_in_calendar) $loop = false; } while ($loop); $i++; @@ -756,28 +756,28 @@ if ($showbirthday) 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 + $url = $extcal['src']; // Example: https://www.google.com/calendar/ical/eldy10%40gmail.com/private-cde92aa7d7e0ef6110010a821a2aaeb/basic.ics $namecal = $extcal['name']; $offsettz = $extcal['offsettz']; $colorcal = $extcal['color']; $buggedfile = $extcal['buggedfile']; //print "url=".$url." namecal=".$namecal." colorcal=".$colorcal." buggedfile=".$buggedfile; - $ical=new ICal(); + $ical = new ICal(); $ical->parse($url); // After this $ical->cal['VEVENT'] contains array of events, $ical->cal['DAYLIGHT'] contains daylight info, $ical->cal['STANDARD'] contains non daylight info, ... //var_dump($ical->cal); exit; - $icalevents=array(); - if (is_array($ical->get_event_list())) $icalevents=array_merge($icalevents, $ical->get_event_list()); // Add $ical->cal['VEVENT'] - if (is_array($ical->get_freebusy_list())) $icalevents=array_merge($icalevents, $ical->get_freebusy_list()); // Add $ical->cal['VFREEBUSY'] + $icalevents = array(); + if (is_array($ical->get_event_list())) $icalevents = array_merge($icalevents, $ical->get_event_list()); // Add $ical->cal['VEVENT'] + if (is_array($ical->get_freebusy_list())) $icalevents = array_merge($icalevents, $ical->get_freebusy_list()); // Add $ical->cal['VFREEBUSY'] - if (count($icalevents)>0) + if (count($icalevents) > 0) { // Duplicate all repeatable events into new entries - $moreicalevents=array(); - foreach($icalevents as $icalevent) + $moreicalevents = array(); + foreach ($icalevents as $icalevent) { if (isset($icalevent['RRULE']) && is_array($icalevent['RRULE'])) //repeatable event { @@ -785,26 +785,26 @@ if (count($listofextcals)) //if ($event->date_end_in_calendar > $lastdaytoshow) $event->date_end_in_calendar=($lastdaytoshow-1); if ($icalevent['DTSTART;VALUE=DATE']) //fullday event { - $datecurstart=dol_stringtotime($icalevent['DTSTART;VALUE=DATE'], 1); - $datecurend=dol_stringtotime($icalevent['DTEND;VALUE=DATE'], 1)-1; // We remove one second to get last second of day + $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) + $datecurstart = $icalevent['DTSTART']['unixtime']; + $datecurend = $icalevent['DTEND']['unixtime']; + if (!empty($ical->cal['DAYLIGHT']['DTSTART']) && $datecurstart) { //var_dump($ical->cal); - $tmpcurstart=$datecurstart; - $tmpcurend=$datecurend; - $tmpdaylightstart=dol_mktime(0, 0, 0, 1, 1, 1970, 1) + (int) $ical->cal['DAYLIGHT']['DTSTART']; - $tmpdaylightend=dol_mktime(0, 0, 0, 1, 1, 1970, 1) + (int) $ical->cal['STANDARD']['DTSTART']; + $tmpcurstart = $datecurstart; + $tmpcurend = $datecurend; + $tmpdaylightstart = dol_mktime(0, 0, 0, 1, 1, 1970, 1) + (int) $ical->cal['DAYLIGHT']['DTSTART']; + $tmpdaylightend = dol_mktime(0, 0, 0, 1, 1, 1970, 1) + (int) $ical->cal['STANDARD']['DTSTART']; //var_dump($tmpcurstart);var_dump($tmpcurend); var_dump($ical->cal['DAYLIGHT']['DTSTART']);var_dump($ical->cal['STANDARD']['DTSTART']); // Edit datecurstart and datecurend - if ($tmpcurstart >= $tmpdaylightstart && $tmpcurstart < $tmpdaylightend) $datecurstart-=((int) $ical->cal['DAYLIGHT']['TZOFFSETTO'])*36; - else $datecurstart-=((int) $ical->cal['STANDARD']['TZOFFSETTO'])*36; - if ($tmpcurend >= $tmpdaylightstart && $tmpcurstart < $tmpdaylightend) $datecurend-=((int) $ical->cal['DAYLIGHT']['TZOFFSETTO'])*36; - else $datecurend-=((int) $ical->cal['STANDARD']['TZOFFSETTO'])*36; + 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; @@ -817,106 +817,106 @@ if (count($listofextcals)) } //print 'xx'.$datecurstart;exit; - $interval=(empty($icalevent['RRULE']['INTERVAL'])?1:$icalevent['RRULE']['INTERVAL']); - $until=empty($icalevent['RRULE']['UNTIL'])?0:dol_stringtotime($icalevent['RRULE']['UNTIL'], 1); - $maxrepeat=empty($icalevent['RRULE']['COUNT'])?0:$icalevent['RRULE']['COUNT']; - if ($until && ($until+($datecurend-$datecurstart)) < $firstdaytoshow) continue; // We discard repeatable event that end before start date to show - if ($datecurstart >= $lastdaytoshow) continue; // We discard repeatable event that start after end date to show + $interval = (empty($icalevent['RRULE']['INTERVAL']) ? 1 : $icalevent['RRULE']['INTERVAL']); + $until = empty($icalevent['RRULE']['UNTIL']) ? 0 : dol_stringtotime($icalevent['RRULE']['UNTIL'], 1); + $maxrepeat = empty($icalevent['RRULE']['COUNT']) ? 0 : $icalevent['RRULE']['COUNT']; + if ($until && ($until + ($datecurend - $datecurstart)) < $firstdaytoshow) continue; // We discard repeatable event that end before start date to show + if ($datecurstart >= $lastdaytoshow) continue; // We discard repeatable event that start after end date to show - $numofevent=0; + $numofevent = 0; while (($datecurstart < $lastdaytoshow) && (empty($maxrepeat) || ($numofevent < $maxrepeat))) { if ($datecurend >= $firstdaytoshow) // We add event { - $newevent=$icalevent; + $newevent = $icalevent; unset($newevent['RRULE']); if ($icalevent['DTSTART;VALUE=DATE']) { - $newevent['DTSTART;VALUE=DATE']=dol_print_date($datecurstart, '%Y%m%d'); - $newevent['DTEND;VALUE=DATE']=dol_print_date($datecurend+1, '%Y%m%d'); + $newevent['DTSTART;VALUE=DATE'] = dol_print_date($datecurstart, '%Y%m%d'); + $newevent['DTEND;VALUE=DATE'] = dol_print_date($datecurend + 1, '%Y%m%d'); } else { - $newevent['DTSTART']=$datecurstart; - $newevent['DTEND']=$datecurend; + $newevent['DTSTART'] = $datecurstart; + $newevent['DTEND'] = $datecurend; } - $moreicalevents[]=$newevent; + $moreicalevents[] = $newevent; } // Jump on next occurence $numofevent++; - $savdatecurstart=$datecurstart; - if ($icalevent['RRULE']['FREQ']=='DAILY') + $savdatecurstart = $datecurstart; + if ($icalevent['RRULE']['FREQ'] == 'DAILY') { - $datecurstart=dol_time_plus_duree($datecurstart, $interval, 'd'); - $datecurend=dol_time_plus_duree($datecurend, $interval, 'd'); + $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'); + $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'); + $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'); + $datecurstart = dol_time_plus_duree($datecurstart, $interval, 'y'); + $datecurend = dol_time_plus_duree($datecurend, $interval, 'y'); } // Test to avoid infinite loop ($datecurstart must increase) if ($savdatecurstart >= $datecurstart) { dol_syslog("Found a rule freq ".$icalevent['RRULE']['FREQ']." not managed by dolibarr code. Assume 1 week frequency.", LOG_ERR); - $datecurstart+=3600*24*7; - $datecurend+=3600*24*7; + $datecurstart += 3600 * 24 * 7; + $datecurend += 3600 * 24 * 7; } } } } - $icalevents=array_merge($icalevents, $moreicalevents); + $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); + $event = new ActionComm($db); $addevent = false; if (isset($icalevent['DTSTART;VALUE=DATE'])) // fullday event { // For full day events, date are also GMT but they wont but converted using tz during output - $datestart=dol_stringtotime($icalevent['DTSTART;VALUE=DATE'], 1); - $dateend=dol_stringtotime($icalevent['DTEND;VALUE=DATE'], 1)-1; // We remove one second to get last second of day + $datestart = dol_stringtotime($icalevent['DTSTART;VALUE=DATE'], 1); + $dateend = dol_stringtotime($icalevent['DTEND;VALUE=DATE'], 1) - 1; // We remove one second to get last second of day //print 'x'.$datestart.'-'.$dateend;exit; //print dol_print_date($dateend,'dayhour','gmt'); - $event->fulldayevent=1; - $addevent=true; + $event->fulldayevent = 1; + $addevent = true; } elseif (!is_array($icalevent['DTSTART'])) // not fullday event (DTSTART is not array. It is a value like '19700101T000000Z' for 00:00 in greenwitch) { - $datestart=$icalevent['DTSTART']; - $dateend=$icalevent['DTEND']; + $datestart = $icalevent['DTSTART']; + $dateend = $icalevent['DTEND']; - $datestart+=+($offsettz * 3600); - $dateend+=+($offsettz * 3600); + $datestart += +($offsettz * 3600); + $dateend += +($offsettz * 3600); - $addevent=true; + $addevent = true; //var_dump($offsettz); //var_dump(dol_print_date($datestart, 'dayhour', 'gmt')); } elseif (isset($icalevent['DTSTART']['unixtime'])) // File contains a local timezone + a TZ (for example when using bluemind) { - $datestart=$icalevent['DTSTART']['unixtime']; - $dateend=$icalevent['DTEND']['unixtime']; + $datestart = $icalevent['DTSTART']['unixtime']; + $dateend = $icalevent['DTEND']['unixtime']; - $datestart+=+($offsettz * 3600); - $dateend+=+($offsettz * 3600); + $datestart += +($offsettz * 3600); + $dateend += +($offsettz * 3600); // $buggedfile is set to uselocalandtznodaylight if conf->global->AGENDA_EXT_BUGGEDFILEx = 'uselocalandtznodaylight' if ($buggedfile === 'uselocalandtznodaylight') // unixtime is a local date that does not take daylight into account, TZID is +1 for example for 'Europe/Paris' in summer instead of 2 @@ -930,38 +930,38 @@ if (count($listofextcals)) $localtze = new DateTimeZone(preg_replace('/"/', '', $icalevent['DTEND']['TZID'])); $localdts = new DateTime(dol_print_date($datestart, 'dayrfc', 'gmt'), $localtzs); $localdte = new DateTime(dol_print_date($dateend, 'dayrfc', 'gmt'), $localtze); - $tmps=-1*$localtzs->getOffset($localdts); - $tmpe=-1*$localtze->getOffset($localdte); - $datestart+=$tmps; - $dateend+=$tmpe; + $tmps = -1 * $localtzs->getOffset($localdts); + $tmpe = -1 * $localtze->getOffset($localdte); + $datestart += $tmps; + $dateend += $tmpe; //var_dump($datestart); } - $addevent=true; + $addevent = true; } if ($addevent) { - $event->id=$icalevent['UID']; - $event->icalname=$namecal; - $event->icalcolor=$colorcal; - $usertime=0; // We dont modify date because we want to have date into memory datep and datef stored as GMT date. Compensation will be done during output. - $event->datep=$datestart+$usertime; - $event->datef=$dateend+$usertime; - $event->type_code="ICALEVENT"; + $event->id = $icalevent['UID']; + $event->icalname = $namecal; + $event->icalcolor = $colorcal; + $usertime = 0; // We dont modify date because we want to have date into memory datep and datef stored as GMT date. Compensation will be done during output. + $event->datep = $datestart + $usertime; + $event->datef = $dateend + $usertime; + $event->type_code = "ICALEVENT"; - if($icalevent['SUMMARY']) $event->label=$icalevent['SUMMARY']; - elseif($icalevent['DESCRIPTION']) $event->label=dol_nl2br($icalevent['DESCRIPTION'], 1); + if ($icalevent['SUMMARY']) $event->label = $icalevent['SUMMARY']; + elseif ($icalevent['DESCRIPTION']) $event->label = dol_nl2br($icalevent['DESCRIPTION'], 1); else $event->label = $langs->trans("ExtSiteNoLabel"); - $event->date_start_in_calendar=$event->datep; + $event->date_start_in_calendar = $event->datep; - if ($event->datef != '' && $event->datef >= $event->datep) $event->date_end_in_calendar=$event->datef; - else $event->date_end_in_calendar=$event->datep; + if ($event->datef != '' && $event->datef >= $event->datep) $event->date_end_in_calendar = $event->datef; + else $event->date_end_in_calendar = $event->datep; // Define ponctual property if ($event->date_start_in_calendar == $event->date_end_in_calendar) { - $event->ponctuel=1; + $event->ponctuel = 1; //print 'x'.$datestart.'-'.$dateend;exit; } @@ -975,26 +975,26 @@ if (count($listofextcals)) } 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; + $daycursor = $event->date_start_in_calendar; $annee = date('Y', $daycursor); $mois = date('m', $daycursor); $jour = date('d', $daycursor); // Loop on each day covered by action to prepare an index to show on calendar - $loop=true; $j=0; + $loop = true; $j = 0; // daykey must be date that represent day box in calendar so must be a user time - $daykey=dol_mktime(0, 0, 0, $mois, $jour, $annee); - $daykeygmt=dol_mktime(0, 0, 0, $mois, $jour, $annee, true, 0); + $daykey = dol_mktime(0, 0, 0, $mois, $jour, $annee); + $daykeygmt = dol_mktime(0, 0, 0, $mois, $jour, $annee, true, 0); do { //if ($event->fulldayevent) print dol_print_date($daykeygmt,'dayhour','gmt').'-'.dol_print_date($daykey,'dayhour','gmt').'-'.dol_print_date($event->date_end_in_calendar,'dayhour','gmt').' '; - $eventarray[$daykey][]=$event; - $daykey+=60*60*24; $daykeygmt+=60*60*24; // Add one day - if (($event->fulldayevent ? $daykeygmt : $daykey) > $event->date_end_in_calendar) $loop=false; + $eventarray[$daykey][] = $event; + $daykey += 60 * 60 * 24; $daykeygmt += 60 * 60 * 24; // Add one day + if (($event->fulldayevent ? $daykeygmt : $daykey) > $event->date_end_in_calendar) $loop = false; } while ($loop); } @@ -1007,28 +1007,28 @@ if (count($listofextcals)) // Complete $eventarray with events coming from external module -$parameters=array(); $object=null; -$reshook=$hookmanager->executeHooks('getCalendarEvents', $parameters, $object, $action); -if (! empty($hookmanager->resArray['eventarray'])) { +$parameters = array(); $object = null; +$reshook = $hookmanager->executeHooks('getCalendarEvents', $parameters, $object, $action); +if (!empty($hookmanager->resArray['eventarray'])) { foreach ($hookmanager->resArray['eventarray'] as $keyDate => $events) { if (!isset($eventarray[$keyDate])) { - $eventarray[$keyDate]=array(); + $eventarray[$keyDate] = array(); } - $eventarray[$keyDate]=array_merge($eventarray[$keyDate], $events); + $eventarray[$keyDate] = array_merge($eventarray[$keyDate], $events); } } // Sort events -foreach($eventarray as $keyDate => &$dateeventarray) +foreach ($eventarray as $keyDate => &$dateeventarray) { usort($dateeventarray, 'sort_events_by_date'); } -$maxnbofchar=0; -$cachethirdparties=array(); -$cachecontacts=array(); -$cacheusers=array(); +$maxnbofchar = 0; +$cachethirdparties = array(); +$cachecontacts = array(); +$cacheusers = array(); // Define theme_datacolor array $color_file = DOL_DOCUMENT_ROOT."/theme/".$conf->theme."/theme_vars.inc.php"; @@ -1036,34 +1036,34 @@ 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)); if (empty($action) || $action == 'show_month') // View by month { - $newparam=$param; // newparam is for birthday links - $newparam=preg_replace('/showbirthday=/i', 'showbirthday_=', $newparam); // To avoid replacement when replace day= is done - $newparam=preg_replace('/action=show_month&?/i', '', $newparam); - $newparam=preg_replace('/action=show_week&?/i', '', $newparam); - $newparam=preg_replace('/day=[0-9]+&?/i', '', $newparam); - $newparam=preg_replace('/month=[0-9]+&?/i', '', $newparam); - $newparam=preg_replace('/year=[0-9]+&?/i', '', $newparam); - $newparam=preg_replace('/viewcal=[0-9]+&?/i', '', $newparam); - $newparam=preg_replace('/showbirthday_=/i', 'showbirthday=', $newparam); // Restore correct parameter - $newparam.='&viewcal=1'; + $newparam = $param; // newparam is for birthday links + $newparam = preg_replace('/showbirthday=/i', 'showbirthday_=', $newparam); // To avoid replacement when replace day= is done + $newparam = preg_replace('/action=show_month&?/i', '', $newparam); + $newparam = preg_replace('/action=show_week&?/i', '', $newparam); + $newparam = preg_replace('/day=[0-9]+&?/i', '', $newparam); + $newparam = preg_replace('/month=[0-9]+&?/i', '', $newparam); + $newparam = preg_replace('/year=[0-9]+&?/i', '', $newparam); + $newparam = preg_replace('/viewcal=[0-9]+&?/i', '', $newparam); + $newparam = preg_replace('/showbirthday_=/i', 'showbirthday=', $newparam); // Restore correct parameter + $newparam .= '&viewcal=1'; print '
'; print ''; print ' '; - $i=0; + $i = 0; while ($i < 7) { print ' '."\n"; - $todayarray=dol_getdate($now, 'fast'); - $todaytms=dol_mktime(0, 0, 0, $todayarray['mon'], $todayarray['mday'], $todayarray['year']); + $todayarray = dol_getdate($now, 'fast'); + $todaytms = dol_mktime(0, 0, 0, $todayarray['mon'], $todayarray['mday'], $todayarray['year']); // In loops, tmpday contains day nb in current month (can be zero or negative for days of previous month) //var_dump($eventarray); - for ($iter_week = 0; $iter_week < 6 ; $iter_week++) + for ($iter_week = 0; $iter_week < 6; $iter_week++) { echo " \n"; for ($iter_day = 0; $iter_day < 7; $iter_day++) @@ -1085,8 +1085,8 @@ if (empty($action) || $action == 'show_month') // View by month /* Show days before the beginning of the current month (previous month) */ if ($tmpday <= 0) { - $style='cal_other_month cal_past'; - if ($iter_day == 6) $style.=' cal_other_month_right'; + $style = 'cal_other_month cal_past'; + if ($iter_day == 6) $style .= ' cal_other_month_right'; echo ' \n"; @@ -1095,12 +1095,12 @@ if (empty($action) || $action == 'show_month') // View by month elseif ($tmpday <= $max_day_in_month) { $curtime = dol_mktime(0, 0, 0, $month, $tmpday, $year); - $style='cal_current_month'; - if ($iter_day == 6) $style.=' cal_current_month_right'; - $today=0; - if ($todayarray['mday']==$tmpday && $todayarray['mon']==$month && $todayarray['year']==$year) $today=1; - if ($today) $style='cal_today'; - if ($curtime < $todaytms) $style.=' cal_past'; + $style = 'cal_current_month'; + if ($iter_day == 6) $style .= ' cal_current_month_right'; + $today = 0; + if ($todayarray['mday'] == $tmpday && $todayarray['mon'] == $month && $todayarray['year'] == $year) $today = 1; + if ($today) $style = 'cal_today'; + if ($curtime < $todaytms) $style .= ' cal_past'; //var_dump($todayarray['mday']."==".$tmpday." && ".$todayarray['mon']."==".$month." && ".$todayarray['year']."==".$year.' -> '.$style); echo ' \n"; @@ -1124,28 +1124,28 @@ if (empty($action) || $action == 'show_month') // View by month print ''; print ''; - print '' ; + print ''; } elseif ($action == 'show_week') // View by week { - $newparam=$param; // newparam is for birthday links - $newparam=preg_replace('/showbirthday=/i', 'showbirthday_=', $newparam); // To avoid replacement when replace day= is done - $newparam=preg_replace('/action=show_month&?/i', '', $newparam); - $newparam=preg_replace('/action=show_week&?/i', '', $newparam); - $newparam=preg_replace('/day=[0-9]+&?/i', '', $newparam); - $newparam=preg_replace('/month=[0-9]+&?/i', '', $newparam); - $newparam=preg_replace('/year=[0-9]+&?/i', '', $newparam); - $newparam=preg_replace('/viewweek=[0-9]+&?/i', '', $newparam); - $newparam=preg_replace('/showbirthday_=/i', 'showbirthday=', $newparam); // Restore correct parameter - $newparam.='&viewweek=1'; + $newparam = $param; // newparam is for birthday links + $newparam = preg_replace('/showbirthday=/i', 'showbirthday_=', $newparam); // To avoid replacement when replace day= is done + $newparam = preg_replace('/action=show_month&?/i', '', $newparam); + $newparam = preg_replace('/action=show_week&?/i', '', $newparam); + $newparam = preg_replace('/day=[0-9]+&?/i', '', $newparam); + $newparam = preg_replace('/month=[0-9]+&?/i', '', $newparam); + $newparam = preg_replace('/year=[0-9]+&?/i', '', $newparam); + $newparam = preg_replace('/viewweek=[0-9]+&?/i', '', $newparam); + $newparam = preg_replace('/showbirthday_=/i', 'showbirthday=', $newparam); // Restore correct parameter + $newparam .= '&viewweek=1'; print '
'; print '
'; - $numdayinweek=(($i+(isset($conf->global->MAIN_START_WEEK)?$conf->global->MAIN_START_WEEK:1)) % 7); - if (! empty($conf->dol_optimize_smallscreen)) + $numdayinweek = (($i + (isset($conf->global->MAIN_START_WEEK) ? $conf->global->MAIN_START_WEEK : 1)) % 7); + if (!empty($conf->dol_optimize_smallscreen)) { - $labelshort=array(0=>'SundayMin',1=>'MondayMin',2=>'TuesdayMin',3=>'WednesdayMin',4=>'ThursdayMin',5=>'FridayMin',6=>'SaturdayMin'); + $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); @@ -1072,12 +1072,12 @@ if (empty($action) || $action == 'show_month') // View by month } echo '
'; show_day_events($db, $max_day_in_prev_month + $tmpday, $prev_month, $prev_year, $month, $style, $eventarray, $maxprint, $maxnbofchar, $newparam); echo " '; show_day_events($db, $tmpday, $month, $year, $month, $style, $eventarray, $maxprint, $maxnbofchar, $newparam); @@ -1109,8 +1109,8 @@ if (empty($action) || $action == 'show_month') // View by month /* Show days after the current month (next month) */ else { - $style='cal_other_month'; - if ($iter_day == 6) $style.=' cal_other_month_right'; + $style = 'cal_other_month'; + if ($iter_day == 6) $style .= ' cal_other_month_right'; echo ' '; show_day_events($db, $tmpday - $max_day_in_month, $next_month, $next_year, $month, $style, $eventarray, $maxprint, $maxnbofchar, $newparam); echo "
'; print ' '; - $i=0; + $i = 0; while ($i < 7) { - echo ' \n"; + echo ' \n"; $i++; } echo " \n"; @@ -1161,12 +1161,12 @@ elseif ($action == 'show_week') // View by week $tmpmonth = $tmparray['mon']; $tmpyear = $tmparray['year']; - $style='cal_current_month'; - if ($iter_day == 6) $style.=' cal_other_month_right'; - $today=0; - $todayarray=dol_getdate($now, 'fast'); - if ($todayarray['mday']==$tmpday && $todayarray['mon']==$tmpmonth && $todayarray['year']==$tmpyear) $today=1; - if ($today) $style='cal_today'; + $style = 'cal_current_month'; + if ($iter_day == 6) $style .= ' cal_other_month_right'; + $today = 0; + $todayarray = dol_getdate($now, 'fast'); + if ($todayarray['mday'] == $tmpday && $todayarray['mon'] == $tmpmonth && $todayarray['year'] == $tmpyear) $today = 1; + if ($today) $style = 'cal_today'; echo ' '; // Prefix - if (! empty($conf->global->SOCIETE_USEPREFIX)) // Old not used prefix field + if (!empty($conf->global->SOCIETE_USEPREFIX)) // Old not used prefix field { print ''; } @@ -298,13 +298,13 @@ if ($object->id > 0) if ($mysoc->country_code == 'ES') { // Local Taxes - if ($mysoc->localtax1_assuj=="1") + if ($mysoc->localtax1_assuj == "1") { print ''; } - if ($mysoc->localtax1_assuj=="1") + if ($mysoc->localtax1_assuj == "1") { print '"; print ''; - if (! empty($conf->banque->enabled)) + if (!empty($conf->banque->enabled)) { // Compte bancaire par défaut print '
'.$langs->trans("Day".(($i+(isset($conf->global->MAIN_START_WEEK)?$conf->global->MAIN_START_WEEK:1)) % 7))."'.$langs->trans("Day".(($i + (isset($conf->global->MAIN_START_WEEK) ? $conf->global->MAIN_START_WEEK : 1)) % 7))."
'; show_day_events($db, $tmpday, $tmpmonth, $tmpyear, $month, $style, $eventarray, 0, $maxnbofchar, $newparam, 1, 300); @@ -1179,24 +1179,24 @@ elseif ($action == 'show_week') // View by week echo ''; echo ''; - echo '' ; + echo ''; } else // View by day { - $newparam=$param; // newparam is for birthday links - $newparam=preg_replace('/action=show_month&?/i', '', $newparam); - $newparam=preg_replace('/action=show_week&?/i', '', $newparam); - $newparam=preg_replace('/viewday=[0-9]+&?/i', '', $newparam); - $newparam.='&viewday=1'; + $newparam = $param; // newparam is for birthday links + $newparam = preg_replace('/action=show_month&?/i', '', $newparam); + $newparam = preg_replace('/action=show_week&?/i', '', $newparam); + $newparam = preg_replace('/viewday=[0-9]+&?/i', '', $newparam); + $newparam .= '&viewday=1'; // Code to show just one day - $style='cal_current_month cal_current_month_oneday'; - $today=0; - $todayarray=dol_getdate($now, 'fast'); - if ($todayarray['mday']==$day && $todayarray['mon']==$month && $todayarray['year']==$year) $today=1; + $style = 'cal_current_month cal_current_month_oneday'; + $today = 0; + $todayarray = dol_getdate($now, 'fast'); + if ($todayarray['mday'] == $day && $todayarray['mon'] == $month && $todayarray['year'] == $year) $today = 1; //if ($today) $style='cal_today'; - $timestamp=dol_mktime(12, 0, 0, $month, $day, $year); - $arraytimestamp=dol_getdate($timestamp); + $timestamp = dol_mktime(12, 0, 0, $month, $day, $year); + $arraytimestamp = dol_getdate($timestamp); //echo ''; echo '
'; @@ -1221,14 +1221,14 @@ else // View by day $useviewhour = 0; if ($useviewhour) { - print '
'; // You can use div-table-responsive-no-min if you dont need reserved height for your table + 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 + $maxheightwin = (isset($_SESSION["dol_screenheight"]) && $_SESSION["dol_screenheight"] > 500) ? ($_SESSION["dol_screenheight"] - 200) : 660; // Also into index.php file echo '
'; echo '
'; - $maxnbofchar=80; + $maxnbofchar = 80; $tmp = explode('-', $conf->global->MAIN_DEFAULT_WORKING_HOURS); $minhour = round($tmp[0], 0); @@ -1242,7 +1242,7 @@ else // View by day while ($i < 24) { echo '
'."\n"; - echo '
'.dol_print_date($i*3600, 'hour', 'gmt').'
'; + echo '
'.dol_print_date($i * 3600, 'hour', 'gmt').'
'; echo '
'; echo "
\n"; echo "
\n"; @@ -1258,7 +1258,7 @@ else // View by day } else { - print '
'; // You can use div-table-responsive-no-min if you dont need reserved height for your table + print '
'; // You can use div-table-responsive-no-min if you dont need reserved height for your table show_day_events($db, $day, $month, $year, $month, $style, $eventarray, 0, $maxnbofchar, $newparam, 1, 300, 0); @@ -1294,7 +1294,7 @@ $db->close(); function show_day_events($db, $day, $month, $year, $monthshown, $style, &$eventarray, $maxprint = 0, $maxnbofchar = 16, $newparam = '', $showinfo = 0, $minheight = 60, $nonew = 0) { global $user, $conf, $langs; - global $action, $filter, $filtert, $status, $actioncode, $usergroup; // Filters used into search form + global $action, $filter, $filtert, $status, $actioncode, $usergroup; // Filters used into search form global $theme_datacolor; global $cachethirdparties, $cachecontacts, $cacheusers, $colorindexused; @@ -1319,11 +1319,11 @@ function show_day_events($db, $day, $month, $year, $monthshown, $style, &$eventa print '
'; if ($user->rights->agenda->myactions->create || $user->rights->agenda->allactions->create) { - $newparam.='&month='.str_pad($month, 2, "0", STR_PAD_LEFT).'&year='.$year; + $newparam .= '&month='.str_pad($month, 2, "0", STR_PAD_LEFT).'&year='.$year; //$param='month='.$monthshown.'&year='.$year; - $hourminsec='100000'; - print ''; + $hourminsec = '100000'; + print ''; print img_picto($langs->trans("NewAction"), 'edit_add.png'); print ''; } @@ -1341,11 +1341,11 @@ function show_day_events($db, $day, $month, $year, $monthshown, $style, &$eventa print '
'; //$curtime = dol_mktime (0, 0, 0, $month, $day, $year); - $i=0; $numother=0; $numbirthday=0; $numical=0; $numicals=array(); - $ymd=sprintf("%04d", $year).sprintf("%02d", $month).sprintf("%02d", $day); + $i = 0; $numother = 0; $numbirthday = 0; $numical = 0; $numicals = array(); + $ymd = sprintf("%04d", $year).sprintf("%02d", $month).sprintf("%02d", $day); - $colorindexused[$user->id] = 0; // Color index for current user (user->id) is always 0 - $nextindextouse=is_array($colorindexused)?count($colorindexused):0; // At first run this is 0, so fist user has 0, next 1, ... + $colorindexused[$user->id] = 0; // Color index for current user (user->id) is always 0 + $nextindextouse = is_array($colorindexused) ?count($colorindexused) : 0; // At first run this is 0, so fist user has 0, next 1, ... //var_dump($colorindexused); foreach ($eventarray as $daykey => $notused) @@ -1353,117 +1353,117 @@ function show_day_events($db, $day, $month, $year, $monthshown, $style, &$eventa $annee = date('Y', $daykey); $mois = date('m', $daykey); $jour = date('d', $daykey); - if ($day==$jour && $month==$mois && $year==$annee) + 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 ($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); + $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; + $color = -1; $cssclass = ''; $colorindex = -1; if (in_array($user->id, $keysofuserassigned)) { - $cssclass='family_mytasks'; + $cssclass = 'family_mytasks'; if (empty($cacheusers[$event->userownerid])) { - $newuser=new User($db); + $newuser = new User($db); $newuser->fetch($event->userownerid); - $cacheusers[$event->userownerid]=$newuser; + $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; + 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)])) { + if (!empty($event->icalname)) { + if (!isset($numicals[dol_string_nospecial($event->icalname)])) { $numicals[dol_string_nospecial($event->icalname)] = 0; } $numicals[dol_string_nospecial($event->icalname)]++; } - $color=($event->icalcolor?$event->icalcolor:-1); - $cssclass=(! empty($event->icalname)?'family_ext'.md5($event->icalname):'family_other'); + $color = ($event->icalcolor ? $event->icalcolor : -1); + $cssclass = (!empty($event->icalname) ? 'family_ext'.md5($event->icalname) : 'family_other'); } elseif ($event->type_code == 'BIRTHDAY') { - $numbirthday++; $colorindex=2; $cssclass='family_birthday unmovable'; $color=sprintf("%02x%02x%02x", $theme_datacolor[$colorindex][0], $theme_datacolor[$colorindex][1], $theme_datacolor[$colorindex][2]); + $numbirthday++; $colorindex = 2; $cssclass = 'family_birthday unmovable'; $color = sprintf("%02x%02x%02x", $theme_datacolor[$colorindex][0], $theme_datacolor[$colorindex][1], $theme_datacolor[$colorindex][2]); } else { $numother++; - $color=($event->icalcolor?$event->icalcolor:-1); - $cssclass=(! empty($event->icalname)?'family_ext'.md5($event->icalname):'family_other'); + $color = ($event->icalcolor ? $event->icalcolor : -1); + $cssclass = (!empty($event->icalname) ? 'family_ext'.md5($event->icalname) : 'family_other'); if (empty($cacheusers[$event->userownerid])) { - $newuser=new User($db); + $newuser = new User($db); $newuser->fetch($event->userownerid); - $cacheusers[$event->userownerid]=$newuser; + $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; + if (!empty($cacheusers[$event->userownerid]->color)) $color = $cacheusers[$event->userownerid]->color; } if ($color < 0) // Color was not set on user card. Set color according to color index. { // Define color index if not yet defined - $idusertouse=($event->userownerid?$event->userownerid:0); + $idusertouse = ($event->userownerid ? $event->userownerid : 0); if (isset($colorindexused[$idusertouse])) { - $colorindex=$colorindexused[$idusertouse]; // Color already assigned to this user + $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 - $color=sprintf("%02x%02x%02x", $theme_datacolor[$colorindex][0], $theme_datacolor[$colorindex][1], $theme_datacolor[$colorindex][2]); + $color = sprintf("%02x%02x%02x", $theme_datacolor[$colorindex][0], $theme_datacolor[$colorindex][1], $theme_datacolor[$colorindex][2]); } - $cssclass=$cssclass.' '.$cssclass.'_day_'.$ymd; + $cssclass = $cssclass.' '.$cssclass.'_day_'.$ymd; // Defined style to disable drag and drop feature - if ($event->type_code =='AC_OTH_AUTO') + if ($event->type_code == 'AC_OTH_AUTO') { - $cssclass.= " unmovable"; + $cssclass .= " unmovable"; } elseif ($event->type_code == 'ICALEVENT') { - $cssclass.= " unmovable"; + $cssclass .= " unmovable"; } elseif ($event->date_end_in_calendar && date('Ymd', $event->date_start_in_calendar) != date('Ymd', $event->date_end_in_calendar)) { $tmpyearend = date('Y', $event->date_end_in_calendar); $tmpmonthend = date('m', $event->date_end_in_calendar); $tmpdayend = date('d', $event->date_end_in_calendar); if ($tmpyearend == $annee && $tmpmonthend == $mois && $tmpdayend == $jour) { - $cssclass.= " unmovable"; + $cssclass .= " unmovable"; } } - else{ + else { if ($user->rights->agenda->allactions->create || (($event->authorid == $user->id || $event->userownerid == $user->id) && $user->rights->agenda->myactions->create)) { - $cssclass.= " movable cursormove"; - }else{ - $cssclass.= " unmovable"; + $cssclass .= " movable cursormove"; + } else { + $cssclass .= " unmovable"; } } - $h=''; $nowrapontd=1; - if ($action == 'show_day') { $h='height: 100%; '; $nowrapontd=0; } - if ($action == 'show_week') { $h='height: 100%; '; $nowrapontd=0; } + $h = ''; $nowrapontd = 1; + if ($action == 'show_day') { $h = 'height: 100%; '; $nowrapontd = 0; } + if ($action == 'show_week') { $h = 'height: 100%; '; $nowrapontd = 0; } // Show rect of event print "\n"; @@ -1476,25 +1476,32 @@ function show_day_events($db, $day, $month, $year, $monthshown, $style, &$eventa //var_dump($event->userassigned); //var_dump($event->transparency); - print '
transparency)?' cal_event_notbusy':' cal_event_busy'); + //if (empty($event->transparency) && empty($conf->global->AGENDA_NO_TRANSPARENT_ON_NOT_BUSY)) print ' opacitymedium'; // Not busy + 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)) { - print 'border: 2px solid #'.$color.';'; + print 'border: 2px solid #'.$colortouse.';'; } else { - print 'background: #'.$color.';'; - 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($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).'));'; //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;"'; //print 'border: 1px solid #ccc" width="100%"'; print '">'; print ''; - print ''; // Status - Percent - $withstatus=0; + $withstatus = 0; if ($event->type_code != 'BIRTHDAY' && $event->type_code != 'ICALEVENT') { - $withstatus=1; - if ($event->percentage >= 0) $withstatus=2; + $withstatus = 1; + if ($event->percentage >= 0) $withstatus = 2; } - print '
'; + print ''; - $daterange=''; + $daterange = ''; if ($event->type_code == 'BIRTHDAY') // It's a birthday { @@ -1521,11 +1528,11 @@ function show_day_events($db, $day, $month, $year, $monthshown, $style, &$eventa // Hour start if ($tmpyearstart == $annee && $tmpmonthstart == $mois && $tmpdaystart == $jour) { - $daterange.=dol_print_date($event->date_start_in_calendar, '%H:%M'); // Il faudrait utiliser ici tzuser, mais si on ne peut pas car qd on rentre un date dans fiche action, en input la conversion local->gmt se base sur le TZ server et non user + $daterange .= dol_print_date($event->date_start_in_calendar, '%H:%M'); // Il faudrait utiliser ici tzuser, mais si on ne peut pas car qd on rentre un date dans fiche action, en input la conversion local->gmt se base sur le TZ server et non user if ($event->date_end_in_calendar && $event->date_start_in_calendar != $event->date_end_in_calendar) { if ($tmpyearstart == $tmpyearend && $tmpmonthstart == $tmpmonthend && $tmpdaystart == $tmpdayend) - $daterange.='-'; + $daterange .= '-'; //else //print '...'; } @@ -1534,14 +1541,14 @@ function show_day_events($db, $day, $month, $year, $monthshown, $style, &$eventa { if ($tmpyearstart != $tmpyearend || $tmpmonthstart != $tmpmonthend || $tmpdaystart != $tmpdayend) { - $daterange.='...'; + $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, '%H:%M'); // Il faudrait utiliser ici tzuser, mais si on ne peut pas car qd on rentre un date dans fiche action, en input la conversion local->gmt se base sur le TZ server et non user + $daterange .= dol_print_date($event->date_end_in_calendar, '%H:%M'); // Il faudrait utiliser ici tzuser, mais si on ne peut pas car qd on rentre un date dans fiche action, en input la conversion local->gmt se base sur le TZ server et non user } } else @@ -1554,34 +1561,34 @@ function show_day_events($db, $day, $month, $year, $monthshown, $style, &$eventa // Show title $titletoshow = $daterange; - $titletoshow.=($titletoshow?' ':'').($event->label?$event->label:$event->libelle); + $titletoshow .= ($titletoshow ? ' ' : '').($event->label ? $event->label : $event->libelle); if ($event->type_code == 'ICALEVENT') print $titletoshow; else { - $savlabel=$event->label?$event->label:$event->libelle; - $event->label=$titletoshow; - $event->libelle=$titletoshow; + $savlabel = $event->label ? $event->label : $event->libelle; + $event->label = $titletoshow; + $event->libelle = $titletoshow; print $event->getNomUrl(0, $maxnbofchar, 'cal_event', '', 0, 0); - $event->label=$savlabel; - $event->libelle=$savlabel; + $event->label = $savlabel; + $event->libelle = $savlabel; } // Loop on each assigned user - $listofusertoshow=''; - $posuserassigned=0; - foreach($event->userassigned as $tmpid => $tmpdata) + $listofusertoshow = ''; + $posuserassigned = 0; + foreach ($event->userassigned as $tmpid => $tmpdata) { - if (! $posuserassigned && $titletoshow) $listofusertoshow.='
'; + if (!$posuserassigned && $titletoshow) $listofusertoshow .= '
'; $posuserassigned++; if (empty($cacheusers[$tmpid])) { - $newuser=new User($db); + $newuser = new User($db); $newuser->fetch($tmpid); - $cacheusers[$tmpid]=$newuser; + $cacheusers[$tmpid] = $newuser; } - $listofusertoshow.=$cacheusers[$tmpid]->getNomUrl(-3, '', 0, 0, 0, 0, '', 'paddingright valigntextbottom'); + $listofusertoshow .= $cacheusers[$tmpid]->getNomUrl(-3, '', 0, 0, 0, 0, '', 'paddingright valigntextbottom'); } print $listofusertoshow; @@ -1591,35 +1598,35 @@ function show_day_events($db, $day, $month, $year, $monthshown, $style, &$eventa $contact_id = ($event->contact_id > 0 ? $event->contact_id : ((is_object($event->contact) && $event->cotact->id > 0) ? $event->contact->id : 0)); // If action related to company / contact - $linerelatedto=''; + $linerelatedto = ''; if ($thirdparty_id > 0) { - if (! isset($cachethirdparties[$thirdparty_id]) || ! is_object($cachethirdparties[$thirdparty_id])) + if (!isset($cachethirdparties[$thirdparty_id]) || !is_object($cachethirdparties[$thirdparty_id])) { - $thirdparty=new Societe($db); + $thirdparty = new Societe($db); $thirdparty->fetch($thirdparty_id); - $cachethirdparties[$thirdparty_id]=$thirdparty; + $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 (!empty($contact_id) && $contact_id > 0) { - if (! is_object($cachecontacts[$contact_id])) + if (!is_object($cachecontacts[$contact_id])) { - $contact=new Contact($db); + $contact = new Contact($db); $contact->fetch($contact_id); - $cachecontacts[$contact_id]=$contact; + $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.='
'; - $linerelatedto.=dolGetElementUrl($event->fk_element, $event->elementtype, 1); + if ($linerelatedto) $linerelatedto .= '
'; + $linerelatedto .= dolGetElementUrl($event->fk_element, $event->elementtype, 1); } if ($linerelatedto) print '
'.$linerelatedto; } @@ -1636,13 +1643,13 @@ function show_day_events($db, $day, $month, $year, $monthshown, $style, &$eventa print '
'; + print ''; if ($withstatus) print $event->getLibStatut(3, 1); else print ' '; print '
'; @@ -1653,9 +1660,9 @@ function show_day_events($db, $day, $month, $year, $monthshown, $style, &$eventa { print ''.img_picto("all", "1downarrow_selected.png").' ...'; print ' +'.(count($eventarray[$daykey])-$maxprint); print ''; @@ -1667,9 +1674,9 @@ function show_day_events($db, $day, $month, $year, $monthshown, $style, &$eventa break; } } - if (! $i) print ' '; + if (!$i) print ' '; - if (! empty($conf->global->MAIN_JS_SWITCH_AGENDA) && $i > $maxprint && $maxprint) + if (!empty($conf->global->MAIN_JS_SWITCH_AGENDA) && $i > $maxprint && $maxprint) { print '
'.img_picto("all", "1downarrow_selected.png").' +'.$langs->trans("More").'...
'; //print ' +'.(count($eventarray[$daykey])-$maxprint); @@ -1688,9 +1695,9 @@ function show_day_events($db, $day, $month, $year, $monthshown, $style, &$eventa print ''."\n"; } - print ''; // td tr + print ''; // td tr - print ''; // table + print ''; // table print "\n"; } @@ -1705,12 +1712,12 @@ function show_day_events($db, $day, $month, $year, $monthshown, $style, &$eventa */ function dol_color_minus($color, $minus, $minusunit = 16) { - $newcolor=$color; + $newcolor = $color; 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)); + $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)); } else { @@ -1719,7 +1726,6 @@ function dol_color_minus($color, $minus, $minusunit = 16) return $newcolor; } - /** * Sort events by date * @@ -1729,24 +1735,52 @@ function dol_color_minus($color, $minus, $minusunit = 16) */ function sort_events_by_date($a, $b) { - if($a->datep != $b->datep) + // datep => Event start time + // datef => Event end time + + // Events have different start time + if ($a->datep !== $b->datep) { return $a->datep - $b->datep; } - // If both events have the same start time, longest first - - if(! is_numeric($b->datef)) + // Events have same start time and no end time + if ((!is_numeric($b->datef)) || (!is_numeric($a->datef))) { - // when event B have no end timestamp, event B should sort be before event A (All day events on top) - return 1; + return sort_events_by_percentage($a, $b); } - if(! is_numeric($a->datef)) + // Events have the same start time and same end time + if ($b->datef === $a->datef) + { + return sort_events_by_percentage($a, $b); + } + + // Events have the same start time, but have different end time -> longest event first + return $b->datef - $a->datef; +} + +/** + * Sort events by percentage + * + * @param object $a Event A + * @param object $b Event B + * @return int < 0 if event A should be before event B, > 0 otherwise, 0 if they have the exact same percentage + */ +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) { - // when event A have no end timestamp , event A should sort be before event B (All day events on top) return -1; } - return $b->datef - $a->datef; + if ($b->percentage < 0) + { + return 1; + } + + return $b->percentage - $a->percentage; } diff --git a/htdocs/comm/action/list.php b/htdocs/comm/action/list.php index 48faa5ca2c0..fdaac89eda0 100644 --- a/htdocs/comm/action/list.php +++ b/htdocs/comm/action/list.php @@ -26,7 +26,7 @@ * \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'; @@ -37,43 +37,43 @@ include_once DOL_DOCUMENT_ROOT.'/core/class/html.formactions.class.php'; require_once DOL_DOCUMENT_ROOT.'/core/class/extrafields.class.php'; // Load translation files required by the page -$langs->loadLangs(array("users","companies","agenda","commercial")); +$langs->loadLangs(array("users", "companies", "agenda", "commercial")); -$action=GETPOST('action', 'alpha'); -$contextpage=GETPOST('contextpage', 'aZ')?GETPOST('contextpage', 'aZ'):'actioncommlist'; // To manage different context of search -$resourceid=GETPOST("search_resourceid", "int")?GETPOST("search_resourceid", "int"):GETPOST("resourceid", "int"); -$pid=GETPOST("search_projectid", 'int', 3)?GETPOST("search_projectid", 'int', 3):GETPOST("projectid", 'int', 3); -$status=(GETPOST("search_status", 'alpha') != '')?GETPOST("search_status", 'alpha'):GETPOST("status", 'alpha'); -$type=GETPOST('search_type', 'alphanohtml')?GETPOST('search_type', 'alphanohtml'):GETPOST('type', 'alphanohtml'); +$action = GETPOST('action', 'alpha'); +$contextpage = GETPOST('contextpage', 'aZ') ?GETPOST('contextpage', 'aZ') : 'actioncommlist'; // To manage different context of search +$resourceid = GETPOST("search_resourceid", "int") ?GETPOST("search_resourceid", "int") : GETPOST("resourceid", "int"); +$pid = GETPOST("search_projectid", 'int', 3) ?GETPOST("search_projectid", 'int', 3) : GETPOST("projectid", 'int', 3); +$status = (GETPOST("search_status", 'alpha') != '') ?GETPOST("search_status", 'alpha') : GETPOST("status", 'alpha'); +$type = GETPOST('search_type', 'alphanohtml') ?GETPOST('search_type', 'alphanohtml') : GETPOST('type', 'alphanohtml'); $optioncss = GETPOST('optioncss', 'alpha'); -$year=GETPOST("year", 'int'); -$month=GETPOST("month", 'int'); -$day=GETPOST("day", 'int'); +$year = GETPOST("year", 'int'); +$month = GETPOST("month", 'int'); +$day = GETPOST("day", 'int'); // Set actioncode (this code must be same for setting actioncode into peruser, listacton and index) if (GETPOST('search_actioncode', 'array')) { - $actioncode=GETPOST('search_actioncode', 'array', 3); - if (! count($actioncode)) $actioncode='0'; + $actioncode = GETPOST('search_actioncode', 'array', 3); + 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)); + $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); -$search_id=GETPOST('search_id', 'alpha'); -$search_title=GETPOST('search_title', 'alpha'); -$search_note=GETPOST('search_note', 'alpha'); +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'); -$dateselect=dol_mktime(0, 0, 0, GETPOST('dateselectmonth', 'int'), GETPOST('dateselectday', 'int'), GETPOST('dateselectyear', 'int')); -$datestart=dol_mktime(0, 0, 0, GETPOST('datestartmonth', 'int'), GETPOST('datestartday', 'int'), GETPOST('datestartyear', 'int')); -$dateend=dol_mktime(0, 0, 0, GETPOST('dateendmonth', 'int'), GETPOST('dateendday', 'int'), GETPOST('dateendyear', 'int')); -if ($status == '' && ! isset($_GET['status']) && ! isset($_POST['status'])) $status=(empty($conf->global->AGENDA_DEFAULT_FILTER_STATUS)?'':$conf->global->AGENDA_DEFAULT_FILTER_STATUS); -if (empty($action) && ! isset($_GET['action']) && ! isset($_POST['action'])) $action=(empty($conf->global->AGENDA_DEFAULT_VIEW)?'show_month':$conf->global->AGENDA_DEFAULT_VIEW); +$dateselect = dol_mktime(0, 0, 0, GETPOST('dateselectmonth', 'int'), GETPOST('dateselectday', 'int'), GETPOST('dateselectyear', 'int')); +$datestart = dol_mktime(0, 0, 0, GETPOST('datestartmonth', 'int'), GETPOST('datestartday', 'int'), GETPOST('datestartyear', 'int')); +$dateend = dol_mktime(0, 0, 0, GETPOST('dateendmonth', 'int'), GETPOST('dateendday', 'int'), GETPOST('dateendyear', 'int')); +if ($status == '' && !isset($_GET['status']) && !isset($_POST['status'])) $status = (empty($conf->global->AGENDA_DEFAULT_FILTER_STATUS) ? '' : $conf->global->AGENDA_DEFAULT_FILTER_STATUS); +if (empty($action) && !isset($_GET['action']) && !isset($_POST['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); -$usergroup = GETPOST("search_usergroup", "int", 3)?GETPOST("search_usergroup", "int", 3):GETPOST("usergroup", "int", 3); -$showbirthday = empty($conf->use_javascript_ajax)?(GETPOST("search_showbirthday", "int")?GETPOST("search_showbirthday", "int"):GETPOST("showbirthday", "int")):1; +$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); +$usergroup = GETPOST("search_usergroup", "int", 3) ?GETPOST("search_usergroup", "int", 3) : GETPOST("usergroup", "int", 3); +$showbirthday = empty($conf->use_javascript_ajax) ? (GETPOST("search_showbirthday", "int") ?GETPOST("search_showbirthday", "int") : GETPOST("showbirthday", "int")) : 1; // Initialize technical object to manage hooks of page. Note that conf->hooks_modules contains array of hook context $object = new ActionComm($db); @@ -84,45 +84,45 @@ $extrafields = new ExtraFields($db); // fetch optionals attributes and labels $extrafields->fetch_name_optionals_label($object->table_element); -$search_array_options=$extrafields->getOptionalsFromPost($object->table_element, '', 'search_'); +$search_array_options = $extrafields->getOptionalsFromPost($object->table_element, '', 'search_'); // If not choice done on calendar owner, we filter on user. if (empty($filtert) && empty($conf->global->AGENDA_ALL_CALENDARS)) { - $filtert=$user->id; + $filtert = $user->id; } -$limit = GETPOST('limit', 'int')?GETPOST('limit', 'int'):$conf->liste_limit; +$limit = GETPOST('limit', 'int') ?GETPOST('limit', 'int') : $conf->liste_limit; $sortfield = GETPOST("sortfield", 'alpha'); $sortorder = GETPOST("sortorder", 'alpha'); $page = GETPOST("page", 'int'); -if ($page == -1 || $page == null) { $page = 0 ; } -$offset = $limit * $page ; -if (! $sortorder) +if ($page == -1 || $page == null) { $page = 0; } +$offset = $limit * $page; +if (!$sortorder) { - $sortorder="DESC,DESC"; - if ($status == 'todo') $sortorder="DESC,DESC"; + $sortorder = "DESC,DESC"; + if ($status == 'todo') $sortorder = "DESC,DESC"; } -if (! $sortfield) +if (!$sortfield) { - $sortfield="a.datep,a.id"; - if ($status == 'todo') $sortfield="a.datep,a.id"; + $sortfield = "a.datep,a.id"; + if ($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; +$socid = GETPOST("search_socid", 'int') ?GETPOST("search_socid", 'int') : GETPOST("socid", 'int'); +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 +$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 { - $filtert=$user->id; + $filtert = $user->id; } -$arrayfields=array( +$arrayfields = array( 'a.id'=>array('label'=>"Ref", 'checked'=>1), 'owner'=>array('label'=>"Owner", 'checked'=>1), 'c.libelle'=>array('label'=>"Type", 'checked'=>1), @@ -132,7 +132,7 @@ $arrayfields=array( 'a.datep2'=>array('label'=>"DateEnd", 'checked'=>1), 's.nom'=>array('label'=>"ThirdParty", 'checked'=>1), 'a.fk_contact'=>array('label'=>"Contact", 'checked'=>1), - 'a.fk_element'=>array('label'=>"LinkedObject", 'checked'=>0, 'enabled'=>(! empty($conf->global->AGENDA_SHOW_LINKED_OBJECT))), + 'a.fk_element'=>array('label'=>"LinkedObject", 'checked'=>0, 'enabled'=>(!empty($conf->global->AGENDA_SHOW_LINKED_OBJECT))), 'a.percent'=>array('label'=>"Status", 'checked'=>1, 'position'=>1000), 'a.datec'=>array('label'=>'DateCreation', 'checked'=>0), 'a.tms'=>array('label'=>'DateModification', 'checked'=>0) @@ -140,10 +140,10 @@ $arrayfields=array( // 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) + 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], 'checked'=>(($extrafields->attributes[$object->table_element]['list'][$key]<0)?0:1), 'position'=>$extrafields->attributes[$object->table_element]['pos'][$key], 'enabled'=>(abs($extrafields->attributes[$object->table_element]['list'][$key])!=3 && $extrafields->attributes[$object->table_element]['perms'][$key])); + if (!empty($extrafields->attributes[$object->table_element]['list'][$key])) + $arrayfields["ef.".$key] = array('label'=>$extrafields->attributes[$object->table_element]['label'][$key], 'checked'=>(($extrafields->attributes[$object->table_element]['list'][$key] < 0) ? 0 : 1), 'position'=>$extrafields->attributes[$object->table_element]['pos'][$key], 'enabled'=>(abs($extrafields->attributes[$object->table_element]['list'][$key]) != 3 && $extrafields->attributes[$object->table_element]['perms'][$key])); } } $object->fields = dol_sort_array($object->fields, 'position'); @@ -156,12 +156,12 @@ $arrayfields = dol_sort_array($arrayfields, 'position'); if (GETPOST("viewcal") || GETPOST("viewweek") || GETPOST("viewday")) { - $param=''; + $param = ''; if (is_array($_POST)) { - foreach($_POST as $key => $val) + foreach ($_POST as $key => $val) { - $param.='&'.$key.'='.urlencode($val); + $param .= '&'.$key.'='.urlencode($val); } } //print $param; @@ -169,8 +169,8 @@ if (GETPOST("viewcal") || GETPOST("viewweek") || GETPOST("viewday")) exit; } -$parameters=array('id'=>$socid); -$reshook=$hookmanager->executeHooks('doActions', $parameters, $object, $action); // Note that $action and $object may have been modified by some hooks +$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'); // Selection of new fields @@ -179,13 +179,13 @@ include DOL_DOCUMENT_ROOT.'/core/actions_changeselectedfields.inc.php'; if (GETPOST('button_removefilter_x', 'alpha') || GETPOST('button_removefilter.x', 'alpha') || GETPOST('button_removefilter', 'alpha')) // All tests are required to be compatible with all browsers { //$actioncode=''; - $search_id=''; - $search_title=''; - $search_note=''; - $datestart=''; - $dateend=''; - $status=''; - $search_array_options=array(); + $search_id = ''; + $search_title = ''; + $search_note = ''; + $datestart = ''; + $dateend = ''; + $status = ''; + $search_array_options = array(); } @@ -193,154 +193,154 @@ if (GETPOST('button_removefilter_x', 'alpha') || GETPOST('button_removefilter.x' * View */ -$form=new Form($db); -$userstatic=new User($db); -$formactions=new FormActions($db); +$form = new Form($db); +$userstatic = new User($db); +$formactions = new FormActions($db); $nav = ''; $nav .= $form->selectDate($dateselect, 'dateselect', 0, 0, 1, '', 1, 0); -$nav .=' '; +$nav .= ' '; -$now=dol_now(); +$now = dol_now(); -$help_url='EN:Module_Agenda_En|FR:Module_Agenda|ES:M&omodulodulo_Agenda'; +$help_url = 'EN:Module_Agenda_En|FR:Module_Agenda|ES:M&omodulodulo_Agenda'; llxHeader('', $langs->trans("Agenda"), $help_url); // Define list of all external calendars -$listofextcals=array(); +$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); +$param = ''; +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); + if (is_array($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 != '' && $status > -1) $param.="&search_status=".urlencode($status); -if ($filter) $param.="&search_filter=".urlencode($filter); -if ($filtert) $param.="&search_filtert=".urlencode($filtert); -if ($socid) $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 ($usergroup) $param.="&search_usergroup=".urlencode($usergroup); -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 ($status != '' && $status > -1) $param .= "&search_status=".urlencode($status); +if ($filter) $param .= "&search_filter=".urlencode($filter); +if ($filtert) $param .= "&search_filtert=".urlencode($filtert); +if ($socid) $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 ($usergroup) $param .= "&search_usergroup=".urlencode($usergroup); +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'; $sql = "SELECT"; -if ($usergroup > 0) $sql.=" DISTINCT"; -$sql.= " s.nom as societe, s.rowid as socid, s.client, s.email as socemail,"; -$sql.= " a.id, a.label, a.note, a.datep as dp, a.datep2 as dp2, a.fulldayevent, a.location,"; -$sql.= ' a.fk_user_author,a.fk_user_action,'; -$sql.= " a.fk_contact, a.note, a.percent as percent,"; -$sql.= " a.fk_element, a.elementtype, a.datec, a.tms as datem,"; -$sql.= " c.code as type_code, c.libelle as type_label,"; -$sql.= " sp.lastname, sp.firstname, sp.email, sp.phone, sp.address, sp.phone as phone_pro, sp.phone_mobile, sp.phone_perso, sp.fk_pays as country_id"; +if ($usergroup > 0) $sql .= " DISTINCT"; +$sql .= " s.nom as societe, s.rowid as socid, s.client, s.email as socemail,"; +$sql .= " a.id, a.label, a.note, a.datep as dp, a.datep2 as dp2, a.fulldayevent, a.location,"; +$sql .= ' a.fk_user_author,a.fk_user_action,'; +$sql .= " a.fk_contact, a.note, a.percent as percent,"; +$sql .= " a.fk_element, a.elementtype, a.datec, a.tms as datem,"; +$sql .= " c.code as type_code, c.libelle as type_label,"; +$sql .= " sp.lastname, sp.firstname, sp.email, sp.phone, sp.address, sp.phone as phone_pro, sp.phone_mobile, sp.phone_perso, sp.fk_pays as country_id"; // 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 : ''); +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 : ''); } // Add fields from hooks -$parameters=array(); -$reshook=$hookmanager->executeHooks('printFieldListSelect', $parameters); // Note that $action and $object may have been modified by hook -$sql.=$hookmanager->resPrint; +$parameters = array(); +$reshook = $hookmanager->executeHooks('printFieldListSelect', $parameters); // Note that $action and $object may have been modified by hook +$sql .= $hookmanager->resPrint; -$sql.= " FROM ".MAIN_DB_PREFIX."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"; -$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"; +$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"; +$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"; -$sql.= " WHERE c.id = a.fk_action"; -$sql.= ' AND a.entity IN ('.getEntity('agenda').')'; +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($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'"; + 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 ($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'"; + 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)."')"; + $sql .= " AND c.code IN ('".implode("','", $actioncode)."')"; } else { - $sql.=" AND c.code IN ('".implode("','", explode(',', $actioncode))."')"; + $sql .= " AND c.code IN ('".implode("','", explode(',', $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 = ".$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 == '100') { $sql.= " AND a.percent = 100"; } -if ($status == 'done') { $sql.= " AND (a.percent = 100)"; } -if ($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 = ".$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 == '100') { $sql .= " AND a.percent = 100"; } +if ($status == 'done') { $sql .= " AND (a.percent = 100)"; } +if ($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) { - $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; - $sql.= ")"; + $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; + $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'; // Add where from hooks -$parameters=array(); -$reshook=$hookmanager->executeHooks('printFieldListWhere', $parameters); // Note that $action and $object may have been modified by hook -$sql.=$hookmanager->resPrint; +$parameters = array(); +$reshook = $hookmanager->executeHooks('printFieldListWhere', $parameters); // Note that $action and $object may have been modified by hook +$sql .= $hookmanager->resPrint; -$sql.= $db->order($sortfield, $sortorder); +$sql .= $db->order($sortfield, $sortorder); $nbtotalofrecords = ''; if (empty($conf->global->MAIN_DISABLE_FULL_SCANLIST)) @@ -354,23 +354,23 @@ if (empty($conf->global->MAIN_DISABLE_FULL_SCANLIST)) } } -$sql.= $db->plimit($limit + 1, $offset); +$sql .= $db->plimit($limit + 1, $offset); //print $sql; dol_syslog("comm/action/list.php", LOG_DEBUG); -$resql=$db->query($sql); +$resql = $db->query($sql); if ($resql) { - $actionstatic=new ActionComm($db); - $societestatic=new Societe($db); + $actionstatic = new ActionComm($db); + $societestatic = new Societe($db); $num = $db->num_rows($resql); // Local calendar - $newtitle ='
' . $langs->trans("LocalAgenda").'  
'; + $newtitle = '
'.$langs->trans("LocalAgenda").'  
'; //$newtitle=$langs->trans($title); - $tabactive='cardlist'; + $tabactive = 'cardlist'; $head = calendars_prepare_head($param); @@ -384,14 +384,14 @@ if ($resql) print ''; print ''; print ''; - $nav=''; + $nav = ''; //if ($actioncode) $nav.=''; //if ($resourceid) $nav.=''; - if ($filter) $nav.=''; + if ($filter) $nav .= ''; //if ($filtert) $nav.=''; //if ($socid) $nav.=''; - if ($showbirthday) $nav.=''; + if ($showbirthday) $nav .= ''; //if ($pid) $nav.=''; //if ($usergroup) $nav.=''; print $nav; @@ -401,7 +401,7 @@ if ($resql) dol_fiche_end(); // Add link to show birthdays - $link=''; + $link = ''; /* if (empty($conf->use_javascript_ajax)) { @@ -417,76 +417,76 @@ if ($resql) } */ - $s=$newtitle; + $s = $newtitle; // Calendars from hooks - $parameters=array(); $object=null; - $reshook=$hookmanager->executeHooks('addCalendarChoice', $parameters, $object, $action); + $parameters = array(); $object = null; + $reshook = $hookmanager->executeHooks('addCalendarChoice', $parameters, $object, $action); if (empty($reshook)) { - $s.= $hookmanager->resPrint; + $s .= $hookmanager->resPrint; } elseif ($reshook > 1) { $s = $hookmanager->resPrint; } - $newcardbutton=''; + $newcardbutton = ''; if ($user->rights->agenda->myactions->create || $user->rights->agenda->allactions->create) { - $tmpforcreatebutton=dol_getdate(dol_now(), true); + $tmpforcreatebutton = dol_getdate(dol_now(), true); - $newparam.='&month='.str_pad($month, 2, "0", STR_PAD_LEFT).'&year='.$tmpforcreatebutton['year']; + $newparam .= '&month='.str_pad($month, 2, "0", STR_PAD_LEFT).'&year='.$tmpforcreatebutton['year']; //$param='month='.$monthshown.'&year='.$year; - $hourminsec='100000'; - $newcardbutton.= dolGetButtonTitle($langs->trans('AddAction'), '', 'fa fa-plus-circle', DOL_URL_ROOT.'/comm/action/card.php?action=create&datep='.sprintf("%04d%02d%02d", $tmpforcreatebutton['year'], $tmpforcreatebutton['mon'], $tmpforcreatebutton['mday']).$hourminsec.'&backtopage='.urlencode($_SERVER["PHP_SELF"].($newparam?'?'.$newparam:''))); + $hourminsec = '100000'; + $newcardbutton .= dolGetButtonTitle($langs->trans('AddAction'), '', 'fa fa-plus-circle', DOL_URL_ROOT.'/comm/action/card.php?action=create&datep='.sprintf("%04d%02d%02d", $tmpforcreatebutton['year'], $tmpforcreatebutton['mon'], $tmpforcreatebutton['mday']).$hourminsec.'&backtopage='.urlencode($_SERVER["PHP_SELF"].($newparam ? '?'.$newparam : ''))); } print_barre_liste($s, $page, $_SERVER["PHP_SELF"], $param, $sortfield, $sortorder, '', $num, -1 * $nbtotalofrecords, '', 0, $nav.$newcardbutton, '', $limit); - $moreforfilter=''; + $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); + $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); $i = 0; print '
'; - print ''."\n"; + 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.datep']['checked'])) { + 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.datep2']['checked'])) { + if (!empty($arrayfields['a.datep2']['checked'])) { print ''; } - if (! empty($arrayfields['s.nom']['checked'])) { + if (!empty($arrayfields['s.nom']['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'; // Fields from hook - $parameters=array('arrayfields'=>$arrayfields); - $reshook=$hookmanager->executeHooks('printFieldListOption', $parameters); // Note that $action and $object may have been modified by hook + $parameters = array('arrayfields'=>$arrayfields); + $reshook = $hookmanager->executeHooks('printFieldListOption', $parameters); // Note that $action and $object may have been modified by hook print $hookmanager->resPrint; - if (! empty($arrayfields['a.datec']['checked'])) print ''; - if (! empty($arrayfields['a.tms']['checked'])) print ''; - if (! empty($arrayfields['a.percent']['checked'])) { + if (!empty($arrayfields['a.datec']['checked'])) print ''; + if (!empty($arrayfields['a.tms']['checked'])) print ''; + if (!empty($arrayfields['a.percent']['checked'])) { print ''; 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'; // Hook fields - $parameters=array('arrayfields'=>$arrayfields,'param'=>$param,'sortfield'=>$sortfield,'sortorder'=>$sortorder); - $reshook=$hookmanager->executeHooks('printFieldListTitle', $parameters); // Note that $action and $object may have been modified by hook + $parameters = array('arrayfields'=>$arrayfields, 'param'=>$param, 'sortfield'=>$sortfield, 'sortorder'=>$sortorder); + $reshook = $hookmanager->executeHooks('printFieldListTitle', $parameters); // Note that $action and $object may have been modified by hook print $hookmanager->resPrint; - if (! empty($arrayfields['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"; $contactstatic = new Contact($db); - $now=dol_now(); - $delay_warning=$conf->global->MAIN_DELAY_ACTIONS_TODO*24*60*60; + $now = dol_now(); + $delay_warning = $conf->global->MAIN_DELAY_ACTIONS_TODO * 24 * 60 * 60; require_once DOL_DOCUMENT_ROOT.'/comm/action/class/cactioncomm.class.php'; - $caction=new CActionComm($db); - $arraylist=$caction->liste_array(1, 'code', '', (empty($conf->global->AGENDA_USE_EVENT_TYPE)?1:0), '', 1); + $caction = new CActionComm($db); + $arraylist = $caction->liste_array(1, 'code', '', (empty($conf->global->AGENDA_USE_EVENT_TYPE) ? 1 : 0), '', 1); $contactListCache = array(); while ($i < min($num, $limit)) @@ -541,34 +541,34 @@ if ($resql) $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; } - $actionstatic->id=$obj->id; - $actionstatic->ref=$obj->id; - $actionstatic->type_code=$obj->type_code; - $actionstatic->type_label=$obj->type_label; - $actionstatic->type_picto=$obj->type_picto; - $actionstatic->label=$obj->label; + $actionstatic->id = $obj->id; + $actionstatic->ref = $obj->id; + $actionstatic->type_code = $obj->type_code; + $actionstatic->type_label = $obj->type_label; + $actionstatic->type_picto = $obj->type_picto; + $actionstatic->label = $obj->label; $actionstatic->location = $obj->location; - $actionstatic->note=dol_htmlentitiesbr($obj->note); + $actionstatic->note = dol_htmlentitiesbr($obj->note); print ''; // Ref - if (! empty($arrayfields['a.id']['checked'])) { + if (!empty($arrayfields['a.id']['checked'])) { print ''; } // User owner - if (! empty($arrayfields['owner']['checked'])) + if (!empty($arrayfields['owner']['checked'])) { - print ''; } // Label - if (! empty($arrayfields['a.label']['checked'])) { + if (!empty($arrayfields['a.label']['checked'])) { print ''; } // Description - if (! empty($arrayfields['a.note']['checked'])) { + if (!empty($arrayfields['a.note']['checked'])) { print ''; } - $formatToUse = $obj->fulldayevent?'day':'dayhour'; + $formatToUse = $obj->fulldayevent ? 'day' : 'dayhour'; // Start date - if (! empty($arrayfields['a.datep']['checked'])) { + if (!empty($arrayfields['a.datep']['checked'])) { print ''; } // End date - if (! empty($arrayfields['a.datep2']['checked'])) { + if (!empty($arrayfields['a.datep2']['checked'])) { print ''; } // Third party - if (! empty($arrayfields['s.nom']['checked'])) { + if (!empty($arrayfields['s.nom']['checked'])) { print ''; } // Date update - if (! empty($arrayfields['a.tms']['checked'])) { + if (!empty($arrayfields['a.tms']['checked'])) { print ''; } - if (! empty($arrayfields['a.percent']['checked'])) { + if (!empty($arrayfields['a.percent']['checked'])) { // Status/Percent - $datep=$db->jdate($obj->datep); + $datep = $db->jdate($obj->datep); print ''; } print ''; diff --git a/htdocs/comm/action/peruser.php b/htdocs/comm/action/peruser.php index 3280ddc7af4..54373fcf8a9 100644 --- a/htdocs/comm/action/peruser.php +++ b/htdocs/comm/action/peruser.php @@ -39,11 +39,11 @@ 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); -$usergroup = GETPOST("search_usergroup", "int", 3)?GETPOST("search_usergroup", "int", 3):GETPOST("usergroup", "int", 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); +$usergroup = GETPOST("search_usergroup", "int", 3) ?GETPOST("search_usergroup", "int", 3) : GETPOST("usergroup", "int", 3); //if (! ($usergroup > 0) && ! ($filtert > 0)) $filtert = $user->id; //$showbirthday = empty($conf->use_javascript_ajax)?GETPOST("showbirthday","int"):1; $showbirthday = 0; @@ -150,11 +150,11 @@ $hookmanager->initHooks(array('agenda')); * Actions */ -if ($action =='delete_action') +if ($action == 'delete_action') { $event = new ActionComm($db); $event->fetch($actionid); - $result=$event->delete(); + $result = $event->delete(); } @@ -163,21 +163,21 @@ if ($action =='delete_action') * View */ -$form=new Form($db); -$companystatic=new Societe($db); +$form = new Form($db); +$companystatic = new Societe($db); -$help_url='EN:Module_Agenda_En|FR:Module_Agenda|ES:Módulo_Agenda'; +$help_url = 'EN:Module_Agenda_En|FR:Module_Agenda|ES:Módulo_Agenda'; llxHeader('', $langs->trans("Agenda"), $help_url); -$now=dol_now(); -$nowarray=dol_getdate($now); -$nowyear=$nowarray['year']; -$nowmonth=$nowarray['mon']; -$nowday=$nowarray['mday']; +$now = dol_now(); +$nowarray = dol_getdate($now); +$nowyear = $nowarray['year']; +$nowmonth = $nowarray['mon']; +$nowday = $nowarray['mday']; // Define list of all external calendars (global setup) -$listofextcals=array(); +$listofextcals = array(); $prev = dol_get_first_day_week($day, $month, $year); $first_day = $prev['first_day']; @@ -198,31 +198,31 @@ $tmpday = $first_day; //print 'xx'.$prev_year.'-'.$prev_month.'-'.$prev_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"); +$title = $langs->trans("DoneAndToDoActions"); +if ($status == 'done') $title = $langs->trans("DoneActions"); +if ($status == 'todo') $title = $langs->trans("ToDoActions"); -$param=''; +$param = ''; if ($actioncode || isset($_GET['search_actioncode']) || isset($_POST['search_actioncode'])) { - if(is_array($actioncode)) { - foreach($actioncode as $str_action) $param.="&search_actioncode[]=".urlencode($str_action); - } else $param.="&search_actioncode=".urlencode($actioncode); + if (is_array($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 || isset($_GET['status']) || isset($_POST['status'])) $param.="&search_status=".urlencode($status); -if ($filter) $param.="&search_filter=".urlencode($filter); -if ($filtert) $param.="&search_filtert=".urlencode($filtert); -if ($usergroup) $param.="&search_usergroup=".urlencode($usergroup); -if ($socid) $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); +if ($resourceid > 0) $param .= "&search_resourceid=".urlencode($resourceid); +if ($status || isset($_GET['status']) || isset($_POST['status'])) $param .= "&search_status=".urlencode($status); +if ($filter) $param .= "&search_filter=".urlencode($filter); +if ($filtert) $param .= "&search_filtert=".urlencode($filtert); +if ($usergroup) $param .= "&search_usergroup=".urlencode($usergroup); +if ($socid) $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); $prev = dol_get_first_day_week($day, $month, $year); @@ -232,7 +232,7 @@ $prev_year = $prev['prev_year']; $prev_month = $prev['prev_month']; $prev_day = $prev['prev_day']; $first_day = $prev['first_day']; -$first_month= $prev['first_month']; +$first_month = $prev['first_month']; $first_year = $prev['first_year']; $week = $prev['week']; @@ -244,10 +244,10 @@ $next_month = $next['month']; $next_day = $next['day']; // Define firstdaytoshow and lastdaytoshow (warning: lastdaytoshow is last second to show + 1) -$firstdaytoshow=dol_mktime(0, 0, 0, $first_month, $first_day, $first_year); +$firstdaytoshow = dol_mktime(0, 0, 0, $first_month, $first_day, $first_year); -$nb_weeks_to_show = (! empty($conf->global->AGENDA_NB_WEEKS_IN_VIEW_PER_USER)) ? ((int) $conf->global->AGENDA_NB_WEEKS_IN_VIEW_PER_USER * 7) : 7; -$lastdaytoshow=dol_time_plus_duree($firstdaytoshow, $nb_weeks_to_show, 'd'); +$nb_weeks_to_show = (!empty($conf->global->AGENDA_NB_WEEKS_IN_VIEW_PER_USER)) ? ((int) $conf->global->AGENDA_NB_WEEKS_IN_VIEW_PER_USER * 7) : 7; +$lastdaytoshow = dol_time_plus_duree($firstdaytoshow, $nb_weeks_to_show, 'd'); //print $firstday.'-'.$first_month.'-'.$first_year; //print dol_print_date($firstdaytoshow,'dayhour'); //print dol_print_date($lastdaytoshow,'dayhour'); @@ -255,13 +255,13 @@ $lastdaytoshow=dol_time_plus_duree($firstdaytoshow, $nb_weeks_to_show, 'd'); $max_day_in_month = date("t", dol_mktime(0, 0, 0, $month, 1, $year)); $tmpday = $first_day; -$picto='calendarweek'; +$picto = 'calendarweek'; -$nav ="trans("Previous"))."\">   \n"; -$nav.=" ".dol_print_date(dol_mktime(0, 0, 0, $first_month, $first_day, $first_year), "%Y").", ".$langs->trans("Week")." ".$week; -$nav.=" \n"; -$nav.="   trans("Next"))."\">\n"; -$nav.="   (".$langs->trans("Today").")"; +$nav = "trans("Previous"))."\">   \n"; +$nav .= " ".dol_print_date(dol_mktime(0, 0, 0, $first_month, $first_day, $first_year), "%Y").", ".$langs->trans("Week")." ".$week; +$nav .= " \n"; +$nav .= "   trans("Next"))."\">\n"; +$nav .= "   (".$langs->trans("Today").")"; /*$nav.='   '; $nav.=''; @@ -279,24 +279,24 @@ $nav.=''; $nav.=''; $nav.=''; */ -$nav.= $form->selectDate($dateselect, 'dateselect', 0, 0, 1, '', 1, 0); -$nav.=' '; +$nav .= $form->selectDate($dateselect, 'dateselect', 0, 0, 1, '', 1, 0); +$nav .= ' '; //$nav.=''; // Must be after the nav definition -$param.='&year='.urlencode($year).'&month='.urlencode($month).($day?'&day='.urlencode($day):''); +$param .= '&year='.urlencode($year).'&month='.urlencode($month).($day ? '&day='.urlencode($day) : ''); //print 'x'.$param; -$tabactive=''; -if ($action == 'show_month') $tabactive='cardmonth'; -if ($action == 'show_week') $tabactive='cardweek'; -if ($action == 'show_day') $tabactive='cardday'; -if ($action == 'show_list') $tabactive='cardlist'; -if ($action == 'show_peruser') $tabactive='cardperuser'; +$tabactive = ''; +if ($action == 'show_month') $tabactive = 'cardmonth'; +if ($action == 'show_week') $tabactive = 'cardweek'; +if ($action == 'show_day') $tabactive = 'cardday'; +if ($action == 'show_list') $tabactive = 'cardlist'; +if ($action == 'show_peruser') $tabactive = 'cardperuser'; -$paramnoaction=preg_replace('/action=[a-z_]+/', '', $param); +$paramnoaction = preg_replace('/action=[a-z_]+/', '', $param); $head = calendars_prepare_head($paramnoaction); @@ -306,51 +306,51 @@ dol_fiche_head($head, $tabactive, $langs->trans('Agenda'), 0, 'action'); print_actions_filter($form, $canedit, $status, $year, $month, $day, $showbirthday, 0, $filtert, 0, $pid, $socid, $action, $listofextcals, $actioncode, $usergroup, '', $resourceid); dol_fiche_end(); -$showextcals=$listofextcals; +$showextcals = $listofextcals; // Legend if ($conf->use_javascript_ajax) { - $s=''; - $s.='' . "\n"; - if (! empty($conf->use_javascript_ajax)) + $s .= '});'."\n"; + $s .= ''."\n"; + if (!empty($conf->use_javascript_ajax)) { - $s.='
' . $langs->trans("LocalAgenda").'  
'; + $s .= '
'.$langs->trans("LocalAgenda").'  
'; if (is_array($showextcals) && count($showextcals) > 0) { foreach ($showextcals as $val) { $htmlname = md5($val['name']); - $s.='' . "\n"; - $s.='
' . $val ['name'] . '  
'; + $s .= ''."\n"; + $s .= '
'.$val ['name'].'  
'; } } //$s.='
'.$langs->trans("AgendaShowBirthdayEvents").'  
'; // Calendars from hooks - $parameters=array(); $object=null; - $reshook=$hookmanager->executeHooks('addCalendarChoice', $parameters, $object, $action); + $parameters = array(); $object = null; + $reshook = $hookmanager->executeHooks('addCalendarChoice', $parameters, $object, $action); if (empty($reshook)) { - $s.= $hookmanager->resPrint; + $s .= $hookmanager->resPrint; } elseif ($reshook > 1) { @@ -555,29 +555,29 @@ if ($resql) else { //print $i.' - '.dol_print_date($this->date_start_in_calendar, 'dayhour').' - '.dol_print_date($this->date_end_in_calendar, 'dayhour').'
'."\n"; - $event->fetch_userassigned(); // This load $event->userassigned + $event->fetch_userassigned(); // This load $event->userassigned - if ($event->date_start_in_calendar < $firstdaytoshow) $event->date_start_in_calendar=$firstdaytoshow; - if ($event->date_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; + $daycursor = $event->date_start_in_calendar; $annee = date('Y', $daycursor); $mois = date('m', $daycursor); $jour = date('d', $daycursor); // Loop on each day covered by action to prepare an index to show on calendar - $loop=true; $j=0; - $daykey=dol_mktime(0, 0, 0, $mois, $jour, $annee); + $loop = true; $j = 0; + $daykey = dol_mktime(0, 0, 0, $mois, $jour, $annee); do { //if ($event->id==408) print 'daykey='.$daykey.' '.$event->datep.' '.$event->datef.'
'; - $eventarray[$daykey][]=$event; + $eventarray[$daykey][] = $event; $j++; - $daykey+=60*60*24; - if ($daykey > $event->date_end_in_calendar) $loop=false; + $daykey += 60 * 60 * 24; + if ($daykey > $event->date_end_in_calendar) $loop = false; } while ($loop); @@ -593,10 +593,10 @@ else dol_print_error($db); } -$maxnbofchar=18; -$cachethirdparties=array(); -$cachecontacts=array(); -$cacheusers=array(); +$maxnbofchar = 18; +$cachethirdparties = array(); +$cachecontacts = array(); +$cacheusers = array(); // Define theme_datacolor array $color_file = DOL_DOCUMENT_ROOT."/theme/".$conf->theme."/theme_vars.inc.php"; @@ -604,23 +604,23 @@ 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)); -$newparam=$param; // newparam is for birthday links -$newparam=preg_replace('/showbirthday=/i', 'showbirthday_=', $newparam); // To avoid replacement when replace day= is done -$newparam=preg_replace('/action=show_month&?/i', '', $newparam); -$newparam=preg_replace('/action=show_week&?/i', '', $newparam); -$newparam=preg_replace('/day=[0-9]+&?/i', '', $newparam); -$newparam=preg_replace('/month=[0-9]+&?/i', '', $newparam); -$newparam=preg_replace('/year=[0-9]+&?/i', '', $newparam); -$newparam=preg_replace('/viewweek=[0-9]+&?/i', '', $newparam); -$newparam=preg_replace('/showbirthday_=/i', 'showbirthday=', $newparam); // Restore correct parameter -$newparam.='&viewweek=1'; +$newparam = $param; // newparam is for birthday links +$newparam = preg_replace('/showbirthday=/i', 'showbirthday_=', $newparam); // To avoid replacement when replace day= is done +$newparam = preg_replace('/action=show_month&?/i', '', $newparam); +$newparam = preg_replace('/action=show_week&?/i', '', $newparam); +$newparam = preg_replace('/day=[0-9]+&?/i', '', $newparam); +$newparam = preg_replace('/month=[0-9]+&?/i', '', $newparam); +$newparam = preg_replace('/year=[0-9]+&?/i', '', $newparam); +$newparam = preg_replace('/viewweek=[0-9]+&?/i', '', $newparam); +$newparam = preg_replace('/showbirthday_=/i', 'showbirthday=', $newparam); // Restore correct parameter +$newparam .= '&viewweek=1'; echo ''; echo ''; -echo '' ; +echo ''; // Line header with list of days @@ -644,7 +644,7 @@ while($currentdaytoshow<$lastdaytoshow) { continue; } echo ''; echo ''; - $i=0; + $i = 0; while ($i < 7) { if (($i + 1) < $begin_d || ($i + 1) > $end_d) @@ -679,7 +679,7 @@ while($currentdaytoshow<$lastdaytoshow) { $usernames = array(); //init $usernamesid = array(); /* Use this to have list of users only if users have events */ - if (! empty($conf->global->AGENDA_SHOWOWNERONLY_ONPERUSERVIEW)) + if (!empty($conf->global->AGENDA_SHOWOWNERONLY_ONPERUSERVIEW)) { foreach ($eventarray as $daykey => $notused) { @@ -699,12 +699,12 @@ while($currentdaytoshow<$lastdaytoshow) { else { $sql = "SELECT u.rowid, u.lastname as lastname, u.firstname, u.statut, u.login, u.admin, u.entity"; - $sql.= " FROM ".MAIN_DB_PREFIX."user as u"; - if ($usergroup > 0) $sql.= " LEFT JOIN ".MAIN_DB_PREFIX."usergroup_user as ug ON u.rowid = ug.fk_user"; - $sql.= " WHERE u.statut = 1 AND u.entity IN (".getEntity('user').")"; - if ($usergroup > 0) $sql.= " AND ug.fk_usergroup = ".$usergroup; + $sql .= " FROM ".MAIN_DB_PREFIX."user as u"; + if ($usergroup > 0) $sql .= " LEFT JOIN ".MAIN_DB_PREFIX."usergroup_user as ug ON u.rowid = ug.fk_user"; + $sql .= " WHERE u.statut = 1 AND u.entity IN (".getEntity('user').")"; + if ($usergroup > 0) $sql .= " AND ug.fk_usergroup = ".$usergroup; //print $sql; - $resql=$db->query($sql); + $resql = $db->query($sql); if ($resql) { $num = $db->num_rows($resql); @@ -714,7 +714,7 @@ while($currentdaytoshow<$lastdaytoshow) { while ($i < $num) { $obj = $db->fetch_object($resql); - $usernamesid[$obj->rowid]=$obj->rowid; + $usernamesid[$obj->rowid] = $obj->rowid; $i++; } } @@ -722,11 +722,11 @@ while($currentdaytoshow<$lastdaytoshow) { else dol_print_error($db); } //var_dump($usernamesid); - foreach($usernamesid as $id) + foreach ($usernamesid as $id) { - $tmpuser=new User($db); - $result=$tmpuser->fetch($id); - $usernames[]=$tmpuser; + $tmpuser = new User($db); + $result = $tmpuser->fetch($id); + $usernames[] = $tmpuser; } /* @@ -791,11 +791,11 @@ while($currentdaytoshow<$lastdaytoshow) { $tmpmonth = $tmparray['mon']; $tmpyear = $tmparray['year']; - $style='cal_current_month'; - if ($iter_day == 6) $style.=' cal_other_month'; - $today=0; - if ($todayarray['mday']==$tmpday && $todayarray['mon']==$tmpmonth && $todayarray['year']==$tmpyear) $today=1; - if ($today) $style='cal_today_peruser'; + $style = 'cal_current_month'; + if ($iter_day == 6) $style .= ' cal_other_month'; + $today = 0; + if ($todayarray['mday'] == $tmpday && $todayarray['mon'] == $tmpmonth && $todayarray['year'] == $tmpyear) $today = 1; + if ($today) $style = 'cal_today_peruser'; show_day_events2($username, $tmpday, $tmpmonth, $tmpyear, $monthshown, $style, $eventarray, 0, $maxnbofchar, $newparam, 1, 300, $showheader, $colorsbytype, $var); @@ -808,21 +808,21 @@ while($currentdaytoshow<$lastdaytoshow) { echo "
'; print $form->selectDate($datestart, 'datestart', 0, 0, 1, '', 1, 0); print ''; print $form->selectDate($dateend, 'dateend', 0, 0, 1, '', 1, 0); print ''; $formactions->form_select_status_action('formaction', $status, 1, 'status', 1, 2, 'minwidth100imp maxwidth125'); print ajax_combobox('selectstatus'); @@ -494,46 +494,46 @@ if ($resql) } // Action column print ''; - $searchpicto=$form->showFilterButtons(); + $searchpicto = $form->showFilterButtons(); print $searchpicto; print '
'; print $actionstatic->getNomUrl(1, -1); print ''; // With edge and chrome the td overflow is not supported correctly when content is not full text. + print ''; // With edge and chrome the td overflow is not supported correctly when content is not full text. if ($obj->fk_user_action > 0) { $userstatic->fetch($obj->fk_user_action); @@ -579,10 +579,10 @@ if ($resql) } // Type - if (! empty($arrayfields['c.libelle']['checked'])) + if (!empty($arrayfields['c.libelle']['checked'])) { print ''; - if (! empty($conf->global->AGENDA_USE_EVENT_TYPE)) + if (!empty($conf->global->AGENDA_USE_EVENT_TYPE)) { if ($actionstatic->type_picto) print img_picto('', $actionstatic->type_picto); else { @@ -591,60 +591,60 @@ if ($resql) elseif ($actionstatic->type_code == 'AC_FAX') print img_picto('', 'object_phoning_fax', '', false, 0, 0, '', 'paddingright').' '; elseif ($actionstatic->type_code == 'AC_EMAIL') print img_picto('', 'object_email', '', false, 0, 0, '', 'paddingright').' '; elseif ($actionstatic->type_code == 'AC_INT') print img_picto('', 'object_intervention', '', false, 0, 0, '', 'paddingright').' '; - elseif (! preg_match('/_AUTO/', $actionstatic->type_code)) print img_picto('', 'object_action', '', false, 0, 0, '', 'paddingright').' '; + elseif (!preg_match('/_AUTO/', $actionstatic->type_code)) print img_picto('', 'object_action', '', false, 0, 0, '', 'paddingright').' '; } } - $labeltype=$obj->type_code; - if (empty($conf->global->AGENDA_USE_EVENT_TYPE) && empty($arraylist[$labeltype])) $labeltype='AC_OTH'; - if (! empty($arraylist[$labeltype])) $labeltype=$arraylist[$labeltype]; + $labeltype = $obj->type_code; + if (empty($conf->global->AGENDA_USE_EVENT_TYPE) && empty($arraylist[$labeltype])) $labeltype = 'AC_OTH'; + if (!empty($arraylist[$labeltype])) $labeltype = $arraylist[$labeltype]; print dol_trunc($labeltype, 28); print ''; print $actionstatic->label; print ''; $text = dolGetFirstLineOfText(dol_string_nohtmltag($actionstatic->note, 0)); print $form->textwithtooltip(dol_trunc($text, 40), $actionstatic->note); print ''; print dol_print_date($db->jdate($obj->dp), $formatToUse); - $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; + $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")).' '; print ''; print dol_print_date($db->jdate($obj->dp2), $formatToUse); print ''; if ($obj->socid > 0) { - $societestatic->id=$obj->socid; - $societestatic->client=$obj->client; - $societestatic->name=$obj->societe; - $societestatic->email=$obj->socemail; + $societestatic->id = $obj->socid; + $societestatic->client = $obj->client; + $societestatic->name = $obj->societe; + $societestatic->email = $obj->socemail; print $societestatic->getNomUrl(1, '', 28); } @@ -653,44 +653,44 @@ if ($resql) } // Contact - if (! empty($arrayfields['a.fk_contact']['checked'])) { + if (!empty($arrayfields['a.fk_contact']['checked'])) { print ''; $actionstatic->fetchResources(); - if(!empty($actionstatic->socpeopleassigned)) + if (!empty($actionstatic->socpeopleassigned)) { $contactList = array(); foreach ($actionstatic->socpeopleassigned as $socpeopleassigned) { - if(!isset($contactListCache[$socpeopleassigned['id']])) + 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); } } - else{ + else { // use cache $contactList[] = $contactListCache[$socpeopleassigned['id']]; } } - if(!empty($contactList)){ + if (!empty($contactList)) { print implode(', ', $contactList); } } elseif ($obj->fk_contact > 0) //keep for retrocompatibility with faraway event { - $contactstatic->id=$obj->fk_contact; - $contactstatic->email=$obj->email; - $contactstatic->lastname=$obj->lastname; - $contactstatic->firstname=$obj->firstname; - $contactstatic->phone_pro=$obj->phone_pro; - $contactstatic->phone_mobile=$obj->phone_mobile; - $contactstatic->phone_perso=$obj->phone_perso; - $contactstatic->country_id=$obj->country_id; + $contactstatic->id = $obj->fk_contact; + $contactstatic->email = $obj->email; + $contactstatic->lastname = $obj->lastname; + $contactstatic->firstname = $obj->firstname; + $contactstatic->phone_pro = $obj->phone_pro; + $contactstatic->phone_mobile = $obj->phone_mobile; + $contactstatic->phone_perso = $obj->phone_perso; + $contactstatic->country_id = $obj->country_id; print $contactstatic->getNomUrl(1, '', 0); } else @@ -701,10 +701,10 @@ if ($resql) } // Linked object - if (! empty($arrayfields['a.fk_element']['checked'])) { + if (!empty($arrayfields['a.fk_element']['checked'])) { print ''; //var_dump($obj->fkelement.' '.$obj->elementtype); - if ($obj->fk_element > 0 && ! empty($obj->elementtype)) { + if ($obj->fk_element > 0 && !empty($obj->elementtype)) { include_once DOL_DOCUMENT_ROOT.'/core/lib/functions2.lib.php'; print dolGetElementUrl($obj->fk_element, $obj->elementtype, 1); } else { @@ -716,22 +716,22 @@ if ($resql) // Extra fields include DOL_DOCUMENT_ROOT.'/core/tpl/extrafields_list_print_fields.tpl.php'; // Fields from hook - $parameters=array('arrayfields'=>$arrayfields, 'obj'=>$obj); - $reshook=$hookmanager->executeHooks('printFieldListValue', $parameters); // Note that $action and $object may have been modified by hook + $parameters = array('arrayfields'=>$arrayfields, 'obj'=>$obj); + $reshook = $hookmanager->executeHooks('printFieldListValue', $parameters); // Note that $action and $object may have been modified by hook print $hookmanager->resPrint; // Date creation - if (! empty($arrayfields['a.datec']['checked'])) { + if (!empty($arrayfields['a.datec']['checked'])) { // Status/Percent print ''.dol_print_date($db->jdate($obj->datec), 'dayhour').''.dol_print_date($db->jdate($obj->datem), 'dayhour').''.$actionstatic->LibStatut($obj->percent, 3, 0, $datep).''; - echo $langs->trans("Day".(($i+(isset($conf->global->MAIN_START_WEEK)?$conf->global->MAIN_START_WEEK:1)) % 7)); + echo $langs->trans("Day".(($i + (isset($conf->global->MAIN_START_WEEK) ? $conf->global->MAIN_START_WEEK : 1)) % 7)); print "
"; if ($i) print dol_print_date(dol_time_plus_duree($currentdaytoshow, $i, 'd'), 'day'); else print dol_print_date($currentdaytoshow, 'day'); @@ -655,7 +655,7 @@ while($currentdaytoshow<$lastdaytoshow) { echo '
\n"; echo "
"; - $currentdaytoshow = dol_time_plus_duree($currentdaytoshow, 7, 'd'); + $currentdaytoshow = dol_time_plus_duree($currentdaytoshow, 7, 'd'); } echo '
'; -if (! empty($conf->global->AGENDA_USE_EVENT_TYPE) && ! empty($conf->global->AGENDA_USE_COLOR_PER_EVENT_TYPE)) +if (!empty($conf->global->AGENDA_USE_EVENT_TYPE) && !empty($conf->global->AGENDA_USE_COLOR_PER_EVENT_TYPE)) { $langs->load("commercial"); print '
'.$langs->trans("Legend").':
'; - foreach($colorsbytype as $code => $color) + foreach ($colorsbytype as $code => $color) { if ($color) { - print '
 
'; - print $langs->trans("Action".$code)!="Action".$code?$langs->trans("Action".$code):$labelbytype[$code]; + print '
 
'; + print $langs->trans("Action".$code) != "Action".$code ? $langs->trans("Action".$code) : $labelbytype[$code]; //print $code; print '
'; } @@ -907,21 +907,21 @@ function show_day_events2($username, $day, $month, $year, $monthshown, $style, & { global $db; global $user, $conf, $langs, $hookmanager, $action; - global $filter, $filtert, $status, $actioncode; // Filters used into search form - global $theme_datacolor; // Array with a list of different we can use (come from theme) + global $filter, $filtert, $status, $actioncode; // Filters used into search form + global $theme_datacolor; // Array with a list of different we can use (come from theme) global $cachethirdparties, $cachecontacts, $cacheusers, $cacheprojects, $colorindexused; global $begin_h, $end_h; - $cases1 = array(); // Color first half hour + $cases1 = array(); // Color first half hour $cases2 = array(); // Color second half hour $curtime = dol_mktime(0, 0, 0, $month, $day, $year, false, 0); - $i=0; $numother=0; $numbirthday=0; $numical=0; $numicals=array(); - $ymd=sprintf("%04d", $year).sprintf("%02d", $month).sprintf("%02d", $day); + $i = 0; $numother = 0; $numbirthday = 0; $numical = 0; $numicals = array(); + $ymd = sprintf("%04d", $year).sprintf("%02d", $month).sprintf("%02d", $day); - $colorindexused[$user->id] = 0; // Color index for current user (user->id) is always 0 - $nextindextouse=count($colorindexused); // At first run this is 0, so first user has 0, next 1, ... + $colorindexused[$user->id] = 0; // Color index for current user (user->id) is always 0 + $nextindextouse = count($colorindexused); // At first run this is 0, so first user has 0, next 1, ... //if ($username->id && $day==1) var_dump($eventarray); // We are in a particular day for $username, now we scan all events @@ -932,96 +932,96 @@ function show_day_events2($username, $day, $month, $year, $monthshown, $style, & $jour = date('d', $daykey); //print $annee.'-'.$mois.'-'.$jour.' '.$year.'-'.$month.'-'.$day."
\n"; - if ($day==$jour && $month==$mois && $year==$annee) // Is it the day we are looking for when calling function ? + if ($day == $jour && $month == $mois && $year == $annee) // Is it the day we are looking for when calling function ? { // Scan all event for this date foreach ($eventarray[$daykey] as $index => $event) { //var_dump($event); - $keysofuserassigned=array_keys($event->userassigned); - $ponct=($event->date_start_in_calendar == $event->date_end_in_calendar); + $keysofuserassigned = array_keys($event->userassigned); + $ponct = ($event->date_start_in_calendar == $event->date_end_in_calendar); - if (! in_array($username->id, $keysofuserassigned)) continue; // We discard record if event is from another user than user we want to show + if (!in_array($username->id, $keysofuserassigned)) continue; // We discard record if event is from another user than user we want to show //if ($username->id != $event->userownerid) continue; // We discard record if event is from another user than user we want to show - $parameters=array(); - $reshook=$hookmanager->executeHooks('formatEvent', $parameters, $event, $action); // Note that $action and $object may have been modified by some hooks + $parameters = array(); + $reshook = $hookmanager->executeHooks('formatEvent', $parameters, $event, $action); // Note that $action and $object may have been modified by some hooks if ($reshook < 0) setEventMessages($hookmanager->error, $hookmanager->errors, 'errors'); // Define $color (Hex string like '0088FF') and $cssclass of event - $color=-1; $cssclass=''; $colorindex=-1; + $color = -1; $cssclass = ''; $colorindex = -1; if (in_array($user->id, $keysofuserassigned)) { - $cssclass='family_mytasks'; + $cssclass = 'family_mytasks'; if (empty($cacheusers[$event->userownerid])) { - $newuser=new User($db); + $newuser = new User($db); $newuser->fetch($event->userownerid); - $cacheusers[$event->userownerid]=$newuser; + $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; + if (!empty($cacheusers[$event->userownerid]->color)) $color = $cacheusers[$event->userownerid]->color; - if (! empty($conf->global->AGENDA_USE_COLOR_PER_EVENT_TYPE)) $color=$event->type_color; + if (!empty($conf->global->AGENDA_USE_COLOR_PER_EVENT_TYPE)) $color = $event->type_color; } elseif ($event->type_code == 'ICALEVENT') { $numical++; - if (! empty($event->icalname)) + if (!empty($event->icalname)) { - if (! isset($numicals[dol_string_nospecial($event->icalname)])) { + if (!isset($numicals[dol_string_nospecial($event->icalname)])) { $numicals[dol_string_nospecial($event->icalname)] = 0; } $numicals[dol_string_nospecial($event->icalname)]++; } - $color=$event->icalcolor; - $cssclass=(! empty($event->icalname)?'family_ext'.md5($event->icalname):'family_other unsortable'); + $color = $event->icalcolor; + $cssclass = (!empty($event->icalname) ? 'family_ext'.md5($event->icalname) : 'family_other unsortable'); } elseif ($event->type_code == 'BIRTHDAY') { - $numbirthday++; $colorindex=2; $cssclass='family_birthday unsortable'; $color=sprintf("%02x%02x%02x", $theme_datacolor[$colorindex][0], $theme_datacolor[$colorindex][1], $theme_datacolor[$colorindex][2]); + $numbirthday++; $colorindex = 2; $cssclass = 'family_birthday unsortable'; $color = sprintf("%02x%02x%02x", $theme_datacolor[$colorindex][0], $theme_datacolor[$colorindex][1], $theme_datacolor[$colorindex][2]); } else { $numother++; - $color=($event->icalcolor?$event->icalcolor:-1); - $cssclass=(! empty($event->icalname)?'family_ext'.md5($event->icalname):'family_other'); + $color = ($event->icalcolor ? $event->icalcolor : -1); + $cssclass = (!empty($event->icalname) ? 'family_ext'.md5($event->icalname) : 'family_other'); if (empty($cacheusers[$event->userownerid])) { - $newuser=new User($db); + $newuser = new User($db); $newuser->fetch($event->userownerid); - $cacheusers[$event->userownerid]=$newuser; + $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; + if (!empty($cacheusers[$event->userownerid]->color)) $color = $cacheusers[$event->userownerid]->color; - if (! empty($conf->global->AGENDA_USE_COLOR_PER_EVENT_TYPE)) $color=$event->type_color; + if (!empty($conf->global->AGENDA_USE_COLOR_PER_EVENT_TYPE)) $color = $event->type_color; } if ($color < 0) // Color was not set on user card. Set color according to color index. { // Define color index if not yet defined - $idusertouse=($event->userownerid?$event->userownerid:0); + $idusertouse = ($event->userownerid ? $event->userownerid : 0); if (isset($colorindexused[$idusertouse])) { - $colorindex=$colorindexused[$idusertouse]; // Color already assigned to this user + $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 } // Define color - $color=sprintf("%02x%02x%02x", $theme_datacolor[$colorindex][0], $theme_datacolor[$colorindex][1], $theme_datacolor[$colorindex][2]); + $color = sprintf("%02x%02x%02x", $theme_datacolor[$colorindex][0], $theme_datacolor[$colorindex][1], $theme_datacolor[$colorindex][2]); } //$cssclass=$cssclass.' '.$cssclass.'_day_'.$ymd; diff --git a/htdocs/comm/card.php b/htdocs/comm/card.php index a0263065dee..6e42b1068c1 100644 --- a/htdocs/comm/card.php +++ b/htdocs/comm/card.php @@ -72,8 +72,8 @@ if (empty($page) || $page == -1) { $page = 0; } // If $page is not defined, $offset = $conf->liste_limit * $page; $pageprev = $page - 1; $pagenext = $page + 1; -if (! $sortorder) $sortorder="ASC"; -if (! $sortfield) $sortfield="nom"; +if (!$sortorder) $sortorder = "ASC"; +if (!$sortfield) $sortfield = "nom"; $cancelbutton = GETPOST('cancel', 'alpha'); $object = new Client($db); @@ -83,7 +83,7 @@ $extrafields = new ExtraFields($db); $extrafields->fetch_name_optionals_label($object->table_element); // Initialize technical object to manage hooks of page. Note that conf->hooks_modules contains array of hook context -$hookmanager->initHooks(array('thirdpartycomm','globalcard')); +$hookmanager->initHooks(array('thirdpartycomm', 'globalcard')); @@ -99,15 +99,15 @@ if (empty($reshook)) { if ($cancelbutton) { - $action=""; + $action = ""; } // set accountancy code if ($action == 'setcustomeraccountancycode') { - $result=$object->fetch($id); - $object->code_compta=$_POST["customeraccountancycode"]; - $result=$object->update($object->id, $user, 1, 1, 0); + $result = $object->fetch($id); + $object->code_compta = $_POST["customeraccountancycode"]; + $result = $object->update($object->id, $user, 1, 1, 0); if ($result < 0) setEventMessages($object->error, $object->errors, 'errors'); } @@ -115,7 +115,7 @@ if (empty($reshook)) if ($action == 'setconditions' && $user->rights->societe->creer) { $object->fetch($id); - $result=$object->setPaymentTerms(GETPOST('cond_reglement_id', 'int')); + $result = $object->setPaymentTerms(GETPOST('cond_reglement_id', 'int')); if ($result < 0) setEventMessages($object->error, $object->errors, 'errors'); } @@ -123,7 +123,7 @@ if (empty($reshook)) if ($action == 'setmode' && $user->rights->societe->creer) { $object->fetch($id); - $result=$object->setPaymentMethods(GETPOST('mode_reglement_id', 'int')); + $result = $object->setPaymentMethods(GETPOST('mode_reglement_id', 'int')); if ($result < 0) setEventMessages($object->error, $object->errors, 'errors'); } @@ -131,7 +131,7 @@ if (empty($reshook)) if ($action == 'setbankaccount' && $user->rights->societe->creer) { $object->fetch($id); - $result=$object->setBankAccount(GETPOST('fk_account', 'int')); + $result = $object->setBankAccount(GETPOST('fk_account', 'int')); if ($result < 0) setEventMessages($object->error, $object->errors, 'errors'); } @@ -147,8 +147,8 @@ if (empty($reshook)) if ($action == 'setassujtva' && $user->rights->societe->creer) { $object->fetch($id); - $object->tva_assuj=$_POST['assujtva_value']; - $result=$object->update($object->id); + $object->tva_assuj = $_POST['assujtva_value']; + $result = $object->update($object->id); if ($result < 0) setEventMessages($object->error, $object->errors, 'errors'); } @@ -156,8 +156,8 @@ if (empty($reshook)) if ($action == 'setprospectlevel' && $user->rights->societe->creer) { $object->fetch($id); - $object->fk_prospectlevel=GETPOST('prospect_level_id', 'alpha'); - $result=$object->update($object->id, $user); + $object->fk_prospectlevel = GETPOST('prospect_level_id', 'alpha'); + $result = $object->update($object->id, $user); if ($result < 0) setEventMessages($object->error, $object->errors, 'errors'); } @@ -165,8 +165,8 @@ if (empty($reshook)) if ($action == 'setstcomm') { $object->fetch($id); - $object->stcomm_id=dol_getIdFromCode($db, GETPOST('stcomm', 'alpha'), 'c_stcomm'); - $result=$object->update($object->id, $user); + $object->stcomm_id = dol_getIdFromCode($db, GETPOST('stcomm', 'alpha'), 'c_stcomm'); + $result = $object->update($object->id, $user); if ($result < 0) setEventMessages($object->error, $object->errors, 'errors'); } @@ -174,8 +174,8 @@ if (empty($reshook)) if ($action == 'setoutstanding_limit') { $object->fetch($id); - $object->outstanding_limit=GETPOST('outstanding_limit'); - $result=$object->update($object->id, $user); + $object->outstanding_limit = GETPOST('outstanding_limit'); + $result = $object->update($object->id, $user); if ($result < 0) setEventMessages($object->error, $object->errors, 'errors'); } @@ -183,8 +183,8 @@ if (empty($reshook)) if ($action == 'setorder_min_amount') { $object->fetch($id); - $object->order_min_amount=price2num(GETPOST('order_min_amount', 'alpha')); - $result=$object->update($object->id, $user); + $object->order_min_amount = price2num(GETPOST('order_min_amount', 'alpha')); + $result = $object->update($object->id, $user); if ($result < 0) setEventMessages($object->error, $object->errors, 'errors'); } @@ -196,7 +196,7 @@ if (empty($reshook)) // Fill array 'array_options' with data from update form $ret = $extrafields->setOptionalsFromPost(null, $object, GETPOST('attribute', 'none')); if ($ret < 0) $error++; - if (! $error) + if (!$error) { $result = $object->insertExtraFields('COMPANY_MODIFY'); if ($result < 0) @@ -215,20 +215,20 @@ if (empty($reshook)) */ $contactstatic = new Contact($db); -$userstatic=new User($db); +$userstatic = new User($db); $form = new Form($db); -$formcompany=new FormCompany($db); +$formcompany = new FormCompany($db); if ($id > 0 && empty($object->id)) { // Load data of third party - $res=$object->fetch($id); + $res = $object->fetch($id); if ($object->id < 0) dol_print_error($db, $object->error, $object->errors); } -$title=$langs->trans("CustomerCard"); -if (! empty($conf->global->MAIN_HTML_TITLE) && preg_match('/thirdpartynameonly/', $conf->global->MAIN_HTML_TITLE) && $object->name) $title=$object->name; -$help_url='EN:Module_Third_Parties|FR:Module_Tiers|ES:Empresas'; +$title = $langs->trans("CustomerCard"); +if (!empty($conf->global->MAIN_HTML_TITLE) && preg_match('/thirdpartynameonly/', $conf->global->MAIN_HTML_TITLE) && $object->name) $title = $object->name; +$help_url = 'EN:Module_Third_Parties|FR:Module_Tiers|ES:Empresas'; llxHeader('', $title, $help_url); @@ -253,10 +253,10 @@ if ($object->id > 0) print '
'.$langs->trans("Prefix").''; - print ($object->prefix_comm?$object->prefix_comm:' '); + print ($object->prefix_comm ? $object->prefix_comm : ' '); print '
'.$langs->transcountry("LocalTax1IsUsed", $mysoc->country_code).''; print yn($object->localtax1_assuj); print '
'.$langs->transcountry("LocalTax2IsUsed", $mysoc->country_code).''; print yn($object->localtax2_assuj); @@ -356,7 +356,7 @@ if ($object->id > 0) print "
'; @@ -392,7 +392,7 @@ if ($object->id > 0) print ''.img_edit($langs->trans("Modify")).''; } print '
'; - print '
'.($object->remise_percent?''.$object->remise_percent.'%':'').''.($object->remise_percent ? ''.$object->remise_percent.'%' : '').'
'; print '
'; - $amount_discount=$object->getAvailableDiscounts(); + $amount_discount = $object->getAvailableDiscounts(); if ($amount_discount < 0) dol_print_error($db, $object->error); if ($amount_discount > 0) print ''.price($amount_discount, 1, $langs, 1, -1, -1, $conf->currency).''; //else print $langs->trans("DiscountNone"); @@ -423,7 +423,7 @@ if ($object->id > 0) print ''; print $form->editfieldkey("OutstandingBill", 'outstanding_limit', $object->outstanding_limit, $object, $user->rights->societe->creer); print ''; - $limit_field_type = (! empty($conf->global->MAIN_USE_JQUERY_JEDITABLE)) ? 'numeric' : 'amount'; + $limit_field_type = (!empty($conf->global->MAIN_USE_JQUERY_JEDITABLE)) ? 'numeric' : 'amount'; print $form->editfieldval("OutstandingBill", 'outstanding_limit', $object->outstanding_limit, $object, $user->rights->societe->creer, $limit_field_type, ($object->outstanding_limit != '' ? price($object->outstanding_limit) : '')); print '
'; print '
'; @@ -459,14 +459,14 @@ if ($object->id > 0) print '
'; print '
'; print $object->price_level; - $keyforlabel='PRODUIT_MULTIPRICES_LABEL'.$object->price_level; - if (! empty($conf->global->$keyforlabel)) print ' - '.$langs->trans($conf->global->$keyforlabel); + $keyforlabel = 'PRODUIT_MULTIPRICES_LABEL'.$object->price_level; + if (!empty($conf->global->$keyforlabel)) print ' - '.$langs->trans($conf->global->$keyforlabel); print "
'; print ''; + print ''; print '"; } // Other attributes - $parameters=array('socid'=>$object->id); - include DOL_DOCUMENT_ROOT . '/core/tpl/extrafields_view.tpl.php'; + $parameters = array('socid'=>$object->id); + include DOL_DOCUMENT_ROOT.'/core/tpl/extrafields_view.tpl.php'; // Sales representative include DOL_DOCUMENT_ROOT.'/societe/tpl/linesalesrepresentative.tpl.php'; // Module Adherent - if (! empty($conf->adherent->enabled)) + if (!empty($conf->adherent->enabled)) { $langs->load("members"); $langs->load("users"); print ''; print ''; @@ -574,65 +574,65 @@ if ($object->id > 0) $boxstat = ''; // Nbre max d'elements des petites listes - $MAXLIST=$conf->global->MAIN_SIZE_SHORTLIST_LIMIT; + $MAXLIST = $conf->global->MAIN_SIZE_SHORTLIST_LIMIT; // Lien recap - $boxstat.='
'; - $boxstat.='
'; print $langs->trans('SendingMethod'); @@ -476,7 +476,7 @@ if ($object->id > 0) print ''; if ($action == 'editshipping') { - $form->formSelectShippingMethod($_SERVER['PHP_SELF'].'?socid='.$object->id, $object->shipping_method_id, 'shipping_method_id'); + $form->formSelectShippingMethod($_SERVER['PHP_SELF'].'?socid='.$object->id, $object->shipping_method_id, 'shipping_method_id', 1); } else { @@ -489,32 +489,32 @@ if ($object->id > 0) // Categories if (!empty($conf->categorie->enabled) && !empty($user->rights->categorie->lire)) { $langs->load("categories"); - print '
' . $langs->trans("CustomersCategoriesShort") . '
'.$langs->trans("CustomersCategoriesShort").''; print $form->showCategories($object->id, 'customer', 1); print "
'.$langs->trans("LinkedToDolibarrMember").''; - $adh=new Adherent($db); - $result=$adh->fetch('', '', $object->id); + $adh = new Adherent($db); + $result = $adh->fetch('', '', $object->id); if ($result > 0) { - $adh->ref=$adh->getFullName($langs); + $adh->ref = $adh->getFullName($langs); print $adh->getNomUrl(1); } else @@ -558,10 +558,10 @@ if ($object->id > 0) print '
'.$langs->trans("StatusProsp").''.$object->getLibProspCommStatut(4, $object->cacheprospectstatus[$object->stcomm_id]['label']); print '     '; print '
'; - foreach($object->cacheprospectstatus as $key => $val) + 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']; + $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']).''; } print '
'; - $boxstat.=''; + $boxstat .= '
'; + $boxstat .= '
'; + $boxstat .= ''; + $boxstat .= ''; - $boxstat.='
'; - if (! empty($conf->propal->enabled)) + if (!empty($conf->propal->enabled)) { // Box proposals $tmp = $object->getOutstandingProposals(); - $outstandingOpened=$tmp['opened']; - $outstandingTotal=$tmp['total_ht']; - $outstandingTotalIncTax=$tmp['total_ttc']; - $text=$langs->trans("OverAllProposals"); - $link=DOL_URL_ROOT.'/comm/propal/list.php?socid='.$object->id; - $icon='bill'; - if ($link) $boxstat.=''; - $boxstat.='
'; - $boxstat.=''.img_object("", $icon).' '.$text.'
'; - $boxstat.=''.price($outstandingTotal, 1, $langs, 1, -1, -1, $conf->currency).''; - $boxstat.='
'; - if ($link) $boxstat.='
'; + $outstandingOpened = $tmp['opened']; + $outstandingTotal = $tmp['total_ht']; + $outstandingTotalIncTax = $tmp['total_ttc']; + $text = $langs->trans("OverAllProposals"); + $link = DOL_URL_ROOT.'/comm/propal/list.php?socid='.$object->id; + $icon = 'bill'; + if ($link) $boxstat .= ''; + $boxstat .= '
'; + $boxstat .= ''.img_object("", $icon).' '.$text.'
'; + $boxstat .= ''.price($outstandingTotal, 1, $langs, 1, -1, -1, $conf->currency).''; + $boxstat .= '
'; + if ($link) $boxstat .= '
'; } - if (! empty($conf->commande->enabled)) + if (!empty($conf->commande->enabled)) { // Box commandes $tmp = $object->getOutstandingOrders(); - $outstandingOpened=$tmp['opened']; - $outstandingTotal=$tmp['total_ht']; - $outstandingTotalIncTax=$tmp['total_ttc']; - $text=$langs->trans("OverAllOrders"); - $link=DOL_URL_ROOT.'/commande/list.php?socid='.$object->id; - $icon='bill'; - if ($link) $boxstat.=''; - $boxstat.='
'; - $boxstat.=''.img_object("", $icon).' '.$text.'
'; - $boxstat.=''.price($outstandingTotal, 1, $langs, 1, -1, -1, $conf->currency).''; - $boxstat.='
'; - if ($link) $boxstat.='
'; + $outstandingOpened = $tmp['opened']; + $outstandingTotal = $tmp['total_ht']; + $outstandingTotalIncTax = $tmp['total_ttc']; + $text = $langs->trans("OverAllOrders"); + $link = DOL_URL_ROOT.'/commande/list.php?socid='.$object->id; + $icon = 'bill'; + if ($link) $boxstat .= ''; + $boxstat .= '
'; + $boxstat .= ''.img_object("", $icon).' '.$text.'
'; + $boxstat .= ''.price($outstandingTotal, 1, $langs, 1, -1, -1, $conf->currency).''; + $boxstat .= '
'; + if ($link) $boxstat .= '
'; } - if (! empty($conf->facture->enabled)) + if (!empty($conf->facture->enabled)) { // Box factures $tmp = $object->getOutstandingBills(); - $outstandingOpened=$tmp['opened']; - $outstandingTotal=$tmp['total_ht']; - $outstandingTotalIncTax=$tmp['total_ttc']; - $text=$langs->trans("OverAllInvoices"); - $link=DOL_URL_ROOT.'/compta/facture/list.php?socid='.$object->id; - $icon='bill'; - if ($link) $boxstat.=''; - $boxstat.='
'; - $boxstat.=''.img_object("", $icon).' '.$text.'
'; - $boxstat.=''.price($outstandingTotal, 1, $langs, 1, -1, -1, $conf->currency).''; - $boxstat.='
'; - if ($link) $boxstat.='
'; + $outstandingOpened = $tmp['opened']; + $outstandingTotal = $tmp['total_ht']; + $outstandingTotalIncTax = $tmp['total_ttc']; + $text = $langs->trans("OverAllInvoices"); + $link = DOL_URL_ROOT.'/compta/facture/list.php?socid='.$object->id; + $icon = 'bill'; + if ($link) $boxstat .= ''; + $boxstat .= '
'; + $boxstat .= ''.img_object("", $icon).' '.$text.'
'; + $boxstat .= ''.price($outstandingTotal, 1, $langs, 1, -1, -1, $conf->currency).''; + $boxstat .= '
'; + if ($link) $boxstat .= '
'; // Box outstanding bill $warn = ''; @@ -640,50 +640,50 @@ if ($object->id > 0) { $warn = ' '.img_warning($langs->trans("OutstandingBillReached")); } - $text=$langs->trans("CurrentOutstandingBill"); - $link=DOL_URL_ROOT.'/compta/recap-compta.php?socid='.$object->id; - $icon='bill'; - if ($link) $boxstat.=''; - $boxstat.='
'; - $boxstat.=''.img_object("", $icon).' '.$text.'
'; - $boxstat.=''.price($outstandingOpened, 1, $langs, 1, -1, -1, $conf->currency).$warn.''; - $boxstat.='
'; - if ($link) $boxstat.='
'; + $text = $langs->trans("CurrentOutstandingBill"); + $link = DOL_URL_ROOT.'/compta/recap-compta.php?socid='.$object->id; + $icon = 'bill'; + if ($link) $boxstat .= ''; + $boxstat .= '
'; + $boxstat .= ''.img_object("", $icon).' '.$text.'
'; + $boxstat .= ''.price($outstandingOpened, 1, $langs, 1, -1, -1, $conf->currency).$warn.''; + $boxstat .= '
'; + if ($link) $boxstat .= '
'; } $parameters = array(); $reshook = $hookmanager->executeHooks('addMoreBoxStatsCustomer', $parameters, $object, $action); - if(empty($reshook)){ - $boxstat.= $hookmanager->resPrint; + if (empty($reshook)) { + $boxstat .= $hookmanager->resPrint; } - $boxstat.='
'; - $boxstat.='
'; + $boxstat .= '
'; + $boxstat .= ''; print $boxstat; - $now=dol_now(); + $now = dol_now(); /* * Last proposals */ - if (! empty($conf->propal->enabled) && $user->rights->propal->lire) + if (!empty($conf->propal->enabled) && $user->rights->propal->lire) { $langs->load("propal"); $sql = "SELECT s.nom, s.rowid, p.rowid as propalid, p.fk_statut, p.total_ht"; - $sql.= ", p.tva as total_tva"; - $sql.= ", p.total as total_ttc"; - $sql.= ", p.ref, p.ref_client, p.remise"; - $sql.= ", p.datep as dp, p.fin_validite as datelimite"; - $sql.= " FROM ".MAIN_DB_PREFIX."societe as s, ".MAIN_DB_PREFIX."propal as p, ".MAIN_DB_PREFIX."c_propalst as c"; - $sql.= " WHERE p.fk_soc = s.rowid AND p.fk_statut = c.id"; - $sql.= " AND s.rowid = ".$object->id; - $sql.= " AND p.entity IN (".getEntity('propal').")"; - $sql.= " ORDER BY p.datep DESC"; + $sql .= ", p.tva as total_tva"; + $sql .= ", p.total as total_ttc"; + $sql .= ", p.ref, p.ref_client, p.remise"; + $sql .= ", p.datep as dp, p.fin_validite as datelimite"; + $sql .= " FROM ".MAIN_DB_PREFIX."societe as s, ".MAIN_DB_PREFIX."propal as p, ".MAIN_DB_PREFIX."c_propalst as c"; + $sql .= " WHERE p.fk_soc = s.rowid AND p.fk_statut = c.id"; + $sql .= " AND s.rowid = ".$object->id; + $sql .= " AND p.entity IN (".getEntity('propal').")"; + $sql .= " ORDER BY p.datep DESC"; - $resql=$db->query($sql); + $resql = $db->query($sql); if ($resql) { $propal_static = new Propal($db); @@ -695,7 +695,7 @@ if ($object->id > 0) print ''; print ''; - print '
'; + print ''; print ''; @@ -715,7 +715,7 @@ if ($object->id > 0) $propal_static->total_tva = $objp->total_tva; $propal_static->total_ttc = $objp->total_ttc; print $propal_static->getNomUrl(1); - if ( ($db->jdate($objp->datelimite) < ($now - $conf->propal->cloture->warning_delay)) && $objp->fk_statut == 1 ) { + if (($db->jdate($objp->datelimite) < ($now - $conf->propal->cloture->warning_delay)) && $objp->fk_statut == 1) { print " ".img_warning(); } print '\n"; @@ -740,39 +740,39 @@ if ($object->id > 0) /* * Last orders */ - if (! empty($conf->commande->enabled) && $user->rights->commande->lire) + if (!empty($conf->commande->enabled) && $user->rights->commande->lire) { $sql = "SELECT s.nom, s.rowid"; - $sql.= ", c.rowid as cid, c.total_ht"; - $sql.= ", c.tva as total_tva"; - $sql.= ", c.total_ttc"; - $sql.= ", c.ref, c.ref_client, c.fk_statut, c.facture"; - $sql.= ", c.date_commande as dc"; - $sql.= " FROM ".MAIN_DB_PREFIX."societe as s, ".MAIN_DB_PREFIX."commande as c"; - $sql.= " WHERE c.fk_soc = s.rowid "; - $sql.= " AND s.rowid = ".$object->id; - $sql.= " AND c.entity = ".$conf->entity; - $sql.= " ORDER BY c.date_commande DESC"; + $sql .= ", c.rowid as cid, c.total_ht"; + $sql .= ", c.tva as total_tva"; + $sql .= ", c.total_ttc"; + $sql .= ", c.ref, c.ref_client, c.fk_statut, c.facture"; + $sql .= ", c.date_commande as dc"; + $sql .= " FROM ".MAIN_DB_PREFIX."societe as s, ".MAIN_DB_PREFIX."commande as c"; + $sql .= " WHERE c.fk_soc = s.rowid "; + $sql .= " AND s.rowid = ".$object->id; + $sql .= " AND c.entity = ".$conf->entity; + $sql .= " ORDER BY c.date_commande DESC"; - $resql=$db->query($sql); + $resql = $db->query($sql); if ($resql) { - $commande_static=new Commande($db); + $commande_static = new Commande($db); $num = $db->num_rows($resql); if ($num > 0) { // Check if there are orders billable $sql2 = 'SELECT s.nom, s.rowid as socid, s.client, c.rowid, c.ref, c.total_ht, c.ref_client,'; - $sql2.= ' c.date_valid, c.date_commande, c.date_livraison, c.fk_statut, c.facture as billed'; - $sql2.= ' FROM '.MAIN_DB_PREFIX.'societe as s'; - $sql2.= ', '.MAIN_DB_PREFIX.'commande as c'; - $sql2.= ' WHERE c.fk_soc = s.rowid'; - $sql2.= ' AND s.rowid = '.$object->id; + $sql2 .= ' c.date_valid, c.date_commande, c.date_livraison, c.fk_statut, c.facture as billed'; + $sql2 .= ' FROM '.MAIN_DB_PREFIX.'societe as s'; + $sql2 .= ', '.MAIN_DB_PREFIX.'commande as c'; + $sql2 .= ' WHERE c.fk_soc = s.rowid'; + $sql2 .= ' AND s.rowid = '.$object->id; // Show orders with status validated, shipping started and delivered (well any order we can bill) - $sql2.= " AND ((c.fk_statut IN (1,2)) OR (c.fk_statut = 3 AND c.facture = 0))"; + $sql2 .= " AND ((c.fk_statut IN (1,2)) OR (c.fk_statut = 3 AND c.facture = 0))"; - $resql2=$db->query($sql2); + $resql2 = $db->query($sql2); $orders2invoice = $db->num_rows($resql2); $db->free($resql2); @@ -780,7 +780,7 @@ if ($object->id > 0) print '
'.$langs->trans("LastPropals", ($num<=$MAXLIST?"":$MAXLIST)).''.$langs->trans("AllPropals").' '.$num.''; print ''; print '
'.$langs->trans("LastPropals", ($num <= $MAXLIST ? "" : $MAXLIST)).''.$langs->trans("AllPropals").' '.$num.''.img_picto($langs->trans("Statistics"), 'stats').'
'.dol_print_date($db->jdate($objp->dp), 'day')."
'; print ''; - print '\n"; - if (! $i) $totalarray['nbfield']++; + if (!$i) $totalarray['nbfield']++; } - if (! empty($arrayfields['p.ref_client']['checked'])) + if (!empty($arrayfields['p.ref_client']['checked'])) { // Customer ref print ''; - if (! $i) $totalarray['nbfield']++; + if (!$i) $totalarray['nbfield']++; } - if (! empty($arrayfields['pr.ref']['checked'])) + if (!empty($arrayfields['pr.ref']['checked'])) { // Project ref print ''; - if (! $i) $totalarray['nbfield']++; + if (!$i) $totalarray['nbfield']++; } - if (! empty($arrayfields['pr.title']['checked'])) + if (!empty($arrayfields['pr.title']['checked'])) { // Project label print ''; - if (! $i) $totalarray['nbfield']++; + if (!$i) $totalarray['nbfield']++; } // Thirdparty - if (! empty($arrayfields['s.nom']['checked'])) + if (!empty($arrayfields['s.nom']['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'])) { - if (! is_array($typenArray) || empty($typenArray)) $typenArray = $formcompany->typent_array(1); + if (!is_array($typenArray) || empty($typenArray)) $typenArray = $formcompany->typent_array(1); print ''; - if (! $i) $totalarray['nbfield']++; + if (!$i) $totalarray['nbfield']++; } // Date proposal - if (! empty($arrayfields['p.date']['checked'])) + if (!empty($arrayfields['p.date']['checked'])) { print '\n"; - if (! $i) $totalarray['nbfield']++; + if (!$i) $totalarray['nbfield']++; } // Date end validity - if (! empty($arrayfields['p.fin_validite']['checked'])) + if (!empty($arrayfields['p.fin_validite']['checked'])) { if ($obj->dfv) { @@ -917,10 +917,10 @@ if ($resql) { print ''; } - if (! $i) $totalarray['nbfield']++; + if (!$i) $totalarray['nbfield']++; } // Date delivery - if (! empty($arrayfields['p.date_livraison']['checked'])) + if (!empty($arrayfields['p.date_livraison']['checked'])) { if ($obj->ddelivery) { @@ -1038,17 +1038,17 @@ if ($resql) } elseif ($nbofsalesrepresentative > 0) { - $userstatic=new User($db); - $j=0; - foreach($listsalesrepresentatives as $val) + $userstatic = new User($db); + $j = 0; + foreach ($listsalesrepresentatives as $val) { - $userstatic->id=$val['id']; - $userstatic->lastname=$val['lastname']; - $userstatic->firstname=$val['firstname']; - $userstatic->email=$val['email']; - $userstatic->statut=$val['statut']; - $userstatic->entity=$val['entity']; - $userstatic->photo=$val['photo']; + $userstatic->id = $val['id']; + $userstatic->lastname = $val['lastname']; + $userstatic->firstname = $val['firstname']; + $userstatic->email = $val['email']; + $userstatic->statut = $val['statut']; + $userstatic->entity = $val['entity']; + $userstatic->photo = $val['photo']; //print '
': print $userstatic->getNomUrl(-2); @@ -1064,55 +1064,55 @@ if ($resql) print ' '; } print ''; - if (! $i) $totalarray['nbfield']++; + if (!$i) $totalarray['nbfield']++; } // Extra fields include DOL_DOCUMENT_ROOT.'/core/tpl/extrafields_list_print_fields.tpl.php'; // Fields from hook - $parameters=array('arrayfields'=>$arrayfields, 'obj'=>$obj, 'i'=>$i); - $reshook=$hookmanager->executeHooks('printFieldListValue', $parameters); // Note that $action and $object may have been modified by hook + $parameters = array('arrayfields'=>$arrayfields, 'obj'=>$obj, 'i'=>$i); + $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']++; } // Date cloture - if (! empty($arrayfields['p.date_cloture']['checked'])) + if (!empty($arrayfields['p.date_cloture']['checked'])) { print ''; - if (! $i) $totalarray['nbfield']++; + if (!$i) $totalarray['nbfield']++; } // Status - if (! empty($arrayfields['p.fk_statut']['checked'])) + if (!empty($arrayfields['p.fk_statut']['checked'])) { print ''; - if (! $i) $totalarray['nbfield']++; + if (!$i) $totalarray['nbfield']++; } // Action column print ''; - if (! $i) $totalarray['nbfield']++; + if (!$i) $totalarray['nbfield']++; print "\n"; @@ -1124,8 +1124,8 @@ if ($resql) $db->free($resql); - $parameters=array('arrayfields'=>$arrayfields, 'sql'=>$sql); - $reshook=$hookmanager->executeHooks('printFieldListFooter', $parameters); // Note that $action and $object may have been modified by hook + $parameters = array('arrayfields'=>$arrayfields, 'sql'=>$sql); + $reshook = $hookmanager->executeHooks('printFieldListFooter', $parameters); // Note that $action and $object may have been modified by hook print $hookmanager->resPrint; print '
'; + print '
'.$langs->trans("LastCustomerOrders", ($num<=$MAXLIST?"":$MAXLIST)).''.$langs->trans("AllOrders").' '.$num.''; print ''; //if($num2 > 0) print ''; //else print ''; @@ -795,7 +795,7 @@ if ($object->id > 0) $commande_static->id = $objp->cid; $commande_static->ref = $objp->ref; - $commande_static->ref_client=$objp->ref_client; + $commande_static->ref_client = $objp->ref_client; $commande_static->total_ht = $objp->total_ht; $commande_static->total_tva = $objp->total_tva; $commande_static->total_ttc = $objp->total_ttc; @@ -811,7 +811,7 @@ if ($object->id > 0) } $db->free($resql); - if ($num >0) + if ($num > 0) { print "
'.$langs->trans("LastCustomerOrders", ($num <= $MAXLIST ? "" : $MAXLIST)).''.$langs->trans("AllOrders").' '.$num.''.img_picto($langs->trans("Statistics"), 'stats').''.img_picto($langs->trans("CreateInvoiceForThisCustomer"),'object_bill').''.img_picto($langs->trans("NoOrdersToInvoice"),'object_bill').'
"; print ''; @@ -826,24 +826,24 @@ if ($object->id > 0) /* * Last shipments */ - if (! empty($conf->expedition->enabled) && $user->rights->expedition->lire) + if (!empty($conf->expedition->enabled) && $user->rights->expedition->lire) { $sql = 'SELECT e.rowid as id'; - $sql.= ', e.ref'; - $sql.= ', e.date_creation'; - $sql.= ', e.fk_statut as statut'; - $sql.= ', s.nom'; - $sql.= ', s.rowid as socid'; - $sql.= " FROM ".MAIN_DB_PREFIX."societe as s, ".MAIN_DB_PREFIX."expedition as e"; - $sql.= " WHERE e.fk_soc = s.rowid AND s.rowid = ".$object->id; - $sql.= " AND e.entity IN (".getEntity('expedition').")"; - $sql.= ' GROUP BY e.rowid'; - $sql.= ', e.ref'; - $sql.= ', e.date_creation'; - $sql.= ', e.fk_statut'; - $sql.= ', s.nom'; - $sql.= ', s.rowid'; - $sql.= " ORDER BY e.date_creation DESC"; + $sql .= ', e.ref'; + $sql .= ', e.date_creation'; + $sql .= ', e.fk_statut as statut'; + $sql .= ', s.nom'; + $sql .= ', s.rowid as socid'; + $sql .= " FROM ".MAIN_DB_PREFIX."societe as s, ".MAIN_DB_PREFIX."expedition as e"; + $sql .= " WHERE e.fk_soc = s.rowid AND s.rowid = ".$object->id; + $sql .= " AND e.entity IN (".getEntity('expedition').")"; + $sql .= ' GROUP BY e.rowid'; + $sql .= ', e.ref'; + $sql .= ', e.date_creation'; + $sql .= ', e.fk_statut'; + $sql .= ', s.nom'; + $sql .= ', s.rowid'; + $sql .= " ORDER BY e.date_creation DESC"; $resql = $db->query($sql); if ($resql) @@ -856,7 +856,7 @@ if ($object->id > 0) print ''; print ''; - print '
'; + print ''; print ''; @@ -880,7 +880,7 @@ if ($object->id > 0) print ''; } - print ''; + print ''; print "\n"; $i++; } @@ -899,28 +899,28 @@ if ($object->id > 0) /* * Last linked contracts */ - if (! empty($conf->contrat->enabled) && $user->rights->contrat->lire) + if (!empty($conf->contrat->enabled) && $user->rights->contrat->lire) { $sql = "SELECT s.nom, s.rowid, c.rowid as id, c.ref as ref, c.statut, c.datec as dc, c.date_contrat as dcon, c.ref_customer as refcus, c.ref_supplier as refsup"; - $sql.= " FROM ".MAIN_DB_PREFIX."societe as s, ".MAIN_DB_PREFIX."contrat as c"; - $sql.= " WHERE c.fk_soc = s.rowid "; - $sql.= " AND s.rowid = ".$object->id; - $sql.= " AND c.entity = ".$conf->entity; - $sql.= " ORDER BY c.datec DESC"; + $sql .= " FROM ".MAIN_DB_PREFIX."societe as s, ".MAIN_DB_PREFIX."contrat as c"; + $sql .= " WHERE c.fk_soc = s.rowid "; + $sql .= " AND s.rowid = ".$object->id; + $sql .= " AND c.entity = ".$conf->entity; + $sql .= " ORDER BY c.datec DESC"; - $resql=$db->query($sql); + $resql = $db->query($sql); if ($resql) { - $contrat=new Contrat($db); + $contrat = new Contrat($db); $num = $db->num_rows($resql); - if ($num >0) + if ($num > 0) { print '
'; print '
'.$langs->trans("LastSendings", ($num<=$MAXLIST?"":$MAXLIST)).''.$langs->trans("AllSendings").' '.$num.''; print ''; print '
'.$langs->trans("LastSendings", ($num <= $MAXLIST ? "" : $MAXLIST)).''.$langs->trans("AllSendings").' '.$num.''.img_picto($langs->trans("Statistics"), 'stats').'
!!!' . $sendingstatic->LibStatut($objp->statut, 5) . ''.$sendingstatic->LibStatut($objp->statut, 5).'
'; print ''; - print ''; - print ''; + print ''; + print ''; print ''; // Multicurrency Amount VAT - print ''; - print ''; + print ''; + print ''; print ''; // Multicurrency Amount TTC - print ''; - print ''; + print ''; + print ''; print ''; } // Amount HT - print ''; - print ''; + print ''; + print ''; print ''; // Amount VAT - print ''; - print ''; + print ''; + print ''; print ''; // Amount Local Taxes if ($mysoc->localtax1_assuj == "1" || $object->total_localtax1 != 0) // Localtax1 { - print ''; - print ''; + print ''; + print ''; print ''; } if ($mysoc->localtax2_assuj == "1" || $object->total_localtax2 != 0) // Localtax2 { - print ''; - print ''; + print ''; + print ''; print ''; } // Amount TTC - print ''; - print ''; + print ''; + print ''; print ''; // Statut @@ -2380,7 +2380,7 @@ if ($action == 'create') print '
'; + print ''; @@ -932,10 +932,10 @@ if ($object->id > 0) { $objp = $db->fetch_object($resql); - $contrat->id=$objp->id; - $contrat->ref=$objp->ref?$objp->ref:$objp->id; - $contrat->ref_customer=$objp->refcus; - $contrat->ref_supplier=$objp->refsup; + $contrat->id = $objp->id; + $contrat->ref = $objp->ref ? $objp->ref : $objp->id; + $contrat->ref_customer = $objp->refcus; + $contrat->ref_supplier = $objp->refsup; $contrat->fetch_lines(); print ''; @@ -969,19 +969,19 @@ if ($object->id > 0) /* * Last interventions */ - if (! empty($conf->ficheinter->enabled) && $user->rights->ficheinter->lire) + if (!empty($conf->ficheinter->enabled) && $user->rights->ficheinter->lire) { $sql = "SELECT s.nom, s.rowid, f.rowid as id, f.ref, f.fk_statut, f.duree as duration, f.datei as startdate"; - $sql.= " FROM ".MAIN_DB_PREFIX."societe as s, ".MAIN_DB_PREFIX."fichinter as f"; - $sql.= " WHERE f.fk_soc = s.rowid"; - $sql.= " AND s.rowid = ".$object->id; - $sql.= " AND f.entity = ".$conf->entity; - $sql.= " ORDER BY f.tms DESC"; + $sql .= " FROM ".MAIN_DB_PREFIX."societe as s, ".MAIN_DB_PREFIX."fichinter as f"; + $sql .= " WHERE f.fk_soc = s.rowid"; + $sql .= " AND s.rowid = ".$object->id; + $sql .= " AND f.entity = ".$conf->entity; + $sql .= " ORDER BY f.tms DESC"; - $resql=$db->query($sql); + $resql = $db->query($sql); if ($resql) { - $fichinter_static=new Fichinter($db); + $fichinter_static = new Fichinter($db); $num = $db->num_rows($resql); if ($num > 0) @@ -990,7 +990,7 @@ if ($object->id > 0) print '
'.$langs->trans("LastContracts", ($num<=$MAXLIST?"":$MAXLIST)).''; print ''; //print ''; print '
'.$langs->trans("LastContracts", ($num <= $MAXLIST ? "" : $MAXLIST)).''.$langs->trans("AllContracts").' '.$num.''.img_picto($langs->trans("Statistics"),'stats').'
'; print ''; - print ''; print ''; } - if (! empty($conf->global->BANK_ASK_PAYMENT_BANK_DURING_PROPOSAL) && ! empty($conf->banque->enabled)) + if (!empty($conf->global->BANK_ASK_PAYMENT_BANK_DURING_PROPOSAL) && !empty($conf->banque->enabled)) { // Bank Account print ''; } - $tmparray=$object->getTotalWeightVolume(); - $totalWeight=$tmparray['weight']; - $totalVolume=$tmparray['volume']; + $tmparray = $object->getTotalWeightVolume(); + $totalWeight = $tmparray['weight']; + $totalVolume = $tmparray['volume']; if ($totalWeight) { - print ''; + print ''; print ''; } if ($totalVolume) { - print ''; + print ''; print ''; } @@ -2310,13 +2310,13 @@ if ($action == 'create') } 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); + print $form->select_incoterms((!empty($object->fk_incoterms) ? $object->fk_incoterms : ''), (!empty($object->location_incoterms) ? $object->location_incoterms : ''), $_SERVER['PHP_SELF'].'?id='.$object->id); } print ''; } // Other attributes - include DOL_DOCUMENT_ROOT . '/core/tpl/extrafields_view.tpl.php'; + include DOL_DOCUMENT_ROOT.'/core/tpl/extrafields_view.tpl.php'; print '
'; + print ''; print ''; @@ -1001,8 +1001,8 @@ if ($object->id > 0) { $objp = $db->fetch_object($resql); - $fichinter_static->id=$objp->id; - $fichinter_static->statut=$objp->fk_statut; + $fichinter_static->id = $objp->id; + $fichinter_static->statut = $objp->fk_statut; print ''; print ''."\n"; @@ -1030,28 +1030,28 @@ if ($object->id > 0) /* * Last invoices templates */ - if (! empty($conf->facture->enabled) && $user->rights->facture->lire) + if (!empty($conf->facture->enabled) && $user->rights->facture->lire) { $sql = 'SELECT f.rowid as id, f.titre as ref, f.amount'; - $sql.= ', f.total as total_ht'; - $sql.= ', f.tva as total_tva'; - $sql.= ', f.total_ttc'; - $sql.= ', f.datec as dc'; - $sql.= ', f.date_last_gen, f.date_when'; - $sql.= ', f.frequency'; - $sql.= ', f.unit_frequency'; - $sql.= ', f.suspended as suspended'; - $sql.= ', s.nom, s.rowid as socid'; - $sql.= " FROM ".MAIN_DB_PREFIX."societe as s,".MAIN_DB_PREFIX."facture_rec as f"; - $sql.= " WHERE f.fk_soc = s.rowid AND s.rowid = ".$object->id; - $sql.= " AND f.entity = ".$conf->entity; - $sql.= ' GROUP BY f.rowid, f.titre, f.amount, f.total, f.tva, f.total_ttc,'; - $sql.= ' f.date_last_gen, f.datec, f.frequency, f.unit_frequency,'; - $sql.= ' f.suspended,'; - $sql.= ' s.nom, s.rowid'; - $sql.= " ORDER BY f.date_last_gen, f.datec DESC"; + $sql .= ', f.total as total_ht'; + $sql .= ', f.tva as total_tva'; + $sql .= ', f.total_ttc'; + $sql .= ', f.datec as dc'; + $sql .= ', f.date_last_gen, f.date_when'; + $sql .= ', f.frequency'; + $sql .= ', f.unit_frequency'; + $sql .= ', f.suspended as suspended'; + $sql .= ', s.nom, s.rowid as socid'; + $sql .= " FROM ".MAIN_DB_PREFIX."societe as s,".MAIN_DB_PREFIX."facture_rec as f"; + $sql .= " WHERE f.fk_soc = s.rowid AND s.rowid = ".$object->id; + $sql .= " AND f.entity = ".$conf->entity; + $sql .= ' GROUP BY f.rowid, f.titre, f.amount, f.total, f.tva, f.total_ttc,'; + $sql .= ' f.date_last_gen, f.datec, f.frequency, f.unit_frequency,'; + $sql .= ' f.suspended,'; + $sql .= ' s.nom, s.rowid'; + $sql .= " ORDER BY f.date_last_gen, f.datec DESC"; - $resql=$db->query($sql); + $resql = $db->query($sql); if ($resql) { $invoicetemplate = new FactureRec($db); @@ -1063,7 +1063,7 @@ if ($object->id > 0) print '
'.$langs->trans("LastInterventions", ($num<=$MAXLIST?"":$MAXLIST)).''.$langs->trans("AllInterventions").' '.$num.''; print ''; print '
'.$langs->trans("LastInterventions", ($num <= $MAXLIST ? "" : $MAXLIST)).''.$langs->trans("AllInterventions").' '.$num.''.img_picto($langs->trans("Statistics"), 'stats').'
'.img_object($langs->trans("ShowPropal"), "propal").' '.$objp->ref.'
'; print ''; - print ''; @@ -2223,16 +2223,16 @@ if ($action == 'create') print $form->editfieldkey('CurrencyRate', 'multicurrency_tx', '', $object, 0); print ''; if ($action != 'editmulticurrencyrate' && $object->statut == $object::STATUS_DRAFT && $object->multicurrency_code && $object->multicurrency_code != $conf->currency && $usercancreate) - print ''; + print ''; print '
'; + print ''; print ''; } @@ -1107,7 +1107,7 @@ if ($object->id > 0) print price($objp->total_ht); print ''; - if (! empty($conf->global->MAIN_SHOW_PRICE_WITH_TAX_IN_SUMMARIES)) + if (!empty($conf->global->MAIN_SHOW_PRICE_WITH_TAX_IN_SUMMARIES)) { print ''; // Multicurrency - if (! empty($conf->multicurrency->enabled)) + if (!empty($conf->multicurrency->enabled)) { // Multicurrency code print ''; @@ -2203,13 +2203,13 @@ if ($action == 'create') print $form->editfieldkey('Currency', 'multicurrency_code', '', $object, 0); print ''; if ($action != 'editmulticurrencycode' && $object->statut == $object::STATUS_DRAFT && $usercancreate) - print ''; + print ''; print '
'.$langs->trans("LatestCustomerTemplateInvoices", ($num<=$MAXLIST?"":$MAXLIST)).''.$langs->trans("AllCustomerTemplateInvoices").' '.$num.''; print '
'.$langs->trans("LatestCustomerTemplateInvoices", ($num <= $MAXLIST ? "" : $MAXLIST)).''.$langs->trans("AllCustomerTemplateInvoices").' '.$num.'
'; print price($objp->total_ttc); @@ -1138,25 +1138,25 @@ if ($object->id > 0) /* * Last invoices */ - if (! empty($conf->facture->enabled) && $user->rights->facture->lire) + if (!empty($conf->facture->enabled) && $user->rights->facture->lire) { $sql = 'SELECT f.rowid as facid, f.ref, f.type, f.amount'; - $sql.= ', f.total as total_ht'; - $sql.= ', f.tva as total_tva'; - $sql.= ', f.total_ttc'; - $sql.= ', f.datef as df, f.datec as dc, f.paye as paye, f.fk_statut as statut'; - $sql.= ', s.nom, s.rowid as socid'; - $sql.= ', SUM(pf.amount) as am'; - $sql.= " FROM ".MAIN_DB_PREFIX."societe as s,".MAIN_DB_PREFIX."facture as f"; - $sql.= ' LEFT JOIN '.MAIN_DB_PREFIX.'paiement_facture as pf ON f.rowid=pf.fk_facture'; - $sql.= " WHERE f.fk_soc = s.rowid AND s.rowid = ".$object->id; - $sql.= " AND f.entity IN (".getEntity('invoice').")"; - $sql.= ' GROUP BY f.rowid, f.ref, f.type, f.amount, f.total, f.tva, f.total_ttc,'; - $sql.= ' f.datef, f.datec, f.paye, f.fk_statut,'; - $sql.= ' s.nom, s.rowid'; - $sql.= " ORDER BY f.datef DESC, f.datec DESC"; + $sql .= ', f.total as total_ht'; + $sql .= ', f.tva as total_tva'; + $sql .= ', f.total_ttc'; + $sql .= ', f.datef as df, f.datec as dc, f.paye as paye, f.fk_statut as statut'; + $sql .= ', s.nom, s.rowid as socid'; + $sql .= ', SUM(pf.amount) as am'; + $sql .= " FROM ".MAIN_DB_PREFIX."societe as s,".MAIN_DB_PREFIX."facture as f"; + $sql .= ' LEFT JOIN '.MAIN_DB_PREFIX.'paiement_facture as pf ON f.rowid=pf.fk_facture'; + $sql .= " WHERE f.fk_soc = s.rowid AND s.rowid = ".$object->id; + $sql .= " AND f.entity IN (".getEntity('invoice').")"; + $sql .= ' GROUP BY f.rowid, f.ref, f.type, f.amount, f.total, f.tva, f.total_ttc,'; + $sql .= ' f.datef, f.datec, f.paye, f.fk_statut,'; + $sql .= ' s.nom, s.rowid'; + $sql .= " ORDER BY f.datef DESC, f.datec DESC"; - $resql=$db->query($sql); + $resql = $db->query($sql); if ($resql) { $facturestatic = new Facture($db); @@ -1168,7 +1168,7 @@ if ($object->id > 0) print ''; print ''; - print ''; - $trackid=''; // TODO To avoid conflicts with 2 mass emailing, we should set a trackid here, even if we use another one into email header. + $trackid = ''; // TODO To avoid conflicts with 2 mass emailing, we should set a trackid here, even if we use another one into email header. dol_init_file_process($upload_dir, $trackid); // Joined files - $addfileaction='addfile'; + $addfileaction = 'addfile'; print ''; print ''; @@ -1330,14 +1330,14 @@ else { // Editeur wysiwyg require_once DOL_DOCUMENT_ROOT.'/core/class/doleditor.class.php'; - $doleditor=new DolEditor('bodyemail', $object->body, '', 600, 'dolibarr_mailings', '', true, true, $conf->global->FCKEDITOR_ENABLE_MAILING, 20, '90%'); + $doleditor = new DolEditor('bodyemail', $object->body, '', 600, 'dolibarr_mailings', '', true, true, $conf->global->FCKEDITOR_ENABLE_MAILING, 20, '90%'); $doleditor->Create(); } if ($action == 'edithtml') { // Editor HTML source require_once DOL_DOCUMENT_ROOT.'/core/class/doleditor.class.php'; - $doleditor=new DolEditor('bodyemail', $object->body, '', 600, 'dolibarr_mailings', '', true, true, 'ace', 20, '90%'); + $doleditor = new DolEditor('bodyemail', $object->body, '', 600, 'dolibarr_mailings', '', true, true, 'ace', 20, '90%'); $doleditor->Create(0, '', false, 'HTML Source', 'php'); } diff --git a/htdocs/comm/mailing/cibles.php b/htdocs/comm/mailing/cibles.php index 819e0acf562..f2754658f37 100644 --- a/htdocs/comm/mailing/cibles.php +++ b/htdocs/comm/mailing/cibles.php @@ -36,11 +36,11 @@ require_once DOL_DOCUMENT_ROOT.'/core/lib/functions2.lib.php'; $langs->load("mails"); // Security check -if (! $user->rights->mailing->lire || $user->socid > 0) accessforbidden(); +if (!$user->rights->mailing->lire || $user->socid > 0) accessforbidden(); // Load variable for pagination -$limit = GETPOST('limit', 'int')?GETPOST('limit', 'int'):$conf->liste_limit; +$limit = GETPOST('limit', 'int') ?GETPOST('limit', 'int') : $conf->liste_limit; $sortfield = GETPOST('sortfield', 'alpha'); $sortorder = GETPOST('sortorder', 'alpha'); $page = GETPOST('page', 'int'); @@ -48,23 +48,23 @@ if (empty($page) || $page == -1) { $page = 0; } // If $page is not defined, $offset = $limit * $page; $pageprev = $page - 1; $pagenext = $page + 1; -if (! $sortfield) $sortfield="email"; -if (! $sortorder) $sortorder="ASC"; +if (!$sortfield) $sortfield = "email"; +if (!$sortorder) $sortorder = "ASC"; -$id=GETPOST('id', 'int'); -$rowid=GETPOST('rowid', 'int'); -$action=GETPOST('action', 'aZ09'); -$search_lastname=GETPOST("search_lastname", 'alphanohtml'); -$search_firstname=GETPOST("search_firstname", 'alphanohtml'); -$search_email=GETPOST("search_email", 'alphanohtml'); -$search_other=GETPOST("search_other", 'alphanohtml'); -$search_dest_status=GETPOST('search_dest_status', 'alphanohtml'); +$id = GETPOST('id', 'int'); +$rowid = GETPOST('rowid', 'int'); +$action = GETPOST('action', 'aZ09'); +$search_lastname = GETPOST("search_lastname", 'alphanohtml'); +$search_firstname = GETPOST("search_firstname", 'alphanohtml'); +$search_email = GETPOST("search_email", 'alphanohtml'); +$search_other = GETPOST("search_other", 'alphanohtml'); +$search_dest_status = GETPOST('search_dest_status', 'alphanohtml'); // Search modules dirs $modulesdir = dolGetModulesDirs('/mailings'); $object = new Mailing($db); -$result=$object->fetch($id); +$result = $object->fetch($id); /* @@ -73,8 +73,8 @@ $result=$object->fetch($id); if ($action == 'add') { - $module=GETPOST("module", 'alpha'); - $result=-1; + $module = GETPOST("module", 'alpha'); + $result = -1; foreach ($modulesdir as $dir) { @@ -93,7 +93,7 @@ if ($action == 'add') // Add targets into database $obj = new $classname($db); dol_syslog("Call add_to_target on class ".$classname); - $result=$obj->add_to_target($id); + $result = $obj->add_to_target($id); } } if ($result > 0) @@ -109,7 +109,7 @@ if ($action == 'add') } if ($result < 0) { - setEventMessages($langs->trans("Error").($obj->error?' '.$obj->error:''), null, 'errors'); + setEventMessages($langs->trans("Error").($obj->error ? ' '.$obj->error : ''), null, 'errors'); } } @@ -128,7 +128,7 @@ if (GETPOST('exportcsv', 'int')) { $completefilename = 'targets_emailing'.$object->id.'_'.dol_print_date(dol_now(), 'dayhourlog').'.csv'; header('Content-Type: text/csv'); - header('Content-Disposition: attachment;filename=' . $completefilename); + header('Content-Disposition: attachment;filename='.$completefilename); // List of selected targets $sql = "SELECT mc.rowid, mc.lastname, mc.firstname, mc.email, mc.other, mc.statut, mc.date_envoi, mc.tms,"; @@ -137,7 +137,7 @@ if (GETPOST('exportcsv', 'int')) $sql .= " WHERE mc.fk_mailing=".$object->id; $sql .= $db->order($sortfield, $sortorder); - $resql=$db->query($sql); + $resql = $db->query($sql); if ($resql) { $num = $db->num_rows($resql); @@ -145,17 +145,17 @@ if (GETPOST('exportcsv', 'int')) while ($obj = $db->fetch_object($resql)) { - print $obj->rowid . $sep; - print $obj->lastname . $sep; - print $obj->firstname . $sep; - print $obj->email . $sep; - print $obj->other . $sep; - print $obj->date_envoi . $sep; - print $obj->tms . $sep; - print $obj->source_url . $sep; - print $obj->source_id . $sep; - print $obj->source_type . $sep; - print $obj->error_text . $sep; + print $obj->rowid.$sep; + print $obj->lastname.$sep; + print $obj->firstname.$sep; + print $obj->email.$sep; + print $obj->other.$sep; + print $obj->date_envoi.$sep; + print $obj->tms.$sep; + print $obj->source_url.$sep; + print $obj->source_id.$sep; + print $obj->source_type.$sep; + print $obj->error_text.$sep; print "\n"; } @@ -171,11 +171,11 @@ if (GETPOST('exportcsv', 'int')) if ($action == 'delete') { // Ici, rowid indique le destinataire et id le mailing - $sql="DELETE FROM ".MAIN_DB_PREFIX."mailing_cibles WHERE rowid=".$rowid; - $resql=$db->query($sql); + $sql = "DELETE FROM ".MAIN_DB_PREFIX."mailing_cibles WHERE rowid=".$rowid; + $resql = $db->query($sql); if ($resql) { - if (! empty($id)) + if (!empty($id)) { $obj = new MailingTargets($db); $obj->update_nb($id); @@ -195,13 +195,13 @@ if ($action == 'delete') } // Purge search criteria -if (GETPOST('button_removefilter_x', 'alpha') || GETPOST('button_removefilter.x', 'alpha') ||GETPOST('button_removefilter', 'alpha')) // All tests are required to be compatible with all browsers +if (GETPOST('button_removefilter_x', 'alpha') || GETPOST('button_removefilter.x', 'alpha') || GETPOST('button_removefilter', 'alpha')) // All tests are required to be compatible with all browsers { - $search_lastname=''; - $search_firstname=''; - $search_email=''; - $search_other=''; - $search_dest_status=''; + $search_lastname = ''; + $search_firstname = ''; + $search_email = ''; + $search_other = ''; + $search_dest_status = ''; } @@ -223,16 +223,16 @@ if ($object->fetch($id) >= 0) $linkback = ''.$langs->trans("BackToList").''; - $morehtmlright=''; + $morehtmlright = ''; $nbtry = $nbok = 0; if ($object->statut == 2 || $object->statut == 3) { $nbtry = $object->countNbOfTargets('alreadysent'); $nbko = $object->countNbOfTargets('alreadysentko'); - $morehtmlright.=' ('.$nbtry.'/'.$object->nbemail; - if ($nbko) $morehtmlright.=' - '.$nbko.' '.$langs->trans("Error"); - $morehtmlright.=')   '; + $morehtmlright .= ' ('.$nbtry.'/'.$object->nbemail; + if ($nbko) $morehtmlright .= ' - '.$nbko.' '.$langs->trans("Error"); + $morehtmlright .= ')   '; } dol_banner_tab($object, 'id', $linkback, 1, 'rowid', 'ref', '', '', 0, '', $morehtmlright); @@ -254,22 +254,22 @@ if ($object->fetch($id) >= 0) print ''; print ''; @@ -2124,24 +2124,24 @@ if ($action == 'create') print ''; print ''; // Shipping Method - if (! empty($conf->expedition->enabled)) { + if (!empty($conf->expedition->enabled)) { print ''; print ''; @@ -2183,18 +2183,18 @@ if ($action == 'create') print $langs->trans('PaymentMode'); print ''; if ($action != 'editmode' && $object->statut == Propal::STATUS_DRAFT && $usercancreate) - print ''; + print ''; print '
'; + print ''; print ''; @@ -1202,7 +1202,7 @@ if ($object->id > 0) print price($objp->total_ht); print ''; - if (! empty($conf->global->MAIN_SHOW_PRICE_WITH_TAX_IN_SUMMARIES)) + if (!empty($conf->global->MAIN_SHOW_PRICE_WITH_TAX_IN_SUMMARIES)) { print '"; print ''; print ''."\n"; - if(! empty($conf->global->MAIN_DASHBOARD_USE_TOTAL_HT)) { + if (!empty($conf->global->MAIN_DASHBOARD_USE_TOTAL_HT)) { print ''; } else { @@ -883,7 +883,7 @@ if (! empty($conf->commande->enabled) && $user->rights->commande->lire) { print '"; } - elseif ($total>0) + elseif ($total > 0) { print '"; } diff --git a/htdocs/comm/mailing/advtargetemailing.php b/htdocs/comm/mailing/advtargetemailing.php index d9fbd9a37b2..94e885d53dc 100644 --- a/htdocs/comm/mailing/advtargetemailing.php +++ b/htdocs/comm/mailing/advtargetemailing.php @@ -22,30 +22,30 @@ * \brief Page to define emailing targets */ -if (! defined('NOSTYLECHECK')) define('NOSTYLECHECK', '1'); +if (!defined('NOSTYLECHECK')) define('NOSTYLECHECK', '1'); require '../../main.inc.php'; -require_once DOL_DOCUMENT_ROOT . '/comm/mailing/class/mailing.class.php'; -require_once DOL_DOCUMENT_ROOT . '/core/lib/emailing.lib.php'; -require_once DOL_DOCUMENT_ROOT . '/comm/mailing/class/advtargetemailing.class.php'; -require_once DOL_DOCUMENT_ROOT . '/comm/mailing/class/html.formadvtargetemailing.class.php'; -require_once DOL_DOCUMENT_ROOT . '/core/modules/mailings/advthirdparties.modules.php'; -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.'/comm/mailing/class/mailing.class.php'; +require_once DOL_DOCUMENT_ROOT.'/core/lib/emailing.lib.php'; +require_once DOL_DOCUMENT_ROOT.'/comm/mailing/class/advtargetemailing.class.php'; +require_once DOL_DOCUMENT_ROOT.'/comm/mailing/class/html.formadvtargetemailing.class.php'; +require_once DOL_DOCUMENT_ROOT.'/core/modules/mailings/advthirdparties.modules.php'; +require_once DOL_DOCUMENT_ROOT.'/core/class/html.formcompany.class.php'; +require_once DOL_DOCUMENT_ROOT.'/core/class/html.formother.class.php'; // Load translation files required by the page $langs->loadLangs(array('mails', 'companies')); -if (! empty($conf->categorie->enabled)) { +if (!empty($conf->categorie->enabled)) { $langs->load("categories"); } // Security check -if (! $user->rights->mailing->lire || $user->socid > 0) +if (!$user->rights->mailing->lire || $user->socid > 0) accessforbidden(); // Load variable for pagination -$limit = GETPOST('limit', 'int')?GETPOST('limit', 'int'):$conf->liste_limit; +$limit = GETPOST('limit', 'int') ?GETPOST('limit', 'int') : $conf->liste_limit; $sortfield = GETPOST('sortfield', 'alpha'); $sortorder = GETPOST('sortorder', 'alpha'); $page = GETPOST('page', 'int'); @@ -53,9 +53,9 @@ if (empty($page) || $page == -1) { $page = 0; } // If $page is not defined, $offset = $limit * $page; $pageprev = $page - 1; $pagenext = $page + 1; -if (! $sortorder) +if (!$sortorder) $sortorder = "ASC"; -if (! $sortfield) +if (!$sortfield) $sortfield = "email"; $id = GETPOST('id', 'int'); @@ -72,7 +72,7 @@ if (GETPOST('button_removefilter_x', 'alpha')) { $search_prenom = ''; $search_email = ''; } -$array_query = array (); +$array_query = array(); $object = new Mailing($db); $advTarget = new AdvanceTargetingMailing($db); @@ -90,7 +90,7 @@ if ($result < 0) } else { - if (! empty($advTarget->id)) { + if (!empty($advTarget->id)) { $array_query = json_decode($advTarget->filtervalue, true); } } @@ -101,12 +101,12 @@ else */ if ($action == 'loadfilter') { - if (! empty($template_id)) { + if (!empty($template_id)) { $result = $advTarget->fetch($template_id); if ($result < 0) { setEventMessages($advTarget->error, $advTarget->errors, 'errors'); } else { - if (! empty($advTarget->id)) { + if (!empty($advTarget->id)) { $array_query = json_decode($advTarget->filtervalue, true); } } @@ -116,7 +116,7 @@ if ($action == 'loadfilter') { if ($action == 'add') { $user_contact_query = false; - $array_query = array (); + $array_query = array(); // Get extra fields @@ -125,17 +125,17 @@ if ($action == 'add') { if (preg_match("/^options_.*(?contact_lines) == 0) { - $advTarget->contact_lines = array ( + $advTarget->contact_lines = array( 0 ); } } else { - $advTarget->contact_lines = array (); + $advTarget->contact_lines = array(); } if ((count($advTarget->thirdparty_lines) > 0) || (count($advTarget->contact_lines) > 0)) { @@ -234,11 +234,11 @@ if ($action == 'add') { if ($result > 0) { $query_temlate_id = ''; - if (! empty($template_id)) { - $query_temlate_id = '&template_id=' . $template_id; + if (!empty($template_id)) { + $query_temlate_id = '&template_id='.$template_id; } setEventMessages($langs->trans("XTargetsAdded", $result), null, 'mesgs'); - header("Location: " . $_SERVER['PHP_SELF'] . "?id=" . $id . $query_temlate_id); + header("Location: ".$_SERVER['PHP_SELF']."?id=".$id.$query_temlate_id); exit(); } if ($result == 0) { @@ -255,7 +255,7 @@ if ($action == 'clear') { $obj = new $classname($db); $obj->clear_target($id); - header("Location: " . $_SERVER['PHP_SELF'] . "?id=" . $id); + header("Location: ".$_SERVER['PHP_SELF']."?id=".$id); exit(); } @@ -265,28 +265,28 @@ if ($action == 'savefilter' || $action == 'createfilter') { if ($action == 'createfilter' && empty($template_name)) { setEventMessages($langs->trans('ErrorFieldRequired', $langs->transnoentitiesnoconv('AdvTgtOrCreateNewFilter')), null, 'errors'); - $error ++; + $error++; } if (empty($error)) { - $array_query = array (); + $array_query = array(); // Get extra fields foreach ($_POST as $key => $value) { if (preg_match("/^options_.*(?error, $advTarget->errors, 'errors'); } - header("Location: " . $_SERVER['PHP_SELF'] . "?id=" . $id); + header("Location: ".$_SERVER['PHP_SELF']."?id=".$id); exit(); } if ($action == 'delete') { // Ici, rowid indique le destinataire et id le mailing - $sql = "DELETE FROM " . MAIN_DB_PREFIX . "mailing_cibles WHERE rowid=" . $rowid; + $sql = "DELETE FROM ".MAIN_DB_PREFIX."mailing_cibles WHERE rowid=".$rowid; $resql = $db->query($sql); if ($resql) { - if (! empty($id)) { + if (!empty($id)) { $classname = "MailingTargets"; $obj = new $classname($db); $obj->update_nb($id); - header("Location: " . $_SERVER['PHP_SELF'] . "?id=" . $id); + header("Location: ".$_SERVER['PHP_SELF']."?id=".$id); exit(); } else { header("Location: liste.php"); @@ -419,32 +419,32 @@ if ($object->fetch($id) >= 0) { dol_fiche_head($head, 'advtargets', $langs->trans("Mailing"), 0, 'email'); - print '
'.$langs->trans("LastCustomersBills", ($num<=$MAXLIST?"":$MAXLIST)).''.$langs->trans("AllBills").' '.$num.''; print ''; print '
'.$langs->trans("LastCustomersBills", ($num <= $MAXLIST ? "" : $MAXLIST)).''.$langs->trans("AllBills").' '.$num.''.img_picto($langs->trans("Statistics"), 'stats').'
'; print price($objp->total_ttc); @@ -1249,25 +1249,25 @@ if ($object->id > 0) print ''; } - if (! empty($conf->propal->enabled) && $user->rights->propal->creer && $object->status==1) + if (!empty($conf->propal->enabled) && $user->rights->propal->creer && $object->status == 1) { $langs->load("propal"); print ''; } - if (! empty($conf->commande->enabled) && $user->rights->commande->creer && $object->status==1) + if (!empty($conf->commande->enabled) && $user->rights->commande->creer && $object->status == 1) { $langs->load("orders"); print ''; } - if ($user->rights->contrat->creer && $object->status==1) + if ($user->rights->contrat->creer && $object->status == 1) { $langs->load("contracts"); print ''; } - if (! empty($conf->ficheinter->enabled) && $user->rights->ficheinter->creer && $object->status==1) + if (!empty($conf->ficheinter->enabled) && $user->rights->ficheinter->creer && $object->status == 1) { $langs->load("fichinter"); print ''; @@ -1276,13 +1276,13 @@ if ($object->id > 0) // Add invoice if ($user->socid == 0) { - if (! empty($conf->deplacement->enabled) && $object->status==1) + if (!empty($conf->deplacement->enabled) && $object->status == 1) { $langs->load("trips"); print ''; } - if (! empty($conf->facture->enabled) && $object->status==1) + if (!empty($conf->facture->enabled) && $object->status == 1) { if (empty($user->rights->facture->creer)) { @@ -1310,7 +1310,7 @@ if ($object->id > 0) } // Add action - if (! empty($conf->agenda->enabled) && ! empty($conf->global->MAIN_REPEATTASKONEACHTAB) && $object->status==1) + if (!empty($conf->agenda->enabled) && !empty($conf->global->MAIN_REPEATTASKONEACHTAB) && $object->status == 1) { if ($user->rights->agenda->myactions->create) { @@ -1325,13 +1325,13 @@ if ($object->id > 0) print ''; - if (! empty($conf->global->MAIN_DUPLICATE_CONTACTS_TAB_ON_CUSTOMER_CARD)) + if (!empty($conf->global->MAIN_DUPLICATE_CONTACTS_TAB_ON_CUSTOMER_CARD)) { // 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"), '', ''); diff --git a/htdocs/comm/contact.php b/htdocs/comm/contact.php index 6c0aea2f935..8b3f4cf4894 100644 --- a/htdocs/comm/contact.php +++ b/htdocs/comm/contact.php @@ -128,7 +128,7 @@ if ($resql) print '
'; - print ''; + print '
'; print ''; print_liste_field_titre("Lastname", $_SERVER["PHP_SELF"], "p.name", $begin, $param, "", $sortfield, $sortorder); print_liste_field_titre("Firstname", $_SERVER["PHP_SELF"], "p.firstname", $begin, $param, "", $sortfield, $sortorder); diff --git a/htdocs/comm/index.php b/htdocs/comm/index.php index 245d3874d92..6e26e732010 100644 --- a/htdocs/comm/index.php +++ b/htdocs/comm/index.php @@ -30,13 +30,13 @@ require_once DOL_DOCUMENT_ROOT.'/core/class/html.formfile.class.php'; require_once DOL_DOCUMENT_ROOT.'/societe/class/client.class.php'; require_once DOL_DOCUMENT_ROOT.'/comm/action/class/actioncomm.class.php'; require_once DOL_DOCUMENT_ROOT.'/core/lib/agenda.lib.php'; -if (! empty($conf->contrat->enabled)) require_once DOL_DOCUMENT_ROOT.'/contrat/class/contrat.class.php'; -if (! empty($conf->propal->enabled)) require_once DOL_DOCUMENT_ROOT.'/comm/propal/class/propal.class.php'; -if (! empty($conf->supplier_proposal->enabled)) require_once DOL_DOCUMENT_ROOT.'/supplier_proposal/class/supplier_proposal.class.php'; -if (! empty($conf->commande->enabled)) require_once DOL_DOCUMENT_ROOT.'/commande/class/commande.class.php'; -if (! empty($conf->fournisseur->enabled)) require_once DOL_DOCUMENT_ROOT.'/fourn/class/fournisseur.commande.class.php'; +if (!empty($conf->contrat->enabled)) require_once DOL_DOCUMENT_ROOT.'/contrat/class/contrat.class.php'; +if (!empty($conf->propal->enabled)) require_once DOL_DOCUMENT_ROOT.'/comm/propal/class/propal.class.php'; +if (!empty($conf->supplier_proposal->enabled)) require_once DOL_DOCUMENT_ROOT.'/supplier_proposal/class/supplier_proposal.class.php'; +if (!empty($conf->commande->enabled)) require_once DOL_DOCUMENT_ROOT.'/commande/class/commande.class.php'; +if (!empty($conf->fournisseur->enabled)) require_once DOL_DOCUMENT_ROOT.'/fourn/class/fournisseur.commande.class.php'; -if (! $user->rights->societe->lire) accessforbidden(); +if (!$user->rights->societe->lire) accessforbidden(); $hookmanager = new HookManager($db); @@ -46,19 +46,19 @@ $hookmanager->initHooks(array('commercialindex')); // Load translation files required by the page $langs->loadLangs(array("commercial", "propal")); -$action=GETPOST('action', 'alpha'); -$bid=GETPOST('bid', 'int'); +$action = GETPOST('action', 'alpha'); +$bid = GETPOST('bid', 'int'); // Securite acces client -$socid=GETPOST('socid', 'int'); +$socid = GETPOST('socid', 'int'); if (isset($user->socid) && $user->socid > 0) { $action = ''; $socid = $user->socid; } -$max=3; -$now=dol_now(); +$max = 3; +$now = dol_now(); /* * Actions @@ -71,11 +71,11 @@ $now=dol_now(); $form = new Form($db); $formfile = new FormFile($db); -$companystatic=new Societe($db); -if (! empty($conf->propal->enabled)) $propalstatic=new Propal($db); -if (! empty($conf->supplier_proposal->enabled)) $supplierproposalstatic=new SupplierProposal($db); -if (! empty($conf->commande->enabled)) $orderstatic=new Commande($db); -if (! empty($conf->fournisseur->enabled)) $supplierorderstatic=new CommandeFournisseur($db); +$companystatic = new Societe($db); +if (!empty($conf->propal->enabled)) $propalstatic = new Propal($db); +if (!empty($conf->supplier_proposal->enabled)) $supplierproposalstatic = new SupplierProposal($db); +if (!empty($conf->commande->enabled)) $orderstatic = new Commande($db); +if (!empty($conf->fournisseur->enabled)) $supplierorderstatic = new CommandeFournisseur($db); llxHeader("", $langs->trans("CommercialArea")); @@ -83,37 +83,37 @@ print load_fiche_titre($langs->trans("CommercialArea"), '', 'commercial'); 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 proposal - if (! empty($conf->propal->enabled) && $user->rights->propal->lire) + if (!empty($conf->propal->enabled) && $user->rights->propal->lire) { - $listofsearchfields['search_proposal']=array('text'=>'Proposal'); + $listofsearchfields['search_proposal'] = array('text'=>'Proposal'); } // Search customer order - if (! empty($conf->commande->enabled) && $user->rights->commande->lire) + if (!empty($conf->commande->enabled) && $user->rights->commande->lire) { - $listofsearchfields['search_customer_order']=array('text'=>'CustomerOrder'); + $listofsearchfields['search_customer_order'] = array('text'=>'CustomerOrder'); } // Search supplier proposal - if (! empty($conf->supplier_proposal->enabled) && $user->rights->supplier_proposal->lire) + if (!empty($conf->supplier_proposal->enabled) && $user->rights->supplier_proposal->lire) { - $listofsearchfields['search_supplier_proposal']=array('text'=>'SupplierProposalShort'); + $listofsearchfields['search_supplier_proposal'] = array('text'=>'SupplierProposalShort'); } // Search supplier order - if (! empty($conf->fournisseur->enabled) && $user->rights->fournisseur->commande->lire) + if (!empty($conf->fournisseur->enabled) && $user->rights->fournisseur->commande->lire) { - $listofsearchfields['search_supplier_order']=array('text'=>'SupplierOrder'); + $listofsearchfields['search_supplier_order'] = array('text'=>'SupplierOrder'); } // Search intervention - if (! empty($conf->ficheinter->enabled) && $user->rights->ficheinter->lire) + if (!empty($conf->ficheinter->enabled) && $user->rights->ficheinter->lire) { - $listofsearchfields['search_intervention']=array('text'=>'Intervention'); + $listofsearchfields['search_intervention'] = array('text'=>'Intervention'); } // Search contract - if (! empty($conf->contrat->enabled) && $user->rights->contrat->lire) + if (!empty($conf->contrat->enabled) && $user->rights->contrat->lire) { - $listofsearchfields['search_contract']=array('text'=>'Contract'); + $listofsearchfields['search_contract'] = array('text'=>'Contract'); } if (count($listofsearchfields)) @@ -122,8 +122,8 @@ if (! empty($conf->global->MAIN_SEARCH_FORM_ON_HOME_AREAS)) // This is usele print ''; print '
'; print '
'; - $i=0; - foreach($listofsearchfields as $key => $value) + $i = 0; + foreach ($listofsearchfields as $key => $value) { if ($i == 0) print ''; print ''; @@ -143,56 +143,56 @@ if (! empty($conf->global->MAIN_SEARCH_FORM_ON_HOME_AREAS)) // This is usele /* * Draft proposals */ -if (! empty($conf->propal->enabled) && $user->rights->propal->lire) +if (!empty($conf->propal->enabled) && $user->rights->propal->lire) { $langs->load("propal"); $sql = "SELECT p.rowid, p.ref, p.ref_client, p.total_ht, p.tva as total_tva, p.total as total_ttc, s.rowid as socid, s.nom as name, s.client, s.canvas"; - $sql.= ", s.code_client"; - $sql.= " FROM ".MAIN_DB_PREFIX."propal as p"; - $sql.= ", ".MAIN_DB_PREFIX."societe as s"; - if (! $user->rights->societe->client->voir && ! $socid) $sql.= ", ".MAIN_DB_PREFIX."societe_commerciaux as sc"; - $sql.= " WHERE p.fk_statut = 0"; - $sql.= " AND p.fk_soc = s.rowid"; - $sql.= " AND p.entity IN (".getEntity('propal').")"; - 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 .= ", s.code_client"; + $sql .= " FROM ".MAIN_DB_PREFIX."propal as p"; + $sql .= ", ".MAIN_DB_PREFIX."societe as s"; + if (!$user->rights->societe->client->voir && !$socid) $sql .= ", ".MAIN_DB_PREFIX."societe_commerciaux as sc"; + $sql .= " WHERE p.fk_statut = 0"; + $sql .= " AND p.fk_soc = s.rowid"; + $sql .= " AND p.entity IN (".getEntity('propal').")"; + 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; - $resql=$db->query($sql); + $resql = $db->query($sql); if ($resql) { $total = 0; $num = $db->num_rows($resql); print '
'; - print '
'.$langs->trans("Search").'
'; + print '
'; print ''; print ''; if ($num > 0) { $i = 0; - $nbofloop=min($num, (empty($conf->global->MAIN_MAXLIST_OVERLOAD)?500:$conf->global->MAIN_MAXLIST_OVERLOAD)); + $nbofloop = min($num, (empty($conf->global->MAIN_MAXLIST_OVERLOAD) ? 500 : $conf->global->MAIN_MAXLIST_OVERLOAD)); while ($i < $nbofloop) { $obj = $db->fetch_object($resql); print ''; print ''; print ''; @@ -203,7 +203,7 @@ if (! empty($conf->propal->enabled) && $user->rights->propal->lire) { print '"; } - elseif ($total>0) + elseif ($total > 0) { print '"; } @@ -227,55 +227,55 @@ if (! empty($conf->propal->enabled) && $user->rights->propal->lire) /* * Draft supplier proposals */ -if (! empty($conf->supplier_proposal->enabled) && $user->rights->supplier_proposal->lire) +if (!empty($conf->supplier_proposal->enabled) && $user->rights->supplier_proposal->lire) { $langs->load("supplier_proposal"); $sql = "SELECT p.rowid, p.ref, p.total_ht, p.tva as total_tva, p.total as total_ttc, s.rowid as socid, s.nom as name, s.client, s.canvas"; - $sql.= ", s.code_client"; - $sql.= " FROM ".MAIN_DB_PREFIX."supplier_proposal as p"; - $sql.= ", ".MAIN_DB_PREFIX."societe as s"; - if (! $user->rights->societe->client->voir && ! $socid) $sql.= ", ".MAIN_DB_PREFIX."societe_commerciaux as sc"; - $sql.= " WHERE p.fk_statut = 0"; - $sql.= " AND p.fk_soc = s.rowid"; - $sql.= " AND p.entity IN (".getEntity('supplier_proposal').")"; - 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 .= ", s.code_client"; + $sql .= " FROM ".MAIN_DB_PREFIX."supplier_proposal as p"; + $sql .= ", ".MAIN_DB_PREFIX."societe as s"; + if (!$user->rights->societe->client->voir && !$socid) $sql .= ", ".MAIN_DB_PREFIX."societe_commerciaux as sc"; + $sql .= " WHERE p.fk_statut = 0"; + $sql .= " AND p.fk_soc = s.rowid"; + $sql .= " AND p.entity IN (".getEntity('supplier_proposal').")"; + 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; - $resql=$db->query($sql); + $resql = $db->query($sql); if ($resql) { $total = 0; $num = $db->num_rows($resql); print '
'; - print '
'.$langs->trans("ProposalsDraft").' '.$num.'
'; - $propalstatic->id=$obj->rowid; - $propalstatic->ref=$obj->ref; - $propalstatic->ref_client=$obj->ref_client; + $propalstatic->id = $obj->rowid; + $propalstatic->ref = $obj->ref; + $propalstatic->ref_client = $obj->ref_client; $propalstatic->total_ht = $obj->total_ht; $propalstatic->total_tva = $obj->total_tva; $propalstatic->total_ttc = $obj->total_ttc; print $propalstatic->getNomUrl(1); print ''; - $companystatic->id=$obj->socid; - $companystatic->name=$obj->name; - $companystatic->client=$obj->client; + $companystatic->id = $obj->socid; + $companystatic->name = $obj->name; + $companystatic->client = $obj->client; $companystatic->code_client = $obj->code_client; $companystatic->code_fournisseur = $obj->code_fournisseur; - $companystatic->canvas=$obj->canvas; + $companystatic->canvas = $obj->canvas; print $companystatic->getNomUrl(1, 'customer', 16); print ''.price($obj->total_ht).'
'.$langs->trans("XMoreLines", ($num - $nbofloop))."
'.$langs->trans("Total").''.price($total)."
'; + print '
'; print ''; - print ''; + print ''; if ($num > 0) { $i = 0; - $nbofloop=min($num, (empty($conf->global->MAIN_MAXLIST_OVERLOAD)?500:$conf->global->MAIN_MAXLIST_OVERLOAD)); + $nbofloop = min($num, (empty($conf->global->MAIN_MAXLIST_OVERLOAD) ? 500 : $conf->global->MAIN_MAXLIST_OVERLOAD)); while ($i < $nbofloop) { $obj = $db->fetch_object($resql); print ''; print ''; print ''; @@ -286,7 +286,7 @@ if (! empty($conf->supplier_proposal->enabled) && $user->rights->supplier_propos { print '"; } - elseif ($total>0) + elseif ($total > 0) { print '"; } @@ -309,20 +309,20 @@ if (! empty($conf->supplier_proposal->enabled) && $user->rights->supplier_propos /* * Draft orders */ -if (! empty($conf->commande->enabled) && $user->rights->commande->lire) +if (!empty($conf->commande->enabled) && $user->rights->commande->lire) { $langs->load("orders"); $sql = "SELECT c.rowid, c.ref, c.ref_client, c.total_ht, c.tva as total_tva, c.total_ttc, s.rowid as socid, s.nom as name, s.client, s.canvas"; - $sql.= ", s.code_client"; - $sql.= " FROM ".MAIN_DB_PREFIX."commande as c"; - $sql.= ", ".MAIN_DB_PREFIX."societe as s"; - 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.fk_statut = 0"; - $sql.= " AND c.entity IN (".getEntity('commande').")"; - 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 .= ", s.code_client"; + $sql .= " FROM ".MAIN_DB_PREFIX."commande as c"; + $sql .= ", ".MAIN_DB_PREFIX."societe as s"; + 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.fk_statut = 0"; + $sql .= " AND c.entity IN (".getEntity('commande').")"; + 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) @@ -331,36 +331,36 @@ if (! empty($conf->commande->enabled) && $user->rights->commande->lire) $num = $db->num_rows($resql); print '
'; - print '
'.$langs->trans("SupplierProposalsDraft").($num?' '.$num.'':'').'
'.$langs->trans("SupplierProposalsDraft").($num ? ' '.$num.'' : '').'
'; - $supplierproposalstatic->id=$obj->rowid; - $supplierproposalstatic->ref=$obj->ref; + $supplierproposalstatic->id = $obj->rowid; + $supplierproposalstatic->ref = $obj->ref; $supplierproposalstatic->total_ht = $obj->total_ht; $supplierproposalstatic->total_tva = $obj->total_tva; $supplierproposalstatic->total_ttc = $obj->total_ttc; print $supplierproposalstatic->getNomUrl(1); print ''; - $companystatic->id=$obj->socid; - $companystatic->name=$obj->name; - $companystatic->client=$obj->client; + $companystatic->id = $obj->socid; + $companystatic->name = $obj->name; + $companystatic->client = $obj->client; $companystatic->code_client = $obj->code_client; $companystatic->code_fournisseur = $obj->code_fournisseur; - $companystatic->canvas=$obj->canvas; + $companystatic->canvas = $obj->canvas; print $companystatic->getNomUrl(1, 'supplier', 16); print ''.price($obj->total_ht).'
'.$langs->trans("XMoreLines", ($num - $nbofloop))."
'.$langs->trans("Total").''.price($total)."
'; + print '
'; print ''; - print ''; + print ''; if ($num > 0) { $i = 0; - $nbofloop=min($num, (empty($conf->global->MAIN_MAXLIST_OVERLOAD)?500:$conf->global->MAIN_MAXLIST_OVERLOAD)); + $nbofloop = min($num, (empty($conf->global->MAIN_MAXLIST_OVERLOAD) ? 500 : $conf->global->MAIN_MAXLIST_OVERLOAD)); while ($i < $nbofloop) { $obj = $db->fetch_object($resql); print ''; print ''; - if(! empty($conf->global->MAIN_DASHBOARD_USE_TOTAL_HT)) { + if (!empty($conf->global->MAIN_DASHBOARD_USE_TOTAL_HT)) { print ''; } else { @@ -373,7 +373,7 @@ if (! empty($conf->commande->enabled) && $user->rights->commande->lire) { print '"; } - elseif ($total>0) + elseif ($total > 0) { print '"; } @@ -397,21 +397,21 @@ if (! empty($conf->commande->enabled) && $user->rights->commande->lire) /* * Draft suppliers orders */ -if (! empty($conf->fournisseur->enabled) && $user->rights->fournisseur->commande->lire) +if (!empty($conf->fournisseur->enabled) && $user->rights->fournisseur->commande->lire) { $langs->load("orders"); $sql = "SELECT cf.rowid, cf.ref, cf.ref_supplier, cf.total_ttc, s.rowid as socid, s.nom as name, s.client, s.canvas"; - $sql.= ", s.code_client"; - $sql.= ", s.code_fournisseur"; - $sql.= " FROM ".MAIN_DB_PREFIX."commande_fournisseur as cf"; - $sql.= ", ".MAIN_DB_PREFIX."societe as s"; - 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.fk_statut = 0"; - $sql.= " AND cf.entity IN (".getEntity('supplier_order').")"; - if (!$user->rights->societe->client->voir && !$socid) $sql.= " AND s.rowid = sc.fk_soc AND sc.fk_user = " .$user->id; - if ($socid) $sql.= " AND cf.fk_soc = ".$socid; + $sql .= ", s.code_client"; + $sql .= ", s.code_fournisseur"; + $sql .= " FROM ".MAIN_DB_PREFIX."commande_fournisseur as cf"; + $sql .= ", ".MAIN_DB_PREFIX."societe as s"; + 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.fk_statut = 0"; + $sql .= " AND cf.entity IN (".getEntity('supplier_order').")"; + if (!$user->rights->societe->client->voir && !$socid) $sql .= " AND s.rowid = sc.fk_soc AND sc.fk_user = ".$user->id; + if ($socid) $sql .= " AND cf.fk_soc = ".$socid; $resql = $db->query($sql); if ($resql) @@ -420,36 +420,36 @@ if (! empty($conf->fournisseur->enabled) && $user->rights->fournisseur->commande $num = $db->num_rows($resql); print '
'; - print '
'.$langs->trans("DraftOrders").($num?' '.$num.'':'').'
'.$langs->trans("DraftOrders").($num ? ' '.$num.'' : '').'
'; - $orderstatic->id=$obj->rowid; - $orderstatic->ref=$obj->ref; - $orderstatic->ref_client=$obj->ref_client; + $orderstatic->id = $obj->rowid; + $orderstatic->ref = $obj->ref; + $orderstatic->ref_client = $obj->ref_client; $orderstatic->total_ht = $obj->total_ht; $orderstatic->total_tva = $obj->total_tva; $orderstatic->total_ttc = $obj->total_ttc; print $orderstatic->getNomUrl(1); print ''; - $companystatic->id=$obj->socid; - $companystatic->name=$obj->name; - $companystatic->client=$obj->client; + $companystatic->id = $obj->socid; + $companystatic->name = $obj->name; + $companystatic->client = $obj->client; $companystatic->code_client = $obj->code_client; $companystatic->code_fournisseur = $obj->code_fournisseur; - $companystatic->canvas=$obj->canvas; + $companystatic->canvas = $obj->canvas; print $companystatic->getNomUrl(1, 'customer', 16); print ''.price($obj->total_ht).'
'.$langs->trans("XMoreLines", ($num - $nbofloop))."
'.$langs->trans("Total").''.price($total)."
'; + print '
'; print ''; - print ''; + print ''; if ($num > 0) { $i = 0; - $nbofloop=min($num, (empty($conf->global->MAIN_MAXLIST_OVERLOAD)?500:$conf->global->MAIN_MAXLIST_OVERLOAD)); + $nbofloop = min($num, (empty($conf->global->MAIN_MAXLIST_OVERLOAD) ? 500 : $conf->global->MAIN_MAXLIST_OVERLOAD)); while ($i < $nbofloop) { $obj = $db->fetch_object($resql); print ''; print ''; - if(! empty($conf->global->MAIN_DASHBOARD_USE_TOTAL_HT)) { + if (!empty($conf->global->MAIN_DASHBOARD_USE_TOTAL_HT)) { print ''; } else { @@ -462,7 +462,7 @@ if (! empty($conf->fournisseur->enabled) && $user->rights->fournisseur->commande { print '"; } - elseif ($total>0) + elseif ($total > 0) { print '"; } @@ -484,24 +484,24 @@ if (! empty($conf->fournisseur->enabled) && $user->rights->fournisseur->commande print '
'; -$max=3; +$max = 3; /* * Last modified customers or prospects */ -if (! empty($conf->societe->enabled) && $user->rights->societe->lire) +if (!empty($conf->societe->enabled) && $user->rights->societe->lire) { $langs->load("boxes"); $sql = "SELECT s.rowid, s.nom as name, s.client, s.datec, s.tms, s.canvas"; - $sql.= ", s.code_client"; - $sql.= " FROM ".MAIN_DB_PREFIX."societe as s"; - if (! $user->rights->societe->client->voir && ! $socid) $sql.= ", ".MAIN_DB_PREFIX."societe_commerciaux as sc"; - $sql.= " WHERE s.client IN (1, 2, 3)"; - $sql.= " AND s.entity IN (".getEntity($companystatic->element).")"; - 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 .= ", s.code_client"; + $sql .= " FROM ".MAIN_DB_PREFIX."societe as s"; + if (!$user->rights->societe->client->voir && !$socid) $sql .= ", ".MAIN_DB_PREFIX."societe_commerciaux as sc"; + $sql .= " WHERE s.client IN (1, 2, 3)"; + $sql .= " AND s.entity IN (".getEntity($companystatic->element).")"; + 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); @@ -512,11 +512,11 @@ if (! empty($conf->societe->enabled) && $user->rights->societe->lire) $i = 0; print '
'; - print '
'.$langs->trans("DraftSuppliersOrders").($num?' '.$num.'':'').'
'.$langs->trans("DraftSuppliersOrders").($num ? ' '.$num.'' : '').'
'; - $supplierorderstatic->id=$obj->rowid; - $supplierorderstatic->ref=$obj->ref; - $supplierorderstatic->ref_supplier=$obj->ref_suppliert; + $supplierorderstatic->id = $obj->rowid; + $supplierorderstatic->ref = $obj->ref; + $supplierorderstatic->ref_supplier = $obj->ref_suppliert; $supplierorderstatic->total_ht = $obj->total_ht; $supplierorderstatic->total_tva = $obj->total_tva; $supplierorderstatic->total_ttc = $obj->total_ttc; print $supplierorderstatic->getNomUrl(1); print ''; - $companystatic->id=$obj->socid; - $companystatic->name=$obj->name; - $companystatic->client=$obj->client; + $companystatic->id = $obj->socid; + $companystatic->name = $obj->name; + $companystatic->client = $obj->client; $companystatic->code_client = $obj->code_client; $companystatic->code_fournisseur = $obj->code_fournisseur; - $companystatic->canvas=$obj->canvas; + $companystatic->canvas = $obj->canvas; print $companystatic->getNomUrl(1, 'supplier', 16); print ''.price($obj->total_ht).'
'.$langs->trans("XMoreLines", ($num - $nbofloop))."
'.$langs->trans("Total").''.price($total)."
'; + print '
'; print ''; print ''; print ''; @@ -526,12 +526,12 @@ if (! empty($conf->societe->enabled) && $user->rights->societe->lire) while ($i < $num) { $objp = $db->fetch_object($resql); - $companystatic->id=$objp->rowid; - $companystatic->name=$objp->name; - $companystatic->client=$objp->client; + $companystatic->id = $objp->rowid; + $companystatic->name = $objp->name; + $companystatic->client = $objp->client; $companystatic->code_client = $objp->code_client; $companystatic->code_fournisseur = $objp->code_fournisseur; - $companystatic->canvas=$objp->canvas; + $companystatic->canvas = $objp->canvas; print ''; print ''; print '"; print ''; print ''."\n"; - if(! empty($conf->global->MAIN_DASHBOARD_USE_TOTAL_HT)) { + if (!empty($conf->global->MAIN_DASHBOARD_USE_TOTAL_HT)) { print ''; } else { @@ -779,7 +779,7 @@ if (! empty($conf->propal->enabled) && $user->rights->propal->lire) { print '"; } - elseif ($total>0) + elseif ($total > 0) { print '"; } @@ -796,23 +796,23 @@ if (! empty($conf->propal->enabled) && $user->rights->propal->lire) /* * Opened Order */ -if (! empty($conf->commande->enabled) && $user->rights->commande->lire) +if (!empty($conf->commande->enabled) && $user->rights->commande->lire) { $langs->load("orders"); $sql = "SELECT s.nom as name, s.rowid, c.rowid as commandeid, c.total_ttc, c.total_ht, c.tva as total_tva, c.ref, c.ref_client, c.fk_statut, c.date_valid as dv, c.facture as billed"; - $sql.= ", s.code_client"; - $sql.= " FROM ".MAIN_DB_PREFIX."societe as s"; - $sql.= ", ".MAIN_DB_PREFIX."commande as c"; - 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('commande').")"; - $sql.= " AND (c.fk_statut = ".Commande::STATUS_VALIDATED." or c.fk_statut = ".Commande::STATUS_SHIPMENTONPROCESS.")"; - 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 c.rowid DESC"; + $sql .= ", s.code_client"; + $sql .= " FROM ".MAIN_DB_PREFIX."societe as s"; + $sql .= ", ".MAIN_DB_PREFIX."commande as c"; + 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('commande').")"; + $sql .= " AND (c.fk_statut = ".Commande::STATUS_VALIDATED." or c.fk_statut = ".Commande::STATUS_SHIPMENTONPROCESS.")"; + 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 c.rowid DESC"; - $result=$db->query($sql); + $result = $db->query($sql); if ($result) { $total = 0; @@ -821,10 +821,10 @@ if (! empty($conf->commande->enabled) && $user->rights->commande->lire) if ($num > 0) { print '
'; - print '
'; if (empty($conf->global->SOCIETE_DISABLE_PROSPECTS) && empty($conf->global->SOCIETE_DISABLE_CUSTOMERS)) print $langs->trans("BoxTitleLastCustomersOrProspects", $max); - elseif (! empty($conf->global->SOCIETE_DISABLE_CUSTOMERS)) print $langs->trans("BoxTitleLastModifiedProspects", $max); + elseif (!empty($conf->global->SOCIETE_DISABLE_CUSTOMERS)) print $langs->trans("BoxTitleLastModifiedProspects", $max); else print $langs->trans("BoxTitleLastModifiedCustomers", $max); print ''.$langs->trans("FullList").'
'.$companystatic->getNomUrl(1, 'customer', 48).''; @@ -554,20 +554,20 @@ if (! empty($conf->societe->enabled) && $user->rights->societe->lire) } // Last suppliers -if (! empty($conf->fournisseur->enabled) && $user->rights->societe->lire) +if (!empty($conf->fournisseur->enabled) && $user->rights->societe->lire) { $langs->load("boxes"); $sql = "SELECT s.nom as name, s.rowid, s.datec as dc, s.canvas, s.tms as dm"; - $sql.= ", s.code_fournisseur"; - $sql.= " FROM ".MAIN_DB_PREFIX."societe as s"; - 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($companystatic->element).")"; - if (! $user->rights->societe->client->voir && ! $user->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.datec DESC"; - $sql.= $db->plimit($max, 0); + $sql .= ", s.code_fournisseur"; + $sql .= " FROM ".MAIN_DB_PREFIX."societe as s"; + 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($companystatic->element).")"; + if (!$user->rights->societe->client->voir && !$user->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.datec DESC"; + $sql .= $db->plimit($max, 0); $result = $db->query($sql); if ($result) @@ -576,7 +576,7 @@ if (! empty($conf->fournisseur->enabled) && $user->rights->societe->lire) $i = 0; print '
'; - print ''; + print '
'; print ''; print ''; print ''; @@ -586,11 +586,11 @@ if (! empty($conf->fournisseur->enabled) && $user->rights->societe->lire) while ($i < $num && $i < $max) { $objp = $db->fetch_object($result); - $companystatic->id=$objp->rowid; - $companystatic->name=$objp->name; + $companystatic->id = $objp->rowid; + $companystatic->name = $objp->name; $companystatic->code_client = $objp->code_client; $companystatic->code_fournisseur = $objp->code_fournisseur; - $companystatic->canvas=$objp->canvas; + $companystatic->canvas = $objp->canvas; print ''; print ''; print ''; @@ -630,26 +630,26 @@ if ($user->rights->agenda->myactions->read) /* * Last contracts */ -if (! empty($conf->contrat->enabled) && $user->rights->contrat->lire && 0) // TODO A REFAIRE DEPUIS NOUVEAU CONTRAT +if (!empty($conf->contrat->enabled) && $user->rights->contrat->lire && 0) // TODO A REFAIRE DEPUIS NOUVEAU CONTRAT { $langs->load("contracts"); $sql = "SELECT s.nom as name, s.rowid, s.canvas, "; - $sql.= ", s.code_client"; - $sql.= " c.statut, c.rowid as contratid, p.ref, c.mise_en_service as datemes, c.fin_validite as datefin, c.date_cloture as dateclo"; - $sql.= " FROM ".MAIN_DB_PREFIX."societe as s"; - $sql.= ", ".MAIN_DB_PREFIX."contrat as c"; - $sql.= ", ".MAIN_DB_PREFIX."product as p"; - 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('contract').")"; - $sql.= " AND c.fk_product = p.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; - $sql.= " ORDER BY c.tms DESC"; - $sql.= $db->plimit(5, 0); + $sql .= ", s.code_client"; + $sql .= " c.statut, c.rowid as contratid, p.ref, c.mise_en_service as datemes, c.fin_validite as datefin, c.date_cloture as dateclo"; + $sql .= " FROM ".MAIN_DB_PREFIX."societe as s"; + $sql .= ", ".MAIN_DB_PREFIX."contrat as c"; + $sql .= ", ".MAIN_DB_PREFIX."product as p"; + 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('contract').")"; + $sql .= " AND c.fk_product = p.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; + $sql .= " ORDER BY c.tms DESC"; + $sql .= $db->plimit(5, 0); - $resql=$db->query($sql); + $resql = $db->query($sql); if ($resql) { $num = $db->num_rows($resql); @@ -657,22 +657,22 @@ if (! empty($conf->contrat->enabled) && $user->rights->contrat->lire && 0) // TO if ($num > 0) { print '
'; - print '
'.$langs->trans("BoxTitleLastModifiedSuppliers", min($max, $num)).''.$langs->trans("FullList").'
'.$companystatic->getNomUrl(1, 'supplier', 44).''.dol_print_date($db->jdate($objp->dm), 'day').'
'; + print '
'; print ''; $i = 0; - $staticcontrat=new Contrat($db); + $staticcontrat = new Contrat($db); while ($i < $num) { $obj = $db->fetch_object($resql); print ''; print ''."\n"; print "\n"; @@ -692,23 +692,23 @@ if (! empty($conf->contrat->enabled) && $user->rights->contrat->lire && 0) // TO /* * Opened proposals */ -if (! empty($conf->propal->enabled) && $user->rights->propal->lire) +if (!empty($conf->propal->enabled) && $user->rights->propal->lire) { $langs->load("propal"); $sql = "SELECT s.nom as name, s.rowid, s.code_client"; - $sql.= ", p.rowid as propalid, p.entity, p.total as total_ttc, p.total_ht, p.tva as total_tva, p.ref, p.ref_client, p.fk_statut, p.datep as dp, p.fin_validite as dfv"; - $sql.= " FROM ".MAIN_DB_PREFIX."societe as s"; - $sql.= ", ".MAIN_DB_PREFIX."propal as p"; - if (! $user->rights->societe->client->voir && ! $socid) $sql.= ", ".MAIN_DB_PREFIX."societe_commerciaux as sc"; - $sql.= " WHERE p.fk_soc = s.rowid"; - $sql.= " AND p.entity IN (".getEntity('propal').")"; - $sql.= " AND p.fk_statut = 1"; - 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 p.rowid DESC"; + $sql .= ", p.rowid as propalid, p.entity, p.total as total_ttc, p.total_ht, p.tva as total_tva, p.ref, p.ref_client, p.fk_statut, p.datep as dp, p.fin_validite as dfv"; + $sql .= " FROM ".MAIN_DB_PREFIX."societe as s"; + $sql .= ", ".MAIN_DB_PREFIX."propal as p"; + if (!$user->rights->societe->client->voir && !$socid) $sql .= ", ".MAIN_DB_PREFIX."societe_commerciaux as sc"; + $sql .= " WHERE p.fk_soc = s.rowid"; + $sql .= " AND p.entity IN (".getEntity('propal').")"; + $sql .= " AND p.fk_statut = 1"; + 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 p.rowid DESC"; - $result=$db->query($sql); + $result = $db->query($sql); if ($result) { $total = 0; @@ -717,10 +717,10 @@ if (! empty($conf->propal->enabled) && $user->rights->propal->lire) if ($num > 0) { print '
'; - print '
'.$langs->trans("LastContracts", 5).'
contratid."\">".img_object($langs->trans("ShowContract","contract"), "contract")." ".$obj->ref."'; - $companystatic->id=$objp->rowid; - $companystatic->name=$objp->name; + $companystatic->id = $objp->rowid; + $companystatic->name = $objp->name; $companystatic->code_client = $objp->code_client; $companystatic->code_fournisseur = $objp->code_fournisseur; - $companystatic->canvas=$objp->canvas; + $companystatic->canvas = $objp->canvas; print $companystatic->getNomUrl(1, 'customer', 44); print '".$staticcontrat->LibStatut($obj->statut, 3)."
'; + print '
'; print ''; - $nbofloop=min($num, (empty($conf->global->MAIN_MAXLIST_OVERLOAD)?500:$conf->global->MAIN_MAXLIST_OVERLOAD)); + $nbofloop = min($num, (empty($conf->global->MAIN_MAXLIST_OVERLOAD) ? 500 : $conf->global->MAIN_MAXLIST_OVERLOAD)); while ($i < $nbofloop) { $obj = $db->fetch_object($result); @@ -730,9 +730,9 @@ if (! empty($conf->propal->enabled) && $user->rights->propal->lire) // Ref print ''; print '
'.$langs->trans("ProposalsOpened").' '.$num.'
'; - $propalstatic->id=$obj->propalid; - $propalstatic->ref=$obj->ref; - $propalstatic->ref_client=$obj->ref_client; + $propalstatic->id = $obj->propalid; + $propalstatic->ref = $obj->ref; + $propalstatic->ref_client = $obj->ref_client; $propalstatic->total_ht = $obj->total_ht; $propalstatic->total_tva = $obj->total_tva; $propalstatic->total_ttc = $obj->total_ttc; @@ -745,26 +745,26 @@ if (! empty($conf->propal->enabled) && $user->rights->propal->lire) if ($db->jdate($obj->dfv) < ($now - $conf->propal->cloture->warning_delay)) print img_warning($langs->trans("Late")); print ''; - $filename=dol_sanitizeFileName($obj->ref); - $filedir=$conf->propal->multidir_output[$obj->entity] . '/' . dol_sanitizeFileName($obj->ref); - $urlsource=$_SERVER['PHP_SELF'].'?id='.$obj->propalid; + $filename = dol_sanitizeFileName($obj->ref); + $filedir = $conf->propal->multidir_output[$obj->entity].'/'.dol_sanitizeFileName($obj->ref); + $urlsource = $_SERVER['PHP_SELF'].'?id='.$obj->propalid; print $formfile->getDocumentsLink($propalstatic->element, $filename, $filedir); print '
'; print "
'; - $companystatic->id=$obj->rowid; - $companystatic->name=$obj->name; - $companystatic->client=$obj->client; + $companystatic->id = $obj->rowid; + $companystatic->name = $obj->name; + $companystatic->client = $obj->client; $companystatic->code_client = $obj->code_client; $companystatic->code_fournisseur = $obj->code_fournisseur; - $companystatic->canvas=$obj->canvas; + $companystatic->canvas = $obj->canvas; print $companystatic->getNomUrl(1, 'customer', 44); print ''; print dol_print_date($db->jdate($obj->dp), 'day').''.price($obj->total_ht).'
'.$langs->trans("XMoreLines", ($num - $nbofloop))."
'.$langs->trans("Total")."".price($total)." 
'; + print '
'; print ''; - $nbofloop=min($num, (empty($conf->global->MAIN_MAXLIST_OVERLOAD)?500:$conf->global->MAIN_MAXLIST_OVERLOAD)); + $nbofloop = min($num, (empty($conf->global->MAIN_MAXLIST_OVERLOAD) ? 500 : $conf->global->MAIN_MAXLIST_OVERLOAD)); while ($i < $nbofloop) { $obj = $db->fetch_object($result); @@ -834,9 +834,9 @@ if (! empty($conf->commande->enabled) && $user->rights->commande->lire) // Ref print ''; print '
'.$langs->trans("OrdersOpened").' '.$num.'
'; - $orderstatic->id=$obj->commandeid; - $orderstatic->ref=$obj->ref; - $orderstatic->ref_client=$obj->ref_client; + $orderstatic->id = $obj->commandeid; + $orderstatic->ref = $obj->ref; + $orderstatic->ref_client = $obj->ref_client; $orderstatic->total_ht = $obj->total_ht; $orderstatic->total_tva = $obj->total_tva; $orderstatic->total_ttc = $obj->total_ttc; @@ -849,26 +849,26 @@ if (! empty($conf->commande->enabled) && $user->rights->commande->lire) //if ($db->jdate($obj->dfv) < ($now - $conf->propal->cloture->warning_delay)) print img_warning($langs->trans("Late")); print ''; - $filename=dol_sanitizeFileName($obj->ref); - $filedir=$conf->commande->dir_output . '/' . dol_sanitizeFileName($obj->ref); - $urlsource=$_SERVER['PHP_SELF'].'?id='.$obj->propalid; + $filename = dol_sanitizeFileName($obj->ref); + $filedir = $conf->commande->dir_output.'/'.dol_sanitizeFileName($obj->ref); + $urlsource = $_SERVER['PHP_SELF'].'?id='.$obj->propalid; print $formfile->getDocumentsLink($orderstatic->element, $filename, $filedir); print '
'; print "
'; - $companystatic->id=$obj->rowid; - $companystatic->name=$obj->name; - $companystatic->client=$obj->client; + $companystatic->id = $obj->rowid; + $companystatic->name = $obj->name; + $companystatic->client = $obj->client; $companystatic->code_client = $obj->code_client; $companystatic->code_fournisseur = $obj->code_fournisseur; - $companystatic->canvas=$obj->canvas; + $companystatic->canvas = $obj->canvas; print $companystatic->getNomUrl(1, 'customer', 44); print ''; print dol_print_date($db->jdate($obj->dp), 'day').''.price($obj->total_ht).'
'.$langs->trans("XMoreLines", ($num - $nbofloop))."
'.$langs->trans("Total")."".price($total)." 
'; + print '
'; - $linkback = '' . $langs->trans("BackToList") . ''; + $linkback = ''.$langs->trans("BackToList").''; - print ''; + print ''; print ''; - print ''; + print ''; - print ''; + print ''; // Errors to - print ''; // Status - print ''; + print ''; // Nb of distinct emails print '
' . $langs->trans("Ref") . '
'.$langs->trans("Ref").''; print $form->showrefnav($object, 'id', $linkback); print '
' . $langs->trans("MailTitle") . '' . $object->titre . '
'.$langs->trans("MailTitle").''.$object->titre.'
' . $langs->trans("MailFrom") . '' . dol_print_email($object->email_from, 0, 0, 0, 0, 1) . '
'.$langs->trans("MailFrom").''.dol_print_email($object->email_from, 0, 0, 0, 0, 1).'
' . $langs->trans("MailErrorsTo") . '' . dol_print_email($object->email_errorsto, 0, 0, 0, 0, 1); + print '
'.$langs->trans("MailErrorsTo").''.dol_print_email($object->email_errorsto, 0, 0, 0, 0, 1); print '
' . $langs->trans("Status") . '' . $object->getLibStatut(4) . '
'.$langs->trans("Status").''.$object->getLibStatut(4).'
'; print $langs->trans("TotalNbOfDistinctRecipients"); print ''; $nbemail = ($object->nbemail ? $object->nbemail : '0'); - if (! empty($conf->global->MAILING_LIMIT_SENDBYWEB) && $conf->global->MAILING_LIMIT_SENDBYWEB < $nbemail) { + if (!empty($conf->global->MAILING_LIMIT_SENDBYWEB) && $conf->global->MAILING_LIMIT_SENDBYWEB < $nbemail) { $text = $langs->trans('LimitSendingEmailing', $conf->global->MAILING_LIMIT_SENDBYWEB); print $form->textwithpicto($nbemail, $text, 1, 'warning'); } else { @@ -458,7 +458,7 @@ if ($object->fetch($id) >= 0) { // Show email selectors if ($object->statut == 0 && $user->rights->mailing->creer) { - include DOL_DOCUMENT_ROOT . '/core/tpl/advtarget.tpl.php'; + include DOL_DOCUMENT_ROOT.'/core/tpl/advtarget.tpl.php'; } } diff --git a/htdocs/comm/mailing/card.php b/htdocs/comm/mailing/card.php index 714a84fe95a..8deb8100c72 100644 --- a/htdocs/comm/mailing/card.php +++ b/htdocs/comm/mailing/card.php @@ -23,7 +23,7 @@ * \brief Fiche mailing, onglet general */ -if (! defined('NOSTYLECHECK')) define('NOSTYLECHECK', '1'); +if (!defined('NOSTYLECHECK')) define('NOSTYLECHECK', '1'); require '../../main.inc.php'; require_once DOL_DOCUMENT_ROOT.'/core/lib/emailing.lib.php'; @@ -54,26 +54,26 @@ $extrafields = new ExtraFields($db); $extrafields->fetch_name_optionals_label($object->table_element); // Initialize technical object to manage hooks of page. Note that conf->hooks_modules contains array of hook context -$hookmanager->initHooks(array('mailingcard','globalcard')); +$hookmanager->initHooks(array('mailingcard', 'globalcard')); // Array of possible substitutions (See also file mailing-send.php that should manage same substitutions) -$object->substitutionarray=FormMail::getAvailableSubstitKey('emailing'); +$object->substitutionarray = FormMail::getAvailableSubstitKey('emailing'); // Set $object->substitutionarrayfortest -$signature = ((!empty($user->signature) && empty($conf->global->MAIN_MAIL_DO_NOT_USE_SIGN))?$user->signature:''); +$signature = ((!empty($user->signature) && empty($conf->global->MAIN_MAIL_DO_NOT_USE_SIGN)) ? $user->signature : ''); -$targetobject = null; // Not defined with mass emailing +$targetobject = null; // Not defined with mass emailing -$parameters=array('mode'=>'emailing'); -$substitutionarray=FormMail::getAvailableSubstitKey('emailing', $targetobject); +$parameters = array('mode'=>'emailing'); +$substitutionarray = FormMail::getAvailableSubstitKey('emailing', $targetobject); $object->substitutionarrayfortest = $substitutionarray; // List of sending methods -$listofmethods=array(); -$listofmethods['mail']='PHP mail function'; -$listofmethods['smtps']='SMTP/SMTPS socket library'; +$listofmethods = array(); +$listofmethods['mail'] = 'PHP mail function'; +$listofmethods['smtps'] = 'SMTP/SMTPS socket library'; @@ -81,8 +81,8 @@ $listofmethods['smtps']='SMTP/SMTPS socket library'; * Actions */ -$parameters=array(); -$reshook=$hookmanager->executeHooks('doActions', $parameters, $object, $action); // Note that $action and $object may have been modified by some hooks +$parameters = array(); +$reshook = $hookmanager->executeHooks('doActions', $parameters, $object, $action); // Note that $action and $object may have been modified by some hooks if ($reshook < 0) setEventMessages($hookmanager->error, $hookmanager->errors, 'errors'); if (empty($reshook)) @@ -96,7 +96,7 @@ if (empty($reshook)) } else { - $result=$object->createFromClone($user, $object->id, $_REQUEST["clone_content"], $_REQUEST["clone_receivers"]); + $result = $object->createFromClone($user, $object->id, $_REQUEST["clone_content"], $_REQUEST["clone_receivers"]); if ($result > 0) { header("Location: ".$_SERVER['PHP_SELF'].'?id='.$result); @@ -107,7 +107,7 @@ if (empty($reshook)) setEventMessages($object->error, $object->errors, 'errors'); } } - $action=''; + $action = ''; } // Action send emailing for everybody @@ -119,16 +119,16 @@ if (empty($reshook)) setEventMessages($langs->trans("MailingNeedCommand"), null, 'warnings'); setEventMessages('', null, 'warnings'); setEventMessages($langs->trans("MailingNeedCommand2"), null, 'warnings'); - $action=''; + $action = ''; } elseif ($conf->global->MAILING_LIMIT_SENDBYWEB < 0) { setEventMessages($langs->trans("NotEnoughPermissions"), null, 'warnings'); - $action=''; + $action = ''; } else { - $upload_dir = $conf->mailing->dir_output . "/" . get_exdir($object->id, 2, 0, 1, $object, 'mailing'); + $upload_dir = $conf->mailing->dir_output."/".get_exdir($object->id, 2, 0, 1, $object, 'mailing'); if ($object->statut == 0) { @@ -143,37 +143,37 @@ if (empty($reshook)) $replyto = $object->email_replyto; $errorsto = $object->email_errorsto; // Le message est-il en html - $msgishtml=-1; // Unknown by default - if (preg_match('/[\s\t]*/i', $message)) $msgishtml=1; + $msgishtml = -1; // Unknown by default + if (preg_match('/[\s\t]*/i', $message)) $msgishtml = 1; // Warning, we must not use begin-commit transaction here // because we want to save update for each mail sent. - $nbok=0; $nbko=0; + $nbok = 0; $nbko = 0; // On choisit les mails non deja envoyes pour ce mailing (statut=0) // ou envoyes en erreur (statut=-1) $sql = "SELECT mc.rowid, mc.fk_mailing, mc.lastname, mc.firstname, mc.email, mc.other, mc.source_url, mc.source_id, mc.source_type, mc.tag"; $sql .= " FROM ".MAIN_DB_PREFIX."mailing_cibles as mc"; $sql .= " WHERE mc.statut < 1 AND mc.fk_mailing = ".$object->id; - $sql .= " ORDER BY mc.statut DESC"; // first status 0, then status -1 + $sql .= " ORDER BY mc.statut DESC"; // first status 0, then status -1 dol_syslog("card.php: select targets", LOG_DEBUG); - $resql=$db->query($sql); + $resql = $db->query($sql); if ($resql) { - $num = $db->num_rows($resql); // nb of possible recipients + $num = $db->num_rows($resql); // nb of possible recipients if ($num) { dol_syslog("comm/mailing/card.php: nb of targets = ".$num, LOG_DEBUG); - $now=dol_now(); + $now = dol_now(); // Positionne date debut envoi - $sql="UPDATE ".MAIN_DB_PREFIX."mailing SET date_envoi='".$db->idate($now)."' WHERE rowid=".$object->id; - $resql2=$db->query($sql); - if (! $resql2) + $sql = "UPDATE ".MAIN_DB_PREFIX."mailing SET date_envoi='".$db->idate($now)."' WHERE rowid=".$object->id; + $resql2 = $db->query($sql); + if (!$resql2) { dol_print_error($db); } @@ -184,8 +184,8 @@ if (empty($reshook)) while ($i < $num && $i < $conf->global->MAILING_LIMIT_SENDBYWEB) { // Here code is common with same loop ino mailing-send.php - $res=1; - $now=dol_now(); + $res = 1; + $now = dol_now(); $obj = $db->fetch_object($resql); @@ -193,18 +193,18 @@ if (empty($reshook)) $sendto = str_replace(',', ' ', dolGetFirstLastname($obj->firstname, $obj->lastname))." <".$obj->email.">"; // Make substitutions on topic and body. From (AA=YY;BB=CC;...) we keep YY, CC, ... - $other=explode(';', $obj->other); - $tmpfield=explode('=', $other[0], 2); $other1=(isset($tmpfield[1])?$tmpfield[1]:$tmpfield[0]); - $tmpfield=explode('=', $other[1], 2); $other2=(isset($tmpfield[1])?$tmpfield[1]:$tmpfield[0]); - $tmpfield=explode('=', $other[2], 2); $other3=(isset($tmpfield[1])?$tmpfield[1]:$tmpfield[0]); - $tmpfield=explode('=', $other[3], 2); $other4=(isset($tmpfield[1])?$tmpfield[1]:$tmpfield[0]); - $tmpfield=explode('=', $other[4], 2); $other5=(isset($tmpfield[1])?$tmpfield[1]:$tmpfield[0]); + $other = explode(';', $obj->other); + $tmpfield = explode('=', $other[0], 2); $other1 = (isset($tmpfield[1]) ? $tmpfield[1] : $tmpfield[0]); + $tmpfield = explode('=', $other[1], 2); $other2 = (isset($tmpfield[1]) ? $tmpfield[1] : $tmpfield[0]); + $tmpfield = explode('=', $other[2], 2); $other3 = (isset($tmpfield[1]) ? $tmpfield[1] : $tmpfield[0]); + $tmpfield = explode('=', $other[3], 2); $other4 = (isset($tmpfield[1]) ? $tmpfield[1] : $tmpfield[0]); + $tmpfield = explode('=', $other[4], 2); $other5 = (isset($tmpfield[1]) ? $tmpfield[1] : $tmpfield[0]); - $signature = ((!empty($user->signature) && empty($conf->global->MAIN_MAIL_DO_NOT_USE_SIGN))?$user->signature:''); + $signature = ((!empty($user->signature) && empty($conf->global->MAIN_MAIL_DO_NOT_USE_SIGN)) ? $user->signature : ''); - $targetobject = null; // Not defined with mass emailing - $parameters=array('mode'=>'emailing'); - $substitutionarray=getCommonSubstitutionArray($langs, 0, array('object','objectamount'), $targetobject); // Note: On mass emailing, this is null because be don't know object + $targetobject = null; // Not defined with mass emailing + $parameters = array('mode'=>'emailing'); + $substitutionarray = getCommonSubstitutionArray($langs, 0, array('object', 'objectamount'), $targetobject); // Note: On mass emailing, this is null because be don't know object // Array of possible substitutions (See also file mailing-send.php that should manage same substitutions) $substitutionarray['__ID__'] = $obj->source_id; @@ -217,79 +217,79 @@ if (empty($reshook)) $substitutionarray['__OTHER3__'] = $other3; $substitutionarray['__OTHER4__'] = $other4; $substitutionarray['__OTHER5__'] = $other5; - $substitutionarray['__USER_SIGNATURE__'] = $signature; // Signature is empty when ran from command line or taken from user in parameter) - $substitutionarray['__SIGNATURE__'] = $signature; // For backward compatibility + $substitutionarray['__USER_SIGNATURE__'] = $signature; // Signature is empty when ran from command line or taken from user in parameter) + $substitutionarray['__SIGNATURE__'] = $signature; // For backward compatibility $substitutionarray['__CHECK_READ__'] = ''; $substitutionarray['__UNSUBSCRIBE__'] = ''.$langs->trans("MailUnsubcribe").''; $onlinepaymentenabled = 0; - if (! empty($conf->paypal->enabled)) $onlinepaymentenabled++; - if (! empty($conf->paybox->enabled)) $onlinepaymentenabled++; - if (! empty($conf->stripe->enabled)) $onlinepaymentenabled++; - if ($onlinepaymentenabled && ! empty($conf->global->PAYMENT_SECURITY_TOKEN)) + if (!empty($conf->paypal->enabled)) $onlinepaymentenabled++; + if (!empty($conf->paybox->enabled)) $onlinepaymentenabled++; + if (!empty($conf->stripe->enabled)) $onlinepaymentenabled++; + if ($onlinepaymentenabled && !empty($conf->global->PAYMENT_SECURITY_TOKEN)) { - $substitutionarray['__SECUREKEYPAYMENT__']=dol_hash($conf->global->PAYMENT_SECURITY_TOKEN, 2); + $substitutionarray['__SECUREKEYPAYMENT__'] = dol_hash($conf->global->PAYMENT_SECURITY_TOKEN, 2); if (empty($conf->global->PAYMENT_SECURITY_TOKEN_UNIQUE)) { - $substitutionarray['__SECUREKEYPAYMENT_MEMBER__']=dol_hash($conf->global->PAYMENT_SECURITY_TOKEN, 2); - $substitutionarray['__SECUREKEYPAYMENT_ORDER__']=dol_hash($conf->global->PAYMENT_SECURITY_TOKEN, 2); - $substitutionarray['__SECUREKEYPAYMENT_INVOICE__']=dol_hash($conf->global->PAYMENT_SECURITY_TOKEN, 2); - $substitutionarray['__SECUREKEYPAYMENT_CONTRACTLINE__']=dol_hash($conf->global->PAYMENT_SECURITY_TOKEN, 2); + $substitutionarray['__SECUREKEYPAYMENT_MEMBER__'] = dol_hash($conf->global->PAYMENT_SECURITY_TOKEN, 2); + $substitutionarray['__SECUREKEYPAYMENT_ORDER__'] = dol_hash($conf->global->PAYMENT_SECURITY_TOKEN, 2); + $substitutionarray['__SECUREKEYPAYMENT_INVOICE__'] = dol_hash($conf->global->PAYMENT_SECURITY_TOKEN, 2); + $substitutionarray['__SECUREKEYPAYMENT_CONTRACTLINE__'] = dol_hash($conf->global->PAYMENT_SECURITY_TOKEN, 2); } else { - $substitutionarray['__SECUREKEYPAYMENT_MEMBER__']=dol_hash($conf->global->PAYMENT_SECURITY_TOKEN . 'membersubscription' . $obj->source_id, 2); - $substitutionarray['__SECUREKEYPAYMENT_ORDER__']=dol_hash($conf->global->PAYMENT_SECURITY_TOKEN . 'order' . $obj->source_id, 2); - $substitutionarray['__SECUREKEYPAYMENT_INVOICE__']=dol_hash($conf->global->PAYMENT_SECURITY_TOKEN . 'invoice' . $obj->source_id, 2); - $substitutionarray['__SECUREKEYPAYMENT_CONTRACTLINE__']=dol_hash($conf->global->PAYMENT_SECURITY_TOKEN . 'contractline' . $obj->source_id, 2); + $substitutionarray['__SECUREKEYPAYMENT_MEMBER__'] = dol_hash($conf->global->PAYMENT_SECURITY_TOKEN.'membersubscription'.$obj->source_id, 2); + $substitutionarray['__SECUREKEYPAYMENT_ORDER__'] = dol_hash($conf->global->PAYMENT_SECURITY_TOKEN.'order'.$obj->source_id, 2); + $substitutionarray['__SECUREKEYPAYMENT_INVOICE__'] = dol_hash($conf->global->PAYMENT_SECURITY_TOKEN.'invoice'.$obj->source_id, 2); + $substitutionarray['__SECUREKEYPAYMENT_CONTRACTLINE__'] = dol_hash($conf->global->PAYMENT_SECURITY_TOKEN.'contractline'.$obj->source_id, 2); } } /* For backward compatibility, deprecated */ - if (! empty($conf->paypal->enabled) && ! empty($conf->global->PAYPAL_SECURITY_TOKEN)) + if (!empty($conf->paypal->enabled) && !empty($conf->global->PAYPAL_SECURITY_TOKEN)) { - $substitutionarray['__SECUREKEYPAYPAL__']=dol_hash($conf->global->PAYPAL_SECURITY_TOKEN, 2); + $substitutionarray['__SECUREKEYPAYPAL__'] = dol_hash($conf->global->PAYPAL_SECURITY_TOKEN, 2); - if (empty($conf->global->PAYPAL_SECURITY_TOKEN_UNIQUE)) $substitutionarray['__SECUREKEYPAYPAL_MEMBER__']=dol_hash($conf->global->PAYPAL_SECURITY_TOKEN, 2); - else $substitutionarray['__SECUREKEYPAYPAL_MEMBER__']=dol_hash($conf->global->PAYPAL_SECURITY_TOKEN . 'membersubscription' . $obj->source_id, 2); + if (empty($conf->global->PAYPAL_SECURITY_TOKEN_UNIQUE)) $substitutionarray['__SECUREKEYPAYPAL_MEMBER__'] = dol_hash($conf->global->PAYPAL_SECURITY_TOKEN, 2); + else $substitutionarray['__SECUREKEYPAYPAL_MEMBER__'] = dol_hash($conf->global->PAYPAL_SECURITY_TOKEN.'membersubscription'.$obj->source_id, 2); - if (empty($conf->global->PAYPAL_SECURITY_TOKEN_UNIQUE)) $substitutionarray['__SECUREKEYPAYPAL_ORDER__']=dol_hash($conf->global->PAYPAL_SECURITY_TOKEN, 2); - else $substitutionarray['__SECUREKEYPAYPAL_ORDER__']=dol_hash($conf->global->PAYPAL_SECURITY_TOKEN . 'order' . $obj->source_id, 2); + if (empty($conf->global->PAYPAL_SECURITY_TOKEN_UNIQUE)) $substitutionarray['__SECUREKEYPAYPAL_ORDER__'] = dol_hash($conf->global->PAYPAL_SECURITY_TOKEN, 2); + else $substitutionarray['__SECUREKEYPAYPAL_ORDER__'] = dol_hash($conf->global->PAYPAL_SECURITY_TOKEN.'order'.$obj->source_id, 2); - if (empty($conf->global->PAYPAL_SECURITY_TOKEN_UNIQUE)) $substitutionarray['__SECUREKEYPAYPAL_INVOICE__']=dol_hash($conf->global->PAYPAL_SECURITY_TOKEN, 2); - else $substitutionarray['__SECUREKEYPAYPAL_INVOICE__']=dol_hash($conf->global->PAYPAL_SECURITY_TOKEN . 'invoice' . $obj->source_id, 2); + if (empty($conf->global->PAYPAL_SECURITY_TOKEN_UNIQUE)) $substitutionarray['__SECUREKEYPAYPAL_INVOICE__'] = dol_hash($conf->global->PAYPAL_SECURITY_TOKEN, 2); + else $substitutionarray['__SECUREKEYPAYPAL_INVOICE__'] = dol_hash($conf->global->PAYPAL_SECURITY_TOKEN.'invoice'.$obj->source_id, 2); - if (empty($conf->global->PAYPAL_SECURITY_TOKEN_UNIQUE)) $substitutionarray['__SECUREKEYPAYPAL_CONTRACTLINE__']=dol_hash($conf->global->PAYPAL_SECURITY_TOKEN, 2); - else $substitutionarray['__SECUREKEYPAYPAL_CONTRACTLINE__']=dol_hash($conf->global->PAYPAL_SECURITY_TOKEN . 'contractline' . $obj->source_id, 2); + if (empty($conf->global->PAYPAL_SECURITY_TOKEN_UNIQUE)) $substitutionarray['__SECUREKEYPAYPAL_CONTRACTLINE__'] = dol_hash($conf->global->PAYPAL_SECURITY_TOKEN, 2); + else $substitutionarray['__SECUREKEYPAYPAL_CONTRACTLINE__'] = dol_hash($conf->global->PAYPAL_SECURITY_TOKEN.'contractline'.$obj->source_id, 2); } //$substitutionisok=true; complete_substitutions_array($substitutionarray, $langs); - $newsubject=make_substitutions($subject, $substitutionarray); - $newmessage=make_substitutions($message, $substitutionarray); + $newsubject = make_substitutions($subject, $substitutionarray); + $newmessage = make_substitutions($message, $substitutionarray); $arr_file = array(); $arr_mime = array(); $arr_name = array(); $arr_css = array(); - $listofpaths=dol_dir_list($upload_dir, 'all', 0, '', '', 'name', SORT_ASC, 0); + $listofpaths = dol_dir_list($upload_dir, 'all', 0, '', '', 'name', SORT_ASC, 0); if (count($listofpaths)) { - foreach($listofpaths as $key => $val) + foreach ($listofpaths as $key => $val) { - $arr_file[]=$listofpaths[$key]['fullname']; - $arr_mime[]=dol_mimetype($listofpaths[$key]['name']); - $arr_name[]=$listofpaths[$key]['name']; + $arr_file[] = $listofpaths[$key]['fullname']; + $arr_mime[] = dol_mimetype($listofpaths[$key]['name']); + $arr_name[] = $listofpaths[$key]['name']; } } // Fabrication du mail - $trackid='emailing-'.$obj->fk_mailing.'-'.$obj->rowid; + $trackid = 'emailing-'.$obj->fk_mailing.'-'.$obj->rowid; $mail = new CMailFile($newsubject, $sendto, $from, $newmessage, $arr_file, $arr_mime, $arr_name, '', '', 0, $msgishtml, $errorsto, $arr_css, $trackid, '', 'emailing'); if ($mail->error) { - $res=0; + $res = 0; } /*if (! $substitutionisok) { @@ -300,7 +300,7 @@ if (empty($reshook)) // Send mail if ($res) { - $res=$mail->sendfile(); + $res = $mail->sendfile(); } if ($res) @@ -308,12 +308,12 @@ if (empty($reshook)) // Mail successful $nbok++; - dol_syslog("comm/mailing/card.php: ok for #".$i.($mail->error?' - '.$mail->error:''), LOG_DEBUG); + dol_syslog("comm/mailing/card.php: ok for #".$i.($mail->error ? ' - '.$mail->error : ''), LOG_DEBUG); - $sql="UPDATE ".MAIN_DB_PREFIX."mailing_cibles"; - $sql.=" SET statut=1, date_envoi='".$db->idate($now)."' WHERE rowid=".$obj->rowid; - $resql2=$db->query($sql); - if (! $resql2) + $sql = "UPDATE ".MAIN_DB_PREFIX."mailing_cibles"; + $sql .= " SET statut=1, date_envoi='".$db->idate($now)."' WHERE rowid=".$obj->rowid; + $resql2 = $db->query($sql); + if (!$resql2) { dol_print_error($db); } @@ -325,8 +325,8 @@ if (empty($reshook)) //Update status communication of thirdparty prospect $sql = "UPDATE ".MAIN_DB_PREFIX."societe SET fk_stcomm=2 WHERE rowid IN (SELECT source_id FROM ".MAIN_DB_PREFIX."mailing_cibles WHERE rowid=".$obj->rowid.")"; dol_syslog("card.php: set prospect thirdparty status", LOG_DEBUG); - $resql2=$db->query($sql); - if (! $resql2) + $resql2 = $db->query($sql); + if (!$resql2) { dol_print_error($db); } @@ -335,8 +335,8 @@ if (empty($reshook)) $sql = "UPDATE ".MAIN_DB_PREFIX."societe SET fk_stcomm=2 WHERE rowid IN (SELECT sc.fk_soc FROM ".MAIN_DB_PREFIX."socpeople AS sc INNER JOIN ".MAIN_DB_PREFIX."mailing_cibles AS mc ON mc.rowid=".$obj->rowid." AND mc.source_type = 'contact' AND mc.source_id = sc.rowid)"; dol_syslog("card.php: set prospect contact status", LOG_DEBUG); - $resql2=$db->query($sql); - if (! $resql2) + $resql2 = $db->query($sql); + if (!$resql2) { dol_print_error($db); } @@ -355,12 +355,12 @@ if (empty($reshook)) // Mail failed $nbko++; - dol_syslog("comm/mailing/card.php: error for #".$i.($mail->error?' - '.$mail->error:''), LOG_WARNING); + dol_syslog("comm/mailing/card.php: error for #".$i.($mail->error ? ' - '.$mail->error : ''), LOG_WARNING); - $sql="UPDATE ".MAIN_DB_PREFIX."mailing_cibles"; - $sql.=" SET statut=-1, error_text='".$db->escape($mail->error)."', date_envoi='".$db->idate($now)."' WHERE rowid=".$obj->rowid; - $resql2=$db->query($sql); - if (! $resql2) + $sql = "UPDATE ".MAIN_DB_PREFIX."mailing_cibles"; + $sql .= " SET statut=-1, error_text='".$db->escape($mail->error)."', date_envoi='".$db->idate($now)."' WHERE rowid=".$obj->rowid; + $resql2 = $db->query($sql); + if (!$resql2) { dol_print_error($db); } @@ -377,7 +377,7 @@ if (empty($reshook)) // Loop finished, set global statut of mail if ($nbko > 0) { - $statut=2; // Status 'sent partially' (because at least one error) + $statut = 2; // Status 'sent partially' (because at least one error) if ($nbok > 0) setEventMessages($langs->transnoentitiesnoconv("EMailSentToNRecipients", $nbok), null, 'mesgs'); else setEventMessages($langs->transnoentitiesnoconv("EMailSentToNRecipients", $nbok), null, 'mesgs'); } @@ -385,20 +385,20 @@ if (empty($reshook)) { if ($nbok >= $num) { - $statut=3; // Send to everybody + $statut = 3; // Send to everybody setEventMessages($langs->transnoentitiesnoconv("EMailSentToNRecipients", $nbok), null, 'mesgs'); } else { - $statut=2; // Status 'sent partially' (because not send to everybody) + $statut = 2; // Status 'sent partially' (because not send to everybody) setEventMessages($langs->transnoentitiesnoconv("EMailSentToNRecipients", $nbok), null, 'mesgs'); } } - $sql="UPDATE ".MAIN_DB_PREFIX."mailing SET statut=".$statut." WHERE rowid=".$object->id; + $sql = "UPDATE ".MAIN_DB_PREFIX."mailing SET statut=".$statut." WHERE rowid=".$object->id; dol_syslog("comm/mailing/card.php: update global status", LOG_DEBUG); - $resql2=$db->query($sql); - if (! $resql2) + $resql2 = $db->query($sql); + if (!$resql2) { dol_print_error($db); } @@ -416,22 +416,22 @@ if (empty($reshook)) // Action send test emailing if ($action == 'send' && empty($_POST["cancel"])) { - $error=0; + $error = 0; - $upload_dir = $conf->mailing->dir_output . "/" . get_exdir($object->id, 2, 0, 1, $object, 'mailing'); + $upload_dir = $conf->mailing->dir_output."/".get_exdir($object->id, 2, 0, 1, $object, 'mailing'); $object->sendto = $_POST["sendto"]; - if (! $object->sendto) + if (!$object->sendto) { setEventMessages($langs->trans("ErrorFieldRequired", $langs->transnoentitiesnoconv("MailTo")), null, 'errors'); $error++; } - if (! $error) + if (!$error) { // Le message est-il en html - $msgishtml=-1; // Inconnu par defaut - if (preg_match('/[\s\t]*/i', $object->body)) $msgishtml=1; + $msgishtml = -1; // Inconnu par defaut + if (preg_match('/[\s\t]*/i', $object->body)) $msgishtml = 1; // other are set at begin of page $object->substitutionarrayfortest['__EMAIL__'] = $object->sendto; @@ -439,8 +439,8 @@ if (empty($reshook)) // Pratique les substitutions sur le sujet et message complete_substitutions_array($object->substitutionarrayfortest, $langs); - $tmpsujet=make_substitutions($object->sujet, $object->substitutionarrayfortest); - $tmpbody=make_substitutions($object->body, $object->substitutionarrayfortest); + $tmpsujet = make_substitutions($object->sujet, $object->substitutionarrayfortest); + $tmpbody = make_substitutions($object->body, $object->substitutionarrayfortest); $arr_file = array(); $arr_mime = array(); @@ -448,25 +448,25 @@ if (empty($reshook)) $arr_css = array(); // Ajout CSS - if (!empty($object->bgcolor)) $arr_css['bgcolor'] = (preg_match('/^#/', $object->bgcolor)?'':'#').$object->bgcolor; + if (!empty($object->bgcolor)) $arr_css['bgcolor'] = (preg_match('/^#/', $object->bgcolor) ? '' : '#').$object->bgcolor; if (!empty($object->bgimage)) $arr_css['bgimage'] = $object->bgimage; // Attached files - $listofpaths=dol_dir_list($upload_dir, 'all', 0, '', '', 'name', SORT_ASC, 0); + $listofpaths = dol_dir_list($upload_dir, 'all', 0, '', '', 'name', SORT_ASC, 0); if (count($listofpaths)) { - foreach($listofpaths as $key => $val) + foreach ($listofpaths as $key => $val) { - $arr_file[]=$listofpaths[$key]['fullname']; - $arr_mime[]=dol_mimetype($listofpaths[$key]['name']); - $arr_name[]=$listofpaths[$key]['name']; + $arr_file[] = $listofpaths[$key]['fullname']; + $arr_mime[] = dol_mimetype($listofpaths[$key]['name']); + $arr_name[] = $listofpaths[$key]['name']; } } - $trackid='emailingtest'; + $trackid = 'emailingtest'; $mailfile = new CMailFile($tmpsujet, $object->sendto, $object->email_from, $tmpbody, $arr_file, $arr_mime, $arr_name, '', '', 0, $msgishtml, $object->email_errorsto, $arr_css, $trackid, '', 'emailing'); - $result=$mailfile->sendfile(); + $result = $mailfile->sendfile(); if ($result) { setEventMessages($langs->trans("MailSuccessfulySent", $mailfile->getValidAddress($object->email_from, 2), $mailfile->getValidAddress($object->sendto, 2)), null, 'mesgs'); @@ -494,13 +494,13 @@ if (empty($reshook)) $object->bgcolor = trim($_POST["bgcolor"]); $object->bgimage = trim($_POST["bgimage"]); - if (! $object->titre) { + if (!$object->titre) { $mesgs[] = $langs->trans("ErrorFieldRequired", $langs->transnoentities("MailTitle")); } - if (! $object->sujet) { + if (!$object->sujet) { $mesgs[] = $langs->trans("ErrorFieldRequired", $langs->transnoentities("MailTopic")); } - if (! $object->body) { + if (!$object->body) { $mesgs[] = $langs->trans("ErrorFieldRequired", $langs->transnoentities("MailMessage")); } @@ -515,17 +515,17 @@ if (empty($reshook)) } setEventMessages($mesg, $mesgs, 'errors'); - $action="create"; + $action = "create"; } // Action update description of emailing if ($action == 'settitre' || $action == 'setemail_from' || $action == 'setreplyto' || $action == 'setemail_errorsto') { - $upload_dir = $conf->mailing->dir_output . "/" . get_exdir($object->id, 2, 0, 1, $object, 'mailing'); + $upload_dir = $conf->mailing->dir_output."/".get_exdir($object->id, 2, 0, 1, $object, 'mailing'); if ($action == 'settitre') $object->titre = trim(GETPOST('titre', 'alpha')); elseif ($action == 'setemail_from') $object->email_from = trim(GETPOST('email_from', 'alpha')); - elseif ($action == 'setemail_replyto') $object->email_replyto = trim(GETPOST('email_replyto', 'alpha')); + elseif ($action == 'setemail_replyto') $object->email_replyto = trim(GETPOST('email_replyto', 'alpha')); elseif ($action == 'setemail_errorsto') { $object->email_errorsto = trim(GETPOST('email_errorsto', 'alpha')); } elseif ($action == 'settitre' && empty($object->titre)) { @@ -534,7 +534,7 @@ if (empty($reshook)) $mesg = $langs->trans("ErrorFieldRequired", $langs->transnoentities("MailFrom")); } - if (! $mesg) + if (!$mesg) { if ($object->update($user) >= 0) { @@ -545,34 +545,34 @@ if (empty($reshook)) } setEventMessages($mesg, $mesgs, 'errors'); - $action=""; + $action = ""; } /* * Add file in email form */ - if (! empty($_POST['addfile'])) + if (!empty($_POST['addfile'])) { - $upload_dir = $conf->mailing->dir_output . "/" . get_exdir($object->id, 2, 0, 1, $object, 'mailing'); + $upload_dir = $conf->mailing->dir_output."/".get_exdir($object->id, 2, 0, 1, $object, 'mailing'); require_once DOL_DOCUMENT_ROOT.'/core/lib/files.lib.php'; // Set tmp user directory dol_add_file_process($upload_dir, 0, 0); - $action="edit"; + $action = "edit"; } // Action remove file - if (! empty($_POST["removedfile"])) + if (!empty($_POST["removedfile"])) { - $upload_dir = $conf->mailing->dir_output . "/" . get_exdir($object->id, 2, 0, 1, $object, 'mailing'); + $upload_dir = $conf->mailing->dir_output."/".get_exdir($object->id, 2, 0, 1, $object, 'mailing'); require_once DOL_DOCUMENT_ROOT.'/core/lib/files.lib.php'; - dol_remove_file_process($_POST['removedfile'], 0, 0); // We really delete file linked to mailing + dol_remove_file_process($_POST['removedfile'], 0, 0); // We really delete file linked to mailing - $action="edit"; + $action = "edit"; } // Action update emailing @@ -580,9 +580,9 @@ if (empty($reshook)) { require_once DOL_DOCUMENT_ROOT.'/core/lib/files.lib.php'; - $isupload=0; + $isupload = 0; - if (! $isupload) + if (!$isupload) { $mesgs = array(); @@ -591,10 +591,10 @@ if (empty($reshook)) $object->bgcolor = trim($_POST["bgcolor"]); $object->bgimage = trim($_POST["bgimage"]); - if (! $object->sujet) { + if (!$object->sujet) { $mesgs[] = $langs->trans("ErrorFieldRequired", $langs->transnoentities("MailTopic")); } - if (! $object->body) { + if (!$object->body) { $mesgs[] = $langs->trans("ErrorFieldRequired", $langs->transnoentities("MailMessage")); } @@ -605,15 +605,15 @@ if (empty($reshook)) header("Location: ".$_SERVER['PHP_SELF']."?id=".$object->id); exit; } - $mesgs[] =$object->error; + $mesgs[] = $object->error; } setEventMessages($mesg, $mesgs, 'errors'); - $action="edit"; + $action = "edit"; } else { - $action="edit"; + $action = "edit"; } } @@ -663,10 +663,10 @@ if (empty($reshook)) { $db->begin(); - $result=$object->valid($user); + $result = $object->valid($user); if ($result > 0) { - $result=$object->reset_targets_status($user); + $result = $object->reset_targets_status($user); } if ($result > 0) @@ -692,13 +692,13 @@ if (empty($reshook)) { if ($object->delete($object->id)) { - $url= (! empty($urlfrom) ? $urlfrom : 'list.php'); + $url = (!empty($urlfrom) ? $urlfrom : 'list.php'); header("Location: ".$url); exit; } } - if (! empty($_POST["cancel"])) + if (!empty($_POST["cancel"])) { $action = ''; } @@ -712,7 +712,7 @@ if (empty($reshook)) $form = new Form($db); $htmlother = new FormOther($db); -$help_url='EN:Module_EMailing|FR:Module_Mailing|ES:Módulo_Mailing'; +$help_url = 'EN:Module_EMailing|FR:Module_Mailing|ES:Módulo_Mailing'; llxHeader('', $langs->trans("Mailing"), $help_url, '', 0, 0, array( '/includes/ace/src/ace.js', @@ -729,14 +729,14 @@ if ($action == 'create') print ''; $htmltext = ''.$langs->trans("FollowingConstantsWillBeSubstituted").':
'; - foreach($object->substitutionarray as $key => $val) + foreach ($object->substitutionarray as $key => $val) { - $htmltext.=$key.' = '.$langs->trans($val).'
'; + $htmltext .= $key.' = '.$langs->trans($val).'
'; } - $htmltext.='
'; + $htmltext .= ''; - $availablelink=$form->textwithpicto($langs->trans("AvailableVariables"), $htmltext, 1, 'help', '', 0, 2, 'availvar'); + $availablelink = $form->textwithpicto($langs->trans("AvailableVariables"), $htmltext, 1, 'help', '', 0, 2, 'availvar'); //print ''.img_picto($langs->trans("ClickToShowDescription"), $imginfo).''; @@ -748,11 +748,11 @@ if ($action == 'create') print ''; print ''; print ''; - print ''; + print ''; // Other attributes - $parameters=array(); - $reshook=$hookmanager->executeHooks('formObjectOptions', $parameters, $object, $action); // Note that $action and $object may have been modified by hook + $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)) { @@ -762,7 +762,7 @@ if ($action == 'create') print '
'.$langs->trans("MailTitle").'
'.$langs->trans("MailFrom").'
'.$langs->trans("MailErrorsTo").'
'.$langs->trans("MailErrorsTo").'
'; print '

'; - print ''; + print '
'; print ''; print ''; // Other attributes - include DOL_DOCUMENT_ROOT . '/core/tpl/extrafields_view.tpl.php'; + include DOL_DOCUMENT_ROOT.'/core/tpl/extrafields_view.tpl.php'; print '
'.$langs->trans("MailTopic").'
'.$langs->trans("BackgroundColorByDefault").''; print $htmlother->selectColor($_POST['bgcolor'], 'bgcolor', '', 0); @@ -773,7 +773,7 @@ if ($action == 'create') print '
'; // Editeur wysiwyg require_once DOL_DOCUMENT_ROOT.'/core/class/doleditor.class.php'; - $doleditor=new DolEditor('bodyemail', GETPOST('bodyemail', 'none'), '', 600, 'dolibarr_mailings', '', true, true, $conf->global->FCKEDITOR_ENABLE_MAILING, 20, '90%'); + $doleditor = new DolEditor('bodyemail', GETPOST('bodyemail', 'none'), '', 600, 'dolibarr_mailings', '', true, true, $conf->global->FCKEDITOR_ENABLE_MAILING, 20, '90%'); $doleditor->Create(); print '
'; @@ -787,7 +787,7 @@ else { if ($object->id > 0) { - $upload_dir = $conf->mailing->dir_output . "/" . get_exdir($object->id, 2, 0, 1, $object, 'mailing'); + $upload_dir = $conf->mailing->dir_output."/".get_exdir($object->id, 2, 0, 1, $object, 'mailing'); $head = emailing_prepare_head($object); @@ -809,7 +809,7 @@ else // Confirm delete elseif ($action == 'delete') { - print $form->formconfirm($_SERVER["PHP_SELF"]."?id=".$object->id.(! empty($urlfrom) ? '&urlfrom='.urlencode($urlfrom) : ''), $langs->trans("DeleteAMailing"), $langs->trans("ConfirmDeleteMailing"), "confirm_delete", '', '', 1); + print $form->formconfirm($_SERVER["PHP_SELF"]."?id=".$object->id.(!empty($urlfrom) ? '&urlfrom='.urlencode($urlfrom) : ''), $langs->trans("DeleteAMailing"), $langs->trans("ConfirmDeleteMailing"), "confirm_delete", '', '', 1); } @@ -919,22 +919,22 @@ else print '
'; print $langs->trans("TotalNbOfDistinctRecipients"); print ''; - $nbemail = ($object->nbemail?$object->nbemail:0); + $nbemail = ($object->nbemail ? $object->nbemail : 0); if (is_numeric($nbemail)) { - $text=''; - if ((! empty($conf->global->MAILING_LIMIT_SENDBYWEB) && $conf->global->MAILING_LIMIT_SENDBYWEB < $nbemail) && ($object->statut == 1 || ($object->statut == 2 && $nbtry < $nbemail))) + $text = ''; + if ((!empty($conf->global->MAILING_LIMIT_SENDBYWEB) && $conf->global->MAILING_LIMIT_SENDBYWEB < $nbemail) && ($object->statut == 1 || ($object->statut == 2 && $nbtry < $nbemail))) { if ($conf->global->MAILING_LIMIT_SENDBYWEB > 0) { - $text.=$langs->trans('LimitSendingEmailing', $conf->global->MAILING_LIMIT_SENDBYWEB); + $text .= $langs->trans('LimitSendingEmailing', $conf->global->MAILING_LIMIT_SENDBYWEB); } else { - $text.=$langs->trans('SendingFromWebInterfaceIsNotAllowed'); + $text .= $langs->trans('SendingFromWebInterfaceIsNotAllowed'); } } - if (empty($nbemail)) $nbemail.=' '.img_warning('').' '.$langs->trans("NoTargetYet").''; + if (empty($nbemail)) $nbemail .= ' '.img_warning('').' '.$langs->trans("NoTargetYet").''; if ($text) { print $form->textwithpicto($nbemail, $text, 1, 'warning'); @@ -947,7 +947,7 @@ else print '
'; @@ -960,9 +960,9 @@ else if ($action == 'clone') { // Create an array for form - $formquestion=array( + $formquestion = array( 'text' => $langs->trans("ConfirmClone"), - array('type' => 'checkbox', 'name' => 'clone_content', 'label' => $langs->trans("CloneContent"), 'value' => 1), + array('type' => 'checkbox', 'name' => 'clone_content', 'label' => $langs->trans("CloneContent"), 'value' => 1), array('type' => 'checkbox', 'name' => 'clone_receivers', 'label' => $langs->trans("CloneReceivers"), 'value' => 0) ); // Paiement incomplet. On demande si motif = escompte ou autre @@ -973,7 +973,7 @@ else * Boutons d'action */ - if (GETPOST('cancel', 'alpha') || $confirm=='no' || $action == '' || in_array($action, array('settodraft','valid','delete','sendall','clone','test'))) + if (GETPOST('cancel', 'alpha') || $confirm == 'no' || $action == '' || in_array($action, array('settodraft', 'valid', 'delete', 'sendall', 'clone', 'test'))) { print "\n\n
\n"; @@ -984,7 +984,7 @@ else if (($object->statut == 0 || $object->statut == 1) && $user->rights->mailing->creer) { - if (! empty($conf->fckeditor->enabled) && ! empty($conf->global->FCKEDITOR_ENABLE_MAILING)) + if (!empty($conf->fckeditor->enabled) && !empty($conf->global->FCKEDITOR_ENABLE_MAILING)) { print ''.$langs->trans("EditWithEditor").''; } @@ -993,12 +993,12 @@ else print ''.$langs->trans("EditWithTextEditor").''; } - if (! empty($conf->use_javascript_ajax)) print ''.$langs->trans("EditHTMLSource").''; + if (!empty($conf->use_javascript_ajax)) print ''.$langs->trans("EditHTMLSource").''; } //print ''.$langs->trans("PreviewMailing").''; - if (! empty($conf->global->MAIN_USE_ADVANCED_PERMS) && ! $user->rights->mailing->mailing_advance->send) + if (!empty($conf->global->MAIN_USE_ADVANCED_PERMS) && !$user->rights->mailing->mailing_advance->send) { print ''.$langs->trans("TestMailing").''; } @@ -1029,7 +1029,7 @@ else { print ''.$langs->trans("SendMailing").''; } - elseif (! empty($conf->global->MAIN_USE_ADVANCED_PERMS) && ! $user->rights->mailing->mailing_advance->send) + elseif (!empty($conf->global->MAIN_USE_ADVANCED_PERMS) && !$user->rights->mailing->mailing_advance->send) { print ''.$langs->trans("SendMailing").''; } @@ -1046,7 +1046,7 @@ else if (($object->statut == 2 || $object->statut == 3) && $user->rights->mailing->valider) { - if (! empty($conf->global->MAIN_USE_ADVANCED_PERMS) && ! $user->rights->mailing->mailing_advance->send) + if (!empty($conf->global->MAIN_USE_ADVANCED_PERMS) && !$user->rights->mailing->mailing_advance->send) { print ''.$langs->trans("ResetMailing").''; } @@ -1058,13 +1058,13 @@ else if (($object->statut <= 1 && $user->rights->mailing->creer) || $user->rights->mailing->supprimer) { - if ($object->statut > 0 && (! empty($conf->global->MAIN_USE_ADVANCED_PERMS) && ! $user->rights->mailing->mailing_advance->delete)) + if ($object->statut > 0 && (!empty($conf->global->MAIN_USE_ADVANCED_PERMS) && !$user->rights->mailing->mailing_advance->delete)) { print ''.$langs->trans("DeleteMailing").''; } else { - print ''.$langs->trans("DeleteMailing").''; + print ''.$langs->trans("DeleteMailing").''; } } @@ -1084,25 +1084,25 @@ else $formmail = new FormMail($db); $formmail->fromname = $object->email_from; $formmail->frommail = $object->email_from; - $formmail->withsubstit=1; - $formmail->withfrom=0; - $formmail->withto=$user->email?$user->email:1; - $formmail->withtocc=0; - $formmail->withtoccc=$conf->global->MAIN_EMAIL_USECCC; - $formmail->withtopic=0; - $formmail->withtopicreadonly=1; - $formmail->withfile=0; - $formmail->withbody=0; - $formmail->withbodyreadonly=1; - $formmail->withcancel=1; - $formmail->withdeliveryreceipt=0; + $formmail->withsubstit = 1; + $formmail->withfrom = 0; + $formmail->withto = $user->email ? $user->email : 1; + $formmail->withtocc = 0; + $formmail->withtoccc = $conf->global->MAIN_EMAIL_USECCC; + $formmail->withtopic = 0; + $formmail->withtopicreadonly = 1; + $formmail->withfile = 0; + $formmail->withbody = 0; + $formmail->withbodyreadonly = 1; + $formmail->withcancel = 1; + $formmail->withdeliveryreceipt = 0; // Tableau des substitutions - $formmail->substit=$object->substitutionarrayfortest; + $formmail->substit = $object->substitutionarrayfortest; // Tableau des parametres complementaires du post - $formmail->param["action"]="send"; - $formmail->param["models"]='none'; - $formmail->param["mailid"]=$object->id; - $formmail->param["returnurl"]=$_SERVER['PHP_SELF']."?id=".$object->id; + $formmail->param["action"] = "send"; + $formmail->param["models"] = 'none'; + $formmail->param["mailid"] = $object->id; + $formmail->param["returnurl"] = $_SERVER['PHP_SELF']."?id=".$object->id; print $formmail->get_form(); @@ -1115,11 +1115,11 @@ else $htmltext = ''.$langs->trans("FollowingConstantsWillBeSubstituted").':
'; - foreach($object->substitutionarray as $key => $val) + foreach ($object->substitutionarray as $key => $val) { - $htmltext.=$key.' = '.$langs->trans($val).'
'; + $htmltext .= $key.' = '.$langs->trans($val).'
'; } - $htmltext.='
'; + $htmltext .= ''; // Print mail content print load_fiche_titre($langs->trans("EMail"), $form->textwithpicto(''.$langs->trans("AvailableVariables").'', $htmltext, 1, 'helpclickable', '', 0, 2, 'emailsubstitionhelp'), 'generic'); @@ -1134,10 +1134,10 @@ else // Joined files print '
'.$langs->trans("MailFile").''; // List of files - $listofpaths=dol_dir_list($upload_dir, 'all', 0, '', '', 'name', SORT_ASC, 0); + $listofpaths = dol_dir_list($upload_dir, 'all', 0, '', '', 'name', SORT_ASC, 0); if (count($listofpaths)) { - foreach($listofpaths as $key => $val) + foreach ($listofpaths as $key => $val) { print img_mime($listofpaths[$key]['name']).' '.$listofpaths[$key]['name']; print '
'; @@ -1157,13 +1157,13 @@ else print '
'; // Message - print '
'; + print '
'; if (empty($object->bgcolor) || strtolower($object->bgcolor) == 'ffffff') // CKEditor does not apply the color of the div into its content area { - $readonly=1; + $readonly = 1; // Editeur wysiwyg require_once DOL_DOCUMENT_ROOT.'/core/class/doleditor.class.php'; - $doleditor=new DolEditor('bodyemail', $object->body, '', 600, 'dolibarr_mailings', '', false, true, empty($conf->global->FCKEDITOR_ENABLE_MAILING)?0:1, 20, '90%', $readonly); + $doleditor = new DolEditor('bodyemail', $object->body, '', 600, 'dolibarr_mailings', '', false, true, empty($conf->global->FCKEDITOR_ENABLE_MAILING) ? 0 : 1, 20, '90%', $readonly); $doleditor->Create(); } else print dol_htmlentitiesbr($object->body); @@ -1181,15 +1181,15 @@ else $linkback = ''.$langs->trans("BackToList").''; - $morehtmlright=''; - if ($object->statut == 2) $morehtmlright.=' ('.$object->countNbOfTargets('alreadysent').'/'.$object->nbemail.') '; + $morehtmlright = ''; + if ($object->statut == 2) $morehtmlright .= ' ('.$object->countNbOfTargets('alreadysent').'/'.$object->nbemail.') '; dol_banner_tab($object, 'id', $linkback, 1, 'rowid', 'ref', '', '', 0, '', $morehtmlright); print '
'; print '
'; - print ''; + print '
'; /* print ''; @@ -1209,22 +1209,22 @@ else print ''; // Other attributes - $parameters=array(); - $reshook=$hookmanager->executeHooks('formObjectOptions', $parameters, $object, $action); // Note that $action and $object may have been modified by hook + $parameters = array(); + $reshook = $hookmanager->executeHooks('formObjectOptions', $parameters, $object, $action); // Note that $action and $object may have been modified by hook print $hookmanager->resPrint; if (empty($reshook)) { - print $object->showOptionals($extrafields, 'edit'); + print $object->showOptionals($extrafields, 'edit', $parameters); } print '
'.$langs->trans("Ref").'
'; print $langs->trans("TotalNbOfDistinctRecipients"); print ''; - $nbemail = ($object->nbemail?$object->nbemail:0); + $nbemail = ($object->nbemail ? $object->nbemail : 0); if (is_numeric($nbemail)) { - $text=''; - if ((! empty($conf->global->MAILING_LIMIT_SENDBYWEB) && $conf->global->MAILING_LIMIT_SENDBYWEB < $nbemail) && ($object->statut == 1 || $object->statut == 2)) + $text = ''; + if ((!empty($conf->global->MAILING_LIMIT_SENDBYWEB) && $conf->global->MAILING_LIMIT_SENDBYWEB < $nbemail) && ($object->statut == 1 || $object->statut == 2)) { if ($conf->global->MAILING_LIMIT_SENDBYWEB > 0) { - $text.=$langs->trans('LimitSendingEmailing', $conf->global->MAILING_LIMIT_SENDBYWEB); + $text .= $langs->trans('LimitSendingEmailing', $conf->global->MAILING_LIMIT_SENDBYWEB); } else { - $text.=$langs->trans('SendingFromWebInterfaceIsNotAllowed'); + $text .= $langs->trans('SendingFromWebInterfaceIsNotAllowed'); } } - if (empty($nbemail)) $nbemail.=' '.img_warning('').' '.$langs->trans("NoTargetYet").''; + if (empty($nbemail)) $nbemail .= ' '.img_warning('').' '.$langs->trans("NoTargetYet").''; if ($text) { print $form->textwithpicto($nbemail, $text, 1, 'warning'); @@ -1237,12 +1237,12 @@ else print '
'; @@ -1260,11 +1260,11 @@ else print ''; $htmltext = ''.$langs->trans("FollowingConstantsWillBeSubstituted").':
'; - foreach($object->substitutionarray as $key => $val) + foreach ($object->substitutionarray as $key => $val) { - $htmltext.=$key.' = '.$langs->trans($val).'
'; + $htmltext .= $key.' = '.$langs->trans($val).'
'; } - $htmltext.='
'; + $htmltext .= ''; // Print mail content print load_fiche_titre($langs->trans("EMail"), $form->textwithpicto($langs->trans("AvailableVariables"), $htmltext, 1, 'help', '', 0, 2, 'emailsubstitionhelp'), 'generic'); @@ -1276,43 +1276,43 @@ else // Subject print '
'.$langs->trans("MailTopic").'
'.$langs->trans("MailFile").''; // List of files - $listofpaths=dol_dir_list($upload_dir, 'all', 0, '', '', 'name', SORT_ASC, 0); + $listofpaths = dol_dir_list($upload_dir, 'all', 0, '', '', 'name', SORT_ASC, 0); // TODO Trick to have param removedfile containing nb of image to delete. But this does not works without javascript - $out.= ''."\n"; - $out.= ''."\n"; + $out .= ''."\n"; + $out .= ''."\n"; if (count($listofpaths)) { - foreach($listofpaths as $key => $val) + foreach ($listofpaths as $key => $val) { - $out.= '
'; - $out.= img_mime($listofpaths[$key]['name']).' '.$listofpaths[$key]['name']; - $out.= ' '; - $out.= '
'; + $out .= '
'; + $out .= img_mime($listofpaths[$key]['name']).' '.$listofpaths[$key]['name']; + $out .= ' '; + $out .= '
'; } } else { - $out.= $langs->trans("NoAttachedFiles").'
'; + $out .= $langs->trans("NoAttachedFiles").'
'; } // Add link to add file - $out.= ''; - $out.= ' '; - $out.= ''; + $out .= ''; + $out .= ' '; + $out .= ''; print $out; print '
'; print $langs->trans("TotalNbOfDistinctRecipients"); print ''; - $nbemail = ($object->nbemail?$object->nbemail:0); + $nbemail = ($object->nbemail ? $object->nbemail : 0); if (is_numeric($nbemail)) { - $text=''; - if ((! empty($conf->global->MAILING_LIMIT_SENDBYWEB) && $conf->global->MAILING_LIMIT_SENDBYWEB < $nbemail) && ($object->statut == 1 || ($object->statut == 2 && $nbtry < $nbemail))) + $text = ''; + if ((!empty($conf->global->MAILING_LIMIT_SENDBYWEB) && $conf->global->MAILING_LIMIT_SENDBYWEB < $nbemail) && ($object->statut == 1 || ($object->statut == 2 && $nbtry < $nbemail))) { if ($conf->global->MAILING_LIMIT_SENDBYWEB > 0) { - $text.=$langs->trans('LimitSendingEmailing', $conf->global->MAILING_LIMIT_SENDBYWEB); + $text .= $langs->trans('LimitSendingEmailing', $conf->global->MAILING_LIMIT_SENDBYWEB); } else { - $text.=$langs->trans('SendingFromWebInterfaceIsNotAllowed'); + $text .= $langs->trans('SendingFromWebInterfaceIsNotAllowed'); } } - if (empty($nbemail)) $nbemail.=' '.img_warning('').' '.$langs->trans("NoTargetYet").''; + if (empty($nbemail)) $nbemail .= ' '.img_warning('').' '.$langs->trans("NoTargetYet").''; if ($text) { print $form->textwithpicto($nbemail, $text, 1, 'warning'); @@ -290,14 +290,14 @@ if ($object->fetch($id) >= 0) print '
'; - $allowaddtarget=($object->statut == 0); + $allowaddtarget = ($object->statut == 0); // Show email selectors if ($allowaddtarget && $user->rights->mailing->creer) { - print load_fiche_titre($langs->trans("ToAddRecipientsChooseHere"), ($user->admin?info_admin($langs->trans("YouCanAddYourOwnPredefindedListHere"), 1):''), 'generic'); + print load_fiche_titre($langs->trans("ToAddRecipientsChooseHere"), ($user->admin ?info_admin($langs->trans("YouCanAddYourOwnPredefindedListHere"), 1) : ''), 'generic'); - //print ''; + //print '
'; print '
'; //print '
'; @@ -317,22 +317,22 @@ if ($object->fetch($id) >= 0) foreach ($modulesdir as $dir) { - $modulenames=array(); + $modulenames = array(); // Load modules attributes in arrays (name, numero, orders) from dir directory //print $dir."\n
"; dol_syslog("Scan directory ".$dir." for modules"); - $handle=@opendir($dir); + $handle = @opendir($dir); if (is_resource($handle)) { - while (($file = readdir($handle))!==false) + while (($file = readdir($handle)) !== false) { if (substr($file, 0, 1) <> '.' && substr($file, 0, 3) <> 'CVS') { if (preg_match("/(.*)\.modules\.php$/i", $file, $reg)) { if ($reg[1] == 'example') continue; - $modulenames[]=$reg[1]; + $modulenames[] = $reg[1]; } } } @@ -345,7 +345,7 @@ if ($object->fetch($id) >= 0) $var = true; // Loop on each submodule - foreach($modulenames as $modulename) + foreach ($modulenames as $modulename) { // Loading Class $file = $dir.$modulename.".modules.php"; @@ -355,12 +355,12 @@ if ($object->fetch($id) >= 0) $obj = new $classname($db); // Check dependencies - $qualified=(isset($obj->enabled)?$obj->enabled:1); + $qualified = (isset($obj->enabled) ? $obj->enabled : 1); foreach ($obj->require_module as $key) { - if (! $conf->$key->enabled || (! $user->admin && $obj->require_admin)) + if (!$conf->$key->enabled || (!$user->admin && $obj->require_admin)) { - $qualified=0; + $qualified = 0; //print "Les prerequis d'activation du module mailing ne sont pas respectes. Il ne sera pas actif"; break; } @@ -369,7 +369,7 @@ if ($object->fetch($id) >= 0) // Si le module mailing est qualifie if ($qualified) { - $var = ! $var; + $var = !$var; if ($allowaddtarget) { @@ -382,16 +382,16 @@ if ($object->fetch($id) >= 0) } print '
'; - if (empty($obj->picto)) $obj->picto='generic'; + if (empty($obj->picto)) $obj->picto = 'generic'; print img_object($langs->trans("EmailingTargetSelector").': '.get_class($obj), $obj->picto, 'class="valignmiddle pictomodule"'); print ' '; print $obj->getDesc(); print '
'; try { - $nbofrecipient=$obj->getNbOfRecipients(''); + $nbofrecipient = $obj->getNbOfRecipients(''); } - catch(Exception $e) + catch (Exception $e) { dol_syslog($e->getMessage(), LOG_ERR); } @@ -411,9 +411,9 @@ if ($object->fetch($id) >= 0) if ($allowaddtarget) { try { - $filter=$obj->formFilter(); + $filter = $obj->formFilter(); } - catch(Exception $e) + catch (Exception $e) { dol_syslog($e->getMessage(), LOG_ERR); } @@ -451,11 +451,11 @@ if ($object->fetch($id) >= 0) $sql .= " mc.source_url, mc.source_id, mc.source_type, mc.error_text"; $sql .= " FROM ".MAIN_DB_PREFIX."mailing_cibles as mc"; $sql .= " WHERE mc.fk_mailing=".$object->id; - if ($search_lastname) $sql.= natural_search("mc.lastname", $search_lastname); - if ($search_firstname) $sql.= natural_search("mc.firstname", $search_firstname); - if ($search_email) $sql.= natural_search("mc.email", $search_email); - if ($search_other) $sql.= natural_search("mc.other", $search_other); - if ($search_dest_status != '' && $search_dest_status >= -1) $sql.= " AND mc.statut=".$db->escape($search_dest_status)." "; + if ($search_lastname) $sql .= natural_search("mc.lastname", $search_lastname); + if ($search_firstname) $sql .= natural_search("mc.firstname", $search_firstname); + if ($search_email) $sql .= natural_search("mc.email", $search_email); + if ($search_other) $sql .= natural_search("mc.other", $search_other); + if ($search_dest_status != '' && $search_dest_status >= -1) $sql .= " AND mc.statut=".$db->escape($search_dest_status)." "; $sql .= $db->order($sortfield, $sortorder); // Count total nb of records @@ -472,20 +472,20 @@ if ($object->fetch($id) >= 0) } //$nbtotalofrecords=$object->nbemail; // nbemail is a denormalized field storing nb of targets - $sql .= $db->plimit($limit+1, $offset); + $sql .= $db->plimit($limit + 1, $offset); - $resql=$db->query($sql); + $resql = $db->query($sql); if ($resql) { $num = $db->num_rows($resql); $param = "&id=".$object->id; //if (! empty($contextpage) && $contextpage != $_SERVER["PHP_SELF"]) $param.='&contextpage='.urlencode($contextpage); - if ($limit > 0 && $limit != $conf->liste_limit) $param.='&limit='.urlencode($limit); - if ($search_lastname) $param.= "&search_lastname=".urlencode($search_lastname); - if ($search_firstname) $param.= "&search_firstname=".urlencode($search_firstname); - if ($search_email) $param.= "&search_email=".urlencode($search_email); - if ($search_other) $param.= "&search_other=".urlencode($search_other); + if ($limit > 0 && $limit != $conf->liste_limit) $param .= '&limit='.urlencode($limit); + if ($search_lastname) $param .= "&search_lastname=".urlencode($search_lastname); + if ($search_firstname) $param .= "&search_firstname=".urlencode($search_firstname); + if ($search_email) $param .= "&search_email=".urlencode($search_email); + if ($search_other) $param .= "&search_other=".urlencode($search_other); print ''; print ''; @@ -494,11 +494,11 @@ if ($object->fetch($id) >= 0) print ''; print ''; - $morehtmlcenter=''; + $morehtmlcenter = ''; if ($allowaddtarget) { - $morehtmlcenter=''.$langs->trans("ToClearAllRecipientsClickHere").'id.'" class="button reposition">'.$langs->trans("TargetsReset").''; + $morehtmlcenter = ''.$langs->trans("ToClearAllRecipientsClickHere").'id.'" class="button reposition">'.$langs->trans("TargetsReset").''; } - $morehtmlcenter.=' id.'">'.$langs->trans("Download").''; + $morehtmlcenter .= ' id.'">'.$langs->trans("Download").''; print_barre_liste($langs->trans("MailSelectedRecipients"), $page, $_SERVER["PHP_SELF"], $param, $sortfield, $sortorder, $morehtmlcenter, $num, $nbtotalofrecords, 'generic', 0, '', '', $limit); @@ -555,12 +555,12 @@ if ($object->fetch($id) >= 0) print ''; // Action column print ''; print ''; - if ($page) $param.= "&page=".urlencode($page); + if ($page) $param .= "&page=".urlencode($page); print ''; print_liste_field_titre("EMail", $_SERVER["PHP_SELF"], "mc.email", $param, "", "", $sortfield, $sortorder); @@ -584,10 +584,10 @@ if ($object->fetch($id) >= 0) include_once DOL_DOCUMENT_ROOT.'/user/class/user.class.php'; include_once DOL_DOCUMENT_ROOT.'/societe/class/societe.class.php'; include_once DOL_DOCUMENT_ROOT.'/contact/class/contact.class.php'; - $objectstaticmember=new Adherent($db); - $objectstaticuser=new User($db); - $objectstaticcompany=new Societe($db); - $objectstaticcontact=new Contact($db); + $objectstaticmember = new Adherent($db); + $objectstaticuser = new User($db); + $objectstaticcompany = new Societe($db); + $objectstaticcontact = new Contact($db); while ($i < min($num, $limit)) { @@ -601,7 +601,7 @@ if ($object->fetch($id) >= 0) print ''; if ($action != 'editconditions' && $object->statut == Propal::STATUS_DRAFT && $usercancreate) - print ''; + print ''; print '
'; - $searchpicto=$form->showFilterAndCheckAddButtons($massactionbutton?1:0, 'checkforselect', 1); + $searchpicto = $form->showFilterAndCheckAddButtons($massactionbutton ? 1 : 0, 'checkforselect', 1); print $searchpicto; print '
'; if (empty($obj->source_id) || empty($obj->source_type)) { - print empty($obj->source_url)?'':$obj->source_url; // For backward compatibility + print empty($obj->source_url) ? '' : $obj->source_url; // For backward compatibility } else { diff --git a/htdocs/comm/mailing/class/advtargetemailing.class.php b/htdocs/comm/mailing/class/advtargetemailing.class.php index 465bf7dcc50..0b47d8c4aa5 100644 --- a/htdocs/comm/mailing/class/advtargetemailing.class.php +++ b/htdocs/comm/mailing/class/advtargetemailing.class.php @@ -36,7 +36,7 @@ class AdvanceTargetingMailing extends CommonObject /** * @var string Error code (or message) */ - public $error=''; + public $error = ''; /** * @var string[] Error codes (or messages) @@ -46,12 +46,12 @@ class AdvanceTargetingMailing extends CommonObject /** * @var string ID to identify managed object */ - public $element='advtargetemailing'; + public $element = 'advtargetemailing'; /** * @var string Name of table without prefix where object is stored */ - public $table_element='advtargetemailing'; + public $table_element = 'advtargetemailing'; /** * @var int ID @@ -64,12 +64,12 @@ class AdvanceTargetingMailing extends CommonObject public $type_element; public $filtervalue; public $fk_user_author; - public $datec=''; + public $datec = ''; public $fk_user_mod; - public $tms=''; + public $tms = ''; public $select_target_type = array(); - public $type_statuscommprospect=array(); + public $type_statuscommprospect = array(); public $thirdparty_lines; public $contact_lines; @@ -88,12 +88,12 @@ class AdvanceTargetingMailing extends CommonObject $this->select_target_type = array( '2' => $langs->trans('Contacts'), - '1' => $langs->trans('Contacts') . '+' . $langs->trans('ThirdParty'), + '1' => $langs->trans('Contacts').'+'.$langs->trans('ThirdParty'), '3' => $langs->trans('ThirdParty'), '4' => $langs->trans('ContactsWithThirdpartyFilter') ); $this->type_statuscommprospect = array( - - 1 => $langs->trans("StatusProspect-1"), + -1 => $langs->trans("StatusProspect-1"), 0 => $langs->trans("StatusProspect0"), 1 => $langs->trans("StatusProspect1"), 2 => $langs->trans("StatusProspect2"), @@ -111,50 +111,50 @@ class AdvanceTargetingMailing extends CommonObject public function create($user, $notrigger = 0) { global $conf, $langs; - $error=0; + $error = 0; // Clean parameters - if (isset($this->fk_element)) $this->fk_element=(int) $this->fk_element; - if (isset($this->type_element)) $this->type_element=trim($this->type_element); + if (isset($this->fk_element)) $this->fk_element = (int) $this->fk_element; + if (isset($this->type_element)) $this->type_element = trim($this->type_element); - if (isset($this->name)) $this->name=trim($this->name); - if (isset($this->filtervalue)) $this->filtervalue=trim($this->filtervalue); + if (isset($this->name)) $this->name = trim($this->name); + if (isset($this->filtervalue)) $this->filtervalue = trim($this->filtervalue); // Check parameters // Put here code to add control on parameters values // Insert request $sql = "INSERT INTO ".MAIN_DB_PREFIX."advtargetemailing("; - $sql.= "name,"; - $sql.= "entity,"; - $sql.= "fk_element,"; - $sql.= "type_element,"; - $sql.= "filtervalue,"; - $sql.= "fk_user_author,"; - $sql.= "datec,"; - $sql.= "fk_user_mod"; - $sql.= ") VALUES ("; - $sql.= " ".(! isset($this->name)?'NULL':"'".$this->db->escape($this->name)."'").","; - $sql.= " ".$conf->entity.","; - $sql.= " ".(! isset($this->fk_element)?'NULL':"'".$this->db->escape($this->fk_element)."'").","; - $sql.= " ".(! isset($this->type_element)?'NULL':"'".$this->db->escape($this->type_element)."'").","; - $sql.= " ".(! isset($this->filtervalue)?'NULL':"'".$this->db->escape($this->filtervalue)."'").","; - $sql.= " ".$user->id.","; - $sql.= " '".$this->db->idate(dol_now())."',"; - $sql.= " null"; - $sql.= ")"; + $sql .= "name,"; + $sql .= "entity,"; + $sql .= "fk_element,"; + $sql .= "type_element,"; + $sql .= "filtervalue,"; + $sql .= "fk_user_author,"; + $sql .= "datec,"; + $sql .= "fk_user_mod"; + $sql .= ") VALUES ("; + $sql .= " ".(!isset($this->name) ? 'NULL' : "'".$this->db->escape($this->name)."'").","; + $sql .= " ".$conf->entity.","; + $sql .= " ".(!isset($this->fk_element) ? 'NULL' : "'".$this->db->escape($this->fk_element)."'").","; + $sql .= " ".(!isset($this->type_element) ? 'NULL' : "'".$this->db->escape($this->type_element)."'").","; + $sql .= " ".(!isset($this->filtervalue) ? 'NULL' : "'".$this->db->escape($this->filtervalue)."'").","; + $sql .= " ".$user->id.","; + $sql .= " '".$this->db->idate(dol_now())."',"; + $sql .= " null"; + $sql .= ")"; $this->db->begin(); dol_syslog(get_class($this)."::create sql=".$sql, LOG_DEBUG); - $resql=$this->db->query($sql); - if (! $resql) { $error++; $this->errors[]="Error ".$this->db->lasterror(); } + $resql = $this->db->query($sql); + if (!$resql) { $error++; $this->errors[] = "Error ".$this->db->lasterror(); } - if (! $error) + if (!$error) { $this->id = $this->db->last_insert_id(MAIN_DB_PREFIX."advtargetemailing"); - if (! $notrigger) + if (!$notrigger) { // Uncomment this and change MYOBJECT to your own tag if you // want this action calls a trigger. @@ -171,13 +171,13 @@ class AdvanceTargetingMailing extends CommonObject // Commit or rollback if ($error) { - foreach($this->errors as $errmsg) + foreach ($this->errors as $errmsg) { dol_syslog(get_class($this)."::create ".$errmsg, LOG_ERR); - $this->error.=($this->error?', '.$errmsg:$errmsg); + $this->error .= ($this->error ? ', '.$errmsg : $errmsg); } $this->db->rollback(); - return -1*$error; + return -1 * $error; } else { @@ -196,30 +196,30 @@ class AdvanceTargetingMailing extends CommonObject { global $langs; $sql = "SELECT"; - $sql.= " t.rowid,"; + $sql .= " t.rowid,"; - $sql.= " t.name,"; - $sql.= " t.entity,"; - $sql.= " t.fk_element,"; - $sql.= " t.type_element,"; - $sql.= " t.filtervalue,"; - $sql.= " t.fk_user_author,"; - $sql.= " t.datec,"; - $sql.= " t.fk_user_mod,"; - $sql.= " t.tms"; + $sql .= " t.name,"; + $sql .= " t.entity,"; + $sql .= " t.fk_element,"; + $sql .= " t.type_element,"; + $sql .= " t.filtervalue,"; + $sql .= " t.fk_user_author,"; + $sql .= " t.datec,"; + $sql .= " t.fk_user_mod,"; + $sql .= " t.tms"; - $sql.= " FROM ".MAIN_DB_PREFIX."advtargetemailing as t"; - $sql.= " WHERE t.rowid = ".$id; + $sql .= " FROM ".MAIN_DB_PREFIX."advtargetemailing as t"; + $sql .= " WHERE t.rowid = ".$id; dol_syslog(get_class($this)."::fetch sql=".$sql, LOG_DEBUG); - $resql=$this->db->query($sql); + $resql = $this->db->query($sql); if ($resql) { if ($this->db->num_rows($resql)) { $obj = $this->db->fetch_object($resql); - $this->id = $obj->rowid; + $this->id = $obj->rowid; $this->name = $obj->name; $this->entity = $obj->entity; @@ -237,7 +237,7 @@ class AdvanceTargetingMailing extends CommonObject } else { - $this->error="Error ".$this->db->lasterror(); + $this->error = "Error ".$this->db->lasterror(); dol_syslog(get_class($this)."::fetch ".$this->error, LOG_ERR); return -1; } @@ -255,34 +255,34 @@ class AdvanceTargetingMailing extends CommonObject // phpcs:enable global $langs; $sql = "SELECT"; - $sql.= " t.rowid,"; + $sql .= " t.rowid,"; - $sql.= " t.name,"; - $sql.= " t.entity,"; - $sql.= " t.fk_element,"; - $sql.= " t.type_element,"; - $sql.= " t.filtervalue,"; - $sql.= " t.fk_user_author,"; - $sql.= " t.datec,"; - $sql.= " t.fk_user_mod,"; - $sql.= " t.tms"; + $sql .= " t.name,"; + $sql .= " t.entity,"; + $sql .= " t.fk_element,"; + $sql .= " t.type_element,"; + $sql .= " t.filtervalue,"; + $sql .= " t.fk_user_author,"; + $sql .= " t.datec,"; + $sql .= " t.fk_user_mod,"; + $sql .= " t.tms"; - $sql.= " FROM ".MAIN_DB_PREFIX."advtargetemailing as t"; + $sql .= " FROM ".MAIN_DB_PREFIX."advtargetemailing as t"; if (!empty($id)) { - $sql.= " WHERE t.fk_element = ".$id." AND type_element='mailing'"; - }else { - $sql.= " WHERE t.fk_element = ".$this->fk_element." AND type_element='mailing'"; + $sql .= " WHERE t.fk_element = ".$id." AND type_element='mailing'"; + } else { + $sql .= " WHERE t.fk_element = ".$this->fk_element." AND type_element='mailing'"; } dol_syslog(get_class($this)."::fetch sql=".$sql, LOG_DEBUG); - $resql=$this->db->query($sql); + $resql = $this->db->query($sql); if ($resql) { if ($this->db->num_rows($resql)) { $obj = $this->db->fetch_object($resql); - $this->id = $obj->rowid; + $this->id = $obj->rowid; $this->name = $obj->name; $this->entity = $obj->entity; @@ -300,7 +300,7 @@ class AdvanceTargetingMailing extends CommonObject } else { - $this->error="Error ".$this->db->lasterror(); + $this->error = "Error ".$this->db->lasterror(); dol_syslog(get_class($this)."::fetch ".$this->error, LOG_ERR); return -1; } @@ -322,34 +322,34 @@ class AdvanceTargetingMailing extends CommonObject // phpcs:enable global $langs; $sql = "SELECT"; - $sql.= " t.rowid,"; + $sql .= " t.rowid,"; - $sql.= " t.name,"; - $sql.= " t.entity,"; - $sql.= " t.fk_element,"; - $sql.= " t.type_element,"; - $sql.= " t.filtervalue,"; - $sql.= " t.fk_user_author,"; - $sql.= " t.datec,"; - $sql.= " t.fk_user_mod,"; - $sql.= " t.tms"; + $sql .= " t.name,"; + $sql .= " t.entity,"; + $sql .= " t.fk_element,"; + $sql .= " t.type_element,"; + $sql .= " t.filtervalue,"; + $sql .= " t.fk_user_author,"; + $sql .= " t.datec,"; + $sql .= " t.fk_user_mod,"; + $sql .= " t.tms"; - $sql.= " FROM ".MAIN_DB_PREFIX."advtargetemailing as t"; + $sql .= " FROM ".MAIN_DB_PREFIX."advtargetemailing as t"; if (!empty($id)) { - $sql.= " WHERE t.fk_element = ".$id." AND type_element='$type_element'"; - }else { - $sql.= " WHERE t.fk_element = ".$this->fk_element." AND type_element='$type_element'"; + $sql .= " WHERE t.fk_element = ".$id." AND type_element='$type_element'"; + } else { + $sql .= " WHERE t.fk_element = ".$this->fk_element." AND type_element='$type_element'"; } dol_syslog(get_class($this)."::fetch sql=".$sql, LOG_DEBUG); - $resql=$this->db->query($sql); + $resql = $this->db->query($sql); if ($resql) { if ($this->db->num_rows($resql)) { $obj = $this->db->fetch_object($resql); - $this->id = $obj->rowid; + $this->id = $obj->rowid; $this->name = $obj->name; $this->entity = $obj->entity; @@ -367,7 +367,7 @@ class AdvanceTargetingMailing extends CommonObject } else { - $this->error="Error ".$this->db->lasterror(); + $this->error = "Error ".$this->db->lasterror(); dol_syslog(get_class($this)."::fetch ".$this->error, LOG_ERR); return -1; } @@ -383,13 +383,13 @@ class AdvanceTargetingMailing extends CommonObject public function update($user, $notrigger = 0) { global $conf, $langs; - $error=0; + $error = 0; // Clean parameters - if (isset($this->fk_element)) $this->fk_element=(int) $this->fk_element; - if (isset($this->type_element)) $this->type_element=trim($this->type_element); - if (isset($this->name)) $this->name=trim($this->name); - if (isset($this->filtervalue)) $this->filtervalue=trim($this->filtervalue); + if (isset($this->fk_element)) $this->fk_element = (int) $this->fk_element; + if (isset($this->type_element)) $this->type_element = trim($this->type_element); + if (isset($this->name)) $this->name = trim($this->name); + if (isset($this->filtervalue)) $this->filtervalue = trim($this->filtervalue); // Check parameters // Put here code to add a control on parameters values @@ -397,21 +397,21 @@ class AdvanceTargetingMailing extends CommonObject // Update request $sql = "UPDATE ".MAIN_DB_PREFIX."advtargetemailing SET"; - $sql.= " name=".(isset($this->name)?"'".$this->db->escape($this->name)."'":"''").","; - $sql.= " entity=".$conf->entity.","; - $sql.= " fk_element=".(isset($this->fk_element)?$this->fk_element:"null").","; - $sql.= " type_element=".(isset($this->type_element)?"'".$this->db->escape($this->type_element)."'":"null").","; - $sql.= " filtervalue=".(isset($this->filtervalue)?"'".$this->db->escape($this->filtervalue)."'":"null").","; - $sql.= " fk_user_mod=".$user->id; + $sql .= " name=".(isset($this->name) ? "'".$this->db->escape($this->name)."'" : "''").","; + $sql .= " entity=".$conf->entity.","; + $sql .= " fk_element=".(isset($this->fk_element) ? $this->fk_element : "null").","; + $sql .= " type_element=".(isset($this->type_element) ? "'".$this->db->escape($this->type_element)."'" : "null").","; + $sql .= " filtervalue=".(isset($this->filtervalue) ? "'".$this->db->escape($this->filtervalue)."'" : "null").","; + $sql .= " fk_user_mod=".$user->id; - $sql.= " WHERE rowid=".$this->id; + $sql .= " WHERE rowid=".$this->id; $this->db->begin(); dol_syslog(get_class($this)."::update sql=".$sql, LOG_DEBUG); $resql = $this->db->query($sql); - if (! $resql) { + if (!$resql) { $error++; - $this->errors[]="Error ".$this->db->lasterror(); + $this->errors[] = "Error ".$this->db->lasterror(); } //if (! $error) @@ -433,13 +433,13 @@ class AdvanceTargetingMailing extends CommonObject // Commit or rollback if ($error) { - foreach($this->errors as $errmsg) + foreach ($this->errors as $errmsg) { dol_syslog(get_class($this)."::update ".$errmsg, LOG_ERR); - $this->error.=($this->error?', '.$errmsg:$errmsg); + $this->error .= ($this->error ? ', '.$errmsg : $errmsg); } $this->db->rollback(); - return -1*$error; + return -1 * $error; } else { @@ -458,13 +458,13 @@ class AdvanceTargetingMailing extends CommonObject public function delete($user, $notrigger = 0) { global $conf, $langs; - $error=0; + $error = 0; $this->db->begin(); - if (! $error) + if (!$error) { - if (! $notrigger) + if (!$notrigger) { // Uncomment this and change MYOBJECT to your own tag if you // want this action calls a trigger. @@ -478,26 +478,26 @@ class AdvanceTargetingMailing extends CommonObject } } - if (! $error) + if (!$error) { $sql = "DELETE FROM ".MAIN_DB_PREFIX."advtargetemailing"; - $sql.= " WHERE rowid=".$this->id; + $sql .= " WHERE rowid=".$this->id; dol_syslog(get_class($this)."::delete sql=".$sql); $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) + foreach ($this->errors as $errmsg) { dol_syslog(get_class($this)."::delete ".$errmsg, LOG_ERR); - $this->error.=($this->error?', '.$errmsg:$errmsg); + $this->error .= ($this->error ? ', '.$errmsg : $errmsg); } $this->db->rollback(); - return -1*$error; + return -1 * $error; } else { @@ -516,17 +516,17 @@ class AdvanceTargetingMailing extends CommonObject */ public function savequery($user, $arrayquery) { - global $langs,$conf; + global $langs, $conf; if (!empty($arrayquery)) { - $result=$this->fetch_by_mailing($this->fk_element); - $this->filtervalue=json_encode($arrayquery); - if ($result<0) { + $result = $this->fetch_by_mailing($this->fk_element); + $this->filtervalue = json_encode($arrayquery); + if ($result < 0) { return -1; } if (!empty($this->id)) { $this->update($user); - }else { + } else { $this->create($user); } } @@ -662,7 +662,7 @@ class AdvanceTargetingMailing extends CommonObject if ($num) { - while( $i < $num) + while ($i < $num) { $obj = $this->db->fetch_object($resql); @@ -675,8 +675,8 @@ class AdvanceTargetingMailing extends CommonObject return $num; } else { - $this->error = "Error " . $this->db->lasterror(); - dol_syslog(get_class($this) . "::query_thirdparty " . $this->error, LOG_ERR); + $this->error = "Error ".$this->db->lasterror(); + dol_syslog(get_class($this)."::query_thirdparty ".$this->error, LOG_ERR); return -1; } } @@ -905,7 +905,7 @@ class AdvanceTargetingMailing extends CommonObject if ($num) { - while( $i < $num) + while ($i < $num) { $obj = $this->db->fetch_object($resql); @@ -918,8 +918,8 @@ class AdvanceTargetingMailing extends CommonObject return $num; } else { - $this->error = "Error " . $this->db->lasterror(); - dol_syslog(get_class($this) . "::query_contact " . $this->error, LOG_ERR); + $this->error = "Error ".$this->db->lasterror(); + dol_syslog(get_class($this)."::query_contact ".$this->error, LOG_ERR); return -1; } } @@ -940,26 +940,26 @@ class AdvanceTargetingMailing extends CommonObject //This is a multiple value test if (preg_match('/;/', $criteria)) { - $return_sql_not_like=array(); - $return_sql_like=array(); + $return_sql_not_like = array(); + $return_sql_like = array(); - $criteria_array=explode(';', $criteria); - foreach($criteria_array as $inter_criteria) { + $criteria_array = explode(';', $criteria); + foreach ($criteria_array as $inter_criteria) { if (preg_match('/!/', $inter_criteria)) { - $return_sql_not_like[]= '('.$column_to_test.' NOT LIKE \''.str_replace('!', '', $inter_criteria).'\')'; + $return_sql_not_like[] = '('.$column_to_test.' NOT LIKE \''.str_replace('!', '', $inter_criteria).'\')'; } else { - $return_sql_like[]= '('.$column_to_test.' LIKE \''.$inter_criteria.'\')'; + $return_sql_like[] = '('.$column_to_test.' LIKE \''.$inter_criteria.'\')'; } } - if (count($return_sql_like)>0) { - $return_sql_criteria .= '(' . implode(' OR ', $return_sql_like) .')'; + if (count($return_sql_like) > 0) { + $return_sql_criteria .= '('.implode(' OR ', $return_sql_like).')'; } - if (count($return_sql_not_like)>0) { - $return_sql_criteria .= ' AND (' . implode(' AND ', $return_sql_not_like).')'; + if (count($return_sql_not_like) > 0) { + $return_sql_criteria .= ' AND ('.implode(' AND ', $return_sql_not_like).')'; } } else { - $return_sql_criteria .= $column_to_test . ' LIKE \''.$this->db->escape($criteria).'\''; + $return_sql_criteria .= $column_to_test.' LIKE \''.$this->db->escape($criteria).'\''; } $return_sql_criteria .= ')'; diff --git a/htdocs/comm/mailing/class/html.formadvtargetemailing.class.php b/htdocs/comm/mailing/class/html.formadvtargetemailing.class.php index 67ec7414e7c..9c589c4ae3d 100644 --- a/htdocs/comm/mailing/class/html.formadvtargetemailing.class.php +++ b/htdocs/comm/mailing/class/html.formadvtargetemailing.class.php @@ -35,7 +35,7 @@ class FormAdvTargetEmailing extends Form /** * @var string Error code (or message) */ - public $error=''; + public $error = ''; /** * Constructor @@ -62,15 +62,15 @@ class FormAdvTargetEmailing extends Form $options_array = array(); $sql = "SELECT code, label"; - $sql .= " FROM " . MAIN_DB_PREFIX . "c_prospectlevel"; + $sql .= " FROM ".MAIN_DB_PREFIX."c_prospectlevel"; $sql .= " WHERE active > 0"; $sql .= " ORDER BY sortorder"; - dol_syslog(get_class($this) . '::multiselectProspectionStatus sql=' . $sql, LOG_DEBUG); + dol_syslog(get_class($this).'::multiselectProspectionStatus sql='.$sql, LOG_DEBUG); $resql = $this->db->query($sql); if ($resql) { $num = $this->db->num_rows($resql); $i = 0; - while ( $i < $num ) { + while ($i < $num) { $obj = $this->db->fetch_object($resql); $level = $langs->trans($obj->code); @@ -78,7 +78,7 @@ class FormAdvTargetEmailing extends Form $level = $langs->trans($obj->label); $options_array[$obj->code] = $level; - $i ++; + $i++; } } else { dol_print_error($this->db); @@ -102,16 +102,16 @@ class FormAdvTargetEmailing extends Form $out = ''; $countryArray = array(); - $label = array (); + $label = array(); $options_array = array(); $sql = "SELECT rowid, code as code_iso, label"; - $sql .= " FROM " . MAIN_DB_PREFIX . "c_country"; + $sql .= " FROM ".MAIN_DB_PREFIX."c_country"; $sql .= " WHERE active = 1 AND code<>''"; $sql .= " ORDER BY code ASC"; - dol_syslog(get_class($this) . "::select_country sql=" . $sql); + dol_syslog(get_class($this)."::select_country sql=".$sql); $resql = $this->db->query($sql); if ($resql) { $num = $this->db->num_rows($resql); @@ -123,9 +123,9 @@ class FormAdvTargetEmailing extends Form $obj = $this->db->fetch_object($resql); $countryArray [$i] ['rowid'] = $obj->rowid; $countryArray [$i] ['code_iso'] = $obj->code_iso; - $countryArray [$i] ['label'] = ($obj->code_iso && $langs->transnoentitiesnoconv("Country" . $obj->code_iso) != "Country" . $obj->code_iso ? $langs->transnoentitiesnoconv("Country" . $obj->code_iso) : ($obj->label != '-' ? $obj->label : '')); + $countryArray [$i] ['label'] = ($obj->code_iso && $langs->transnoentitiesnoconv("Country".$obj->code_iso) != "Country".$obj->code_iso ? $langs->transnoentitiesnoconv("Country".$obj->code_iso) : ($obj->label != '-' ? $obj->label : '')); $label[$i] = $countryArray[$i]['label']; - $i ++; + $i++; } array_multisort($label, SORT_ASC, $countryArray); @@ -133,7 +133,7 @@ class FormAdvTargetEmailing extends Form foreach ($countryArray as $row) { $label = dol_trunc($row['label'], $maxlength, 'middle'); if ($row['code_iso']) - $label .= ' (' . $row['code_iso'] . ')'; + $label .= ' ('.$row['code_iso'].')'; $options_array[$row['rowid']] = $label; } @@ -158,23 +158,23 @@ class FormAdvTargetEmailing extends Form global $conf; - $options_array = array (); + $options_array = array(); - $sql_usr = ''; + $sql_usr = ''; $sql_usr .= "SELECT DISTINCT u2.rowid, u2.lastname as name, u2.firstname, u2.login"; - $sql_usr .= " FROM " . MAIN_DB_PREFIX . "user as u2, " . MAIN_DB_PREFIX . "societe_commerciaux as sc"; - $sql_usr .= " WHERE u2.entity IN (0," . $conf->entity . ")"; + $sql_usr .= " FROM ".MAIN_DB_PREFIX."user as u2, ".MAIN_DB_PREFIX."societe_commerciaux as sc"; + $sql_usr .= " WHERE u2.entity IN (0,".$conf->entity.")"; $sql_usr .= " AND u2.rowid = sc.fk_user "; - if (! empty($conf->global->USER_HIDE_INACTIVE_IN_COMBOBOX)) + if (!empty($conf->global->USER_HIDE_INACTIVE_IN_COMBOBOX)) $sql_usr .= " AND u2.statut<>0 "; $sql_usr .= " ORDER BY name ASC"; // print $sql_usr;exit; $resql_usr = $this->db->query($sql_usr); if ($resql_usr) { - while ( $obj_usr = $this->db->fetch_object($resql_usr) ) { - $label = $obj_usr->firstname . " " . $obj_usr->name . " (" . $obj_usr->login . ')'; + while ($obj_usr = $this->db->fetch_object($resql_usr)) { + $label = $obj_usr->firstname." ".$obj_usr->name." (".$obj_usr->login.')'; $options_array [$obj_usr->rowid] = $label; } @@ -196,11 +196,11 @@ class FormAdvTargetEmailing extends Form public function multiselectselectLanguage($htmlname = '', $selected_array = array()) { - global $conf,$langs; + global $conf, $langs; - $options_array = array (); + $options_array = array(); - $langs_available=$langs->get_available_languages(DOL_DOCUMENT_ROOT, 12); + $langs_available = $langs->get_available_languages(DOL_DOCUMENT_ROOT, 12); foreach ($langs_available as $key => $value) { @@ -222,7 +222,7 @@ class FormAdvTargetEmailing extends Form */ public function advMultiselectarraySelllist($htmlname, $sqlqueryparam = array(), $selected_array = array()) { - $options_array=array(); + $options_array = array(); if (is_array($sqlqueryparam)) { @@ -238,39 +238,39 @@ class FormAdvTargetEmailing extends Form if (count($InfoFieldList) >= 3) { if (strpos($InfoFieldList [3], 'extra.') !== false) { - $keyList = 'main.' . $InfoFieldList [2] . ' as rowid'; + $keyList = 'main.'.$InfoFieldList [2].' as rowid'; } else { - $keyList = $InfoFieldList [2] . ' as rowid'; + $keyList = $InfoFieldList [2].' as rowid'; } } - $sql = 'SELECT ' . $keyList . ', ' . $InfoFieldList [1]; - $sql .= ' FROM ' . MAIN_DB_PREFIX . $InfoFieldList [0]; - if (! empty($InfoFieldList [3])) { + $sql = 'SELECT '.$keyList.', '.$InfoFieldList [1]; + $sql .= ' FROM '.MAIN_DB_PREFIX.$InfoFieldList [0]; + if (!empty($InfoFieldList [3])) { // We have to join on extrafield table if (strpos($InfoFieldList [3], 'extra') !== false) { - $sql .= ' as main, ' . MAIN_DB_PREFIX . $InfoFieldList [0] . '_extrafields as extra'; - $sql .= ' WHERE extra.fk_object=main.' . $InfoFieldList [2] . ' AND ' . $InfoFieldList [3]; + $sql .= ' as main, '.MAIN_DB_PREFIX.$InfoFieldList [0].'_extrafields as extra'; + $sql .= ' WHERE extra.fk_object=main.'.$InfoFieldList [2].' AND '.$InfoFieldList [3]; } else { - $sql .= ' WHERE ' . $InfoFieldList [3]; + $sql .= ' WHERE '.$InfoFieldList [3]; } } - if (! empty($InfoFieldList[1])) { + if (!empty($InfoFieldList[1])) { $sql .= " ORDER BY nom"; } // $sql.= ' WHERE entity = '.$conf->entity; - dol_syslog(get_class($this) . "::".__METHOD__, LOG_DEBUG); + dol_syslog(get_class($this)."::".__METHOD__, LOG_DEBUG); $resql = $this->db->query($sql); if ($resql) { $num = $this->db->num_rows($resql); $i = 0; if ($num) { - while ( $i < $num ) { + while ($i < $num) { $obj = $this->db->fetch_object($resql); $labeltoshow = dol_trunc($obj->$InfoFieldList [1], 90); - $options_array[$obj->rowid]=$labeltoshow; - $i ++; + $options_array[$obj->rowid] = $labeltoshow; + $i++; } } $this->db->free($resql); @@ -289,17 +289,17 @@ class FormAdvTargetEmailing extends Form */ public function multiselectCivility($htmlname = 'civilite_id', $selected_array = array()) { - global $conf,$langs,$user; + global $conf, $langs, $user; $langs->load("dict"); - $options_array=array(); + $options_array = array(); $sql = "SELECT rowid, code, label as civilite, active FROM ".MAIN_DB_PREFIX."c_civility"; - $sql.= " WHERE active = 1"; + $sql .= " WHERE active = 1"; dol_syslog(get_class($this)."::".__METHOD__, LOG_DEBUG); - $resql=$this->db->query($sql); + $resql = $this->db->query($sql); if ($resql) { $num = $this->db->num_rows($resql); @@ -310,10 +310,10 @@ class FormAdvTargetEmailing extends Form { $obj = $this->db->fetch_object($resql); // Si traduction existe, on l'utilise, sinon on prend le libelle par defaut - $label= ($langs->trans("Civility".$obj->code)!="Civility".$obj->code ? $langs->trans("Civility".$obj->code) : ($obj->civilite!='-'?$obj->civilite:'')); + $label = ($langs->trans("Civility".$obj->code) != "Civility".$obj->code ? $langs->trans("Civility".$obj->code) : ($obj->civilite != '-' ? $obj->civilite : '')); - $options_array[$obj->code]=$label; + $options_array[$obj->code] = $label; $i++; } @@ -340,7 +340,7 @@ class FormAdvTargetEmailing extends Form { global $conf, $langs; - $form=new Form($this->db); + $form = new Form($this->db); $return = $form->multiselectarray($htmlname, $options_array, $selected_array, 0, 0, '', 0, 295); return $return; } @@ -379,16 +379,16 @@ class FormAdvTargetEmailing extends Form */ public function multiselectCategories($htmlname = '', $selected_array = array(), $type = 0) { - global $conf,$langs,$user; + global $conf, $langs, $user; $langs->load("dict"); - $options_array=array(); + $options_array = array(); $sql = "SELECT rowid, label FROM ".MAIN_DB_PREFIX."categorie"; - $sql.= " WHERE type=".$type; + $sql .= " WHERE type=".$type; dol_syslog(get_class($this)."::".__METHOD__, LOG_DEBUG); - $resql=$this->db->query($sql); + $resql = $this->db->query($sql); if ($resql) { $num = $this->db->num_rows($resql); @@ -399,7 +399,7 @@ class FormAdvTargetEmailing extends Form { $obj = $this->db->fetch_object($resql); - $options_array[$obj->rowid]=$obj->label; + $options_array[$obj->rowid] = $obj->label; $i++; } @@ -429,32 +429,32 @@ class FormAdvTargetEmailing extends Form $out = ''; $sql = "SELECT c.rowid, c.name, c.fk_element"; - $sql .= " FROM " . MAIN_DB_PREFIX . "advtargetemailing as c"; + $sql .= " FROM ".MAIN_DB_PREFIX."advtargetemailing as c"; $sql .= " WHERE type_element='$type_element'"; $sql .= " ORDER BY c.name"; - dol_syslog(get_class($this) . "::".__METHOD__, LOG_DEBUG); + dol_syslog(get_class($this)."::".__METHOD__, LOG_DEBUG); $resql = $this->db->query($sql); if ($resql) { - $out .= ''; if ($showempty) $out .= ''; $num = $this->db->num_rows($resql); $i = 0; if ($num) { - while ( $i < $num ) { + while ($i < $num) { $obj = $this->db->fetch_object($resql); $label = $obj->name; if (empty($label)) { - $label=$obj->fk_element; + $label = $obj->fk_element; } if ($selected > 0 && $selected == $obj->rowid) { - $out .= ''; + $out .= ''; } else { - $out .= ''; + $out .= ''; } - $i ++; + $i++; } } $out .= ''; diff --git a/htdocs/comm/mailing/index.php b/htdocs/comm/mailing/index.php index 701dd2d4716..1dc7a430575 100644 --- a/htdocs/comm/mailing/index.php +++ b/htdocs/comm/mailing/index.php @@ -25,7 +25,7 @@ */ require '../../main.inc.php'; -require_once DOL_DOCUMENT_ROOT .'/comm/mailing/class/mailing.class.php'; +require_once DOL_DOCUMENT_ROOT.'/comm/mailing/class/mailing.class.php'; require_once DOL_DOCUMENT_ROOT.'/core/lib/functions2.lib.php'; $hookmanager = new HookManager($db); @@ -38,14 +38,14 @@ $langs->loadLangs(array('commercial', 'orders')); // Security check -$result=restrictedArea($user, 'mailing'); +$result = restrictedArea($user, 'mailing'); /* * View */ -$help_url='EN:Module_EMailing|FR:Module_Mailing|ES:Módulo_Mailing'; +$help_url = 'EN:Module_EMailing|FR:Module_Mailing|ES:Módulo_Mailing'; llxHeader('', 'EMailing', $help_url); print load_fiche_titre($langs->trans("MailingArea")); @@ -61,7 +61,7 @@ print '
'; print ''; print ''; print '
'; - print ''; + print '
'; print ''; print ''; @@ -74,21 +74,21 @@ print '
'; // Affiche stats de tous les modules de destinataires mailings -print '
'.$langs->trans("SearchAMailing").'
'; print $langs->trans("Ref").':
'; +print '
'; print ''; -$dir=DOL_DOCUMENT_ROOT."/core/modules/mailings"; -$handle=opendir($dir); +$dir = DOL_DOCUMENT_ROOT."/core/modules/mailings"; +$handle = opendir($dir); if (is_resource($handle)) { - while (($file = readdir($handle))!==false) + while (($file = readdir($handle)) !== false) { if (substr($file, 0, 1) <> '.' && substr($file, 0, 3) <> 'CVS') { if (preg_match("/(.*)\.(.*)\.(.*)/i", $file, $reg)) { - $modulename=$reg[1]; + $modulename = $reg[1]; if ($modulename == 'example') continue; // Loading Class @@ -97,12 +97,12 @@ if (is_resource($handle)) require_once $file; $mailmodule = new $classname($db); - $qualified=1; + $qualified = 1; foreach ($mailmodule->require_module as $key) { - if (! $conf->$key->enabled || (! $user->admin && $mailmodule->require_admin)) + if (!$conf->$key->enabled || (!$user->admin && $mailmodule->require_admin)) { - $qualified=0; + $qualified = 0; //print "Les pr�requis d'activation du module mailing ne sont pas respect�s. Il ne sera pas actif"; break; } @@ -115,13 +115,13 @@ if (is_resource($handle)) { print ''; - $result=$db->query($sql); + $result = $db->query($sql); if ($result) { $num = $db->num_rows($result); $i = 0; - while ($i < $num ) + while ($i < $num) { $obj = $db->fetch_object($result); print ''; if ($action != 'editecheance' && $object->statut == Propal::STATUS_DRAFT && $usercancreate) - print ''; + print ''; print '
'.$langs->trans("TargetsStatistics").'
'.img_object('', $mailmodule->picto).' '.$obj->label.''.$obj->nb.''; @@ -154,15 +154,15 @@ print '
'; /* * List of last emailings */ -$limit=10; +$limit = 10; $sql = "SELECT m.rowid, m.titre, m.nbemail, m.statut, m.date_creat"; -$sql.= " FROM ".MAIN_DB_PREFIX."mailing as m"; -$sql.= " ORDER BY m.date_creat DESC"; -$sql.= " LIMIT ".$limit; -$result=$db->query($sql); +$sql .= " FROM ".MAIN_DB_PREFIX."mailing as m"; +$sql .= " ORDER BY m.date_creat DESC"; +$sql .= " LIMIT ".$limit; +$result = $db->query($sql); if ($result) { print '
'; - print ''; + print '
'; print ''; print ''; print ''; @@ -174,10 +174,10 @@ if ($result) { { $i = 0; - while ($i < $num ) + while ($i < $num) { $obj = $db->fetch_object($result); - $mailstatic=new Mailing($db); + $mailstatic = new Mailing($db); $mailstatic->id = $obj->rowid; $mailstatic->ref = $obj->rowid; @@ -185,7 +185,7 @@ if ($result) { print ''; print ''; print ''; - print ''; + print ''; print ''; print ''; $i++; diff --git a/htdocs/comm/mailing/list.php b/htdocs/comm/mailing/list.php index 0e3d7a7725e..b38a796d3c7 100644 --- a/htdocs/comm/mailing/list.php +++ b/htdocs/comm/mailing/list.php @@ -29,22 +29,22 @@ require_once DOL_DOCUMENT_ROOT.'/comm/mailing/class/mailing.class.php'; $langs->load("mails"); // Security check -$result=restrictedArea($user, 'mailing'); +$result = restrictedArea($user, 'mailing'); $sortfield = GETPOST("sortfield", 'alpha'); $sortorder = GETPOST("sortorder", 'alpha'); -$limit = GETPOST('limit', 'int')?GETPOST('limit', 'int'):$conf->liste_limit; +$limit = GETPOST('limit', 'int') ?GETPOST('limit', 'int') : $conf->liste_limit; $page = 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 $offset = $limit * $page; $pageprev = $page - 1; $pagenext = $page + 1; -if (! $sortorder) $sortorder="DESC"; -if (! $sortfield) $sortfield="m.date_creat"; +if (!$sortorder) $sortorder = "DESC"; +if (!$sortfield) $sortfield = "m.date_creat"; -$search_all=trim((GETPOST('search_all', 'alphanohtml')!='')?GETPOST('search_all', 'alphanohtml'):GETPOST('sall', 'alphanohtml')); -$search_ref=GETPOST("search_ref", "alpha") ? GETPOST("search_ref", "alpha") : GETPOST("sref", "alpha"); -$filteremail=GETPOST('filteremail', 'alpha'); +$search_all = trim((GETPOST('search_all', 'alphanohtml') != '') ?GETPOST('search_all', 'alphanohtml') : GETPOST('sall', 'alphanohtml')); +$search_ref = GETPOST("search_ref", "alpha") ? GETPOST("search_ref", "alpha") : GETPOST("sref", "alpha"); +$filteremail = GETPOST('filteremail', 'alpha'); $object = new Mailing($db); @@ -55,7 +55,7 @@ $extrafields = new ExtraFields($db); // fetch optionals attributes and labels $extrafields->fetch_name_optionals_label($object->table_element); -$search_array_options=$extrafields->getOptionalsFromPost($object->table_element, '', 'search_'); +$search_array_options = $extrafields->getOptionalsFromPost($object->table_element, '', 'search_'); // List of fields to search into when doing a "search in all" $fieldstosearchall = array( @@ -69,11 +69,11 @@ $fieldstosearchall = array( * 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 +$parameters = array(); +$reshook = $hookmanager->executeHooks('doActions', $parameters, $object, $action); // Note that $action and $object may have been modified by some hooks if ($reshook < 0) setEventMessages($hookmanager->error, $hookmanager->errors, 'errors'); if (empty($reshook)) @@ -82,7 +82,7 @@ if (empty($reshook)) 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 { /*foreach($object->fields as $key => $val) { @@ -90,13 +90,13 @@ if (empty($reshook)) }*/ $search_ref = ''; $search_all = ''; - $toselect=''; - $search_array_options=array(); + $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')) { - $massaction=''; // Protection to avoid mass action if we force a new search during a mass action confirmation + $massaction = ''; // Protection to avoid mass action if we force a new search during a mass action confirmation } // Mass actions @@ -121,28 +121,28 @@ $form = new Form($db); if ($filteremail) { $sql = "SELECT m.rowid, m.titre, m.nbemail, m.statut, m.date_creat as datec, m.date_envoi as date_envoi,"; - $sql.= " mc.statut as sendstatut"; - $sql.= " FROM ".MAIN_DB_PREFIX."mailing as m, ".MAIN_DB_PREFIX."mailing_cibles as mc"; - $sql.= " WHERE m.rowid = mc.fk_mailing AND m.entity = ".$conf->entity; - $sql.= " AND mc.email = '".$db->escape($filteremail)."'"; - if ($search_ref) $sql.= " AND m.rowid = '".$db->escape($search_ref)."'"; - if ($search_all) $sql.= " AND (m.titre like '%".$db->escape($search_all)."%' OR m.sujet like '%".$db->escape($search_all)."%' OR m.body like '%".$db->escape($search_all)."%')"; - if (! $sortorder) $sortorder="ASC"; - if (! $sortfield) $sortfield="m.rowid"; - $sql.= $db->order($sortfield, $sortorder); - $sql.= $db->plimit($conf->liste_limit +1, $offset); + $sql .= " mc.statut as sendstatut"; + $sql .= " FROM ".MAIN_DB_PREFIX."mailing as m, ".MAIN_DB_PREFIX."mailing_cibles as mc"; + $sql .= " WHERE m.rowid = mc.fk_mailing AND m.entity = ".$conf->entity; + $sql .= " AND mc.email = '".$db->escape($filteremail)."'"; + if ($search_ref) $sql .= " AND m.rowid = '".$db->escape($search_ref)."'"; + if ($search_all) $sql .= " AND (m.titre like '%".$db->escape($search_all)."%' OR m.sujet like '%".$db->escape($search_all)."%' OR m.body like '%".$db->escape($search_all)."%')"; + if (!$sortorder) $sortorder = "ASC"; + if (!$sortfield) $sortfield = "m.rowid"; + $sql .= $db->order($sortfield, $sortorder); + $sql .= $db->plimit($conf->liste_limit + 1, $offset); } else { $sql = "SELECT m.rowid, m.titre, m.nbemail, m.statut, m.date_creat as datec, m.date_envoi as date_envoi"; - $sql.= " FROM ".MAIN_DB_PREFIX."mailing as m"; - $sql.= " WHERE m.entity = ".$conf->entity; - if ($search_ref) $sql.= " AND m.rowid = '".$db->escape($search_ref)."'"; - if ($search_all) $sql.= " AND (m.titre like '%".$db->escape($search_all)."%' OR m.sujet like '%".$db->escape($search_all)."%' OR m.body like '%".$db->escape($search_all)."%')"; - if (! $sortorder) $sortorder="ASC"; - if (! $sortfield) $sortfield="m.rowid"; - $sql.= $db->order($sortfield, $sortorder); - $sql.= $db->plimit($conf->liste_limit +1, $offset); + $sql .= " FROM ".MAIN_DB_PREFIX."mailing as m"; + $sql .= " WHERE m.entity = ".$conf->entity; + if ($search_ref) $sql .= " AND m.rowid = '".$db->escape($search_ref)."'"; + if ($search_all) $sql .= " AND (m.titre like '%".$db->escape($search_all)."%' OR m.sujet like '%".$db->escape($search_all)."%' OR m.body like '%".$db->escape($search_all)."%')"; + if (!$sortorder) $sortorder = "ASC"; + if (!$sortfield) $sortfield = "m.rowid"; + $sql .= $db->order($sortfield, $sortorder); + $sql .= $db->plimit($conf->liste_limit + 1, $offset); } //print $sql; @@ -151,19 +151,19 @@ if ($result) { $num = $db->num_rows($result); - $title=$langs->trans("ListOfEMailings"); - if ($filteremail) $title.=' ('.$langs->trans("SentTo", $filteremail).')'; + $title = $langs->trans("ListOfEMailings"); + if ($filteremail) $title .= ' ('.$langs->trans("SentTo", $filteremail).')'; - $newcardbutton=''; + $newcardbutton = ''; if ($user->rights->mailing->creer) { - $newcardbutton.= dolGetButtonTitle($langs->trans('NewMailing'), '', 'fa fa-plus-circle', DOL_URL_ROOT.'/comm/mailing/card.php?action=create'); + $newcardbutton .= dolGetButtonTitle($langs->trans('NewMailing'), '', 'fa fa-plus-circle', DOL_URL_ROOT.'/comm/mailing/card.php?action=create'); } $i = 0; $param = "&search_all=".urlencode($search_all); - if ($filteremail) $param.='&filteremail='.urlencode($filteremail); + if ($filteremail) $param .= '&filteremail='.urlencode($filteremail); print ''; if ($optioncss != '') print ''; @@ -178,7 +178,7 @@ if ($result) $moreforfilter = ''; print '
'; - print '
'.$langs->trans("LastMailings", $limit).''.$langs->trans("DateCreation").''.$mailstatic->getNomUrl(1).''.dol_trunc($obj->titre, 38).''.dol_print_date($db->jdate($obj->date_creat), 'day').''.($obj->nbemail?$obj->nbemail:"0").''.($obj->nbemail ? $obj->nbemail : "0").''.$mailstatic->LibStatut($obj->statut, 5).'
'."\n"; + print '
'."\n"; print ''; print ''; print ''; - if (! $filteremail) print ''; + if (!$filteremail) print ''; print ''; print ''; print ''; print "\n"; @@ -202,15 +202,15 @@ if ($result) print_liste_field_titre("Ref", $_SERVER["PHP_SELF"], "m.rowid", $param, "", "", $sortfield, $sortorder); print_liste_field_titre("Title", $_SERVER["PHP_SELF"], "m.titre", $param, "", "", $sortfield, $sortorder); print_liste_field_titre("DateCreation", $_SERVER["PHP_SELF"], "m.date_creat", $param, "", 'align="center"', $sortfield, $sortorder); - if (! $filteremail) print_liste_field_titre("NbOfEMails", $_SERVER["PHP_SELF"], "m.nbemail", $param, "", 'align="center"', $sortfield, $sortorder); - if (! $filteremail) print_liste_field_titre("DateLastSend", $_SERVER["PHP_SELF"], "m.date_envoi", $param, "", 'align="center"', $sortfield, $sortorder); + if (!$filteremail) print_liste_field_titre("NbOfEMails", $_SERVER["PHP_SELF"], "m.nbemail", $param, "", 'align="center"', $sortfield, $sortorder); + if (!$filteremail) print_liste_field_titre("DateLastSend", $_SERVER["PHP_SELF"], "m.date_envoi", $param, "", 'align="center"', $sortfield, $sortorder); else print_liste_field_titre("DateSending", $_SERVER["PHP_SELF"], "mc.date_envoi", $param, "", 'align="center"', $sortfield, $sortorder); - print_liste_field_titre("Status", $_SERVER["PHP_SELF"], ($filteremail?"mc.statut":"m.statut"), $param, "", 'class="right"', $sortfield, $sortorder); + print_liste_field_titre("Status", $_SERVER["PHP_SELF"], ($filteremail ? "mc.statut" : "m.statut"), $param, "", 'class="right"', $sortfield, $sortorder); print_liste_field_titre('', $_SERVER["PHP_SELF"], "", '', '', 'class="right"', $sortfield, $sortorder, 'maxwidthsearch '); print "\n"; - $email=new Mailing($db); + $email = new Mailing($db); while ($i < min($num, $limit)) { @@ -233,7 +233,7 @@ if ($result) print ''; // Nb of email - if (! $filteremail) + if (!$filteremail) { print '
'; @@ -189,11 +189,11 @@ if ($result) print ''; print '     '; - $searchpicto=$form->showFilterAndCheckAddButtons(0); + $searchpicto = $form->showFilterAndCheckAddButtons(0); print $searchpicto; print '
'; $nbemail = $obj->nbemail; diff --git a/htdocs/comm/multiprix.php b/htdocs/comm/multiprix.php index c99048a8955..32fe301489e 100644 --- a/htdocs/comm/multiprix.php +++ b/htdocs/comm/multiprix.php @@ -60,13 +60,13 @@ if ($_POST["action"] == 'setpricelevel') llxHeader(); -$userstatic=new User($db); +$userstatic = new User($db); if ($_socid > 0) { // On recupere les donnees societes par l'objet $objsoc = new Societe($db); - $objsoc->id=$_socid; + $objsoc->id = $_socid; $objsoc->fetch($_socid, $to); if ($errmesg) @@ -81,9 +81,9 @@ if ($_socid > 0) $head = societe_prepare_head($objsoc); - $tabchoice=''; - if ($objsoc->client == 1) $tabchoice='customer'; - if ($objsoc->client == 2) $tabchoice='prospect'; + $tabchoice = ''; + if ($objsoc->client == 1) $tabchoice = 'customer'; + if ($objsoc->client == 2) $tabchoice = 'prospect'; print ''; print ''; @@ -99,14 +99,14 @@ if ($_socid > 0) print '
'; print $langs->trans("NewValue").''; print ''; @@ -129,32 +129,32 @@ if ($_socid > 0) */ $sql = "SELECT rc.rowid,rc.price_level, rc.datec as dc, u.rowid as uid, u.login"; $sql .= " FROM ".MAIN_DB_PREFIX."societe_prices as rc, ".MAIN_DB_PREFIX."user as u"; - $sql .= " WHERE rc.fk_soc =". $objsoc->id; + $sql .= " WHERE rc.fk_soc =".$objsoc->id; $sql .= " AND u.rowid = rc.fk_user_author"; $sql .= " ORDER BY rc.datec DESC"; - $resql=$db->query($sql); + $resql = $db->query($sql); if ($resql) { - print ''; + print '
'; $tag = !$tag; print ''; print ''; print ''; print ''; print ''; - $i = 0 ; + $i = 0; $num = $db->num_rows($resql); - while ($i < $num ) + while ($i < $num) { $obj = $db->fetch_object($resql); print ''; print ''; print ''; - $userstatic->id=$obj->uid; - $userstatic->lastname=$obj->login; + $userstatic->id = $obj->uid; + $userstatic->lastname = $obj->login; print ''; print ''; $i++; diff --git a/htdocs/comm/propal/card.php b/htdocs/comm/propal/card.php index 85a3b059164..b3d8360e39a 100644 --- a/htdocs/comm/propal/card.php +++ b/htdocs/comm/propal/card.php @@ -36,21 +36,21 @@ */ require '../../main.inc.php'; -require_once DOL_DOCUMENT_ROOT . '/core/class/html.formother.class.php'; -require_once DOL_DOCUMENT_ROOT . '/core/class/html.formfile.class.php'; -require_once DOL_DOCUMENT_ROOT . '/core/class/html.formpropal.class.php'; -require_once DOL_DOCUMENT_ROOT . '/core/class/html.formmargin.class.php'; -require_once DOL_DOCUMENT_ROOT . '/comm/propal/class/propal.class.php'; -require_once DOL_DOCUMENT_ROOT . '/comm/action/class/actioncomm.class.php'; -require_once DOL_DOCUMENT_ROOT . '/core/modules/propale/modules_propale.php'; -require_once DOL_DOCUMENT_ROOT . '/core/lib/propal.lib.php'; -require_once DOL_DOCUMENT_ROOT . '/core/lib/functions2.lib.php'; -require_once DOL_DOCUMENT_ROOT . '/core/lib/signature.lib.php'; -require_once DOL_DOCUMENT_ROOT . '/core/class/extrafields.class.php'; -require_once DOL_DOCUMENT_ROOT . '/core/class/doleditor.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'; +require_once DOL_DOCUMENT_ROOT.'/core/class/html.formother.class.php'; +require_once DOL_DOCUMENT_ROOT.'/core/class/html.formfile.class.php'; +require_once DOL_DOCUMENT_ROOT.'/core/class/html.formpropal.class.php'; +require_once DOL_DOCUMENT_ROOT.'/core/class/html.formmargin.class.php'; +require_once DOL_DOCUMENT_ROOT.'/comm/propal/class/propal.class.php'; +require_once DOL_DOCUMENT_ROOT.'/comm/action/class/actioncomm.class.php'; +require_once DOL_DOCUMENT_ROOT.'/core/modules/propale/modules_propale.php'; +require_once DOL_DOCUMENT_ROOT.'/core/lib/propal.lib.php'; +require_once DOL_DOCUMENT_ROOT.'/core/lib/functions2.lib.php'; +require_once DOL_DOCUMENT_ROOT.'/core/lib/signature.lib.php'; +require_once DOL_DOCUMENT_ROOT.'/core/class/extrafields.class.php'; +require_once DOL_DOCUMENT_ROOT.'/core/class/doleditor.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'; } if (!empty($conf->variants->enabled)) { @@ -60,7 +60,7 @@ if (!empty($conf->variants->enabled)) { // Load translation files required by the page $langs->loadLangs(array('companies', 'propal', 'compta', 'bills', 'orders', 'products', 'deliveries', 'sendings', 'other')); if (!empty($conf->incoterm->enabled)) $langs->load('incoterm'); -if (! empty($conf->margin->enabled)) +if (!empty($conf->margin->enabled)) $langs->load('margins'); $error = 0; @@ -78,15 +78,15 @@ $contactid = GETPOST('contactid', 'int'); $projectid = GETPOST('projectid', 'int'); // PDF -$hidedetails = (GETPOST('hidedetails', 'int') ? GETPOST('hidedetails', 'int') : (! empty($conf->global->MAIN_GENERATE_DOCUMENTS_HIDE_DETAILS) ? 1 : 0)); -$hidedesc = (GETPOST('hidedesc', 'int') ? GETPOST('hidedesc', 'int') : (! empty($conf->global->MAIN_GENERATE_DOCUMENTS_HIDE_DESC) ? 1 : 0)); -$hideref = (GETPOST('hideref', 'int') ? GETPOST('hideref', 'int') : (! empty($conf->global->MAIN_GENERATE_DOCUMENTS_HIDE_REF) ? 1 : 0)); +$hidedetails = (GETPOST('hidedetails', 'int') ? GETPOST('hidedetails', 'int') : (!empty($conf->global->MAIN_GENERATE_DOCUMENTS_HIDE_DETAILS) ? 1 : 0)); +$hidedesc = (GETPOST('hidedesc', 'int') ? GETPOST('hidedesc', 'int') : (!empty($conf->global->MAIN_GENERATE_DOCUMENTS_HIDE_DESC) ? 1 : 0)); +$hideref = (GETPOST('hideref', 'int') ? GETPOST('hideref', 'int') : (!empty($conf->global->MAIN_GENERATE_DOCUMENTS_HIDE_REF) ? 1 : 0)); // Nombre de ligne pour choix de produit/service predefinis $NBLINES = 4; // Security check -if (! empty($user->socid)) $socid = $user->socid; +if (!empty($user->socid)) $socid = $user->socid; $result = restrictedArea($user, 'propal', $id); $object = new Propal($db); @@ -96,7 +96,7 @@ $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(); @@ -108,13 +108,13 @@ if ($id > 0 || ! empty($ref)) { } // Initialize technical object to manage hooks of page. Note that conf->hooks_modules contains array of hook context -$hookmanager->initHooks(array('propalcard','globalcard')); +$hookmanager->initHooks(array('propalcard', 'globalcard')); $usercanread = $user->rights->propal->lire; $usercancreate = $user->rights->propal->creer; $usercanclose = $user->rights->propal->cloturer; $usercandelete = $user->rights->propal->supprimer; -$usercanvalidate = ((empty($conf->global->MAIN_USE_ADVANCED_PERMS) && $usercancreate) || (! empty($conf->global->MAIN_USE_ADVANCED_PERMS) && ! empty($user->rights->propal->propal_advance->validate))); +$usercanvalidate = ((empty($conf->global->MAIN_USE_ADVANCED_PERMS) && $usercancreate) || (!empty($conf->global->MAIN_USE_ADVANCED_PERMS) && !empty($user->rights->propal->propal_advance->validate))); $usercansend = (empty($conf->global->MAIN_USE_ADVANCED_PERMS) || $user->rights->propal->propal_advance->send); $usercancreateorder = $user->rights->commande->creer; @@ -124,7 +124,7 @@ $usercancreateintervention = $user->rights->ficheinter->creer; $usercancreatepurchaseorder = $user->rights->fournisseur->commande->creer; $permissionnote = $usercancreate; // Used by the include of actions_setnotes.inc.php -$permissiondellink = $usercancreate; // Used by the include of actions_dellink.inc.php +$permissiondellink = $usercancreate; // Used by the include of actions_dellink.inc.php $permissiontoedit = $usercancreate; // Used by the include of actions_lineupdown.inc.php @@ -140,24 +140,24 @@ if (empty($reshook)) { if ($cancel) { - if (! empty($backtopage)) + if (!empty($backtopage)) { header("Location: ".$backtopage); exit; } - $action=''; + $action = ''; } 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 + include DOL_DOCUMENT_ROOT.'/core/actions_dellink.inc.php'; // Must be include, not include_once - include DOL_DOCUMENT_ROOT.'/core/actions_lineupdown.inc.php'; // Must be include, not include_once + 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 (! GETPOST('socid', 3)) + if (!GETPOST('socid', 3)) { setEventMessages($langs->trans("NoCloneOptionsSpecified"), null, 'errors'); } @@ -195,7 +195,7 @@ if (empty($reshook)) $result = $object->createFromClone($user, $socid); if ($result > 0) { - header("Location: " . $_SERVER['PHP_SELF'] . '?id=' . $result); + header("Location: ".$_SERVER['PHP_SELF'].'?id='.$result); exit(); } else { if (count($object->errors) > 0) setEventMessages($object->error, $object->errors, 'errors'); @@ -210,7 +210,7 @@ if (empty($reshook)) { $result = $object->delete($user); if ($result > 0) { - header('Location: ' . DOL_URL_ROOT . '/comm/propal/list.php?restore_lastsearch_values=1'); + header('Location: '.DOL_URL_ROOT.'/comm/propal/list.php?restore_lastsearch_values=1'); exit(); } else { $langs->load("errors"); @@ -229,7 +229,7 @@ if (empty($reshook)) if (empty($conf->global->MAIN_DISABLE_PDF_AUTOUPDATE)) { // Define output language $outputlangs = $langs; - if (! empty($conf->global->MAIN_MULTILANGS)) { + if (!empty($conf->global->MAIN_MULTILANGS)) { $outputlangs = new Translate("", $conf); $newlang = (GETPOST('lang_id', 'aZ09') ? GETPOST('lang_id', 'aZ09') : $object->thirdparty->default_lang); $outputlangs->setDefaultLang($newlang); @@ -238,7 +238,7 @@ if (empty($reshook)) $object->generateDocument($object->modelpdf, $outputlangs, $hidedetails, $hidedesc, $hideref); } - header('Location: ' . $_SERVER["PHP_SELF"] . '?id=' . $object->id); + header('Location: '.$_SERVER["PHP_SELF"].'?id='.$object->id); exit(); } @@ -254,11 +254,11 @@ if (empty($reshook)) $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 (!empty($newlang)) { $outputlangs = new Translate("", $conf); $outputlangs->setDefaultLang($newlang); } - $model=$object->modelpdf; + $model = $object->modelpdf; $ret = $object->fetch($id); // Reload to get new records $object->generateDocument($model, $outputlangs, $hidedetails, $hidedesc, $hideref); @@ -275,11 +275,11 @@ if (empty($reshook)) $datep = dol_mktime(12, 0, 0, $_POST['remonth'], $_POST['reday'], $_POST['reyear']); if (empty($datep)) { - $error ++; + $error++; setEventMessages($langs->trans("ErrorFieldRequired", $langs->transnoentitiesnoconv("Date")), null, 'errors'); } - if (! $error) { + if (!$error) { $result = $object->set_date($user, $datep); if ($result < 0) dol_print_error($db, $object->error); @@ -327,22 +327,22 @@ if (empty($reshook)) if (empty($datep)) { setEventMessages($langs->trans("ErrorFieldRequired", $langs->transnoentitiesnoconv("Date")), null, 'errors'); $action = 'create'; - $error ++; + $error++; } if (empty($duration)) { setEventMessages($langs->trans("ErrorFieldRequired", $langs->transnoentitiesnoconv("ValidityDuration")), null, 'errors'); $action = 'create'; - $error ++; + $error++; } if ($socid < 1) { setEventMessages($langs->trans("ErrorFieldRequired", $langs->transnoentitiesnoconv("Customer")), null, 'errors'); $action = 'create'; - $error ++; + $error++; } - if (! $error) + if (!$error) { $db->begin(); @@ -413,12 +413,12 @@ if (empty($reshook)) // Fill array 'array_options' with data from add form $ret = $extrafields->setOptionalsFromPost(null, $object); if ($ret < 0) { - $error ++; + $error++; $action = 'create'; } } - if (! $error) + if (!$error) { if ($origin && $originid) { @@ -452,19 +452,19 @@ 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']); } $id = $object->create($user); if ($id > 0) { - dol_include_once('/' . $element . '/class/' . $subelement . '.class.php'); + dol_include_once('/'.$element.'/class/'.$subelement.'.class.php'); $classname = ucfirst($subelement); $srcobject = new $classname($db); - dol_syslog("Try to find source object origin=" . $object->origin . " originid=" . $object->origin_id . " to add lines"); + 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) @@ -476,12 +476,12 @@ if (empty($reshook)) $lines = $srcobject->lines; } - $fk_parent_line=0; - $num=count($lines); - for ($i=0;$i<$num;$i++) + $fk_parent_line = 0; + $num = count($lines); + for ($i = 0; $i < $num; $i++) { - $label=(! empty($lines[$i]->label)?$lines[$i]->label:''); - $desc=(! empty($lines[$i]->desc)?$lines[$i]->desc:$lines[$i]->libelle); + $label = (!empty($lines[$i]->label) ? $lines[$i]->label : ''); + $desc = (!empty($lines[$i]->desc) ? $lines[$i]->desc : $lines[$i]->libelle); // Positive line $product_type = ($lines[$i]->product_type ? $lines[$i]->product_type : 0); @@ -516,7 +516,7 @@ if (empty($reshook)) } $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, 'HT', 0, $lines[$i]->info_bits, $product_type, $lines[$i]->rang, $lines[$i]->special_code, $fk_parent_line, $lines[$i]->fk_fournprice, $lines[$i]->pa_ht, $label, $date_start, $date_end, $array_options, $lines[$i]->fk_unit); @@ -524,7 +524,7 @@ if (empty($reshook)) $lineid = $result; } else { $lineid = 0; - $error ++; + $error++; break; } @@ -539,14 +539,14 @@ if (empty($reshook)) $reshook = $hookmanager->executeHooks('createFrom', $parameters, $object, $action); // Note that $action and $object may have been // modified by hook if ($reshook < 0) - $error ++; + $error++; } else { setEventMessages($srcobject->error, $srcobject->errors, 'errors'); - $error ++; + $error++; } } else { setEventMessages($object->error, $object->errors, 'errors'); - $error ++; + $error++; } } // Standard creation else @@ -567,7 +567,7 @@ if (empty($reshook)) } } - if (! empty($conf->global->PROPOSAL_AUTO_ADD_AUTHOR_AS_CONTACT)) + if (!empty($conf->global->PROPOSAL_AUTO_ADD_AUTHOR_AS_CONTACT)) { $result = $object->add_contact($user->id, 'SALESREPFOLL', 'internal'); if ($result < 0) @@ -577,7 +577,7 @@ if (empty($reshook)) } } - if (! $error) + if (!$error) { $db->commit(); @@ -588,31 +588,31 @@ if (empty($reshook)) $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 (!empty($newlang)) { $outputlangs = new Translate("", $conf); $outputlangs->setDefaultLang($newlang); } - $model=$object->modelpdf; + $model = $object->modelpdf; $ret = $object->fetch($id); // Reload to get new records - $result=$object->generateDocument($model, $outputlangs, $hidedetails, $hidedesc, $hideref); + $result = $object->generateDocument($model, $outputlangs, $hidedetails, $hidedesc, $hideref); if ($result < 0) dol_print_error($db, $result); } - header('Location: ' . $_SERVER["PHP_SELF"] . '?id=' . $id); + header('Location: '.$_SERVER["PHP_SELF"].'?id='.$id); exit(); } else { $db->rollback(); - $action='create'; + $action = 'create'; } } else { setEventMessages($object->error, $object->errors, 'errors'); $db->rollback(); - $action='create'; + $action = 'create'; } } } @@ -623,14 +623,14 @@ if (empty($reshook)) { $db->begin(); - $result=$object->cloture($user, Propal::STATUS_BILLED, ''); + $result = $object->cloture($user, Propal::STATUS_BILLED, ''); if ($result < 0) { setEventMessages($object->error, $object->errors, 'errors'); $error++; } - if (! $error) + if (!$error) { $db->commit(); } @@ -641,8 +641,8 @@ if (empty($reshook)) } // Close proposal - elseif ($action == 'setstatut' && $usercanclose && ! GETPOST('cancel', 'alpha')) { - if (! (GETPOST('statut', 'int') > 0)) { + elseif ($action == 'setstatut' && $usercanclose && !GETPOST('cancel', 'alpha')) { + if (!(GETPOST('statut', 'int') > 0)) { setEventMessages($langs->trans("ErrorFieldRequired", $langs->transnoentitiesnoconv("CloseAs")), null, 'errors'); $action = 'statut'; } else { @@ -651,14 +651,14 @@ if (empty($reshook)) { $db->begin(); - $result=$object->cloture($user, GETPOST('statut', 'int'), GETPOST('note_private', 'none')); + $result = $object->cloture($user, GETPOST('statut', 'int'), GETPOST('note_private', 'none')); if ($result < 0) { setEventMessages($object->error, $object->errors, 'errors'); $error++; } - if (! $error) + if (!$error) { $db->commit(); } @@ -671,20 +671,20 @@ if (empty($reshook)) } // Reopen proposal - elseif ($action == 'confirm_reopen' && $usercanclose && ! GETPOST('cancel', 'alpha')) { + elseif ($action == 'confirm_reopen' && $usercanclose && !GETPOST('cancel', 'alpha')) { // prevent browser refresh from reopening proposal several times if ($object->statut == Propal::STATUS_SIGNED || $object->statut == Propal::STATUS_NOTSIGNED || $object->statut == Propal::STATUS_BILLED) { $db->begin(); - $result=$object->reopen($user, 1); + $result = $object->reopen($user, 1); if ($result < 0) { setEventMessages($object->error, $object->errors, 'errors'); $error++; } - if (! $error) + if (!$error) { $db->commit(); } @@ -696,7 +696,7 @@ if (empty($reshook)) } // add lines from objectlinked - elseif($action == 'import_lines_from_object' + elseif ($action == 'import_lines_from_object' && $user->rights->propal->creer && $object->statut == Propal::STATUS_DRAFT ) @@ -705,14 +705,14 @@ if (empty($reshook)) $fromElementid = GETPOST('fromelementid'); $importLines = GETPOST('line_checkbox'); - if(!empty($importLines) && is_array($importLines) && !empty($fromElement) && ctype_alpha($fromElement) && !empty($fromElementid)) + if (!empty($importLines) && is_array($importLines) && !empty($fromElement) && ctype_alpha($fromElement) && !empty($fromElementid)) { - if($fromElement == 'commande') + 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'; @@ -720,11 +720,11 @@ if (empty($reshook)) $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($lineId); $desc = $originLine->desc; @@ -740,15 +740,15 @@ if (empty($reshook)) $ventil = 0; $info_bits = $originLine->info_bits; $fk_remise_except = $originLine->fk_remise_except; - $price_base_type='HT'; - $pu_ttc=0; + $price_base_type = 'HT'; + $pu_ttc = 0; $type = $originLine->product_type; - $rang=$nextRang++; + $rang = $nextRang++; $special_code = $originLine->special_code; $origin = $originLine->element; $origin_id = $originLine->id; - $fk_parent_line=0; - $fk_fournprice=$originLine->fk_fournprice; + $fk_parent_line = 0; + $fk_fournprice = $originLine->fk_fournprice; $pa_ht = $originLine->pa_ht; $label = $originLine->label; $array_options = $originLine->array_options; @@ -759,18 +759,18 @@ if (empty($reshook)) $res = $object->addline($desc, $pu_ht, $qty, $txtva, $txlocaltax1, $txlocaltax2, $fk_product, $remise_percent, $price_base_type, $pu_ttc, $info_bits, $type, $rang, $special_code, $fk_parent_line, $fk_fournprice, $pa_ht, $label, $date_start, $date_end, $array_options, $fk_unit, $origin, $origin_id, $pu_ht_devise, $fk_remise_except); - if($res > 0){ + if ($res > 0) { $importCount++; - }else{ + } else { $error++; } } - else{ + else { $error++; } } - if($error) + if ($error) { setEventMessages($langs->trans('ErrorsOnXLines', $error), null, 'errors'); } @@ -780,10 +780,10 @@ if (empty($reshook)) include DOL_DOCUMENT_ROOT.'/core/actions_printing.inc.php'; // Actions to send emails - $actiontypecode='AC_OTH_AUTO'; - $trigger_name='PROPAL_SENTBYMAIL'; - $autocopy='MAIN_MAIL_AUTOCOPY_PROPOSAL_TO'; - $trackid='pro'.$object->id; + $actiontypecode = 'AC_OTH_AUTO'; + $trigger_name = 'PROPAL_SENTBYMAIL'; + $autocopy = 'MAIN_MAIL_AUTOCOPY_PROPOSAL_TO'; + $trackid = 'pro'.$object->id; include DOL_DOCUMENT_ROOT.'/core/actions_sendmails.inc.php'; @@ -796,7 +796,7 @@ if (empty($reshook)) { // Define output language $outputlangs = $langs; - if (! empty($conf->global->MAIN_MULTILANGS)) { + if (!empty($conf->global->MAIN_MULTILANGS)) { $outputlangs = new Translate("", $conf); $newlang = (GETPOST('lang_id', 'aZ09') ? GETPOST('lang_id', 'aZ09') : $object->thirdparty->default_lang); $outputlangs->setDefaultLang($newlang); @@ -820,25 +820,25 @@ if (empty($reshook)) // Add line elseif ($action == 'addline' && $usercancreate) { // Set if we used free entry or predefined product - $predef=''; - $product_desc=(GETPOST('dp_desc')?GETPOST('dp_desc'):''); + $predef = ''; + $product_desc = (GETPOST('dp_desc') ?GETPOST('dp_desc') : ''); $price_ht = GETPOST('price_ht'); $price_ht_devise = GETPOST('multicurrency_price_ht'); $prod_entry_mode = GETPOST('prod_entry_mode'); if ($prod_entry_mode == 'free') { - $idprod=0; + $idprod = 0; $tva_tx = (GETPOST('tva_tx') ? GETPOST('tva_tx') : 0); } else { - $idprod=GETPOST('idprod', 'int'); + $idprod = GETPOST('idprod', 'int'); $tva_tx = ''; } - $qty = GETPOST('qty' . $predef); - $remise_percent = GETPOST('remise_percent' . $predef); - if (empty($remise_percent)) $remise_percent=0; + $qty = GETPOST('qty'.$predef); + $remise_percent = GETPOST('remise_percent'.$predef); + if (empty($remise_percent)) $remise_percent = 0; // Extrafields $extralabelsline = $extrafields->fetch_name_optionals_label($object->table_element_line); @@ -847,23 +847,23 @@ if (empty($reshook)) if (is_array($extralabelsline)) { // Get extra fields foreach ($extralabelsline as $key => $value) { - unset($_POST["options_" . $key]); + unset($_POST["options_".$key]); } } if ($prod_entry_mode == 'free' && empty($idprod) && GETPOST('type') < 0) { setEventMessages($langs->trans("ErrorFieldRequired", $langs->transnoentitiesnoconv("Type")), null, 'errors'); - $error ++; + $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 proposal. { setEventMessages($langs->trans("ErrorFieldRequired", $langs->transnoentitiesnoconv("UnitPriceHT")), null, 'errors'); - $error ++; + $error++; } if ($prod_entry_mode == 'free' && empty($idprod) && empty($product_desc)) { setEventMessages($langs->trans("ErrorFieldRequired", $langs->transnoentitiesnoconv("Description")), null, 'errors'); - $error ++; + $error++; } if (!$error && !empty($conf->variants->enabled) && $prod_entry_mode != 'free') { @@ -875,12 +875,12 @@ if (empty($reshook)) $idprod = $res->fk_product_child; } else { setEventMessages($langs->trans('ErrorProductCombinationNotFound'), null, 'errors'); - $error ++; + $error++; } } } - if (! $error && ($qty >= 0) && (! empty($product_desc) || ! empty($idprod))) { + if (!$error && ($qty >= 0) && (!empty($product_desc) || !empty($idprod))) { $pu_ht = 0; $pu_ttc = 0; $price_min = 0; @@ -894,7 +894,7 @@ if (empty($reshook)) // Ecrase $desc par celui du produit // Ecrase $tva_tx par celui du produit // Replaces $fk_unit with the product unit - if (! empty($idprod)) { + if (!empty($idprod)) { $prod = new Product($db); $prod->fetch($idprod); @@ -903,7 +903,7 @@ 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; // Price unique per product $pu_ht = $prod->price; @@ -912,22 +912,22 @@ if (empty($reshook)) $price_base_type = $prod->price_base_type; // If price per segment - if (! empty($conf->global->PRODUIT_MULTIPRICES) && $object->thirdparty->price_level) + if (!empty($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]; - if (! empty($conf->global->PRODUIT_MULTIPRICES_USE_VAT_PER_LEVEL)) // using this option is a bug. kept for backward compatibility + if (!empty($conf->global->PRODUIT_MULTIPRICES_USE_VAT_PER_LEVEL)) // using this option is a bug. kept for backward compatibility { - if (isset($prod->multiprices_tva_tx[$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 (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)) { - require_once DOL_DOCUMENT_ROOT . '/product/class/productcustomerprice.class.php'; + require_once DOL_DOCUMENT_ROOT.'/product/class/productcustomerprice.class.php'; $prodcustprice = new Productcustomerprice($db); @@ -940,15 +940,15 @@ if (empty($reshook)) $pu_ht = price($prodcustprice->lines[0]->price); $pu_ttc = price($prodcustprice->lines[0]->price_ttc); $price_base_type = $prodcustprice->lines[0]->price_base_type; - $tva_tx = ($prodcustprice->lines[0]->default_vat_code ? $prodcustprice->lines[0]->tva_tx . ' ('.$prodcustprice->lines[0]->default_vat_code.' )' : $prodcustprice->lines[0]->tva_tx); - if ($prodcustprice->lines[0]->default_vat_code && ! preg_match('/\(.*\)/', $tva_tx)) $tva_tx.= ' ('.$prodcustprice->lines[0]->default_vat_code.')'; + $tva_tx = ($prodcustprice->lines[0]->default_vat_code ? $prodcustprice->lines[0]->tva_tx.' ('.$prodcustprice->lines[0]->default_vat_code.' )' : $prodcustprice->lines[0]->tva_tx); + 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; } } } // If price per quantity - elseif (! empty($conf->global->PRODUIT_CUSTOMER_PRICES_BY_QTY)) + elseif (!empty($conf->global->PRODUIT_CUSTOMER_PRICES_BY_QTY)) { if ($prod->prices_by_qty[0]) // yes, this product has some prices per quantity { @@ -956,7 +956,7 @@ if (empty($reshook)) $pqp = GETPOST('pbq', 'int'); // Search price into product_price_by_qty from $prod->id - foreach($prod->prices_by_qty_list[0] as $priceforthequantityarray) + foreach ($prod->prices_by_qty_list[0] as $priceforthequantityarray) { if ($priceforthequantityarray['rowid'] != $pqp) continue; // We found the price @@ -974,7 +974,7 @@ if (empty($reshook)) } } // If price per quantity and customer - elseif (! empty($conf->global->PRODUIT_CUSTOMER_PRICES_BY_QTY_MULTIPRICES)) + 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 { @@ -982,7 +982,7 @@ if (empty($reshook)) $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) + foreach ($prod->prices_by_qty_list[$object->thirdparty->price_level] as $priceforthequantityarray) { if ($priceforthequantityarray['rowid'] != $pqp) continue; // We found the price @@ -1004,7 +1004,7 @@ if (empty($reshook)) $tmpprodvat = price2num(preg_replace('/\s*\(.*\)/', '', $prod->tva_tx)); // if price ht is forced (ie: calculated by margin rate and cost price). TODO Why this ? - if (! empty($price_ht)) { + if (!empty($price_ht)) { $pu_ht = price2num($price_ht, 'MU'); $pu_ttc = price2num($pu_ht * (1 + ($tmpvat / 100)), 'MU'); } @@ -1021,24 +1021,24 @@ if (empty($reshook)) $desc = ''; // 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)) { $outputlangs = $langs; $newlang = ''; if (empty($newlang) && GETPOST('lang_id', 'aZ09')) $newlang = GETPOST('lang_id', 'aZ09'); if (empty($newlang)) $newlang = $object->thirdparty->default_lang; - if (! empty($newlang)) { + 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; } - if (!empty($product_desc) && !empty($conf->global->MAIN_NO_CONCAT_DESCRIPTION)) $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)); // Add dimensions into product description @@ -1054,35 +1054,35 @@ if (empty($reshook)) }*/ // Add custom code and origin country into description - if (empty($conf->global->MAIN_PRODUCT_DISABLE_CUSTOMCOUNTRYCODE) && (! empty($prod->customcode) || ! empty($prod->country_code))) + if (empty($conf->global->MAIN_PRODUCT_DISABLE_CUSTOMCOUNTRYCODE) && (!empty($prod->customcode) || !empty($prod->country_code))) { $tmptxt = '('; // 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)) { $outputlangs = $langs; $newlang = ''; if (empty($newlang) && GETPOST('lang_id', 'alpha')) $newlang = GETPOST('lang_id', 'alpha'); if (empty($newlang)) $newlang = $object->thirdparty->default_lang; - if (! empty($newlang)) { + if (!empty($newlang)) { $outputlangs = new Translate("", $conf); $outputlangs->setDefaultLang($newlang); $outputlangs->load('products'); } - if (! empty($prod->customcode)) - $tmptxt .= $outputlangs->transnoentitiesnoconv("CustomCode") . ': ' . $prod->customcode; - if (! empty($prod->customcode) && ! empty($prod->country_code)) + if (!empty($prod->customcode)) + $tmptxt .= $outputlangs->transnoentitiesnoconv("CustomCode").': '.$prod->customcode; + if (!empty($prod->customcode) && !empty($prod->country_code)) $tmptxt .= ' - '; - if (! empty($prod->country_code)) - $tmptxt .= $outputlangs->transnoentitiesnoconv("CountryOrigin") . ': ' . getCountry($prod->country_code, 0, $db, $outputlangs, 0); + if (!empty($prod->country_code)) + $tmptxt .= $outputlangs->transnoentitiesnoconv("CountryOrigin").': '.getCountry($prod->country_code, 0, $db, $outputlangs, 0); } else { - if (! empty($prod->customcode)) - $tmptxt .= $langs->transnoentitiesnoconv("CustomCode") . ': ' . $prod->customcode; - if (! empty($prod->customcode) && ! empty($prod->country_code)) + if (!empty($prod->customcode)) + $tmptxt .= $langs->transnoentitiesnoconv("CustomCode").': '.$prod->customcode; + if (!empty($prod->customcode) && !empty($prod->country_code)) $tmptxt .= ' - '; - if (! empty($prod->country_code)) - $tmptxt .= $langs->transnoentitiesnoconv("CountryOrigin") . ': ' . getCountry($prod->country_code, 0, $db, $langs, 0); + if (!empty($prod->country_code)) + $tmptxt .= $langs->transnoentitiesnoconv("CountryOrigin").': '.getCountry($prod->country_code, 0, $db, $langs, 0); } $tmptxt .= ')'; $desc = dol_concatdesc($desc, $tmptxt); @@ -1104,11 +1104,11 @@ if (empty($reshook)) } // Margin - $fournprice = price2num(GETPOST('fournprice' . $predef) ? GETPOST('fournprice' . $predef) : ''); - $buyingprice = price2num(GETPOST('buying_price' . $predef) != '' ? GETPOST('buying_price' . $predef) : ''); // If buying_price is '0', we muste keep this value + $fournprice = price2num(GETPOST('fournprice'.$predef) ? GETPOST('fournprice'.$predef) : ''); + $buyingprice = price2num(GETPOST('buying_price'.$predef) != '' ? GETPOST('buying_price'.$predef) : ''); // If buying_price is '0', we muste keep this value - $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')); + $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')); // Local Taxes $localtax1_tx = get_localtax($tva_tx, 1, $object->thirdparty, $tva_npr); @@ -1118,7 +1118,7 @@ if (empty($reshook)) 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)))) { + 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)); setEventMessages($mesg, null, 'errors'); } else { @@ -1131,7 +1131,7 @@ if (empty($reshook)) if (empty($conf->global->MAIN_DISABLE_PDF_AUTOUPDATE)) { // Define output language $outputlangs = $langs; - if (! empty($conf->global->MAIN_MULTILANGS)) { + if (!empty($conf->global->MAIN_MULTILANGS)) { $outputlangs = new Translate("", $conf); $newlang = (GETPOST('lang_id', 'aZ09') ? GETPOST('lang_id', 'aZ09') : $object->thirdparty->default_lang); $outputlangs->setDefaultLang($newlang); @@ -1201,7 +1201,7 @@ if (empty($reshook)) // Add buying price $fournprice = price2num(GETPOST('fournprice') ? GETPOST('fournprice') : ''); - $buyingprice = price2num(GETPOST('buying_price') != '' ? GETPOST('buying_price') : ''); // If buying_price is '0', we muste keep this value + $buyingprice = price2num(GETPOST('buying_price') != '' ? GETPOST('buying_price') : ''); // If buying_price is '0', we muste keep this value $pu_ht_devise = GETPOST('multicurrency_subprice'); @@ -1215,30 +1215,30 @@ if (empty($reshook)) if (is_array($extralabelsline)) { // Get extra fields foreach ($extralabelsline as $key => $value) { - unset($_POST["options_" . $key]); + unset($_POST["options_".$key]); } } // Define special_code for special lines - $special_code=GETPOST('special_code'); - if (! GETPOST('qty')) $special_code=3; + $special_code = GETPOST('special_code'); + if (!GETPOST('qty')) $special_code = 3; // Check minimum price $productid = GETPOST('productid', 'int'); - if (! empty($productid)) { + if (!empty($productid)) { $product = new Product($db); $res = $product->fetch($productid); $type = $product->type; $price_min = $product->price_min; - if (! empty($conf->global->PRODUIT_MULTIPRICES) && ! empty($object->thirdparty->price_level)) + if (!empty($conf->global->PRODUIT_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') : ''); - 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(GETPOST('remise_percent')) / 100) < price2num($price_min)))) { + 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(GETPOST('remise_percent')) / 100) < price2num($price_min)))) { setEventMessages($langs->trans("CantBeLessThanMinPrice", price(price2num($price_min, 'MU'), 0, $langs, 0, 0, - 1, $conf->currency)), null, 'errors'); - $error ++; + $error++; } } else { $type = GETPOST('type'); @@ -1247,11 +1247,11 @@ if (empty($reshook)) // Check parameters if (GETPOST('type') < 0) { setEventMessages($langs->trans("ErrorFieldRequired", $langs->transnoentitiesnoconv("Type")), null, 'errors'); - $error ++; + $error++; } } - if (! $error) { + if (!$error) { $db->begin(); if (empty($user->rights->margins->creer)) @@ -1274,7 +1274,7 @@ if (empty($reshook)) if (empty($conf->global->MAIN_DISABLE_PDF_AUTOUPDATE)) { // Define output language $outputlangs = $langs; - if (! empty($conf->global->MAIN_MULTILANGS)) { + if (!empty($conf->global->MAIN_MULTILANGS)) { $outputlangs = new Translate("", $conf); $newlang = (GETPOST('lang_id', 'aZ09') ? GETPOST('lang_id', 'aZ09') : $object->thirdparty->default_lang); $outputlangs->setDefaultLang($newlang); @@ -1316,7 +1316,7 @@ if (empty($reshook)) } } } elseif ($action == 'updateline' && $usercancreate && GETPOST('cancel', 'alpha')) { - header('Location: ' . $_SERVER['PHP_SELF'] . '?id=' . $object->id); // Pour reaffichage de la fiche en cours d'edition + header('Location: '.$_SERVER['PHP_SELF'].'?id='.$object->id); // Pour reaffichage de la fiche en cours d'edition exit(); } @@ -1365,12 +1365,12 @@ if (empty($reshook)) // bank account elseif ($action == 'setbankaccount' && $usercancreate) { - $result=$object->setBankAccount(GETPOST('fk_account', 'int')); + $result = $object->setBankAccount(GETPOST('fk_account', 'int')); } // shipping method elseif ($action == 'setshippingmethod' && $usercancreate) { - $result=$object->setShippingMethod(GETPOST('shipping_method_id', 'int')); + $result = $object->setShippingMethod(GETPOST('shipping_method_id', 'int')); } elseif ($action == 'update_extras') { @@ -1379,7 +1379,7 @@ if (empty($reshook)) // Fill array 'array_options' with data from update form $ret = $extrafields->setOptionalsFromPost(null, $object, GETPOST('attribute', 'none')); if ($ret < 0) $error++; - if (! $error) + if (!$error) { $result = $object->insertExtraFields('PROPAL_MODIFY'); if ($result < 0) @@ -1391,7 +1391,7 @@ if (empty($reshook)) if ($error) $action = 'edit_extras'; } - if (! empty($conf->global->MAIN_DISABLE_CONTACTS_TAB) && $usercancreate) + if (!empty($conf->global->MAIN_DISABLE_CONTACTS_TAB) && $usercancreate) { if ($action == 'addcontact') { @@ -1401,7 +1401,7 @@ if (empty($reshook)) } if ($result >= 0) { - header("Location: " . $_SERVER['PHP_SELF'] . "?id=" . $object->id); + header("Location: ".$_SERVER['PHP_SELF']."?id=".$object->id); exit(); } else { if ($object->error == 'DB_ERROR_RECORD_ALREADY_EXISTS') { @@ -1428,7 +1428,7 @@ if (empty($reshook)) $result = $object->delete_contact($lineid); if ($result >= 0) { - header("Location: " . $_SERVER['PHP_SELF'] . "?id=" . $object->id); + header("Location: ".$_SERVER['PHP_SELF']."?id=".$object->id); exit(); } else { dol_print_error($db); @@ -1455,7 +1455,7 @@ $formfile = new FormFile($db); $formpropal = new FormPropal($db); $formmargin = new FormMargin($db); $companystatic = new Societe($db); -if (! empty($conf->projet->enabled)) { $formproject = new FormProjets($db); } +if (!empty($conf->projet->enabled)) { $formproject = new FormProjets($db); } $now = dol_now(); @@ -1471,7 +1471,7 @@ if ($action == 'create') $res = $soc->fetch($socid); // Load objectsrc - if (! empty($origin) && ! empty($originid)) + if (!empty($origin) && !empty($originid)) { // Parse element/subelement (ex: project_task) $element = $subelement = $origin; @@ -1498,7 +1498,7 @@ if ($action == 'create') $element = $subelement = 'expedition'; } - dol_include_once('/' . $element . '/class/' . $subelement . '.class.php'); + dol_include_once('/'.$element.'/class/'.$subelement.'.class.php'); $classname = ucfirst($subelement); $objectsrc = new $classname($db); @@ -1509,17 +1509,17 @@ if ($action == 'create') } $objectsrc->fetch_thirdparty(); - $projectid = (! empty($objectsrc->fk_project) ? $objectsrc->fk_project : 0); - $ref_client = (! empty($objectsrc->ref_client) ? $objectsrc->ref_client : ''); - $ref_int = (! empty($objectsrc->ref_int) ? $objectsrc->ref_int : ''); + $projectid = (!empty($objectsrc->fk_project) ? $objectsrc->fk_project : 0); + $ref_client = (!empty($objectsrc->ref_client) ? $objectsrc->ref_client : ''); + $ref_int = (!empty($objectsrc->ref_int) ? $objectsrc->ref_int : ''); $soc = $objectsrc->thirdparty; - $cond_reglement_id = (! empty($objectsrc->cond_reglement_id)?$objectsrc->cond_reglement_id:(! empty($soc->cond_reglement_id)?$soc->cond_reglement_id:0)); // TODO maybe add default value option - $mode_reglement_id = (! empty($objectsrc->mode_reglement_id)?$objectsrc->mode_reglement_id:(! empty($soc->mode_reglement_id)?$soc->mode_reglement_id:0)); - $remise_percent = (! empty($objectsrc->remise_percent)?$objectsrc->remise_percent:(! empty($soc->remise_percent)?$soc->remise_percent:0)); - $remise_absolue = (! empty($objectsrc->remise_absolue)?$objectsrc->remise_absolue:(! empty($soc->remise_absolue)?$soc->remise_absolue:0)); - $dateinvoice = (empty($dateinvoice)?(empty($conf->global->MAIN_AUTOFILL_DATE)?-1:''):$dateinvoice); + $cond_reglement_id = (!empty($objectsrc->cond_reglement_id) ? $objectsrc->cond_reglement_id : (!empty($soc->cond_reglement_id) ? $soc->cond_reglement_id : 0)); // TODO maybe add default value option + $mode_reglement_id = (!empty($objectsrc->mode_reglement_id) ? $objectsrc->mode_reglement_id : (!empty($soc->mode_reglement_id) ? $soc->mode_reglement_id : 0)); + $remise_percent = (!empty($objectsrc->remise_percent) ? $objectsrc->remise_percent : (!empty($soc->remise_percent) ? $soc->remise_percent : 0)); + $remise_absolue = (!empty($objectsrc->remise_absolue) ? $objectsrc->remise_absolue : (!empty($soc->remise_absolue) ? $soc->remise_absolue : 0)); + $dateinvoice = (empty($dateinvoice) ? (empty($conf->global->MAIN_AUTOFILL_DATE) ?-1 : '') : $dateinvoice); // Replicate extrafields $objectsrc->fetch_optionals($originid); @@ -1539,37 +1539,37 @@ if ($action == 'create') $object = new Propal($db); - print ''; - print ''; + print ''; + print ''; print ''; if ($origin != 'project' && $originid) { - print ''; - print ''; + print ''; + print ''; } elseif ($origin == 'project' && !empty($projectid)) { - print ''; + print ''; } dol_fiche_head(); - print '
'.$langs->trans("Date").''.$langs->trans("PriceLevel").''.$langs->trans("User").'
'.dol_print_date($db->jdate($obj->dc), "dayhour").''.$obj->price_level.' '.$userstatic->getNomUrl(1).'
'; + print '
'; // Reference - print ''; + print ''; // Ref customer - print ''; print ''; // Third party print ''; - print ''; + print ''; if ($socid > 0) { print ''; - if (! empty($conf->global->SOCIETE_ASK_FOR_SHIPPING_METHOD) && ! empty($soc->shipping_method_id)) { + if (!empty($conf->global->SOCIETE_ASK_FOR_SHIPPING_METHOD) && !empty($soc->shipping_method_id)) { $shipping_method_id = $soc->shipping_method_id; } } else { @@ -1591,71 +1591,71 @@ if ($action == 'create') print ' '.$langs->trans("AddThirdParty").''; print ''; } - print '' . "\n"; + print ''."\n"; if ($socid > 0) { // Contacts (ask contact only if thirdparty already defined). - print "'; // Third party discounts info line - print ''; } // Date - print ''; // Validaty duration - print ''; + print ''; // Terms of payment - print ''; // Mode of payment - print ''; // Bank Account - if (! empty($conf->global->BANK_ASK_PAYMENT_BANK_DURING_PROPOSAL) && ! empty($conf->banque->enabled)) { - print ''; } // What trigger creation - print ''; // Delivery delay - print ''; // Shipping Method - if (! empty($conf->expedition->enabled)) { - print ''; } // Delivery date (or manufacturing) - print ''; + print ''; print ''; // Project - if (! empty($conf->projet->enabled)) + if (!empty($conf->projet->enabled)) { $langs->load("projects"); print ''; - print ''; print ''; } @@ -1686,20 +1686,20 @@ if ($action == 'create') print ''; print ''; print ''; } // Template to use by default print ''; - print ''; + print ''; print '"; // Multicurrency - if (! empty($conf->multicurrency->enabled)) + if (!empty($conf->multicurrency->enabled)) { print ''; print ''; @@ -1710,9 +1710,9 @@ if ($action == 'create') // Public note print ''; - print ''; + print ''; print ''; - print ''; + print ''; print ''; - print ''; - print '"; - if ($mysoc->localtax1_assuj == "1" || $objectsrc->total_localtax1 != 0 ) // Localtax1 + print ''; + print ''; + print '"; + if ($mysoc->localtax1_assuj == "1" || $objectsrc->total_localtax1 != 0) // Localtax1 { - print '"; + print '"; } if ($mysoc->localtax2_assuj == "1" || $objectsrc->total_localtax2 != 0) // Localtax2 { - print '"; + print '"; } - print '"; + print '"; if (!empty($conf->multicurrency->enabled)) { - print ''; - print '"; - print '"; + print ''; + print '"; + print '"; } } @@ -1792,21 +1792,21 @@ if ($action == 'create') if (empty($conf->global->PROPAL_CLONE_ON_CREATE_PAGE)) print ''; - if (! empty($conf->global->PROPAL_CLONE_ON_CREATE_PAGE)) + if (!empty($conf->global->PROPAL_CLONE_ON_CREATE_PAGE)) { print '
' . $langs->trans('Ref') . '' . $langs->trans("Draft") . '
'.$langs->trans('Ref').''.$langs->trans("Draft").'
' . $langs->trans('RefCustomer') . ''; + print '
'.$langs->trans('RefCustomer').''; print '
' . $langs->trans('Customer') . ''.$langs->trans('Customer').''; print $soc->getNomUrl(1); - print ''; + print ''; print '
" . $langs->trans("DefaultContact") . ''; + print "
".$langs->trans("DefaultContact").''; $form->select_contacts($soc->id, $contactid, 'contactid', 1, $srccontactslist); print '
' . $langs->trans('Discounts') . ''; + print '
'.$langs->trans('Discounts').''; $absolute_discount = $soc->getAvailableDiscounts(); $thirdparty = $soc; $discount_type = 0; - $backtopage = urlencode($_SERVER["PHP_SELF"] . '?socid=' . $thirdparty->id . '&action=' . $action . '&origin=' . GETPOST('origin') . '&originid=' . GETPOST('originid')); + $backtopage = urlencode($_SERVER["PHP_SELF"].'?socid='.$thirdparty->id.'&action='.$action.'&origin='.GETPOST('origin').'&originid='.GETPOST('originid')); include DOL_DOCUMENT_ROOT.'/core/tpl/object_discounts.tpl.php'; print '
' . $langs->trans('Date') . ''; + print '
'.$langs->trans('Date').''; print $form->selectDate('', '', '', '', '', "addprop", 1, 1); print '
' . $langs->trans("ValidityDuration") . ' ' . $langs->trans("days") . '
'.$langs->trans("ValidityDuration").' '.$langs->trans("days").'
' . $langs->trans('PaymentConditionsShort') . ''; + print '
'.$langs->trans('PaymentConditionsShort').''; $form->select_conditions_paiements($soc->cond_reglement_id, 'cond_reglement_id', -1, 1); print '
' . $langs->trans('PaymentMode') . ''; + print '
'.$langs->trans('PaymentMode').''; $form->select_types_paiements($soc->mode_reglement_id, 'mode_reglement_id'); print '
' . $langs->trans('BankAccount') . ''; + if (!empty($conf->global->BANK_ASK_PAYMENT_BANK_DURING_PROPOSAL) && !empty($conf->banque->enabled)) { + print '
'.$langs->trans('BankAccount').''; $form->select_comptes($soc->fk_account, 'fk_account', 0, '', 1); print '
' . $langs->trans('Source') . ''; + print '
'.$langs->trans('Source').''; $form->selectInputReason('', 'demand_reason_id', "SRC_PROP", 1); print '
' . $langs->trans('AvailabilityPeriod') . ''; + print '
'.$langs->trans('AvailabilityPeriod').''; $form->selectAvailabilityDelay('', 'availability_id', '', 1); print '
' . $langs->trans('SendingMethod') . ''; + if (!empty($conf->expedition->enabled)) { + print '
'.$langs->trans('SendingMethod').''; print $form->selectShippingMethod($shipping_method_id, 'shipping_method_id', '', 1); print '
' . $langs->trans("DeliveryDate") . '
'.$langs->trans("DeliveryDate").''; if ($conf->global->DATE_LIVRAISON_WEEK_DELAY != "") { $tmpdte = time() + ((7 * $conf->global->DATE_LIVRAISON_WEEK_DELAY) * 24 * 60 * 60); @@ -1669,13 +1669,13 @@ if ($action == 'create') print '
' . $langs->trans("Project") . ''; + print ''.$langs->trans("Project").''; $numprojet = $formproject->select_projects(($soc->id > 0 ? $soc->id : -1), $projectid, 'projectid', 0, 0, 1, 1); - print '   id).'">' . $langs->trans("AddProject") . ''; + print '   id).'">'.$langs->trans("AddProject").''; print '
'; - print $form->select_incoterms((!empty($soc->fk_incoterms) ? $soc->fk_incoterms : ''), (!empty($soc->location_incoterms)?$soc->location_incoterms:'')); + print $form->select_incoterms((!empty($soc->fk_incoterms) ? $soc->fk_incoterms : ''), (!empty($soc->location_incoterms) ? $soc->location_incoterms : '')); print '
' . $langs->trans("DefaultModel") . ''.$langs->trans("DefaultModel").''; $liste = ModelePDFPropales::liste_modeles($db); print $form->selectarray('model', $liste, ($conf->global->PROPALE_ADDON_PDF_ODT_DEFAULT ? $conf->global->PROPALE_ADDON_PDF_ODT_DEFAULT : $conf->global->PROPALE_ADDON_PDF)); print "
'.$form->editfieldkey('Currency', 'multicurrency_code', '', $object, 0).'
' . $langs->trans('NotePublic') . ''.$langs->trans('NotePublic').''; - $note_public = $object->getDefaultCreateValueFor('note_public', (is_object($objectsrc)?$objectsrc->note_public:null)); + $note_public = $object->getDefaultCreateValueFor('note_public', (is_object($objectsrc) ? $objectsrc->note_public : null)); $doleditor = new DolEditor('note_public', $note_public, '', 80, 'dolibarr_notes', 'In', 0, false, true, ROWS_3, '90%'); print $doleditor->Create(1); @@ -1720,9 +1720,9 @@ if ($action == 'create') if (empty($user->socid)) { print '
' . $langs->trans('NotePrivate') . ''.$langs->trans('NotePrivate').''; - $note_private = $object->getDefaultCreateValueFor('note_private', ((! empty($origin) && ! empty($originid) && is_object($objectsrc))?$objectsrc->note_private:null)); + $note_private = $object->getDefaultCreateValueFor('note_private', ((!empty($origin) && !empty($originid) && is_object($objectsrc)) ? $objectsrc->note_private : null)); $doleditor = new DolEditor('note_private', $note_private, '', 80, 'dolibarr_notes', 'In', 0, false, true, ROWS_3, '90%'); print $doleditor->Create(1); // print ' @@ -1730,10 +1730,10 @@ if ($action == 'create') } // Other attributes - include DOL_DOCUMENT_ROOT . '/core/tpl/extrafields_add.tpl.php'; + include DOL_DOCUMENT_ROOT.'/core/tpl/extrafields_add.tpl.php'; // Lines from source - if (! empty($origin) && ! empty($originid) && is_object($objectsrc)) + if (!empty($origin) && !empty($originid) && is_object($objectsrc)) { // TODO for compatibility if ($origin == 'contrat') { @@ -1743,13 +1743,13 @@ if ($action == 'create') $objectsrc->update_price(1, - 1, 1); } - print "\n"; + print "\n"; print "\n"; - print '' . "\n"; - print '' . "\n"; - print '' . "\n"; - print ''; - print ''; + print ''."\n"; + print ''."\n"; + print ''."\n"; + print ''; + print ''; $newclassname = $classname; if ($newclassname == 'Propal') @@ -1761,25 +1761,25 @@ if ($action == 'create') elseif ($newclassname == 'Fichinter') $newclassname = 'Intervention'; - print '
' . $langs->trans($newclassname) . '' . $objectsrc->getNomUrl(1) . '
' . $langs->trans('AmountHT') . '' . price($objectsrc->total_ht, 0, $langs, 1, -1, -1, $conf->currency) . '
' . $langs->trans('AmountVAT') . '' . price($objectsrc->total_tva, 0, $langs, 1, -1, -1, $conf->currency) . "
'.$langs->trans($newclassname).''.$objectsrc->getNomUrl(1).'
'.$langs->trans('AmountHT').''.price($objectsrc->total_ht, 0, $langs, 1, -1, -1, $conf->currency).'
'.$langs->trans('AmountVAT').''.price($objectsrc->total_tva, 0, $langs, 1, -1, -1, $conf->currency)."
' . $langs->transcountry("AmountLT1", $mysoc->country_code) . '' . price($objectsrc->total_localtax1, 0, $langs, 1, -1, -1, $conf->currency) . "
'.$langs->transcountry("AmountLT1", $mysoc->country_code).''.price($objectsrc->total_localtax1, 0, $langs, 1, -1, -1, $conf->currency)."
' . $langs->transcountry("AmountLT2", $mysoc->country_code) . '' . price($objectsrc->total_localtax2, 0, $langs, 1, -1, -1, $conf->currency) . "
'.$langs->transcountry("AmountLT2", $mysoc->country_code).''.price($objectsrc->total_localtax2, 0, $langs, 1, -1, -1, $conf->currency)."
' . $langs->trans('AmountTTC') . '' . price($objectsrc->total_ttc, 0, $langs, 1, -1, -1, $conf->currency) . "
'.$langs->trans('AmountTTC').''.price($objectsrc->total_ttc, 0, $langs, 1, -1, -1, $conf->currency)."
' . $langs->trans('MulticurrencyAmountHT') . '' . price($objectsrc->multicurrency_total_ht) . '
' . $langs->trans('MulticurrencyAmountVAT') . '' . price($objectsrc->multicurrency_total_tva) . "
' . $langs->trans('MulticurrencyAmountTTC') . '' . price($objectsrc->multicurrency_total_ttc) . "
'.$langs->trans('MulticurrencyAmountHT').''.price($objectsrc->multicurrency_total_ht).'
'.$langs->trans('MulticurrencyAmountVAT').''.price($objectsrc->multicurrency_total_tva)."
'.$langs->trans('MulticurrencyAmountTTC').''.price($objectsrc->multicurrency_total_ttc)."
'; // For backward compatibility print ''; print ''; - print ''; + print ''; print ''; print ''; - print ''; + print ''; } - if (! empty($conf->global->PROPAL_CLONE_ON_CREATE_PAGE)) print '
' . $langs->trans("CopyPropalFrom") . ' '.$langs->trans("CopyPropalFrom").' '; $liste_propal = array(); $liste_propal [0] = ''; $sql = "SELECT p.rowid as id, p.ref, s.nom"; - $sql .= " FROM " . MAIN_DB_PREFIX . "propal p"; - $sql .= ", " . MAIN_DB_PREFIX . "societe s"; + $sql .= " FROM ".MAIN_DB_PREFIX."propal p"; + $sql .= ", ".MAIN_DB_PREFIX."societe s"; $sql .= " WHERE s.rowid = p.fk_soc"; $sql .= " AND p.entity IN (".getEntity('propal').")"; $sql .= " AND p.fk_statut <> 0"; @@ -1818,9 +1818,9 @@ if ($action == 'create') $i = 0; while ($i < $num) { $row = $db->fetch_row($resql); - $propalRefAndSocName = $row [1] . " - " . $row [2]; + $propalRefAndSocName = $row [1]." - ".$row [2]; $liste_propal [$row [0]] = $propalRefAndSocName; - $i ++; + $i++; } print $form->selectarray("copie_propal", $liste_propal, 0); } else { @@ -1829,31 +1829,31 @@ if ($action == 'create') print '
' . $langs->trans("CreateEmptyPropal") . '
'.$langs->trans("CreateEmptyPropal").'
'; + if (!empty($conf->global->PROPAL_CLONE_ON_CREATE_PAGE)) print '
'; dol_fiche_end(); $langs->load("bills"); print '
'; - print ''; + print ''; print '     '; - print ''; + print ''; print '
'; print ""; // Show origin lines - if (! empty($origin) && ! empty($originid) && is_object($objectsrc)) { + if (!empty($origin) && !empty($originid) && is_object($objectsrc)) { print '
'; $title = $langs->trans('ProductsAndServices'); print load_fiche_titre($title); - print ''; + print '
'; $objectsrc->printOriginLinesList(); @@ -1880,47 +1880,47 @@ if ($action == 'create') // array('type' => 'checkbox', 'name' => 'clone_content', 'label' => $langs->trans("CloneMainAttributes"), 'value' => 1), // array('type' => 'checkbox', 'name' => 'update_prices', 'label' => $langs->trans("PuttingPricesUpToDate"), 'value' => // 1), - array('type' => 'other','name' => 'socid','label' => $langs->trans("SelectThirdParty"),'value' => $form->select_company(GETPOST('socid', 'int'), 'socid', '(s.client=1 OR s.client=2 OR s.client=3)'))); + array('type' => 'other', 'name' => 'socid', 'label' => $langs->trans("SelectThirdParty"), 'value' => $form->select_company(GETPOST('socid', 'int'), 'socid', '(s.client=1 OR s.client=2 OR s.client=3)'))); if (!empty($conf->global->PROPAL_CLONE_DATE_DELIVERY) && !empty($object->date_livraison)) { - $formquestion[] = array('type' => 'date','name' => 'date_delivery','label' => $langs->trans("DeliveryDate"),'value' => $object->date_livraison); + $formquestion[] = array('type' => 'date', 'name' => 'date_delivery', 'label' => $langs->trans("DeliveryDate"), 'value' => $object->date_livraison); } // Incomplete payment. We ask if reason = discount or other - $formconfirm = $form->formconfirm($_SERVER["PHP_SELF"] . '?id=' . $object->id, $langs->trans('ToClone'), $langs->trans('ConfirmClonePropal', $object->ref), 'confirm_clone', $formquestion, 'yes', 1); + $formconfirm = $form->formconfirm($_SERVER["PHP_SELF"].'?id='.$object->id, $langs->trans('ToClone'), $langs->trans('ConfirmClonePropal', $object->ref), 'confirm_clone', $formquestion, 'yes', 1); } if ($action == 'statut') { //Form to close proposal (signed or not) $formquestion = array( - array('type' => 'select','name' => 'statut','label' => $langs->trans("CloseAs"),'values' => array(2=>$object->LibStatut(Propal::STATUS_SIGNED), 3=>$object->LibStatut(Propal::STATUS_NOTSIGNED))), - array('type' => 'text', 'name' => 'note_private', 'label' => $langs->trans("Note"),'value' => '') // Field to complete private note (not replace) + array('type' => 'select', 'name' => 'statut', 'label' => $langs->trans("CloseAs"), 'values' => array(2=>$object->LibStatut(Propal::STATUS_SIGNED), 3=>$object->LibStatut(Propal::STATUS_NOTSIGNED))), + array('type' => 'text', 'name' => 'note_private', 'label' => $langs->trans("Note"), 'value' => '') // Field to complete private note (not replace) ); - if (! empty($conf->notification->enabled)) + if (!empty($conf->notification->enabled)) { - require_once DOL_DOCUMENT_ROOT . '/core/class/notify.class.php'; + require_once DOL_DOCUMENT_ROOT.'/core/class/notify.class.php'; $notify = new Notify($db); $formquestion = array_merge($formquestion, array( array('type' => 'onecolumn', 'value' => $notify->confirmMessage('PROPAL_CLOSE_SIGNED', $object->socid, $object)), )); } - $formconfirm = $form->formconfirm($_SERVER["PHP_SELF"] . '?id=' . $object->id, $langs->trans('SetAcceptedRefused'), $text, 'setstatut', $formquestion, '', 1, 250); + $formconfirm = $form->formconfirm($_SERVER["PHP_SELF"].'?id='.$object->id, $langs->trans('SetAcceptedRefused'), $text, 'setstatut', $formquestion, '', 1, 250); } // Confirm delete elseif ($action == 'delete') { - $formconfirm = $form->formconfirm($_SERVER["PHP_SELF"] . '?id=' . $object->id, $langs->trans('DeleteProp'), $langs->trans('ConfirmDeleteProp', $object->ref), 'confirm_delete', '', 0, 1); + $formconfirm = $form->formconfirm($_SERVER["PHP_SELF"].'?id='.$object->id, $langs->trans('DeleteProp'), $langs->trans('ConfirmDeleteProp', $object->ref), 'confirm_delete', '', 0, 1); } // Confirm reopen elseif ($action == 'reopen') { - $formconfirm = $form->formconfirm($_SERVER["PHP_SELF"] . '?id=' . $object->id, $langs->trans('ReOpen'), $langs->trans('ConfirmReOpenProp', $object->ref), 'confirm_reopen', '', 0, 1); + $formconfirm = $form->formconfirm($_SERVER["PHP_SELF"].'?id='.$object->id, $langs->trans('ReOpen'), $langs->trans('ConfirmReOpenProp', $object->ref), 'confirm_reopen', '', 0, 1); } // Confirmation delete product/service line elseif ($action == 'ask_deleteline') { - $formconfirm = $form->formconfirm($_SERVER["PHP_SELF"] . '?id=' . $object->id . '&lineid=' . $lineid, $langs->trans('DeleteProductLine'), $langs->trans('ConfirmDeleteProductLine'), 'confirm_deleteline', '', 0, 1); + $formconfirm = $form->formconfirm($_SERVER["PHP_SELF"].'?id='.$object->id.'&lineid='.$lineid, $langs->trans('DeleteProductLine'), $langs->trans('ConfirmDeleteProductLine'), 'confirm_deleteline', '', 0, 1); } // Confirm validate proposal @@ -1932,7 +1932,7 @@ if ($action == 'create') if ($ref == 'PROV') { $numref = $object->getNextNumRef($soc); if (empty($numref)) { - $error ++; + $error++; setEventMessages($object->error, $object->errors, 'errors'); } } else { @@ -1940,22 +1940,22 @@ if ($action == 'create') } $text = $langs->trans('ConfirmValidateProp', $numref); - if (! empty($conf->notification->enabled)) { - require_once DOL_DOCUMENT_ROOT . '/core/class/notify.class.php'; + if (!empty($conf->notification->enabled)) { + require_once DOL_DOCUMENT_ROOT.'/core/class/notify.class.php'; $notify = new Notify($db); $text .= '
'; $text .= $notify->confirmMessage('PROPAL_VALIDATE', $object->socid, $object); } - if (! $error) - $formconfirm = $form->formconfirm($_SERVER["PHP_SELF"] . '?id=' . $object->id, $langs->trans('ValidateProp'), $text, 'confirm_validate', '', 0, 1); + if (!$error) + $formconfirm = $form->formconfirm($_SERVER["PHP_SELF"].'?id='.$object->id, $langs->trans('ValidateProp'), $text, 'confirm_validate', '', 0, 1); } // Call Hook formConfirm $parameters = array('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; @@ -1963,48 +1963,48 @@ if ($action == 'create') // Proposal card - $linkback = '' . $langs->trans("BackToList") . ''; + $linkback = ''.$langs->trans("BackToList").''; - $morehtmlref='
'; + $morehtmlref = '
'; // Ref customer - $morehtmlref.=$form->editfieldkey("RefCustomer", 'ref_client', $object->ref_client, $object, $usercancreate, 'string', '', 0, 1); - $morehtmlref.=$form->editfieldval("RefCustomer", 'ref_client', $object->ref_client, $object, $usercancreate, 'string', '', null, null, '', 1); + $morehtmlref .= $form->editfieldkey("RefCustomer", 'ref_client', $object->ref_client, $object, $usercancreate, 'string', '', 0, 1); + $morehtmlref .= $form->editfieldval("RefCustomer", 'ref_client', $object->ref_client, $object, $usercancreate, 'string', '', null, null, '', 1); // Thirdparty - $morehtmlref.='
'.$langs->trans('ThirdParty') . ' : ' . $object->thirdparty->getNomUrl(1, 'customer'); - if (empty($conf->global->MAIN_DISABLE_OTHER_LINK) && $object->thirdparty->id > 0) $morehtmlref.=' ('.$langs->trans("OtherProposals").')'; + $morehtmlref .= '
'.$langs->trans('ThirdParty').' : '.$object->thirdparty->getNomUrl(1, 'customer'); + if (empty($conf->global->MAIN_DISABLE_OTHER_LINK) && $object->thirdparty->id > 0) $morehtmlref .= ' ('.$langs->trans("OtherProposals").')'; // Project - if (! empty($conf->projet->enabled)) + if (!empty($conf->projet->enabled)) { $langs->load("projects"); - $morehtmlref.='
'.$langs->trans('Project') . ' '; + $morehtmlref .= '
'.$langs->trans('Project').' '; if ($usercancreate) { if ($action != 'classify') - $morehtmlref.='' . img_edit($langs->transnoentitiesnoconv('SetProject')) . ' : '; + $morehtmlref .= ''.img_edit($langs->transnoentitiesnoconv('SetProject')).' : '; if ($action == 'classify') { //$morehtmlref.=$form->form_project($_SERVER['PHP_SELF'] . '?id=' . $object->id, $object->socid, $object->fk_project, 'projectid', 0, 0, 1, 1); - $morehtmlref.='
'; - $morehtmlref.=''; - $morehtmlref.=''; - $morehtmlref.=$formproject->select_projects($object->socid, $object->fk_project, 'projectid', $maxlength, 0, 1, 0, 1, 0, 0, '', 1); - $morehtmlref.=''; - $morehtmlref.=''; + $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); + $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)) { + if (!empty($object->fk_project)) { $proj = new Project($db); $proj->fetch($object->fk_project); - $morehtmlref.=''; - $morehtmlref.=$proj->ref; - $morehtmlref.=''; + $morehtmlref .= ''; + $morehtmlref .= $proj->ref; + $morehtmlref .= ''; } else { - $morehtmlref.=''; + $morehtmlref .= ''; } } } - $morehtmlref.='
'; + $morehtmlref .= '
'; dol_banner_tab($object, 'ref', $linkback, 1, 'ref', 'ref', $morehtmlref); @@ -2017,7 +2017,7 @@ if ($action == 'create') print '
'; // Link for thirdparty discounts - if (! empty($conf->global->FACTURE_DEPOSITS_ARE_JUST_PAYMENTS)) { + if (!empty($conf->global->FACTURE_DEPOSITS_ARE_JUST_PAYMENTS)) { $filterabsolutediscount = "fk_facture_source IS NULL"; // If we want deposit to be substracted to payments only and not to total of final invoice $filtercreditnote = "fk_facture_source IS NOT NULL"; // If we want deposit to be substracted to payments only and not to total of final invoice } else { @@ -2025,7 +2025,7 @@ if ($action == 'create') $filtercreditnote = "fk_facture_source IS NOT NULL AND (description NOT LIKE '(DEPOSIT)%' OR description LIKE '(EXCESS RECEIVED)%')"; } - print ''; @@ -2046,15 +2046,15 @@ if ($action == 'create') print $langs->trans('Date'); print ''; if ($action != 'editdate' && $object->statut == Propal::STATUS_DRAFT && $usercancreate) - print ''; + print ''; print '
' . $langs->trans('Discounts') . ''; + print '
'.$langs->trans('Discounts').''; $absolute_discount = $soc->getAvailableDiscounts('', $filterabsolutediscount); $absolute_creditnote = $soc->getAvailableDiscounts('', $filtercreditnote); @@ -2034,7 +2034,7 @@ if ($action == 'create') $thirdparty = $soc; $discount_type = 0; - $backtopage = urlencode($_SERVER["PHP_SELF"] . '?id=' . $object->id); + $backtopage = urlencode($_SERVER["PHP_SELF"].'?id='.$object->id); include DOL_DOCUMENT_ROOT.'/core/tpl/object_discounts.tpl.php'; print '
id . '">' . img_edit($langs->trans('SetDate'), 1) . 'id.'">'.img_edit($langs->trans('SetDate'), 1).'
'; print '
'; if ($object->statut == Propal::STATUS_DRAFT && $action == 'editdate' && $usercancreate) { - print '
'; - print ''; + print ''; + print ''; print ''; print $form->selectDate($object->date, 're', '', '', 0, "editdate"); - print ''; + print ''; print '
'; } else { if ($object->date) { @@ -2072,18 +2072,18 @@ if ($action == 'create') print $langs->trans('DateEndPropal'); print '
id . '">' . img_edit($langs->trans('SetConditions'), 1) . 'id.'">'.img_edit($langs->trans('SetConditions'), 1).'
'; print '
'; if ($object->statut == Propal::STATUS_DRAFT && $action == 'editecheance' && $usercancreate) { - print '
'; - print ''; + print ''; + print ''; print ''; print $form->selectDate($object->fin_validite, 'ech', '', '', '', "editecheance"); - print ''; + print ''; print '
'; } else { - if (! empty($object->fin_validite)) { + if (!empty($object->fin_validite)) { print dol_print_date($object->fin_validite, 'day'); if ($object->statut == Propal::STATUS_VALIDATED && $object->fin_validite < ($now - $conf->propal->cloture->warning_delay)) print img_warning($langs->trans("Late")); @@ -2100,13 +2100,13 @@ if ($action == 'create') print $langs->trans('PaymentConditionsShort'); print '
id . '">' . img_edit($langs->transnoentitiesnoconv('SetConditions'), 1) . 'id.'">'.img_edit($langs->transnoentitiesnoconv('SetConditions'), 1).'
'; print '
'; if ($object->statut == Propal::STATUS_DRAFT && $action == 'editconditions' && $usercancreate) { - $form->form_conditions_reglement($_SERVER['PHP_SELF'] . '?id=' . $object->id, $object->cond_reglement_id, 'cond_reglement_id'); + $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'); + $form->form_conditions_reglement($_SERVER['PHP_SELF'].'?id='.$object->id, $object->cond_reglement_id, 'none'); } print '
'; print ''; if ($action != 'editavailability' && $object->statut == Propal::STATUS_DRAFT && $usercancreate) - print ''; + print ''; print '
'; print $langs->trans('AvailabilityPeriod'); - if (! empty($conf->commande->enabled)) - print ' (' . $langs->trans('AfterOrder') . ')'; + if (!empty($conf->commande->enabled)) + print ' ('.$langs->trans('AfterOrder').')'; print 'id . '">' . img_edit($langs->transnoentitiesnoconv('SetAvailability'), 1) . 'id.'">'.img_edit($langs->transnoentitiesnoconv('SetAvailability'), 1).'
'; print '
'; if ($object->statut == Propal::STATUS_DRAFT && $action == 'editavailability' && $usercancreate) { - $form->form_availability($_SERVER['PHP_SELF'] . '?id=' . $object->id, $object->availability_id, 'availability_id', 1); + $form->form_availability($_SERVER['PHP_SELF'].'?id='.$object->id, $object->availability_id, 'availability_id', 1); } else { - $form->form_availability($_SERVER['PHP_SELF'] . '?id=' . $object->id, $object->availability_id, 'none', 1); + $form->form_availability($_SERVER['PHP_SELF'].'?id='.$object->id, $object->availability_id, 'none', 1); } print '
'; print ''; if ($action != 'editdemandreason' && $object->statut == Propal::STATUS_DRAFT && $usercancreate) - print ''; + print ''; print '
'; print $langs->trans('SendingMethod'); @@ -2165,13 +2165,13 @@ if ($action == 'create') print $langs->trans('Source'); print 'id . '">' . img_edit($langs->transnoentitiesnoconv('SetDemandReason'), 1) . 'id.'">'.img_edit($langs->transnoentitiesnoconv('SetDemandReason'), 1).'
'; print '
'; if ($object->statut == Propal::STATUS_DRAFT && $action == 'editdemandreason' && $usercancreate) { - $form->formInputReason($_SERVER['PHP_SELF'] . '?id=' . $object->id, $object->demand_reason_id, 'demand_reason_id', 1); + $form->formInputReason($_SERVER['PHP_SELF'].'?id='.$object->id, $object->demand_reason_id, 'demand_reason_id', 1); } else { - $form->formInputReason($_SERVER['PHP_SELF'] . '?id=' . $object->id, $object->demand_reason_id, 'none'); + $form->formInputReason($_SERVER['PHP_SELF'].'?id='.$object->id, $object->demand_reason_id, 'none'); } print '
id . '">' . img_edit($langs->transnoentitiesnoconv('SetMode'), 1) . 'id.'">'.img_edit($langs->transnoentitiesnoconv('SetMode'), 1).'
'; print '
'; if ($object->statut == Propal::STATUS_DRAFT && $action == 'editmode' && $usercancreate) { - $form->form_modes_reglement($_SERVER['PHP_SELF'] . '?id=' . $object->id, $object->mode_reglement_id, 'mode_reglement_id', 'CRDT', 1, 1); + $form->form_modes_reglement($_SERVER['PHP_SELF'].'?id='.$object->id, $object->mode_reglement_id, 'mode_reglement_id', 'CRDT', 1, 1); } else { - $form->form_modes_reglement($_SERVER['PHP_SELF'] . '?id=' . $object->id, $object->mode_reglement_id, 'none'); + $form->form_modes_reglement($_SERVER['PHP_SELF'].'?id='.$object->id, $object->mode_reglement_id, 'none'); } print '
id . '">' . img_edit($langs->transnoentitiesnoconv('SetMultiCurrencyCode'), 1) . 'id.'">'.img_edit($langs->transnoentitiesnoconv('SetMultiCurrencyCode'), 1).'
'; print '
'; if ($object->statut == $object::STATUS_DRAFT && $action == 'editmulticurrencycode' && $usercancreate) { - $form->form_multicurrency_code($_SERVER['PHP_SELF'] . '?id=' . $object->id, $object->multicurrency_code, 'multicurrency_code'); + $form->form_multicurrency_code($_SERVER['PHP_SELF'].'?id='.$object->id, $object->multicurrency_code, 'multicurrency_code'); } else { - $form->form_multicurrency_code($_SERVER['PHP_SELF'] . '?id=' . $object->id, $object->multicurrency_code, 'none'); + $form->form_multicurrency_code($_SERVER['PHP_SELF'].'?id='.$object->id, $object->multicurrency_code, 'none'); } print '
id . '">' . img_edit($langs->transnoentitiesnoconv('SetMultiCurrencyCode'), 1) . 'id.'">'.img_edit($langs->transnoentitiesnoconv('SetMultiCurrencyCode'), 1).'
'; print '
'; - if ($object->statut ==$object::STATUS_DRAFT && ($action == 'editmulticurrencyrate' || $action == 'actualizemulticurrencyrate') && $usercancreate) { - if($action == 'actualizemulticurrencyrate') { + if ($object->statut == $object::STATUS_DRAFT && ($action == 'editmulticurrencyrate' || $action == 'actualizemulticurrencyrate') && $usercancreate) { + if ($action == 'actualizemulticurrencyrate') { list($object->fk_multicurrency, $object->multicurrency_tx) = MultiCurrency::getIdAndTxFromCode($object->db, $object->multicurrency_code); } - $form->form_multicurrency_rate($_SERVER['PHP_SELF'] . '?id=' . $object->id, $object->multicurrency_tx, 'multicurrency_tx', $object->multicurrency_code); + $form->form_multicurrency_rate($_SERVER['PHP_SELF'].'?id='.$object->id, $object->multicurrency_tx, 'multicurrency_tx', $object->multicurrency_code); } else { - $form->form_multicurrency_rate($_SERVER['PHP_SELF'] . '?id=' . $object->id, $object->multicurrency_tx, 'none', $object->multicurrency_code); + $form->form_multicurrency_rate($_SERVER['PHP_SELF'].'?id='.$object->id, $object->multicurrency_tx, 'none', $object->multicurrency_code); if ($object->statut == $object::STATUS_DRAFT && $object->multicurrency_code && $object->multicurrency_code != $conf->currency) { print '
        '; print ''.$langs->trans("ActualizeCurrency").''; @@ -2250,13 +2250,13 @@ if ($action == 'create') print $langs->trans('OutstandingBill'); print '
'; $arrayoutstandingbills = $soc->getOutstandingBills(); - print price($arrayoutstandingbills['opened']) . ' / '; + print price($arrayoutstandingbills['opened']).' / '; print price($soc->outstanding_limit, 0, $langs, 1, - 1, - 1, $conf->currency); print '
'; @@ -2276,19 +2276,19 @@ if ($action == 'create') print '
' . $langs->trans("CalculatedWeight") . '
'.$langs->trans("CalculatedWeight").''; - print showDimensionInBestUnit($totalWeight, 0, "weight", $langs, isset($conf->global->MAIN_WEIGHT_DEFAULT_ROUND)?$conf->global->MAIN_WEIGHT_DEFAULT_ROUND:-1, isset($conf->global->MAIN_WEIGHT_DEFAULT_UNIT)?$conf->global->MAIN_WEIGHT_DEFAULT_UNIT:'no'); + print showDimensionInBestUnit($totalWeight, 0, "weight", $langs, isset($conf->global->MAIN_WEIGHT_DEFAULT_ROUND) ? $conf->global->MAIN_WEIGHT_DEFAULT_ROUND : -1, isset($conf->global->MAIN_WEIGHT_DEFAULT_UNIT) ? $conf->global->MAIN_WEIGHT_DEFAULT_UNIT : 'no'); print '
' . $langs->trans("CalculatedVolume") . '
'.$langs->trans("CalculatedVolume").''; - print showDimensionInBestUnit($totalVolume, 0, "volume", $langs, isset($conf->global->MAIN_VOLUME_DEFAULT_ROUND)?$conf->global->MAIN_VOLUME_DEFAULT_ROUND:-1, isset($conf->global->MAIN_VOLUME_DEFAULT_UNIT)?$conf->global->MAIN_VOLUME_DEFAULT_UNIT:'no'); + print showDimensionInBestUnit($totalVolume, 0, "volume", $langs, isset($conf->global->MAIN_VOLUME_DEFAULT_ROUND) ? $conf->global->MAIN_VOLUME_DEFAULT_ROUND : -1, isset($conf->global->MAIN_VOLUME_DEFAULT_UNIT) ? $conf->global->MAIN_VOLUME_DEFAULT_UNIT : 'no'); print '
'; @@ -2330,48 +2330,48 @@ if ($action == 'create') if (!empty($conf->multicurrency->enabled) && ($object->multicurrency_code != $conf->currency)) { // Multicurrency Amount HT - 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)) . '
'.$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)).'
' . $form->editfieldkey('MulticurrencyAmountVAT', 'multicurrency_total_tva', '', $object, 0) . '' . price($object->multicurrency_total_tva, '', $langs, 0, - 1, - 1, (!empty($object->multicurrency_code) ? $object->multicurrency_code : $conf->currency)) . '
'.$form->editfieldkey('MulticurrencyAmountVAT', 'multicurrency_total_tva', '', $object, 0).''.price($object->multicurrency_total_tva, '', $langs, 0, - 1, - 1, (!empty($object->multicurrency_code) ? $object->multicurrency_code : $conf->currency)).'
' . $form->editfieldkey('MulticurrencyAmountTTC', 'multicurrency_total_ttc', '', $object, 0) . '' . price($object->multicurrency_total_ttc, '', $langs, 0, - 1, - 1, (!empty($object->multicurrency_code) ? $object->multicurrency_code : $conf->currency)) . '
'.$form->editfieldkey('MulticurrencyAmountTTC', 'multicurrency_total_ttc', '', $object, 0).''.price($object->multicurrency_total_ttc, '', $langs, 0, - 1, - 1, (!empty($object->multicurrency_code) ? $object->multicurrency_code : $conf->currency)).'
' . $langs->trans('AmountHT') . '' . price($object->total_ht, '', $langs, 0, - 1, - 1, $conf->currency) . '
'.$langs->trans('AmountHT').''.price($object->total_ht, '', $langs, 0, - 1, - 1, $conf->currency).'
' . $langs->trans('AmountVAT') . '' . price($object->total_tva, '', $langs, 0, - 1, - 1, $conf->currency) . '
'.$langs->trans('AmountVAT').''.price($object->total_tva, '', $langs, 0, - 1, - 1, $conf->currency).'
' . $langs->transcountry("AmountLT1", $mysoc->country_code) . '' . price($object->total_localtax1, '', $langs, 0, - 1, - 1, $conf->currency) . '
'.$langs->transcountry("AmountLT1", $mysoc->country_code).''.price($object->total_localtax1, '', $langs, 0, - 1, - 1, $conf->currency).'
' . $langs->transcountry("AmountLT2", $mysoc->country_code) . '' . price($object->total_localtax2, '', $langs, 0, - 1, - 1, $conf->currency) . '
'.$langs->transcountry("AmountLT2", $mysoc->country_code).''.price($object->total_localtax2, '', $langs, 0, - 1, - 1, $conf->currency).'
' . $langs->trans('AmountTTC') . '' . price($object->total_ttc, '', $langs, 0, - 1, - 1, $conf->currency) . '
'.$langs->trans('AmountTTC').''.price($object->total_ttc, '', $langs, 0, - 1, - 1, $conf->currency).'
'; // Margin Infos - if (! empty($conf->margin->enabled)) + if (!empty($conf->margin->enabled)) { $formmargin->displayMarginInfos($object); } @@ -2391,16 +2391,16 @@ if ($action == 'create') print '

'; - 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'; + 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'; + include DOL_DOCUMENT_ROOT.'/core/tpl/bloc_showhide.tpl.php'; } /* @@ -2410,24 +2410,24 @@ if ($action == 'create') // Show object lines $result = $object->getLinesArray(); - print '
- - + print ' + + - + '; - if (! empty($conf->use_javascript_ajax) && $object->statut == Propal::STATUS_DRAFT) { - include DOL_DOCUMENT_ROOT . '/core/tpl/ajaxrow.tpl.php'; + if (!empty($conf->use_javascript_ajax) && $object->statut == Propal::STATUS_DRAFT) { + include DOL_DOCUMENT_ROOT.'/core/tpl/ajaxrow.tpl.php'; } print '
'; - if (! empty($object->lines) || ($object->statut == Propal::STATUS_DRAFT && $usercancreate && $action != 'selectlines' && $action != 'editline')) + if (!empty($object->lines) || ($object->statut == Propal::STATUS_DRAFT && $usercancreate && $action != 'selectlines' && $action != 'editline')) { print ''; } - if (! empty($object->lines)) + if (!empty($object->lines)) { $ret = $object->printObjectLines($action, $mysoc, $soc, $lineid, 1); } @@ -2445,7 +2445,7 @@ if ($action == 'create') } } - if (! empty($object->lines) || ($object->statut == Propal::STATUS_DRAFT && $usercancreate && $action != 'selectlines' && $action != 'editline')) + if (!empty($object->lines) || ($object->statut == Propal::STATUS_DRAFT && $usercancreate && $action != 'selectlines' && $action != 'editline')) { print '
'; } @@ -2475,10 +2475,10 @@ if ($action == 'create') { if ($usercanvalidate) { - print '' . $langs->trans('Validate') . ''; + print ''.$langs->trans('Validate').''; } else - print '' . $langs->trans('Validate') . ''; + print ''.$langs->trans('Validate').''; } // Create event /*if ($conf->agenda->enabled && ! empty($conf->global->MAIN_ADD_EVENT_ON_ELEMENT_CARD)) // Add hidden condition because this is not a "workflow" action so should appears somewhere else on page. @@ -2487,45 +2487,45 @@ if ($action == 'create') }*/ // Edit if ($object->statut == Propal::STATUS_VALIDATED && $usercancreate) { - print '' . $langs->trans('Modify') . ''; + print ''.$langs->trans('Modify').''; } // ReOpen if (($object->statut == Propal::STATUS_SIGNED || $object->statut == Propal::STATUS_NOTSIGNED || $object->statut == Propal::STATUS_BILLED) && $usercanclose) { - print 'global->MAIN_JUMP_TAG) ? '' : '#reopen') . '"'; - print '>' . $langs->trans('ReOpen') . ''; + print 'global->MAIN_JUMP_TAG) ? '' : '#reopen').'"'; + print '>'.$langs->trans('ReOpen').''; } // Send if ($object->statut == Propal::STATUS_VALIDATED || $object->statut == Propal::STATUS_SIGNED || !empty($conf->global->PROPOSAL_SENDBYEMAIL_FOR_ALL_STATUS)) { if ($usercansend) { - print '' . $langs->trans('SendMail') . ''; + print ''.$langs->trans('SendMail').''; } else - print '' . $langs->trans('SendMail') . ''; + print ''.$langs->trans('SendMail').''; } // Create a sale order - if (! empty($conf->commande->enabled) && $object->statut == Propal::STATUS_SIGNED) { + if (!empty($conf->commande->enabled) && $object->statut == Propal::STATUS_SIGNED) { if ($usercancreateorder) { - print '' . $langs->trans("AddOrder") . ''; + print ''.$langs->trans("AddOrder").''; } } // Create a purchase order - if (! empty($conf->global->WORKFLOW_CAN_CREATE_PURCHASE_ORDER_FROM_PROPOSAL)) + if (!empty($conf->global->WORKFLOW_CAN_CREATE_PURCHASE_ORDER_FROM_PROPOSAL)) { - if (! empty($conf->fournisseur->enabled) && $object->statut == Propal::STATUS_SIGNED) { + if (!empty($conf->fournisseur->enabled) && $object->statut == Propal::STATUS_SIGNED) { if ($usercancreatepurchaseorder) { - print '' . $langs->trans("AddPurchaseOrder") . ''; + print ''.$langs->trans("AddPurchaseOrder").''; } } } // Create an intervention - if (! empty($conf->service->enabled) && ! empty($conf->ficheinter->enabled) && $object->statut == Propal::STATUS_SIGNED) { + if (!empty($conf->service->enabled) && !empty($conf->ficheinter->enabled) && $object->statut == Propal::STATUS_SIGNED) { if ($usercancreateintervention) { $langs->load("interventions"); - print '' . $langs->trans("AddIntervention") . ''; + print ''.$langs->trans("AddIntervention").''; } } @@ -2534,16 +2534,16 @@ if ($action == 'create') $langs->load("contracts"); if ($usercancreatecontract) { - print '' . $langs->trans('AddContract') . ''; + print ''.$langs->trans('AddContract').''; } } // Create an invoice and classify billed if ($object->statut == Propal::STATUS_SIGNED) { - if (! empty($conf->facture->enabled) && $usercancreateinvoice) + if (!empty($conf->facture->enabled) && $usercancreateinvoice) { - print '' . $langs->trans("AddBill") . ''; + print ''.$langs->trans("AddBill").''; } $arrayofinvoiceforpropal = $object->getInvoiceArrayList(); @@ -2551,30 +2551,30 @@ if ($action == 'create') { if ($usercanclose) { - print 'socid . '">' . $langs->trans("ClassifyBilled") . ''; + print 'socid.'">'.$langs->trans("ClassifyBilled").''; } else { - print '' . $langs->trans("ClassifyBilled") . ''; + print ''.$langs->trans("ClassifyBilled").''; } } } // Set accepted/refused if ($object->statut == Propal::STATUS_VALIDATED && $usercanclose) { - print 'global->MAIN_JUMP_TAG) ? '' : '#close') . '"'; - print '>' . $langs->trans('SetAcceptedRefused') . ''; + print 'global->MAIN_JUMP_TAG) ? '' : '#close').'"'; + print '>'.$langs->trans('SetAcceptedRefused').''; } // Clone if ($usercancreate) { - print '' . $langs->trans("ToClone") . ''; + print ''.$langs->trans("ToClone").''; } // Delete if ($usercandelete) { - print '' . $langs->trans('Delete') . ''; + print ''.$langs->trans('Delete').''; } } } @@ -2593,8 +2593,8 @@ if ($action == 'create') * Documents generes */ $filename = dol_sanitizeFileName($object->ref); - $filedir = $conf->propal->multidir_output[$object->entity] . "/" . dol_sanitizeFileName($object->ref); - $urlsource = $_SERVER["PHP_SELF"] . "?id=" . $object->id; + $filedir = $conf->propal->multidir_output[$object->entity]."/".dol_sanitizeFileName($object->ref); + $urlsource = $_SERVER["PHP_SELF"]."?id=".$object->id; $genallowed = $usercanread; $delallowed = $usercancreate; @@ -2604,14 +2604,14 @@ if ($action == 'create') $linktoelem = $form->showLinkToObjectBlock($object, null, array('propal')); $compatibleImportElementsList = false; - if($user->rights->propal->creer && $object->statut == Propal::STATUS_DRAFT) + if ($user->rights->propal->creer && $object->statut == Propal::STATUS_DRAFT) { - $compatibleImportElementsList = array('commande','propal'); // import from linked elements + $compatibleImportElementsList = array('commande', 'propal'); // import from linked elements } $somethingshown = $form->showLinkedObjectBlock($object, $linktoelem, $compatibleImportElementsList); // Show online signature link - $useonlinesignature = $conf->global->MAIN_FEATURES_LEVEL; // Replace this with 1 when feature to make online signature is ok + $useonlinesignature = $conf->global->MAIN_FEATURES_LEVEL; // Replace this with 1 when feature to make online signature is ok if ($object->statut != Propal::STATUS_DRAFT && $useonlinesignature) { @@ -2621,7 +2621,7 @@ if ($action == 'create') } // Show direct download link - if ($object->statut != Propal::STATUS_DRAFT && ! empty($conf->global->PROPOSAL_ALLOW_EXTERNAL_DOWNLOAD)) + if ($object->statut != Propal::STATUS_DRAFT && !empty($conf->global->PROPOSAL_ALLOW_EXTERNAL_DOWNLOAD)) { print '
'."\n"; print showDirectDownloadLink($object).'
'; @@ -2630,7 +2630,7 @@ if ($action == 'create') print '
'; // List of actions on element - include_once DOL_DOCUMENT_ROOT . '/core/class/html.formactions.class.php'; + include_once DOL_DOCUMENT_ROOT.'/core/class/html.formactions.class.php'; $formactions = new FormActions($db); $somethingshown = $formactions->showactions($object, 'propal', $socid, 1); @@ -2638,8 +2638,8 @@ if ($action == 'create') } // Presend form - $modelmail='propal_send'; - $defaulttopic='SendPropalRef'; + $modelmail = 'propal_send'; + $defaulttopic = 'SendPropalRef'; $diroutput = $conf->propal->multidir_output[$object->entity]; $trackid = 'pro'.$object->id; diff --git a/htdocs/comm/propal/class/propal.class.php b/htdocs/comm/propal/class/propal.class.php index 0df1af873a8..ac5b35eef44 100644 --- a/htdocs/comm/propal/class/propal.class.php +++ b/htdocs/comm/propal/class/propal.class.php @@ -35,12 +35,12 @@ * \brief File of class to manage proposals */ -require_once DOL_DOCUMENT_ROOT .'/core/class/commonobject.class.php'; -require_once DOL_DOCUMENT_ROOT ."/core/class/commonobjectline.class.php"; -require_once DOL_DOCUMENT_ROOT .'/product/class/product.class.php'; -require_once DOL_DOCUMENT_ROOT .'/contact/class/contact.class.php'; -require_once DOL_DOCUMENT_ROOT .'/margin/lib/margins.lib.php'; -require_once DOL_DOCUMENT_ROOT .'/multicurrency/class/multicurrency.class.php'; +require_once DOL_DOCUMENT_ROOT.'/core/class/commonobject.class.php'; +require_once DOL_DOCUMENT_ROOT."/core/class/commonobjectline.class.php"; +require_once DOL_DOCUMENT_ROOT.'/product/class/product.class.php'; +require_once DOL_DOCUMENT_ROOT.'/contact/class/contact.class.php'; +require_once DOL_DOCUMENT_ROOT.'/margin/lib/margins.lib.php'; +require_once DOL_DOCUMENT_ROOT.'/multicurrency/class/multicurrency.class.php'; /** * Class to manage proposals @@ -50,27 +50,27 @@ class Propal extends CommonObject /** * @var string ID to identify managed object */ - public $element='propal'; + public $element = 'propal'; /** * @var string Name of table without prefix where object is stored */ - public $table_element='propal'; + public $table_element = 'propal'; /** * @var int Name of subtable line */ - public $table_element_line='propaldet'; + public $table_element_line = 'propaldet'; /** * @var int Field with ID of parent key if this field has a parent */ - public $fk_element ='fk_propal'; + public $fk_element = 'fk_propal'; /** * @var string String with name of icon for myobject. Must be the part after the 'object_' into object_myobject.png */ - public $picto='propal'; + public $picto = 'propal'; /** * 0=No test on entity, 1=Test with field entity, 2=Test with link by societe @@ -121,10 +121,9 @@ class Propal extends CommonObject */ public $datec; - /** - * Creation date - * @var int - */ + /** + * @var integer|string $date_creation; + */ public $date_creation; /** @@ -134,15 +133,13 @@ class Propal extends CommonObject public $datev; /** - * Validation date - * @var int - */ + * @var integer|string $date_validation; + */ public $date_validation; /** - * Date of the quote - * @var - */ + * @var integer|string date of the quote; + */ public $date; /** @@ -150,7 +147,13 @@ class Propal extends CommonObject * @see $date */ public $datep; + + /** + * @var integer|string $date_livraison; + */ public $date_livraison; + + public $fin_validite; public $user_author_id; @@ -192,8 +195,8 @@ class Propal extends CommonObject public $demand_reason_id; public $demand_reason_code; - public $products=array(); - public $extraparams=array(); + public $products = array(); + public $extraparams = array(); /** * @var PropaleLigne[] @@ -201,8 +204,8 @@ class Propal extends CommonObject public $lines = array(); public $line; - public $labelStatus=array(); - public $labelStatusShort=array(); + public $labelStatus = array(); + public $labelStatusShort = array(); public $specimen; @@ -239,7 +242,7 @@ class Propal extends CommonObject /** * Billed or processed quote */ - const STATUS_BILLED = 4; // Todo rename into STATUS_CLOSE ? + const STATUS_BILLED = 4; // Todo rename into STATUS_CLOSE ? /** @@ -251,7 +254,7 @@ class Propal extends CommonObject */ public function __construct($db, $socid = 0, $propalid = 0) { - global $conf,$langs; + global $conf, $langs; $this->db = $db; @@ -260,7 +263,7 @@ class Propal extends CommonObject $this->products = array(); - $this->duree_validite=$conf->global->PROPALE_VALIDITY_DURATION; + $this->duree_validite = $conf->global->PROPALE_VALIDITY_DURATION; } @@ -282,26 +285,26 @@ class Propal extends CommonObject // phpcs:enable global $conf, $mysoc; - if (! $qty) $qty = 1; + if (!$qty) $qty = 1; dol_syslog(get_class($this)."::add_product $idproduct, $qty, $remise_percent"); if ($idproduct > 0) { - $prod=new Product($this->db); + $prod = new Product($this->db); $prod->fetch($idproduct); $productdesc = $prod->description; $tva_tx = get_default_tva($mysoc, $this->thirdparty, $prod->id); $tva_npr = get_default_npr($mysoc, $this->thirdparty, $prod->id); - if (empty($tva_tx)) $tva_npr=0; - $vat_src_code = ''; // May be defined into tva_tx + if (empty($tva_tx)) $tva_npr = 0; + $vat_src_code = ''; // May be defined into tva_tx $localtax1_tx = get_localtax($tva_tx, 1, $mysoc, $this->thirdparty, $tva_npr); $localtax2_tx = get_localtax($tva_tx, 2, $mysoc, $this->thirdparty, $tva_npr); // multiprices - if($conf->global->PRODUIT_MULTIPRICES && $this->thirdparty->price_level) + if ($conf->global->PRODUIT_MULTIPRICES && $this->thirdparty->price_level) { $price = $prod->multiprices[$this->thirdparty->price_level]; } @@ -312,17 +315,17 @@ class Propal extends CommonObject $line = new PropaleLigne($this->db); - $line->fk_product=$idproduct; - $line->desc=$productdesc; - $line->qty=$qty; - $line->subprice=$price; - $line->remise_percent=$remise_percent; - $line->vat_src_code=$vat_src_code; - $line->tva_tx=$tva_tx; - $line->fk_unit=$prod->fk_unit; + $line->fk_product = $idproduct; + $line->desc = $productdesc; + $line->qty = $qty; + $line->subprice = $price; + $line->remise_percent = $remise_percent; + $line->vat_src_code = $vat_src_code; + $line->tva_tx = $tva_tx; + $line->fk_unit = $prod->fk_unit; if ($tva_npr) $line->info_bits = 1; - $this->lines[]=$line; + $this->lines[] = $line; } } @@ -343,46 +346,46 @@ class Propal extends CommonObject $this->db->begin(); - $remise=new DiscountAbsolute($this->db); - $result=$remise->fetch($idremise); + $remise = new DiscountAbsolute($this->db); + $result = $remise->fetch($idremise); if ($result > 0) { if ($remise->fk_facture) // Protection against multiple submission { - $this->error=$langs->trans("ErrorDiscountAlreadyUsed"); + $this->error = $langs->trans("ErrorDiscountAlreadyUsed"); $this->db->rollback(); return -5; } - $line=new PropaleLigne($this->db); + $line = new PropaleLigne($this->db); $this->line->context = $this->context; - $line->fk_propal=$this->id; - $line->fk_remise_except=$remise->id; - $line->desc=$remise->description; // Description ligne - $line->vat_src_code=$remise->vat_src_code; - $line->tva_tx=$remise->tva_tx; - $line->subprice=-$remise->amount_ht; - $line->fk_product=0; // Id produit predefined - $line->qty=1; - $line->remise=0; - $line->remise_percent=0; - $line->rang=-1; - $line->info_bits=2; + $line->fk_propal = $this->id; + $line->fk_remise_except = $remise->id; + $line->desc = $remise->description; // Description ligne + $line->vat_src_code = $remise->vat_src_code; + $line->tva_tx = $remise->tva_tx; + $line->subprice = -$remise->amount_ht; + $line->fk_product = 0; // Id produit predefined + $line->qty = 1; + $line->remise = 0; + $line->remise_percent = 0; + $line->rang = -1; + $line->info_bits = 2; // TODO deprecated - $line->price=-$remise->amount_ht; + $line->price = -$remise->amount_ht; $line->total_ht = -$remise->amount_ht; $line->total_tva = -$remise->amount_tva; $line->total_ttc = -$remise->amount_ttc; - $result=$line->insert(); + $result = $line->insert(); if ($result > 0) { - $result=$this->update_price(1); + $result = $this->update_price(1); if ($result > 0) { $this->db->commit(); @@ -396,7 +399,7 @@ class Propal extends CommonObject } else { - $this->error=$line->error; + $this->error = $line->error; $this->db->rollback(); return -2; } @@ -455,30 +458,30 @@ class Propal extends CommonObject 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($fk_parent_line) || $fk_parent_line < 0) $fk_parent_line=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($fk_parent_line) || $fk_parent_line < 0) $fk_parent_line = 0; - $remise_percent=price2num($remise_percent); - $qty=price2num($qty); - $pu_ht=price2num($pu_ht); - $pu_ht_devise=price2num($pu_ht_devise); - $pu_ttc=price2num($pu_ttc); + $remise_percent = price2num($remise_percent); + $qty = price2num($qty); + $pu_ht = price2num($pu_ht); + $pu_ht_devise = price2num($pu_ht_devise); + $pu_ttc = price2num($pu_ttc); if (!preg_match('/\((.*)\)/', $txtva)) { - $txtva = price2num($txtva); // $txtva can have format '5,1' or '5.1' or '5.1(XXX)', we must clean only if '5,1' + $txtva = price2num($txtva); // $txtva can have format '5,1' or '5.1' or '5.1(XXX)', we must clean only if '5,1' } - $txlocaltax1=price2num($txlocaltax1); - $txlocaltax2=price2num($txlocaltax2); - $pa_ht=price2num($pa_ht); - if ($price_base_type=='HT') + $txlocaltax1 = price2num($txlocaltax1); + $txlocaltax2 = price2num($txlocaltax2); + $pa_ht = price2num($pa_ht); + if ($price_base_type == 'HT') { - $pu=$pu_ht; + $pu = $pu_ht; } else { - $pu=$pu_ttc; + $pu = $pu_ttc; } // Check parameters @@ -486,22 +489,22 @@ class Propal extends CommonObject if ($date_start && $date_end && $date_start > $date_end) { $langs->load("errors"); - $this->error=$langs->trans('ErrorStartDateGreaterEnd'); + $this->error = $langs->trans('ErrorStartDateGreaterEnd'); return -1; } $this->db->begin(); - $product_type=$type; + $product_type = $type; if (!empty($fk_product)) { - $product=new Product($this->db); - $result=$product->fetch($fk_product); - $product_type=$product->type; + $product = new Product($this->db); + $result = $product->fetch($fk_product); + $product_type = $product->type; - if (! empty($conf->global->STOCK_MUST_BE_ENOUGH_FOR_PROPOSAL) && $product_type == 0 && $product->stock_reel < $qty) { + if (!empty($conf->global->STOCK_MUST_BE_ENOUGH_FOR_PROPOSAL) && $product_type == 0 && $product->stock_reel < $qty) { $langs->load("errors"); - $this->error=$langs->trans('ErrorStockIsNotEnoughToAddProductOnProposal', $product->ref); + $this->error = $langs->trans('ErrorStockIsNotEnoughToAddProductOnProposal', $product->ref); $this->db->rollback(); return -3; } @@ -512,17 +515,17 @@ class Propal extends CommonObject // TRES IMPORTANT: C'est au moment de l'insertion ligne qu'on doit stocker // la part ht, tva et ttc, et ce au niveau de la ligne qui a son propre taux tva. - $localtaxes_type=getLocalTaxesFromRate($txtva, 0, $this->thirdparty, $mysoc); + $localtaxes_type = getLocalTaxesFromRate($txtva, 0, $this->thirdparty, $mysoc); // Clean vat code - $vat_src_code=''; + $vat_src_code = ''; if (preg_match('/\((.*)\)/', $txtva, $reg)) { $vat_src_code = $reg[1]; - $txtva = preg_replace('/\s*\(.*\)/', '', $txtva); // Remove code into vatrate. + $txtva = preg_replace('/\s*\(.*\)/', '', $txtva); // Remove code into vatrate. } - $tabprice=calcul_price_total($qty, $pu, $remise_percent, $txtva, $txlocaltax1, $txlocaltax2, 0, $price_base_type, $info_bits, $product_type, $mysoc, $localtaxes_type, 100, $this->multicurrency_tx, $pu_ht_devise); + $tabprice = calcul_price_total($qty, $pu, $remise_percent, $txtva, $txlocaltax1, $txlocaltax2, 0, $price_base_type, $info_bits, $product_type, $mysoc, $localtaxes_type, 100, $this->multicurrency_tx, $pu_ht_devise); $total_ht = $tabprice[0]; $total_tva = $tabprice[1]; @@ -558,39 +561,39 @@ class Propal extends CommonObject } // Insert line - $this->line=new PropaleLigne($this->db); + $this->line = new PropaleLigne($this->db); $this->line->context = $this->context; - $this->line->fk_propal=$this->id; - $this->line->label=$label; - $this->line->desc=$desc; - $this->line->qty=$qty; + $this->line->fk_propal = $this->id; + $this->line->label = $label; + $this->line->desc = $desc; + $this->line->qty = $qty; - $this->line->vat_src_code=$vat_src_code; - $this->line->tva_tx=$txtva; - $this->line->localtax1_tx=($total_localtax1?$localtaxes_type[1]:0); - $this->line->localtax2_tx=($total_localtax2?$localtaxes_type[3]:0); + $this->line->vat_src_code = $vat_src_code; + $this->line->tva_tx = $txtva; + $this->line->localtax1_tx = ($total_localtax1 ? $localtaxes_type[1] : 0); + $this->line->localtax2_tx = ($total_localtax2 ? $localtaxes_type[3] : 0); $this->line->localtax1_type = $localtaxes_type[0]; $this->line->localtax2_type = $localtaxes_type[2]; - $this->line->fk_product=$fk_product; - $this->line->product_type=$type; - $this->line->fk_remise_except=$fk_remise_except; - $this->line->remise_percent=$remise_percent; - $this->line->subprice=$pu_ht; - $this->line->rang=$ranktouse; - $this->line->info_bits=$info_bits; - $this->line->total_ht=$total_ht; - $this->line->total_tva=$total_tva; - $this->line->total_localtax1=$total_localtax1; - $this->line->total_localtax2=$total_localtax2; - $this->line->total_ttc=$total_ttc; - $this->line->special_code=$special_code; - $this->line->fk_parent_line=$fk_parent_line; - $this->line->fk_unit=$fk_unit; + $this->line->fk_product = $fk_product; + $this->line->product_type = $type; + $this->line->fk_remise_except = $fk_remise_except; + $this->line->remise_percent = $remise_percent; + $this->line->subprice = $pu_ht; + $this->line->rang = $ranktouse; + $this->line->info_bits = $info_bits; + $this->line->total_ht = $total_ht; + $this->line->total_tva = $total_tva; + $this->line->total_localtax1 = $total_localtax1; + $this->line->total_localtax2 = $total_localtax2; + $this->line->total_ttc = $total_ttc; + $this->line->special_code = $special_code; + $this->line->fk_parent_line = $fk_parent_line; + $this->line->fk_unit = $fk_unit; - $this->line->date_start=$date_start; - $this->line->date_end=$date_end; + $this->line->date_start = $date_start; + $this->line->date_end = $date_end; $this->line->fk_fournprice = $fk_fournprice; $this->line->pa_ht = $pa_ht; @@ -599,47 +602,47 @@ class Propal extends CommonObject $this->line->origin = $origin; // Multicurrency - $this->line->fk_multicurrency = $this->fk_multicurrency; - $this->line->multicurrency_code = $this->multicurrency_code; + $this->line->fk_multicurrency = $this->fk_multicurrency; + $this->line->multicurrency_code = $this->multicurrency_code; $this->line->multicurrency_subprice = $pu_ht_devise; $this->line->multicurrency_total_ht = $multicurrency_total_ht; $this->line->multicurrency_total_tva = $multicurrency_total_tva; $this->line->multicurrency_total_ttc = $multicurrency_total_ttc; // Mise en option de la ligne - if (empty($qty) && empty($special_code)) $this->line->special_code=3; + if (empty($qty) && empty($special_code)) $this->line->special_code = 3; // TODO deprecated - $this->line->price=$price; - $this->line->remise=$remise; + $this->line->price = $price; + $this->line->remise = $remise; - if (is_array($array_options) && count($array_options)>0) { - $this->line->array_options=$array_options; + if (is_array($array_options) && count($array_options) > 0) { + $this->line->array_options = $array_options; } - $result=$this->line->insert(); + $result = $this->line->insert(); 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 propale meme - $result=$this->update_price(1, 'auto', 0, $mysoc); // This method is designed to add line from user input so total calculation must be done using 'auto' mode. + $result = $this->update_price(1, 'auto', 0, $mysoc); // This method is designed to add line from user input so total calculation must be done using 'auto' mode. if ($result > 0) { $this->db->commit(); - return $this->line->rowid; + return $this->line->id; } else { - $this->error=$this->db->error(); + $this->error = $this->db->error(); $this->db->rollback(); return -1; } } else { - $this->error=$this->line->error; + $this->error = $this->line->error; $this->db->rollback(); return -2; } @@ -689,21 +692,21 @@ class Propal extends CommonObject include_once DOL_DOCUMENT_ROOT.'/core/lib/price.lib.php'; // Clean parameters - $remise_percent=price2num($remise_percent); - $qty=price2num($qty); + $remise_percent = price2num($remise_percent); + $qty = price2num($qty); $pu = price2num($pu); - $pu_ht_devise=price2num($pu_ht_devise); + $pu_ht_devise = price2num($pu_ht_devise); $txtva = price2num($txtva); - $txlocaltax1=price2num($txlocaltax1); - $txlocaltax2=price2num($txlocaltax2); - $pa_ht=price2num($pa_ht); - if (empty($qty) && empty($special_code)) $special_code=3; // Set option tag - if (! empty($qty) && $special_code == 3) $special_code=0; // Remove option tag - if (empty($type)) $type=0; + $txlocaltax1 = price2num($txlocaltax1); + $txlocaltax2 = price2num($txlocaltax2); + $pa_ht = price2num($pa_ht); + if (empty($qty) && empty($special_code)) $special_code = 3; // Set option tag + if (!empty($qty) && $special_code == 3) $special_code = 0; // Remove option tag + if (empty($type)) $type = 0; if ($date_start && $date_end && $date_start > $date_end) { $langs->load("errors"); - $this->error=$langs->trans('ErrorStartDateGreaterEnd'); + $this->error = $langs->trans('ErrorStartDateGreaterEnd'); return -1; } @@ -716,17 +719,17 @@ class Propal extends CommonObject // TRES IMPORTANT: C'est au moment de l'insertion ligne qu'on doit stocker // la part ht, tva et ttc, et ce au niveau de la ligne qui a son propre taux tva. - $localtaxes_type=getLocalTaxesFromRate($txtva, 0, $this->thirdparty, $mysoc); + $localtaxes_type = getLocalTaxesFromRate($txtva, 0, $this->thirdparty, $mysoc); // Clean vat code - $vat_src_code=''; + $vat_src_code = ''; if (preg_match('/\((.*)\)/', $txtva, $reg)) { $vat_src_code = $reg[1]; - $txtva = preg_replace('/\s*\(.*\)/', '', $txtva); // Remove code into vatrate. + $txtva = preg_replace('/\s*\(.*\)/', '', $txtva); // Remove code into vatrate. } - $tabprice=calcul_price_total($qty, $pu, $remise_percent, $txtva, $txlocaltax1, $txlocaltax2, 0, $price_base_type, $info_bits, $type, $mysoc, $localtaxes_type, 100, $this->multicurrency_tx, $pu_ht_devise); + $tabprice = calcul_price_total($qty, $pu, $remise_percent, $txtva, $txlocaltax1, $txlocaltax2, 0, $price_base_type, $info_bits, $type, $mysoc, $localtaxes_type, 100, $this->multicurrency_tx, $pu_ht_devise); $total_ht = $tabprice[0]; $total_tva = $tabprice[1]; $total_ttc = $tabprice[2]; @@ -763,19 +766,19 @@ class Propal extends CommonObject $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; } - $this->line->rowid = $rowid; + $this->line->id = $rowid; $this->line->label = $label; - $this->line->desc = $desc; - $this->line->qty = $qty; + $this->line->desc = $desc; + $this->line->qty = $qty; $this->line->product_type = $type; $this->line->vat_src_code = $vat_src_code; - $this->line->tva_tx = $txtva; + $this->line->tva_tx = $txtva; $this->line->localtax1_tx = $txlocaltax1; $this->line->localtax2_tx = $txlocaltax2; $this->line->localtax1_type = $localtaxes_type[0]; @@ -789,23 +792,23 @@ class Propal extends CommonObject $this->line->total_localtax1 = $total_localtax1; $this->line->total_localtax2 = $total_localtax2; $this->line->total_ttc = $total_ttc; - $this->line->special_code = $special_code; + $this->line->special_code = $special_code; $this->line->fk_parent_line = $fk_parent_line; - $this->line->skip_update_total = $skip_update_total; - $this->line->fk_unit = $fk_unit; + $this->line->skip_update_total = $skip_update_total; + $this->line->fk_unit = $fk_unit; $this->line->fk_fournprice = $fk_fournprice; $this->line->pa_ht = $pa_ht; - $this->line->date_start=$date_start; - $this->line->date_end=$date_end; + $this->line->date_start = $date_start; + $this->line->date_end = $date_end; // TODO deprecated - $this->line->price=$price; - $this->line->remise=$remise; + $this->line->price = $price; + $this->line->remise = $remise; - if (is_array($array_options) && count($array_options)>0) { - $this->line->array_options=$array_options; + if (is_array($array_options) && count($array_options) > 0) { + $this->line->array_options = $array_options; } // Multicurrency @@ -814,11 +817,11 @@ class Propal extends CommonObject $this->line->multicurrency_total_tva = $multicurrency_total_tva; $this->line->multicurrency_total_ttc = $multicurrency_total_ttc; - $result=$this->line->update($notrigger); + $result = $this->line->update($notrigger); 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'); $this->update_price(1); @@ -830,7 +833,7 @@ class Propal extends CommonObject } else { - $this->error=$this->line->error; + $this->error = $this->line->error; $this->db->rollback(); return -1; @@ -858,7 +861,7 @@ class Propal extends CommonObject { $this->db->begin(); - $line=new PropaleLigne($this->db); + $line = new PropaleLigne($this->db); // For triggers $line->fetch($lineid); @@ -878,7 +881,7 @@ class Propal extends CommonObject } else { - $this->error='ErrorDeleteLineNotAllowedByObjectStatus'; + $this->error = 'ErrorDeleteLineNotAllowedByObjectStatus'; return -2; } } @@ -894,19 +897,19 @@ class Propal extends CommonObject */ public function create($user, $notrigger = 0) { - global $conf,$hookmanager; - $error=0; + global $conf, $hookmanager; + $error = 0; - $now=dol_now(); + $now = dol_now(); // Clean parameters - if (empty($this->date)) $this->date=$this->datep; + if (empty($this->date)) $this->date = $this->datep; $this->fin_validite = $this->date + ($this->duree_validite * 24 * 3600); - if (empty($this->availability_id)) $this->availability_id=0; - if (empty($this->demand_reason_id)) $this->demand_reason_id=0; + if (empty($this->availability_id)) $this->availability_id = 0; + if (empty($this->demand_reason_id)) $this->demand_reason_id = 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, $this->date); + 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)) { @@ -918,21 +921,21 @@ class Propal extends CommonObject dol_syslog(get_class($this)."::create"); // Check parameters - $result=$this->fetch_thirdparty(); + $result = $this->fetch_thirdparty(); if ($result < 0) { - $this->error="Failed to fetch company"; + $this->error = "Failed to fetch company"; dol_syslog(get_class($this)."::create ".$this->error, LOG_ERR); return -3; } // Check parameters - if (! empty($this->ref)) // We check that ref is not already used + 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 + $result = self::isExistingObject($this->element, 0, $this->ref); // Check ref is not yet used if ($result > 0) { - $this->error='ErrorRefAlreadyExists'; + $this->error = 'ErrorRefAlreadyExists'; dol_syslog(get_class($this)."::create ".$this->error, LOG_WARNING); $this->db->rollback(); return -1; @@ -941,7 +944,7 @@ class Propal extends CommonObject if (empty($this->date)) { - $this->error="Date of proposal is required"; + $this->error = "Date of proposal is required"; dol_syslog(get_class($this)."::create ".$this->error, LOG_ERR); return -4; } @@ -951,103 +954,103 @@ class Propal extends CommonObject // Insert into database $sql = "INSERT INTO ".MAIN_DB_PREFIX."propal ("; - $sql.= "fk_soc"; - $sql.= ", price"; - $sql.= ", remise"; - $sql.= ", remise_percent"; - $sql.= ", remise_absolue"; - $sql.= ", tva"; - $sql.= ", total"; - $sql.= ", datep"; - $sql.= ", datec"; - $sql.= ", ref"; - $sql.= ", fk_user_author"; - $sql.= ", note_private"; - $sql.= ", note_public"; - $sql.= ", model_pdf"; - $sql.= ", fin_validite"; - $sql.= ", fk_cond_reglement"; - $sql.= ", fk_mode_reglement"; - $sql.= ", fk_account"; - $sql.= ", ref_client"; - $sql.= ", date_livraison"; - $sql.= ", fk_shipping_method"; - $sql.= ", fk_availability"; - $sql.= ", fk_input_reason"; - $sql.= ", fk_projet"; - $sql.= ", fk_incoterms"; - $sql.= ", location_incoterms"; - $sql.= ", entity"; - $sql.= ", fk_multicurrency"; - $sql.= ", multicurrency_code"; - $sql.= ", multicurrency_tx"; - $sql.= ") "; - $sql.= " VALUES ("; - $sql.= $this->socid; - $sql.= ", 0"; - $sql.= ", ".$this->remise; - $sql.= ", ".($this->remise_percent?$this->db->escape($this->remise_percent):'NULL'); - $sql.= ", ".($this->remise_absolue?$this->db->escape($this->remise_absolue):'NULL'); - $sql.= ", 0"; - $sql.= ", 0"; - $sql.= ", '".$this->db->idate($this->date)."'"; - $sql.= ", '".$this->db->idate($now)."'"; - $sql.= ", '(PROV)'"; - $sql.= ", ".($user->id > 0 ? "'".$user->id."'":"NULL"); - $sql.= ", '".$this->db->escape($this->note_private)."'"; - $sql.= ", '".$this->db->escape($this->note_public)."'"; - $sql.= ", '".$this->db->escape($this->modelpdf)."'"; - $sql.= ", ".($this->fin_validite!=''?"'".$this->db->idate($this->fin_validite)."'":"NULL"); - $sql.= ", ".($this->cond_reglement_id > 0 ? $this->cond_reglement_id : 'NULL'); - $sql.= ", ".($this->mode_reglement_id > 0 ? $this->mode_reglement_id : 'NULL'); - $sql.= ", ".($this->fk_account>0?$this->fk_account:'NULL'); - $sql.= ", '".$this->db->escape($this->ref_client)."'"; - $sql.= ", ".($this->date_livraison!=''?"'".$this->db->idate($this->date_livraison)."'":"NULL"); - $sql.= ", ".($this->shipping_method_id>0?$this->shipping_method_id:'NULL'); - $sql.= ", ".$this->availability_id; - $sql.= ", ".$this->demand_reason_id; - $sql.= ", ".($this->fk_project?$this->fk_project:"null"); - $sql.= ", ".(int) $this->fk_incoterms; - $sql.= ", '".$this->db->escape($this->location_incoterms)."'"; - $sql.= ", ".setEntity($this); - $sql.= ", ".(int) $this->fk_multicurrency; - $sql.= ", '".$this->db->escape($this->multicurrency_code)."'"; - $sql.= ", ".(double) $this->multicurrency_tx; - $sql.= ")"; + $sql .= "fk_soc"; + $sql .= ", price"; + $sql .= ", remise"; + $sql .= ", remise_percent"; + $sql .= ", remise_absolue"; + $sql .= ", tva"; + $sql .= ", total"; + $sql .= ", datep"; + $sql .= ", datec"; + $sql .= ", ref"; + $sql .= ", fk_user_author"; + $sql .= ", note_private"; + $sql .= ", note_public"; + $sql .= ", model_pdf"; + $sql .= ", fin_validite"; + $sql .= ", fk_cond_reglement"; + $sql .= ", fk_mode_reglement"; + $sql .= ", fk_account"; + $sql .= ", ref_client"; + $sql .= ", date_livraison"; + $sql .= ", fk_shipping_method"; + $sql .= ", fk_availability"; + $sql .= ", fk_input_reason"; + $sql .= ", fk_projet"; + $sql .= ", fk_incoterms"; + $sql .= ", location_incoterms"; + $sql .= ", entity"; + $sql .= ", fk_multicurrency"; + $sql .= ", multicurrency_code"; + $sql .= ", multicurrency_tx"; + $sql .= ") "; + $sql .= " VALUES ("; + $sql .= $this->socid; + $sql .= ", 0"; + $sql .= ", ".$this->remise; + $sql .= ", ".($this->remise_percent ? $this->db->escape($this->remise_percent) : 'NULL'); + $sql .= ", ".($this->remise_absolue ? $this->db->escape($this->remise_absolue) : 'NULL'); + $sql .= ", 0"; + $sql .= ", 0"; + $sql .= ", '".$this->db->idate($this->date)."'"; + $sql .= ", '".$this->db->idate($now)."'"; + $sql .= ", '(PROV)'"; + $sql .= ", ".($user->id > 0 ? "'".$user->id."'" : "NULL"); + $sql .= ", '".$this->db->escape($this->note_private)."'"; + $sql .= ", '".$this->db->escape($this->note_public)."'"; + $sql .= ", '".$this->db->escape($this->modelpdf)."'"; + $sql .= ", ".($this->fin_validite != '' ? "'".$this->db->idate($this->fin_validite)."'" : "NULL"); + $sql .= ", ".($this->cond_reglement_id > 0 ? $this->cond_reglement_id : 'NULL'); + $sql .= ", ".($this->mode_reglement_id > 0 ? $this->mode_reglement_id : 'NULL'); + $sql .= ", ".($this->fk_account > 0 ? $this->fk_account : 'NULL'); + $sql .= ", '".$this->db->escape($this->ref_client)."'"; + $sql .= ", ".($this->date_livraison != '' ? "'".$this->db->idate($this->date_livraison)."'" : "NULL"); + $sql .= ", ".($this->shipping_method_id > 0 ? $this->shipping_method_id : 'NULL'); + $sql .= ", ".$this->availability_id; + $sql .= ", ".$this->demand_reason_id; + $sql .= ", ".($this->fk_project ? $this->fk_project : "null"); + $sql .= ", ".(int) $this->fk_incoterms; + $sql .= ", '".$this->db->escape($this->location_incoterms)."'"; + $sql .= ", ".setEntity($this); + $sql .= ", ".(int) $this->fk_multicurrency; + $sql .= ", '".$this->db->escape($this->multicurrency_code)."'"; + $sql .= ", ".(double) $this->multicurrency_tx; + $sql .= ")"; dol_syslog(get_class($this)."::create", LOG_DEBUG); - $resql=$this->db->query($sql); + $resql = $this->db->query($sql); if ($resql) { $this->id = $this->db->last_insert_id(MAIN_DB_PREFIX."propal"); if ($this->id) { - $this->ref='(PROV'.$this->id.')'; + $this->ref = '(PROV'.$this->id.')'; $sql = 'UPDATE '.MAIN_DB_PREFIX."propal 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++; + $resql = $this->db->query($sql); + if (!$resql) $error++; - if (! empty($this->linkedObjectsIds) && empty($this->linked_objects)) // To use new linkedObjectsIds instead of old linked_objects + 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 + $this->linked_objects = $this->linkedObjectsIds; // TODO Replace linked_objects with linkedObjectsIds } // Add object linked - if (! $error && $this->id && is_array($this->linked_objects) && ! empty($this->linked_objects)) + if (!$error && $this->id && is_array($this->linked_objects) && !empty($this->linked_objects)) { - foreach($this->linked_objects as $origin => $tmp_origin_id) + 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) + foreach ($tmp_origin_id as $origin_id) { $ret = $this->add_object_linked($origin, $origin_id); - if (! $ret) + if (!$ret) { - $this->error=$this->db->lasterror(); + $this->error = $this->db->lasterror(); $error++; } } @@ -1056,9 +1059,9 @@ class Propal extends CommonObject { $origin_id = $tmp_origin_id; $ret = $this->add_object_linked($origin, $origin_id); - if (! $ret) + if (!$ret) { - $this->error=$this->db->lasterror(); + $this->error = $this->db->lasterror(); $error++; } } @@ -1069,14 +1072,14 @@ class Propal extends CommonObject * Insertion du detail des produits dans la base * Insert products detail in database */ - if (! $error) + if (!$error) { - $fk_parent_line=0; - $num=count($this->lines); + $fk_parent_line = 0; + $num = count($this->lines); - for ($i=0;$i<$num;$i++) + for ($i = 0; $i < $num; $i++) { - if (! is_object($this->lines[$i])) // If this->lines is not array of objects, coming from REST API + if (!is_object($this->lines[$i])) // If this->lines is not array of objects, coming from REST API { // Convert into object this->lines[$i]. $line = (object) $this->lines[$i]; } @@ -1090,7 +1093,7 @@ class Propal extends CommonObject } // 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.')'; $result = $this->addline( $line->desc, @@ -1122,7 +1125,7 @@ class Propal extends CommonObject if ($result < 0) { $error++; - $this->error=$this->db->error; + $this->error = $this->db->error; dol_print_error($this->db); break; } @@ -1144,20 +1147,20 @@ class Propal extends CommonObject $result=$this->db->query($sql); }*/ - if (! $error) + if (!$error) { // Mise a jour infos denormalisees - $resql=$this->update_price(1); + $resql = $this->update_price(1); if ($resql) { - $action='update'; + $action = 'update'; // Actions on extra fields - if (! $error) + if (!$error) { if (empty($conf->global->MAIN_EXTRAFIELDS_DISABLED)) // For avoid conflicts if trigger used { - $result=$this->insertExtraFields(); + $result = $this->insertExtraFields(); if ($result < 0) { $error++; @@ -1165,28 +1168,28 @@ class Propal extends CommonObject } } - if (! $error && ! $notrigger) + if (!$error && !$notrigger) { // Call trigger - $result=$this->call_trigger('PROPAL_CREATE', $user); + $result = $this->call_trigger('PROPAL_CREATE', $user); if ($result < 0) { $error++; } // End call triggers } } else { - $this->error=$this->db->lasterror(); + $this->error = $this->db->lasterror(); $error++; } } } else { - $this->error=$this->db->lasterror(); + $this->error = $this->db->lasterror(); $error++; } - if (! $error) + if (!$error) { $this->db->commit(); dol_syslog(get_class($this)."::create done id=".$this->id); @@ -1200,7 +1203,7 @@ class Propal extends CommonObject } else { - $this->error=$this->db->lasterror(); + $this->error = $this->db->lasterror(); $this->db->rollback(); return -1; } @@ -1219,7 +1222,7 @@ class Propal extends CommonObject { // phpcs:enable // i love this function because $this->products is not used in create function... - $this->products=$this->lines; + $this->products = $this->lines; return $this->create($user); } @@ -1233,12 +1236,12 @@ class Propal extends CommonObject */ public function createFromClone(User $user, $socid = 0) { - global $conf,$hookmanager; + global $conf, $hookmanager; dol_include_once('/projet/class/project.class.php'); - $error=0; - $now=dol_now(); + $error = 0; + $now = dol_now(); dol_syslog(__METHOD__, LOG_DEBUG); @@ -1250,17 +1253,17 @@ class Propal extends CommonObject $object->fetch($this->id); $object->fetch_lines(); - $objsoc=new Societe($this->db); + $objsoc = new Societe($this->db); // Change socid if needed - if (! empty($socid) && $socid != $object->socid) + if (!empty($socid) && $socid != $object->socid) { if ($objsoc->fetch($socid) > 0) { - $object->socid = $objsoc->id; - $object->cond_reglement_id = (! empty($objsoc->cond_reglement_id) ? $objsoc->cond_reglement_id : 0); - $object->mode_reglement_id = (! empty($objsoc->mode_reglement_id) ? $objsoc->mode_reglement_id : 0); - $object->fk_delivery_address = ''; + $object->socid = $objsoc->id; + $object->cond_reglement_id = (!empty($objsoc->cond_reglement_id) ? $objsoc->cond_reglement_id : 0); + $object->mode_reglement_id = (!empty($objsoc->mode_reglement_id) ? $objsoc->mode_reglement_id : 0); + $object->fk_delivery_address = ''; /*if (!empty($conf->projet->enabled)) { @@ -1272,11 +1275,11 @@ class Propal extends CommonObject $clonedObj->fk_project = ''; } }*/ - $object->fk_project = ''; // A cloned proposal is set by default to no project. + $object->fk_project = ''; // A cloned proposal is set by default to no project. } // reset ref_client - $object->ref_client = ''; + $object->ref_client = ''; // TODO Change product price if multi-prices } @@ -1285,25 +1288,25 @@ class Propal extends CommonObject $objsoc->fetch($object->socid); } - $object->id=0; - $object->ref=''; - $object->statut=self::STATUS_DRAFT; + $object->id = 0; + $object->ref = ''; + $object->statut = self::STATUS_DRAFT; // Clear fields - $object->user_author = $user->id; - $object->user_valid = ''; - $object->date = $now; - $object->datep = $now; // deprecated - $object->fin_validite = $object->date + ($object->duree_validite * 24 * 3600); - if (empty($conf->global->MAIN_KEEP_REF_CUSTOMER_ON_CLONING)) $object->ref_client = ''; - if ($conf->global->MAIN_DONT_KEEP_NOTE_ON_CLONING==1) + $object->user_author = $user->id; + $object->user_valid = ''; + $object->date = $now; + $object->datep = $now; // deprecated + $object->fin_validite = $object->date + ($object->duree_validite * 24 * 3600); + if (empty($conf->global->MAIN_KEEP_REF_CUSTOMER_ON_CLONING)) $object->ref_client = ''; + if ($conf->global->MAIN_DONT_KEEP_NOTE_ON_CLONING == 1) { - $object->note_private = ''; - $object->note_public = ''; - } + $object->note_private = ''; + $object->note_public = ''; + } // Create clone - $object->context['createfromclone']='createfromclone'; - $result=$object->create($user); + $object->context['createfromclone'] = 'createfromclone'; + $result = $object->create($user); if ($result < 0) { $this->error = $object->error; @@ -1311,7 +1314,7 @@ class Propal extends CommonObject $error++; } - if (! $error) + if (!$error) { // copy internal contacts if ($object->copy_linked_contact($this, 'internal') < 0) @@ -1320,7 +1323,7 @@ class Propal extends CommonObject } } - if (! $error) + if (!$error) { // copy external contacts if same company if ($this->socid == $object->socid) @@ -1330,14 +1333,14 @@ class Propal extends CommonObject } } - if (! $error) + if (!$error) { // Hook of thirdparty module if (is_object($hookmanager)) { - $parameters=array('objFrom'=>$this,'clonedObj'=>$object); - $action=''; - $reshook=$hookmanager->executeHooks('createFrom', $parameters, $object, $action); // Note that $action and $object may have been modified by some hooks + $parameters = array('objFrom'=>$this, 'clonedObj'=>$object); + $action = ''; + $reshook = $hookmanager->executeHooks('createFrom', $parameters, $object, $action); // Note that $action and $object may have been modified by some hooks if ($reshook < 0) $error++; } } @@ -1345,7 +1348,7 @@ class Propal extends CommonObject unset($object->context['createfromclone']); // End - if (! $error) + if (!$error) { $this->db->commit(); return $object->id; @@ -1368,48 +1371,48 @@ class Propal extends CommonObject { $sql = "SELECT p.rowid, p.ref, p.entity, p.remise, p.remise_percent, p.remise_absolue, p.fk_soc"; - $sql.= ", p.total, p.tva, p.localtax1, p.localtax2, p.total_ht"; - $sql.= ", p.datec"; - $sql.= ", p.date_valid as datev"; - $sql.= ", p.datep as dp"; - $sql.= ", p.fin_validite as dfv"; - $sql.= ", p.date_livraison as date_livraison"; - $sql.= ", p.model_pdf, p.last_main_doc, p.ref_client, p.extraparams"; - $sql.= ", p.note_private, p.note_public"; - $sql.= ", p.fk_projet as fk_project, p.fk_statut"; - $sql.= ", p.fk_user_author, p.fk_user_valid, p.fk_user_cloture"; - $sql.= ", p.fk_delivery_address"; - $sql.= ", p.fk_availability"; - $sql.= ", p.fk_input_reason"; - $sql.= ", p.fk_cond_reglement"; - $sql.= ", p.fk_mode_reglement"; - $sql.= ', p.fk_account'; - $sql.= ", p.fk_shipping_method"; - $sql.= ", p.fk_incoterms, p.location_incoterms"; - $sql.= ", p.fk_multicurrency, p.multicurrency_code, p.multicurrency_tx, p.multicurrency_total_ht, p.multicurrency_total_tva, p.multicurrency_total_ttc"; - $sql.= ", p.tms as date_modification"; - $sql.= ", i.libelle as label_incoterms"; - $sql.= ", c.label as statut_label"; - $sql.= ", ca.code as availability_code, ca.label as availability"; - $sql.= ", dr.code as demand_reason_code, dr.label as demand_reason"; - $sql.= ", cr.code as cond_reglement_code, cr.libelle as cond_reglement, cr.libelle_facture as cond_reglement_libelle_doc"; - $sql.= ", cp.code as mode_reglement_code, cp.libelle as mode_reglement"; - $sql.= " FROM ".MAIN_DB_PREFIX."propal as p"; - $sql.= ' LEFT JOIN '.MAIN_DB_PREFIX.'c_propalst as c ON p.fk_statut = c.id'; - $sql.= ' LEFT JOIN '.MAIN_DB_PREFIX.'c_paiement as cp ON p.fk_mode_reglement = cp.id AND cp.entity IN ('.getEntity('c_paiement').')'; - $sql.= ' LEFT JOIN '.MAIN_DB_PREFIX.'c_payment_term as cr ON p.fk_cond_reglement = cr.rowid AND cr.entity IN ('.getEntity('c_payment_term').')'; - $sql.= ' LEFT JOIN '.MAIN_DB_PREFIX.'c_availability as ca ON p.fk_availability = ca.rowid'; - $sql.= ' LEFT JOIN '.MAIN_DB_PREFIX.'c_input_reason as dr ON p.fk_input_reason = dr.rowid'; - $sql.= ' LEFT JOIN '.MAIN_DB_PREFIX.'c_incoterms as i ON p.fk_incoterms = i.rowid'; + $sql .= ", p.total, p.tva, p.localtax1, p.localtax2, p.total_ht"; + $sql .= ", p.datec"; + $sql .= ", p.date_valid as datev"; + $sql .= ", p.datep as dp"; + $sql .= ", p.fin_validite as dfv"; + $sql .= ", p.date_livraison as date_livraison"; + $sql .= ", p.model_pdf, p.last_main_doc, p.ref_client, p.extraparams"; + $sql .= ", p.note_private, p.note_public"; + $sql .= ", p.fk_projet as fk_project, p.fk_statut"; + $sql .= ", p.fk_user_author, p.fk_user_valid, p.fk_user_cloture"; + $sql .= ", p.fk_delivery_address"; + $sql .= ", p.fk_availability"; + $sql .= ", p.fk_input_reason"; + $sql .= ", p.fk_cond_reglement"; + $sql .= ", p.fk_mode_reglement"; + $sql .= ', p.fk_account'; + $sql .= ", p.fk_shipping_method"; + $sql .= ", p.fk_incoterms, p.location_incoterms"; + $sql .= ", p.fk_multicurrency, p.multicurrency_code, p.multicurrency_tx, p.multicurrency_total_ht, p.multicurrency_total_tva, p.multicurrency_total_ttc"; + $sql .= ", p.tms as date_modification"; + $sql .= ", i.libelle as label_incoterms"; + $sql .= ", c.label as statut_label"; + $sql .= ", ca.code as availability_code, ca.label as availability"; + $sql .= ", dr.code as demand_reason_code, dr.label as demand_reason"; + $sql .= ", cr.code as cond_reglement_code, cr.libelle as cond_reglement, cr.libelle_facture as cond_reglement_libelle_doc"; + $sql .= ", cp.code as mode_reglement_code, cp.libelle as mode_reglement"; + $sql .= " FROM ".MAIN_DB_PREFIX."propal as p"; + $sql .= ' LEFT JOIN '.MAIN_DB_PREFIX.'c_propalst as c ON p.fk_statut = c.id'; + $sql .= ' LEFT JOIN '.MAIN_DB_PREFIX.'c_paiement as cp ON p.fk_mode_reglement = cp.id AND cp.entity IN ('.getEntity('c_paiement').')'; + $sql .= ' LEFT JOIN '.MAIN_DB_PREFIX.'c_payment_term as cr ON p.fk_cond_reglement = cr.rowid AND cr.entity IN ('.getEntity('c_payment_term').')'; + $sql .= ' LEFT JOIN '.MAIN_DB_PREFIX.'c_availability as ca ON p.fk_availability = ca.rowid'; + $sql .= ' LEFT JOIN '.MAIN_DB_PREFIX.'c_input_reason as dr ON p.fk_input_reason = dr.rowid'; + $sql .= ' LEFT JOIN '.MAIN_DB_PREFIX.'c_incoterms as i ON p.fk_incoterms = i.rowid'; if ($ref) { - $sql.= " WHERE p.entity IN (".getEntity('propal').")"; // Dont't use entity if you use rowid - $sql.= " AND p.ref='".$this->db->escape($ref)."'"; + $sql .= " WHERE p.entity IN (".getEntity('propal').")"; // Dont't use entity if you use rowid + $sql .= " AND p.ref='".$this->db->escape($ref)."'"; } - else $sql.= " WHERE p.rowid=".$rowid; + else $sql .= " WHERE p.rowid=".$rowid; dol_syslog(get_class($this)."::fetch", LOG_DEBUG); - $resql=$this->db->query($sql); + $resql = $this->db->query($sql); if ($resql) { if ($this->db->num_rows($resql)) @@ -1433,7 +1436,7 @@ class Propal extends CommonObject $this->socid = $obj->fk_soc; $this->fk_project = $obj->fk_project; $this->modelpdf = $obj->model_pdf; - $this->last_main_doc = $obj->last_main_doc; + $this->last_main_doc = $obj->last_main_doc; $this->note = $obj->note_private; // TODO deprecated $this->note_private = $obj->note_private; $this->note_public = $obj->note_public; @@ -1442,32 +1445,32 @@ class Propal extends CommonObject $this->datec = $this->db->jdate($obj->datec); // TODO deprecated $this->datev = $this->db->jdate($obj->datev); // TODO deprecated - $this->date_creation = $this->db->jdate($obj->datec); //Creation date - $this->date_validation = $this->db->jdate($obj->datev); //Validation date - $this->date_modification = $this->db->jdate($obj->date_modification); // tms - $this->date = $this->db->jdate($obj->dp); // Proposal date - $this->datep = $this->db->jdate($obj->dp); // deprecated + $this->date_creation = $this->db->jdate($obj->datec); //Creation date + $this->date_validation = $this->db->jdate($obj->datev); //Validation date + $this->date_modification = $this->db->jdate($obj->date_modification); // tms + $this->date = $this->db->jdate($obj->dp); // Proposal date + $this->datep = $this->db->jdate($obj->dp); // deprecated $this->fin_validite = $this->db->jdate($obj->dfv); $this->date_livraison = $this->db->jdate($obj->date_livraison); - $this->shipping_method_id = ($obj->fk_shipping_method>0)?$obj->fk_shipping_method:null; + $this->shipping_method_id = ($obj->fk_shipping_method > 0) ? $obj->fk_shipping_method : null; $this->availability_id = $obj->fk_availability; $this->availability_code = $obj->availability_code; $this->availability = $obj->availability; $this->demand_reason_id = $obj->fk_input_reason; $this->demand_reason_code = $obj->demand_reason_code; $this->demand_reason = $obj->demand_reason; - $this->fk_address = $obj->fk_delivery_address; + $this->fk_address = $obj->fk_delivery_address; $this->mode_reglement_id = $obj->fk_mode_reglement; $this->mode_reglement_code = $obj->mode_reglement_code; $this->mode_reglement = $obj->mode_reglement; - $this->fk_account = ($obj->fk_account>0)?$obj->fk_account:null; + $this->fk_account = ($obj->fk_account > 0) ? $obj->fk_account : null; $this->cond_reglement_id = $obj->fk_cond_reglement; $this->cond_reglement_code = $obj->cond_reglement_code; $this->cond_reglement = $obj->cond_reglement; $this->cond_reglement_doc = $obj->cond_reglement_libelle_doc; - $this->extraparams = (array) json_decode($obj->extraparams, true); + $this->extraparams = (array) json_decode($obj->extraparams, true); $this->user_author_id = $obj->fk_user_author; $this->user_valid_id = $obj->fk_user_valid; @@ -1480,9 +1483,9 @@ class Propal extends CommonObject // Multicurrency $this->fk_multicurrency = $obj->fk_multicurrency; - $this->multicurrency_code = $obj->multicurrency_code; + $this->multicurrency_code = $obj->multicurrency_code; $this->multicurrency_tx = $obj->multicurrency_tx; - $this->multicurrency_total_ht = $obj->multicurrency_total_ht; + $this->multicurrency_total_ht = $obj->multicurrency_total_ht; $this->multicurrency_total_tva = $obj->multicurrency_total_tva; $this->multicurrency_total_ttc = $obj->multicurrency_total_ttc; @@ -1502,7 +1505,7 @@ class Propal extends CommonObject /* * Lines */ - $result=$this->fetch_lines(); + $result = $this->fetch_lines(); if ($result < 0) { return -3; @@ -1511,12 +1514,12 @@ class Propal extends CommonObject return 1; } - $this->error="Record Not Found"; + $this->error = "Record Not Found"; return 0; } else { - $this->error=$this->db->lasterror(); + $this->error = $this->db->lasterror(); return -1; } } @@ -1532,15 +1535,15 @@ class Propal extends CommonObject { global $conf; - $error=0; + $error = 0; // Clean parameters - if (isset($this->ref)) $this->ref=trim($this->ref); - if (isset($this->ref_client)) $this->ref_client=trim($this->ref_client); - 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->modelpdf)) $this->modelpdf=trim($this->modelpdf); - 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_client)) $this->ref_client = trim($this->ref_client); + 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->modelpdf)) $this->modelpdf = trim($this->modelpdf); + if (isset($this->import_key)) $this->import_key = trim($this->import_key); // Check parameters // Put here code to add control on parameters values @@ -1548,51 +1551,51 @@ class Propal extends CommonObject // Update request $sql = "UPDATE ".MAIN_DB_PREFIX."propal SET"; - $sql.= " ref=".(isset($this->ref)?"'".$this->db->escape($this->ref)."'":"null").","; - $sql.= " ref_client=".(isset($this->ref_client)?"'".$this->db->escape($this->ref_client)."'":"null").","; - $sql.= " ref_ext=".(isset($this->ref_ext)?"'".$this->db->escape($this->ref_ext)."'":"null").","; - $sql.= " fk_soc=".(isset($this->socid)?$this->socid:"null").","; - $sql.= " datep=".(strval($this->datep)!='' ? "'".$this->db->idate($this->datep)."'" : 'null').","; - $sql.= " date_valid=".(strval($this->date_validation)!='' ? "'".$this->db->idate($this->date_validation)."'" : 'null').","; - $sql.= " tva=".(isset($this->total_tva)?$this->total_tva:"null").","; - $sql.= " localtax1=".(isset($this->total_localtax1)?$this->total_localtax1:"null").","; - $sql.= " localtax2=".(isset($this->total_localtax2)?$this->total_localtax2:"null").","; - $sql.= " total_ht=".(isset($this->total_ht)?$this->total_ht:"null").","; - $sql.= " total=".(isset($this->total_ttc)?$this->total_ttc:"null").","; - $sql.= " fk_statut=".(isset($this->statut)?$this->statut:"null").","; - $sql.= " fk_user_author=".(isset($this->user_author_id)?$this->user_author_id:"null").","; - $sql.= " fk_user_valid=".(isset($this->user_valid)?$this->user_valid:"null").","; - $sql.= " fk_projet=".(isset($this->fk_project)?$this->fk_project:"null").","; - $sql.= " fk_cond_reglement=".(isset($this->cond_reglement_id)?$this->cond_reglement_id:"null").","; - $sql.= " fk_mode_reglement=".(isset($this->mode_reglement_id)?$this->mode_reglement_id:"null").","; - $sql.= " note_private=".(isset($this->note_private)?"'".$this->db->escape($this->note_private)."'":"null").","; - $sql.= " note_public=".(isset($this->note_public)?"'".$this->db->escape($this->note_public)."'":"null").","; - $sql.= " model_pdf=".(isset($this->modelpdf)?"'".$this->db->escape($this->modelpdf)."'":"null").","; - $sql.= " import_key=".(isset($this->import_key)?"'".$this->db->escape($this->import_key)."'":"null").""; + $sql .= " ref=".(isset($this->ref) ? "'".$this->db->escape($this->ref)."'" : "null").","; + $sql .= " ref_client=".(isset($this->ref_client) ? "'".$this->db->escape($this->ref_client)."'" : "null").","; + $sql .= " ref_ext=".(isset($this->ref_ext) ? "'".$this->db->escape($this->ref_ext)."'" : "null").","; + $sql .= " fk_soc=".(isset($this->socid) ? $this->socid : "null").","; + $sql .= " datep=".(strval($this->datep) != '' ? "'".$this->db->idate($this->datep)."'" : 'null').","; + $sql .= " date_valid=".(strval($this->date_validation) != '' ? "'".$this->db->idate($this->date_validation)."'" : 'null').","; + $sql .= " tva=".(isset($this->total_tva) ? $this->total_tva : "null").","; + $sql .= " localtax1=".(isset($this->total_localtax1) ? $this->total_localtax1 : "null").","; + $sql .= " localtax2=".(isset($this->total_localtax2) ? $this->total_localtax2 : "null").","; + $sql .= " total_ht=".(isset($this->total_ht) ? $this->total_ht : "null").","; + $sql .= " total=".(isset($this->total_ttc) ? $this->total_ttc : "null").","; + $sql .= " fk_statut=".(isset($this->statut) ? $this->statut : "null").","; + $sql .= " fk_user_author=".(isset($this->user_author_id) ? $this->user_author_id : "null").","; + $sql .= " fk_user_valid=".(isset($this->user_valid) ? $this->user_valid : "null").","; + $sql .= " fk_projet=".(isset($this->fk_project) ? $this->fk_project : "null").","; + $sql .= " fk_cond_reglement=".(isset($this->cond_reglement_id) ? $this->cond_reglement_id : "null").","; + $sql .= " fk_mode_reglement=".(isset($this->mode_reglement_id) ? $this->mode_reglement_id : "null").","; + $sql .= " note_private=".(isset($this->note_private) ? "'".$this->db->escape($this->note_private)."'" : "null").","; + $sql .= " note_public=".(isset($this->note_public) ? "'".$this->db->escape($this->note_public)."'" : "null").","; + $sql .= " model_pdf=".(isset($this->modelpdf) ? "'".$this->db->escape($this->modelpdf)."'" : "null").","; + $sql .= " import_key=".(isset($this->import_key) ? "'".$this->db->escape($this->import_key)."'" : "null").""; - $sql.= " WHERE rowid=".$this->id; + $sql .= " WHERE rowid=".$this->id; $this->db->begin(); dol_syslog(get_class($this)."::update", LOG_DEBUG); $resql = $this->db->query($sql); - if (! $resql) { - $error++; $this->errors[]="Error ".$this->db->lasterror(); + if (!$resql) { + $error++; $this->errors[] = "Error ".$this->db->lasterror(); } - if (! $error && empty($conf->global->MAIN_EXTRAFIELDS_DISABLED) && is_array($this->array_options) && count($this->array_options)>0) + if (!$error && empty($conf->global->MAIN_EXTRAFIELDS_DISABLED) && is_array($this->array_options) && count($this->array_options) > 0) { - $result=$this->insertExtraFields(); + $result = $this->insertExtraFields(); if ($result < 0) { $error++; } } - if (! $error && ! $notrigger) + if (!$error && !$notrigger) { // Call trigger - $result=$this->call_trigger('PROPAL_MODIFY', $user); + $result = $this->call_trigger('PROPAL_MODIFY', $user); if ($result < 0) $error++; // End call triggers } @@ -1600,13 +1603,13 @@ class Propal extends CommonObject // Commit or rollback if ($error) { - foreach($this->errors as $errmsg) + foreach ($this->errors as $errmsg) { dol_syslog(get_class($this)."::update ".$errmsg, LOG_ERR); - $this->error.=($this->error?', '.$errmsg:$errmsg); + $this->error .= ($this->error ? ', '.$errmsg : $errmsg); } $this->db->rollback(); - return -1*$error; + return -1 * $error; } else { @@ -1629,20 +1632,20 @@ class Propal extends CommonObject { global $langs, $conf; // phpcs:enable - $this->lines=array(); + $this->lines = array(); $sql = 'SELECT d.rowid, d.fk_propal, d.fk_parent_line, d.label as custom_label, d.description, d.price, d.vat_src_code, d.tva_tx, d.localtax1_tx, d.localtax2_tx, d.localtax1_type, d.localtax2_type, d.qty, d.fk_remise_except, d.remise_percent, d.subprice, d.fk_product,'; - $sql.= ' d.info_bits, d.total_ht, d.total_tva, d.total_localtax1, d.total_localtax2, d.total_ttc, d.fk_product_fournisseur_price as fk_fournprice, d.buy_price_ht as pa_ht, d.special_code, d.rang, d.product_type,'; - $sql.= ' d.fk_unit,'; - $sql.= ' p.ref as product_ref, p.description as product_desc, p.fk_product_type, p.label as product_label, p.tobatch as product_batch,'; - $sql.= ' p.weight, p.weight_units, p.volume, p.volume_units,'; - $sql.= ' d.date_start, d.date_end,'; - $sql.= ' d.fk_multicurrency, d.multicurrency_code, d.multicurrency_subprice, d.multicurrency_total_ht, d.multicurrency_total_tva, d.multicurrency_total_ttc'; - $sql.= ' FROM '.MAIN_DB_PREFIX.'propaldet as d'; - $sql.= ' LEFT JOIN '.MAIN_DB_PREFIX.'product as p ON (d.fk_product = p.rowid)'; - $sql.= ' WHERE d.fk_propal = '.$this->id; + $sql .= ' d.info_bits, d.total_ht, d.total_tva, d.total_localtax1, d.total_localtax2, d.total_ttc, d.fk_product_fournisseur_price as fk_fournprice, d.buy_price_ht as pa_ht, d.special_code, d.rang, d.product_type,'; + $sql .= ' d.fk_unit,'; + $sql .= ' p.ref as product_ref, p.description as product_desc, p.fk_product_type, p.label as product_label, p.tobatch as product_batch,'; + $sql .= ' p.weight, p.weight_units, p.volume, p.volume_units,'; + $sql .= ' d.date_start, d.date_end,'; + $sql .= ' d.fk_multicurrency, d.multicurrency_code, d.multicurrency_subprice, d.multicurrency_total_ht, d.multicurrency_total_tva, d.multicurrency_total_ttc'; + $sql .= ' FROM '.MAIN_DB_PREFIX.'propaldet as d'; + $sql .= ' LEFT JOIN '.MAIN_DB_PREFIX.'product as p ON (d.fk_product = p.rowid)'; + $sql .= ' WHERE d.fk_propal = '.$this->id; if ($only_product) $sql .= ' AND p.fk_product_type = 0'; - $sql.= ' ORDER by d.rang'; + $sql .= ' ORDER by d.rang'; dol_syslog(get_class($this)."::fetch_lines", LOG_DEBUG); $result = $this->db->query($sql); @@ -1659,14 +1662,14 @@ class Propal extends CommonObject $line = new PropaleLigne($this->db); - $line->rowid = $objp->rowid; //Deprecated - $line->id = $objp->rowid; - $line->fk_propal = $objp->fk_propal; - $line->fk_parent_line = $objp->fk_parent_line; + $line->rowid = $objp->rowid; //Deprecated + $line->id = $objp->rowid; + $line->fk_propal = $objp->fk_propal; + $line->fk_parent_line = $objp->fk_parent_line; $line->product_type = $objp->product_type; $line->label = $objp->custom_label; - $line->desc = $objp->description; // Description ligne - $line->description = $objp->description; // Description ligne + $line->desc = $objp->description; // Description ligne + $line->description = $objp->description; // Description ligne $line->qty = $objp->qty; $line->vat_src_code = $objp->vat_src_code; $line->tva_tx = $objp->tva_tx; @@ -1677,7 +1680,7 @@ class Propal extends CommonObject $line->subprice = $objp->subprice; $line->fk_remise_except = $objp->fk_remise_except; $line->remise_percent = $objp->remise_percent; - $line->price = $objp->price; // TODO deprecated + $line->price = $objp->price; // TODO deprecated $line->info_bits = $objp->info_bits; $line->total_ht = $objp->total_ht; @@ -1685,9 +1688,9 @@ class Propal extends CommonObject $line->total_localtax1 = $objp->total_localtax1; $line->total_localtax2 = $objp->total_localtax2; $line->total_ttc = $objp->total_ttc; - $line->fk_fournprice = $objp->fk_fournprice; - $marginInfos = getMarginInfos($objp->subprice, $objp->remise_percent, $objp->tva_tx, $objp->localtax1_tx, $objp->localtax2_tx, $line->fk_fournprice, $objp->pa_ht); - $line->pa_ht = $marginInfos[0]; + $line->fk_fournprice = $objp->fk_fournprice; + $marginInfos = getMarginInfos($objp->subprice, $objp->remise_percent, $objp->tva_tx, $objp->localtax1_tx, $objp->localtax2_tx, $line->fk_fournprice, $objp->pa_ht); + $line->pa_ht = $marginInfos[0]; $line->marge_tx = $marginInfos[1]; $line->marque_tx = $marginInfos[2]; $line->special_code = $objp->special_code; @@ -1722,13 +1725,13 @@ class Propal extends CommonObject $line->fetch_optionals(); // multilangs - if (! empty($conf->global->MAIN_MULTILANGS) && ! empty($objp->fk_product) && ! empty($loadalsotranslation)) { + if (!empty($conf->global->MAIN_MULTILANGS) && !empty($objp->fk_product) && !empty($loadalsotranslation)) { $line = new Product($this->db); $line->fetch($objp->fk_product); $line->getMultiLangs(); } - $this->lines[$i] = $line; + $this->lines[$i] = $line; //dol_syslog("1 ".$line->fk_product); //print "xx $i ".$this->lines[$i]->fk_product; $i++; @@ -1740,7 +1743,7 @@ class Propal extends CommonObject } else { - $this->error=$this->db->lasterror(); + $this->error = $this->db->lasterror(); return -3; } } @@ -1758,7 +1761,7 @@ class Propal extends CommonObject require_once DOL_DOCUMENT_ROOT.'/core/lib/files.lib.php'; - $error=0; + $error = 0; // Protection if ($this->statut == self::STATUS_VALIDATED) @@ -1767,15 +1770,15 @@ class Propal extends CommonObject return 0; } - if (! ((empty($conf->global->MAIN_USE_ADVANCED_PERMS) && ! empty($user->rights->propal->creer)) - || (! empty($conf->global->MAIN_USE_ADVANCED_PERMS) && ! empty($user->rights->propal->propal_advance->validate)))) + if (!((empty($conf->global->MAIN_USE_ADVANCED_PERMS) && !empty($user->rights->propal->creer)) + || (!empty($conf->global->MAIN_USE_ADVANCED_PERMS) && !empty($user->rights->propal->propal_advance->validate)))) { - $this->error='ErrorPermissionDenied'; + $this->error = 'ErrorPermissionDenied'; dol_syslog(get_class($this)."::valid ".$this->error, LOG_ERR); return -1; } - $now=dol_now(); + $now = dol_now(); $this->db->begin(); @@ -1784,7 +1787,7 @@ class Propal extends CommonObject $soc->fetch($this->socid); // Define new ref - if (! $error && (preg_match('/^[\(]?PROV/i', $this->ref) || empty($this->ref))) // empty should not happened, but when it occurs, the test save life + if (!$error && (preg_match('/^[\(]?PROV/i', $this->ref) || empty($this->ref))) // empty should not happened, but when it occurs, the test save life { $num = $this->getNextNumRef($soc); } @@ -1795,28 +1798,28 @@ class Propal extends CommonObject $this->newref = $num; $sql = "UPDATE ".MAIN_DB_PREFIX."propal"; - $sql.= " SET ref = '".$num."',"; - $sql.= " fk_statut = ".self::STATUS_VALIDATED.", date_valid='".$this->db->idate($now)."', fk_user_valid=".$user->id; - $sql.= " WHERE rowid = ".$this->id." AND fk_statut = ".self::STATUS_DRAFT; + $sql .= " SET ref = '".$num."',"; + $sql .= " fk_statut = ".self::STATUS_VALIDATED.", date_valid='".$this->db->idate($now)."', fk_user_valid=".$user->id; + $sql .= " WHERE rowid = ".$this->id." AND fk_statut = ".self::STATUS_DRAFT; dol_syslog(get_class($this)."::valid", LOG_DEBUG); - $resql=$this->db->query($sql); - if (! $resql) + $resql = $this->db->query($sql); + if (!$resql) { dol_print_error($this->db); $error++; } // Trigger calls - if (! $error && ! $notrigger) + if (!$error && !$notrigger) { // Call trigger - $result=$this->call_trigger('PROPAL_VALIDATE', $user); + $result = $this->call_trigger('PROPAL_VALIDATE', $user); if ($result < 0) { $error++; } // End call triggers } - if (! $error) + if (!$error) { $this->oldref = $this->ref; @@ -1824,41 +1827,41 @@ class Propal extends CommonObject 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 = 'propale/".$this->db->escape($this->newref)."'"; - $sql.= " WHERE filename LIKE '".$this->db->escape($this->ref)."%' AND filepath = 'propale/".$this->db->escape($this->ref)."' and entity = ".$conf->entity; + $sql = 'UPDATE '.MAIN_DB_PREFIX."ecm_files set filename = CONCAT('".$this->db->escape($this->newref)."', SUBSTR(filename, ".(strlen($this->ref) + 1).")), filepath = 'propale/".$this->db->escape($this->newref)."'"; + $sql .= " WHERE filename LIKE '".$this->db->escape($this->ref)."%' AND filepath = 'propale/".$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->propal->multidir_output[$this->entity].'/'.$oldref; $dirdest = $conf->propal->multidir_output[$this->entity].'/'.$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)) { dol_syslog("Rename ok"); // Rename docs starting with $oldref with $newref - $listoffiles=dol_dir_list($dirdest, 'files', 1, '^'.preg_quote($oldref, '/')); - foreach($listoffiles as $fileentry) + $listoffiles = dol_dir_list($dirdest, 'files', 1, '^'.preg_quote($oldref, '/')); + foreach ($listoffiles as $fileentry) { - $dirsource=$fileentry['name']; - $dirdest=preg_replace('/^'.preg_quote($oldref, '/').'/', $newref, $dirsource); - $dirsource=$fileentry['path'].'/'.$dirsource; - $dirdest=$fileentry['path'].'/'.$dirdest; + $dirsource = $fileentry['name']; + $dirdest = preg_replace('/^'.preg_quote($oldref, '/').'/', $newref, $dirsource); + $dirsource = $fileentry['path'].'/'.$dirsource; + $dirdest = $fileentry['path'].'/'.$dirdest; @rename($dirsource, $dirdest); } } } } - $this->ref=$num; - $this->brouillon=0; + $this->ref = $num; + $this->brouillon = 0; $this->statut = self::STATUS_VALIDATED; - $this->user_valid_id=$user->id; - $this->datev=$now; + $this->user_valid_id = $user->id; + $this->datev = $now; $this->db->commit(); return 1; @@ -1885,57 +1888,57 @@ class Propal extends CommonObject // phpcs:enable if (empty($date)) { - $this->error='ErrorBadParameter'; + $this->error = 'ErrorBadParameter'; dol_syslog(get_class($this)."::set_date ".$this->error, LOG_ERR); return -1; } - if (! empty($user->rights->propal->creer)) + if (!empty($user->rights->propal->creer)) { - $error=0; + $error = 0; $this->db->begin(); $sql = "UPDATE ".MAIN_DB_PREFIX."propal SET datep = '".$this->db->idate($date)."'"; - $sql.= " WHERE rowid = ".$this->id." AND fk_statut = ".self::STATUS_DRAFT; + $sql .= " WHERE rowid = ".$this->id." AND fk_statut = ".self::STATUS_DRAFT; dol_syslog(__METHOD__, LOG_DEBUG); - $resql=$this->db->query($sql); + $resql = $this->db->query($sql); if (!$resql) { - $this->errors[]=$this->db->error(); + $this->errors[] = $this->db->error(); $error++; } - if (! $error) + if (!$error) { - $this->oldcopy= clone $this; + $this->oldcopy = clone $this; $this->date = $date; - $this->datep = $date; // deprecated + $this->datep = $date; // deprecated } - if (! $notrigger && empty($error)) + if (!$notrigger && empty($error)) { // Call trigger - $result=$this->call_trigger('PROPAL_MODIFY', $user); + $result = $this->call_trigger('PROPAL_MODIFY', $user); 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); + $this->error .= ($this->error ? ', '.$errmsg : $errmsg); } $this->db->rollback(); - return -1*$error; + return -1 * $error; } } } @@ -1952,52 +1955,52 @@ class Propal extends CommonObject public function set_echeance($user, $date_fin_validite, $notrigger = 0) { // phpcs:enable - if (! empty($user->rights->propal->creer)) + if (!empty($user->rights->propal->creer)) { - $error=0; + $error = 0; $this->db->begin(); - $sql = "UPDATE ".MAIN_DB_PREFIX."propal SET fin_validite = ".($date_fin_validite!=''?"'".$this->db->idate($date_fin_validite)."'":'null'); - $sql.= " WHERE rowid = ".$this->id." AND fk_statut = ".self::STATUS_DRAFT; + $sql = "UPDATE ".MAIN_DB_PREFIX."propal SET fin_validite = ".($date_fin_validite != '' ? "'".$this->db->idate($date_fin_validite)."'" : 'null'); + $sql .= " WHERE rowid = ".$this->id." AND fk_statut = ".self::STATUS_DRAFT; dol_syslog(__METHOD__, LOG_DEBUG); - $resql=$this->db->query($sql); + $resql = $this->db->query($sql); if (!$resql) { - $this->errors[]=$this->db->error(); + $this->errors[] = $this->db->error(); $error++; } - if (! $error) + if (!$error) { - $this->oldcopy= clone $this; + $this->oldcopy = clone $this; $this->fin_validite = $date_fin_validite; } - if (! $notrigger && empty($error)) + if (!$notrigger && empty($error)) { // Call trigger - $result=$this->call_trigger('PROPAL_MODIFY', $user); + $result = $this->call_trigger('PROPAL_MODIFY', $user); 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); + $this->error .= ($this->error ? ', '.$errmsg : $errmsg); } $this->db->rollback(); - return -1*$error; + return -1 * $error; } } } @@ -2014,52 +2017,52 @@ class Propal extends CommonObject public function set_date_livraison($user, $date_livraison, $notrigger = 0) { // phpcs:enable - if (! empty($user->rights->propal->creer)) + if (!empty($user->rights->propal->creer)) { - $error=0; + $error = 0; $this->db->begin(); $sql = "UPDATE ".MAIN_DB_PREFIX."propal "; - $sql.= " SET date_livraison = ".($date_livraison!=''?"'".$this->db->idate($date_livraison)."'":'null'); - $sql.= " WHERE rowid = ".$this->id; + $sql .= " SET date_livraison = ".($date_livraison != '' ? "'".$this->db->idate($date_livraison)."'" : 'null'); + $sql .= " WHERE rowid = ".$this->id; dol_syslog(__METHOD__, LOG_DEBUG); - $resql=$this->db->query($sql); + $resql = $this->db->query($sql); if (!$resql) { - $this->errors[]=$this->db->error(); + $this->errors[] = $this->db->error(); $error++; } - if (! $error) + if (!$error) { - $this->oldcopy= clone $this; + $this->oldcopy = clone $this; $this->date_livraison = $date_livraison; } - if (! $notrigger && empty($error)) + if (!$notrigger && empty($error)) { // Call trigger - $result=$this->call_trigger('PROPAL_MODIFY', $user); + $result = $this->call_trigger('PROPAL_MODIFY', $user); 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); + $this->error .= ($this->error ? ', '.$errmsg : $errmsg); } $this->db->rollback(); - return -1*$error; + return -1 * $error; } } } @@ -2076,61 +2079,61 @@ class Propal extends CommonObject public function set_availability($user, $id, $notrigger = 0) { // phpcs:enable - if (! empty($user->rights->propal->creer) && $this->statut >= self::STATUS_DRAFT) + if (!empty($user->rights->propal->creer) && $this->statut >= self::STATUS_DRAFT) { - $error=0; + $error = 0; $this->db->begin(); $sql = "UPDATE ".MAIN_DB_PREFIX."propal "; - $sql.= " SET fk_availability = '".$id."'"; - $sql.= " WHERE rowid = ".$this->id; + $sql .= " SET fk_availability = '".$id."'"; + $sql .= " WHERE rowid = ".$this->id; dol_syslog(__METHOD__.' availability('.$id.')', LOG_DEBUG); - $resql=$this->db->query($sql); + $resql = $this->db->query($sql); if (!$resql) { - $this->errors[]=$this->db->error(); + $this->errors[] = $this->db->error(); $error++; } - if (! $error) + if (!$error) { - $this->oldcopy= clone $this; + $this->oldcopy = clone $this; $this->fk_availability = $id; $this->availability_id = $id; } - if (! $notrigger && empty($error)) + if (!$notrigger && empty($error)) { // Call trigger - $result=$this->call_trigger('PROPAL_MODIFY', $user); + $result = $this->call_trigger('PROPAL_MODIFY', $user); 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); + $this->error .= ($this->error ? ', '.$errmsg : $errmsg); } $this->db->rollback(); - return -1*$error; + return -1 * $error; } } else { - $error_str='Propal status do not meet requirement '.$this->statut; + $error_str = 'Propal status do not meet requirement '.$this->statut; dol_syslog(__METHOD__.$error_str, LOG_ERR); - $this->error=$error_str; - $this->errors[]= $this->error; + $this->error = $error_str; + $this->errors[] = $this->error; return -2; } } @@ -2147,63 +2150,63 @@ class Propal extends CommonObject public function set_demand_reason($user, $id, $notrigger = 0) { // phpcs:enable - if (! empty($user->rights->propal->creer) && $this->statut >= self::STATUS_DRAFT) + if (!empty($user->rights->propal->creer) && $this->statut >= self::STATUS_DRAFT) { - $error=0; + $error = 0; $this->db->begin(); $sql = "UPDATE ".MAIN_DB_PREFIX."propal "; - $sql.= " SET fk_input_reason = ".$id; - $sql.= " WHERE rowid = ".$this->id; + $sql .= " SET fk_input_reason = ".$id; + $sql .= " WHERE rowid = ".$this->id; dol_syslog(__METHOD__, LOG_DEBUG); - $resql=$this->db->query($sql); + $resql = $this->db->query($sql); if (!$resql) { - $this->errors[]=$this->db->error(); + $this->errors[] = $this->db->error(); $error++; } - if (! $error) + if (!$error) { - $this->oldcopy= clone $this; + $this->oldcopy = clone $this; $this->fk_input_reason = $id; $this->demand_reason_id = $id; } - if (! $notrigger && empty($error)) + if (!$notrigger && empty($error)) { // Call trigger - $result=$this->call_trigger('PROPAL_MODIFY', $user); + $result = $this->call_trigger('PROPAL_MODIFY', $user); 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); + $this->error .= ($this->error ? ', '.$errmsg : $errmsg); } $this->db->rollback(); - return -1*$error; + return -1 * $error; } } else { - $error_str='Propal status do not meet requirement '.$this->statut; + $error_str = 'Propal status do not meet requirement '.$this->statut; dol_syslog(__METHOD__.$error_str, LOG_ERR); - $this->error=$error_str; - $this->errors[]= $this->error; + $this->error = $error_str; + $this->errors[] = $this->error; return -2; } } @@ -2220,51 +2223,51 @@ class Propal extends CommonObject public function set_ref_client($user, $ref_client, $notrigger = 0) { // phpcs:enable - if (! empty($user->rights->propal->creer)) + if (!empty($user->rights->propal->creer)) { - $error=0; + $error = 0; $this->db->begin(); $sql = 'UPDATE '.MAIN_DB_PREFIX.'propal SET ref_client = '.(empty($ref_client) ? 'NULL' : '\''.$this->db->escape($ref_client).'\''); - $sql.= ' WHERE rowid = '.$this->id; + $sql .= ' WHERE rowid = '.$this->id; dol_syslog(__METHOD__.' $this->id='.$this->id.', ref_client='.$ref_client, LOG_DEBUG); - $resql=$this->db->query($sql); + $resql = $this->db->query($sql); if (!$resql) { - $this->errors[]=$this->db->error(); + $this->errors[] = $this->db->error(); $error++; } - if (! $error) + if (!$error) { - $this->oldcopy= clone $this; + $this->oldcopy = clone $this; $this->ref_client = $ref_client; } - if (! $notrigger && empty($error)) + if (!$notrigger && empty($error)) { // Call trigger - $result=$this->call_trigger('PROPAL_MODIFY', $user); + $result = $this->call_trigger('PROPAL_MODIFY', $user); 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); + $this->error .= ($this->error ? ', '.$errmsg : $errmsg); } $this->db->rollback(); - return -1*$error; + return -1 * $error; } } else @@ -2285,56 +2288,56 @@ class Propal extends CommonObject public function set_remise_percent($user, $remise, $notrigger = 0) { // phpcs:enable - $remise=trim($remise)?trim($remise):0; + $remise = trim($remise) ?trim($remise) : 0; - if (! empty($user->rights->propal->creer)) + if (!empty($user->rights->propal->creer)) { $remise = price2num($remise); - $error=0; + $error = 0; $this->db->begin(); $sql = "UPDATE ".MAIN_DB_PREFIX."propal SET remise_percent = ".$remise; - $sql.= " WHERE rowid = ".$this->id." AND fk_statut = ".self::STATUS_DRAFT; + $sql .= " WHERE rowid = ".$this->id." AND fk_statut = ".self::STATUS_DRAFT; dol_syslog(__METHOD__, LOG_DEBUG); - $resql=$this->db->query($sql); + $resql = $this->db->query($sql); if (!$resql) { - $this->errors[]=$this->db->error(); + $this->errors[] = $this->db->error(); $error++; } - if (! $error) + if (!$error) { - $this->oldcopy= clone $this; + $this->oldcopy = clone $this; $this->remise_percent = $remise; $this->update_price(1); } - if (! $notrigger && empty($error)) + if (!$notrigger && empty($error)) { // Call trigger - $result=$this->call_trigger('PROPAL_MODIFY', $user); + $result = $this->call_trigger('PROPAL_MODIFY', $user); 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); + $this->error .= ($this->error ? ', '.$errmsg : $errmsg); } $this->db->rollback(); - return -1*$error; + return -1 * $error; } } } @@ -2352,57 +2355,57 @@ class Propal extends CommonObject public function set_remise_absolue($user, $remise, $notrigger = 0) { // phpcs:enable - $remise=trim($remise)?trim($remise):0; + $remise = trim($remise) ?trim($remise) : 0; - if (! empty($user->rights->propal->creer)) + if (!empty($user->rights->propal->creer)) { $remise = price2num($remise); - $error=0; + $error = 0; $this->db->begin(); $sql = "UPDATE ".MAIN_DB_PREFIX."propal "; - $sql.= " SET remise_absolue = ".$remise; - $sql.= " WHERE rowid = ".$this->id." AND fk_statut = ".self::STATUS_DRAFT; + $sql .= " SET remise_absolue = ".$remise; + $sql .= " WHERE rowid = ".$this->id." AND fk_statut = ".self::STATUS_DRAFT; dol_syslog(__METHOD__, LOG_DEBUG); - $resql=$this->db->query($sql); + $resql = $this->db->query($sql); if (!$resql) { - $this->errors[]=$this->db->error(); + $this->errors[] = $this->db->error(); $error++; } - if (! $error) + if (!$error) { - $this->oldcopy= clone $this; + $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('PROPAL_MODIFY', $user); + $result = $this->call_trigger('PROPAL_MODIFY', $user); 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); + $this->error .= ($this->error ? ', '.$errmsg : $errmsg); } $this->db->rollback(); - return -1*$error; + return -1 * $error; } } } @@ -2422,27 +2425,27 @@ class Propal extends CommonObject { $this->statut = $statut; - $error=0; + $error = 0; $sql = "UPDATE ".MAIN_DB_PREFIX."propal"; - $sql.= " SET fk_statut = ".$this->statut.","; - if (! empty($note)) $sql.= " note_private = '".$this->db->escape($note)."',"; - $sql.= " date_cloture=NULL, fk_user_cloture=NULL"; - $sql.= " WHERE rowid = ".$this->id; + $sql .= " SET fk_statut = ".$this->statut.","; + if (!empty($note)) $sql .= " note_private = '".$this->db->escape($note)."',"; + $sql .= " date_cloture=NULL, fk_user_cloture=NULL"; + $sql .= " WHERE rowid = ".$this->id; $this->db->begin(); dol_syslog(get_class($this)."::reopen", LOG_DEBUG); $resql = $this->db->query($sql); - if (! $resql) { - $error++; $this->errors[]="Error ".$this->db->lasterror(); + if (!$resql) { + $error++; $this->errors[] = "Error ".$this->db->lasterror(); } - if (! $error) + if (!$error) { - if (! $notrigger) + if (!$notrigger) { // Call trigger - $result=$this->call_trigger('PROPAL_REOPEN', $user); + $result = $this->call_trigger('PROPAL_REOPEN', $user); if ($result < 0) { $error++; } // End call triggers } @@ -2453,14 +2456,14 @@ class Propal extends CommonObject { if (!empty($this->errors)) { - foreach($this->errors as $errmsg) + foreach ($this->errors as $errmsg) { dol_syslog(get_class($this)."::update ".$errmsg, LOG_ERR); - $this->error.=($this->error?', '.$errmsg:$errmsg); + $this->error .= ($this->error ? ', '.$errmsg : $errmsg); } } $this->db->rollback(); - return -1*$error; + return -1 * $error; } else { @@ -2481,78 +2484,78 @@ class Propal extends CommonObject */ public function cloture($user, $statut, $note = "", $notrigger = 0) { - global $langs,$conf; + global $langs, $conf; - $error=0; - $now=dol_now(); + $error = 0; + $now = dol_now(); $this->db->begin(); $newprivatenote = dol_concatdesc($this->note_private, $note); $sql = "UPDATE ".MAIN_DB_PREFIX."propal"; - $sql.= " SET fk_statut = ".$statut.", note_private = '".$this->db->escape($newprivatenote)."', date_cloture='".$this->db->idate($now)."', fk_user_cloture=".$user->id; - $sql.= " WHERE rowid = ".$this->id; + $sql .= " SET fk_statut = ".$statut.", note_private = '".$this->db->escape($newprivatenote)."', date_cloture='".$this->db->idate($now)."', fk_user_cloture=".$user->id; + $sql .= " WHERE rowid = ".$this->id; - $resql=$this->db->query($sql); + $resql = $this->db->query($sql); if ($resql) { - $modelpdf=$conf->global->PROPALE_ADDON_PDF_ODT_CLOSED?$conf->global->PROPALE_ADDON_PDF_ODT_CLOSED:$this->modelpdf; - $trigger_name='PROPAL_CLOSE_REFUSED'; + $modelpdf = $conf->global->PROPALE_ADDON_PDF_ODT_CLOSED ? $conf->global->PROPALE_ADDON_PDF_ODT_CLOSED : $this->modelpdf; + $trigger_name = 'PROPAL_CLOSE_REFUSED'; if ($statut == self::STATUS_SIGNED) { - $trigger_name='PROPAL_CLOSE_SIGNED'; - $modelpdf=$conf->global->PROPALE_ADDON_PDF_ODT_TOBILL?$conf->global->PROPALE_ADDON_PDF_ODT_TOBILL:$this->modelpdf; + $trigger_name = 'PROPAL_CLOSE_SIGNED'; + $modelpdf = $conf->global->PROPALE_ADDON_PDF_ODT_TOBILL ? $conf->global->PROPALE_ADDON_PDF_ODT_TOBILL : $this->modelpdf; // The connected company is classified as a client - $soc=new Societe($this->db); + $soc = new Societe($this->db); $soc->id = $this->socid; - $result=$soc->set_as_client(); + $result = $soc->set_as_client(); if ($result < 0) { - $this->error=$this->db->lasterror(); + $this->error = $this->db->lasterror(); $this->db->rollback(); return -2; } } if ($statut == self::STATUS_BILLED) // Why this ? { - $trigger_name='PROPAL_CLASSIFY_BILLED'; + $trigger_name = 'PROPAL_CLASSIFY_BILLED'; } if (empty($conf->global->MAIN_DISABLE_PDF_AUTOUPDATE)) { // Define output language $outputlangs = $langs; - if (! empty($conf->global->MAIN_MULTILANGS)) + if (!empty($conf->global->MAIN_MULTILANGS)) { $outputlangs = new Translate("", $conf); - $newlang=(GETPOST('lang_id', 'aZ09') ? GETPOST('lang_id', 'aZ09') : $this->thirdparty->default_lang); + $newlang = (GETPOST('lang_id', 'aZ09') ? GETPOST('lang_id', 'aZ09') : $this->thirdparty->default_lang); $outputlangs->setDefaultLang($newlang); } //$ret=$object->fetch($id); // Reload to get new records $this->generateDocument($modelpdf, $outputlangs); } - if (! $error) + if (!$error) { - $this->oldcopy= clone $this; + $this->oldcopy = clone $this; $this->statut = $statut; $this->date_cloture = $now; $this->note_private = $newprivatenote; } - if (! $notrigger && empty($error)) + if (!$notrigger && empty($error)) { // Call trigger - $result=$this->call_trigger($trigger_name, $user); + $result = $this->call_trigger($trigger_name, $user); if ($result < 0) { $error++; } // End call triggers } - if (! $error) + if (!$error) { $this->db->commit(); return 1; @@ -2569,7 +2572,7 @@ class Propal extends CommonObject } else { - $this->error=$this->db->lasterror(); + $this->error = $this->db->lasterror(); $this->db->rollback(); return -1; } @@ -2584,7 +2587,7 @@ class Propal extends CommonObject */ public function classifyBilled(User $user, $notrigger = 0) { - $error=0; + $error = 0; $this->db->begin(); @@ -2592,41 +2595,41 @@ class Propal extends CommonObject $sql .= ' WHERE rowid = '.$this->id.' AND fk_statut > '.self::STATUS_DRAFT; dol_syslog(__METHOD__, LOG_DEBUG); - $resql=$this->db->query($sql); + $resql = $this->db->query($sql); if (!$resql) { - $this->errors[]=$this->db->error(); + $this->errors[] = $this->db->error(); $error++; } - if (! $error) + if (!$error) { - $this->oldcopy= clone $this; - $this->statut=self::STATUS_BILLED; + $this->oldcopy = clone $this; + $this->statut = self::STATUS_BILLED; } - if (! $notrigger && empty($error)) + if (!$notrigger && empty($error)) { // Call trigger - $result=$this->call_trigger('PROPAL_MODIFY', $user); + $result = $this->call_trigger('PROPAL_MODIFY', $user); 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); + $this->error .= ($this->error ? ', '.$errmsg : $errmsg); } $this->db->rollback(); - return -1*$error; + return -1 * $error; } } @@ -2641,7 +2644,7 @@ class Propal extends CommonObject public function setDraft($user, $notrigger = 0) { // phpcs:enable - $error=0; + $error = 0; // Protection if ($this->statut <= self::STATUS_DRAFT) @@ -2654,30 +2657,30 @@ class Propal extends CommonObject $this->db->begin(); $sql = "UPDATE ".MAIN_DB_PREFIX."propal"; - $sql.= " SET fk_statut = ".self::STATUS_DRAFT; - $sql.= " WHERE rowid = ".$this->id; + $sql .= " SET fk_statut = ".self::STATUS_DRAFT; + $sql .= " WHERE rowid = ".$this->id; - $resql=$this->db->query($sql); + $resql = $this->db->query($sql); if (!$resql) { - $this->errors[]=$this->db->error(); + $this->errors[] = $this->db->error(); $error++; } - if (! $error) + if (!$error) { - $this->oldcopy= clone $this; + $this->oldcopy = clone $this; } - if (! $notrigger && empty($error)) + if (!$notrigger && empty($error)) { // Call trigger - $result=$this->call_trigger('PROPAL_MODIFY', $user); + $result = $this->call_trigger('PROPAL_MODIFY', $user); if ($result < 0) $error++; // End call triggers } - if (! $error) + if (!$error) { $this->statut = self::STATUS_DRAFT; $this->brouillon = 1; @@ -2687,13 +2690,13 @@ class Propal extends CommonObject } else { - foreach($this->errors as $errmsg) + foreach ($this->errors as $errmsg) { dol_syslog(__METHOD__.' Error: '.$errmsg, LOG_ERR); - $this->error.=($this->error?', '.$errmsg:$errmsg); + $this->error .= ($this->error ? ', '.$errmsg : $errmsg); } $this->db->rollback(); - return -1*$error; + return -1 * $error; } } @@ -2720,25 +2723,25 @@ class Propal extends CommonObject $ga = array(); $sql = "SELECT s.rowid, s.nom as name, s.client,"; - $sql.= " p.rowid as propalid, p.fk_statut, p.total_ht, p.ref, p.remise, "; - $sql.= " p.datep as dp, p.fin_validite as datelimite"; - if (! $user->rights->societe->client->voir && ! $socid) $sql .= ", sc.fk_soc, sc.fk_user"; - $sql.= " FROM ".MAIN_DB_PREFIX."societe as s, ".MAIN_DB_PREFIX."propal as p, ".MAIN_DB_PREFIX."c_propalst as c"; - if (! $user->rights->societe->client->voir && ! $socid) $sql .= ", ".MAIN_DB_PREFIX."societe_commerciaux as sc"; - $sql.= " WHERE p.entity IN (".getEntity('propal').")"; - $sql.= " AND p.fk_soc = s.rowid"; - $sql.= " AND p.fk_statut = c.id"; - if (! $user->rights->societe->client->voir && ! $socid) //restriction + $sql .= " p.rowid as propalid, p.fk_statut, p.total_ht, p.ref, p.remise, "; + $sql .= " p.datep as dp, p.fin_validite as datelimite"; + if (!$user->rights->societe->client->voir && !$socid) $sql .= ", sc.fk_soc, sc.fk_user"; + $sql .= " FROM ".MAIN_DB_PREFIX."societe as s, ".MAIN_DB_PREFIX."propal as p, ".MAIN_DB_PREFIX."c_propalst as c"; + if (!$user->rights->societe->client->voir && !$socid) $sql .= ", ".MAIN_DB_PREFIX."societe_commerciaux as sc"; + $sql .= " WHERE p.entity IN (".getEntity('propal').")"; + $sql .= " AND p.fk_soc = s.rowid"; + $sql .= " AND p.fk_statut = c.id"; + if (!$user->rights->societe->client->voir && !$socid) //restriction { - $sql.= " AND s.rowid = sc.fk_soc AND sc.fk_user = " .$user->id; + $sql .= " AND s.rowid = sc.fk_soc AND sc.fk_user = ".$user->id; } - if ($socid) $sql.= " AND s.rowid = ".$socid; - if ($draft) $sql.= " AND p.fk_statut = ".self::STATUS_DRAFT; - if ($notcurrentuser > 0) $sql.= " AND p.fk_user_author <> ".$user->id; - $sql.= $this->db->order($sortfield, $sortorder); - $sql.= $this->db->plimit($limit, $offset); + if ($socid) $sql .= " AND s.rowid = ".$socid; + if ($draft) $sql .= " AND p.fk_statut = ".self::STATUS_DRAFT; + if ($notcurrentuser > 0) $sql .= " AND p.fk_user_author <> ".$user->id; + $sql .= $this->db->order($sortfield, $sortorder); + $sql .= $this->db->plimit($limit, $offset); - $result=$this->db->query($sql); + $result = $this->db->query($sql); if ($result) { $num = $this->db->num_rows($result); @@ -2759,7 +2762,7 @@ class Propal extends CommonObject } else { - $ga[$i]['id'] = $obj->propalid; + $ga[$i]['id'] = $obj->propalid; $ga[$i]['ref'] = $obj->ref; $ga[$i]['name'] = $obj->name; } @@ -2800,11 +2803,11 @@ class Propal extends CommonObject $linkedInvoices = array(); $this->fetchObjectLinked($id, $this->element); - foreach($this->linkedObjectsIds as $objecttype => $objectid) + foreach ($this->linkedObjectsIds as $objecttype => $objectid) { // Nouveau système du comon object renvoi des rowid et non un id linéaire de 1 à n // On parcourt donc une liste d'objets en tant qu'objet unique - foreach($objectid as $key => $object) + foreach ($objectid as $key => $object) { // Cas des factures liees directement if ($objecttype == 'facture') @@ -2815,9 +2818,9 @@ class Propal extends CommonObject else { $this->fetchObjectLinked($object, $objecttype); - foreach($this->linkedObjectsIds as $subobjecttype => $subobjectid) + foreach ($this->linkedObjectsIds as $subobjecttype => $subobjectid) { - foreach($subobjectid as $subkey => $subobject) + foreach ($subobjectid as $subkey => $subobject) { if ($subobjecttype == 'facture') { @@ -2831,18 +2834,18 @@ class Propal extends CommonObject if (count($linkedInvoices) > 0) { - $sql= "SELECT rowid as facid, ref, total, datef as df, fk_user_author, fk_statut, paye"; - $sql.= " FROM ".MAIN_DB_PREFIX."facture"; - $sql.= " WHERE rowid IN (".implode(',', $linkedInvoices).")"; + $sql = "SELECT rowid as facid, ref, total, datef as df, fk_user_author, fk_statut, paye"; + $sql .= " FROM ".MAIN_DB_PREFIX."facture"; + $sql .= " WHERE rowid IN (".implode(',', $linkedInvoices).")"; dol_syslog(get_class($this)."::InvoiceArrayList", LOG_DEBUG); - $resql=$this->db->query($sql); + $resql = $this->db->query($sql); if ($resql) { - $tab_sqlobj=array(); + $tab_sqlobj = array(); $nump = $this->db->num_rows($resql); - for ($i = 0;$i < $nump;$i++) + for ($i = 0; $i < $nump; $i++) { $sqlobj = $this->db->fetch_object($resql); $tab_sqlobj[] = $sqlobj; @@ -2885,19 +2888,19 @@ class Propal extends CommonObject global $conf; require_once DOL_DOCUMENT_ROOT.'/core/lib/files.lib.php'; - $error=0; + $error = 0; $this->db->begin(); - if (! $notrigger) + if (!$notrigger) { // Call trigger - $result=$this->call_trigger('PROPAL_DELETE', $user); + $result = $this->call_trigger('PROPAL_DELETE', $user); if ($result < 0) { $error++; } // End call triggers } - if (! $error) + if (!$error) { $sql = "DELETE FROM ".MAIN_DB_PREFIX."propaldet WHERE fk_propal = ".$this->id; if ($this->db->query($sql)) @@ -2913,33 +2916,33 @@ class Propal extends CommonObject $res = $this->delete_linked_contact(); if ($res < 0) $error++; - if (! $error) + if (!$error) { // We remove directory $ref = dol_sanitizeFileName($this->ref); if ($conf->propal->multidir_output[$this->entity] && !empty($this->ref)) { - $dir = $conf->propal->multidir_output[$this->entity] . "/" . $ref ; - $file = $dir . "/" . $ref . ".pdf"; + $dir = $conf->propal->multidir_output[$this->entity]."/".$ref; + $file = $dir."/".$ref.".pdf"; 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 { - $this->error='ErrorFailToDeleteFile'; - $this->errors=array('ErrorFailToDeleteFile'); + $this->error = 'ErrorFailToDeleteFile'; + $this->errors = array('ErrorFailToDeleteFile'); $this->db->rollback(); return 0; } } if (file_exists($dir)) { - $res=@dol_delete_dir_recursive($dir); - if (! $res) + $res = @dol_delete_dir_recursive($dir); + if (!$res) { - $this->error='ErrorFailToDeleteDir'; - $this->errors=array('ErrorFailToDeleteDir'); + $this->error = 'ErrorFailToDeleteDir'; + $this->errors = array('ErrorFailToDeleteDir'); $this->db->rollback(); return 0; } @@ -2948,21 +2951,21 @@ class Propal extends CommonObject } // Removed extrafields - if (! $error) + if (!$error) { if (empty($conf->global->MAIN_EXTRAFIELDS_DISABLED)) // For avoid conflicts if trigger used { - $result=$this->deleteExtraFields(); + $result = $this->deleteExtraFields(); if ($result < 0) { $error++; - $errorflag=-4; + $errorflag = -4; dol_syslog(get_class($this)."::delete erreur ".$errorflag." ".$this->error, LOG_ERR); } } } - if (! $error) + if (!$error) { dol_syslog(get_class($this)."::delete ".$this->id." by ".$user->id, LOG_DEBUG); $this->db->commit(); @@ -2970,21 +2973,21 @@ class Propal extends CommonObject } else { - $this->error=$this->db->lasterror(); + $this->error = $this->db->lasterror(); $this->db->rollback(); return 0; } } else { - $this->error=$this->db->lasterror(); + $this->error = $this->db->lasterror(); $this->db->rollback(); return -3; } } else { - $this->error=$this->db->lasterror(); + $this->error = $this->db->lasterror(); $this->db->rollback(); return -2; } @@ -3010,7 +3013,7 @@ class Propal extends CommonObject if ($this->statut >= self::STATUS_DRAFT) { - $error=0; + $error = 0; $this->db->begin(); @@ -3019,49 +3022,49 @@ class Propal extends CommonObject $sql .= ' WHERE rowid='.$this->id; dol_syslog(__METHOD__.' availability('.$availability_id.')', LOG_DEBUG); - $resql=$this->db->query($sql); + $resql = $this->db->query($sql); if (!$resql) { - $this->errors[]=$this->db->error(); + $this->errors[] = $this->db->error(); $error++; } - if (! $error) + if (!$error) { - $this->oldcopy= clone $this; + $this->oldcopy = clone $this; $this->availability_id = $availability_id; } - if (! $notrigger && empty($error)) + if (!$notrigger && empty($error)) { // Call trigger - $result=$this->call_trigger('PROPAL_MODIFY', $user); + $result = $this->call_trigger('PROPAL_MODIFY', $user); 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); + $this->error .= ($this->error ? ', '.$errmsg : $errmsg); } $this->db->rollback(); - return -1*$error; + return -1 * $error; } } else { - $error_str='Propal status do not meet requirement '.$this->statut; + $error_str = 'Propal status do not meet requirement '.$this->statut; dol_syslog(__METHOD__.$error_str, LOG_ERR); - $this->error=$error_str; - $this->errors[]= $this->error; + $this->error = $error_str; + $this->errors[] = $this->error; return -2; } } @@ -3082,7 +3085,7 @@ class Propal extends CommonObject if ($this->statut >= self::STATUS_DRAFT) { - $error=0; + $error = 0; $this->db->begin(); @@ -3091,49 +3094,49 @@ class Propal extends CommonObject $sql .= ' WHERE rowid='.$this->id; dol_syslog(__METHOD__.' demand_reason('.$demand_reason_id.')', LOG_DEBUG); - $resql=$this->db->query($sql); + $resql = $this->db->query($sql); if (!$resql) { - $this->errors[]=$this->db->error(); + $this->errors[] = $this->db->error(); $error++; } - if (! $error) + if (!$error) { - $this->oldcopy= clone $this; + $this->oldcopy = clone $this; $this->demand_reason_id = $demand_reason_id; } - if (! $notrigger && empty($error)) + if (!$notrigger && empty($error)) { // Call trigger - $result=$this->call_trigger('PROPAL_MODIFY', $user); + $result = $this->call_trigger('PROPAL_MODIFY', $user); 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); + $this->error .= ($this->error ? ', '.$errmsg : $errmsg); } $this->db->rollback(); - return -1*$error; + return -1 * $error; } } else { - $error_str='Propal status do not meet requirement '.$this->statut; + $error_str = 'Propal status do not meet requirement '.$this->statut; dol_syslog(__METHOD__.$error_str, LOG_ERR); - $this->error=$error_str; - $this->errors[]= $this->error; + $this->error = $error_str; + $this->errors[] = $this->error; return -2; } } @@ -3148,10 +3151,10 @@ class Propal extends CommonObject public function info($id) { $sql = "SELECT c.rowid, "; - $sql.= " c.datec, c.date_valid as datev, c.date_cloture as dateo,"; - $sql.= " c.fk_user_author, c.fk_user_valid, c.fk_user_cloture"; - $sql.= " FROM ".MAIN_DB_PREFIX."propal as c"; - $sql.= " WHERE c.rowid = ".$id; + $sql .= " c.datec, c.date_valid as datev, c.date_cloture as dateo,"; + $sql .= " c.fk_user_author, c.fk_user_valid, c.fk_user_cloture"; + $sql .= " FROM ".MAIN_DB_PREFIX."propal as c"; + $sql .= " WHERE c.rowid = ".$id; $result = $this->db->query($sql); @@ -3169,20 +3172,20 @@ class Propal extends CommonObject $cuser = new User($this->db); $cuser->fetch($obj->fk_user_author); - $this->user_creation = $cuser; + $this->user_creation = $cuser; if ($obj->fk_user_valid) { $vuser = new User($this->db); $vuser->fetch($obj->fk_user_valid); - $this->user_validation = $vuser; + $this->user_validation = $vuser; } if ($obj->fk_user_cloture) { $cluser = new User($this->db); $cluser->fetch($obj->fk_user_cloture); - $this->user_cloture = $cluser; + $this->user_cloture = $cluser; } } $this->db->free($result); @@ -3305,10 +3308,10 @@ class Propal extends CommonObject $response->img = img_object('', "propal"); // This assignment in condition is not a bug. It allows walking the results. - while ($obj=$this->db->fetch_object($resql)) + while ($obj = $this->db->fetch_object($resql)) { $response->nbtodo++; - $response->total+=$obj->total_ht; + $response->total += $obj->total_ht; if ($mode == 'opened') { @@ -3326,7 +3329,7 @@ class Propal extends CommonObject } else { - $this->error=$this->db->error(); + $this->error = $this->db->error(); return -1; } } @@ -3347,8 +3350,8 @@ class Propal extends CommonObject $num_prods = 0; $prodids = array(); $sql = "SELECT rowid"; - $sql.= " FROM ".MAIN_DB_PREFIX."product"; - $sql.= " WHERE entity IN (".getEntity('product').")"; + $sql .= " FROM ".MAIN_DB_PREFIX."product"; + $sql .= " WHERE entity IN (".getEntity('product').")"; $resql = $this->db->query($sql); if ($resql) { @@ -3363,13 +3366,13 @@ class Propal extends CommonObject } // Initialise parametres - $this->id=0; + $this->id = 0; $this->ref = 'SPECIMEN'; - $this->ref_client='NEMICEPS'; - $this->specimen=1; + $this->ref_client = 'NEMICEPS'; + $this->specimen = 1; $this->socid = 1; $this->date = time(); - $this->fin_validite = $this->date+3600*24*30; + $this->fin_validite = $this->date + 3600 * 24 * 30; $this->cond_reglement_id = 1; $this->cond_reglement_code = 'RECEP'; $this->mode_reglement_id = 7; @@ -3378,44 +3381,44 @@ class Propal extends CommonObject $this->availability_code = 'AV_NOW'; $this->demand_reason_id = 1; $this->demand_reason_code = 'SRC_00'; - $this->note_public='This is a comment (public)'; - $this->note_private='This is a comment (private)'; + $this->note_public = 'This is a comment (public)'; + $this->note_private = 'This is a comment (private)'; // Lines $nbp = 5; $xnbp = 0; while ($xnbp < $nbp) { - $line=new PropaleLigne($this->db); - $line->desc=$langs->trans("Description")." ".$xnbp; - $line->qty=1; - $line->subprice=100; - $line->price=100; - $line->tva_tx=20; - $line->localtax1_tx=0; - $line->localtax2_tx=0; + $line = new PropaleLigne($this->db); + $line->desc = $langs->trans("Description")." ".$xnbp; + $line->qty = 1; + $line->subprice = 100; + $line->price = 100; + $line->tva_tx = 20; + $line->localtax1_tx = 0; + $line->localtax2_tx = 0; if ($xnbp == 2) { - $line->total_ht=50; - $line->total_ttc=60; - $line->total_tva=10; - $line->remise_percent=50; + $line->total_ht = 50; + $line->total_ttc = 60; + $line->total_tva = 10; + $line->remise_percent = 50; } else { - $line->total_ht=100; - $line->total_ttc=120; - $line->total_tva=20; - $line->remise_percent=00; + $line->total_ht = 100; + $line->total_ttc = 120; + $line->total_tva = 20; + $line->remise_percent = 00; } if ($num_prods > 0) { $prodid = mt_rand(1, $num_prods); - $line->fk_product=$prodids[$prodid]; - $line->product_ref='SPECIMEN'; + $line->fk_product = $prodids[$prodid]; + $line->product_ref = 'SPECIMEN'; } - $this->lines[$xnbp]=$line; + $this->lines[$xnbp] = $line; $this->total_ht += $line->total_ht; $this->total_tva += $line->total_tva; @@ -3464,7 +3467,7 @@ class Propal extends CommonObject else { dol_print_error($this->db); - $this->error=$this->db->error(); + $this->error = $this->db->error(); return -1; } } @@ -3479,14 +3482,14 @@ class Propal extends CommonObject */ public function getNextNumRef($soc) { - global $conf,$langs; + global $conf, $langs; $langs->load("propal"); $classname = $conf->global->PROPALE_ADDON; - if (! empty($classname)) + if (!empty($classname)) { - $mybool=false; + $mybool = false; $file = $classname.".php"; @@ -3496,10 +3499,10 @@ class Propal extends CommonObject $dir = dol_buildpath($reldir."core/modules/propale/"); // Load file with numbering class (if found) - $mybool|=@include_once $dir.$file; + $mybool |= @include_once $dir.$file; } - if (! $mybool) + if (!$mybool) { dol_print_error('', "Failed to include file ".$file); return ''; @@ -3515,7 +3518,7 @@ class Propal extends CommonObject } else { - $this->error=$obj->error; + $this->error = $obj->error; //dol_print_error($db,"Propale::getNextNumRef ".$obj->error); return ""; } @@ -3542,66 +3545,66 @@ class Propal extends CommonObject { global $langs, $conf, $user; - if (! empty($conf->dol_no_mouse_hover)) $notooltip=1; // Force disable tooltips + if (!empty($conf->dol_no_mouse_hover)) $notooltip = 1; // Force disable tooltips - $result=''; - $label=''; - $url=''; + $result = ''; + $label = ''; + $url = ''; if ($user->rights->propal->lire) { - $label = '' . $langs->trans("ShowPropal") . ''; - if (! empty($this->ref)) - $label.= '
'.$langs->trans('Ref').': '.$this->ref; - if (! empty($this->ref_client)) - $label.= '
'.$langs->trans('RefCustomer').': '.$this->ref_client; - if (! empty($this->total_ht)) - $label.= '
' . $langs->trans('AmountHT') . ': ' . price($this->total_ht, 0, $langs, 0, -1, -1, $conf->currency); - if (! empty($this->total_tva)) - $label.= '
' . $langs->trans('VAT') . ': ' . price($this->total_tva, 0, $langs, 0, -1, -1, $conf->currency); - if (! empty($this->total_ttc)) - $label.= '
' . $langs->trans('AmountTTC') . ': ' . price($this->total_ttc, 0, $langs, 0, -1, -1, $conf->currency); + $label = ''.$langs->trans("ShowPropal").''; + if (!empty($this->ref)) + $label .= '
'.$langs->trans('Ref').': '.$this->ref; + if (!empty($this->ref_client)) + $label .= '
'.$langs->trans('RefCustomer').': '.$this->ref_client; + if (!empty($this->total_ht)) + $label .= '
'.$langs->trans('AmountHT').': '.price($this->total_ht, 0, $langs, 0, -1, -1, $conf->currency); + if (!empty($this->total_tva)) + $label .= '
'.$langs->trans('VAT').': '.price($this->total_tva, 0, $langs, 0, -1, -1, $conf->currency); + if (!empty($this->total_ttc)) + $label .= '
'.$langs->trans('AmountTTC').': '.price($this->total_ttc, 0, $langs, 0, -1, -1, $conf->currency); if ($option == '') { - $url = DOL_URL_ROOT.'/comm/propal/card.php?id='.$this->id. $get_params; + $url = DOL_URL_ROOT.'/comm/propal/card.php?id='.$this->id.$get_params; } elseif ($option == 'compta') { // deprecated - $url = DOL_URL_ROOT.'/comm/propal/card.php?id='.$this->id. $get_params; + $url = DOL_URL_ROOT.'/comm/propal/card.php?id='.$this->id.$get_params; } elseif ($option == 'expedition') { - $url = DOL_URL_ROOT.'/expedition/propal.php?id='.$this->id. $get_params; + $url = DOL_URL_ROOT.'/expedition/propal.php?id='.$this->id.$get_params; } elseif ($option == 'document') { - $url = DOL_URL_ROOT.'/comm/propal/document.php?id='.$this->id. $get_params; + $url = DOL_URL_ROOT.'/comm/propal/document.php?id='.$this->id.$get_params; } if ($option != 'nolink') { // Add param to save lastsearch_values or not - $add_save_lastsearch_values=($save_lastsearch_value == 1 ? 1 : 0); - if ($save_lastsearch_value == -1 && preg_match('/list\.php/', $_SERVER["PHP_SELF"])) $add_save_lastsearch_values=1; - if ($add_save_lastsearch_values) $url.='&save_lastsearch_values=1'; + $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=''; + $linkclose = ''; if (empty($notooltip) && $user->rights->propal->lire) { - if (! empty($conf->global->MAIN_OPTIMIZEFORTEXTBROWSER)) + if (!empty($conf->global->MAIN_OPTIMIZEFORTEXTBROWSER)) { - $label=$langs->trans("ShowPropal"); - $linkclose.=' alt="'.dol_escape_htmltag($label, 1).'"'; + $label = $langs->trans("ShowPropal"); + $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"'; } $linkstart = ''; - $linkend=''; + $linkstart .= $linkclose.'>'; + $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; + if ($withpicto) $result .= img_object(($notooltip ? '' : $label), $this->picto, ($notooltip ? (($withpicto != 2) ? 'class="paddingright"' : '') : 'class="'.(($withpicto != 2) ? 'paddingright ' : '').'classfortooltip"'), 0, 0, $notooltip ? 0 : 1); + if ($withpicto != 2) $result .= $this->ref; $result .= $linkend; return $result; @@ -3630,16 +3633,16 @@ class Propal extends CommonObject */ public function generateDocument($modele, $outputlangs, $hidedetails = 0, $hidedesc = 0, $hideref = 0, $moreparams = null) { - global $conf,$langs; + global $conf, $langs; $langs->load("propale"); - if (! dol_strlen($modele)) { + if (!dol_strlen($modele)) { $modele = 'azur'; if ($this->modelpdf) { $modele = $this->modelpdf; - } elseif (! empty($conf->global->PROPALE_ADDON_PDF)) { + } elseif (!empty($conf->global->PROPALE_ADDON_PDF)) { $modele = $conf->global->PROPALE_ADDON_PDF; } } @@ -3676,20 +3679,20 @@ class PropaleLigne extends CommonObjectLine /** * @var string ID to identify managed object */ - public $element='propaldet'; + public $element = 'propaldet'; /** * @var string Name of table without prefix where object is stored */ - public $table_element='propaldet'; + public $table_element = 'propaldet'; public $oldline; // From llx_propaldet public $fk_propal; public $fk_parent_line; - public $desc; // Description ligne - public $fk_product; // Id produit predefini + public $desc; // Description ligne + public $fk_product; // Id produit predefini /** * @deprecated * @see $product_type @@ -3715,18 +3718,18 @@ class PropaleLigne extends CommonObjectLine public $marge_tx; public $marque_tx; - public $special_code; // Tag for special lines (exlusive tags) + public $special_code; // Tag for special lines (exlusive tags) // 1: frais de port // 2: ecotaxe // 3: option line (when qty = 0) - public $info_bits = 0; // Some other info: + public $info_bits = 0; // Some other info: // Bit 0: 0 si TVA normal - 1 si TVA NPR // Bit 1: 0 ligne normale - 1 si ligne de remise fixe - public $total_ht; // Total HT de la ligne toute quantite et incluant la remise ligne - public $total_tva; // Total TVA de la ligne toute quantite et incluant la remise ligne - public $total_ttc; // Total TTC de la ligne toute quantite et incluant la remise ligne + public $total_ht; // Total HT de la ligne toute quantite et incluant la remise ligne + public $total_tva; // Total TVA de la ligne toute quantite et incluant la remise ligne + public $total_ttc; // Total TTC de la ligne toute quantite et incluant la remise ligne /** * @deprecated @@ -3766,12 +3769,12 @@ class PropaleLigne extends CommonObjectLine */ public $product_desc; - public $localtax1_tx; // Local tax 1 - public $localtax2_tx; // Local tax 2 - public $localtax1_type; // Local tax 1 type - public $localtax2_type; // Local tax 2 type - public $total_localtax1; // Line total local tax 1 - public $total_localtax2; // Line total local tax 2 + public $localtax1_tx; // Local tax 1 + public $localtax2_tx; // Local tax 2 + public $localtax1_type; // Local tax 1 type + public $localtax2_type; // Local tax 2 type + public $total_localtax1; // Line total local tax 1 + public $total_localtax2; // Line total local tax 2 public $date_start; public $date_end; @@ -3793,7 +3796,7 @@ class PropaleLigne extends CommonObjectLine */ public function __construct($db) { - $this->db= $db; + $this->db = $db; } /** @@ -3805,16 +3808,16 @@ class PropaleLigne extends CommonObjectLine public function fetch($rowid) { $sql = 'SELECT pd.rowid, pd.fk_propal, pd.fk_parent_line, pd.fk_product, pd.label as custom_label, pd.description, pd.price, pd.qty, pd.vat_src_code, pd.tva_tx,'; - $sql.= ' pd.remise, pd.remise_percent, pd.fk_remise_except, pd.subprice,'; - $sql.= ' pd.info_bits, pd.total_ht, pd.total_tva, pd.total_ttc, pd.fk_product_fournisseur_price as fk_fournprice, pd.buy_price_ht as pa_ht, pd.special_code, pd.rang,'; - $sql.= ' pd.fk_unit,'; - $sql.= ' pd.localtax1_tx, pd.localtax2_tx, pd.total_localtax1, pd.total_localtax2,'; - $sql.= ' pd.fk_multicurrency, pd.multicurrency_code, pd.multicurrency_subprice, pd.multicurrency_total_ht, pd.multicurrency_total_tva, pd.multicurrency_total_ttc,'; - $sql.= ' p.ref as product_ref, p.label as product_label, p.description as product_desc,'; - $sql.= ' pd.date_start, pd.date_end, pd.product_type'; - $sql.= ' FROM '.MAIN_DB_PREFIX.'propaldet as pd'; - $sql.= ' LEFT JOIN '.MAIN_DB_PREFIX.'product as p ON pd.fk_product = p.rowid'; - $sql.= ' WHERE pd.rowid = '.$rowid; + $sql .= ' pd.remise, pd.remise_percent, pd.fk_remise_except, pd.subprice,'; + $sql .= ' pd.info_bits, pd.total_ht, pd.total_tva, pd.total_ttc, pd.fk_product_fournisseur_price as fk_fournprice, pd.buy_price_ht as pa_ht, pd.special_code, pd.rang,'; + $sql .= ' pd.fk_unit,'; + $sql .= ' pd.localtax1_tx, pd.localtax2_tx, pd.total_localtax1, pd.total_localtax2,'; + $sql .= ' pd.fk_multicurrency, pd.multicurrency_code, pd.multicurrency_subprice, pd.multicurrency_total_ht, pd.multicurrency_total_tva, pd.multicurrency_total_ttc,'; + $sql .= ' p.ref as product_ref, p.label as product_label, p.description as product_desc,'; + $sql .= ' pd.date_start, pd.date_end, pd.product_type'; + $sql .= ' FROM '.MAIN_DB_PREFIX.'propaldet as pd'; + $sql .= ' LEFT JOIN '.MAIN_DB_PREFIX.'product as p ON pd.fk_product = p.rowid'; + $sql .= ' WHERE pd.rowid = '.$rowid; $result = $this->db->query($sql); if ($result) @@ -3823,28 +3826,28 @@ class PropaleLigne extends CommonObjectLine if ($objp) { - $this->id = $objp->rowid; - $this->rowid = $objp->rowid; // deprecated - $this->fk_propal = $objp->fk_propal; - $this->fk_parent_line = $objp->fk_parent_line; + $this->id = $objp->rowid; + $this->rowid = $objp->rowid; // deprecated + $this->fk_propal = $objp->fk_propal; + $this->fk_parent_line = $objp->fk_parent_line; $this->label = $objp->custom_label; $this->desc = $objp->description; - $this->qty = $objp->qty; - $this->price = $objp->price; // deprecated - $this->subprice = $objp->subprice; - $this->vat_src_code = $objp->vat_src_code; + $this->qty = $objp->qty; + $this->price = $objp->price; // deprecated + $this->subprice = $objp->subprice; + $this->vat_src_code = $objp->vat_src_code; $this->tva_tx = $objp->tva_tx; - $this->remise = $objp->remise; // deprecated - $this->remise_percent = $objp->remise_percent; + $this->remise = $objp->remise; // deprecated + $this->remise_percent = $objp->remise_percent; $this->fk_remise_except = $objp->fk_remise_except; - $this->fk_product = $objp->fk_product; + $this->fk_product = $objp->fk_product; $this->info_bits = $objp->info_bits; $this->total_ht = $objp->total_ht; $this->total_tva = $objp->total_tva; $this->total_ttc = $objp->total_ttc; - $this->fk_fournprice = $objp->fk_fournprice; + $this->fk_fournprice = $objp->fk_fournprice; $marginInfos = getMarginInfos($objp->subprice, $objp->remise_percent, $objp->tva_tx, $objp->localtax1_tx, $objp->localtax2_tx, $this->fk_fournprice, $objp->pa_ht); $this->pa_ht = $marginInfos[0]; @@ -3853,11 +3856,11 @@ class PropaleLigne extends CommonObjectLine $this->special_code = $objp->special_code; $this->product_type = $objp->product_type; - $this->rang = $objp->rang; + $this->rang = $objp->rang; - $this->ref = $objp->product_ref; // deprecated - $this->product_ref = $objp->product_ref; - $this->libelle = $objp->product_label; // deprecated + $this->ref = $objp->product_ref; // deprecated + $this->product_ref = $objp->product_ref; + $this->libelle = $objp->product_label; // deprecated $this->product_label = $objp->product_label; $this->product_desc = $objp->product_desc; $this->fk_unit = $objp->fk_unit; @@ -3866,8 +3869,8 @@ class PropaleLigne extends CommonObjectLine $this->date_end = $this->db->jdate($objp->date_end); // Multicurrency - $this->fk_multicurrency = $objp->fk_multicurrency; - $this->multicurrency_code = $objp->multicurrency_code; + $this->fk_multicurrency = $objp->fk_multicurrency; + $this->multicurrency_code = $objp->multicurrency_code; $this->multicurrency_subprice = $objp->multicurrency_subprice; $this->multicurrency_total_ht = $objp->multicurrency_total_ht; $this->multicurrency_total_tva = $objp->multicurrency_total_tva; @@ -3898,35 +3901,35 @@ class PropaleLigne extends CommonObjectLine */ public function insert($notrigger = 0) { - global $conf,$user; + global $conf, $user; - $error=0; + $error = 0; dol_syslog(get_class($this)."::insert rang=".$this->rang); $pa_ht_isemptystring = (empty($this->pa_ht) && $this->pa_ht == ''); // If true, we can use a default value. If this->pa_ht = '0', we must use '0'. // 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) || ! is_numeric($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->fk_fournprice)) $this->fk_fournprice=0; - if (! is_numeric($this->qty)) $this->qty = 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 (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) || !is_numeric($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->fk_fournprice)) $this->fk_fournprice = 0; + if (!is_numeric($this->qty)) $this->qty = 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) @@ -3948,71 +3951,71 @@ class PropaleLigne extends CommonObjectLine // Insert line into database $sql = 'INSERT INTO '.MAIN_DB_PREFIX.'propaldet'; - $sql.= ' (fk_propal, fk_parent_line, label, description, fk_product, product_type,'; - $sql.= ' fk_remise_except, qty, vat_src_code, tva_tx, localtax1_tx, localtax2_tx, localtax1_type, localtax2_type,'; - $sql.= ' subprice, remise_percent, '; - $sql.= ' info_bits, '; - $sql.= ' total_ht, total_tva, total_localtax1, total_localtax2, total_ttc, fk_product_fournisseur_price, buy_price_ht, special_code, rang,'; - $sql.= ' fk_unit,'; - $sql.= ' date_start, date_end'; - $sql.= ', fk_multicurrency, multicurrency_code, multicurrency_subprice, multicurrency_total_ht, multicurrency_total_tva, multicurrency_total_ttc)'; - $sql.= " VALUES (".$this->fk_propal.","; - $sql.= " ".($this->fk_parent_line>0?"'".$this->db->escape($this->fk_parent_line)."'":"null").","; - $sql.= " ".(! empty($this->label)?"'".$this->db->escape($this->label)."'":"null").","; - $sql.= " '".$this->db->escape($this->desc)."',"; - $sql.= " ".($this->fk_product?"'".$this->db->escape($this->fk_product)."'":"null").","; - $sql.= " '".$this->db->escape($this->product_type)."',"; - $sql.= " ".($this->fk_remise_except?"'".$this->db->escape($this->fk_remise_except)."'":"null").","; - $sql.= " ".price2num($this->qty).","; - $sql.= " ".(empty($this->vat_src_code)?"''":"'".$this->db->escape($this->vat_src_code)."'").","; - $sql.= " ".price2num($this->tva_tx).","; - $sql.= " ".price2num($this->localtax1_tx).","; - $sql.= " ".price2num($this->localtax2_tx).","; - $sql.= " '".$this->db->escape($this->localtax1_type)."',"; - $sql.= " '".$this->db->escape($this->localtax2_type)."',"; - $sql.= " ".(price2num($this->subprice)!==''?price2num($this->subprice):"null").","; - $sql.= " ".price2num($this->remise_percent).","; - $sql.= " ".(isset($this->info_bits)?"'".$this->db->escape($this->info_bits)."'":"null").","; - $sql.= " ".price2num($this->total_ht).","; - $sql.= " ".price2num($this->total_tva).","; - $sql.= " ".price2num($this->total_localtax1).","; - $sql.= " ".price2num($this->total_localtax2).","; - $sql.= " ".price2num($this->total_ttc).","; - $sql.= " ".(!empty($this->fk_fournprice)?"'".$this->db->escape($this->fk_fournprice)."'":"null").","; - $sql.= " ".(isset($this->pa_ht)?"'".price2num($this->pa_ht)."'":"null").","; - $sql.= ' '.$this->special_code.','; - $sql.= ' '.$this->rang.','; - $sql.= ' '.(!$this->fk_unit ? 'NULL' : $this->fk_unit).','; - $sql.= " ".(! empty($this->date_start)?"'".$this->db->idate($this->date_start)."'":"null").','; - $sql.= " ".(! empty($this->date_end)?"'".$this->db->idate($this->date_end)."'":"null"); - $sql.= ", ".($this->fk_multicurrency > 0?$this->fk_multicurrency:'null'); - $sql.= ", '".$this->db->escape($this->multicurrency_code)."'"; - $sql.= ", ".$this->multicurrency_subprice; - $sql.= ", ".$this->multicurrency_total_ht; - $sql.= ", ".$this->multicurrency_total_tva; - $sql.= ", ".$this->multicurrency_total_ttc; - $sql.= ')'; + $sql .= ' (fk_propal, fk_parent_line, label, description, fk_product, product_type,'; + $sql .= ' fk_remise_except, qty, vat_src_code, tva_tx, localtax1_tx, localtax2_tx, localtax1_type, localtax2_type,'; + $sql .= ' subprice, remise_percent, '; + $sql .= ' info_bits, '; + $sql .= ' total_ht, total_tva, total_localtax1, total_localtax2, total_ttc, fk_product_fournisseur_price, buy_price_ht, special_code, rang,'; + $sql .= ' fk_unit,'; + $sql .= ' date_start, date_end'; + $sql .= ', fk_multicurrency, multicurrency_code, multicurrency_subprice, multicurrency_total_ht, multicurrency_total_tva, multicurrency_total_ttc)'; + $sql .= " VALUES (".$this->fk_propal.","; + $sql .= " ".($this->fk_parent_line > 0 ? "'".$this->db->escape($this->fk_parent_line)."'" : "null").","; + $sql .= " ".(!empty($this->label) ? "'".$this->db->escape($this->label)."'" : "null").","; + $sql .= " '".$this->db->escape($this->desc)."',"; + $sql .= " ".($this->fk_product ? "'".$this->db->escape($this->fk_product)."'" : "null").","; + $sql .= " '".$this->db->escape($this->product_type)."',"; + $sql .= " ".($this->fk_remise_except ? "'".$this->db->escape($this->fk_remise_except)."'" : "null").","; + $sql .= " ".price2num($this->qty).","; + $sql .= " ".(empty($this->vat_src_code) ? "''" : "'".$this->db->escape($this->vat_src_code)."'").","; + $sql .= " ".price2num($this->tva_tx).","; + $sql .= " ".price2num($this->localtax1_tx).","; + $sql .= " ".price2num($this->localtax2_tx).","; + $sql .= " '".$this->db->escape($this->localtax1_type)."',"; + $sql .= " '".$this->db->escape($this->localtax2_type)."',"; + $sql .= " ".(price2num($this->subprice) !== '' ?price2num($this->subprice) : "null").","; + $sql .= " ".price2num($this->remise_percent).","; + $sql .= " ".(isset($this->info_bits) ? "'".$this->db->escape($this->info_bits)."'" : "null").","; + $sql .= " ".price2num($this->total_ht).","; + $sql .= " ".price2num($this->total_tva).","; + $sql .= " ".price2num($this->total_localtax1).","; + $sql .= " ".price2num($this->total_localtax2).","; + $sql .= " ".price2num($this->total_ttc).","; + $sql .= " ".(!empty($this->fk_fournprice) ? "'".$this->db->escape($this->fk_fournprice)."'" : "null").","; + $sql .= " ".(isset($this->pa_ht) ? "'".price2num($this->pa_ht)."'" : "null").","; + $sql .= ' '.$this->special_code.','; + $sql .= ' '.$this->rang.','; + $sql .= ' '.(!$this->fk_unit ? 'NULL' : $this->fk_unit).','; + $sql .= " ".(!empty($this->date_start) ? "'".$this->db->idate($this->date_start)."'" : "null").','; + $sql .= " ".(!empty($this->date_end) ? "'".$this->db->idate($this->date_end)."'" : "null"); + $sql .= ", ".($this->fk_multicurrency > 0 ? $this->fk_multicurrency : 'null'); + $sql .= ", '".$this->db->escape($this->multicurrency_code)."'"; + $sql .= ", ".$this->multicurrency_subprice; + $sql .= ", ".$this->multicurrency_total_ht; + $sql .= ", ".$this->multicurrency_total_tva; + $sql .= ", ".$this->multicurrency_total_ttc; + $sql .= ')'; dol_syslog(get_class($this).'::insert', LOG_DEBUG); - $resql=$this->db->query($sql); + $resql = $this->db->query($sql); if ($resql) { - $this->rowid=$this->db->last_insert_id(MAIN_DB_PREFIX.'propaldet'); + $this->rowid = $this->db->last_insert_id(MAIN_DB_PREFIX.'propaldet'); if (empty($conf->global->MAIN_EXTRAFIELDS_DISABLED)) // For avoid conflicts if trigger used { - $this->id=$this->rowid; - $result=$this->insertExtraFields(); + $this->id = $this->rowid; + $result = $this->insertExtraFields(); if ($result < 0) { $error++; } } - if (! $error && ! $notrigger) + if (!$error && !$notrigger) { // Call trigger - $result=$this->call_trigger('LINEPROPAL_INSERT', $user); + $result = $this->call_trigger('LINEPROPAL_INSERT', $user); if ($result < 0) { $this->db->rollback(); @@ -4026,7 +4029,7 @@ class PropaleLigne extends CommonObjectLine } else { - $this->error=$this->db->error()." sql=".$sql; + $this->error = $this->db->error()." sql=".$sql; $this->db->rollback(); return -1; } @@ -4043,18 +4046,18 @@ class PropaleLigne extends CommonObjectLine { global $conf; - $error=0; + $error = 0; $this->db->begin(); $sql = "DELETE FROM ".MAIN_DB_PREFIX."propaldet WHERE rowid = ".$this->rowid; dol_syslog("PropaleLigne::delete", LOG_DEBUG); - if ($this->db->query($sql) ) + if ($this->db->query($sql)) { // Remove extrafields - if ((! $error) && (empty($conf->global->MAIN_EXTRAFIELDS_DISABLED))) // For avoid conflicts if trigger used + if ((!$error) && (empty($conf->global->MAIN_EXTRAFIELDS_DISABLED))) // For avoid conflicts if trigger used { - $this->id=$this->rowid; - $result=$this->deleteExtraFields(); + $this->id = $this->rowid; + $result = $this->deleteExtraFields(); if ($result < 0) { $error++; @@ -4062,10 +4065,10 @@ class PropaleLigne extends CommonObjectLine } } - if (! $error && ! $notrigger) + if (!$error && !$notrigger) { // Call trigger - $result=$this->call_trigger('LINEPROPAL_DELETE', $user); + $result = $this->call_trigger('LINEPROPAL_DELETE', $user); if ($result < 0) { $this->db->rollback(); @@ -4080,7 +4083,7 @@ class PropaleLigne extends CommonObjectLine } else { - $this->error=$this->db->error()." sql=".$sql; + $this->error = $this->db->error()." sql=".$sql; $this->db->rollback(); return -1; } @@ -4094,31 +4097,31 @@ class PropaleLigne extends CommonObjectLine */ public function update($notrigger = 0) { - global $conf,$user; + global $conf, $user; - $error=0; + $error = 0; $pa_ht_isemptystring = (empty($this->pa_ht) && $this->pa_ht == ''); // If true, we can use a default value. If this->pa_ht = '0', we must use '0'. // 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->total_localtax1)) $this->total_localtax1=0; - if (empty($this->total_localtax2)) $this->total_localtax2=0; - if (empty($this->localtax1_type)) $this->localtax1_type=0; - if (empty($this->localtax2_type)) $this->localtax2_type=0; - if (empty($this->marque_tx)) $this->marque_tx=0; - if (empty($this->marge_tx)) $this->marge_tx=0; - if (empty($this->price)) $this->price=0; // TODO A virer - if (empty($this->remise)) $this->remise=0; // TODO A virer - 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->fk_fournprice)) $this->fk_fournprice=0; - if (empty($this->subprice)) $this->subprice=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->total_localtax1)) $this->total_localtax1 = 0; + if (empty($this->total_localtax2)) $this->total_localtax2 = 0; + if (empty($this->localtax1_type)) $this->localtax1_type = 0; + if (empty($this->localtax2_type)) $this->localtax2_type = 0; + if (empty($this->marque_tx)) $this->marque_tx = 0; + if (empty($this->marge_tx)) $this->marge_tx = 0; + if (empty($this->price)) $this->price = 0; // TODO A virer + if (empty($this->remise)) $this->remise = 0; // TODO A virer + 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->fk_fournprice)) $this->fk_fournprice = 0; + if (empty($this->subprice)) $this->subprice = 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 && $pa_ht_isemptystring) @@ -4137,64 +4140,64 @@ class PropaleLigne extends CommonObjectLine // Mise a jour ligne en base $sql = "UPDATE ".MAIN_DB_PREFIX."propaldet SET"; - $sql.= " description='".$this->db->escape($this->desc)."'"; - $sql.= ", label=".(! empty($this->label)?"'".$this->db->escape($this->label)."'":"null"); - $sql.= ", product_type=".$this->product_type; - $sql.= ", vat_src_code = '".(empty($this->vat_src_code)?'':$this->vat_src_code)."'"; - $sql.= ", tva_tx='".price2num($this->tva_tx)."'"; - $sql.= ", localtax1_tx=".price2num($this->localtax1_tx); - $sql.= ", localtax2_tx=".price2num($this->localtax2_tx); - $sql.= ", localtax1_type='".$this->db->escape($this->localtax1_type)."'"; - $sql.= ", localtax2_type='".$this->db->escape($this->localtax2_type)."'"; - $sql.= ", qty='".price2num($this->qty)."'"; - $sql.= ", subprice=".price2num($this->subprice).""; - $sql.= ", remise_percent=".price2num($this->remise_percent).""; - $sql.= ", price=".price2num($this->price).""; // TODO A virer - $sql.= ", remise=".price2num($this->remise).""; // TODO A virer - $sql.= ", info_bits='".$this->db->escape($this->info_bits)."'"; + $sql .= " description='".$this->db->escape($this->desc)."'"; + $sql .= ", label=".(!empty($this->label) ? "'".$this->db->escape($this->label)."'" : "null"); + $sql .= ", product_type=".$this->product_type; + $sql .= ", vat_src_code = '".(empty($this->vat_src_code) ? '' : $this->vat_src_code)."'"; + $sql .= ", tva_tx='".price2num($this->tva_tx)."'"; + $sql .= ", localtax1_tx=".price2num($this->localtax1_tx); + $sql .= ", localtax2_tx=".price2num($this->localtax2_tx); + $sql .= ", localtax1_type='".$this->db->escape($this->localtax1_type)."'"; + $sql .= ", localtax2_type='".$this->db->escape($this->localtax2_type)."'"; + $sql .= ", qty='".price2num($this->qty)."'"; + $sql .= ", subprice=".price2num($this->subprice).""; + $sql .= ", remise_percent=".price2num($this->remise_percent).""; + $sql .= ", price=".price2num($this->price).""; // TODO A virer + $sql .= ", remise=".price2num($this->remise).""; // TODO A virer + $sql .= ", info_bits='".$this->db->escape($this->info_bits)."'"; if (empty($this->skip_update_total)) { - $sql.= ", total_ht=".price2num($this->total_ht).""; - $sql.= ", total_tva=".price2num($this->total_tva).""; - $sql.= ", total_ttc=".price2num($this->total_ttc).""; - $sql.= ", total_localtax1=".price2num($this->total_localtax1).""; - $sql.= ", total_localtax2=".price2num($this->total_localtax2).""; + $sql .= ", total_ht=".price2num($this->total_ht).""; + $sql .= ", total_tva=".price2num($this->total_tva).""; + $sql .= ", total_ttc=".price2num($this->total_ttc).""; + $sql .= ", total_localtax1=".price2num($this->total_localtax1).""; + $sql .= ", total_localtax2=".price2num($this->total_localtax2).""; } - $sql.= ", fk_product_fournisseur_price=".(! empty($this->fk_fournprice)?"'".$this->db->escape($this->fk_fournprice)."'":"null"); - $sql.= ", buy_price_ht=".price2num($this->pa_ht); - if (strlen($this->special_code)) $sql.= ", special_code=".$this->special_code; - $sql.= ", fk_parent_line=".($this->fk_parent_line>0?$this->fk_parent_line:"null"); - if (! empty($this->rang)) $sql.= ", rang=".$this->rang; - $sql.= ", date_start=".(! empty($this->date_start)?"'".$this->db->idate($this->date_start)."'":"null"); - $sql.= ", date_end=".(! empty($this->date_end)?"'".$this->db->idate($this->date_end)."'":"null"); - $sql.= ", fk_unit=".(!$this->fk_unit ? 'NULL' : $this->fk_unit); + $sql .= ", fk_product_fournisseur_price=".(!empty($this->fk_fournprice) ? "'".$this->db->escape($this->fk_fournprice)."'" : "null"); + $sql .= ", buy_price_ht=".price2num($this->pa_ht); + if (strlen($this->special_code)) $sql .= ", special_code=".$this->special_code; + $sql .= ", fk_parent_line=".($this->fk_parent_line > 0 ? $this->fk_parent_line : "null"); + if (!empty($this->rang)) $sql .= ", rang=".$this->rang; + $sql .= ", date_start=".(!empty($this->date_start) ? "'".$this->db->idate($this->date_start)."'" : "null"); + $sql .= ", date_end=".(!empty($this->date_end) ? "'".$this->db->idate($this->date_end)."'" : "null"); + $sql .= ", fk_unit=".(!$this->fk_unit ? 'NULL' : $this->fk_unit); // Multicurrency - $sql.= ", multicurrency_subprice=".price2num($this->multicurrency_subprice).""; - $sql.= ", multicurrency_total_ht=".price2num($this->multicurrency_total_ht).""; - $sql.= ", multicurrency_total_tva=".price2num($this->multicurrency_total_tva).""; - $sql.= ", multicurrency_total_ttc=".price2num($this->multicurrency_total_ttc).""; + $sql .= ", multicurrency_subprice=".price2num($this->multicurrency_subprice).""; + $sql .= ", multicurrency_total_ht=".price2num($this->multicurrency_total_ht).""; + $sql .= ", multicurrency_total_tva=".price2num($this->multicurrency_total_tva).""; + $sql .= ", multicurrency_total_ttc=".price2num($this->multicurrency_total_ttc).""; - $sql.= " WHERE rowid = ".$this->rowid; + $sql .= " WHERE rowid = ".$this->rowid; dol_syslog(get_class($this)."::update", LOG_DEBUG); - $resql=$this->db->query($sql); + $resql = $this->db->query($sql); if ($resql) { if (empty($conf->global->MAIN_EXTRAFIELDS_DISABLED)) // For avoid conflicts if trigger used { - $this->id=$this->rowid; - $result=$this->insertExtraFields(); + $this->id = $this->rowid; + $result = $this->insertExtraFields(); if ($result < 0) { $error++; } } - if (! $error && ! $notrigger) + if (!$error && !$notrigger) { // Call trigger - $result=$this->call_trigger('LINEPROPAL_UPDATE', $user); + $result = $this->call_trigger('LINEPROPAL_UPDATE', $user); if ($result < 0) { $this->db->rollback(); @@ -4208,7 +4211,7 @@ class PropaleLigne extends CommonObjectLine } else { - $this->error=$this->db->error(); + $this->error = $this->db->error(); $this->db->rollback(); return -2; } @@ -4228,14 +4231,14 @@ class PropaleLigne extends CommonObjectLine // Mise a jour ligne en base $sql = "UPDATE ".MAIN_DB_PREFIX."propaldet SET"; - $sql.= " total_ht=".price2num($this->total_ht, 'MT').""; - $sql.= ",total_tva=".price2num($this->total_tva, 'MT').""; - $sql.= ",total_ttc=".price2num($this->total_ttc, 'MT').""; - $sql.= " WHERE rowid = ".$this->rowid; + $sql .= " total_ht=".price2num($this->total_ht, 'MT').""; + $sql .= ",total_tva=".price2num($this->total_tva, 'MT').""; + $sql .= ",total_ttc=".price2num($this->total_ttc, 'MT').""; + $sql .= " WHERE rowid = ".$this->rowid; dol_syslog("PropaleLigne::update_total", LOG_DEBUG); - $resql=$this->db->query($sql); + $resql = $this->db->query($sql); if ($resql) { $this->db->commit(); @@ -4243,7 +4246,7 @@ class PropaleLigne extends CommonObjectLine } else { - $this->error=$this->db->error(); + $this->error = $this->db->error(); $this->db->rollback(); return -2; } diff --git a/htdocs/comm/propal/contact.php b/htdocs/comm/propal/contact.php index 14f5913c4ce..248ad8f47a0 100644 --- a/htdocs/comm/propal/contact.php +++ b/htdocs/comm/propal/contact.php @@ -62,7 +62,7 @@ if ($id > 0 || ! empty($ref)) $error++; } } -if (! $error) +if (!$error) { $object->fetch_thirdparty(); } @@ -109,7 +109,7 @@ elseif ($action == 'swapstatut' && $user->rights->propale->creer) { if ($object->id > 0) { - $result=$object->swapContactStatus(GETPOST('ligne')); + $result = $object->swapContactStatus(GETPOST('ligne')); } } @@ -143,7 +143,7 @@ elseif ($action == 'setaddress' && $user->rights->propale->creer) llxHeader('', $langs->trans('Proposal'), 'EN:Commercial_Proposals|FR:Proposition_commerciale|ES:Presupuestos'); $form = new Form($db); -$formcompany= new FormCompany($db); +$formcompany = new FormCompany($db); $formother = new FormOther($db); if ($object->id > 0) @@ -205,10 +205,10 @@ if ($object->id > 0) // 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) + $dirtpls = array_merge($conf->modules_parts['tpl'], array('/core/tpl')); + foreach ($dirtpls as $reldir) { - $res=@include dol_buildpath($reldir.'/contacts.tpl.php'); + $res = @include dol_buildpath($reldir.'/contacts.tpl.php'); if ($res) break; } } diff --git a/htdocs/comm/propal/document.php b/htdocs/comm/propal/document.php index 55a21445be2..af2e866966a 100644 --- a/htdocs/comm/propal/document.php +++ b/htdocs/comm/propal/document.php @@ -32,8 +32,8 @@ require_once DOL_DOCUMENT_ROOT.'/core/lib/propal.lib.php'; require_once DOL_DOCUMENT_ROOT.'/core/lib/files.lib.php'; require_once DOL_DOCUMENT_ROOT.'/core/lib/images.lib.php'; require_once DOL_DOCUMENT_ROOT.'/core/class/html.formfile.class.php'; -if (! empty($conf->projet->enabled)) { - require_once DOL_DOCUMENT_ROOT . '/projet/class/project.class.php'; +if (!empty($conf->projet->enabled)) { + require_once DOL_DOCUMENT_ROOT.'/projet/class/project.class.php'; } // Load translation files required by the page @@ -79,7 +79,7 @@ if ($object->id > 0) { $object->fetch_thirdparty(); $upload_dir = $conf->propal->multidir_output[$object->entity].'/'.dol_sanitizeFileName($object->ref); - include_once DOL_DOCUMENT_ROOT . '/core/actions_linkedfiles.inc.php'; + include_once DOL_DOCUMENT_ROOT.'/core/actions_linkedfiles.inc.php'; } @@ -176,8 +176,8 @@ if ($object->id > 0) $modulepart = 'propal'; $permission = $user->rights->propal->creer; $permtoedit = $user->rights->propal->creer; - $param = '&id=' . $object->id; - include_once DOL_DOCUMENT_ROOT . '/core/tpl/document_actions_post_headers.tpl.php'; + $param = '&id='.$object->id; + include_once DOL_DOCUMENT_ROOT.'/core/tpl/document_actions_post_headers.tpl.php'; } else { diff --git a/htdocs/comm/propal/index.php b/htdocs/comm/propal/index.php index d802548ac6b..bfd7bdb7baf 100644 --- a/htdocs/comm/propal/index.php +++ b/htdocs/comm/propal/index.php @@ -26,7 +26,7 @@ require '../../main.inc.php'; require_once DOL_DOCUMENT_ROOT.'/core/class/html.formfile.class.php'; -require_once DOL_DOCUMENT_ROOT .'/comm/propal/class/propal.class.php'; +require_once DOL_DOCUMENT_ROOT.'/comm/propal/class/propal.class.php'; $hookmanager = new HookManager($db); @@ -37,8 +37,8 @@ $hookmanager->initHooks(array('proposalindex')); $langs->loadLangs(array('propal', 'companies')); // Security check -$socid=GETPOST('socid', 'int'); -if (isset($user->socid) && $user->socid > 0) +$socid = GETPOST('socid', 'int'); +if (isset($user->socid) && $user->socid > 0) { $action = ''; $socid = $user->socid; @@ -49,12 +49,12 @@ $result = restrictedArea($user, 'propal'); /* * View */ -$now=dol_now(); -$propalstatic=new Propal($db); -$companystatic=new Societe($db); +$now = dol_now(); +$propalstatic = new Propal($db); +$companystatic = new Societe($db); $form = new Form($db); $formfile = new FormFile($db); -$help_url="EN:Module_Commercial_Proposals|FR:Module_Propositions_commerciales|ES:Módulo_Presupuestos"; +$help_url = "EN:Module_Commercial_Proposals|FR:Module_Propositions_commerciales|ES:Módulo_Presupuestos"; llxHeader("", $langs->trans("ProspectionArea"), $help_url); @@ -65,15 +65,16 @@ print load_fiche_titre($langs->trans("ProspectionArea"), '', 'commercial'); 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 { print ''; + print '
'; print ''; - print ''; + print '
'; print ''; print ''; - print "
'.$langs->trans("Search").'
'; print $langs->trans("Proposal").':

\n"; + print "

\n"; } @@ -82,25 +83,25 @@ if (! empty($conf->global->MAIN_SEARCH_FORM_ON_HOME_AREAS)) // This is usele */ $sql = "SELECT count(p.rowid), p.fk_statut"; -$sql.= " FROM ".MAIN_DB_PREFIX."societe as s"; -$sql.= ", ".MAIN_DB_PREFIX."propal as p"; -if (!$user->rights->societe->client->voir && !$socid) $sql.= ", ".MAIN_DB_PREFIX."societe_commerciaux as sc"; -$sql.= " WHERE p.fk_soc = s.rowid"; -$sql.= " AND p.entity IN (".getEntity('propal').")"; -if ($user->socid) $sql.=' AND p.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.= " AND p.fk_statut IN (0,1,2,3,4)"; -$sql.= " GROUP BY p.fk_statut"; +$sql .= " FROM ".MAIN_DB_PREFIX."societe as s"; +$sql .= ", ".MAIN_DB_PREFIX."propal as p"; +if (!$user->rights->societe->client->voir && !$socid) $sql .= ", ".MAIN_DB_PREFIX."societe_commerciaux as sc"; +$sql .= " WHERE p.fk_soc = s.rowid"; +$sql .= " AND p.entity IN (".getEntity('propal').")"; +if ($user->socid) $sql .= ' AND p.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 .= " AND p.fk_statut IN (0,1,2,3,4)"; +$sql .= " GROUP BY p.fk_statut"; $resql = $db->query($sql); if ($resql) { $num = $db->num_rows($resql); $i = 0; - $total=0; - $totalinprocess=0; - $dataseries=array(); - $vals=array(); + $total = 0; + $totalinprocess = 0; + $dataseries = array(); + $vals = array(); // -1=Canceled, 0=Draft, 1=Validated, (2=Accepted/On process not managed for customer orders), 3=Closed (Sent/Received, billed or not) while ($i < $num) { @@ -109,26 +110,27 @@ if ($resql) { //if ($row[1]!=-1 && ($row[1]!=3 || $row[2]!=1)) { - $vals[$row[1]]=$row[0]; - $totalinprocess+=$row[0]; + $vals[$row[1]] = $row[0]; + $totalinprocess += $row[0]; } - $total+=$row[0]; + $total += $row[0]; } $i++; } $db->free($resql); - print ''; + print '
'; + print '
'; print ''."\n"; - $listofstatus=array(0,1,2,3,4); + $listofstatus = array(0, 1, 2, 3, 4); foreach ($listofstatus as $status) { - $dataseries[]=array($propalstatic->LibStatut($status, 1), (isset($vals[$status])?(int) $vals[$status]:0)); - if (! $conf->use_javascript_ajax) + $dataseries[] = array($propalstatic->LibStatut($status, 1), (isset($vals[$status]) ? (int) $vals[$status] : 0)); + if (!$conf->use_javascript_ajax) { print ''; print ''; - print ''; + print ''; print "\n"; } } @@ -144,14 +146,14 @@ if ($resql) $dolgraph->SetType(array('pie')); $dolgraph->setWidth('100%'); $dolgraph->draw('idgraphthirdparties'); - print $dolgraph->show($total?0:1); + print $dolgraph->show($total ? 0 : 1); print ''; } //if ($totalinprocess != $total) //print ''; print ''; - print "
'.$langs->trans("Statistics").' - '.$langs->trans("Proposals").'
'.$propalstatic->LibStatut($status, 0).''.(isset($vals[$status])?$vals[$status]:0).''.(isset($vals[$status]) ? $vals[$status] : 0).'
'.$langs->trans("Total").' ('.$langs->trans("CustomersOrdersRunning").')'.$totalinprocess.'
'.$langs->trans("Total").''.$total.'

"; + print "

"; } else { @@ -162,45 +164,45 @@ else /* * Draft proposals */ -if (! empty($conf->propal->enabled)) +if (!empty($conf->propal->enabled)) { $sql = "SELECT c.rowid, c.ref, s.nom as socname, s.rowid as socid, s.canvas, s.client"; - $sql.= " FROM ".MAIN_DB_PREFIX."propal as c"; - $sql.= ", ".MAIN_DB_PREFIX."societe as s"; - 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('propal').")"; - $sql.= " AND c.fk_statut = 0"; - 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; + $sql .= " FROM ".MAIN_DB_PREFIX."propal as c"; + $sql .= ", ".MAIN_DB_PREFIX."societe as s"; + 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('propal').")"; + $sql .= " AND c.fk_statut = 0"; + 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; - $resql=$db->query($sql); + $resql = $db->query($sql); if ($resql) { $num = $db->num_rows($resql); if ($num) { print '
'; - print ''; + print '
'; print ''; $langs->load("propal"); print ''; $i = 0; - $nbofloop=min($num, (empty($conf->global->MAIN_MAXLIST_OVERLOAD)?500:$conf->global->MAIN_MAXLIST_OVERLOAD)); + $nbofloop = min($num, (empty($conf->global->MAIN_MAXLIST_OVERLOAD) ? 500 : $conf->global->MAIN_MAXLIST_OVERLOAD)); while ($i < $nbofloop) { $obj = $db->fetch_object($resql); print ''; - $propalstatic->id=$obj->rowid; - $propalstatic->ref=$obj->ref; + $propalstatic->id = $obj->rowid; + $propalstatic->ref = $obj->ref; print ''; - $companystatic->id=$obj->socid; - $companystatic->name=$obj->socname; - $companystatic->client=$obj->client; - $companystatic->canvas=$obj->canvas; + $companystatic->id = $obj->socid; + $companystatic->name = $obj->socname; + $companystatic->client = $obj->client; + $companystatic->canvas = $obj->canvas; print ''; print ''; @@ -210,7 +212,7 @@ if (! empty($conf->propal->enabled)) { print '"; } - elseif ($total>0) + elseif ($total > 0) { print '"; } @@ -225,30 +227,30 @@ if (! empty($conf->propal->enabled)) print '
'; -$max=5; +$max = 5; /* * Last modified proposals */ $sql = "SELECT c.rowid, c.entity, c.ref, c.fk_statut, s.nom as socname, s.rowid as socid, s.canvas, s.client,"; -$sql.= " date_cloture as datec"; -$sql.= " FROM ".MAIN_DB_PREFIX."propal as c"; -$sql.= ", ".MAIN_DB_PREFIX."societe as s"; -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('propal').")"; +$sql .= " date_cloture as datec"; +$sql .= " FROM ".MAIN_DB_PREFIX."propal as c"; +$sql .= ", ".MAIN_DB_PREFIX."societe as s"; +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('propal').")"; //$sql.= " AND c.fk_statut > 2"; 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; -$sql.= " ORDER BY c.tms DESC"; -$sql.= $db->plimit($max, 0); +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); +$resql = $db->query($sql); if ($resql) { print '
'; - print '
'.$langs->trans("DraftPropals").' '.$num.'
'.$propalstatic->getNomUrl(1).''.$companystatic->getNomUrl(1, 'customer', 24).'
'.$langs->trans("XMoreLines", ($num - $nbofloop))."
'.$langs->trans("Total").''.price($total)."
'; + print '
'; print ''; print ''; @@ -263,8 +265,8 @@ if ($resql) print ''; print ''; - $companystatic->id=$obj->socid; - $companystatic->name=$obj->socname; - $companystatic->client=$obj->client; - $companystatic->canvas=$obj->canvas; + $companystatic->id = $obj->socid; + $companystatic->name = $obj->socname; + $companystatic->client = $obj->client; + $companystatic->canvas = $obj->canvas; print ''; print ''; @@ -305,25 +307,25 @@ else dol_print_error($db); /* * Opened proposals */ -if (! empty($conf->propal->enabled) && $user->rights->propale->lire) +if (!empty($conf->propal->enabled) && $user->rights->propale->lire) { $langs->load("propal"); - $now=dol_now(); + $now = dol_now(); $sql = "SELECT s.nom as socname, s.rowid as socid, s.canvas, s.client"; - $sql.= ", p.rowid as propalid, p.entity, p.total as total_ttc, p.total_ht, p.ref, p.fk_statut, p.datep as dp, p.fin_validite as dfv"; - $sql.= " FROM ".MAIN_DB_PREFIX."societe as s"; - $sql.= ", ".MAIN_DB_PREFIX."propal as p"; - if (!$user->rights->societe->client->voir && !$socid) $sql.= ", ".MAIN_DB_PREFIX."societe_commerciaux as sc"; - $sql.= " WHERE p.fk_soc = s.rowid"; - $sql.= " AND p.entity IN (".getEntity('propal').")"; - $sql.= " AND p.fk_statut = 1"; - 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 p.rowid DESC"; + $sql .= ", p.rowid as propalid, p.entity, p.total as total_ttc, p.total_ht, p.ref, p.fk_statut, p.datep as dp, p.fin_validite as dfv"; + $sql .= " FROM ".MAIN_DB_PREFIX."societe as s"; + $sql .= ", ".MAIN_DB_PREFIX."propal as p"; + if (!$user->rights->societe->client->voir && !$socid) $sql .= ", ".MAIN_DB_PREFIX."societe_commerciaux as sc"; + $sql .= " WHERE p.fk_soc = s.rowid"; + $sql .= " AND p.entity IN (".getEntity('propal').")"; + $sql .= " AND p.fk_statut = 1"; + 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 p.rowid DESC"; - $result=$db->query($sql); + $result = $db->query($sql); if ($result) { $total = 0; @@ -332,10 +334,10 @@ if (! empty($conf->propal->enabled) && $user->rights->propale->lire) if ($num > 0) { print '
'; - print '
'.$langs->trans("LastModifiedProposals", $max).'
'; - $propalstatic->id=$obj->rowid; - $propalstatic->ref=$obj->ref; + $propalstatic->id = $obj->rowid; + $propalstatic->ref = $obj->ref; print ''; print ''; print '
'; @@ -276,18 +278,18 @@ if ($resql) print ''; - $filename=dol_sanitizeFileName($obj->ref); - $filedir=$conf->propal->multidir_output[$obj->entity] . '/' . dol_sanitizeFileName($obj->ref); - $urlsource=$_SERVER['PHP_SELF'].'?id='.$obj->rowid; + $filename = dol_sanitizeFileName($obj->ref); + $filedir = $conf->propal->multidir_output[$obj->entity].'/'.dol_sanitizeFileName($obj->ref); + $urlsource = $_SERVER['PHP_SELF'].'?id='.$obj->rowid; print $formfile->getDocumentsLink($propalstatic->element, $filename, $filedir); print '
'; print '
'.$companystatic->getNomUrl(1, 'customer').''.dol_print_date($db->jdate($obj->datec), 'day').'
'; + print '
'; print ''; - $nbofloop=min($num, (empty($conf->global->MAIN_MAXLIST_OVERLOAD)?500:$conf->global->MAIN_MAXLIST_OVERLOAD)); + $nbofloop = min($num, (empty($conf->global->MAIN_MAXLIST_OVERLOAD) ? 500 : $conf->global->MAIN_MAXLIST_OVERLOAD)); while ($i < $nbofloop) { $obj = $db->fetch_object($result); @@ -345,8 +347,8 @@ if (! empty($conf->propal->enabled) && $user->rights->propale->lire) // Ref print '"; - $companystatic->id=$obj->socid; - $companystatic->name=$obj->socname; - $companystatic->client=$obj->client; - $companystatic->canvas=$obj->canvas; + $companystatic->id = $obj->socid; + $companystatic->name = $obj->socname; + $companystatic->client = $obj->client; + $companystatic->canvas = $obj->canvas; print ''."\n"; print '"; } - elseif ($total>0) + elseif ($total > 0) { print '"; } @@ -419,7 +421,7 @@ if (! empty($conf->propal->enabled)) $num = $db->num_rows($resql); print '
'; - print '
'.$langs->trans("ProposalsOpened").' '.$num.'
'; - $propalstatic->id=$obj->propalid; - $propalstatic->ref=$obj->ref; + $propalstatic->id = $obj->propalid; + $propalstatic->ref = $obj->ref; print ''; print ''; print '
'; @@ -356,18 +358,18 @@ if (! empty($conf->propal->enabled) && $user->rights->propale->lire) if ($db->jdate($obj->dfv) < ($now - $conf->propal->cloture->warning_delay)) print img_warning($langs->trans("Late")); print ''; - $filename=dol_sanitizeFileName($obj->ref); - $filedir=$conf->propal->multidir_output[$obj->entity] . '/' . dol_sanitizeFileName($obj->ref); - $urlsource=$_SERVER['PHP_SELF'].'?id='.$obj->propalid; + $filename = dol_sanitizeFileName($obj->ref); + $filedir = $conf->propal->multidir_output[$obj->entity].'/'.dol_sanitizeFileName($obj->ref); + $urlsource = $_SERVER['PHP_SELF'].'?id='.$obj->propalid; print $formfile->getDocumentsLink($propalstatic->element, $filename, $filedir); print '
'; print "
'.$companystatic->getNomUrl(1, 'customer', 44).''; @@ -382,7 +384,7 @@ if (! empty($conf->propal->enabled) && $user->rights->propale->lire) { print '
'.$langs->trans("XMoreLines", ($num - $nbofloop))."
'.$langs->trans("Total")."".price($total)." 
'; + print '
'; print ''; print ''; @@ -492,7 +494,7 @@ if (! empty($conf->propal->enabled)) $num = $db->num_rows($resql); print '
'; - print '
'.$langs->trans("ProposalsToProcess").' '.$num.'
'; + print '
'; print ''; print ''; diff --git a/htdocs/comm/propal/list.php b/htdocs/comm/propal/list.php index bccc742aa8e..4a38ff4096a 100644 --- a/htdocs/comm/propal/list.php +++ b/htdocs/comm/propal/list.php @@ -47,57 +47,57 @@ require_once DOL_DOCUMENT_ROOT.'/projet/class/project.class.php'; // Load translation files required by the page $langs->loadLangs(array('companies', 'propal', 'compta', 'bills', 'orders', 'products', 'deliveries', 'categories')); -$socid=GETPOST('socid', 'int'); +$socid = GETPOST('socid', 'int'); -$action=GETPOST('action', 'alpha'); -$massaction=GETPOST('massaction', 'alpha'); -$show_files=GETPOST('show_files', 'int'); -$confirm=GETPOST('confirm', 'alpha'); +$action = GETPOST('action', 'alpha'); +$massaction = GETPOST('massaction', 'alpha'); +$show_files = GETPOST('show_files', 'int'); +$confirm = GETPOST('confirm', 'alpha'); $toselect = GETPOST('toselect', 'array'); -$contextpage=GETPOST('contextpage', 'aZ')?GETPOST('contextpage', 'aZ'):'proposallist'; +$contextpage = GETPOST('contextpage', 'aZ') ?GETPOST('contextpage', 'aZ') : 'proposallist'; -$search_user=GETPOST('search_user', 'int'); -$search_sale=GETPOST('search_sale', 'int'); -$search_ref=GETPOST('sf_ref')?GETPOST('sf_ref', 'alpha'):GETPOST('search_ref', 'alpha'); -$search_refcustomer=GETPOST('search_refcustomer', 'alpha'); +$search_user = GETPOST('search_user', 'int'); +$search_sale = GETPOST('search_sale', 'int'); +$search_ref = GETPOST('sf_ref') ?GETPOST('sf_ref', 'alpha') : GETPOST('search_ref', 'alpha'); +$search_refcustomer = GETPOST('search_refcustomer', 'alpha'); -$search_refproject=GETPOST('search_refproject', 'alpha'); -$search_project=GETPOST('search_project', 'alpha'); +$search_refproject = GETPOST('search_refproject', 'alpha'); +$search_project = GETPOST('search_project', 'alpha'); -$search_societe=GETPOST('search_societe', 'alpha'); -$search_montant_ht=GETPOST('search_montant_ht', 'alpha'); -$search_montant_vat=GETPOST('search_montant_vat', 'alpha'); -$search_montant_ttc=GETPOST('search_montant_ttc', 'alpha'); -$search_login=GETPOST('search_login', 'alpha'); -$search_product_category=GETPOST('search_product_category', 'int'); -$search_town=GETPOST('search_town', 'alpha'); -$search_zip=GETPOST('search_zip', 'alpha'); -$search_state=trim(GETPOST("search_state")); -$search_country=GETPOST("search_country", 'int'); -$search_type_thirdparty=GETPOST("search_type_thirdparty", 'int'); -$search_day=GETPOST("search_day", "int"); -$search_month=GETPOST("search_month", "int"); -$search_year=GETPOST("search_year", "int"); -$search_dayfin=GETPOST("search_dayfin", "int"); -$search_month_end=GETPOST("search_month_end", "int"); -$search_yearfin=GETPOST("search_yearfin", "int"); -$search_daydelivery=GETPOST("search_daydelivery", "int"); -$search_monthdelivery=GETPOST("search_monthdelivery", "int"); -$search_yeardelivery=GETPOST("search_yeardelivery", "int"); -$search_availability=GETPOST('search_availability', 'int'); -$search_categ_cus=trim(GETPOST("search_categ_cus", 'int')); -$search_btn=GETPOST('button_search', 'alpha'); -$search_remove_btn=GETPOST('button_removefilter', 'alpha'); +$search_societe = GETPOST('search_societe', 'alpha'); +$search_montant_ht = GETPOST('search_montant_ht', 'alpha'); +$search_montant_vat = GETPOST('search_montant_vat', 'alpha'); +$search_montant_ttc = GETPOST('search_montant_ttc', 'alpha'); +$search_login = GETPOST('search_login', 'alpha'); +$search_product_category = GETPOST('search_product_category', 'int'); +$search_town = GETPOST('search_town', 'alpha'); +$search_zip = GETPOST('search_zip', 'alpha'); +$search_state = trim(GETPOST("search_state")); +$search_country = GETPOST("search_country", 'int'); +$search_type_thirdparty = GETPOST("search_type_thirdparty", 'int'); +$search_day = GETPOST("search_day", "int"); +$search_month = GETPOST("search_month", "int"); +$search_year = GETPOST("search_year", "int"); +$search_dayfin = GETPOST("search_dayfin", "int"); +$search_month_end = GETPOST("search_month_end", "int"); +$search_yearfin = GETPOST("search_yearfin", "int"); +$search_daydelivery = GETPOST("search_daydelivery", "int"); +$search_monthdelivery = GETPOST("search_monthdelivery", "int"); +$search_yeardelivery = GETPOST("search_yeardelivery", "int"); +$search_availability = GETPOST('search_availability', 'int'); +$search_categ_cus = trim(GETPOST("search_categ_cus", 'int')); +$search_btn = GETPOST('button_search', 'alpha'); +$search_remove_btn = GETPOST('button_removefilter', 'alpha'); -$viewstatut=GETPOST('viewstatut', 'alpha'); +$viewstatut = GETPOST('viewstatut', 'alpha'); $optioncss = GETPOST('optioncss', 'alpha'); -$object_statut=GETPOST('search_statut', 'alpha'); +$object_statut = GETPOST('search_statut', 'alpha'); -$sall=trim((GETPOST('search_all', 'alphanohtml')!='')?GETPOST('search_all', 'alphanohtml'):GETPOST('sall', 'alphanohtml')); -$mesg=(GETPOST("msg") ? GETPOST("msg") : GETPOST("mesg")); +$sall = trim((GETPOST('search_all', 'alphanohtml') != '') ?GETPOST('search_all', 'alphanohtml') : GETPOST('sall', 'alphanohtml')); +$mesg = (GETPOST("msg") ? GETPOST("msg") : GETPOST("mesg")); -$limit = GETPOST('limit', 'int')?GETPOST('limit', 'int'):$conf->liste_limit; +$limit = GETPOST('limit', 'int') ?GETPOST('limit', 'int') : $conf->liste_limit; $sortfield = GETPOST("sortfield", 'alpha'); $sortorder = GETPOST("sortorder", 'alpha'); $page = GETPOST("page", 'int'); @@ -105,23 +105,23 @@ if (empty($page) || $page == -1 || !empty($search_btn) || !empty($search_remove_ $offset = $limit * $page; $pageprev = $page - 1; $pagenext = $page + 1; -if (! $sortfield) $sortfield='p.ref'; -if (! $sortorder) $sortorder='DESC'; +if (!$sortfield) $sortfield = 'p.ref'; +if (!$sortorder) $sortorder = 'DESC'; // Security check -$module='propal'; -$dbtable=''; -$objectid=''; -if (! empty($user->socid)) $socid=$user->socid; -if (! empty($socid)) +$module = 'propal'; +$dbtable = ''; +$objectid = ''; +if (!empty($user->socid)) $socid = $user->socid; +if (!empty($socid)) { - $objectid=$socid; - $module='societe'; - $dbtable='&societe'; + $objectid = $socid; + $module = 'societe'; + $dbtable = '&societe'; } $result = restrictedArea($user, $module, $objectid, $dbtable); -$diroutputmassaction=$conf->propal->multidir_output[$conf->entity] . '/temp/massgeneration/'.$user->id; +$diroutputmassaction = $conf->propal->multidir_output[$conf->entity].'/temp/massgeneration/'.$user->id; // Initialize technical object to manage hooks of page. Note that conf->hooks_modules contains array of hook context $object = new Propal($db); @@ -131,7 +131,7 @@ $extrafields = new ExtraFields($db); // fetch optionals attributes and labels $extrafields->fetch_name_optionals_label($object->table_element); -$search_array_options=$extrafields->getOptionalsFromPost($object->table_element, '', 'search_'); +$search_array_options = $extrafields->getOptionalsFromPost($object->table_element, '', 'search_'); // List of fields to search into when doing a "search in all" $fieldstosearchall = array( @@ -142,15 +142,15 @@ $fieldstosearchall = array( 's.name_alias'=>"AliasNameShort", 'p.note_public'=>'NotePublic', ); -if (empty($user->socid)) $fieldstosearchall["p.note_private"]="NotePrivate"; +if (empty($user->socid)) $fieldstosearchall["p.note_private"] = "NotePrivate"; -$checkedtypetiers=0; -$arrayfields=array( +$checkedtypetiers = 0; +$arrayfields = array( 'p.ref'=>array('label'=>"Ref", 'checked'=>1), 'p.ref_client'=>array('label'=>"RefCustomer", 'checked'=>1), - 'pr.ref'=>array('label'=>"ProjectRef", 'checked'=>1, 'enabled'=>(empty($conf->projet->enabled)?0:1)), - 'pr.title'=>array('label'=>"ProjectLabel", 'checked'=>0, 'enabled'=>(empty($conf->projet->enabled)?0:1)), + 'pr.ref'=>array('label'=>"ProjectRef", 'checked'=>1, 'enabled'=>(empty($conf->projet->enabled) ? 0 : 1)), + 'pr.title'=>array('label'=>"ProjectLabel", 'checked'=>0, 'enabled'=>(empty($conf->projet->enabled) ? 0 : 1)), 's.nom'=>array('label'=>"ThirdParty", 'checked'=>1), 's.town'=>array('label'=>"Town", 'checked'=>1), 's.zip'=>array('label'=>"Zip", 'checked'=>1), @@ -176,10 +176,10 @@ $arrayfields=array( // 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) + 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], 'checked'=>(($extrafields->attributes[$object->table_element]['list'][$key]<0)?0:1), 'position'=>$extrafields->attributes[$object->table_element]['pos'][$key], 'enabled'=>(abs($extrafields->attributes[$object->table_element]['list'][$key])!=3 && $extrafields->attributes[$object->table_element]['perms'][$key])); + if (!empty($extrafields->attributes[$object->table_element]['list'][$key])) + $arrayfields["ef.".$key] = array('label'=>$extrafields->attributes[$object->table_element]['label'][$key], 'checked'=>(($extrafields->attributes[$object->table_element]['list'][$key] < 0) ? 0 : 1), 'position'=>$extrafields->attributes[$object->table_element]['pos'][$key], 'enabled'=>(abs($extrafields->attributes[$object->table_element]['list'][$key]) != 3 && $extrafields->attributes[$object->table_element]['perms'][$key])); } } @@ -188,11 +188,11 @@ if (is_array($extrafields->attributes[$object->table_element]['label']) && count * 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 +$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'); include DOL_DOCUMENT_ROOT.'/core/actions_changeselectedfields.inc.php'; @@ -200,47 +200,47 @@ 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 tests are required to be compatible with all browsers { - $search_categ=''; - $search_user=''; - $search_sale=''; - $search_ref=''; - $search_refcustomer=''; - $search_refproject=''; - $search_project=''; - $search_societe=''; - $search_montant_ht=''; - $search_montant_vat=''; - $search_montant_ttc=''; - $search_login=''; - $search_product_category=''; - $search_town=''; - $search_zip=""; - $search_state=""; - $search_type=''; - $search_country=''; - $search_type_thirdparty=''; - $search_year=''; - $search_month=''; - $search_day=''; - $search_yearfin=''; - $search_month_end=''; - $search_dayfin=''; - $search_yeardelivery=''; - $search_monthdelivery=''; - $search_daydelivery=''; - $search_availability=''; - $viewstatut=''; - $object_statut=''; - $toselect=''; - $search_array_options=array(); - $search_categ_cus=0; + $search_categ = ''; + $search_user = ''; + $search_sale = ''; + $search_ref = ''; + $search_refcustomer = ''; + $search_refproject = ''; + $search_project = ''; + $search_societe = ''; + $search_montant_ht = ''; + $search_montant_vat = ''; + $search_montant_ttc = ''; + $search_login = ''; + $search_product_category = ''; + $search_town = ''; + $search_zip = ""; + $search_state = ""; + $search_type = ''; + $search_country = ''; + $search_type_thirdparty = ''; + $search_year = ''; + $search_month = ''; + $search_day = ''; + $search_yearfin = ''; + $search_month_end = ''; + $search_dayfin = ''; + $search_yeardelivery = ''; + $search_monthdelivery = ''; + $search_daydelivery = ''; + $search_availability = ''; + $viewstatut = ''; + $object_statut = ''; + $toselect = ''; + $search_array_options = array(); + $search_categ_cus = 0; } -if ($object_statut != '') $viewstatut=$object_statut; +if ($object_statut != '') $viewstatut = $object_statut; if (empty($reshook)) { - $objectclass='Propal'; - $objectlabel='Proposals'; + $objectclass = 'Propal'; + $objectlabel = 'Proposals'; $permissiontoread = $user->rights->propal->lire; $permissiontodelete = $user->rights->propal->supprimer; $permissiontoclose = $user->rights->propal->cloturer; @@ -254,68 +254,68 @@ if (empty($reshook)) * View */ -$now=dol_now(); +$now = dol_now(); $form = new Form($db); $formother = new FormOther($db); $formfile = new FormFile($db); $formpropal = new FormPropal($db); -$companystatic=new Societe($db); -$projectstatic=new Project($db); -$formcompany=new FormCompany($db); +$companystatic = new Societe($db); +$projectstatic = new Project($db); +$formcompany = new FormCompany($db); -$help_url='EN:Commercial_Proposals|FR:Proposition_commerciale|ES:Presupuestos'; +$help_url = 'EN:Commercial_Proposals|FR:Proposition_commerciale|ES:Presupuestos'; //llxHeader('',$langs->trans('Proposal'),$help_url); $sql = 'SELECT'; if ($sall || $search_product_category > 0) $sql = 'SELECT DISTINCT'; -$sql.= ' s.rowid as socid, s.nom as name, s.email, s.town, s.zip, s.fk_pays, s.client, s.code_client, '; -$sql.= " typent.code as typent_code,"; -$sql.= " ava.rowid as availability,"; -$sql.= " state.code_departement as state_code, state.nom as state_name,"; -$sql.= ' p.rowid, p.entity, p.note_private, p.total_ht, p.tva as total_vat, p.total as total_ttc, p.localtax1, p.localtax2, p.ref, p.ref_client, p.fk_statut, p.fk_user_author, p.datep as dp, p.fin_validite as dfv,p.date_livraison as ddelivery,'; -$sql.= ' p.datec as date_creation, p.tms as date_update, p.date_cloture as date_cloture,'; -$sql.= " pr.rowid as project_id, pr.ref as project_ref, pr.title as project_label,"; -$sql.= ' u.login'; -if (! $user->rights->societe->client->voir && ! $socid) $sql .= ", sc.fk_soc, sc.fk_user"; +$sql .= ' s.rowid as socid, s.nom as name, s.email, s.town, s.zip, s.fk_pays, s.client, s.code_client, '; +$sql .= " typent.code as typent_code,"; +$sql .= " ava.rowid as availability,"; +$sql .= " state.code_departement as state_code, state.nom as state_name,"; +$sql .= ' p.rowid, p.entity, p.note_private, p.total_ht, p.tva as total_vat, p.total as total_ttc, p.localtax1, p.localtax2, p.ref, p.ref_client, p.fk_statut, p.fk_user_author, p.datep as dp, p.fin_validite as dfv,p.date_livraison as ddelivery,'; +$sql .= ' p.datec as date_creation, p.tms as date_update, p.date_cloture as date_cloture,'; +$sql .= " pr.rowid as project_id, pr.ref as project_ref, pr.title as project_label,"; +$sql .= ' u.login'; +if (!$user->rights->societe->client->voir && !$socid) $sql .= ", sc.fk_soc, sc.fk_user"; 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 : ''); +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 : ''); } // 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=preg_replace('/, $/', '', $sql); -$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 -$sql.= ', '.MAIN_DB_PREFIX.'propal 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 ($sall || $search_product_category > 0) $sql.= ' LEFT JOIN '.MAIN_DB_PREFIX.'propaldet as pd ON p.rowid=pd.fk_propal'; -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 p.fk_user_author = u.rowid'; -$sql.= " LEFT JOIN ".MAIN_DB_PREFIX."projet as pr ON pr.rowid = p.fk_projet"; -$sql.= " LEFT JOIN ".MAIN_DB_PREFIX."c_availability as ava on (ava.rowid = p.fk_availability)"; +$parameters = array(); +$reshook = $hookmanager->executeHooks('printFieldListSelect', $parameters); // Note that $action and $object may have been modified by hook +$sql .= $hookmanager->resPrint; +$sql = preg_replace('/, $/', '', $sql); +$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 +$sql .= ', '.MAIN_DB_PREFIX.'propal 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 ($sall || $search_product_category > 0) $sql .= ' LEFT JOIN '.MAIN_DB_PREFIX.'propaldet as pd ON p.rowid=pd.fk_propal'; +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 p.fk_user_author = u.rowid'; +$sql .= " LEFT JOIN ".MAIN_DB_PREFIX."projet as pr ON pr.rowid = p.fk_projet"; +$sql .= " LEFT JOIN ".MAIN_DB_PREFIX."c_availability as ava on (ava.rowid = p.fk_availability)"; // 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_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 c"; - $sql.=", ".MAIN_DB_PREFIX."c_type_contact as tc"; + $sql .= ", ".MAIN_DB_PREFIX."element_contact as c"; + $sql .= ", ".MAIN_DB_PREFIX."c_type_contact as tc"; } -$sql.= ' WHERE p.fk_soc = s.rowid'; -$sql.= ' AND p.entity IN ('.getEntity('propal').')'; -if (! $user->rights->societe->client->voir && ! $socid) //restriction +$sql .= ' WHERE p.fk_soc = s.rowid'; +$sql .= ' AND p.entity IN ('.getEntity('propal').')'; +if (!$user->rights->societe->client->voir && !$socid) //restriction { - $sql.= " AND s.rowid = sc.fk_soc AND sc.fk_user = " .$user->id; + $sql .= " AND s.rowid = sc.fk_soc AND sc.fk_user = ".$user->id; } -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_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->escape($search_country).')'; if ($search_type_thirdparty) $sql .= " AND s.fk_typent IN (".$db->escape($search_type_thirdparty).')'; if ($search_ref) $sql .= natural_search('p.ref', $search_ref); @@ -326,39 +326,39 @@ if ($search_availability) $sql .= " AND p.fk_availability IN (".$db->escape($sea if ($search_societe) $sql .= natural_search('s.nom', $search_societe); if ($search_login) $sql .= natural_search("u.login", $search_login); -if ($search_montant_ht != '') $sql.= natural_search("p.total_ht", $search_montant_ht, 1); -if ($search_montant_vat != '') $sql.= natural_search("p.tva", $search_montant_vat, 1); -if ($search_montant_ttc != '') $sql.= natural_search("p.total", $search_montant_ttc, 1); +if ($search_montant_ht != '') $sql .= natural_search("p.total_ht", $search_montant_ht, 1); +if ($search_montant_vat != '') $sql .= natural_search("p.tva", $search_montant_vat, 1); +if ($search_montant_ttc != '') $sql .= natural_search("p.total", $search_montant_ttc, 1); if ($sall) { $sql .= natural_search(array_keys($fieldstosearchall), $sall); } -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_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_product_category > 0) $sql.=" AND cp.fk_categorie = ".$db->escape($search_product_category); -if ($socid > 0) $sql.= ' AND s.rowid = '.$socid; +if ($search_product_category > 0) $sql .= " AND cp.fk_categorie = ".$db->escape($search_product_category); +if ($socid > 0) $sql .= ' AND s.rowid = '.$socid; if ($viewstatut != '' && $viewstatut != '-1') { - $sql.= ' AND p.fk_statut IN ('.$db->escape($viewstatut).')'; + $sql .= ' AND p.fk_statut IN ('.$db->escape($viewstatut).')'; } -$sql.= dolSqlDateFilter("p.datep", $search_day, $search_month, $search_year); -$sql.= dolSqlDateFilter("p.fin_validite", $search_dayfin, $search_month_end, $search_yearfin); -$sql.= dolSqlDateFilter("p.date_livraison", $search_daydelivery, $search_monthdelivery, $search_yeardelivery); -if ($search_sale > 0) $sql.= " AND s.rowid = sc.fk_soc AND sc.fk_user = " .$db->escape($search_sale); +$sql .= dolSqlDateFilter("p.datep", $search_day, $search_month, $search_year); +$sql .= dolSqlDateFilter("p.fin_validite", $search_dayfin, $search_month_end, $search_yearfin); +$sql .= dolSqlDateFilter("p.date_livraison", $search_daydelivery, $search_monthdelivery, $search_yeardelivery); +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 c.fk_c_type_contact = tc.rowid AND tc.element='propal' AND tc.source='internal' AND c.element_id = p.rowid AND c.fk_socpeople = ".$db->escape($search_user); + $sql .= " AND c.fk_c_type_contact = tc.rowid AND tc.element='propal' AND tc.source='internal' AND c.element_id = p.rowid AND c.fk_socpeople = ".$db->escape($search_user); } // Add where from extra fields include DOL_DOCUMENT_ROOT.'/core/tpl/extrafields_list_search_sql.tpl.php'; // Add where from hooks -$parameters=array(); -$reshook=$hookmanager->executeHooks('printFieldListWhere', $parameters); // Note that $action and $object may have been modified by hook -$sql.=$hookmanager->resPrint; +$parameters = array(); +$reshook = $hookmanager->executeHooks('printFieldListWhere', $parameters); // Note that $action and $object may have been modified by hook +$sql .= $hookmanager->resPrint; -$sql.= $db->order($sortfield, $sortorder); -$sql.=', p.ref DESC'; +$sql .= $db->order($sortfield, $sortorder); +$sql .= ', p.ref DESC'; // Count total nb of records $nbtotalofrecords = ''; @@ -374,20 +374,20 @@ if (empty($conf->global->MAIN_DISABLE_FULL_SCANLIST)) } } -$sql.= $db->plimit($limit+1, $offset); +$sql .= $db->plimit($limit + 1, $offset); -$resql=$db->query($sql); +$resql = $db->query($sql); if ($resql) { - $objectstatic=new Propal($db); - $userstatic=new User($db); + $objectstatic = new Propal($db); + $userstatic = new User($db); if ($socid > 0) { $soc = new Societe($db); $soc->fetch($socid); - $title = $langs->trans('ListOfProposals') . ' - '.$soc->name; + $title = $langs->trans('ListOfProposals').' - '.$soc->name; if (empty($search_societe)) $search_societe = $soc->name; } else @@ -397,9 +397,9 @@ if ($resql) $num = $db->num_rows($resql); - $arrayofselected=is_array($toselect)?$toselect:array(); + $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); @@ -411,46 +411,46 @@ if ($resql) llxHeader('', $langs->trans('Proposal'), $help_url); - $param='&viewstatut='.urlencode($viewstatut); - 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_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_ref) $param.='&search_ref='.urlencode($search_ref); - if ($search_refcustomer) $param.='&search_refcustomer='.urlencode($search_refcustomer); - if ($search_refproject) $param.='&search_refproject='.urlencode($search_refproject); - if ($search_societe) $param.='&search_societe='.urlencode($search_societe); - if ($search_user > 0) $param.='&search_user='.urlencode($search_user); - if ($search_sale > 0) $param.='&search_sale='.urlencode($search_sale); - if ($search_montant_ht) $param.='&search_montant_ht='.urlencode($search_montant_ht); - if ($search_login) $param.='&search_login='.urlencode($search_login); - if ($search_town) $param.='&search_town='.urlencode($search_town); - if ($search_zip) $param.='&search_zip='.urlencode($search_zip); - if ($socid > 0) $param.='&socid='.urlencode($socid); - if ($optioncss != '') $param.='&optioncss='.urlencode($optioncss); - if ($search_categ_cus > 0) $param.='&search_categ_cus='.urlencode($search_categ_cus); - if ($search_product_category != '') $param.='&search_product_category='.$search_product_category; + $param = '&viewstatut='.urlencode($viewstatut); + 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_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_ref) $param .= '&search_ref='.urlencode($search_ref); + if ($search_refcustomer) $param .= '&search_refcustomer='.urlencode($search_refcustomer); + if ($search_refproject) $param .= '&search_refproject='.urlencode($search_refproject); + if ($search_societe) $param .= '&search_societe='.urlencode($search_societe); + if ($search_user > 0) $param .= '&search_user='.urlencode($search_user); + if ($search_sale > 0) $param .= '&search_sale='.urlencode($search_sale); + if ($search_montant_ht) $param .= '&search_montant_ht='.urlencode($search_montant_ht); + if ($search_login) $param .= '&search_login='.urlencode($search_login); + if ($search_town) $param .= '&search_town='.urlencode($search_town); + if ($search_zip) $param .= '&search_zip='.urlencode($search_zip); + if ($socid > 0) $param .= '&socid='.urlencode($socid); + if ($optioncss != '') $param .= '&optioncss='.urlencode($optioncss); + if ($search_categ_cus > 0) $param .= '&search_categ_cus='.urlencode($search_categ_cus); + if ($search_product_category != '') $param .= '&search_product_category='.$search_product_category; // Add $param from extra fields include DOL_DOCUMENT_ROOT.'/core/tpl/extrafields_list_search_param.tpl.php'; // List of mass actions available - $arrayofmassactions = array( + $arrayofmassactions = array( 'generate_doc'=>$langs->trans("ReGeneratePDF"), 'builddoc'=>$langs->trans("PDFMerge"), 'presend'=>$langs->trans("SendByMail"), ); - if ($user->rights->propal->supprimer) $arrayofmassactions['predelete']=''.$langs->trans("Delete"); - if ($user->rights->propal->cloturer) $arrayofmassactions['closed']=$langs->trans("Close"); - if (in_array($massaction, array('presend','predelete','closed'))) $arrayofmassactions=array(); - $massactionbutton=$form->selectMassAction('', $arrayofmassactions); + if ($user->rights->propal->supprimer) $arrayofmassactions['predelete'] = ''.$langs->trans("Delete"); + if ($user->rights->propal->cloturer) $arrayofmassactions['closed'] = $langs->trans("Close"); + if (in_array($massaction, array('presend', 'predelete', 'closed'))) $arrayofmassactions = array(); + $massactionbutton = $form->selectMassAction('', $arrayofmassactions); - $newcardbutton=''; + $newcardbutton = ''; if ($user->rights->propal->creer) { - $newcardbutton.= dolGetButtonTitle($langs->trans('NewPropal'), '', 'fa fa-plus-circle', DOL_URL_ROOT.'/comm/propal/card.php?action=create'); + $newcardbutton .= dolGetButtonTitle($langs->trans('NewPropal'), '', 'fa fa-plus-circle', DOL_URL_ROOT.'/comm/propal/card.php?action=create'); } // Fields title search @@ -466,213 +466,213 @@ if ($resql) print_barre_liste($title, $page, $_SERVER["PHP_SELF"], $param, $sortfield, $sortorder, $massactionbutton, $num, $nbtotalofrecords, 'commercial', 0, $newcardbutton, '', $limit); - $topicmail="SendPropalRef"; - $modelmail="proposal_send"; - $objecttmp=new Propal($db); - $trackid='pro'.$object->id; + $topicmail = "SendPropalRef"; + $modelmail = "proposal_send"; + $objecttmp = new Propal($db); + $trackid = 'pro'.$object->id; include DOL_DOCUMENT_ROOT.'/core/tpl/massactions_pre.tpl.php'; if ($sall) { - foreach($fieldstosearchall as $key => $val) $fieldstosearchall[$key]=$langs->trans($val); - print '
'.$langs->trans("FilterOnInto", $sall) . join(', ', $fieldstosearchall).'
'; + foreach ($fieldstosearchall as $key => $val) $fieldstosearchall[$key] = $langs->trans($val); + print '
'.$langs->trans("FilterOnInto", $sall).join(', ', $fieldstosearchall).'
'; } $i = 0; - $moreforfilter=''; + $moreforfilter = ''; // If the user can view prospects other than his' 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.='
'; + $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 .= '
'; + $moreforfilter .= $langs->trans('LinkedToSpecificUsers').': '; + $moreforfilter .= $form->select_dolusers($search_user, 'search_user', 1, '', 0, '', '', 0, 0, 0, '', 0, '', 'maxwidth200'); + $moreforfilter .= '
'; } // If the user can view products 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'). ': '; + $moreforfilter .= '
'; + $moreforfilter .= $langs->trans('IncludingProductWithTag').': '; $cate_arbo = $form->select_all_categories(Categorie::TYPE_PRODUCT, null, 'parent', null, null, 1); - $moreforfilter.=$form->selectarray('search_product_category', $cate_arbo, $search_product_category, 1, 0, 0, '', 0, 0, 0, 0, 'maxwidth300', 1); - $moreforfilter.='
'; + $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)) + if (!empty($conf->categorie->enabled)) { - require_once DOL_DOCUMENT_ROOT . '/categories/class/categorie.class.php'; - $moreforfilter.='
'; - $moreforfilter.=$langs->trans('CustomersProspectsCategoriesShort').': '; - $moreforfilter.=$formother->select_categories('customer', $search_categ_cus, 'search_categ_cus', 1); - $moreforfilter.='
'; + require_once DOL_DOCUMENT_ROOT.'/categories/class/categorie.class.php'; + $moreforfilter .= '
'; + $moreforfilter .= $langs->trans('CustomersProspectsCategoriesShort').': '; + $moreforfilter .= $formother->select_categories('customer', $search_categ_cus, 'search_categ_cus', 1); + $moreforfilter .= '
'; } - $parameters=array(); - $reshook=$hookmanager->executeHooks('printFieldPreListTitle', $parameters); // Note that $action and $object may have been modified by hook + $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($moreforfilter)) + if (!empty($moreforfilter)) { print '
'; print $moreforfilter; print '
'; } - $varpage=empty($contextpage)?$_SERVER["PHP_SELF"]:$contextpage; - $selectedfields=$form->multiSelectArrayWithCheckbox('selectedfields', $arrayfields, $varpage); // This also change content of $arrayfields - $selectedfields.=(count($arrayofmassactions) ? $form->showCheckAddButtons('checkforselect', 1) : ''); + $varpage = empty($contextpage) ? $_SERVER["PHP_SELF"] : $contextpage; + $selectedfields = $form->multiSelectArrayWithCheckbox('selectedfields', $arrayfields, $varpage); // This also change content of $arrayfields + $selectedfields .= (count($arrayofmassactions) ? $form->showCheckAddButtons('checkforselect', 1) : ''); print '
'; - print '
'.$langs->trans("OnProcessOrders").' '.$num.'
'."\n"; + print '
'."\n"; print ''; - if (! empty($arrayfields['p.ref']['checked'])) + if (!empty($arrayfields['p.ref']['checked'])) { print ''; } - if (! empty($arrayfields['p.ref_client']['checked'])) + if (!empty($arrayfields['p.ref_client']['checked'])) { print ''; } - if (! empty($arrayfields['pr.ref']['checked'])) + if (!empty($arrayfields['pr.ref']['checked'])) { print ''; } - if (! empty($arrayfields['pr.title']['checked'])) + if (!empty($arrayfields['pr.title']['checked'])) { print ''; } - if (! empty($arrayfields['s.nom']['checked'])) + if (!empty($arrayfields['s.nom']['checked'])) { print ''; } - if (! empty($arrayfields['s.town']['checked'])) print ''; - if (! empty($arrayfields['s.zip']['checked'])) print ''; + if (!empty($arrayfields['s.town']['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 ''; } // Date - if (! empty($arrayfields['p.date']['checked'])) + if (!empty($arrayfields['p.date']['checked'])) { print ''; } // Date end - if (! empty($arrayfields['p.fin_validite']['checked'])) + if (!empty($arrayfields['p.fin_validite']['checked'])) { print ''; } // Date delivery - if (! empty($arrayfields['p.date_livraison']['checked'])) + if (!empty($arrayfields['p.date_livraison']['checked'])) { print ''; } // Availability - if (! empty($arrayfields['ava.rowid']['checked'])) + if (!empty($arrayfields['ava.rowid']['checked'])) { print ''; } - if (! empty($arrayfields['p.total_ht']['checked'])) + if (!empty($arrayfields['p.total_ht']['checked'])) { // Amount print ''; } - if (! empty($arrayfields['p.total_vat']['checked'])) + if (!empty($arrayfields['p.total_vat']['checked'])) { // Amount print ''; } - if (! empty($arrayfields['p.total_ttc']['checked'])) + if (!empty($arrayfields['p.total_ttc']['checked'])) { // Amount print ''; } - if (! empty($arrayfields['p.total_ht_invoiced']['checked'])) + if (!empty($arrayfields['p.total_ht_invoiced']['checked'])) { // Amount invoiced print ''; } - if (! empty($arrayfields['p.total_invoiced']['checked'])) + if (!empty($arrayfields['p.total_invoiced']['checked'])) { // Amount invoiced print ''; } - if (! empty($arrayfields['u.login']['checked'])) + if (!empty($arrayfields['u.login']['checked'])) { // Author print ''; } - if (! empty($arrayfields['sale_representative']['checked'])) + if (!empty($arrayfields['sale_representative']['checked'])) { print ''; } @@ -680,29 +680,29 @@ if ($resql) include DOL_DOCUMENT_ROOT.'/core/tpl/extrafields_list_search_input.tpl.php'; // Fields from hook - $parameters=array('arrayfields'=>$arrayfields); - $reshook=$hookmanager->executeHooks('printFieldListOption', $parameters); // Note that $action and $object may have been modified by hook + $parameters = array('arrayfields'=>$arrayfields); + $reshook = $hookmanager->executeHooks('printFieldListOption', $parameters); // Note that $action and $object may have been modified by hook print $hookmanager->resPrint; // Date creation - if (! empty($arrayfields['p.datec']['checked'])) + if (!empty($arrayfields['p.datec']['checked'])) { print ''; } // Date modification - if (! empty($arrayfields['p.tms']['checked'])) + if (!empty($arrayfields['p.tms']['checked'])) { print ''; } // Date cloture - if (! empty($arrayfields['p.date_cloture']['checked'])) + if (!empty($arrayfields['p.date_cloture']['checked'])) { print ''; } // Status - if (! empty($arrayfields['p.fk_statut']['checked'])) + if (!empty($arrayfields['p.fk_statut']['checked'])) { print ''; @@ -719,65 +719,65 @@ if ($resql) // Fields title print ''; - 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.ref_client']['checked'])) print_liste_field_titre($arrayfields['p.ref_client']['label'], $_SERVER["PHP_SELF"], 'p.ref_client', '', $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['pr.title']['checked'])) print_liste_field_titre($arrayfields['pr.title']['label'], $_SERVER["PHP_SELF"], 'pr.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.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['p.date']['checked'])) print_liste_field_titre($arrayfields['p.date']['label'], $_SERVER["PHP_SELF"], 'p.datep', '', $param, 'align="center"', $sortfield, $sortorder); - if (! empty($arrayfields['p.fin_validite']['checked'])) print_liste_field_titre($arrayfields['p.fin_validite']['label'], $_SERVER["PHP_SELF"], 'dfv', '', $param, 'align="center"', $sortfield, $sortorder); - if (! empty($arrayfields['p.date_livraison']['checked'])) print_liste_field_titre($arrayfields['p.date_livraison']['label'], $_SERVER["PHP_SELF"], 'ddelivery', '', $param, 'align="center"', $sortfield, $sortorder); - if (! empty($arrayfields['ava.rowid']['checked'])) print_liste_field_titre($arrayfields['ava.rowid']['label'], $_SERVER["PHP_SELF"], 'availability', '', $param, '', $sortfield, $sortorder); - if (! empty($arrayfields['p.total_ht']['checked'])) print_liste_field_titre($arrayfields['p.total_ht']['label'], $_SERVER["PHP_SELF"], 'p.total_ht', '', $param, 'class="right"', $sortfield, $sortorder); - if (! empty($arrayfields['p.total_vat']['checked'])) print_liste_field_titre($arrayfields['p.total_vat']['label'], $_SERVER["PHP_SELF"], 'p.tva', '', $param, 'class="right"', $sortfield, $sortorder); - if (! empty($arrayfields['p.total_ttc']['checked'])) print_liste_field_titre($arrayfields['p.total_ttc']['label'], $_SERVER["PHP_SELF"], 'p.total', '', $param, 'class="right"', $sortfield, $sortorder); - if (! empty($arrayfields['p.total_ht_invoiced']['checked'])) print_liste_field_titre($arrayfields['p.total_ht_invoiced']['label'], $_SERVER["PHP_SELF"], '', '', $param, 'class="right"', $sortfield, $sortorder); - if (! empty($arrayfields['p.total_invoiced']['checked'])) print_liste_field_titre($arrayfields['p.total_invoiced']['label'], $_SERVER["PHP_SELF"], '', '', $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['sale_representative']['checked'])) print_liste_field_titre($arrayfields['sale_representative']['label'], $_SERVER["PHP_SELF"], "", "", "$param", '', $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.ref_client']['checked'])) print_liste_field_titre($arrayfields['p.ref_client']['label'], $_SERVER["PHP_SELF"], 'p.ref_client', '', $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['pr.title']['checked'])) print_liste_field_titre($arrayfields['pr.title']['label'], $_SERVER["PHP_SELF"], 'pr.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.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['p.date']['checked'])) print_liste_field_titre($arrayfields['p.date']['label'], $_SERVER["PHP_SELF"], 'p.datep', '', $param, 'align="center"', $sortfield, $sortorder); + if (!empty($arrayfields['p.fin_validite']['checked'])) print_liste_field_titre($arrayfields['p.fin_validite']['label'], $_SERVER["PHP_SELF"], 'dfv', '', $param, 'align="center"', $sortfield, $sortorder); + if (!empty($arrayfields['p.date_livraison']['checked'])) print_liste_field_titre($arrayfields['p.date_livraison']['label'], $_SERVER["PHP_SELF"], 'ddelivery', '', $param, 'align="center"', $sortfield, $sortorder); + if (!empty($arrayfields['ava.rowid']['checked'])) print_liste_field_titre($arrayfields['ava.rowid']['label'], $_SERVER["PHP_SELF"], 'availability', '', $param, '', $sortfield, $sortorder); + if (!empty($arrayfields['p.total_ht']['checked'])) print_liste_field_titre($arrayfields['p.total_ht']['label'], $_SERVER["PHP_SELF"], 'p.total_ht', '', $param, 'class="right"', $sortfield, $sortorder); + if (!empty($arrayfields['p.total_vat']['checked'])) print_liste_field_titre($arrayfields['p.total_vat']['label'], $_SERVER["PHP_SELF"], 'p.tva', '', $param, 'class="right"', $sortfield, $sortorder); + if (!empty($arrayfields['p.total_ttc']['checked'])) print_liste_field_titre($arrayfields['p.total_ttc']['label'], $_SERVER["PHP_SELF"], 'p.total', '', $param, 'class="right"', $sortfield, $sortorder); + if (!empty($arrayfields['p.total_ht_invoiced']['checked'])) print_liste_field_titre($arrayfields['p.total_ht_invoiced']['label'], $_SERVER["PHP_SELF"], '', '', $param, 'class="right"', $sortfield, $sortorder); + if (!empty($arrayfields['p.total_invoiced']['checked'])) print_liste_field_titre($arrayfields['p.total_invoiced']['label'], $_SERVER["PHP_SELF"], '', '', $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['sale_representative']['checked'])) print_liste_field_titre($arrayfields['sale_representative']['label'], $_SERVER["PHP_SELF"], "", "", "$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 + $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['p.datec']['checked'])) print_liste_field_titre($arrayfields['p.datec']['label'], $_SERVER["PHP_SELF"], "p.datec", "", $param, 'align="center" class="nowrap"', $sortfield, $sortorder); - if (! empty($arrayfields['p.tms']['checked'])) print_liste_field_titre($arrayfields['p.tms']['label'], $_SERVER["PHP_SELF"], "p.tms", "", $param, 'align="center" class="nowrap"', $sortfield, $sortorder); - if (! empty($arrayfields['p.date_cloture']['checked'])) print_liste_field_titre($arrayfields['p.date_cloture']['label'], $_SERVER["PHP_SELF"], "p.date_cloture", "", $param, 'align="center" class="nowrap"', $sortfield, $sortorder); - if (! empty($arrayfields['p.fk_statut']['checked'])) print_liste_field_titre($arrayfields['p.fk_statut']['label'], $_SERVER["PHP_SELF"], "p.fk_statut", "", $param, 'class="right"', $sortfield, $sortorder); + if (!empty($arrayfields['p.datec']['checked'])) print_liste_field_titre($arrayfields['p.datec']['label'], $_SERVER["PHP_SELF"], "p.datec", "", $param, 'align="center" class="nowrap"', $sortfield, $sortorder); + if (!empty($arrayfields['p.tms']['checked'])) print_liste_field_titre($arrayfields['p.tms']['label'], $_SERVER["PHP_SELF"], "p.tms", "", $param, 'align="center" class="nowrap"', $sortfield, $sortorder); + if (!empty($arrayfields['p.date_cloture']['checked'])) print_liste_field_titre($arrayfields['p.date_cloture']['label'], $_SERVER["PHP_SELF"], "p.date_cloture", "", $param, 'align="center" class="nowrap"', $sortfield, $sortorder); + if (!empty($arrayfields['p.fk_statut']['checked'])) print_liste_field_titre($arrayfields['p.fk_statut']['label'], $_SERVER["PHP_SELF"], "p.fk_statut", "", $param, 'class="right"', $sortfield, $sortorder); print_liste_field_titre($selectedfields, $_SERVER["PHP_SELF"], "", '', '', 'align="center"', $sortfield, $sortorder, 'maxwidthsearch '); print ''."\n"; $now = dol_now(); - $i=0; - $totalarray=array(); - $typenArray=null; + $i = 0; + $totalarray = array(); + $typenArray = null; while ($i < min($num, $limit)) { $obj = $db->fetch_object($resql); - $objectstatic->id=$obj->rowid; - $objectstatic->ref=$obj->ref; + $objectstatic->id = $obj->rowid; + $objectstatic->ref = $obj->ref; - $companystatic->id=$obj->socid; - $companystatic->name=$obj->name; - $companystatic->client=$obj->client; - $companystatic->code_client=$obj->code_client; - $companystatic->email=$obj->email; + $companystatic->id = $obj->socid; + $companystatic->name = $obj->name; + $companystatic->client = $obj->client; + $companystatic->code_client = $obj->code_client; + $companystatic->email = $obj->email; - $projectstatic->id=$obj->project_id; - $projectstatic->ref=$obj->project_ref; - $projectstatic->title=$obj->project_label; + $projectstatic->id = $obj->project_id; + $projectstatic->ref = $obj->project_ref; + $projectstatic->title = $obj->project_label; print ''; - if (! empty($arrayfields['p.ref']['checked'])) + if (!empty($arrayfields['p.ref']['checked'])) { print ''; // Warning - $warnornote=''; - if ($obj->fk_statut == 1 && $db->jdate($obj->dfv) < ($now - $conf->propal->cloture->warning_delay)) $warnornote.=img_warning($langs->trans("Late")); - if (! empty($obj->note_private)) + $warnornote = ''; + if ($obj->fk_statut == 1 && $db->jdate($obj->dfv) < ($now - $conf->propal->cloture->warning_delay)) $warnornote .= img_warning($langs->trans("Late")); + if (!empty($obj->note_private)) { - $warnornote.=($warnornote?' ':''); - $warnornote.= ''; - $warnornote.= ''.img_picto($langs->trans("ViewPrivateNote"), 'object_generic').''; - $warnornote.= ''; + $warnornote .= ($warnornote ? ' ' : ''); + $warnornote .= ''; + $warnornote .= ''.img_picto($langs->trans("ViewPrivateNote"), 'object_generic').''; + $warnornote .= ''; } if ($warnornote) { @@ -804,26 +804,26 @@ if ($resql) } // Other picto tool 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, 0, 0, 0, '', 0, 0, 0, (empty($conf->global->SOCIETE_SORT_ON_TYPEENT)?'ASC':$conf->global->SOCIETE_SORT_ON_TYPEENT)); + print $form->selectarray("search_type_thirdparty", $formcompany->typent_array(0), $search_type_thirdparty, 0, 0, 0, '', 0, 0, 0, (empty($conf->global->SOCIETE_SORT_ON_TYPEENT) ? 'ASC' : $conf->global->SOCIETE_SORT_ON_TYPEENT)); print ajax_combobox('search_type_thirdparty'); 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').': '; $formother->select_year($search_year, 'search_year', 1, 20, 5); 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').': '; $formother->select_year($search_yearfin, 'search_yearfin', 1, 20, 5); 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').': '; $formother->select_year($search_yeardelivery, 'search_yeardelivery', 1, 20, 5); print ''; print $form->selectAvailabilityDelay($search_availability, 'search_availability', '', 1); print ajax_combobox('search_availability'); print ''; print ''; print ''; print ''; print ''; print ''; print ''; print ''; print ''; print ''; print ''; print ''; print ''; print ''; $formpropal->selectProposalStatus($viewstatut, 1, 0, 1, 'customer', 'search_statut'); @@ -710,7 +710,7 @@ if ($resql) } // Action column print ''; - $searchpicto=$form->showFilterButtons(); + $searchpicto = $form->showFilterButtons(); print $searchpicto; print '
'; @@ -787,14 +787,14 @@ if ($resql) print $objectstatic->getNomUrl(1, '', '', 0, 1); print ''; - $filename=dol_sanitizeFileName($obj->ref); - $filedir=$conf->propal->multidir_output[$obj->entity] . '/' . dol_sanitizeFileName($obj->ref); - $urlsource=$_SERVER['PHP_SELF'].'?id='.$obj->rowid; + $filename = dol_sanitizeFileName($obj->ref); + $filedir = $conf->propal->multidir_output[$obj->entity].'/'.dol_sanitizeFileName($obj->ref); + $urlsource = $_SERVER['PHP_SELF'].'?id='.$obj->rowid; print $formfile->getDocumentsLink($objectstatic->element, $filename, $filedir); print '
'; print "
'; print $obj->ref_client; print ''; @@ -831,10 +831,10 @@ if ($resql) print $projectstatic->getNomUrl(1); } print ''; @@ -842,71 +842,71 @@ if ($resql) print $projectstatic->title; } print ''; print $companystatic->getNomUrl(1, 'customer'); print ''; print $obj->town; print ''; print $obj->zip; print '".$obj->state_name."'; - $tmparray=getCountry($obj->fk_pays, 'all'); + $tmparray = getCountry($obj->fk_pays, 'all'); print $tmparray['label']; print ''; print $typenArray[$obj->typent_code]; print ''; print dol_print_date($db->jdate($obj->dp), 'day'); 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 ''; print dol_print_date($db->jdate($obj->date_cloture), 'dayhour', 'tzuser'); print ''.$objectstatic->LibStatut($obj->fk_statut, 5).''; if ($massactionbutton || $massaction) // If we are in select mode (massactionbutton defined) or if we have already selected and sent an action ($massaction) defined { - $selected=0; - if (in_array($obj->rowid, $arrayofselected)) $selected=1; - print ''; + $selected = 0; + if (in_array($obj->rowid, $arrayofselected)) $selected = 1; + print ''; } print '
'."\n"; @@ -1133,16 +1133,16 @@ if ($resql) print ''."\n"; - $hidegeneratedfilelistifempty=1; - if ($massaction == 'builddoc' || $action == 'remove_file' || $show_files) $hidegeneratedfilelistifempty=0; + $hidegeneratedfilelistifempty = 1; + if ($massaction == 'builddoc' || $action == 'remove_file' || $show_files) $hidegeneratedfilelistifempty = 0; // Show list of available documents - $urlsource=$_SERVER['PHP_SELF'].'?sortfield='.$sortfield.'&sortorder='.$sortorder; - $urlsource.=str_replace('&', '&', $param); + $urlsource = $_SERVER['PHP_SELF'].'?sortfield='.$sortfield.'&sortorder='.$sortorder; + $urlsource .= str_replace('&', '&', $param); - $filedir=$diroutputmassaction; - $genallowed=$user->rights->propal->lire; - $delallowed=$user->rights->propal->creer; + $filedir = $diroutputmassaction; + $genallowed = $user->rights->propal->lire; + $delallowed = $user->rights->propal->creer; print $formfile->showdocuments('massfilesarea_proposals', '', $filedir, $urlsource, 0, $delallowed, '', 1, 1, 0, 48, 1, $param, $title, '', '', '', null, $hidegeneratedfilelistifempty); } diff --git a/htdocs/comm/propal/note.php b/htdocs/comm/propal/note.php index ee9d9bd9c4f..1abbeb6370c 100644 --- a/htdocs/comm/propal/note.php +++ b/htdocs/comm/propal/note.php @@ -51,9 +51,9 @@ $object = new Propal($db); * Actions */ -$permissionnote=$user->rights->propale->creer; // Used by the include of actions_setnotes.inc.php +$permissionnote = $user->rights->propale->creer; // Used by the include of actions_setnotes.inc.php -include DOL_DOCUMENT_ROOT.'/core/actions_setnotes.inc.php'; // Must be include, not includ_once +include DOL_DOCUMENT_ROOT.'/core/actions_setnotes.inc.php'; // Must be include, not includ_once @@ -65,11 +65,11 @@ llxHeader('', $langs->trans('Proposal'), 'EN:Commercial_Proposals|FR:Proposition $form = new Form($db); -if ($id > 0 || ! empty($ref)) +if ($id > 0 || !empty($ref)) { if ($mesg) print $mesg; - $now=dol_now(); + $now = dol_now(); if ($object->fetch($id, $ref) > 0) { diff --git a/htdocs/comm/propal/stats/index.php b/htdocs/comm/propal/stats/index.php index a37006d60fb..4c7b393c8db 100644 --- a/htdocs/comm/propal/stats/index.php +++ b/htdocs/comm/propal/stats/index.php @@ -243,7 +243,7 @@ print '
'; // Show filter box print '
'; print ''; - print ''; + print '
'; print ''; // Company print '
'.$langs->trans("Filter").'
'.$langs->trans("ThirdParty").''; @@ -272,7 +272,7 @@ print '
'; //} print '
'; -print ''; +print '
'; print ''; print ''; print ''; @@ -320,7 +320,7 @@ print '
'; // Show graphs -print '
'.$langs->trans("Year").''.$langs->trans("NbOfProposals").'
'; +print '
'; if ($mesg) { print $mesg; } else { print $px1->show(); diff --git a/htdocs/comm/prospect/index.php b/htdocs/comm/prospect/index.php index 485771939c4..4bdcbae59a8 100644 --- a/htdocs/comm/prospect/index.php +++ b/htdocs/comm/prospect/index.php @@ -41,7 +41,7 @@ if ($user->socid > 0) * View */ -$companystatic=new Societe($db); +$companystatic = new Societe($db); llxHeader(); @@ -52,12 +52,12 @@ print load_fiche_titre($langs->trans("ProspectionArea")); print '
'; -if (! empty($conf->propal->enabled)) +if (!empty($conf->propal->enabled)) { - $var=false; + $var = false; print ''; print ''; - print ''; + print '
'; print ''; print ''; @@ -72,24 +72,24 @@ if (! empty($conf->propal->enabled)) */ $sql = "SELECT count(*) as cc, st.libelle, st.id"; -$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"; -$sql.= " WHERE s.fk_stcomm = st.id"; -$sql.= " AND s.client IN (2, 3)"; -$sql.= " AND s.entity IN (".getEntity($companystatic->element).")"; -if (! $user->rights->societe->client->voir && ! $socid) $sql.= " AND s.rowid = sc.fk_soc AND sc.fk_user = " .$user->id; -$sql.= " GROUP BY st.id"; -$sql.= " ORDER BY st.id"; +$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"; +$sql .= " WHERE s.fk_stcomm = st.id"; +$sql .= " AND s.client IN (2, 3)"; +$sql .= " AND s.entity IN (".getEntity($companystatic->element).")"; +if (!$user->rights->societe->client->voir && !$socid) $sql .= " AND s.rowid = sc.fk_soc AND sc.fk_user = ".$user->id; +$sql .= " GROUP BY st.id"; +$sql .= " ORDER BY st.id"; -$resql=$db->query($sql); +$resql = $db->query($sql); if ($resql) { $num = $db->num_rows($resql); $i = 0; - if ($num > 0 ) + if ($num > 0) { - print '
'.$langs->trans("SearchAProposal").'
'; print $langs->trans("Ref").':
'; + print '
'; print ''; print ''; while ($i < $num) @@ -111,21 +111,21 @@ if ($resql) /* * Liste des propal brouillons */ -if (! empty($conf->propal->enabled) && $user->rights->propale->lire) +if (!empty($conf->propal->enabled) && $user->rights->propale->lire) { $sql = "SELECT p.rowid, p.ref, p.price, s.nom as sname"; - $sql.= " FROM ".MAIN_DB_PREFIX."propal as p"; - $sql.= ", ".MAIN_DB_PREFIX."societe as s"; - if (! $user->rights->societe->client->voir && ! $socid) $sql.= ", ".MAIN_DB_PREFIX."societe_commerciaux as sc"; - $sql.= " WHERE p.fk_statut = 0"; - $sql.= " AND p.fk_soc = s.rowid"; - $sql.= " AND p.entity IN (".getEntity('propal').")"; - if (! $user->rights->societe->client->voir && ! $socid) $sql.= " AND s.rowid = sc.fk_soc AND sc.fk_user = " .$user->id; + $sql .= " FROM ".MAIN_DB_PREFIX."propal as p"; + $sql .= ", ".MAIN_DB_PREFIX."societe as s"; + if (!$user->rights->societe->client->voir && !$socid) $sql .= ", ".MAIN_DB_PREFIX."societe_commerciaux as sc"; + $sql .= " WHERE p.fk_statut = 0"; + $sql .= " AND p.fk_soc = s.rowid"; + $sql .= " AND p.entity IN (".getEntity('propal').")"; + if (!$user->rights->societe->client->voir && !$socid) $sql .= " AND s.rowid = sc.fk_soc AND sc.fk_user = ".$user->id; - $resql=$db->query($sql); + $resql = $db->query($sql); if ($resql) { - $total=0; + $total = 0; $num = $db->num_rows($resql); $i = 0; if ($num > 0) @@ -146,7 +146,7 @@ if (! empty($conf->propal->enabled) && $user->rights->propale->lire) $i++; $total += $obj->price; } - if ($total>0) { + if ($total > 0) { print '"; } print "
'.$langs->trans("ProspectsByStatus").'
'.$langs->trans("Total")."".price($total)."

"; @@ -163,29 +163,29 @@ print '
'; /* * Actions commerciales a faire */ -if (! empty($conf->agenda->enabled)) show_array_actions_to_do(10); +if (!empty($conf->agenda->enabled)) show_array_actions_to_do(10); /* * Dernieres propales ouvertes */ -if (! empty($conf->propal->enabled) && $user->rights->propale->lire) +if (!empty($conf->propal->enabled) && $user->rights->propale->lire) { $sql = "SELECT s.nom as name, s.rowid as socid, s.client, s.canvas,"; - $sql.= " p.rowid as propalid, p.total as total_ttc, p.ref, p.datep as dp, c.label as statut, c.id as statutid"; - $sql.= " FROM ".MAIN_DB_PREFIX."societe as s"; - $sql.= ", ".MAIN_DB_PREFIX."propal as p"; - $sql.= ", ".MAIN_DB_PREFIX."c_propalst as c"; - if (! $user->rights->societe->client->voir && ! $socid) $sql.= ", ".MAIN_DB_PREFIX."societe_commerciaux as sc"; - $sql.= " WHERE p.fk_soc = s.rowid"; - $sql.= " AND p.fk_statut = c.id"; - $sql.= " AND p.fk_statut = 1"; - $sql.= " AND p.entity IN (".getEntity('propal').")"; - 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 p.rowid DESC"; - $sql.= $db->plimit(5, 0); + $sql .= " p.rowid as propalid, p.total as total_ttc, p.ref, p.datep as dp, c.label as statut, c.id as statutid"; + $sql .= " FROM ".MAIN_DB_PREFIX."societe as s"; + $sql .= ", ".MAIN_DB_PREFIX."propal as p"; + $sql .= ", ".MAIN_DB_PREFIX."c_propalst as c"; + if (!$user->rights->societe->client->voir && !$socid) $sql .= ", ".MAIN_DB_PREFIX."societe_commerciaux as sc"; + $sql .= " WHERE p.fk_soc = s.rowid"; + $sql .= " AND p.fk_statut = c.id"; + $sql .= " AND p.fk_statut = 1"; + $sql .= " AND p.entity IN (".getEntity('propal').")"; + 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 p.rowid DESC"; + $sql .= $db->plimit(5, 0); - $resql=$db->query($sql); + $resql = $db->query($sql); if ($resql) { $total = 0; @@ -193,7 +193,7 @@ if (! empty($conf->propal->enabled) && $user->rights->propale->lire) $i = 0; if ($num > 0) { - print ''; + print '
'; print ''; while ($i < $num) @@ -205,10 +205,10 @@ if (! empty($conf->propal->enabled) && $user->rights->propale->lire) print img_object($langs->trans("ShowPropal"), "propal").' '.$obj->ref.''; print "\n"; print ""; } @@ -235,22 +235,22 @@ if (! empty($conf->propal->enabled) && $user->rights->propale->lire) * */ $sql = "SELECT s.nom as name, s.rowid as socid, s.client, s.canvas"; -$sql.= " FROM ".MAIN_DB_PREFIX."societe as s"; -if (! $user->rights->societe->client->voir && ! $socid) $sql.= ", ".MAIN_DB_PREFIX."societe_commerciaux as sc"; -$sql.= " WHERE s.fk_stcomm = 1"; -$sql.= " AND s.entity IN (".getEntity($companystatic->element).")"; -if (! $user->rights->societe->client->voir && ! $socid) $sql.= " AND s.rowid = sc.fk_soc AND sc.fk_user = " .$user->id; -$sql.= " ORDER BY s.tms ASC"; -$sql.= $db->plimit(15, 0); +$sql .= " FROM ".MAIN_DB_PREFIX."societe as s"; +if (!$user->rights->societe->client->voir && !$socid) $sql .= ", ".MAIN_DB_PREFIX."societe_commerciaux as sc"; +$sql .= " WHERE s.fk_stcomm = 1"; +$sql .= " AND s.entity IN (".getEntity($companystatic->element).")"; +if (!$user->rights->societe->client->voir && !$socid) $sql .= " AND s.rowid = sc.fk_soc AND sc.fk_user = ".$user->id; +$sql .= " ORDER BY s.tms ASC"; +$sql .= $db->plimit(15, 0); -$resql=$db->query($sql); +$resql = $db->query($sql); if ($resql) { $num = $db->num_rows($resql); $i = 0; - if ($num > 0 ) + if ($num > 0) { - print '
'.$langs->trans("ProposalsOpened").'
"; - $companystatic->id=$obj->socid; - $companystatic->name=$obj->name; - $companystatic->client=$obj->client; - $companystatic->canvas=$obj->canvas; + $companystatic->id = $obj->socid; + $companystatic->name = $obj->name; + $companystatic->client = $obj->client; + $companystatic->canvas = $obj->canvas; print $companystatic->getNomUrl(1, '', 44); print ""; @@ -217,7 +217,7 @@ if (! empty($conf->propal->enabled) && $user->rights->propale->lire) $i++; $total += $obj->price; } - if ($total>0) + if ($total > 0) { print '
'.$langs->trans("Total")."".price($total)."
'; + print '
'; print ''; while ($i < $num) @@ -258,10 +258,10 @@ if ($resql) $obj = $db->fetch_object($resql); print ''; $i++; diff --git a/htdocs/comm/prospect/recap-prospect.php b/htdocs/comm/prospect/recap-prospect.php index 07741635bcc..f1e15a51ecc 100644 --- a/htdocs/comm/prospect/recap-prospect.php +++ b/htdocs/comm/prospect/recap-prospect.php @@ -62,7 +62,7 @@ if ($socid > 0) print "
'.$langs->trans("ProspectToContact").'
'; - $companystatic->id=$obj->socid; - $companystatic->name=$obj->name; - $companystatic->client=$obj->client; - $companystatic->canvas=$obj->canvas; + $companystatic->id = $obj->socid; + $companystatic->name = $obj->name; + $companystatic->client = $obj->client; + $companystatic->canvas = $obj->canvas; print $companystatic->getNomUrl(1, 'prospect', 44); print '
\n"; print '
'; - print ''; + print '
'; // Name print ''; diff --git a/htdocs/comm/recap-client.php b/htdocs/comm/recap-client.php index 9605281d6ca..81e7446cff1 100644 --- a/htdocs/comm/recap-client.php +++ b/htdocs/comm/recap-client.php @@ -62,7 +62,7 @@ if ($socid > 0) print "
'.$langs->trans("Thirdpary").''.$societe->getNomUrl(1).'
\n"; print '
'; - print ''; + print '
'; // Name print ''; diff --git a/htdocs/comm/remise.php b/htdocs/comm/remise.php index 32c6869d576..a4f3fb0503b 100644 --- a/htdocs/comm/remise.php +++ b/htdocs/comm/remise.php @@ -29,9 +29,9 @@ require_once DOL_DOCUMENT_ROOT.'/contact/class/contact.class.php'; // Load translation files required by the page $langs->loadLangs(array('companies', 'orders', 'bills')); -$id=GETPOST("id", 'int'); +$id = GETPOST("id", 'int'); -$socid = GETPOST('id', 'int')?GETPOST('id', 'int'):GETPOST('socid', 'int'); +$socid = GETPOST('id', 'int') ?GETPOST('id', 'int') : GETPOST('socid', 'int'); // Security check if ($user->socid > 0) { @@ -45,7 +45,7 @@ $backtopage = GETPOST('backtopage', 'alpha'); * Actions */ -if (GETPOST('cancel', 'alpha') && ! empty($backtopage)) +if (GETPOST('cancel', 'alpha') && !empty($backtopage)) { header("Location: ".$backtopage); exit; @@ -58,15 +58,15 @@ if (GETPOST('action', 'aZ09') == 'setremise') $discount_type = GETPOST('discount_type', 'int'); - if(! empty($discount_type)) { - $result=$object->set_remise_supplier(price2num(GETPOST("remise")), GETPOST("note"), $user); + if (!empty($discount_type)) { + $result = $object->set_remise_supplier(price2num(GETPOST("remise")), GETPOST("note"), $user); } else { - $result=$object->set_remise_client(price2num(GETPOST("remise")), GETPOST("note"), $user); + $result = $object->set_remise_client(price2num(GETPOST("remise")), GETPOST("note"), $user); } if ($result > 0) { - if (! empty($backtopage)) + if (!empty($backtopage)) { header("Location: ".$backtopage); exit; @@ -88,7 +88,7 @@ if (GETPOST('action', 'aZ09') == 'setremise') * View */ -$form=new Form($db); +$form = new Form($db); llxHeader(); @@ -116,13 +116,13 @@ if ($socid > 0) dol_fiche_head($head, 'relativediscount', $langs->trans("ThirdParty"), -1, 'company'); - dol_banner_tab($object, 'socid', '', ($user->socid?0:1), 'rowid', 'nom'); + dol_banner_tab($object, 'socid', '', ($user->socid ? 0 : 1), 'rowid', 'nom'); print '
'; print '
'; - if (! $isCustomer && ! $isSupplier) { + if (!$isCustomer && !$isSupplier) { print '

'.$langs->trans('ThirdpartyIsNeitherCustomerNorClientSoCannotHaveDiscounts').'

'; dol_fiche_end(); @@ -176,7 +176,7 @@ if ($socid > 0) print ' '; } if ($isSupplier) { - print ' '; + print ' '; } print ''; } @@ -197,7 +197,7 @@ if ($socid > 0) print '
'; print ''; - if (! empty($backtopage)) + if (!empty($backtopage)) { print '     '; print ''; @@ -208,8 +208,8 @@ if ($socid > 0) print '
'; - if($isCustomer) { - if($isSupplier) { + if ($isCustomer) { + if ($isSupplier) { print '
'; print '
'; print load_fiche_titre($langs->trans("CustomerDiscounts"), '', ''); @@ -218,18 +218,18 @@ if ($socid > 0) /* * List log of all customer percent discounts */ - $sql = "SELECT rc.rowid, rc.remise_client as remise_percent, rc.note, rc.datec as dc,"; - $sql.= " u.login, u.rowid as user_id"; - $sql.= " FROM ".MAIN_DB_PREFIX."societe_remise as rc, ".MAIN_DB_PREFIX."user as u"; - $sql.= " WHERE rc.fk_soc = " . $object->id; - $sql.= " AND rc.entity = " . $conf->entity; - $sql.= " AND u.rowid = rc.fk_user_author"; - $sql.= " ORDER BY rc.datec DESC"; + $sql = "SELECT rc.rowid, rc.remise_client as remise_percent, rc.note, rc.datec as dc,"; + $sql .= " u.login, u.rowid as user_id"; + $sql .= " FROM ".MAIN_DB_PREFIX."societe_remise as rc, ".MAIN_DB_PREFIX."user as u"; + $sql .= " WHERE rc.fk_soc = ".$object->id; + $sql .= " AND rc.entity = ".$conf->entity; + $sql .= " AND u.rowid = rc.fk_user_author"; + $sql .= " ORDER BY rc.datec DESC"; - $resql=$db->query($sql); + $resql = $db->query($sql); if ($resql) { - print '
'.$langs->trans("ThirdParty").''.$societe->getNomUrl(1).'
'; + print '
'; $tag = !$tag; print ''; print ''; @@ -266,8 +266,8 @@ if ($socid > 0) } } - if($isSupplier) { - if($isCustomer) { + if ($isSupplier) { + if ($isCustomer) { print ''; // class="fichehalfleft" print '
'; print '
'; @@ -277,18 +277,18 @@ if ($socid > 0) /* * List log of all supplier percent discounts */ - $sql = "SELECT rc.rowid, rc.remise_supplier as remise_percent, rc.note, rc.datec as dc,"; - $sql.= " u.login, u.rowid as user_id"; - $sql.= " FROM ".MAIN_DB_PREFIX."societe_remise_supplier as rc, ".MAIN_DB_PREFIX."user as u"; - $sql.= " WHERE rc.fk_soc = " . $object->id; - $sql.= " AND rc.entity = " . $conf->entity; - $sql.= " AND u.rowid = rc.fk_user_author"; - $sql.= " ORDER BY rc.datec DESC"; + $sql = "SELECT rc.rowid, rc.remise_supplier as remise_percent, rc.note, rc.datec as dc,"; + $sql .= " u.login, u.rowid as user_id"; + $sql .= " FROM ".MAIN_DB_PREFIX."societe_remise_supplier as rc, ".MAIN_DB_PREFIX."user as u"; + $sql .= " WHERE rc.fk_soc = ".$object->id; + $sql .= " AND rc.entity = ".$conf->entity; + $sql .= " AND u.rowid = rc.fk_user_author"; + $sql .= " ORDER BY rc.datec DESC"; - $resql=$db->query($sql); + $resql = $db->query($sql); if ($resql) { - print '
'.$langs->trans("Date").'
'; + print '
'; $tag = !$tag; print ''; print ''; @@ -324,7 +324,7 @@ if ($socid > 0) dol_print_error($db); } - if($isCustomer) { + if ($isCustomer) { print ''; // class="ficheaddleft" print ''; // class="fichehalfright" print ''; // class="fichecenter" diff --git a/htdocs/comm/remx.php b/htdocs/comm/remx.php index 523c6ebc7b1..ac79c1fe0a7 100644 --- a/htdocs/comm/remx.php +++ b/htdocs/comm/remx.php @@ -33,13 +33,13 @@ require_once DOL_DOCUMENT_ROOT.'/core/class/discount.class.php'; // Load translation files required by the page $langs->loadLangs(array('orders', 'bills', 'companies')); -$id=GETPOST('id', 'int'); +$id = GETPOST('id', 'int'); -$action=GETPOST('action', 'alpha'); -$backtopage=GETPOST('backtopage', 'alpha'); +$action = GETPOST('action', 'alpha'); +$backtopage = GETPOST('backtopage', 'alpha'); // Security check -$socid = GETPOST('id', 'int')?GETPOST('id', 'int'):GETPOST('socid', 'int'); +$socid = GETPOST('id', 'int') ?GETPOST('id', 'int') : GETPOST('socid', 'int'); if ($user->socid > 0) { $socid = $user->socid; @@ -50,7 +50,7 @@ if ($user->socid > 0) * Actions */ -if (GETPOST('cancel', 'alpha') && ! empty($backtopage)) +if (GETPOST('cancel', 'alpha') && !empty($backtopage)) { header("Location: ".$backtopage); exit; @@ -61,82 +61,82 @@ if ($action == 'confirm_split' && GETPOST("confirm") == 'yes') //if ($user->rights->societe->creer) //if ($user->rights->facture->creer) - $amount_ttc_1=GETPOST('amount_ttc_1'); - $amount_ttc_2=GETPOST('amount_ttc_2'); + $amount_ttc_1 = GETPOST('amount_ttc_1'); + $amount_ttc_2 = GETPOST('amount_ttc_2'); - $error=0; - $remid=GETPOST("remid")?GETPOST("remid"):0; - $discount=new DiscountAbsolute($db); - $res=$discount->fetch($remid); - if (! $res > 0) + $error = 0; + $remid = GETPOST("remid") ?GETPOST("remid") : 0; + $discount = new DiscountAbsolute($db); + $res = $discount->fetch($remid); + if (!$res > 0) { $error++; setEventMessages($langs->trans("ErrorFailedToLoadDiscount"), null, 'errors'); } - if (! $error && price2num($amount_ttc_1+$amount_ttc_2) != $discount->amount_ttc) + if (!$error && price2num($amount_ttc_1 + $amount_ttc_2) != $discount->amount_ttc) { $error++; setEventMessages($langs->trans("TotalOfTwoDiscountMustEqualsOriginal"), null, 'errors'); } - if (! $error && $discount->fk_facture_line) + if (!$error && $discount->fk_facture_line) { $error++; setEventMessages($langs->trans("ErrorCantSplitAUsedDiscount"), null, 'errors'); } - if (! $error) + if (!$error) { - $newdiscount1=new DiscountAbsolute($db); - $newdiscount2=new DiscountAbsolute($db); - $newdiscount1->fk_facture_source=$discount->fk_facture_source; - $newdiscount2->fk_facture_source=$discount->fk_facture_source; - $newdiscount1->fk_facture=$discount->fk_facture; - $newdiscount2->fk_facture=$discount->fk_facture; - $newdiscount1->fk_facture_line=$discount->fk_facture_line; - $newdiscount2->fk_facture_line=$discount->fk_facture_line; - $newdiscount1->fk_invoice_supplier_source=$discount->fk_invoice_supplier_source; - $newdiscount2->fk_invoice_supplier_source=$discount->fk_invoice_supplier_source; - $newdiscount1->fk_invoice_supplier=$discount->fk_invoice_supplier; - $newdiscount2->fk_invoice_supplier=$discount->fk_invoice_supplier; - $newdiscount1->fk_invoice_supplier_line=$discount->fk_invoice_supplier_line; - $newdiscount2->fk_invoice_supplier_line=$discount->fk_invoice_supplier_line; + $newdiscount1 = new DiscountAbsolute($db); + $newdiscount2 = new DiscountAbsolute($db); + $newdiscount1->fk_facture_source = $discount->fk_facture_source; + $newdiscount2->fk_facture_source = $discount->fk_facture_source; + $newdiscount1->fk_facture = $discount->fk_facture; + $newdiscount2->fk_facture = $discount->fk_facture; + $newdiscount1->fk_facture_line = $discount->fk_facture_line; + $newdiscount2->fk_facture_line = $discount->fk_facture_line; + $newdiscount1->fk_invoice_supplier_source = $discount->fk_invoice_supplier_source; + $newdiscount2->fk_invoice_supplier_source = $discount->fk_invoice_supplier_source; + $newdiscount1->fk_invoice_supplier = $discount->fk_invoice_supplier; + $newdiscount2->fk_invoice_supplier = $discount->fk_invoice_supplier; + $newdiscount1->fk_invoice_supplier_line = $discount->fk_invoice_supplier_line; + $newdiscount2->fk_invoice_supplier_line = $discount->fk_invoice_supplier_line; if ($discount->description == '(CREDIT_NOTE)' || $discount->description == '(DEPOSIT)') { - $newdiscount1->description=$discount->description; - $newdiscount2->description=$discount->description; + $newdiscount1->description = $discount->description; + $newdiscount2->description = $discount->description; } else { - $newdiscount1->description=$discount->description.' (1)'; - $newdiscount2->description=$discount->description.' (2)'; + $newdiscount1->description = $discount->description.' (1)'; + $newdiscount2->description = $discount->description.' (2)'; } - $newdiscount1->fk_user=$discount->fk_user; - $newdiscount2->fk_user=$discount->fk_user; - $newdiscount1->fk_soc=$discount->fk_soc; - $newdiscount2->fk_soc=$discount->fk_soc; - $newdiscount1->discount_type=$discount->discount_type; - $newdiscount2->discount_type=$discount->discount_type; - $newdiscount1->datec=$discount->datec; - $newdiscount2->datec=$discount->datec; - $newdiscount1->tva_tx=$discount->tva_tx; - $newdiscount2->tva_tx=$discount->tva_tx; - $newdiscount1->amount_ttc=$_POST["amount_ttc_1"]; - $newdiscount2->amount_ttc=price2num($discount->amount_ttc-$newdiscount1->amount_ttc); - $newdiscount1->amount_ht=price2num($newdiscount1->amount_ttc/(1+$newdiscount1->tva_tx/100), 'MT'); - $newdiscount2->amount_ht=price2num($newdiscount2->amount_ttc/(1+$newdiscount2->tva_tx/100), 'MT'); - $newdiscount1->amount_tva=price2num($newdiscount1->amount_ttc-$newdiscount1->amount_ht); - $newdiscount2->amount_tva=price2num($newdiscount2->amount_ttc-$newdiscount2->amount_ht); + $newdiscount1->fk_user = $discount->fk_user; + $newdiscount2->fk_user = $discount->fk_user; + $newdiscount1->fk_soc = $discount->fk_soc; + $newdiscount2->fk_soc = $discount->fk_soc; + $newdiscount1->discount_type = $discount->discount_type; + $newdiscount2->discount_type = $discount->discount_type; + $newdiscount1->datec = $discount->datec; + $newdiscount2->datec = $discount->datec; + $newdiscount1->tva_tx = $discount->tva_tx; + $newdiscount2->tva_tx = $discount->tva_tx; + $newdiscount1->amount_ttc = $_POST["amount_ttc_1"]; + $newdiscount2->amount_ttc = price2num($discount->amount_ttc - $newdiscount1->amount_ttc); + $newdiscount1->amount_ht = price2num($newdiscount1->amount_ttc / (1 + $newdiscount1->tva_tx / 100), 'MT'); + $newdiscount2->amount_ht = price2num($newdiscount2->amount_ttc / (1 + $newdiscount2->tva_tx / 100), 'MT'); + $newdiscount1->amount_tva = price2num($newdiscount1->amount_ttc - $newdiscount1->amount_ht); + $newdiscount2->amount_tva = price2num($newdiscount2->amount_ttc - $newdiscount2->amount_ht); $db->begin(); - $discount->fk_facture_source=0; // This is to delete only the require record (that we will recreate with two records) and not all family with same fk_facture_source + $discount->fk_facture_source = 0; // This is to delete only the require record (that we will recreate with two records) and not all family with same fk_facture_source // This is to delete only the require record (that we will recreate with two records) and not all family with same fk_invoice_supplier_source - $discount->fk_invoice_supplier_source=0; - $res=$discount->delete($user); - $newid1=$newdiscount1->create($user); - $newid2=$newdiscount2->create($user); + $discount->fk_invoice_supplier_source = 0; + $res = $discount->delete($user); + $newid1 = $newdiscount1->create($user); + $newid2 = $newdiscount2->create($user); if ($res > 0 && $newid1 > 0 && $newid2 > 0) { $db->commit(); - header("Location: ".$_SERVER["PHP_SELF"].'?id='.$id.($backtopage?'&backtopage='.urlencode($backtopage):'')); // To avoid pb whith back + header("Location: ".$_SERVER["PHP_SELF"].'?id='.$id.($backtopage ? '&backtopage='.urlencode($backtopage) : '')); // To avoid pb whith back exit; } else @@ -151,29 +151,29 @@ if ($action == 'setremise' && $user->rights->societe->creer) //if ($user->rights->societe->creer) //if ($user->rights->facture->creer) - $amount_ht=GETPOST('amount_ht'); - $desc=GETPOST('desc', 'alpha'); - $tva_tx=GETPOST('tva_tx', 'alpha'); - $discount_type=! empty($_POST['discount_type'])?GETPOST('discount_type', 'alpha'):0; + $amount_ht = GETPOST('amount_ht'); + $desc = GETPOST('desc', 'alpha'); + $tva_tx = GETPOST('tva_tx', 'alpha'); + $discount_type = !empty($_POST['discount_type']) ?GETPOST('discount_type', 'alpha') : 0; if (price2num($amount_ht) > 0) { - $error=0; + $error = 0; if (empty($desc)) { setEventMessages($langs->trans("ErrorFieldRequired", $langs->transnoentitiesnoconv("ReasonDiscount")), null, 'errors'); $error++; } - if (! $error) + if (!$error) { $soc = new Societe($db); $soc->fetch($id); - $discountid=$soc->set_remise_except($amount_ht, $user, $desc, $tva_tx, $discount_type); + $discountid = $soc->set_remise_except($amount_ht, $user, $desc, $tva_tx, $discount_type); if ($discountid > 0) { - if (! empty($backtopage)) + if (!empty($backtopage)) { header("Location: ".$backtopage.'&discountid='.$discountid); exit; @@ -197,7 +197,7 @@ if ($action == 'setremise' && $user->rights->societe->creer) } } -if (GETPOST('action', 'aZ09') == 'confirm_remove' && GETPOST("confirm")=='yes') +if (GETPOST('action', 'aZ09') == 'confirm_remove' && GETPOST("confirm") == 'yes') { //if ($user->rights->societe->creer) //if ($user->rights->facture->creer) @@ -205,12 +205,12 @@ if (GETPOST('action', 'aZ09') == 'confirm_remove' && GETPOST("confirm")=='yes') $db->begin(); $discount = new DiscountAbsolute($db); - $result=$discount->fetch(GETPOST("remid")); - $result=$discount->delete($user); + $result = $discount->fetch(GETPOST("remid")); + $result = $discount->delete($user); if ($result > 0) { $db->commit(); - header("Location: ".$_SERVER["PHP_SELF"].'?id='.$id); // To avoid pb whith back + header("Location: ".$_SERVER["PHP_SELF"].'?id='.$id); // To avoid pb whith back exit; } else @@ -225,9 +225,9 @@ if (GETPOST('action', 'aZ09') == 'confirm_remove' && GETPOST("confirm")=='yes') * View */ -$form=new Form($db); -$facturestatic=new Facture($db); -$facturefournstatic=new FactureFournisseur($db); +$form = new Form($db); +$facturestatic = new Facture($db); +$facturefournstatic = new FactureFournisseur($db); llxHeader('', $langs->trans("GlobalDiscount")); @@ -252,13 +252,13 @@ if ($socid > 0) dol_fiche_head($head, 'absolutediscount', $langs->trans("ThirdParty"), 0, 'company'); - dol_banner_tab($object, 'socid', '', ($user->socid?0:1), 'rowid', 'nom'); + dol_banner_tab($object, 'socid', '', ($user->socid ? 0 : 1), 'rowid', 'nom'); print '
'; print '
'; - if(! $isCustomer && ! $isSupplier) { + if (!$isCustomer && !$isSupplier) { print '

'.$langs->trans('ThirdpartyIsNeitherCustomerNorClientSoCannotHaveDiscounts').'

'; dol_fiche_end(); @@ -273,21 +273,21 @@ if ($socid > 0) print '
'.$langs->trans("Date").'
'; - if($isCustomer) { // Calcul avoirs client en cours - $remise_all=$remise_user=0; + if ($isCustomer) { // Calcul avoirs client en cours + $remise_all = $remise_user = 0; $sql = "SELECT SUM(rc.amount_ht) as amount, rc.fk_user"; - $sql.= " FROM ".MAIN_DB_PREFIX."societe_remise_except as rc"; - $sql.= " WHERE rc.fk_soc = " . $object->id; - $sql.= " AND rc.entity = " . $conf->entity; - $sql.= " AND discount_type = 0"; // Exclude supplier discounts - $sql.= " AND (fk_facture_line IS NULL AND fk_facture IS NULL)"; - $sql.= " GROUP BY rc.fk_user"; - $resql=$db->query($sql); + $sql .= " FROM ".MAIN_DB_PREFIX."societe_remise_except as rc"; + $sql .= " WHERE rc.fk_soc = ".$object->id; + $sql .= " AND rc.entity = ".$conf->entity; + $sql .= " AND discount_type = 0"; // Exclude supplier discounts + $sql .= " AND (fk_facture_line IS NULL AND fk_facture IS NULL)"; + $sql .= " GROUP BY rc.fk_user"; + $resql = $db->query($sql); if ($resql) { $obj = $db->fetch_object($resql); - $remise_all+=$obj->amount; - if ($obj->fk_user == $user->id) $remise_user+=$obj->amount; + $remise_all += $obj->amount; + if ($obj->fk_user == $user->id) $remise_user += $obj->amount; } else { @@ -297,29 +297,29 @@ if ($socid > 0) print ''; print ''; - if (! empty($user->fk_soc)) // No need to show this for external users + if (!empty($user->fk_soc)) // No need to show this for external users { print ''; print ''; } } - if($isSupplier) { + if ($isSupplier) { // Calcul avoirs fournisseur en cours - $remise_all=$remise_user=0; + $remise_all = $remise_user = 0; $sql = "SELECT SUM(rc.amount_ht) as amount, rc.fk_user"; - $sql.= " FROM ".MAIN_DB_PREFIX."societe_remise_except as rc"; - $sql.= " WHERE rc.fk_soc = " . $object->id; - $sql.= " AND rc.entity = " . $conf->entity; - $sql.= " AND discount_type = 1"; // Exclude customer discounts - $sql.= " AND (fk_invoice_supplier_line IS NULL AND fk_invoice_supplier IS NULL)"; - $sql.= " GROUP BY rc.fk_user"; - $resql=$db->query($sql); + $sql .= " FROM ".MAIN_DB_PREFIX."societe_remise_except as rc"; + $sql .= " WHERE rc.fk_soc = ".$object->id; + $sql .= " AND rc.entity = ".$conf->entity; + $sql .= " AND discount_type = 1"; // Exclude customer discounts + $sql .= " AND (fk_invoice_supplier_line IS NULL AND fk_invoice_supplier IS NULL)"; + $sql .= " GROUP BY rc.fk_user"; + $resql = $db->query($sql); if ($resql) { $obj = $db->fetch_object($resql); - $remise_all+=$obj->amount; - if ($obj->fk_user == $user->id) $remise_user+=$obj->amount; + $remise_all += $obj->amount; + if ($obj->fk_user == $user->id) $remise_user += $obj->amount; } else { @@ -329,7 +329,7 @@ if ($socid > 0) print ''; print ''; - if (! empty($user->fk_soc)) // No need to show this for external users + if (!empty($user->fk_soc)) // No need to show this for external users { print ''; print ''; @@ -348,16 +348,16 @@ if ($socid > 0) print '
'; - if($isCustomer && ! $isSupplier) { + if ($isCustomer && !$isSupplier) { print ''; } - if(! $isCustomer && $isSupplier) { + if (!$isCustomer && $isSupplier) { print ''; } - print '
'.$langs->trans("CustomerAbsoluteDiscountAllUsers").''.$remise_all.' '.$langs->trans("Currency".$conf->currency).' '.$langs->trans("HT").'
'.$langs->trans("CustomerAbsoluteDiscountMy").''.$remise_user.' '.$langs->trans("Currency".$conf->currency).' '.$langs->trans("HT").'
'.$langs->trans("SupplierAbsoluteDiscountAllUsers").''.$remise_all.' '.$langs->trans("Currency".$conf->currency).' '.$langs->trans("HT").'
'.$langs->trans("SupplierAbsoluteDiscountMy").''.$remise_user.' '.$langs->trans("Currency".$conf->currency).' '.$langs->trans("HT").'
'; - if($isCustomer && $isSupplier) { + print '
'; + if ($isCustomer && $isSupplier) { print ''; print ''; - print ''; + print ''; + print ''; print ''; // Multicurrency Amount VAT - print ''; - print ''; + print ''; + print ''; print ''; // Multicurrency Amount TTC - print ''; - print ''; + print ''; + print ''; print ''; } // Total HT $alert = ''; - if (! empty($conf->global->ORDER_MANAGE_MIN_AMOUNT) && $object->total_ht < $object->thirdparty->order_min_amount) { - $alert = ' ' . img_warning($langs->trans('OrderMinAmount').': '.price($object->thirdparty->order_min_amount)); + if (!empty($conf->global->ORDER_MANAGE_MIN_AMOUNT) && $object->total_ht < $object->thirdparty->order_min_amount) { + $alert = ' '.img_warning($langs->trans('OrderMinAmount').': '.price($object->thirdparty->order_min_amount)); } - print ''; - print ''; + print ''; + print ''; // Total VAT - print ''; + print ''; // Amount Local Taxes if ($mysoc->localtax1_assuj == "1" || $object->total_localtax1 != 0) // Localtax1 { - print ''; - print ''; + print ''; + print ''; } if ($mysoc->localtax2_assuj == "1" || $object->total_localtax2 != 0) // Localtax2 IRPF { - print ''; - print ''; + print ''; + print ''; } // Total TTC - print ''; + print ''; // Statut //print ''; @@ -2462,27 +2462,27 @@ if ($action == 'create' && $usercancreate) print '
'.$langs->trans('DiscountType').' '; print '   '; @@ -382,7 +382,7 @@ if ($socid > 0) { print '
'; print ''; - if (! empty($backtopage)) + if (!empty($backtopage)) { print '     '; print ''; @@ -407,44 +407,44 @@ if ($socid > 0) print load_fiche_titre($langs->trans("DiscountStillRemaining")); - if($isCustomer) { - if($isSupplier) { + if ($isCustomer) { + if ($isSupplier) { print '
'; print '
'; print load_fiche_titre($langs->trans("CustomerDiscounts"), '', ''); } $sql = "SELECT rc.rowid, rc.amount_ht, rc.amount_tva, rc.amount_ttc, rc.tva_tx, rc.multicurrency_amount_ht, rc.multicurrency_amount_tva, rc.multicurrency_amount_ttc,"; - $sql.= " rc.datec as dc, rc.description,"; - $sql.= " rc.fk_facture_source,"; - $sql.= " u.login, u.rowid as user_id,"; - $sql.= " fa.ref as ref, fa.type as type"; - $sql.= " FROM ".MAIN_DB_PREFIX."user as u, ".MAIN_DB_PREFIX."societe_remise_except as rc"; - $sql.= " LEFT JOIN ".MAIN_DB_PREFIX."facture as fa ON rc.fk_facture_source = fa.rowid"; - $sql.= " WHERE rc.fk_soc = " . $object->id; - $sql.= " AND rc.entity = " . $conf->entity; - $sql.= " AND u.rowid = rc.fk_user"; - $sql.= " AND rc.discount_type = 0"; // Eliminate supplier discounts - $sql.= " AND (rc.fk_facture_line IS NULL AND rc.fk_facture IS NULL)"; - $sql.= " ORDER BY rc.datec DESC"; + $sql .= " rc.datec as dc, rc.description,"; + $sql .= " rc.fk_facture_source,"; + $sql .= " u.login, u.rowid as user_id,"; + $sql .= " fa.ref as ref, fa.type as type"; + $sql .= " FROM ".MAIN_DB_PREFIX."user as u, ".MAIN_DB_PREFIX."societe_remise_except as rc"; + $sql .= " LEFT JOIN ".MAIN_DB_PREFIX."facture as fa ON rc.fk_facture_source = fa.rowid"; + $sql .= " WHERE rc.fk_soc = ".$object->id; + $sql .= " AND rc.entity = ".$conf->entity; + $sql .= " AND u.rowid = rc.fk_user"; + $sql .= " AND rc.discount_type = 0"; // Eliminate supplier discounts + $sql .= " AND (rc.fk_facture_line IS NULL AND rc.fk_facture IS NULL)"; + $sql .= " ORDER BY rc.datec DESC"; - $resql=$db->query($sql); + $resql = $db->query($sql); if ($resql) { print '
'; print ''; print ''; - print ''; // Need 120+ for format with AM/PM + print ''; // Need 120+ for format with AM/PM print ''; print ''; print ''; - if (! empty($conf->multicurrency->enabled)) + if (!empty($conf->multicurrency->enabled)) { print ''; } print ''; print ''; - if (! empty($conf->multicurrency->enabled)) + if (!empty($conf->multicurrency->enabled)) { print ''; } @@ -452,7 +452,7 @@ if ($socid > 0) print ''; print ''; - $showconfirminfo=array(); + $showconfirminfo = array(); $i = 0; $num = $db->num_rows($resql); @@ -467,27 +467,27 @@ if ($socid > 0) if (preg_match('/\(CREDIT_NOTE\)/', $obj->description)) { print ''; } elseif (preg_match('/\(DEPOSIT\)/', $obj->description)) { print ''; } elseif (preg_match('/\(EXCESS RECEIVED\)/', $obj->description)) { print ''; } @@ -499,13 +499,13 @@ if ($socid > 0) } print ''; print ''; - if (! empty($conf->multicurrency->enabled)) + if (!empty($conf->multicurrency->enabled)) { print ''; } print ''; print ''; - if (! empty($conf->multicurrency->enabled)) + if (!empty($conf->multicurrency->enabled)) { print ''; } @@ -515,18 +515,18 @@ if ($socid > 0) if ($user->rights->societe->creer || $user->rights->facture->creer) { print ''; } else print ''; print ''; - if ($_GET["action"]=='split' && GETPOST('remid') == $obj->rowid) + if ($_GET["action"] == 'split' && GETPOST('remid') == $obj->rowid) { - $showconfirminfo['rowid']=$obj->rowid; - $showconfirminfo['amount_ttc']=$obj->amount_ttc; + $showconfirminfo['rowid'] = $obj->rowid; + $showconfirminfo['amount_ttc'] = $obj->amount_ttc; } $i++; } @@ -541,15 +541,15 @@ if ($socid > 0) if (count($showconfirminfo)) { - $amount1=price2num($showconfirminfo['amount_ttc']/2, 'MT'); - $amount2=($showconfirminfo['amount_ttc']-$amount1); - $formquestion=array( + $amount1 = price2num($showconfirminfo['amount_ttc'] / 2, 'MT'); + $amount2 = ($showconfirminfo['amount_ttc'] - $amount1); + $formquestion = array( 'text' => $langs->trans('TypeAmountOfEachNewDiscount'), array('type' => 'text', 'name' => 'amount_ttc_1', 'label' => $langs->trans("AmountTTC").' 1', 'value' => $amount1, 'size' => '5'), array('type' => 'text', 'name' => 'amount_ttc_2', 'label' => $langs->trans("AmountTTC").' 2', 'value' => $amount2, 'size' => '5') ); $langs->load("dict"); - print $form->formconfirm($_SERVER["PHP_SELF"].'?id='.$object->id.'&remid='.$showconfirminfo['rowid'].($backtopage?'&backtopage='.urlencode($backtopage):''), $langs->trans('SplitDiscount'), $langs->trans('ConfirmSplitDiscount', price($showconfirminfo['amount_ttc']), $langs->transnoentities("Currency".$conf->currency)), 'confirm_split', $formquestion, 0, 0); + print $form->formconfirm($_SERVER["PHP_SELF"].'?id='.$object->id.'&remid='.$showconfirminfo['rowid'].($backtopage ? '&backtopage='.urlencode($backtopage) : ''), $langs->trans('SplitDiscount'), $langs->trans('ConfirmSplitDiscount', price($showconfirminfo['amount_ttc']), $langs->transnoentities("Currency".$conf->currency)), 'confirm_split', $formquestion, 0, 0); } } else @@ -558,8 +558,8 @@ if ($socid > 0) } } - if($isSupplier) { - if($isCustomer) { + if ($isSupplier) { + if ($isCustomer) { print ''; // class="fichehalfleft" print '
'; print '
'; @@ -570,36 +570,36 @@ if ($socid > 0) * Liste remises fixes fournisseur restant en cours (= liees a aucune facture ni ligne de facture) */ $sql = "SELECT rc.rowid, rc.amount_ht, rc.amount_tva, rc.amount_ttc, rc.tva_tx, rc.multicurrency_amount_ht, rc.multicurrency_amount_tva, rc.multicurrency_amount_ttc,"; - $sql.= " rc.datec as dc, rc.description,"; - $sql.= " rc.fk_invoice_supplier_source,"; - $sql.= " u.login, u.rowid as user_id,"; - $sql.= " fa.ref, fa.type as type"; - $sql.= " FROM ".MAIN_DB_PREFIX."user as u, ".MAIN_DB_PREFIX."societe_remise_except as rc"; - $sql.= " LEFT JOIN ".MAIN_DB_PREFIX."facture_fourn as fa ON rc.fk_invoice_supplier_source = fa.rowid"; - $sql.= " WHERE rc.fk_soc = " . $object->id; - $sql.= " AND rc.entity = " . $conf->entity; - $sql.= " AND u.rowid = rc.fk_user"; - $sql.= " AND rc.discount_type = 1"; // Eliminate customer discounts - $sql.= " AND (rc.fk_invoice_supplier IS NULL AND rc.fk_invoice_supplier_line IS NULL)"; - $sql.= " ORDER BY rc.datec DESC"; + $sql .= " rc.datec as dc, rc.description,"; + $sql .= " rc.fk_invoice_supplier_source,"; + $sql .= " u.login, u.rowid as user_id,"; + $sql .= " fa.ref, fa.type as type"; + $sql .= " FROM ".MAIN_DB_PREFIX."user as u, ".MAIN_DB_PREFIX."societe_remise_except as rc"; + $sql .= " LEFT JOIN ".MAIN_DB_PREFIX."facture_fourn as fa ON rc.fk_invoice_supplier_source = fa.rowid"; + $sql .= " WHERE rc.fk_soc = ".$object->id; + $sql .= " AND rc.entity = ".$conf->entity; + $sql .= " AND u.rowid = rc.fk_user"; + $sql .= " AND rc.discount_type = 1"; // Eliminate customer discounts + $sql .= " AND (rc.fk_invoice_supplier IS NULL AND rc.fk_invoice_supplier_line IS NULL)"; + $sql .= " ORDER BY rc.datec DESC"; - $resql=$db->query($sql); + $resql = $db->query($sql); if ($resql) { print '
'; print '
'.$langs->trans("Date").''.$langs->trans("Date").''.$langs->trans("ReasonDiscount").''.$langs->trans("ConsumedBy").''.$langs->trans("AmountHT").''.$langs->trans("MulticurrencyAmountHT").''.$langs->trans("VATRate").''.$langs->trans("AmountTTC").''.$langs->trans("MulticurrencyAmountTTC").' 
'; - $facturestatic->id=$obj->fk_facture_source; - $facturestatic->ref=$obj->ref; - $facturestatic->type=$obj->type; + $facturestatic->id = $obj->fk_facture_source; + $facturestatic->ref = $obj->ref; + $facturestatic->type = $obj->type; print preg_replace('/\(CREDIT_NOTE\)/', $langs->trans("CreditNote"), $obj->description).' '.$facturestatic->getNomURl(1); print ''; - $facturestatic->id=$obj->fk_facture_source; - $facturestatic->ref=$obj->ref; - $facturestatic->type=$obj->type; + $facturestatic->id = $obj->fk_facture_source; + $facturestatic->ref = $obj->ref; + $facturestatic->type = $obj->type; print preg_replace('/\(DEPOSIT\)/', $langs->trans("InvoiceDeposit"), $obj->description).' '.$facturestatic->getNomURl(1); print ''; - $facturestatic->id=$obj->fk_facture_source; - $facturestatic->ref=$obj->ref; - $facturestatic->type=$obj->type; + $facturestatic->id = $obj->fk_facture_source; + $facturestatic->ref = $obj->ref; + $facturestatic->type = $obj->type; print preg_replace('/\(EXCESS RECEIVED\)/', $langs->trans("ExcessReceived"), $obj->description).' '.$facturestatic->getNomURl(1); print ''.$langs->trans("NotConsumed").''.price($obj->amount_ht).''.price($obj->multicurrency_amount_ht).''.vatrate($obj->tva_tx, true).''.price($obj->amount_ttc).''.price($obj->multicurrency_amount_ttc).''; - print 'rowid.($backtopage?'&backtopage='.urlencode($backtopage):'').'">'.img_split($langs->trans("SplitDiscount")).''; + print 'rowid.($backtopage ? '&backtopage='.urlencode($backtopage) : '').'">'.img_split($langs->trans("SplitDiscount")).''; //print '   '; - print 'rowid.($backtopage?'&backtopage='.urlencode($backtopage):'').'">'.img_delete($langs->trans("RemoveDiscount")).''; + print 'rowid.($backtopage ? '&backtopage='.urlencode($backtopage) : '').'">'.img_delete($langs->trans("RemoveDiscount")).''; print ' 
'; print ''; - print ''; // Need 120+ for format with AM/PM + print ''; // Need 120+ for format with AM/PM print ''; print ''; print ''; - if (! empty($conf->multicurrency->enabled)) + if (!empty($conf->multicurrency->enabled)) { print ''; } print ''; print ''; - if (! empty($conf->multicurrency->enabled)) + if (!empty($conf->multicurrency->enabled)) { print ''; } @@ -607,7 +607,7 @@ if ($socid > 0) print ''; print ''; - $showconfirminfo=array(); + $showconfirminfo = array(); $i = 0; $num = $db->num_rows($resql); @@ -622,27 +622,27 @@ if ($socid > 0) if (preg_match('/\(CREDIT_NOTE\)/', $obj->description)) { print ''; } elseif (preg_match('/\(DEPOSIT\)/', $obj->description)) { print ''; } elseif (preg_match('/\(EXCESS PAID\)/', $obj->description)) { print ''; } @@ -654,13 +654,13 @@ if ($socid > 0) } print ''; print ''; - if (! empty($conf->multicurrency->enabled)) + if (!empty($conf->multicurrency->enabled)) { print ''; } print ''; print ''; - if (! empty($conf->multicurrency->enabled)) + if (!empty($conf->multicurrency->enabled)) { print ''; } @@ -670,18 +670,18 @@ if ($socid > 0) if ($user->rights->societe->creer || $user->rights->facture->creer) { print ''; } else print ''; print ''; - if ($_GET["action"]=='split' && GETPOST('remid') == $obj->rowid) + if ($_GET["action"] == 'split' && GETPOST('remid') == $obj->rowid) { - $showconfirminfo['rowid']=$obj->rowid; - $showconfirminfo['amount_ttc']=$obj->amount_ttc; + $showconfirminfo['rowid'] = $obj->rowid; + $showconfirminfo['amount_ttc'] = $obj->amount_ttc; } $i++; } @@ -696,15 +696,15 @@ if ($socid > 0) if (count($showconfirminfo)) { - $amount1=price2num($showconfirminfo['amount_ttc']/2, 'MT'); - $amount2=($showconfirminfo['amount_ttc']-$amount1); - $formquestion=array( + $amount1 = price2num($showconfirminfo['amount_ttc'] / 2, 'MT'); + $amount2 = ($showconfirminfo['amount_ttc'] - $amount1); + $formquestion = array( 'text' => $langs->trans('TypeAmountOfEachNewDiscount'), array('type' => 'text', 'name' => 'amount_ttc_1', 'label' => $langs->trans("AmountTTC").' 1', 'value' => $amount1, 'size' => '5'), array('type' => 'text', 'name' => 'amount_ttc_2', 'label' => $langs->trans("AmountTTC").' 2', 'value' => $amount2, 'size' => '5') ); $langs->load("dict"); - print $form->formconfirm($_SERVER["PHP_SELF"].'?id='.$object->id.'&remid='.$showconfirminfo['rowid'].($backtopage?'&backtopage='.urlencode($backtopage):''), $langs->trans('SplitDiscount'), $langs->trans('ConfirmSplitDiscount', price($showconfirminfo['amount_ttc']), $langs->transnoentities("Currency".$conf->currency)), 'confirm_split', $formquestion, 0, 0); + print $form->formconfirm($_SERVER["PHP_SELF"].'?id='.$object->id.'&remid='.$showconfirminfo['rowid'].($backtopage ? '&backtopage='.urlencode($backtopage) : ''), $langs->trans('SplitDiscount'), $langs->trans('ConfirmSplitDiscount', price($showconfirminfo['amount_ttc']), $langs->transnoentities("Currency".$conf->currency)), 'confirm_split', $formquestion, 0, 0); } } else @@ -727,8 +727,8 @@ if ($socid > 0) print load_fiche_titre($langs->trans("DiscountAlreadyCounted")); - if($isCustomer) { - if($isSupplier) { + if ($isCustomer) { + if ($isSupplier) { print '
'; print '
'; print load_fiche_titre($langs->trans("CustomerDiscounts"), '', ''); @@ -736,59 +736,59 @@ if ($socid > 0) // Discount linked to invoice lines $sql = "SELECT rc.rowid, rc.amount_ht, rc.amount_tva, rc.amount_ttc, rc.tva_tx, rc.multicurrency_amount_ht, rc.multicurrency_amount_tva, rc.multicurrency_amount_ttc,"; - $sql.= " rc.datec as dc, rc.description, rc.fk_facture_line, rc.fk_facture,"; - $sql.= " rc.fk_facture_source,"; - $sql.= " u.login, u.rowid as user_id,"; - $sql.= " f.rowid, f.ref,"; - $sql.= " fa.ref as ref, fa.type as type"; - $sql.= " FROM ".MAIN_DB_PREFIX."facture as f"; - $sql.= " , ".MAIN_DB_PREFIX."user as u"; - $sql.= " , ".MAIN_DB_PREFIX."facturedet as fc"; - $sql.= " , ".MAIN_DB_PREFIX."societe_remise_except as rc"; - $sql.= " LEFT JOIN ".MAIN_DB_PREFIX."facture as fa ON rc.fk_facture_source = fa.rowid"; - $sql.= " WHERE rc.fk_soc =". $object->id; - $sql.= " AND rc.fk_facture_line = fc.rowid"; - $sql.= " AND fc.fk_facture = f.rowid"; - $sql.= " AND rc.fk_user = u.rowid"; - $sql.= " AND rc.discount_type = 0"; // Eliminate supplier discounts - $sql.= " ORDER BY dc DESC"; + $sql .= " rc.datec as dc, rc.description, rc.fk_facture_line, rc.fk_facture,"; + $sql .= " rc.fk_facture_source,"; + $sql .= " u.login, u.rowid as user_id,"; + $sql .= " f.rowid, f.ref,"; + $sql .= " fa.ref as ref, fa.type as type"; + $sql .= " FROM ".MAIN_DB_PREFIX."facture as f"; + $sql .= " , ".MAIN_DB_PREFIX."user as u"; + $sql .= " , ".MAIN_DB_PREFIX."facturedet as fc"; + $sql .= " , ".MAIN_DB_PREFIX."societe_remise_except as rc"; + $sql .= " LEFT JOIN ".MAIN_DB_PREFIX."facture as fa ON rc.fk_facture_source = fa.rowid"; + $sql .= " WHERE rc.fk_soc =".$object->id; + $sql .= " AND rc.fk_facture_line = fc.rowid"; + $sql .= " AND fc.fk_facture = f.rowid"; + $sql .= " AND rc.fk_user = u.rowid"; + $sql .= " AND rc.discount_type = 0"; // Eliminate supplier discounts + $sql .= " ORDER BY dc DESC"; //$sql.= " UNION "; // Remises liees a factures $sql2 = "SELECT rc.rowid, rc.amount_ht, rc.amount_tva, rc.amount_ttc, rc.tva_tx,"; - $sql2.= " rc.datec as dc, rc.description, rc.fk_facture_line, rc.fk_facture,"; - $sql2.= " rc.fk_facture_source,"; - $sql2.= " u.login, u.rowid as user_id,"; - $sql2.= " f.rowid, f.ref,"; - $sql2.= " fa.ref as ref, fa.type as type"; - $sql2.= " FROM ".MAIN_DB_PREFIX."facture as f"; - $sql2.= " , ".MAIN_DB_PREFIX."user as u"; - $sql2.= " , ".MAIN_DB_PREFIX."societe_remise_except as rc"; - $sql2.= " LEFT JOIN ".MAIN_DB_PREFIX."facture as fa ON rc.fk_facture_source = fa.rowid"; - $sql2.= " WHERE rc.fk_soc =". $object->id; - $sql2.= " AND rc.fk_facture = f.rowid"; - $sql2.= " AND rc.fk_user = u.rowid"; - $sql2.= " AND rc.discount_type = 0"; // Eliminate supplier discounts - $sql2.= " ORDER BY dc DESC"; + $sql2 .= " rc.datec as dc, rc.description, rc.fk_facture_line, rc.fk_facture,"; + $sql2 .= " rc.fk_facture_source,"; + $sql2 .= " u.login, u.rowid as user_id,"; + $sql2 .= " f.rowid, f.ref,"; + $sql2 .= " fa.ref as ref, fa.type as type"; + $sql2 .= " FROM ".MAIN_DB_PREFIX."facture as f"; + $sql2 .= " , ".MAIN_DB_PREFIX."user as u"; + $sql2 .= " , ".MAIN_DB_PREFIX."societe_remise_except as rc"; + $sql2 .= " LEFT JOIN ".MAIN_DB_PREFIX."facture as fa ON rc.fk_facture_source = fa.rowid"; + $sql2 .= " WHERE rc.fk_soc =".$object->id; + $sql2 .= " AND rc.fk_facture = f.rowid"; + $sql2 .= " AND rc.fk_user = u.rowid"; + $sql2 .= " AND rc.discount_type = 0"; // Eliminate supplier discounts + $sql2 .= " ORDER BY dc DESC"; - $resql=$db->query($sql); - $resql2=null; - if ($resql) $resql2=$db->query($sql2); + $resql = $db->query($sql); + $resql2 = null; + if ($resql) $resql2 = $db->query($sql2); if ($resql2) { print '
'; - print '
'.$langs->trans("Date").''.$langs->trans("Date").''.$langs->trans("ReasonDiscount").''.$langs->trans("ConsumedBy").''.$langs->trans("AmountHT").''.$langs->trans("MulticurrencyAmountHT").''.$langs->trans("VATRate").''.$langs->trans("AmountTTC").''.$langs->trans("MulticurrencyAmountTTC").' 
'; - $facturefournstatic->id=$obj->fk_invoice_supplier_source; - $facturefournstatic->ref=$obj->ref; - $facturefournstatic->type=$obj->type; + $facturefournstatic->id = $obj->fk_invoice_supplier_source; + $facturefournstatic->ref = $obj->ref; + $facturefournstatic->type = $obj->type; print preg_replace('/\(CREDIT_NOTE\)/', $langs->trans("CreditNote"), $obj->description).' '.$facturefournstatic->getNomURl(1); print ''; - $facturefournstatic->id=$obj->fk_invoice_supplier_source; - $facturefournstatic->ref=$obj->ref; - $facturefournstatic->type=$obj->type; + $facturefournstatic->id = $obj->fk_invoice_supplier_source; + $facturefournstatic->ref = $obj->ref; + $facturefournstatic->type = $obj->type; print preg_replace('/\(DEPOSIT\)/', $langs->trans("InvoiceDeposit"), $obj->description).' '.$facturefournstatic->getNomURl(1); print ''; - $facturefournstatic->id=$obj->fk_invoice_supplier_source; - $facturefournstatic->ref=$obj->ref; - $facturefournstatic->type=$obj->type; + $facturefournstatic->id = $obj->fk_invoice_supplier_source; + $facturefournstatic->ref = $obj->ref; + $facturefournstatic->type = $obj->type; print preg_replace('/\(EXCESS PAID\)/', $langs->trans("ExcessPaid"), $obj->description).' '.$facturefournstatic->getNomURl(1); print ''.$langs->trans("NotConsumed").''.price($obj->amount_ht).''.price($obj->multicurrency_amount_ht).''.vatrate($obj->tva_tx, true).''.price($obj->amount_ttc).''.price($obj->multicurrency_amount_ttc).''; - print 'rowid.($backtopage?'&backtopage='.urlencode($backtopage):'').'">'.img_split($langs->trans("SplitDiscount")).''; + print 'rowid.($backtopage ? '&backtopage='.urlencode($backtopage) : '').'">'.img_split($langs->trans("SplitDiscount")).''; //print '   '; - print 'rowid.($backtopage?'&backtopage='.urlencode($backtopage):'').'">'.img_delete($langs->trans("RemoveDiscount")).''; + print 'rowid.($backtopage ? '&backtopage='.urlencode($backtopage) : '').'">'.img_delete($langs->trans("RemoveDiscount")).''; print ' 
'; + print '
'; print ''; - print ''; // Need 120+ for format with AM/PM + print ''; // Need 120+ for format with AM/PM print ''; print ''; print ''; - if (! empty($conf->multicurrency->enabled)) + if (!empty($conf->multicurrency->enabled)) { print ''; } print ''; print ''; - if (! empty($conf->multicurrency->enabled)) + if (!empty($conf->multicurrency->enabled)) { print ''; } @@ -796,26 +796,26 @@ if ($socid > 0) print ''; print ''; - $tab_sqlobj=array(); - $tab_sqlobjOrder=array(); + $tab_sqlobj = array(); + $tab_sqlobjOrder = array(); $num = $db->num_rows($resql); if ($num > 0) { - for ($i = 0;$i < $num; $i++) + for ($i = 0; $i < $num; $i++) { $sqlobj = $db->fetch_object($resql); $tab_sqlobj[] = $sqlobj; - $tab_sqlobjOrder[]=$db->jdate($sqlobj->dc); + $tab_sqlobjOrder[] = $db->jdate($sqlobj->dc); } } $db->free($resql); $num = $db->num_rows($resql2); - for ($i = 0;$i < $num;$i++) + for ($i = 0; $i < $num; $i++) { $sqlobj = $db->fetch_object($resql2); $tab_sqlobj[] = $sqlobj; - $tab_sqlobjOrder[]= $db->jdate($sqlobj->dc); + $tab_sqlobjOrder[] = $db->jdate($sqlobj->dc); } $db->free($resql2); array_multisort($tab_sqlobjOrder, SORT_DESC, $tab_sqlobj); @@ -823,8 +823,8 @@ if ($socid > 0) $num = count($tab_sqlobj); if ($num > 0) { - $i = 0 ; - while ($i < $num ) + $i = 0; + while ($i < $num) { $obj = array_shift($tab_sqlobj); print ''; @@ -832,27 +832,27 @@ if ($socid > 0) if (preg_match('/\(CREDIT_NOTE\)/', $obj->description)) { print ''; } elseif (preg_match('/\(DEPOSIT\)/', $obj->description)) { print ''; } elseif (preg_match('/\(EXCESS RECEIVED\)/', $obj->description)) { print ''; } @@ -864,13 +864,13 @@ if ($socid > 0) } print ''; print ''; - if (! empty($conf->multicurrency->enabled)) + if (!empty($conf->multicurrency->enabled)) { print ''; } print ''; print ''; - if (! empty($conf->multicurrency->enabled)) + if (!empty($conf->multicurrency->enabled)) { print ''; } @@ -896,8 +896,8 @@ if ($socid > 0) } } - if($isSupplier) { - if($isCustomer) { + if ($isSupplier) { + if ($isCustomer) { print ''; // class="fichehalfleft" print '
'; print '
'; @@ -906,59 +906,59 @@ if ($socid > 0) // Discount linked to invoice lines $sql = "SELECT rc.rowid, rc.amount_ht, rc.amount_tva, rc.amount_ttc, rc.tva_tx, rc.multicurrency_amount_ht, rc.multicurrency_amount_tva, rc.multicurrency_amount_ttc,"; - $sql.= " rc.datec as dc, rc.description, rc.fk_invoice_supplier_line, rc.fk_invoice_supplier,"; - $sql.= " rc.fk_invoice_supplier_source,"; - $sql.= " u.login, u.rowid as user_id,"; - $sql.= " f.rowid, f.ref as ref,"; - $sql.= " fa.ref, fa.type as type"; - $sql.= " FROM ".MAIN_DB_PREFIX."facture_fourn as f"; - $sql.= " , ".MAIN_DB_PREFIX."user as u"; - $sql.= " , ".MAIN_DB_PREFIX."facture_fourn_det as fc"; - $sql.= " , ".MAIN_DB_PREFIX."societe_remise_except as rc"; - $sql.= " LEFT JOIN ".MAIN_DB_PREFIX."facture_fourn as fa ON rc.fk_invoice_supplier_source = fa.rowid"; - $sql.= " WHERE rc.fk_soc =". $object->id; - $sql.= " AND rc.fk_invoice_supplier_line = fc.rowid"; - $sql.= " AND fc.fk_facture_fourn = f.rowid"; - $sql.= " AND rc.fk_user = u.rowid"; - $sql.= " AND rc.discount_type = 1"; // Eliminate customer discounts - $sql.= " ORDER BY dc DESC"; + $sql .= " rc.datec as dc, rc.description, rc.fk_invoice_supplier_line, rc.fk_invoice_supplier,"; + $sql .= " rc.fk_invoice_supplier_source,"; + $sql .= " u.login, u.rowid as user_id,"; + $sql .= " f.rowid, f.ref as ref,"; + $sql .= " fa.ref, fa.type as type"; + $sql .= " FROM ".MAIN_DB_PREFIX."facture_fourn as f"; + $sql .= " , ".MAIN_DB_PREFIX."user as u"; + $sql .= " , ".MAIN_DB_PREFIX."facture_fourn_det as fc"; + $sql .= " , ".MAIN_DB_PREFIX."societe_remise_except as rc"; + $sql .= " LEFT JOIN ".MAIN_DB_PREFIX."facture_fourn as fa ON rc.fk_invoice_supplier_source = fa.rowid"; + $sql .= " WHERE rc.fk_soc =".$object->id; + $sql .= " AND rc.fk_invoice_supplier_line = fc.rowid"; + $sql .= " AND fc.fk_facture_fourn = f.rowid"; + $sql .= " AND rc.fk_user = u.rowid"; + $sql .= " AND rc.discount_type = 1"; // Eliminate customer discounts + $sql .= " ORDER BY dc DESC"; //$sql.= " UNION "; // Remises liees a factures $sql2 = "SELECT rc.rowid, rc.amount_ht, rc.amount_tva, rc.amount_ttc, rc.tva_tx,"; - $sql2.= " rc.datec as dc, rc.description, rc.fk_invoice_supplier_line, rc.fk_invoice_supplier,"; - $sql2.= " rc.fk_invoice_supplier_source,"; - $sql2.= " u.login, u.rowid as user_id,"; - $sql2.= " f.rowid, f.ref as ref,"; - $sql2.= " fa.ref, fa.type as type"; - $sql2.= " FROM ".MAIN_DB_PREFIX."facture_fourn as f"; - $sql2.= " , ".MAIN_DB_PREFIX."user as u"; - $sql2.= " , ".MAIN_DB_PREFIX."societe_remise_except as rc"; - $sql2.= " LEFT JOIN ".MAIN_DB_PREFIX."facture_fourn as fa ON rc.fk_invoice_supplier_source = fa.rowid"; - $sql2.= " WHERE rc.fk_soc =". $object->id; - $sql2.= " AND rc.fk_invoice_supplier = f.rowid"; - $sql2.= " AND rc.fk_user = u.rowid"; - $sql2.= " AND rc.discount_type = 1"; // Eliminate customer discounts - $sql2.= " ORDER BY dc DESC"; + $sql2 .= " rc.datec as dc, rc.description, rc.fk_invoice_supplier_line, rc.fk_invoice_supplier,"; + $sql2 .= " rc.fk_invoice_supplier_source,"; + $sql2 .= " u.login, u.rowid as user_id,"; + $sql2 .= " f.rowid, f.ref as ref,"; + $sql2 .= " fa.ref, fa.type as type"; + $sql2 .= " FROM ".MAIN_DB_PREFIX."facture_fourn as f"; + $sql2 .= " , ".MAIN_DB_PREFIX."user as u"; + $sql2 .= " , ".MAIN_DB_PREFIX."societe_remise_except as rc"; + $sql2 .= " LEFT JOIN ".MAIN_DB_PREFIX."facture_fourn as fa ON rc.fk_invoice_supplier_source = fa.rowid"; + $sql2 .= " WHERE rc.fk_soc =".$object->id; + $sql2 .= " AND rc.fk_invoice_supplier = f.rowid"; + $sql2 .= " AND rc.fk_user = u.rowid"; + $sql2 .= " AND rc.discount_type = 1"; // Eliminate customer discounts + $sql2 .= " ORDER BY dc DESC"; - $resql=$db->query($sql); - $resql2=null; - if ($resql) $resql2=$db->query($sql2); + $resql = $db->query($sql); + $resql2 = null; + if ($resql) $resql2 = $db->query($sql2); if ($resql2) { print '
'; - print '
'.$langs->trans("Date").''.$langs->trans("Date").''.$langs->trans("ReasonDiscount").''.$langs->trans("ConsumedBy").''.$langs->trans("AmountHT").''.$langs->trans("MulticurrencyAmountHT").''.$langs->trans("VATRate").''.$langs->trans("AmountTTC").''.$langs->trans("MulticurrencyAmountTTC").' 
'; - $facturestatic->id=$obj->fk_facture_source; - $facturestatic->ref=$obj->ref; - $facturestatic->type=$obj->type; + $facturestatic->id = $obj->fk_facture_source; + $facturestatic->ref = $obj->ref; + $facturestatic->type = $obj->type; print preg_replace('/\(CREDIT_NOTE\)/', $langs->trans("CreditNote"), $obj->description).' '.$facturestatic->getNomURl(1); print ''; - $facturestatic->id=$obj->fk_facture_source; - $facturestatic->ref=$obj->ref; - $facturestatic->type=$obj->type; + $facturestatic->id = $obj->fk_facture_source; + $facturestatic->ref = $obj->ref; + $facturestatic->type = $obj->type; print preg_replace('/\(DEPOSIT\)/', $langs->trans("InvoiceDeposit"), $obj->description).' '.$facturestatic->getNomURl(1); print ''; - $facturestatic->id=$obj->fk_facture_source; - $facturestatic->ref=$obj->ref; - $facturestatic->type=$obj->type; + $facturestatic->id = $obj->fk_facture_source; + $facturestatic->ref = $obj->ref; + $facturestatic->type = $obj->type; print preg_replace('/\(EXCESS RECEIVED\)/', $langs->trans("Invoice"), $obj->description).' '.$facturestatic->getNomURl(1); print ''.img_object($langs->trans("ShowBill"), 'bill').' '.$obj->ref.''.price($obj->amount_ht).''.price($obj->multicurrency_amount_ht).''.vatrate($obj->tva_tx, true).''.price($obj->amount_ttc).''.price($obj->multicurrency_amount_ttc).'
'; + print '
'; print ''; - print ''; // Need 120+ for format with AM/PM + print ''; // Need 120+ for format with AM/PM print ''; print ''; print ''; - if (! empty($conf->multicurrency->enabled)) + if (!empty($conf->multicurrency->enabled)) { print ''; } print ''; print ''; - if (! empty($conf->multicurrency->enabled)) + if (!empty($conf->multicurrency->enabled)) { print ''; } @@ -966,26 +966,26 @@ if ($socid > 0) print ''; print ''; - $tab_sqlobj=array(); - $tab_sqlobjOrder=array(); + $tab_sqlobj = array(); + $tab_sqlobjOrder = array(); $num = $db->num_rows($resql); if ($num > 0) { - for ($i = 0;$i < $num; $i++) + for ($i = 0; $i < $num; $i++) { $sqlobj = $db->fetch_object($resql); $tab_sqlobj[] = $sqlobj; - $tab_sqlobjOrder[]=$db->jdate($sqlobj->dc); + $tab_sqlobjOrder[] = $db->jdate($sqlobj->dc); } } $db->free($resql); $num = $db->num_rows($resql2); - for ($i = 0;$i < $num;$i++) + for ($i = 0; $i < $num; $i++) { $sqlobj = $db->fetch_object($resql2); $tab_sqlobj[] = $sqlobj; - $tab_sqlobjOrder[]= $db->jdate($sqlobj->dc); + $tab_sqlobjOrder[] = $db->jdate($sqlobj->dc); } $db->free($resql2); array_multisort($tab_sqlobjOrder, SORT_DESC, $tab_sqlobj); @@ -993,8 +993,8 @@ if ($socid > 0) $num = count($tab_sqlobj); if ($num > 0) { - $i = 0 ; - while ($i < $num ) + $i = 0; + while ($i < $num) { $obj = array_shift($tab_sqlobj); print ''; @@ -1002,27 +1002,27 @@ if ($socid > 0) if (preg_match('/\(CREDIT_NOTE\)/', $obj->description)) { print ''; } elseif (preg_match('/\(DEPOSIT\)/', $obj->description)) { print ''; } elseif (preg_match('/\(EXCESS PAID\)/', $obj->description)) { print ''; } @@ -1034,13 +1034,13 @@ if ($socid > 0) } print ''; print ''; - if (! empty($conf->multicurrency->enabled)) + if (!empty($conf->multicurrency->enabled)) { print ''; } print ''; print ''; - if (! empty($conf->multicurrency->enabled)) + if (!empty($conf->multicurrency->enabled)) { print ''; } @@ -1065,7 +1065,7 @@ if ($socid > 0) dol_print_error($db); } - if($isCustomer) { + if ($isCustomer) { print ''; // class="ficheaddleft" print ''; // class="fichehalfright" print ''; // class="fichecenter" diff --git a/htdocs/commande/card.php b/htdocs/commande/card.php index 57dbbabcf1d..803d699077f 100644 --- a/htdocs/commande/card.php +++ b/htdocs/commande/card.php @@ -35,34 +35,34 @@ */ require '../main.inc.php'; -require_once DOL_DOCUMENT_ROOT . '/core/class/html.formfile.class.php'; -require_once DOL_DOCUMENT_ROOT . '/core/class/html.formorder.class.php'; -require_once DOL_DOCUMENT_ROOT . '/core/class/html.formmargin.class.php'; -require_once DOL_DOCUMENT_ROOT . '/core/modules/commande/modules_commande.php'; -require_once DOL_DOCUMENT_ROOT . '/commande/class/commande.class.php'; -require_once DOL_DOCUMENT_ROOT . '/comm/action/class/actioncomm.class.php'; -require_once DOL_DOCUMENT_ROOT . '/core/lib/order.lib.php'; -require_once DOL_DOCUMENT_ROOT . '/core/lib/functions2.lib.php'; -require_once DOL_DOCUMENT_ROOT . '/core/class/extrafields.class.php'; -if (! empty($conf->propal->enabled)) { - require_once DOL_DOCUMENT_ROOT . '/comm/propal/class/propal.class.php'; +require_once DOL_DOCUMENT_ROOT.'/core/class/html.formfile.class.php'; +require_once DOL_DOCUMENT_ROOT.'/core/class/html.formorder.class.php'; +require_once DOL_DOCUMENT_ROOT.'/core/class/html.formmargin.class.php'; +require_once DOL_DOCUMENT_ROOT.'/core/modules/commande/modules_commande.php'; +require_once DOL_DOCUMENT_ROOT.'/commande/class/commande.class.php'; +require_once DOL_DOCUMENT_ROOT.'/comm/action/class/actioncomm.class.php'; +require_once DOL_DOCUMENT_ROOT.'/core/lib/order.lib.php'; +require_once DOL_DOCUMENT_ROOT.'/core/lib/functions2.lib.php'; +require_once DOL_DOCUMENT_ROOT.'/core/class/extrafields.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'; +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'; } -require_once DOL_DOCUMENT_ROOT . '/core/class/doleditor.class.php'; +require_once DOL_DOCUMENT_ROOT.'/core/class/doleditor.class.php'; if (!empty($conf->variants->enabled)) { require_once DOL_DOCUMENT_ROOT.'/variants/class/ProductCombination.class.php'; } // Load translation files required by the page -$langs->loadLangs(array('orders','sendings','companies','bills','propal','deliveries','products','other')); +$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->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'); @@ -77,12 +77,12 @@ $origin = GETPOST('origin', 'alpha'); $originid = (GETPOST('originid', 'int') ? GETPOST('originid', 'int') : GETPOST('origin_id', 'int')); // For backward compatibility // PDF -$hidedetails = (GETPOST('hidedetails', 'int') ? GETPOST('hidedetails', 'int') : (! empty($conf->global->MAIN_GENERATE_DOCUMENTS_HIDE_DETAILS) ? 1 : 0)); -$hidedesc = (GETPOST('hidedesc', 'int') ? GETPOST('hidedesc', 'int') : (! empty($conf->global->MAIN_GENERATE_DOCUMENTS_HIDE_DESC) ? 1 : 0)); -$hideref = (GETPOST('hideref', 'int') ? GETPOST('hideref', 'int') : (! empty($conf->global->MAIN_GENERATE_DOCUMENTS_HIDE_REF) ? 1 : 0)); +$hidedetails = (GETPOST('hidedetails', 'int') ? GETPOST('hidedetails', 'int') : (!empty($conf->global->MAIN_GENERATE_DOCUMENTS_HIDE_DETAILS) ? 1 : 0)); +$hidedesc = (GETPOST('hidedesc', 'int') ? GETPOST('hidedesc', 'int') : (!empty($conf->global->MAIN_GENERATE_DOCUMENTS_HIDE_DESC) ? 1 : 0)); +$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); @@ -126,24 +126,24 @@ if (empty($reshook)) { if ($cancel) { - if (! empty($backtopage)) + if (!empty($backtopage)) { header("Location: ".$backtopage); exit; } - $action=''; + $action = ''; } - include DOL_DOCUMENT_ROOT.'/core/actions_setnotes.inc.php'; // Must be include, not include_once + include DOL_DOCUMENT_ROOT.'/core/actions_setnotes.inc.php'; // Must be include, not include_once - include DOL_DOCUMENT_ROOT.'/core/actions_dellink.inc.php'; // Must be include, not include_once + include DOL_DOCUMENT_ROOT.'/core/actions_dellink.inc.php'; // Must be include, not include_once - include DOL_DOCUMENT_ROOT.'/core/actions_lineupdown.inc.php'; // Must be include, not include_once + 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 (1 == 0 && !GETPOST('clone_content') && !GETPOST('clone_receivers')) { setEventMessages($langs->trans("NoCloneOptionsSpecified"), null, 'errors'); } @@ -154,7 +154,7 @@ if (empty($reshook)) // Because createFromClone modifies the object, we must clone it so that we can restore it later $orig = clone $object; - $result=$object->createFromClone($user, $socid); + $result = $object->createFromClone($user, $socid); if ($result > 0) { header("Location: ".$_SERVER['PHP_SELF'].'?id='.$result); @@ -164,7 +164,7 @@ if (empty($reshook)) { setEventMessages($object->error, $object->errors, 'errors'); $object = $orig; - $action=''; + $action = ''; } } } @@ -215,7 +215,7 @@ if (empty($reshook)) $newlang = GETPOST('lang_id', 'aZ09'); 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); } @@ -258,7 +258,7 @@ if (empty($reshook)) $error++; } - if (! $error) { + if (!$error) { $object->socid = $socid; $object->fetch_thirdparty(); @@ -286,14 +286,14 @@ 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 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; @@ -320,22 +320,22 @@ if (empty($reshook)) // Possibility to add external linked objects with hooks $object->linked_objects [$object->origin] = $object->origin_id; $other_linked_objects = GETPOST('other_linked_objects', 'array'); - if (! empty($other_linked_objects)) { + if (!empty($other_linked_objects)) { $object->linked_objects = array_merge($object->linked_objects, $other_linked_objects); } - if (! $error) + if (!$error) { $object_id = $object->create($user); if ($object_id > 0) { - dol_include_once('/' . $element . '/class/' . $subelement . '.class.php'); + dol_include_once('/'.$element.'/class/'.$subelement.'.class.php'); $classname = ucfirst($subelement); $srcobject = new $classname($db); - dol_syslog("Try to find source object origin=" . $object->origin . " originid=" . $object->origin_id . " to add lines"); + 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) { @@ -349,13 +349,13 @@ if (empty($reshook)) $fk_parent_line = 0; $num = count($lines); - for($i = 0; $i < $num; $i ++) + for ($i = 0; $i < $num; $i++) { - if(!in_array($lines[$i]->id, $selectedLines)) continue; // Skip unselected lines + 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 : ''); - $product_type = (! empty($lines[$i]->product_type) ? $lines[$i]->product_type : 0); + $label = (!empty($lines[$i]->label) ? $lines[$i]->label : ''); + $desc = (!empty($lines[$i]->desc) ? $lines[$i]->desc : ''); + $product_type = (!empty($lines[$i]->product_type) ? $lines[$i]->product_type : 0); // Dates // TODO mutualiser @@ -383,7 +383,7 @@ if (empty($reshook)) } $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, @@ -449,17 +449,17 @@ if (empty($reshook)) $action = 'create'; } } else { - if (! $error) + if (!$error) { $object_id = $object->create($user); // If some invoice's lines already known $NBLINES = 8; - for($i = 1; $i <= $NBLINES; $i ++) { - if ($_POST['idprod' . $i]) { - $xid = 'idprod' . $i; - $xqty = 'qty' . $i; - $xremise = 'remise_percent' . $i; + for ($i = 1; $i <= $NBLINES; $i++) { + if ($_POST['idprod'.$i]) { + $xid = 'idprod'.$i; + $xqty = 'qty'.$i; + $xremise = 'remise_percent'.$i; $object->add_product($_POST[$xid], $_POST[$xqty], $_POST[$xremise]); } } @@ -483,10 +483,10 @@ 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); + header('Location: '.$_SERVER["PHP_SELF"].'?id='.$object_id); exit(); } else { $db->rollback(); @@ -498,7 +498,7 @@ if (empty($reshook)) elseif ($action == 'classifybilled' && $usercancreate) { - $ret=$object->classifyBilled($user); + $ret = $object->classifyBilled($user); if ($ret < 0) { setEventMessages($object->error, $object->errors, 'errors'); @@ -506,7 +506,7 @@ if (empty($reshook)) } elseif ($action == 'classifyunbilled' && $usercancreate) { - $ret=$object->classifyUnBilled(); + $ret = $object->classifyUnBilled(); if ($ret < 0) { setEventMessages($object->error, $object->errors, 'errors'); } @@ -598,7 +598,7 @@ if (empty($reshook)) $newlang = GETPOST('lang_id', 'alpha'); 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); } @@ -620,7 +620,7 @@ if (empty($reshook)) // bank account elseif ($action == 'setbankaccount' && $usercancreate) { - $result=$object->setBankAccount(GETPOST('fk_account', 'int')); + $result = $object->setBankAccount(GETPOST('fk_account', 'int')); if ($result < 0) { setEventMessages($object->error, $object->errors, 'errors'); } @@ -657,23 +657,23 @@ if (empty($reshook)) $error = 0; // Set if we used free entry or predefined product - $predef=''; - $product_desc=(GETPOST('dp_desc')?GETPOST('dp_desc'):''); + $predef = ''; + $product_desc = (GETPOST('dp_desc') ?GETPOST('dp_desc') : ''); $price_ht = GETPOST('price_ht'); $price_ht_devise = GETPOST('multicurrency_price_ht'); $prod_entry_mode = GETPOST('prod_entry_mode'); if ($prod_entry_mode == 'free') { - $idprod=0; + $idprod = 0; $tva_tx = (GETPOST('tva_tx') ? GETPOST('tva_tx') : 0); } else { - $idprod=GETPOST('idprod', 'int'); + $idprod = GETPOST('idprod', 'int'); $tva_tx = ''; } - $qty = GETPOST('qty' . $predef); + $qty = GETPOST('qty'.$predef); $remise_percent = (GETPOST('remise_percent'.$predef) != '' ? GETPOST('remise_percent'.$predef) : 0); // Extrafields @@ -683,7 +683,7 @@ if (empty($reshook)) if (is_array($extralabelsline)) { // Get extra fields foreach ($extralabelsline as $key => $value) { - unset($_POST["options_" . $key]); + unset($_POST["options_".$key]); } } @@ -720,22 +720,22 @@ if (empty($reshook)) else { setEventMessages($langs->trans('ErrorProductCombinationNotFound'), null, 'errors'); - $error ++; + $error++; } } } - if (! $error && ($qty >= 0) && (! empty($product_desc) || ! empty($idprod))) { + if (!$error && ($qty >= 0) && (!empty($product_desc) || !empty($idprod))) { // 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')); - $price_base_type = (GETPOST('price_base_type', 'alpha')?GETPOST('price_base_type', 'alpha'):'HT'); + $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')); + $price_base_type = (GETPOST('price_base_type', 'alpha') ?GETPOST('price_base_type', 'alpha') : 'HT'); // Ecrase $pu par celui du produit // Ecrase $desc par celui du produit // Ecrase $tva_tx par celui du produit // Ecrase $base_price_type par celui du produit - if (! empty($idprod)) { + if (!empty($idprod)) { $prod = new Product($db); $prod->fetch($idprod); @@ -744,7 +744,7 @@ 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; @@ -752,26 +752,26 @@ 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 (!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 (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)) { - require_once DOL_DOCUMENT_ROOT . '/product/class/productcustomerprice.class.php'; + require_once DOL_DOCUMENT_ROOT.'/product/class/productcustomerprice.class.php'; $prodcustprice = new Productcustomerprice($db); - $filter = array('t.fk_product' => $prod->id,'t.fk_soc' => $object->thirdparty->id); + $filter = array('t.fk_product' => $prod->id, 't.fk_soc' => $object->thirdparty->id); $result = $prodcustprice->fetch_all('', '', 0, 0, $filter); if ($result >= 0) @@ -782,9 +782,9 @@ 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; } } else @@ -793,7 +793,7 @@ if (empty($reshook)) } } // If price per quantity - elseif (! empty($conf->global->PRODUIT_CUSTOMER_PRICES_BY_QTY)) + elseif (!empty($conf->global->PRODUIT_CUSTOMER_PRICES_BY_QTY)) { if ($prod->prices_by_qty[0]) // yes, this product has some prices per quantity { @@ -801,7 +801,7 @@ if (empty($reshook)) $pqp = GETPOST('pbq', 'int'); // Search price into product_price_by_qty from $prod->id - foreach($prod->prices_by_qty_list[0] as $priceforthequantityarray) + foreach ($prod->prices_by_qty_list[0] as $priceforthequantityarray) { if ($priceforthequantityarray['rowid'] != $pqp) continue; // We found the price @@ -819,14 +819,14 @@ if (empty($reshook)) } } // If price per quantity and customer - elseif (! empty($conf->global->PRODUIT_CUSTOMER_PRICES_BY_QTY_MULTIPRICES)) + 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 { // 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) + foreach ($prod->prices_by_qty_list[$object->thirdparty->price_level] as $priceforthequantityarray) { if ($priceforthequantityarray['rowid'] != $pqp) continue; // We found the price @@ -848,7 +848,7 @@ if (empty($reshook)) $tmpprodvat = price2num(preg_replace('/\s*\(.*\)/', '', $prod->tva_tx)); // if price ht is forced (ie: calculated by margin rate and cost price). TODO Why this ? - if (! empty($price_ht)) { + if (!empty($price_ht)) { $pu_ht = price2num($price_ht, 'MU'); $pu_ttc = price2num($pu_ht * (1 + ($tmpvat / 100)), 'MU'); } @@ -865,55 +865,55 @@ if (empty($reshook)) $desc = ''; // 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)) { $outputlangs = $langs; $newlang = ''; if (empty($newlang) && GETPOST('lang_id', 'aZ09')) $newlang = GETPOST('lang_id', 'aZ09'); if (empty($newlang)) $newlang = $object->thirdparty->default_lang; - if (! empty($newlang)) { + 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; } - if (!empty($product_desc) && !empty($conf->global->MAIN_NO_CONCAT_DESCRIPTION)) $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)); // Add custom code and origin country into description - if (empty($conf->global->MAIN_PRODUCT_DISABLE_CUSTOMCOUNTRYCODE) && (! empty($prod->customcode) || ! empty($prod->country_code))) { + if (empty($conf->global->MAIN_PRODUCT_DISABLE_CUSTOMCOUNTRYCODE) && (!empty($prod->customcode) || !empty($prod->country_code))) { $tmptxt = '('; // 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)) { $outputlangs = $langs; $newlang = ''; if (empty($newlang) && GETPOST('lang_id', 'alpha')) $newlang = GETPOST('lang_id', 'alpha'); if (empty($newlang)) $newlang = $object->thirdparty->default_lang; - if (! empty($newlang)) { + if (!empty($newlang)) { $outputlangs = new Translate("", $conf); $outputlangs->setDefaultLang($newlang); $outputlangs->load('products'); } - if (! empty($prod->customcode)) - $tmptxt .= $outputlangs->transnoentitiesnoconv("CustomCode") . ': ' . $prod->customcode; - if (! empty($prod->customcode) && ! empty($prod->country_code)) + if (!empty($prod->customcode)) + $tmptxt .= $outputlangs->transnoentitiesnoconv("CustomCode").': '.$prod->customcode; + if (!empty($prod->customcode) && !empty($prod->country_code)) $tmptxt .= ' - '; - if (! empty($prod->country_code)) - $tmptxt .= $outputlangs->transnoentitiesnoconv("CountryOrigin") . ': ' . getCountry($prod->country_code, 0, $db, $outputlangs, 0); + if (!empty($prod->country_code)) + $tmptxt .= $outputlangs->transnoentitiesnoconv("CountryOrigin").': '.getCountry($prod->country_code, 0, $db, $outputlangs, 0); } else { - if (! empty($prod->customcode)) - $tmptxt .= $langs->transnoentitiesnoconv("CustomCode") . ': ' . $prod->customcode; - if (! empty($prod->customcode) && ! empty($prod->country_code)) + if (!empty($prod->customcode)) + $tmptxt .= $langs->transnoentitiesnoconv("CustomCode").': '.$prod->customcode; + if (!empty($prod->customcode) && !empty($prod->country_code)) $tmptxt .= ' - '; - if (! empty($prod->country_code)) - $tmptxt .= $langs->transnoentitiesnoconv("CountryOrigin") . ': ' . getCountry($prod->country_code, 0, $db, $langs, 0); + if (!empty($prod->country_code)) + $tmptxt .= $langs->transnoentitiesnoconv("CountryOrigin").': '.getCountry($prod->country_code, 0, $db, $langs, 0); } $tmptxt .= ')'; $desc = dol_concatdesc($desc, $tmptxt); @@ -929,13 +929,13 @@ if (empty($reshook)) $label = (GETPOST('product_label') ? GETPOST('product_label') : ''); $desc = $product_desc; $type = GETPOST('type'); - $fk_unit=GETPOST('units', 'alpha'); + $fk_unit = GETPOST('units', 'alpha'); $pu_ht_devise = price2num($price_ht_devise, 'MU'); } // Margin - $fournprice = price2num(GETPOST('fournprice' . $predef) ? GETPOST('fournprice' . $predef) : ''); - $buyingprice = price2num(GETPOST('buying_price' . $predef) != '' ? GETPOST('buying_price' . $predef) : ''); // If buying_price is '0', we muste keep this value + $fournprice = price2num(GETPOST('fournprice'.$predef) ? GETPOST('fournprice'.$predef) : ''); + $buyingprice = price2num(GETPOST('buying_price'.$predef) != '' ? GETPOST('buying_price'.$predef) : ''); // If buying_price is '0', we muste keep this value // Local Taxes $localtax1_tx = get_localtax($tva_tx, 1, $object->thirdparty); @@ -947,7 +947,7 @@ if (empty($reshook)) 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)))) { + 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)); setEventMessages($mesg, null, 'errors'); } else { @@ -961,9 +961,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)) { + if (!empty($newlang)) { $outputlangs = new Translate("", $conf); $outputlangs->setDefaultLang($newlang); } @@ -1016,13 +1016,13 @@ if (empty($reshook)) elseif ($action == 'updateline' && $usercancreate && GETPOST('save')) { // Clean parameters - $date_start=''; - $date_end=''; - $date_start=dol_mktime(GETPOST('date_starthour'), GETPOST('date_startmin'), GETPOST('date_startsec'), GETPOST('date_startmonth'), GETPOST('date_startday'), GETPOST('date_startyear')); - $date_end=dol_mktime(GETPOST('date_endhour'), GETPOST('date_endmin'), GETPOST('date_endsec'), GETPOST('date_endmonth'), GETPOST('date_endday'), GETPOST('date_endyear')); - $description=dol_htmlcleanlastbr(GETPOST('product_desc', 'none')); - $pu_ht=GETPOST('price_ht'); - $vat_rate=(GETPOST('tva_tx')?GETPOST('tva_tx'):0); + $date_start = ''; + $date_end = ''; + $date_start = dol_mktime(GETPOST('date_starthour'), GETPOST('date_startmin'), GETPOST('date_startsec'), GETPOST('date_startmonth'), GETPOST('date_startday'), GETPOST('date_startyear')); + $date_end = dol_mktime(GETPOST('date_endhour'), GETPOST('date_endmin'), GETPOST('date_endsec'), GETPOST('date_endmonth'), GETPOST('date_endday'), GETPOST('date_endyear')); + $description = dol_htmlcleanlastbr(GETPOST('product_desc', 'none')); + $pu_ht = GETPOST('price_ht'); + $vat_rate = (GETPOST('tva_tx') ?GETPOST('tva_tx') : 0); $pu_ht_devise = GETPOST('multicurrency_subprice'); // Define info_bits @@ -1037,7 +1037,7 @@ if (empty($reshook)) // Add buying price $fournprice = price2num(GETPOST('fournprice') ? GETPOST('fournprice') : ''); - $buyingprice = price2num(GETPOST('buying_price') != '' ? GETPOST('buying_price') : ''); // If buying_price is '0', we muste keep this value + $buyingprice = price2num(GETPOST('buying_price') != '' ? GETPOST('buying_price') : ''); // If buying_price is '0', we muste keep this value // Extrafields Lines $extralabelsline = $extrafields->fetch_name_optionals_label($object->table_element_line); @@ -1045,29 +1045,29 @@ if (empty($reshook)) // Unset extrafield POST Data if (is_array($extralabelsline)) { foreach ($extralabelsline as $key => $value) { - unset($_POST["options_" . $key]); + unset($_POST["options_".$key]); } } // Define special_code for special lines - $special_code=GETPOST('special_code'); - if (! GETPOST('qty')) $special_code=3; + $special_code = GETPOST('special_code'); + if (!GETPOST('qty')) $special_code = 3; // Check minimum price $productid = GETPOST('productid', 'int'); - if (! empty($productid)) { + if (!empty($productid)) { $product = new Product($db); $product->fetch($productid); $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') : ''); - 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(GETPOST('remise_percent')) / 100) < price2num($price_min)))) { + 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(GETPOST('remise_percent')) / 100) < price2num($price_min)))) { setEventMessages($langs->trans("CantBeLessThanMinPrice", price(price2num($price_min, 'MU'), 0, $langs, 0, 0, - 1, $conf->currency)), null, 'errors'); $error++; } @@ -1082,7 +1082,7 @@ if (empty($reshook)) } } - if (! $error) { + if (!$error) { if (empty($user->rights->margins->creer)) { foreach ($object->lines as &$line) @@ -1106,7 +1106,7 @@ if (empty($reshook)) $newlang = GETPOST('lang_id', 'aZ09'); 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); } @@ -1146,7 +1146,7 @@ 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 + header('Location: '.$_SERVER['PHP_SELF'].'?id='.$object->id); // Pour reaffichage de la fiche en cours d'edition exit(); } @@ -1154,28 +1154,28 @@ if (empty($reshook)) { $idwarehouse = GETPOST('idwarehouse'); - $qualified_for_stock_change=0; + $qualified_for_stock_change = 0; if (empty($conf->global->STOCK_SUPPORTS_SERVICES)) { - $qualified_for_stock_change=$object->hasProductsOrServices(2); + $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 (!empty($conf->stock->enabled) && !empty($conf->global->STOCK_CALCULATE_ON_VALIDATE_ORDER) && $qualified_for_stock_change) { - if (! $idwarehouse || $idwarehouse == -1) + if (!$idwarehouse || $idwarehouse == -1) { $error++; setEventMessages($langs->trans('ErrorFieldRequired', $langs->transnoentitiesnoconv("Warehouse")), null, 'errors'); - $action=''; + $action = ''; } } - if (! $error) { + if (!$error) { $result = $object->valid($user, $idwarehouse); if ($result >= 0) { @@ -1186,11 +1186,11 @@ if (empty($reshook)) $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 (!empty($newlang)) { $outputlangs = new Translate("", $conf); $outputlangs->setDefaultLang($newlang); } - $model=$object->modelpdf; + $model = $object->modelpdf; $ret = $object->fetch($id); // Reload to get new records $object->generateDocument($model, $outputlangs, $hidedetails, $hidedesc, $hideref); @@ -1207,28 +1207,28 @@ if (empty($reshook)) elseif ($action == 'confirm_modif' && $usercancreate) { $idwarehouse = GETPOST('idwarehouse'); - $qualified_for_stock_change=0; + $qualified_for_stock_change = 0; if (empty($conf->global->STOCK_SUPPORTS_SERVICES)) { - $qualified_for_stock_change=$object->hasProductsOrServices(2); + $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 (!empty($conf->stock->enabled) && !empty($conf->global->STOCK_CALCULATE_ON_VALIDATE_ORDER) && $qualified_for_stock_change) { - if (! $idwarehouse || $idwarehouse == -1) + if (!$idwarehouse || $idwarehouse == -1) { $error++; setEventMessages($langs->trans('ErrorFieldRequired', $langs->transnoentitiesnoconv("Warehouse")), null, 'errors'); - $action=''; + $action = ''; } } - if (! $error) { + if (!$error) { $result = $object->setDraft($user, $idwarehouse); if ($result >= 0) { @@ -1239,11 +1239,11 @@ if (empty($reshook)) $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 (!empty($newlang)) { $outputlangs = new Translate("", $conf); $outputlangs->setDefaultLang($newlang); } - $model=$object->modelpdf; + $model = $object->modelpdf; $ret = $object->fetch($id); // Reload to get new records $object->generateDocument($model, $outputlangs, $hidedetails, $hidedesc, $hideref); @@ -1263,28 +1263,28 @@ if (empty($reshook)) { $idwarehouse = GETPOST('idwarehouse'); - $qualified_for_stock_change=0; + $qualified_for_stock_change = 0; if (empty($conf->global->STOCK_SUPPORTS_SERVICES)) { - $qualified_for_stock_change=$object->hasProductsOrServices(2); + $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 (!empty($conf->stock->enabled) && !empty($conf->global->STOCK_CALCULATE_ON_VALIDATE_ORDER) && $qualified_for_stock_change) { - if (! $idwarehouse || $idwarehouse == -1) + if (!$idwarehouse || $idwarehouse == -1) { $error++; setEventMessages($langs->trans('ErrorFieldRequired', $langs->transnoentitiesnoconv("Warehouse")), null, 'errors'); - $action=''; + $action = ''; } } - if (! $error) { + if (!$error) { $result = $object->cancel($idwarehouse); if ($result < 0) { @@ -1301,7 +1301,7 @@ if (empty($reshook)) $ret = $extrafields->setOptionalsFromPost(null, $object, GETPOST('attribute', 'none')); if ($ret < 0) $error++; - if (! $error) + if (!$error) { // Actions on extra fields $result = $object->insertExtraFields('ORDER_MODIFY'); @@ -1320,12 +1320,12 @@ if (empty($reshook)) $object->fetch($id); $object->setValueFrom('fk_soc', $socid, '', '', 'date', '', $user, 'ORDER_MODIFY'); - header('Location: ' . $_SERVER["PHP_SELF"] . '?id=' . $id); + header('Location: '.$_SERVER["PHP_SELF"].'?id='.$id); exit(); } // add lines from objectlinked - if($action == 'import_lines_from_object' + if ($action == 'import_lines_from_object' && $usercancreate && $object->statut == Commande::STATUS_DRAFT ) @@ -1334,14 +1334,14 @@ if (empty($reshook)) $fromElementid = GETPOST('fromelementid'); $importLines = GETPOST('line_checkbox'); - if(!empty($importLines) && is_array($importLines) && !empty($fromElement) && ctype_alpha($fromElement) && !empty($fromElementid)) + if (!empty($importLines) && is_array($importLines) && !empty($fromElement) && ctype_alpha($fromElement) && !empty($fromElementid)) { - if($fromElement == 'commande') + 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'; @@ -1349,11 +1349,11 @@ if (empty($reshook)) $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($lineId); $desc = $originLine->desc; @@ -1369,15 +1369,15 @@ if (empty($reshook)) $ventil = 0; $info_bits = $originLine->info_bits; $fk_remise_except = $originLine->fk_remise_except; - $price_base_type='HT'; - $pu_ttc=0; + $price_base_type = 'HT'; + $pu_ttc = 0; $type = $originLine->product_type; - $rang=$nextRang++; + $rang = $nextRang++; $special_code = $originLine->special_code; $origin = $originLine->element; $origin_id = $originLine->id; - $fk_parent_line=0; - $fk_fournprice=$originLine->fk_fournprice; + $fk_parent_line = 0; + $fk_fournprice = $originLine->fk_fournprice; $pa_ht = $originLine->pa_ht; $label = $originLine->label; $array_options = $originLine->array_options; @@ -1388,18 +1388,18 @@ if (empty($reshook)) $res = $object->addline($desc, $pu_ht, $qty, $txtva, $txlocaltax1, $txlocaltax2, $fk_product, $remise_percent, $info_bits, $fk_remise_except, $price_base_type, $pu_ttc, $date_start, $date_end, $type, $rang, $special_code, $fk_parent_line, $fk_fournprice, $pa_ht, $label, $array_options, $fk_unit, $origin, $origin_id, $pu_ht_devise); - if($res > 0){ + if ($res > 0) { $importCount++; - }else{ + } else { $error++; } } - else{ + else { $error++; } } - if($error) + if ($error) { setEventMessages($langs->trans('ErrorsOnXLines', $error), null, 'errors'); } @@ -1415,14 +1415,14 @@ if (empty($reshook)) include DOL_DOCUMENT_ROOT.'/core/actions_builddoc.inc.php'; // Actions to send emails - $trigger_name='ORDER_SENTBYMAIL'; - $paramname='id'; - $autocopy='MAIN_MAIL_AUTOCOPY_ORDER_TO'; // used to know the automatic BCC to add - $trackid='ord'.$object->id; + $trigger_name = 'ORDER_SENTBYMAIL'; + $paramname = 'id'; + $autocopy = 'MAIN_MAIL_AUTOCOPY_ORDER_TO'; // used to know the automatic BCC to add + $trackid = 'ord'.$object->id; include DOL_DOCUMENT_ROOT.'/core/actions_sendmails.inc.php'; - if (! $error && ! empty($conf->global->MAIN_DISABLE_CONTACTS_TAB) && $usercancreate) + if (!$error && !empty($conf->global->MAIN_DISABLE_CONTACTS_TAB) && $usercancreate) { if ($action == 'addcontact') { @@ -1432,7 +1432,7 @@ if (empty($reshook)) } if ($result >= 0) { - header("Location: " . $_SERVER['PHP_SELF'] . "?id=" . $object->id); + header("Location: ".$_SERVER['PHP_SELF']."?id=".$object->id); exit(); } else { if ($object->error == 'DB_ERROR_RECORD_ALREADY_EXISTS') { @@ -1460,7 +1460,7 @@ if (empty($reshook)) $result = $object->delete_contact($lineid); if ($result >= 0) { - header("Location: " . $_SERVER['PHP_SELF'] . "?id=" . $object->id); + header("Location: ".$_SERVER['PHP_SELF']."?id=".$object->id); exit(); } else { dol_print_error($db); @@ -1480,7 +1480,7 @@ $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) @@ -1495,7 +1495,7 @@ if ($action == 'create' && $usercancreate) $currency_code = $conf->currency; - 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)) { @@ -1517,7 +1517,7 @@ if ($action == 'create' && $usercancreate) } if (!$dateorder) { // Do not set 0 here (0 for a date is 1970) - $dateorder = (empty($dateinvoice)?(empty($conf->global->MAIN_AUTOFILL_DATE_ODER)?-1:''):$dateorder); + $dateorder = (empty($dateinvoice) ? (empty($conf->global->MAIN_AUTOFILL_DATE_ODER) ?-1 : '') : $dateorder); } } else { // For compatibility @@ -1532,7 +1532,7 @@ if ($action == 'create' && $usercancreate) $element = $subelement = 'contrat'; } - dol_include_once('/' . $element . '/class/' . $subelement . '.class.php'); + dol_include_once('/'.$element.'/class/'.$subelement.'.class.php'); $classname = ucfirst($subelement); $objectsrc = new $classname($db); @@ -1545,22 +1545,22 @@ if ($action == 'create' && $usercancreate) $objectsrc->fetch_optionals($originid); $object->array_options = $objectsrc->array_options; - $projectid = (! empty($objectsrc->fk_project) ? $objectsrc->fk_project : ''); - $ref_client = (! empty($objectsrc->ref_client) ? $objectsrc->ref_client : ''); + $projectid = (!empty($objectsrc->fk_project) ? $objectsrc->fk_project : ''); + $ref_client = (!empty($objectsrc->ref_client) ? $objectsrc->ref_client : ''); $soc = $objectsrc->thirdparty; - $cond_reglement_id = (!empty($objectsrc->cond_reglement_id)?$objectsrc->cond_reglement_id:(!empty($soc->cond_reglement_id)?$soc->cond_reglement_id:0)); // TODO maybe add default value option - $mode_reglement_id = (!empty($objectsrc->mode_reglement_id)?$objectsrc->mode_reglement_id:(!empty($soc->mode_reglement_id)?$soc->mode_reglement_id:0)); - $fk_account = (! empty($objectsrc->fk_account)?$objectsrc->fk_account:(! empty($soc->fk_account)?$soc->fk_account:0)); - $availability_id = (!empty($objectsrc->availability_id)?$objectsrc->availability_id:(!empty($soc->availability_id)?$soc->availability_id:0)); - $shipping_method_id = (! empty($objectsrc->shipping_method_id)?$objectsrc->shipping_method_id:(! empty($soc->shipping_method_id)?$soc->shipping_method_id:0)); - $warehouse_id = (! empty($objectsrc->warehouse_id)?$objectsrc->warehouse_id:(! empty($soc->warehouse_id)?$soc->warehouse_id:0)); - $demand_reason_id = (!empty($objectsrc->demand_reason_id)?$objectsrc->demand_reason_id:(!empty($soc->demand_reason_id)?$soc->demand_reason_id:0)); - $remise_percent = (!empty($objectsrc->remise_percent)?$objectsrc->remise_percent:(!empty($soc->remise_percent)?$soc->remise_percent:0)); - $remise_absolue = (!empty($objectsrc->remise_absolue)?$objectsrc->remise_absolue:(!empty($soc->remise_absolue)?$soc->remise_absolue:0)); - $dateorder = empty($conf->global->MAIN_AUTOFILL_DATE_ORDER)?-1:''; + $cond_reglement_id = (!empty($objectsrc->cond_reglement_id) ? $objectsrc->cond_reglement_id : (!empty($soc->cond_reglement_id) ? $soc->cond_reglement_id : 0)); // TODO maybe add default value option + $mode_reglement_id = (!empty($objectsrc->mode_reglement_id) ? $objectsrc->mode_reglement_id : (!empty($soc->mode_reglement_id) ? $soc->mode_reglement_id : 0)); + $fk_account = (!empty($objectsrc->fk_account) ? $objectsrc->fk_account : (!empty($soc->fk_account) ? $soc->fk_account : 0)); + $availability_id = (!empty($objectsrc->availability_id) ? $objectsrc->availability_id : (!empty($soc->availability_id) ? $soc->availability_id : 0)); + $shipping_method_id = (!empty($objectsrc->shipping_method_id) ? $objectsrc->shipping_method_id : (!empty($soc->shipping_method_id) ? $soc->shipping_method_id : 0)); + $warehouse_id = (!empty($objectsrc->warehouse_id) ? $objectsrc->warehouse_id : (!empty($soc->warehouse_id) ? $soc->warehouse_id : 0)); + $demand_reason_id = (!empty($objectsrc->demand_reason_id) ? $objectsrc->demand_reason_id : (!empty($soc->demand_reason_id) ? $soc->demand_reason_id : 0)); + $remise_percent = (!empty($objectsrc->remise_percent) ? $objectsrc->remise_percent : (!empty($soc->remise_percent) ? $soc->remise_percent : 0)); + $remise_absolue = (!empty($objectsrc->remise_absolue) ? $objectsrc->remise_absolue : (!empty($soc->remise_absolue) ? $soc->remise_absolue : 0)); + $dateorder = empty($conf->global->MAIN_AUTOFILL_DATE_ORDER) ?-1 : ''; - $datedelivery = (! empty($objectsrc->date_livraison) ? $objectsrc->date_livraison : ''); + $datedelivery = (!empty($objectsrc->date_livraison) ? $objectsrc->date_livraison : ''); if (!empty($conf->multicurrency->enabled)) { @@ -1568,11 +1568,11 @@ if ($action == 'create' && $usercancreate) 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)); - $note_public = $object->getDefaultCreateValueFor('note_public', (! empty($objectsrc->note_public) ? $objectsrc->note_public : null)); + $note_private = $object->getDefaultCreateValueFor('note_private', (!empty($objectsrc->note_private) ? $objectsrc->note_private : null)); + $note_public = $object->getDefaultCreateValueFor('note_public', (!empty($objectsrc->note_public) ? $objectsrc->note_public : null)); // Object source contacts list - $srccontactslist = $objectsrc->liste_contact(- 1, 'external', 1); + $srccontactslist = $objectsrc->liste_contact(-1, 'external', 1); } } else @@ -1586,7 +1586,7 @@ if ($action == 'create' && $usercancreate) $demand_reason_id = $soc->demand_reason_id; $remise_percent = $soc->remise_percent; $remise_absolue = 0; - $dateorder = empty($conf->global->MAIN_AUTOFILL_DATE_ORDER)?-1:''; + $dateorder = empty($conf->global->MAIN_AUTOFILL_DATE_ORDER) ?-1 : ''; if (!empty($conf->multicurrency->enabled) && !empty($soc->multicurrency_code)) $currency_code = $soc->multicurrency_code; @@ -1605,7 +1605,7 @@ if ($action == 'create' && $usercancreate) dol_fiche_head(''); - print '
'.$langs->trans("Date").''.$langs->trans("Date").''.$langs->trans("ReasonDiscount").''.$langs->trans("ConsumedBy").''.$langs->trans("AmountHT").''.$langs->trans("MulticurrencyAmountHT").''.$langs->trans("VATRate").''.$langs->trans("AmountTTC").''.$langs->trans("MulticurrencyAmountTTC").' 
'; - $facturefournstatic->id=$obj->fk_invoice_supplier_source; - $facturefournstatic->ref=$obj->ref; - $facturefournstatic->type=$obj->type; + $facturefournstatic->id = $obj->fk_invoice_supplier_source; + $facturefournstatic->ref = $obj->ref; + $facturefournstatic->type = $obj->type; print preg_replace('/\(CREDIT_NOTE\)/', $langs->trans("CreditNote"), $obj->description).' '.$facturefournstatic->getNomURl(1); print ''; - $facturefournstatic->id=$obj->fk_invoice_supplier_source; - $facturefournstatic->ref=$obj->ref; - $facturefournstatic->type=$obj->type; + $facturefournstatic->id = $obj->fk_invoice_supplier_source; + $facturefournstatic->ref = $obj->ref; + $facturefournstatic->type = $obj->type; print preg_replace('/\(DEPOSIT\)/', $langs->trans("InvoiceDeposit"), $obj->description).' '.$facturefournstatic->getNomURl(1); print ''; - $facturefournstatic->id=$obj->fk_invoice_supplier_source; - $facturefournstatic->ref=$obj->ref; - $facturefournstatic->type=$obj->type; + $facturefournstatic->id = $obj->fk_invoice_supplier_source; + $facturefournstatic->ref = $obj->ref; + $facturefournstatic->type = $obj->type; print preg_replace('/\(EXCESS PAID\)/', $langs->trans("Invoice"), $obj->description).' '.$facturefournstatic->getNomURl(1); print ''.img_object($langs->trans("ShowBill"), 'bill').' '.$obj->ref.''.price($obj->amount_ht).''.price($obj->multicurrency_amount_ht).''.vatrate($obj->tva_tx, true).''.price($obj->amount_ttc).''.price($obj->multicurrency_amount_ttc).'
'; + print '
'; // Reference print ''; @@ -1620,11 +1620,11 @@ if ($action == 'create' && $usercancreate) // Thirdparty print ''; - print ''; + print ''; if ($socid > 0) { print ''; } else { print ''; } - print '' . "\n"; + print ''."\n"; // Contact of order if ($socid > 0) { // Contacts (ask contact only if thirdparty already defined). - print "'; // Ligne info remises tiers - print ''; } // Date - print ''; // Delivery date planed print ""; // terms of the settlement - print ''; // Mode de reglement - print ''; // Bank Account - if (! empty($conf->global->BANK_ASK_PAYMENT_BANK_DURING_ORDER) && ! empty($conf->banque->enabled)) + if (!empty($conf->global->BANK_ASK_PAYMENT_BANK_DURING_ORDER) && !empty($conf->banque->enabled)) { - print ''; } // Delivery delay - print ''; // Shipping Method - if (! empty($conf->expedition->enabled)) { - print ''; } // Warehouse - if (! empty($conf->expedition->enabled) && ! empty($conf->global->WAREHOUSE_ASK_WAREHOUSE_DURING_ORDER)) { + if (!empty($conf->expedition->enabled) && !empty($conf->global->WAREHOUSE_ASK_WAREHOUSE_DURING_ORDER)) { require_once DOL_DOCUMENT_ROOT.'/product/class/html.formproduct.class.php'; - $formproduct=new FormProduct($db); - print ''; } // What trigger creation - print ''; // TODO How record was recorded OrderMode (llx_c_input_method) // Project - if (! empty($conf->projet->enabled)) + if (!empty($conf->projet->enabled)) { $langs->load("projects"); print ''; - print ''; print ''; } @@ -1762,7 +1762,7 @@ if ($action == 'create' && $usercancreate) $reshook = $hookmanager->executeHooks('formObjectOptions', $parameters, $object, $action); print $hookmanager->resPrint; if (empty($reshook)) { - if (! empty($conf->global->THIRDPARTY_PROPAGATE_EXTRAFIELDS_TO_ORDER)) { + if (!empty($conf->global->THIRDPARTY_PROPAGATE_EXTRAFIELDS_TO_ORDER)) { // copy from thirdparty $tpExtrafields = new Extrafields($db); $tpExtrafieldLabels = $tpExtrafields->fetch_name_optionals_label($soc->table_element); @@ -1771,19 +1771,19 @@ if ($action == 'create' && $usercancreate) } }; - print $object->showOptionals($extrafields, 'edit'); + print $object->showOptionals($extrafields, 'edit', $parameters); } // Template to use by default - print ''; + print ''; print '"; // Multicurrency - if (! empty($conf->multicurrency->enabled)) + if (!empty($conf->multicurrency->enabled)) { print ''; print ''; @@ -1794,7 +1794,7 @@ if ($action == 'create' && $usercancreate) // Note public print ''; - print ''; + print ''; print ''; - print ''; + print ''; print ''; } - if (! empty($origin) && ! empty($originid) && is_object($objectsrc)) + if (!empty($origin) && !empty($originid) && is_object($objectsrc)) { // TODO for compatibility if ($origin == 'contrat') { @@ -1824,13 +1824,13 @@ if ($action == 'create' && $usercancreate) $objectsrc->update_price(1); } - print "\n"; + print "\n"; print "\n"; - print '' . "\n"; - print '' . "\n"; - print '' . "\n"; - print ''; - print ''; + print ''."\n"; + print ''."\n"; + print ''."\n"; + print ''; + print ''; switch ($classname) { case 'Propal': @@ -1849,28 +1849,28 @@ if ($action == 'create' && $usercancreate) $newclassname = $classname; } - print ''; + print ''; // Amount - print ''; - print '"; + print ''; + print '"; if ($mysoc->localtax1_assuj == "1" || $objectsrc->total_localtax1 != 0) // Localtax1 RE { - print '"; + print '"; } if ($mysoc->localtax2_assuj == "1" || $objectsrc->total_localtax2 != 0) // Localtax2 IRPF { - print '"; + print '"; } - print '"; + print '"; if (!empty($conf->multicurrency->enabled)) { - print ''; - print '"; - print '"; + print ''; + print '"; + print '"; } } @@ -1880,17 +1880,17 @@ if ($action == 'create' && $usercancreate) // Button "Create Draft" print '
'; - print ''; + print ''; print '     '; - print ''; + print ''; print '
'; // 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); - print '
' . $langs->trans('Ref') . '' . $langs->trans("Draft") . '
' . $langs->trans('Customer') . ''.$langs->trans('Customer').''; print $soc->getNomUrl(1); - print ''; + print ''; print ''; @@ -1645,96 +1645,96 @@ if ($action == 'create' && $usercancreate) print ' '.$langs->trans("AddThirdParty").''; print '
" . $langs->trans("DefaultContact") . ''; + print "
".$langs->trans("DefaultContact").''; $form->select_contacts($soc->id, $contactid, 'contactid', 1, $srccontactslist, '', 1); print '
' . $langs->trans('Discounts') . ''; + print '
'.$langs->trans('Discounts').''; $absolute_discount = $soc->getAvailableDiscounts(); $thirdparty = $soc; $discount_type = 0; - $backtopage = urlencode($_SERVER["PHP_SELF"] . '?socid=' . $thirdparty->id . '&action=' . $action . '&origin=' . GETPOST('origin') . '&originid=' . GETPOST('originid')); + $backtopage = urlencode($_SERVER["PHP_SELF"].'?socid='.$thirdparty->id.'&action='.$action.'&origin='.GETPOST('origin').'&originid='.GETPOST('originid')); include DOL_DOCUMENT_ROOT.'/core/tpl/object_discounts.tpl.php'; print '
' . $langs->trans('Date') . ''; - print $form->selectDate('', 're', '', '', '', "crea_commande", 1, 1); // Always autofill date with current date + print '
'.$langs->trans('Date').''; + print $form->selectDate('', 're', '', '', '', "crea_commande", 1, 1); // Always autofill date with current date print '
".$langs->trans("DateDeliveryPlanned").''; if (empty($datedelivery)) { - if (! empty($conf->global->DATE_LIVRAISON_WEEK_DELAY)) $datedelivery = time() + ((7*$conf->global->DATE_LIVRAISON_WEEK_DELAY) * 24 * 60 * 60); - else $datedelivery=empty($conf->global->MAIN_AUTOFILL_DATE_DELIVERY)?-1:''; + if (!empty($conf->global->DATE_LIVRAISON_WEEK_DELAY)) $datedelivery = time() + ((7 * $conf->global->DATE_LIVRAISON_WEEK_DELAY) * 24 * 60 * 60); + else $datedelivery = empty($conf->global->MAIN_AUTOFILL_DATE_DELIVERY) ?-1 : ''; } print $form->selectDate($datedelivery, 'liv_', '', '', '', "crea_commande", 1, 1); print "
' . $langs->trans('PaymentConditionsShort') . ''; + print '
'.$langs->trans('PaymentConditionsShort').''; $form->select_conditions_paiements($cond_reglement_id, 'cond_reglement_id', - 1, 1); print '
' . $langs->trans('PaymentMode') . ''; + print '
'.$langs->trans('PaymentMode').''; $form->select_types_paiements($mode_reglement_id, 'mode_reglement_id'); print '
' . $langs->trans('BankAccount') . ''; + print '
'.$langs->trans('BankAccount').''; $form->select_comptes($fk_account, 'fk_account', 0, '', 1); print '
' . $langs->trans('AvailabilityPeriod') . ''; + print '
'.$langs->trans('AvailabilityPeriod').''; $form->selectAvailabilityDelay($availability_id, 'availability_id', '', 1); print '
' . $langs->trans('SendingMethod') . ''; + if (!empty($conf->expedition->enabled)) { + print '
'.$langs->trans('SendingMethod').''; print $form->selectShippingMethod($shipping_method_id, 'shipping_method_id', '', 1); print '
' . $langs->trans('Warehouse') . ''; + $formproduct = new FormProduct($db); + print '
'.$langs->trans('Warehouse').''; print $formproduct->selectWarehouses($warehouse_id, 'warehouse_id', '', 1); print '
' . $langs->trans('Channel') . ''; + print '
'.$langs->trans('Channel').''; $form->selectInputReason($demand_reason_id, 'demand_reason_id', '', 1); print '
' . $langs->trans("Project") . ''; + print ''.$langs->trans("Project").''; $numprojet = $formproject->select_projects(($soc->id > 0 ? $soc->id : -1), $projectid, 'projectid', 0, 0, 1, 0, 0, 0, 0, '', 0, 0); - print '   id).'">' . $langs->trans("AddProject") . ''; + print '   id).'">'.$langs->trans("AddProject").''; print '
' . $langs->trans('DefaultModel') . '
'.$langs->trans('DefaultModel').''; - include_once DOL_DOCUMENT_ROOT . '/core/modules/commande/modules_commande.php'; + include_once DOL_DOCUMENT_ROOT.'/core/modules/commande/modules_commande.php'; $liste = ModelePDFCommandes::liste_modeles($db); print $form->selectarray('model', $liste, $conf->global->COMMANDE_ADDON_PDF); print "
'.$form->editfieldkey("Currency", 'multicurrency_code', '', $object, 0).'
' . $langs->trans('NotePublic') . ''.$langs->trans('NotePublic').''; $doleditor = new DolEditor('note_public', $note_public, '', 80, 'dolibarr_notes', 'In', 0, false, true, ROWS_3, '90%'); @@ -1805,7 +1805,7 @@ if ($action == 'create' && $usercancreate) // Note private if (empty($user->socid)) { print '
' . $langs->trans('NotePrivate') . ''.$langs->trans('NotePrivate').''; $doleditor = new DolEditor('note_private', $note_private, '', 80, 'dolibarr_notes', 'In', 0, false, true, ROWS_3, '90%'); @@ -1814,7 +1814,7 @@ if ($action == 'create' && $usercancreate) print '
' . $langs->trans($newclassname) . '' . $objectsrc->getNomUrl(1) . '
'.$langs->trans($newclassname).''.$objectsrc->getNomUrl(1).'
' . $langs->trans('AmountHT') . '' . price($objectsrc->total_ht) . '
' . $langs->trans('AmountVAT') . '' . price($objectsrc->total_tva) . "
'.$langs->trans('AmountHT').''.price($objectsrc->total_ht).'
'.$langs->trans('AmountVAT').''.price($objectsrc->total_tva)."
' . $langs->transcountry("AmountLT1", $mysoc->country_code) . '' . price($objectsrc->total_localtax1) . "
'.$langs->transcountry("AmountLT1", $mysoc->country_code).''.price($objectsrc->total_localtax1)."
' . $langs->transcountry("AmountLT2", $mysoc->country_code) . '' . price($objectsrc->total_localtax2) . "
'.$langs->transcountry("AmountLT2", $mysoc->country_code).''.price($objectsrc->total_localtax2)."
' . $langs->trans('AmountTTC') . '' . price($objectsrc->total_ttc) . "
'.$langs->trans('AmountTTC').''.price($objectsrc->total_ttc)."
' . $langs->trans('MulticurrencyAmountHT') . '' . price($objectsrc->multicurrency_total_ht) . '
' . $langs->trans('MulticurrencyAmountVAT') . '' . price($objectsrc->multicurrency_total_tva) . "
' . $langs->trans('MulticurrencyAmountTTC') . '' . price($objectsrc->multicurrency_total_ttc) . "
'.$langs->trans('MulticurrencyAmountHT').''.price($objectsrc->multicurrency_total_ht).'
'.$langs->trans('MulticurrencyAmountVAT').''.price($objectsrc->multicurrency_total_tva)."
'.$langs->trans('MulticurrencyAmountTTC').''.price($objectsrc->multicurrency_total_ttc)."
'; + print '
'; $objectsrc->printOriginLinesList('', $selectedLines); @@ -1920,7 +1920,7 @@ if ($action == 'create' && $usercancreate) // Confirmation to delete if ($action == 'delete') { - $formconfirm = $form->formconfirm($_SERVER["PHP_SELF"] . '?id=' . $object->id, $langs->trans('DeleteOrder'), $langs->trans('ConfirmDeleteOrder'), 'confirm_delete', '', 0, 1); + $formconfirm = $form->formconfirm($_SERVER["PHP_SELF"].'?id='.$object->id, $langs->trans('DeleteOrder'), $langs->trans('ConfirmDeleteOrder'), 'confirm_delete', '', 0, 1); } // Confirmation of validation @@ -1935,81 +1935,81 @@ if ($action == 'create' && $usercancreate) } $text = $langs->trans('ConfirmValidateOrder', $numref); - if (! empty($conf->notification->enabled)) + if (!empty($conf->notification->enabled)) { - require_once DOL_DOCUMENT_ROOT . '/core/class/notify.class.php'; + require_once DOL_DOCUMENT_ROOT.'/core/class/notify.class.php'; $notify = new Notify($db); $text .= '
'; $text .= $notify->confirmMessage('ORDER_VALIDATE', $object->socid, $object); } - $qualified_for_stock_change=0; + $qualified_for_stock_change = 0; if (empty($conf->global->STOCK_SUPPORTS_SERVICES)) { - $qualified_for_stock_change=$object->hasProductsOrServices(2); + $qualified_for_stock_change = $object->hasProductsOrServices(2); } else { - $qualified_for_stock_change=$object->hasProductsOrServices(1); + $qualified_for_stock_change = $object->hasProductsOrServices(1); } - $formquestion=array(); - if (! empty($conf->stock->enabled) && ! empty($conf->global->STOCK_CALCULATE_ON_VALIDATE_ORDER) && $qualified_for_stock_change) + $formquestion = array(); + if (!empty($conf->stock->enabled) && !empty($conf->global->STOCK_CALCULATE_ON_VALIDATE_ORDER) && $qualified_for_stock_change) { $langs->load("stocks"); - require_once DOL_DOCUMENT_ROOT . '/product/class/html.formproduct.class.php'; + require_once DOL_DOCUMENT_ROOT.'/product/class/html.formproduct.class.php'; $formproduct = new FormProduct($db); - $forcecombo=0; - if ($conf->browser->name == 'ie') $forcecombo = 1; // There is a bug in IE10 that make combo inside popup crazy + $forcecombo = 0; + 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), // array('type' => 'checkbox', 'name' => 'update_prices', 'label' => $langs->trans("PuttingPricesUpToDate"), 'value' => 1), - array('type' => 'other','name' => 'idwarehouse','label' => $langs->trans("SelectWarehouseForStockDecrease"),'value' => $formproduct->selectWarehouses(GETPOST('idwarehouse', 'int')?GETPOST('idwarehouse', 'int'):'ifone', 'idwarehouse', '', 1, 0, 0, '', 0, $forcecombo)) + array('type' => 'other', 'name' => 'idwarehouse', 'label' => $langs->trans("SelectWarehouseForStockDecrease"), 'value' => $formproduct->selectWarehouses(GETPOST('idwarehouse', 'int') ?GETPOST('idwarehouse', 'int') : 'ifone', 'idwarehouse', '', 1, 0, 0, '', 0, $forcecombo)) ); } - $formconfirm = $form->formconfirm($_SERVER["PHP_SELF"] . '?id=' . $object->id, $langs->trans('ValidateOrder'), $text, 'confirm_validate', $formquestion, 0, 1, 220); + $formconfirm = $form->formconfirm($_SERVER["PHP_SELF"].'?id='.$object->id, $langs->trans('ValidateOrder'), $text, 'confirm_validate', $formquestion, 0, 1, 220); } // Confirm back to draft status if ($action == 'modif') { - $qualified_for_stock_change=0; + $qualified_for_stock_change = 0; if (empty($conf->global->STOCK_SUPPORTS_SERVICES)) { - $qualified_for_stock_change=$object->hasProductsOrServices(2); + $qualified_for_stock_change = $object->hasProductsOrServices(2); } else { - $qualified_for_stock_change=$object->hasProductsOrServices(1); + $qualified_for_stock_change = $object->hasProductsOrServices(1); } - $text=$langs->trans('ConfirmUnvalidateOrder', $object->ref); - $formquestion=array(); - if (! empty($conf->stock->enabled) && ! empty($conf->global->STOCK_CALCULATE_ON_VALIDATE_ORDER) && $qualified_for_stock_change) + $text = $langs->trans('ConfirmUnvalidateOrder', $object->ref); + $formquestion = array(); + if (!empty($conf->stock->enabled) && !empty($conf->global->STOCK_CALCULATE_ON_VALIDATE_ORDER) && $qualified_for_stock_change) { $langs->load("stocks"); - require_once DOL_DOCUMENT_ROOT . '/product/class/html.formproduct.class.php'; + require_once DOL_DOCUMENT_ROOT.'/product/class/html.formproduct.class.php'; $formproduct = new FormProduct($db); - $forcecombo=0; - if ($conf->browser->name == 'ie') $forcecombo = 1; // There is a bug in IE10 that make combo inside popup crazy + $forcecombo = 0; + 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), // array('type' => 'checkbox', 'name' => 'update_prices', 'label' => $langs->trans("PuttingPricesUpToDate"), 'value' => 1), - array('type' => 'other','name' => 'idwarehouse','label' => $langs->trans("SelectWarehouseForStockIncrease"),'value' => $formproduct->selectWarehouses(GETPOST('idwarehouse')?GETPOST('idwarehouse'):'ifone', 'idwarehouse', '', 1, 0, 0, '', 0, $forcecombo)) + array('type' => 'other', 'name' => 'idwarehouse', 'label' => $langs->trans("SelectWarehouseForStockIncrease"), 'value' => $formproduct->selectWarehouses(GETPOST('idwarehouse') ?GETPOST('idwarehouse') : 'ifone', 'idwarehouse', '', 1, 0, 0, '', 0, $forcecombo)) ); } - $formconfirm = $form->formconfirm($_SERVER["PHP_SELF"] . '?id=' . $object->id, $langs->trans('UnvalidateOrder'), $text, 'confirm_modif', $formquestion, "yes", 1, 220); + $formconfirm = $form->formconfirm($_SERVER["PHP_SELF"].'?id='.$object->id, $langs->trans('UnvalidateOrder'), $text, 'confirm_modif', $formquestion, "yes", 1, 220); } /* * Confirmation de la cloture */ if ($action == 'shipped') { - $formconfirm = $form->formconfirm($_SERVER["PHP_SELF"] . '?id=' . $object->id, $langs->trans('CloseOrder'), $langs->trans('ConfirmCloseOrder'), 'confirm_shipped', '', 0, 1); + $formconfirm = $form->formconfirm($_SERVER["PHP_SELF"].'?id='.$object->id, $langs->trans('CloseOrder'), $langs->trans('ConfirmCloseOrder'), 'confirm_shipped', '', 0, 1); } /* @@ -2017,57 +2017,57 @@ if ($action == 'create' && $usercancreate) */ if ($action == 'cancel') { - $qualified_for_stock_change=0; + $qualified_for_stock_change = 0; if (empty($conf->global->STOCK_SUPPORTS_SERVICES)) { - $qualified_for_stock_change=$object->hasProductsOrServices(2); + $qualified_for_stock_change = $object->hasProductsOrServices(2); } else { - $qualified_for_stock_change=$object->hasProductsOrServices(1); + $qualified_for_stock_change = $object->hasProductsOrServices(1); } - $text=$langs->trans('ConfirmCancelOrder', $object->ref); - $formquestion=array(); - if (! empty($conf->stock->enabled) && ! empty($conf->global->STOCK_CALCULATE_ON_VALIDATE_ORDER) && $qualified_for_stock_change) + $text = $langs->trans('ConfirmCancelOrder', $object->ref); + $formquestion = array(); + if (!empty($conf->stock->enabled) && !empty($conf->global->STOCK_CALCULATE_ON_VALIDATE_ORDER) && $qualified_for_stock_change) { $langs->load("stocks"); - require_once DOL_DOCUMENT_ROOT . '/product/class/html.formproduct.class.php'; + require_once DOL_DOCUMENT_ROOT.'/product/class/html.formproduct.class.php'; $formproduct = new FormProduct($db); - $forcecombo=0; - if ($conf->browser->name == 'ie') $forcecombo = 1; // There is a bug in IE10 that make combo inside popup crazy + $forcecombo = 0; + 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), // array('type' => 'checkbox', 'name' => 'update_prices', 'label' => $langs->trans("PuttingPricesUpToDate"), 'value' => 1), - array('type' => 'other','name' => 'idwarehouse','label' => $langs->trans("SelectWarehouseForStockIncrease"),'value' => $formproduct->selectWarehouses(GETPOST('idwarehouse')?GETPOST('idwarehouse'):'ifone', 'idwarehouse', '', 1, 0, 0, '', 0, $forcecombo)) + array('type' => 'other', 'name' => 'idwarehouse', 'label' => $langs->trans("SelectWarehouseForStockIncrease"), 'value' => $formproduct->selectWarehouses(GETPOST('idwarehouse') ?GETPOST('idwarehouse') : 'ifone', 'idwarehouse', '', 1, 0, 0, '', 0, $forcecombo)) ); } - $formconfirm = $form->formconfirm($_SERVER["PHP_SELF"] . '?id=' . $object->id, $langs->trans('Cancel'), $text, 'confirm_cancel', $formquestion, 0, 1); + $formconfirm = $form->formconfirm($_SERVER["PHP_SELF"].'?id='.$object->id, $langs->trans('Cancel'), $text, 'confirm_cancel', $formquestion, 0, 1); } // 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); + $formconfirm = $form->formconfirm($_SERVER["PHP_SELF"].'?id='.$object->id.'&lineid='.$lineid, $langs->trans('DeleteProductLine'), $langs->trans('ConfirmDeleteProductLine'), 'confirm_deleteline', '', 0, 1); } // Clone confirmation 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.client=1 OR s.client=3)')) + array('type' => 'other', 'name' => 'socid', 'label' => $langs->trans("SelectThirdParty"), 'value' => $form->select_company(GETPOST('socid', 'int'), 'socid', '(s.client=1 OR s.client=3)')) ); - $formconfirm = $form->formconfirm($_SERVER["PHP_SELF"] . '?id=' . $object->id, $langs->trans('ToClone'), $langs->trans('ConfirmCloneOrder', $object->ref), 'confirm_clone', $formquestion, 'yes', 1); + $formconfirm = $form->formconfirm($_SERVER["PHP_SELF"].'?id='.$object->id, $langs->trans('ToClone'), $langs->trans('ConfirmCloneOrder', $object->ref), 'confirm_clone', $formquestion, 'yes', 1); } // Call Hook formConfirm $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; @@ -2075,49 +2075,49 @@ if ($action == 'create' && $usercancreate) // Order card - $linkback = '' . $langs->trans("BackToList") . ''; + $linkback = ''.$langs->trans("BackToList").''; - $morehtmlref='
'; + $morehtmlref = '
'; // Ref customer - $morehtmlref.=$form->editfieldkey("RefCustomer", 'ref_client', $object->ref_client, $object, $usercancreate, 'string', '', 0, 1); - $morehtmlref.=$form->editfieldval("RefCustomer", 'ref_client', $object->ref_client, $object, $usercancreate, 'string', '', null, null, '', 1); + $morehtmlref .= $form->editfieldkey("RefCustomer", 'ref_client', $object->ref_client, $object, $usercancreate, 'string', '', 0, 1); + $morehtmlref .= $form->editfieldval("RefCustomer", 'ref_client', $object->ref_client, $object, $usercancreate, 'string', '', null, null, '', 1); // Thirdparty - $morehtmlref.='
'.$langs->trans('ThirdParty') . ' : ' . $soc->getNomUrl(1); - if (empty($conf->global->MAIN_DISABLE_OTHER_LINK) && $object->thirdparty->id > 0) $morehtmlref.=' ('.$langs->trans("OtherOrders").')'; + $morehtmlref .= '
'.$langs->trans('ThirdParty').' : '.$soc->getNomUrl(1); + if (empty($conf->global->MAIN_DISABLE_OTHER_LINK) && $object->thirdparty->id > 0) $morehtmlref .= ' ('.$langs->trans("OtherOrders").')'; // Project - if (! empty($conf->projet->enabled)) + if (!empty($conf->projet->enabled)) { $langs->load("projects"); - $morehtmlref.='
'.$langs->trans('Project') . ' '; + $morehtmlref .= '
'.$langs->trans('Project').' '; if ($usercancreate) { if ($action != 'classify') - $morehtmlref.='' . img_edit($langs->transnoentitiesnoconv('SetProject')) . ' : '; + $morehtmlref .= ''.img_edit($langs->transnoentitiesnoconv('SetProject')).' : '; if ($action == 'classify') { //$morehtmlref.=$form->form_project($_SERVER['PHP_SELF'] . '?id=' . $object->id, $object->socid, $object->fk_project, 'projectid', 0, 0, 1, 1); - $morehtmlref.=''; - $morehtmlref.=''; - $morehtmlref.=''; - $morehtmlref.=$formproject->select_projects($object->socid, $object->fk_project, 'projectid', $maxlength, 0, 1, 0, 1, 0, 0, '', 1); - $morehtmlref.=''; - $morehtmlref.=''; + $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); + $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)) { + if (!empty($object->fk_project)) { $proj = new Project($db); $proj->fetch($object->fk_project); - $morehtmlref.=''; - $morehtmlref.=$proj->ref; - $morehtmlref.=''; + $morehtmlref .= ''; + $morehtmlref .= $proj->ref; + $morehtmlref .= ''; } else { - $morehtmlref.=''; + $morehtmlref .= ''; } } } - $morehtmlref.='
'; + $morehtmlref .= '
'; dol_banner_tab($object, 'ref', $linkback, 1, 'ref', 'ref', $morehtmlref); @@ -2136,14 +2136,14 @@ if ($action == 'create' && $usercancreate) print $langs->trans('OutstandingBill'); print ''; print ''; } // Relative and absolute discounts - if (! empty($conf->global->FACTURE_DEPOSITS_ARE_JUST_PAYMENTS)) { + if (!empty($conf->global->FACTURE_DEPOSITS_ARE_JUST_PAYMENTS)) { $filterabsolutediscount = "fk_facture_source IS NULL"; // If we want deposit to be substracted to payments only and not to total of final invoice $filtercreditnote = "fk_facture_source IS NOT NULL"; // If we want deposit to be substracted to payments only and not to total of final invoice } else { @@ -2151,11 +2151,11 @@ if ($action == 'create' && $usercancreate) $filtercreditnote = "fk_facture_source IS NOT NULL AND (description NOT LIKE '(DEPOSIT)%' OR description LIKE '(EXCESS RECEIVED)%')"; } - $addrelativediscount = '' . $langs->trans("EditRelativeDiscounts") . ''; - $addabsolutediscount = '' . $langs->trans("EditGlobalDiscounts") . ''; - $addcreditnote = '' . $langs->trans("AddCreditNote") . ''; + $addrelativediscount = ''.$langs->trans("EditRelativeDiscounts").''; + $addabsolutediscount = ''.$langs->trans("EditGlobalDiscounts").''; + $addcreditnote = ''.$langs->trans("AddCreditNote").''; - print ''; @@ -2175,15 +2175,15 @@ if ($action == 'create' && $usercancreate) print $form->editfieldkey("Date", 'date', '', $object, $editenable); print ''; // Shipping Method - if (! empty($conf->expedition->enabled)) { + if (!empty($conf->expedition->enabled)) { print ''; @@ -2264,14 +2264,14 @@ if ($action == 'create' && $usercancreate) print $form->editfieldkey("PaymentMode", 'mode', '', $object, $editenable); print ''; // Multicurrency - if (! empty($conf->multicurrency->enabled)) + if (!empty($conf->multicurrency->enabled)) { // Multicurrency code print ''; @@ -2280,9 +2280,9 @@ if ($action == 'create' && $usercancreate) print $form->editfieldkey("Currency", 'multicurrencycode', '', $object, $editenable); print ''; @@ -2295,13 +2295,13 @@ if ($action == 'create' && $usercancreate) print $form->editfieldkey("CurrencyRate", 'multicurrencyrate', '', $object, $editenable); print ''; @@ -2329,9 +2329,9 @@ if ($action == 'create' && $usercancreate) print $form->editfieldkey("Channel", 'demandreason', '', $object, $editenable); print ''; @@ -2349,19 +2349,19 @@ if ($action == 'create' && $usercancreate) print ''; */ - $tmparray=$object->getTotalWeightVolume(); - $totalWeight=$tmparray['weight']; - $totalVolume=$tmparray['volume']; + $tmparray = $object->getTotalWeightVolume(); + $totalWeight = $tmparray['weight']; + $totalVolume = $tmparray['volume']; if ($totalWeight) { print ''; print ''; } if ($totalVolume) { print ''; print ''; } @@ -2380,13 +2380,13 @@ if ($action == 'create' && $usercancreate) } 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); + print $form->select_incoterms((!empty($object->fk_incoterms) ? $object->fk_incoterms : ''), (!empty($object->location_incoterms) ? $object->location_incoterms : ''), $_SERVER['PHP_SELF'].'?id='.$object->id); } print ''; } // Bank Account - if (! empty($conf->global->BANK_ASK_PAYMENT_BANK_DURING_ORDER) && ! empty($conf->banque->enabled)) { + if (!empty($conf->global->BANK_ASK_PAYMENT_BANK_DURING_ORDER) && !empty($conf->banque->enabled)) { print '
'; $arrayoutstandingbills = $soc->getOutstandingBills(); - print price($arrayoutstandingbills['opened']) . ' / '; + print price($arrayoutstandingbills['opened']).' / '; print price($soc->outstanding_limit, 0, '', 1, - 1, - 1, $conf->currency); print '
' . $langs->trans('Discounts') . ''; + print '
'.$langs->trans('Discounts').''; $absolute_discount = $soc->getAvailableDiscounts('', $filterabsolutediscount); $absolute_creditnote = $soc->getAvailableDiscounts('', $filtercreditnote); @@ -2164,7 +2164,7 @@ if ($action == 'create' && $usercancreate) $thirdparty = $soc; $discount_type = 0; - $backtopage = urlencode($_SERVER["PHP_SELF"] . '?id=' . $object->id); + $backtopage = urlencode($_SERVER["PHP_SELF"].'?id='.$object->id); include DOL_DOCUMENT_ROOT.'/core/tpl/object_discounts.tpl.php'; print '
'; if ($action == 'editdate') { - print '
'; - print ''; + print ''; + print ''; print ''; print $form->selectDate($object->date, 'order_', '', '', '', "setdate"); - print ''; + print ''; print '
'; } else { print $object->date ? dol_print_date($object->date, 'day') : ' '; - if ($object->hasDelay() && ! empty($object->date_livraison)) { + if ($object->hasDelay() && !empty($object->date_livraison)) { print ' '.img_picto($langs->trans("Late").' : '.$object->showDelay(), "warning"); } } @@ -2196,15 +2196,15 @@ if ($action == 'create' && $usercancreate) print $form->editfieldkey("DateDeliveryPlanned", 'date_livraison', '', $object, $editenable); print '
'; if ($action == 'editdate_livraison') { - print '
'; - print ''; + print ''; + print ''; print ''; print $form->selectDate($object->date_livraison ? $object->date_livraison : - 1, 'liv_', '', '', '', "setdate_livraison"); - print ''; + print ''; print '
'; } else { print $object->date_livraison ? dol_print_date($object->date_livraison, 'daytext') : ' '; - if ($object->hasDelay() && ! empty($object->date_livraison)) { + if ($object->hasDelay() && !empty($object->date_livraison)) { print ' '.img_picto($langs->trans("Late").' : '.$object->showDelay(), "warning"); } } @@ -2212,7 +2212,7 @@ if ($action == 'create' && $usercancreate) print '
'; $editenable = $usercancreate; print $form->editfieldkey("SendingMethod", 'shippingmethod', '', $object, $editenable); @@ -2227,10 +2227,10 @@ if ($action == 'create' && $usercancreate) } // Warehouse - if (! empty($conf->expedition->enabled) && ! empty($conf->global->WAREHOUSE_ASK_WAREHOUSE_DURING_ORDER)) { + if (!empty($conf->expedition->enabled) && !empty($conf->global->WAREHOUSE_ASK_WAREHOUSE_DURING_ORDER)) { $langs->load('stocks'); require_once DOL_DOCUMENT_ROOT.'/product/class/html.formproduct.class.php'; - $formproduct=new FormProduct($db); + $formproduct = new FormProduct($db); print '
'; $editenable = $usercancreate; print $form->editfieldkey("Warehouse", 'warehouse', '', $object, $editenable); @@ -2250,9 +2250,9 @@ if ($action == 'create' && $usercancreate) print $form->editfieldkey("PaymentConditionsShort", 'conditions', '', $object, $editenable); print ''; if ($action == 'editconditions') { - $form->form_conditions_reglement($_SERVER['PHP_SELF'] . '?id=' . $object->id, $object->cond_reglement_id, 'cond_reglement_id', 1); + $form->form_conditions_reglement($_SERVER['PHP_SELF'].'?id='.$object->id, $object->cond_reglement_id, 'cond_reglement_id', 1); } else { - $form->form_conditions_reglement($_SERVER['PHP_SELF'] . '?id=' . $object->id, $object->cond_reglement_id, 'none', 1); + $form->form_conditions_reglement($_SERVER['PHP_SELF'].'?id='.$object->id, $object->cond_reglement_id, 'none', 1); } print ''; if ($action == 'editmode') { - $form->form_modes_reglement($_SERVER['PHP_SELF'] . '?id=' . $object->id, $object->mode_reglement_id, 'mode_reglement_id', 'CRDT', 1, 1); + $form->form_modes_reglement($_SERVER['PHP_SELF'].'?id='.$object->id, $object->mode_reglement_id, 'mode_reglement_id', 'CRDT', 1, 1); } else { - $form->form_modes_reglement($_SERVER['PHP_SELF'] . '?id=' . $object->id, $object->mode_reglement_id, 'none'); + $form->form_modes_reglement($_SERVER['PHP_SELF'].'?id='.$object->id, $object->mode_reglement_id, 'none'); } print '
'; if ($action == 'editmulticurrencycode') { - $form->form_multicurrency_code($_SERVER['PHP_SELF'] . '?id=' . $object->id, $object->multicurrency_code, 'multicurrency_code'); + $form->form_multicurrency_code($_SERVER['PHP_SELF'].'?id='.$object->id, $object->multicurrency_code, 'multicurrency_code'); } else { - $form->form_multicurrency_code($_SERVER['PHP_SELF'] . '?id=' . $object->id, $object->multicurrency_code, 'none'); + $form->form_multicurrency_code($_SERVER['PHP_SELF'].'?id='.$object->id, $object->multicurrency_code, 'none'); } print '
'; if ($action == 'editmulticurrencyrate' || $action == 'actualizemulticurrencyrate') { - if($action == 'actualizemulticurrencyrate') { + if ($action == 'actualizemulticurrencyrate') { list($object->fk_multicurrency, $object->multicurrency_tx) = MultiCurrency::getIdAndTxFromCode($object->db, $object->multicurrency_code); } - $form->form_multicurrency_rate($_SERVER['PHP_SELF'] . '?id=' . $object->id, $object->multicurrency_tx, 'multicurrency_tx', $object->multicurrency_code); + $form->form_multicurrency_rate($_SERVER['PHP_SELF'].'?id='.$object->id, $object->multicurrency_tx, 'multicurrency_tx', $object->multicurrency_code); } else { - $form->form_multicurrency_rate($_SERVER['PHP_SELF'] . '?id=' . $object->id, $object->multicurrency_tx, 'none', $object->multicurrency_code); - if($object->statut == $object::STATUS_DRAFT && $object->multicurrency_code && $object->multicurrency_code != $conf->currency) { + $form->form_multicurrency_rate($_SERVER['PHP_SELF'].'?id='.$object->id, $object->multicurrency_tx, 'none', $object->multicurrency_code); + if ($object->statut == $object::STATUS_DRAFT && $object->multicurrency_code && $object->multicurrency_code != $conf->currency) { print '
        '; print ''.$langs->trans("ActualizeCurrency").''; print '
'; @@ -2317,9 +2317,9 @@ if ($action == 'create' && $usercancreate) print $form->editfieldkey("AvailabilityPeriod", 'availability', '', $object, $editenable); print '
'; if ($action == 'editavailability') { - $form->form_availability($_SERVER['PHP_SELF'] . '?id=' . $object->id, $object->availability_id, 'availability_id', 1); + $form->form_availability($_SERVER['PHP_SELF'].'?id='.$object->id, $object->availability_id, 'availability_id', 1); } else { - $form->form_availability($_SERVER['PHP_SELF'] . '?id=' . $object->id, $object->availability_id, 'none', 1); + $form->form_availability($_SERVER['PHP_SELF'].'?id='.$object->id, $object->availability_id, 'none', 1); } print '
'; if ($action == 'editdemandreason') { - $form->formInputReason($_SERVER['PHP_SELF'] . '?id=' . $object->id, $object->demand_reason_id, 'demand_reason_id', 1); + $form->formInputReason($_SERVER['PHP_SELF'].'?id='.$object->id, $object->demand_reason_id, 'demand_reason_id', 1); } else { - $form->formInputReason($_SERVER['PHP_SELF'] . '?id=' . $object->id, $object->demand_reason_id, 'none'); + $form->formInputReason($_SERVER['PHP_SELF'].'?id='.$object->id, $object->demand_reason_id, 'none'); } print '
'.$langs->trans("CalculatedWeight").''; - print showDimensionInBestUnit($totalWeight, 0, "weight", $langs, isset($conf->global->MAIN_WEIGHT_DEFAULT_ROUND)?$conf->global->MAIN_WEIGHT_DEFAULT_ROUND:-1, isset($conf->global->MAIN_WEIGHT_DEFAULT_UNIT)?$conf->global->MAIN_WEIGHT_DEFAULT_UNIT:'no'); + print showDimensionInBestUnit($totalWeight, 0, "weight", $langs, isset($conf->global->MAIN_WEIGHT_DEFAULT_ROUND) ? $conf->global->MAIN_WEIGHT_DEFAULT_ROUND : -1, isset($conf->global->MAIN_WEIGHT_DEFAULT_UNIT) ? $conf->global->MAIN_WEIGHT_DEFAULT_UNIT : 'no'); print '
'.$langs->trans("CalculatedVolume").''; - print showDimensionInBestUnit($totalVolume, 0, "volume", $langs, isset($conf->global->MAIN_VOLUME_DEFAULT_ROUND)?$conf->global->MAIN_VOLUME_DEFAULT_ROUND:-1, isset($conf->global->MAIN_VOLUME_DEFAULT_UNIT)?$conf->global->MAIN_VOLUME_DEFAULT_UNIT:'no'); + print showDimensionInBestUnit($totalVolume, 0, "volume", $langs, isset($conf->global->MAIN_VOLUME_DEFAULT_ROUND) ? $conf->global->MAIN_VOLUME_DEFAULT_ROUND : -1, isset($conf->global->MAIN_VOLUME_DEFAULT_UNIT) ? $conf->global->MAIN_VOLUME_DEFAULT_UNIT : 'no'); print '
'; $editenable = $usercancreate; print $form->editfieldkey("BankAccount", 'bankaccount', '', $object, $editenable); @@ -2401,7 +2401,7 @@ if ($action == 'create' && $usercancreate) } // Other attributes - include DOL_DOCUMENT_ROOT . '/core/tpl/extrafields_view.tpl.php'; + include DOL_DOCUMENT_ROOT.'/core/tpl/extrafields_view.tpl.php'; print '
'; @@ -2415,46 +2415,46 @@ if ($action == 'create' && $usercancreate) if (!empty($conf->multicurrency->enabled) && ($object->multicurrency_code != $conf->currency)) { // Multicurrency Amount HT - 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)) . '
'.$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)).'
' . $form->editfieldkey('MulticurrencyAmountVAT', 'multicurrency_total_tva', '', $object, 0) . '' . price($object->multicurrency_total_tva, '', $langs, 0, - 1, - 1, (!empty($object->multicurrency_code) ? $object->multicurrency_code : $conf->currency)) . '
'.$form->editfieldkey('MulticurrencyAmountVAT', 'multicurrency_total_tva', '', $object, 0).''.price($object->multicurrency_total_tva, '', $langs, 0, - 1, - 1, (!empty($object->multicurrency_code) ? $object->multicurrency_code : $conf->currency)).'
' . $form->editfieldkey('MulticurrencyAmountTTC', 'multicurrency_total_ttc', '', $object, 0) . '' . price($object->multicurrency_total_ttc, '', $langs, 0, - 1, - 1, (!empty($object->multicurrency_code) ? $object->multicurrency_code : $conf->currency)) . '
'.$form->editfieldkey('MulticurrencyAmountTTC', 'multicurrency_total_ttc', '', $object, 0).''.price($object->multicurrency_total_ttc, '', $langs, 0, - 1, - 1, (!empty($object->multicurrency_code) ? $object->multicurrency_code : $conf->currency)).'
' . $langs->trans('AmountHT') . '' . price($object->total_ht, 1, '', 1, - 1, - 1, $conf->currency) . $alert . '
'.$langs->trans('AmountHT').''.price($object->total_ht, 1, '', 1, - 1, - 1, $conf->currency).$alert.'
' . $langs->trans('AmountVAT') . '' . price($object->total_tva, 1, '', 1, - 1, - 1, $conf->currency) . '
'.$langs->trans('AmountVAT').''.price($object->total_tva, 1, '', 1, - 1, - 1, $conf->currency).'
' . $langs->transcountry("AmountLT1", $mysoc->country_code) . '' . price($object->total_localtax1, 1, '', 1, - 1, - 1, $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) . '
'.$langs->transcountry("AmountLT2", $mysoc->country_code).''.price($object->total_localtax2, 1, '', 1, - 1, - 1, $conf->currency).'
' . $langs->trans('AmountTTC') . '' . price($object->total_ttc, 1, '', 1, - 1, - 1, $conf->currency) . '
'.$langs->trans('AmountTTC').''.price($object->total_ttc, 1, '', 1, - 1, - 1, $conf->currency).'
' . $langs->trans('Status') . '' . $object->getLibStatut(4) . '
'; // Margin Infos - if (! empty($conf->margin->enabled)) { + if (!empty($conf->margin->enabled)) { $formmargin->displayMarginInfos($object); } print ''; print ''; - print ''; // Close fichecenter + print ''; // Close fichecenter print '

'; - 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'; + 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'; + include DOL_DOCUMENT_ROOT.'/core/tpl/bloc_showhide.tpl.php'; } /* @@ -2490,21 +2490,21 @@ if ($action == 'create' && $usercancreate) */ $result = $object->getLinesArray(); - print '
- - + print ' + + - '; + '; - if (! empty($conf->use_javascript_ajax) && $object->statut == Commande::STATUS_DRAFT) { - include DOL_DOCUMENT_ROOT . '/core/tpl/ajaxrow.tpl.php'; + if (!empty($conf->use_javascript_ajax) && $object->statut == Commande::STATUS_DRAFT) { + include DOL_DOCUMENT_ROOT.'/core/tpl/ajaxrow.tpl.php'; } print '
'; print ''; // Show object lines - if (! empty($object->lines)) + if (!empty($object->lines)) $ret = $object->printObjectLines($action, $mysoc, $soc, $lineid, 1); $numlines = count($object->lines); @@ -2544,19 +2544,19 @@ if ($action == 'create' && $usercancreate) // Send if ($object->statut > Commande::STATUS_DRAFT || !empty($conf->global->COMMANDE_SENDBYEMAIL_FOR_ALL_STATUS)) { if ($usercansend) { - print '' . $langs->trans('SendMail') . ''; + print ''.$langs->trans('SendMail').''; } else - print '' . $langs->trans('SendMail') . ''; + print ''.$langs->trans('SendMail').''; } // Valid if ($object->statut == Commande::STATUS_DRAFT && $object->total_ttc >= 0 && $numlines > 0 && $usercanvalidate) { - print '' . $langs->trans('Validate') . ''; + print ''.$langs->trans('Validate').''; } // Edit if ($object->statut == Commande::STATUS_VALIDATED && $usercancreate) { - print '' . $langs->trans('Modify') . ''; + print ''.$langs->trans('Modify').''; } // Create event /*if ($conf->agenda->enabled && ! empty($conf->global->MAIN_ADD_EVENT_ON_ELEMENT_CARD)) @@ -2568,11 +2568,11 @@ if ($action == 'create' && $usercancreate) }*/ // Create a purchase order - if (! empty($conf->global->WORKFLOW_CAN_CREATE_PURCHASE_ORDER_FROM_SALE_ORDER)) + if (!empty($conf->global->WORKFLOW_CAN_CREATE_PURCHASE_ORDER_FROM_SALE_ORDER)) { - if (! empty($conf->fournisseur->enabled) && $object->statut > Commande::STATUS_DRAFT && $object->statut < Commande::STATUS_CLOSED && $object->getNbOfServicesLines() > 0) { + if (!empty($conf->fournisseur->enabled) && $object->statut > Commande::STATUS_DRAFT && $object->statut < Commande::STATUS_CLOSED && $object->getNbOfServicesLines() > 0) { if ($usercancreatepurchaseorder) { - print '' . $langs->trans("AddPurchaseOrder") . ''; + print ''.$langs->trans("AddPurchaseOrder").''; } } } @@ -2583,9 +2583,9 @@ if ($action == 'create' && $usercancreate) if ($object->statut > Commande::STATUS_DRAFT && $object->statut < Commande::STATUS_CLOSED && $object->getNbOfServicesLines() > 0) { if ($user->rights->ficheinter->creer) { - print '' . $langs->trans('AddIntervention') . ''; + print ''.$langs->trans('AddIntervention').''; } else { - print '' . $langs->trans('AddIntervention') . ''; + print ''.$langs->trans('AddIntervention').''; } } } @@ -2595,71 +2595,71 @@ if ($action == 'create' && $usercancreate) $langs->load("contracts"); if ($user->rights->contrat->creer) { - print '' . $langs->trans('AddContract') . ''; + print ''.$langs->trans('AddContract').''; } } // Ship $numshipping = 0; - if (! empty($conf->expedition->enabled)) { + if (!empty($conf->expedition->enabled)) { $numshipping = $object->nb_expedition(); if ($object->statut > Commande::STATUS_DRAFT && $object->statut < Commande::STATUS_CLOSED && ($object->getNbOfProductsLines() > 0 || !empty($conf->global->STOCK_SUPPORTS_SERVICES))) { if (($conf->expedition_bon->enabled && $user->rights->expedition->creer) || ($conf->livraison_bon->enabled && $user->rights->expedition->livraison->creer)) { if ($user->rights->expedition->creer) { - print '' . $langs->trans('CreateShipment') . ''; + print ''.$langs->trans('CreateShipment').''; } else { - print '' . $langs->trans('CreateShipment') . ''; + print ''.$langs->trans('CreateShipment').''; } } else { $langs->load("errors"); - print 'transnoentitiesnoconv("Shipment"))) . '">' . $langs->trans('CreateShipment') . ''; + print 'transnoentitiesnoconv("Shipment"))).'">'.$langs->trans('CreateShipment').''; } } } // Reopen a closed order if (($object->statut == Commande::STATUS_CLOSED || $object->statut == Commande::STATUS_CANCELED) && $usercancreate) { - print ''; + print ''; } // Set to shipped if (($object->statut == Commande::STATUS_VALIDATED || $object->statut == Commande::STATUS_SHIPMENTONPROCESS) && $usercanclose) { - print ''; + print ''; } // Create bill and Classify billed // Note: Even if module invoice is not enabled, we should be able to use button "Classified billed" - if ($object->statut > Commande::STATUS_DRAFT && ! $object->billed) { - if (! empty($conf->facture->enabled) && $user->rights->facture->creer && empty($conf->global->WORKFLOW_DISABLE_CREATE_INVOICE_FROM_ORDER)) { - print ''; + if ($object->statut > Commande::STATUS_DRAFT && !$object->billed) { + if (!empty($conf->facture->enabled) && $user->rights->facture->creer && empty($conf->global->WORKFLOW_DISABLE_CREATE_INVOICE_FROM_ORDER)) { + print ''; } if ($usercancreate && $object->statut >= Commande::STATUS_VALIDATED && empty($conf->global->WORKFLOW_DISABLE_CLASSIFY_BILLED_FROM_ORDER) && empty($conf->global->WORKFLOW_BILL_ON_SHIPMENT)) { - print ''; + print ''; } } if ($object->statut > Commande::STATUS_DRAFT && $object->billed) { if ($usercancreate && $object->statut >= Commande::STATUS_VALIDATED && empty($conf->global->WORKFLOW_DISABLE_CLASSIFY_BILLED_FROM_ORDER) && empty($conf->global->WORKFLOW_BILL_ON_SHIPMENT)) { - print ''; + print ''; } } // Clone if ($usercancreate) { - print ''; + print ''; } // Cancel order - if ($object->statut == Commande::STATUS_VALIDATED && (! empty($usercanclose) || ! empty($usercancancel))) + if ($object->statut == Commande::STATUS_VALIDATED && (!empty($usercanclose) || !empty($usercancancel))) { - print ''; + print ''; } // Delete order if ($usercandelete) { if ($numshipping == 0) { - print ''; + print ''; } else { - print ''; + print ''; } } } @@ -2677,9 +2677,9 @@ if ($action == 'create' && $usercancreate) print ''; // ancre // Documents $comref = dol_sanitizeFileName($object->ref); - $relativepath = $comref . '/' . $comref . '.pdf'; - $filedir = $conf->commande->multidir_output[$object->entity] . '/' . $comref; - $urlsource = $_SERVER["PHP_SELF"] . "?id=" . $object->id; + $relativepath = $comref.'/'.$comref.'.pdf'; + $filedir = $conf->commande->multidir_output[$object->entity].'/'.$comref; + $urlsource = $_SERVER["PHP_SELF"]."?id=".$object->id; $genallowed = $usercanread; $delallowed = $usercancreate; print $formfile->showdocuments('commande', $comref, $filedir, $urlsource, $genallowed, $delallowed, $object->modelpdf, 1, 0, 0, 28, 0, '', '', '', $soc->default_lang, '', $object); @@ -2689,16 +2689,16 @@ if ($action == 'create' && $usercancreate) $linktoelem = $form->showLinkToObjectBlock($object, null, array('order')); $compatibleImportElementsList = false; - if($usercancreate + if ($usercancreate && $object->statut == Commande::STATUS_DRAFT) { - $compatibleImportElementsList = array('commande','propal'); // import from linked elements + $compatibleImportElementsList = array('commande', 'propal'); // import from linked elements } $somethingshown = $form->showLinkedObjectBlock($object, $linktoelem, $compatibleImportElementsList); // Show online payment link - $useonlinepayment = (! empty($conf->paypal->enabled) || ! empty($conf->stripe->enabled) || ! empty($conf->paybox->enabled)); - if (! empty($conf->global->ORDER_HIDE_ONLINE_PAYMENT_ON_ORDER)) $useonlinepayment = 0; + $useonlinepayment = (!empty($conf->paypal->enabled) || !empty($conf->stripe->enabled) || !empty($conf->paybox->enabled)); + if (!empty($conf->global->ORDER_HIDE_ONLINE_PAYMENT_ON_ORDER)) $useonlinepayment = 0; if ($object->statut != Commande::STATUS_DRAFT && $useonlinepayment) { print '
'; @@ -2707,7 +2707,7 @@ if ($action == 'create' && $usercancreate) } // Show direct download link - if ($object->statut != Commande::STATUS_DRAFT && ! empty($conf->global->ORDER_ALLOW_EXTERNAL_DOWNLOAD)) + if ($object->statut != Commande::STATUS_DRAFT && !empty($conf->global->ORDER_ALLOW_EXTERNAL_DOWNLOAD)) { print '
'."\n"; print showDirectDownloadLink($object).'
'; @@ -2716,7 +2716,7 @@ if ($action == 'create' && $usercancreate) print '
'; // List of actions on element - include_once DOL_DOCUMENT_ROOT . '/core/class/html.formactions.class.php'; + include_once DOL_DOCUMENT_ROOT.'/core/class/html.formactions.class.php'; $formactions = new FormActions($db); $somethingshown = $formactions->showactions($object, 'order', $socid, 1); @@ -2724,8 +2724,8 @@ if ($action == 'create' && $usercancreate) } // Presend form - $modelmail='order_send'; - $defaulttopic='SendOrderRef'; + $modelmail = 'order_send'; + $defaulttopic = 'SendOrderRef'; $diroutput = $conf->commande->multidir_output[$object->entity]; $trackid = 'ord'.$object->id; diff --git a/htdocs/commande/class/commande.class.php b/htdocs/commande/class/commande.class.php index 6e01ba2f5e2..0c093d561c0 100644 --- a/htdocs/commande/class/commande.class.php +++ b/htdocs/commande/class/commande.class.php @@ -31,11 +31,11 @@ * \ingroup commande * \brief Fichier des classes de commandes */ -include_once DOL_DOCUMENT_ROOT .'/core/class/commonorder.class.php'; -require_once DOL_DOCUMENT_ROOT .'/core/class/commonobjectline.class.php'; -require_once DOL_DOCUMENT_ROOT .'/product/class/product.class.php'; -require_once DOL_DOCUMENT_ROOT .'/margin/lib/margins.lib.php'; -require_once DOL_DOCUMENT_ROOT .'/multicurrency/class/multicurrency.class.php'; +include_once DOL_DOCUMENT_ROOT.'/core/class/commonorder.class.php'; +require_once DOL_DOCUMENT_ROOT.'/core/class/commonobjectline.class.php'; +require_once DOL_DOCUMENT_ROOT.'/product/class/product.class.php'; +require_once DOL_DOCUMENT_ROOT.'/margin/lib/margins.lib.php'; +require_once DOL_DOCUMENT_ROOT.'/multicurrency/class/multicurrency.class.php'; /** * Class to manage customers orders @@ -45,12 +45,12 @@ class Commande extends CommonOrder /** * @var string ID to identify managed object */ - public $element='commande'; + public $element = 'commande'; /** * @var string Name of table without prefix where object is stored */ - public $table_element='commande'; + public $table_element = 'commande'; /** * @var string Name of subtable line @@ -178,7 +178,7 @@ class Commande extends CommonOrder */ public $date_commande; - public $date_livraison; // Date expected of shipment (date starting shipment, not the reception that occurs some days after) + public $date_livraison; // Date expected of shipment (date starting shipment, not the reception that occurs some days after) /** * @var int ID @@ -190,10 +190,10 @@ class Commande extends CommonOrder public $info_bits; public $rang; public $special_code; - public $source; // Order mode. How we received order (by phone, by email, ...) - public $extraparams=array(); + public $source; // Order mode. How we received order (by phone, by email, ...) + public $extraparams = array(); - public $linked_objects=array(); + public $linked_objects = array(); /** * @var int User author ID @@ -253,7 +253,7 @@ class Commande extends CommonOrder * Shipment on process */ const STATUS_SHIPMENTONPROCESS = 2; - const STATUS_ACCEPTED = 2; // For backward compatibility. Use key STATUS_SHIPMENTONPROCESS instead. + const STATUS_ACCEPTED = 2; // For backward compatibility. Use key STATUS_SHIPMENTONPROCESS instead. /** * Closed (Sent, billed or not) @@ -288,21 +288,21 @@ class Commande extends CommonOrder global $langs, $conf; $langs->load("order"); - if (! empty($conf->global->COMMANDE_ADDON)) + if (!empty($conf->global->COMMANDE_ADDON)) { - $mybool=false; + $mybool = false; $file = $conf->global->COMMANDE_ADDON.".php"; $classname = $conf->global->COMMANDE_ADDON; // Include file with class - $dirmodels=array_merge(array('/'), (array) $conf->modules_parts['models']); + $dirmodels = array_merge(array('/'), (array) $conf->modules_parts['models']); foreach ($dirmodels as $reldir) { $dir = dol_buildpath($reldir."core/modules/commande/"); // Load file with numbering class (if found) - $mybool|=@include_once $dir.$file; + $mybool |= @include_once $dir.$file; } if ($mybool === false) @@ -320,7 +320,7 @@ class Commande extends CommonOrder } else { - $this->error=$obj->error; + $this->error = $obj->error; //dol_print_error($this->db,get_class($this)."::getNextNumRef ".$obj->error); return ""; } @@ -356,15 +356,15 @@ class Commande extends CommonOrder return 0; } - if (! ((empty($conf->global->MAIN_USE_ADVANCED_PERMS) && ! empty($user->rights->commande->creer)) - || (! empty($conf->global->MAIN_USE_ADVANCED_PERMS) && ! empty($user->rights->commande->order_advance->validate)))) + if (!((empty($conf->global->MAIN_USE_ADVANCED_PERMS) && !empty($user->rights->commande->creer)) + || (!empty($conf->global->MAIN_USE_ADVANCED_PERMS) && !empty($user->rights->commande->order_advance->validate)))) { - $this->error='NotEnoughPermissions'; + $this->error = 'NotEnoughPermissions'; dol_syslog(get_class($this)."::valid ".$this->error, LOG_ERR); return -1; } - $now=dol_now(); + $now = dol_now(); $this->db->begin(); @@ -373,10 +373,10 @@ class Commande extends CommonOrder $soc->fetch($this->socid); // Class of company linked to order - $result=$soc->set_as_client(); + $result = $soc->set_as_client(); // 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($soc); } @@ -420,11 +420,11 @@ class Commande extends CommonOrder $mouvP = new MouvementStock($this->db); $mouvP->origin = &$this; // We decrement stock of product (and sub-products) - $result=$mouvP->livraison($user, $this->lines[$i]->fk_product, $idwarehouse, $this->lines[$i]->qty, $this->lines[$i]->subprice, $langs->trans("OrderValidatedInDolibarr", $num)); + $result = $mouvP->livraison($user, $this->lines[$i]->fk_product, $idwarehouse, $this->lines[$i]->qty, $this->lines[$i]->subprice, $langs->trans("OrderValidatedInDolibarr", $num)); if ($result < 0) { $error++; - $this->error=$mouvP->error; + $this->error = $mouvP->error; } } if ($error) break; @@ -432,15 +432,15 @@ class Commande extends CommonOrder } } - if (! $error && ! $notrigger) + if (!$error && !$notrigger) { // Call trigger - $result=$this->call_trigger('ORDER_VALIDATE', $user); + $result = $this->call_trigger('ORDER_VALIDATE', $user); if ($result < 0) $error++; // End call triggers } - if (! $error) + if (!$error) { $this->oldref = $this->ref; @@ -481,14 +481,14 @@ class Commande extends CommonOrder } // Set new ref and current status - if (! $error) + if (!$error) { $this->ref = $num; $this->statut = self::STATUS_VALIDATED; $this->brouillon = 0; } - if (! $error) + if (!$error) { $this->db->commit(); return 1; @@ -511,9 +511,9 @@ class Commande extends CommonOrder public function setDraft($user, $idwarehouse = -1) { //phpcs:enable - global $conf,$langs; + global $conf, $langs; - $error=0; + $error = 0; // Protection if ($this->statut <= self::STATUS_DRAFT) @@ -521,10 +521,10 @@ class Commande extends CommonOrder return 0; } - if (! ((empty($conf->global->MAIN_USE_ADVANCED_PERMS) && ! empty($user->rights->commande->creer)) - || (! empty($conf->global->MAIN_USE_ADVANCED_PERMS) && ! empty($user->rights->commande->order_advance->validate)))) + if (!((empty($conf->global->MAIN_USE_ADVANCED_PERMS) && !empty($user->rights->commande->creer)) + || (!empty($conf->global->MAIN_USE_ADVANCED_PERMS) && !empty($user->rights->commande->order_advance->validate)))) { - $this->error='Permission denied'; + $this->error = 'Permission denied'; return -1; } @@ -533,25 +533,25 @@ class Commande extends CommonOrder $this->db->begin(); $sql = "UPDATE ".MAIN_DB_PREFIX."commande"; - $sql.= " SET fk_statut = ".self::STATUS_DRAFT; - $sql.= " WHERE rowid = ".$this->id; + $sql .= " SET fk_statut = ".self::STATUS_DRAFT; + $sql .= " WHERE rowid = ".$this->id; if ($this->db->query($sql)) { - if (! $error) + if (!$error) { - $this->oldcopy= clone $this; + $this->oldcopy = clone $this; } // If stock is decremented on validate order, we must reincrement it - if (! empty($conf->stock->enabled) && $conf->global->STOCK_CALCULATE_ON_VALIDATE_ORDER == 1) + if (!empty($conf->stock->enabled) && $conf->global->STOCK_CALCULATE_ON_VALIDATE_ORDER == 1) { $result = 0; require_once DOL_DOCUMENT_ROOT.'/product/stock/class/mouvementstock.class.php'; $langs->load("agenda"); - $num=count($this->lines); + $num = count($this->lines); for ($i = 0; $i < $num; $i++) { if ($this->lines[$i]->fk_product > 0) @@ -559,30 +559,30 @@ class Commande extends CommonOrder $mouvP = new MouvementStock($this->db); $mouvP->origin = &$this; // We increment stock of product (and sub-products) - $result=$mouvP->reception($user, $this->lines[$i]->fk_product, $idwarehouse, $this->lines[$i]->qty, 0, $langs->trans("OrderBackToDraftInDolibarr", $this->ref)); - if ($result < 0) { $error++; $this->error=$mouvP->error; break; } + $result = $mouvP->reception($user, $this->lines[$i]->fk_product, $idwarehouse, $this->lines[$i]->qty, 0, $langs->trans("OrderBackToDraftInDolibarr", $this->ref)); + if ($result < 0) { $error++; $this->error = $mouvP->error; break; } } } } if (!$error) { // Call trigger - $result=$this->call_trigger('ORDER_UNVALIDATE', $user); + $result = $this->call_trigger('ORDER_UNVALIDATE', $user); if ($result < 0) $error++; } if (!$error) { - $this->statut=self::STATUS_DRAFT; + $this->statut = self::STATUS_DRAFT; $this->db->commit(); return 1; - }else { + } else { $this->db->rollback(); return -1; } } else { - $this->error=$this->db->error(); + $this->error = $this->db->error(); $this->db->rollback(); return -1; } @@ -600,7 +600,7 @@ class Commande extends CommonOrder public function set_reopen($user) { // phpcs:enable - $error=0; + $error = 0; if ($this->statut != self::STATUS_CANCELED && $this->statut != self::STATUS_CLOSED) { @@ -611,26 +611,26 @@ class Commande extends CommonOrder $this->db->begin(); $sql = 'UPDATE '.MAIN_DB_PREFIX.'commande'; - $sql.= ' SET fk_statut='.self::STATUS_VALIDATED.', facture=0'; - $sql.= ' WHERE rowid = '.$this->id; + $sql .= ' SET fk_statut='.self::STATUS_VALIDATED.', facture=0'; + $sql .= ' WHERE rowid = '.$this->id; dol_syslog(get_class($this)."::set_reopen", LOG_DEBUG); $resql = $this->db->query($sql); if ($resql) { // Call trigger - $result=$this->call_trigger('ORDER_REOPEN', $user); + $result = $this->call_trigger('ORDER_REOPEN', $user); if ($result < 0) $error++; // End call triggers } else { $error++; - $this->error=$this->db->lasterror(); + $this->error = $this->db->lasterror(); dol_print_error($this->db); } - if (! $error) + if (!$error) { $this->statut = self::STATUS_VALIDATED; $this->billed = 0; @@ -640,13 +640,13 @@ class Commande extends CommonOrder } else { - foreach($this->errors as $errmsg) + foreach ($this->errors as $errmsg) { dol_syslog(get_class($this)."::set_reopen ".$errmsg, LOG_ERR); - $this->error.=($this->error?', '.$errmsg:$errmsg); + $this->error .= ($this->error ? ', '.$errmsg : $errmsg); } $this->db->rollback(); - return -1*$error; + return -1 * $error; } } @@ -701,7 +701,7 @@ class Commande extends CommonOrder } else { - $this->error=$this->db->lasterror(); + $this->error = $this->db->lasterror(); $this->db->rollback(); return -1; @@ -719,72 +719,72 @@ class Commande extends CommonOrder */ public function cancel($idwarehouse = -1) { - global $conf,$user,$langs; + global $conf, $user, $langs; - $error=0; + $error = 0; $this->db->begin(); $sql = "UPDATE ".MAIN_DB_PREFIX."commande"; - $sql.= " SET fk_statut = ".self::STATUS_CANCELED; - $sql.= " WHERE rowid = ".$this->id; - $sql.= " AND fk_statut = ".self::STATUS_VALIDATED; + $sql .= " SET fk_statut = ".self::STATUS_CANCELED; + $sql .= " WHERE rowid = ".$this->id; + $sql .= " AND fk_statut = ".self::STATUS_VALIDATED; dol_syslog(get_class($this)."::cancel", LOG_DEBUG); if ($this->db->query($sql)) { // If stock is decremented on validate order, we must reincrement it - if (! empty($conf->stock->enabled) && $conf->global->STOCK_CALCULATE_ON_VALIDATE_ORDER == 1) + if (!empty($conf->stock->enabled) && $conf->global->STOCK_CALCULATE_ON_VALIDATE_ORDER == 1) { require_once DOL_DOCUMENT_ROOT.'/product/stock/class/mouvementstock.class.php'; $langs->load("agenda"); - $num=count($this->lines); + $num = count($this->lines); for ($i = 0; $i < $num; $i++) { if ($this->lines[$i]->fk_product > 0) { $mouvP = new MouvementStock($this->db); // We increment stock of product (and sub-products) - $result=$mouvP->reception($user, $this->lines[$i]->fk_product, $idwarehouse, $this->lines[$i]->qty, 0, $langs->trans("OrderCanceledInDolibarr", $this->ref)); // price is 0, we don't want WAP to be changed + $result = $mouvP->reception($user, $this->lines[$i]->fk_product, $idwarehouse, $this->lines[$i]->qty, 0, $langs->trans("OrderCanceledInDolibarr", $this->ref)); // price is 0, we don't want WAP to be changed if ($result < 0) { $error++; - $this->error=$mouvP->error; + $this->error = $mouvP->error; break; } } } } - if (! $error) + if (!$error) { // Call trigger - $result=$this->call_trigger('ORDER_CANCEL', $user); + $result = $this->call_trigger('ORDER_CANCEL', $user); if ($result < 0) $error++; // End call triggers } - if (! $error) + if (!$error) { - $this->statut=self::STATUS_CANCELED; + $this->statut = self::STATUS_CANCELED; $this->db->commit(); return 1; } else { - foreach($this->errors as $errmsg) + foreach ($this->errors as $errmsg) { dol_syslog(get_class($this)."::cancel ".$errmsg, LOG_ERR); - $this->error.=($this->error?', '.$errmsg:$errmsg); + $this->error .= ($this->error ? ', '.$errmsg : $errmsg); } $this->db->rollback(); - return -1*$error; + return -1 * $error; } } else { - $this->error=$this->db->error(); + $this->error = $this->db->error(); $this->db->rollback(); return -1; } @@ -800,17 +800,17 @@ class Commande extends CommonOrder */ public function create($user, $notrigger = 0) { - global $conf,$langs; - $error=0; + global $conf, $langs; + $error = 0; // Clean parameters - $this->brouillon = 1; // set command as draft + $this->brouillon = 1; // set command as draft // $date_commande is deprecated $date = ($this->date_commande ? $this->date_commande : $this->date); // 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); + 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)) { @@ -822,12 +822,12 @@ class Commande extends CommonOrder dol_syslog(get_class($this)."::create user=".$user->id); // 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 + $result = self::isExistingObject($this->element, 0, $this->ref); // Check ref is not yet used if ($result > 0) { - $this->error='ErrorRefAlreadyExists'; + $this->error = 'ErrorRefAlreadyExists'; dol_syslog(get_class($this)."::create ".$this->error, LOG_WARNING); $this->db->rollback(); return -1; @@ -925,7 +925,7 @@ class Commande extends CommonOrder // 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.')'; $result = $this->addline( $line->desc, @@ -958,7 +958,7 @@ class Commande extends CommonOrder { if ($result != self::STOCK_NOT_ENOUGH_FOR_ORDER) { - $this->error=$this->db->lasterror(); + $this->error = $this->db->lasterror(); dol_print_error($this->db); } $this->db->rollback(); @@ -971,8 +971,8 @@ class Commande extends CommonOrder } // update ref - $initialref='(PROV'.$this->id.')'; - if (! empty($this->ref)) $initialref=$this->ref; + $initialref = '(PROV'.$this->id.')'; + if (!empty($this->ref)) $initialref = $this->ref; $sql = 'UPDATE '.MAIN_DB_PREFIX."commande SET ref='".$this->db->escape($initialref)."' WHERE rowid=".$this->id; if ($this->db->query($sql)) @@ -981,24 +981,24 @@ class Commande extends CommonOrder { $this->ref = $initialref; - 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 + $this->linked_objects = $this->linkedObjectsIds; // TODO Replace linked_objects with linkedObjectsIds } // Add object linked - if (! $error && $this->id && is_array($this->linked_objects) && ! empty($this->linked_objects)) + if (!$error && $this->id && is_array($this->linked_objects) && !empty($this->linked_objects)) { - foreach($this->linked_objects as $origin => $tmp_origin_id) + 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) + foreach ($tmp_origin_id as $origin_id) { $ret = $this->add_object_linked($origin, $origin_id); - if (! $ret) + if (!$ret) { - $this->error=$this->db->lasterror(); + $this->error = $this->db->lasterror(); $error++; } } @@ -1007,22 +1007,22 @@ class Commande extends CommonOrder { $origin_id = $tmp_origin_id; $ret = $this->add_object_linked($origin, $origin_id); - if (! $ret) + if (!$ret) { - $this->error=$this->db->lasterror(); + $this->error = $this->db->lasterror(); $error++; } } } } - 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 { - require_once DOL_DOCUMENT_ROOT . '/expedition/class/expedition.class.php'; + require_once DOL_DOCUMENT_ROOT.'/expedition/class/expedition.class.php'; $exp = new Expedition($this->db); $exp->fetch($this->origin_id); $exp->fetchObjectLinked(); @@ -1039,36 +1039,36 @@ class Commande extends CommonOrder } $sqlcontact = "SELECT ctc.code, ctc.source, ec.fk_socpeople FROM ".MAIN_DB_PREFIX."element_contact as ec, ".MAIN_DB_PREFIX."c_type_contact as ctc"; - $sqlcontact.= " WHERE element_id = ".$originidforcontact." AND ec.fk_c_type_contact = ctc.rowid AND ctc.element = '".$originforcontact."'"; + $sqlcontact .= " WHERE element_id = ".$originidforcontact." AND ec.fk_c_type_contact = ctc.rowid AND ctc.element = '".$originforcontact."'"; $resqlcontact = $this->db->query($sqlcontact); if ($resqlcontact) { - while($objcontact = $this->db->fetch_object($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 + $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); } } - if (! $error) + if (!$error) { - $result=$this->insertExtraFields(); + $result = $this->insertExtraFields(); if ($result < 0) $error++; } - if (! $error && ! $notrigger) + if (!$error && !$notrigger) { // Call trigger - $result=$this->call_trigger('ORDER_CREATE', $user); + $result = $this->call_trigger('ORDER_CREATE', $user); if ($result < 0) $error++; // End call triggers } - if (! $error) + if (!$error) { $this->db->commit(); return $this->id; @@ -1076,12 +1076,12 @@ class Commande extends CommonOrder else { $this->db->rollback(); - return -1*$error; + return -1 * $error; } } else { - $this->error=$this->db->lasterror(); + $this->error = $this->db->lasterror(); $this->db->rollback(); return -1; } @@ -1105,55 +1105,55 @@ class Commande extends CommonOrder */ public function createFromClone(User $user, $socid = 0) { - global $conf, $user,$hookmanager; + global $conf, $user, $hookmanager; - $error=0; + $error = 0; $this->db->begin(); // get lines 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); - $this->fk_project = 0; - $this->fk_delivery_address = 0; + $this->socid = $objsoc->id; + $this->cond_reglement_id = (!empty($objsoc->cond_reglement_id) ? $objsoc->cond_reglement_id : 0); + $this->mode_reglement_id = (!empty($objsoc->mode_reglement_id) ? $objsoc->mode_reglement_id : 0); + $this->fk_project = 0; + $this->fk_delivery_address = 0; } // TODO Change product price if multi-prices } - $this->id=0; + $this->id = 0; $this->ref = ''; - $this->statut=self::STATUS_DRAFT; + $this->statut = self::STATUS_DRAFT; // Clear fields $this->user_author_id = $user->id; $this->user_valid = ''; - $this->date = dol_now(); - $this->date_commande = dol_now(); + $this->date = dol_now(); + $this->date_commande = dol_now(); $this->date_creation = ''; $this->date_validation = ''; if (empty($conf->global->MAIN_KEEP_REF_CUSTOMER_ON_CLONING)) $this->ref_client = ''; // Create clone $this->context['createfromclone'] = 'createfromclone'; - $result=$this->create($user); + $result = $this->create($user); if ($result < 0) $error++; - if (! $error) + if (!$error) { // copy internal contacts if ($this->copy_linked_contact($objFrom, 'internal') < 0) @@ -1162,7 +1162,7 @@ class Commande extends CommonOrder } } - if (! $error) + if (!$error) { // copy external contacts if same company if ($this->socid == $objFrom->socid) @@ -1172,14 +1172,14 @@ class Commande extends CommonOrder } } - if (! $error) + if (!$error) { // Hook of thirdparty module if (is_object($hookmanager)) { - $parameters=array('objFrom'=>$objFrom); - $action=''; - $reshook=$hookmanager->executeHooks('createFrom', $parameters, $this, $action); // Note that $action and $object may have been modified by some hooks + $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++; } } @@ -1187,7 +1187,7 @@ class Commande extends CommonOrder unset($this->context['createfromclone']); // End - if (! $error) + if (!$error) { $this->db->commit(); return $this->id; @@ -1213,13 +1213,13 @@ class Commande extends CommonOrder dol_include_once('/core/class/extrafields.class.php'); - $error=0; + $error = 0; $this->date_commande = dol_now(); $this->source = 0; - $num=count($object->lines); + $num = count($object->lines); for ($i = 0; $i < $num; $i++) { $line = new OrderLine($this->db); @@ -1242,9 +1242,9 @@ class Commande extends CommonOrder $line->rang = $object->lines[$i]->rang; $line->special_code = $object->lines[$i]->special_code; $line->fk_parent_line = $object->lines[$i]->fk_parent_line; - $line->fk_unit = $object->lines[$i]->fk_unit; + $line->fk_unit = $object->lines[$i]->fk_unit; - $line->date_start = $object->lines[$i]->date_start; + $line->date_start = $object->lines[$i]->date_start; $line->date_end = $object->lines[$i]->date_end; $line->fk_fournprice = $object->lines[$i]->fk_fournprice; @@ -1255,7 +1255,7 @@ class Commande extends CommonOrder // get extrafields from original line $object->lines[$i]->fetch_optionals(); - foreach($object->lines[$i]->array_options as $options_key => $value) + foreach ($object->lines[$i]->array_options as $options_key => $value) $line->array_options[$options_key] = $value; $this->lines[$i] = $line; @@ -1282,8 +1282,8 @@ class Commande extends CommonOrder $this->note_public = $object->note_public; } - $this->origin = $object->element; - $this->origin_id = $object->id; + $this->origin = $object->element; + $this->origin_id = $object->id; // get extrafields from original line $object->fetch_optionals($object->id); @@ -1291,14 +1291,14 @@ class Commande extends CommonOrder $e = new ExtraFields($this->db); $element_extrafields = $e->fetch_name_optionals_label($this->table_element); - foreach($object->array_options as $options_key => $value) { - if(array_key_exists(str_replace('options_', '', $options_key), $element_extrafields)){ + foreach ($object->array_options as $options_key => $value) { + if (array_key_exists(str_replace('options_', '', $options_key), $element_extrafields)) { $this->array_options[$options_key] = $value; } } // Possibility to add external linked objects with hooks $this->linked_objects[$this->origin] = $this->origin_id; - if (is_array($object->other_linked_objects) && ! empty($object->other_linked_objects)) + if (is_array($object->other_linked_objects) && !empty($object->other_linked_objects)) { $this->linked_objects = array_merge($this->linked_objects, $object->other_linked_objects); } @@ -1310,12 +1310,12 @@ class Commande extends CommonOrder // Actions hooked (by external module) $hookmanager->initHooks(array('orderdao')); - $parameters=array('objFrom'=>$object); - $action=''; - $reshook=$hookmanager->executeHooks('createFrom', $parameters, $this, $action); // Note that $action and $object may have been modified by some hooks + $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 (! $error) + if (!$error) { // Ne pas passer par la commande provisoire if ($conf->global->COMMANDE_VALID_AFTER_CLOSE_PROPAL == 1) @@ -1374,8 +1374,8 @@ class Commande extends CommonOrder global $mysoc, $conf, $langs, $user; $logtext = "::addline commandeid=$this->id, desc=$desc, pu_ht=$pu_ht, qty=$qty, txtva=$txtva, fk_product=$fk_product, remise_percent=$remise_percent"; - $logtext.= ", info_bits=$info_bits, fk_remise_except=$fk_remise_except, price_base_type=$price_base_type, pu_ttc=$pu_ttc, date_start=$date_start"; - $logtext.= ", date_end=$date_end, type=$type special_code=$special_code, fk_unit=$fk_unit, origin=$origin, origin_id=$origin_id, pu_ht_devise=$pu_ht_devise"; + $logtext .= ", info_bits=$info_bits, fk_remise_except=$fk_remise_except, price_base_type=$price_base_type, pu_ttc=$pu_ttc, date_start=$date_start"; + $logtext .= ", date_end=$date_end, type=$type special_code=$special_code, fk_unit=$fk_unit, origin=$origin, origin_id=$origin_id, pu_ht_devise=$pu_ht_devise"; dol_syslog(get_class($this).$logtext, LOG_DEBUG); if ($this->statut == self::STATUS_DRAFT) @@ -1383,60 +1383,60 @@ class Commande extends CommonOrder 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($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($this->fk_multicurrency)) $this->fk_multicurrency=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($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($this->fk_multicurrency)) $this->fk_multicurrency = 0; - $remise_percent=price2num($remise_percent); - $qty=price2num($qty); - $pu_ht=price2num($pu_ht); - $pu_ht_devise=price2num($pu_ht_devise); - $pu_ttc=price2num($pu_ttc); - $pa_ht=price2num($pa_ht); + $remise_percent = price2num($remise_percent); + $qty = price2num($qty); + $pu_ht = price2num($pu_ht); + $pu_ht_devise = price2num($pu_ht_devise); + $pu_ttc = price2num($pu_ttc); + $pa_ht = price2num($pa_ht); if (!preg_match('/\((.*)\)/', $txtva)) { - $txtva = price2num($txtva); // $txtva can have format '5,1' or '5.1' or '5.1(XXX)', we must clean only if '5,1' + $txtva = price2num($txtva); // $txtva can have format '5,1' or '5.1' or '5.1(XXX)', we must clean only if '5,1' } $txlocaltax1 = price2num($txlocaltax1); $txlocaltax2 = price2num($txlocaltax2); - if ($price_base_type=='HT') + if ($price_base_type == 'HT') { - $pu=$pu_ht; + $pu = $pu_ht; } else { - $pu=$pu_ttc; + $pu = $pu_ttc; } - $label=trim($label); - $desc=trim($desc); + $label = trim($label); + $desc = trim($desc); // Check parameters if ($type < 0) return -1; if ($date_start && $date_end && $date_start > $date_end) { $langs->load("errors"); - $this->error=$langs->trans('ErrorStartDateGreaterEnd'); + $this->error = $langs->trans('ErrorStartDateGreaterEnd'); return -1; } $this->db->begin(); - $product_type=$type; + $product_type = $type; if (!empty($fk_product)) { - $product=new Product($this->db); - $result=$product->fetch($fk_product); - $product_type=$product->type; + $product = new Product($this->db); + $result = $product->fetch($fk_product); + $product_type = $product->type; - if (! empty($conf->global->STOCK_MUST_BE_ENOUGH_FOR_ORDER) && $product_type == 0 && $product->stock_reel < $qty) + if (!empty($conf->global->STOCK_MUST_BE_ENOUGH_FOR_ORDER) && $product_type == 0 && $product->stock_reel < $qty) { $langs->load("errors"); - $this->error=$langs->trans('ErrorStockIsNotEnoughToAddProductOnOrder', $product->ref); + $this->error = $langs->trans('ErrorStockIsNotEnoughToAddProductOnOrder', $product->ref); dol_syslog(get_class($this)."::addline error=Product ".$product->ref.": ".$this->error, LOG_ERR); $this->db->rollback(); return self::STOCK_NOT_ENOUGH_FOR_ORDER; @@ -1447,14 +1447,14 @@ class Commande extends CommonOrder // TRES IMPORTANT: C'est au moment de l'insertion ligne qu'on doit stocker // la part ht, tva et ttc, et ce au niveau de la ligne qui a son propre taux tva. - $localtaxes_type=getLocalTaxesFromRate($txtva, 0, $this->thirdparty, $mysoc); + $localtaxes_type = getLocalTaxesFromRate($txtva, 0, $this->thirdparty, $mysoc); // Clean vat code - $vat_src_code=''; + $vat_src_code = ''; if (preg_match('/\((.*)\)/', $txtva, $reg)) { $vat_src_code = $reg[1]; - $txtva = preg_replace('/\s*\(.*\)/', '', $txtva); // Remove code into vatrate. + $txtva = preg_replace('/\s*\(.*\)/', '', $txtva); // Remove code into vatrate. } $tabprice = calcul_price_total($qty, $pu, $remise_percent, $txtva, $txlocaltax1, $txlocaltax2, 0, $price_base_type, $info_bits, $product_type, $mysoc, $localtaxes_type, 100, $this->multicurrency_tx, $pu_ht_devise); @@ -1565,7 +1565,7 @@ class Commande extends CommonOrder if ($result > 0) { $this->db->commit(); - return $this->line->rowid; + return $this->line->id; } else { @@ -1575,7 +1575,7 @@ class Commande extends CommonOrder } else { - $this->error=$this->line->error; + $this->error = $this->line->error; dol_syslog(get_class($this)."::addline error=".$this->error, LOG_ERR); $this->db->rollback(); return -2; @@ -1609,49 +1609,49 @@ class Commande extends CommonOrder // phpcs:enable global $conf, $mysoc; - if (! $qty) $qty = 1; + if (!$qty) $qty = 1; if ($idproduct > 0) { - $prod=new Product($this->db); + $prod = new Product($this->db); $prod->fetch($idproduct); $tva_tx = get_default_tva($mysoc, $this->thirdparty, $prod->id); $tva_npr = get_default_npr($mysoc, $this->thirdparty, $prod->id); - if (empty($tva_tx)) $tva_npr=0; - $vat_src_code = ''; // May be defined into tva_tx + if (empty($tva_tx)) $tva_npr = 0; + $vat_src_code = ''; // May be defined into tva_tx - $localtax1_tx=get_localtax($tva_tx, 1, $this->thirdparty, $mysoc, $tva_npr); - $localtax2_tx=get_localtax($tva_tx, 2, $this->thirdparty, $mysoc, $tva_npr); + $localtax1_tx = get_localtax($tva_tx, 1, $this->thirdparty, $mysoc, $tva_npr); + $localtax2_tx = get_localtax($tva_tx, 2, $this->thirdparty, $mysoc, $tva_npr); // multiprix - if($conf->global->PRODUIT_MULTIPRICES && $this->thirdparty->price_level) { + if ($conf->global->PRODUIT_MULTIPRICES && $this->thirdparty->price_level) { $price = $prod->multiprices[$this->thirdparty->price_level]; } else { $price = $prod->price; } - $line=new OrderLine($this->db); + $line = new OrderLine($this->db); $line->context = $this->context; - $line->fk_product=$idproduct; - $line->desc=$prod->description; - $line->qty=$qty; - $line->subprice=$price; - $line->remise_percent=$remise_percent; - $line->vat_src_code=$vat_src_code; - $line->tva_tx=$tva_tx; - $line->localtax1_tx=$localtax1_tx; - $line->localtax2_tx=$localtax2_tx; - $line->ref=$prod->ref; - $line->libelle=$prod->label; - $line->product_desc=$prod->description; - $line->fk_unit=$prod->fk_unit; + $line->fk_product = $idproduct; + $line->desc = $prod->description; + $line->qty = $qty; + $line->subprice = $price; + $line->remise_percent = $remise_percent; + $line->vat_src_code = $vat_src_code; + $line->tva_tx = $tva_tx; + $line->localtax1_tx = $localtax1_tx; + $line->localtax2_tx = $localtax2_tx; + $line->ref = $prod->ref; + $line->libelle = $prod->label; + $line->product_desc = $prod->description; + $line->fk_unit = $prod->fk_unit; // Save the start and end date of the line in the object if ($date_start) { $line->date_start = $date_start; } - if ($date_end) { $line->date_end = $date_end; } + if ($date_end) { $line->date_end = $date_end; } $this->lines[] = $line; @@ -1732,56 +1732,56 @@ class Commande extends CommonOrder $obj = $this->db->fetch_object($result); if ($obj) { - $this->id = $obj->rowid; - $this->entity = $obj->entity; + $this->id = $obj->rowid; + $this->entity = $obj->entity; - $this->ref = $obj->ref; - $this->ref_client = $obj->ref_client; - $this->ref_customer = $obj->ref_client; + $this->ref = $obj->ref; + $this->ref_client = $obj->ref_client; + $this->ref_customer = $obj->ref_client; $this->ref_ext = $obj->ref_ext; $this->ref_int = $obj->ref_int; - $this->socid = $obj->fk_soc; - $this->statut = $obj->fk_statut; - $this->user_author_id = $obj->fk_user_author; - $this->user_valid = $obj->fk_user_valid; + $this->socid = $obj->fk_soc; + $this->statut = $obj->fk_statut; + $this->user_author_id = $obj->fk_user_author; + $this->user_valid = $obj->fk_user_valid; $this->total_ht = $obj->total_ht; $this->total_tva = $obj->total_tva; $this->total_localtax1 = $obj->total_localtax1; $this->total_localtax2 = $obj->total_localtax2; $this->total_ttc = $obj->total_ttc; - $this->date = $this->db->jdate($obj->date_commande); + $this->date = $this->db->jdate($obj->date_commande); $this->date_commande = $this->db->jdate($obj->date_commande); $this->date_creation = $this->db->jdate($obj->date_creation); - $this->date_validation = $this->db->jdate($obj->date_valid); - $this->date_modification = $this->db->jdate($obj->tms); + $this->date_validation = $this->db->jdate($obj->date_valid); + $this->date_modification = $this->db->jdate($obj->tms); $this->remise = $obj->remise; $this->remise_percent = $obj->remise_percent; $this->remise_absolue = $obj->remise_absolue; $this->source = $obj->source; $this->billed = $obj->billed; - $this->note = $obj->note_private; // deprecated - $this->note_private = $obj->note_private; - $this->note_public = $obj->note_public; - $this->fk_project = $obj->fk_project; - $this->modelpdf = $obj->model_pdf; - $this->last_main_doc = $obj->last_main_doc; + $this->note = $obj->note_private; // deprecated + $this->note_private = $obj->note_private; + $this->note_public = $obj->note_public; + $this->fk_project = $obj->fk_project; + $this->modelpdf = $obj->model_pdf; + $this->last_main_doc = $obj->last_main_doc; $this->mode_reglement_id = $obj->fk_mode_reglement; $this->mode_reglement_code = $obj->mode_reglement_code; $this->mode_reglement = $obj->mode_reglement_libelle; $this->cond_reglement_id = $obj->fk_cond_reglement; $this->cond_reglement_code = $obj->cond_reglement_code; $this->cond_reglement = $obj->cond_reglement_libelle; - $this->cond_reglement_doc = $obj->cond_reglement_libelle_doc; - $this->fk_account = $obj->fk_account; - $this->availability_id = $obj->fk_availability; + $this->cond_reglement_doc = $obj->cond_reglement_libelle_doc; + $this->fk_account = $obj->fk_account; + $this->availability_id = $obj->fk_availability; $this->availability_code = $obj->availability_code; $this->availability = $obj->availability_label; $this->demand_reason_id = $obj->fk_input_reason; - $this->demand_reason_code = $obj->demand_reason_code; - $this->date_livraison = $this->db->jdate($obj->date_livraison); - $this->shipping_method_id = ($obj->fk_shipping_method>0)?$obj->fk_shipping_method:null; - $this->warehouse_id = ($obj->fk_warehouse>0)?$obj->fk_warehouse:null; - $this->fk_delivery_address = $obj->fk_delivery_address; + $this->demand_reason_code = $obj->demand_reason_code; + $this->date_livraison = $this->db->jdate($obj->date_livraison); + $this->shipping_method_id = ($obj->fk_shipping_method > 0) ? $obj->fk_shipping_method : null; + $this->warehouse_id = ($obj->fk_warehouse > 0) ? $obj->fk_warehouse : null; + $this->fk_delivery_address = $obj->fk_delivery_address; $this->module_source = $obj->module_source; $this->pos_source = $obj->pos_source; @@ -1792,15 +1792,15 @@ class Commande extends CommonOrder // Multicurrency $this->fk_multicurrency = $obj->fk_multicurrency; - $this->multicurrency_code = $obj->multicurrency_code; + $this->multicurrency_code = $obj->multicurrency_code; $this->multicurrency_tx = $obj->multicurrency_tx; - $this->multicurrency_total_ht = $obj->multicurrency_total_ht; + $this->multicurrency_total_ht = $obj->multicurrency_total_ht; $this->multicurrency_total_tva = $obj->multicurrency_total_tva; $this->multicurrency_total_ttc = $obj->multicurrency_total_ttc; - $this->extraparams = (array) json_decode($obj->extraparams, true); + $this->extraparams = (array) json_decode($obj->extraparams, true); - $this->lines = array(); + $this->lines = array(); if ($this->statut == self::STATUS_DRAFT) $this->brouillon = 1; @@ -1813,7 +1813,7 @@ class Commande extends CommonOrder /* * Lines */ - $result=$this->fetch_lines(); + $result = $this->fetch_lines(); if ($result < 0) { return -3; @@ -1822,13 +1822,13 @@ class Commande extends CommonOrder } else { - $this->error='Order with id '.$id.' not found sql='.$sql; + $this->error = 'Order with id '.$id.' not found sql='.$sql; return 0; } } else { - $this->error=$this->db->error(); + $this->error = $this->db->error(); return -1; } } @@ -1851,42 +1851,42 @@ class Commande extends CommonOrder $this->db->begin(); - $remise=new DiscountAbsolute($this->db); - $result=$remise->fetch($idremise); + $remise = new DiscountAbsolute($this->db); + $result = $remise->fetch($idremise); if ($result > 0) { if ($remise->fk_facture) // Protection against multiple submission { - $this->error=$langs->trans("ErrorDiscountAlreadyUsed"); + $this->error = $langs->trans("ErrorDiscountAlreadyUsed"); $this->db->rollback(); return -5; } $line = new OrderLine($this->db); - $line->fk_commande=$this->id; - $line->fk_remise_except=$remise->id; - $line->desc=$remise->description; // Description ligne - $line->vat_src_code=$remise->vat_src_code; - $line->tva_tx=$remise->tva_tx; - $line->subprice=-$remise->amount_ht; - $line->price=-$remise->amount_ht; - $line->fk_product=0; // Id produit predefini - $line->qty=1; - $line->remise=0; - $line->remise_percent=0; - $line->rang=-1; - $line->info_bits=2; + $line->fk_commande = $this->id; + $line->fk_remise_except = $remise->id; + $line->desc = $remise->description; // Description ligne + $line->vat_src_code = $remise->vat_src_code; + $line->tva_tx = $remise->tva_tx; + $line->subprice = -$remise->amount_ht; + $line->price = -$remise->amount_ht; + $line->fk_product = 0; // Id produit predefini + $line->qty = 1; + $line->remise = 0; + $line->remise_percent = 0; + $line->rang = -1; + $line->info_bits = 2; $line->total_ht = -$remise->amount_ht; $line->total_tva = -$remise->amount_tva; $line->total_ttc = -$remise->amount_ttc; - $result=$line->insert(); + $result = $line->insert(); if ($result > 0) { - $result=$this->update_price(1); + $result = $this->update_price(1); if ($result > 0) { $this->db->commit(); @@ -1900,7 +1900,7 @@ class Commande extends CommonOrder } else { - $this->error=$line->error; + $this->error = $line->error; $this->db->rollback(); return -2; } @@ -1925,18 +1925,18 @@ class Commande extends CommonOrder { global $langs, $conf; // phpcs:enable - $this->lines=array(); + $this->lines = array(); $sql = 'SELECT l.rowid, l.fk_product, l.fk_parent_line, l.product_type, l.fk_commande, l.label as custom_label, l.description, l.price, l.qty, l.vat_src_code, l.tva_tx,'; - $sql.= ' l.localtax1_tx, l.localtax2_tx, l.localtax1_type, l.localtax2_type, l.fk_remise_except, l.remise_percent, l.subprice, l.fk_product_fournisseur_price as fk_fournprice, l.buy_price_ht as pa_ht, l.rang, l.info_bits, l.special_code,'; - $sql.= ' l.total_ht, l.total_ttc, l.total_tva, l.total_localtax1, l.total_localtax2, l.date_start, l.date_end,'; - $sql.= ' l.fk_unit,'; - $sql.= ' l.fk_multicurrency, l.multicurrency_code, l.multicurrency_subprice, l.multicurrency_total_ht, l.multicurrency_total_tva, l.multicurrency_total_ttc,'; - $sql.= ' p.ref as product_ref, p.description as product_desc, p.fk_product_type, p.label as product_label, p.tobatch as product_tobatch,'; - $sql.= ' p.weight, p.weight_units, p.volume, p.volume_units'; - $sql.= ' FROM '.MAIN_DB_PREFIX.'commandedet as l'; - $sql.= ' LEFT JOIN '.MAIN_DB_PREFIX.'product as p ON (p.rowid = l.fk_product)'; - $sql.= ' WHERE l.fk_commande = '.$this->id; + $sql .= ' l.localtax1_tx, l.localtax2_tx, l.localtax1_type, l.localtax2_type, l.fk_remise_except, l.remise_percent, l.subprice, l.fk_product_fournisseur_price as fk_fournprice, l.buy_price_ht as pa_ht, l.rang, l.info_bits, l.special_code,'; + $sql .= ' l.total_ht, l.total_ttc, l.total_tva, l.total_localtax1, l.total_localtax2, l.date_start, l.date_end,'; + $sql .= ' l.fk_unit,'; + $sql .= ' l.fk_multicurrency, l.multicurrency_code, l.multicurrency_subprice, l.multicurrency_total_ht, l.multicurrency_total_tva, l.multicurrency_total_ttc,'; + $sql .= ' p.ref as product_ref, p.description as product_desc, p.fk_product_type, p.label as product_label, p.tobatch as product_tobatch,'; + $sql .= ' p.weight, p.weight_units, p.volume, p.volume_units'; + $sql .= ' FROM '.MAIN_DB_PREFIX.'commandedet as l'; + $sql .= ' LEFT JOIN '.MAIN_DB_PREFIX.'product as p ON (p.rowid = l.fk_product)'; + $sql .= ' WHERE l.fk_commande = '.$this->id; if ($only_product) $sql .= ' AND p.fk_product_type = 0'; $sql .= ' ORDER BY l.rang, l.rowid'; @@ -1959,7 +1959,7 @@ class Commande extends CommonOrder $line->commande_id = $objp->fk_commande; $line->label = $objp->custom_label; $line->desc = $objp->description; - $line->description = $objp->description; // Description line + $line->description = $objp->description; // Description line $line->product_type = $objp->product_type; $line->qty = $objp->qty; @@ -1979,23 +1979,23 @@ class Commande extends CommonOrder $line->remise_percent = $objp->remise_percent; $line->price = $objp->price; $line->fk_product = $objp->fk_product; - $line->fk_fournprice = $objp->fk_fournprice; - $marginInfos = getMarginInfos($objp->subprice, $objp->remise_percent, $objp->tva_tx, $objp->localtax1_tx, $objp->localtax2_tx, $line->fk_fournprice, $objp->pa_ht); - $line->pa_ht = $marginInfos[0]; + $line->fk_fournprice = $objp->fk_fournprice; + $marginInfos = getMarginInfos($objp->subprice, $objp->remise_percent, $objp->tva_tx, $objp->localtax1_tx, $objp->localtax2_tx, $line->fk_fournprice, $objp->pa_ht); + $line->pa_ht = $marginInfos[0]; $line->marge_tx = $marginInfos[1]; $line->marque_tx = $marginInfos[2]; $line->rang = $objp->rang; $line->info_bits = $objp->info_bits; - $line->special_code = $objp->special_code; - $line->fk_parent_line = $objp->fk_parent_line; + $line->special_code = $objp->special_code; + $line->fk_parent_line = $objp->fk_parent_line; - $line->ref = $objp->product_ref; - $line->product_ref = $objp->product_ref; - $line->libelle = $objp->product_label; - $line->product_label = $objp->product_label; + $line->ref = $objp->product_ref; + $line->product_ref = $objp->product_ref; + $line->libelle = $objp->product_label; + $line->product_label = $objp->product_label; $line->product_desc = $objp->product_desc; $line->product_tobatch = $objp->product_tobatch; - $line->fk_product_type = $objp->fk_product_type; // Produit ou service + $line->fk_product_type = $objp->fk_product_type; // Produit ou service $line->fk_unit = $objp->fk_unit; $line->weight = $objp->weight; @@ -2007,8 +2007,8 @@ class Commande extends CommonOrder $line->date_end = $this->db->jdate($objp->date_end); // Multicurrency - $line->fk_multicurrency = $objp->fk_multicurrency; - $line->multicurrency_code = $objp->multicurrency_code; + $line->fk_multicurrency = $objp->fk_multicurrency; + $line->multicurrency_code = $objp->multicurrency_code; $line->multicurrency_subprice = $objp->multicurrency_subprice; $line->multicurrency_total_ht = $objp->multicurrency_total_ht; $line->multicurrency_total_tva = $objp->multicurrency_total_tva; @@ -2034,7 +2034,7 @@ class Commande extends CommonOrder } else { - $this->error=$this->db->error(); + $this->error = $this->db->error(); return -3; } } @@ -2047,8 +2047,8 @@ class Commande extends CommonOrder */ public function getNbOfProductsLines() { - $nb=0; - foreach($this->lines as $line) + $nb = 0; + foreach ($this->lines as $line) { if ($line->product_type == 0) $nb++; } @@ -2062,8 +2062,8 @@ class Commande extends CommonOrder */ public function getNbOfServicesLines() { - $nb=0; - foreach($this->lines as $line) + $nb = 0; + foreach ($this->lines as $line) { if ($line->product_type == 1) $nb++; } @@ -2080,11 +2080,11 @@ class Commande extends CommonOrder $nb = 0; $sql = 'SELECT COUNT(DISTINCT ed.fk_expedition) as nb'; - $sql.= ' FROM '.MAIN_DB_PREFIX.'expeditiondet as ed,'; - $sql.= ' '.MAIN_DB_PREFIX.'commandedet as cd'; - $sql.= ' WHERE'; - $sql.= ' ed.fk_origin_line = cd.rowid'; - $sql.= ' AND cd.fk_commande =' .$this->id; + $sql .= ' FROM '.MAIN_DB_PREFIX.'expeditiondet as ed,'; + $sql .= ' '.MAIN_DB_PREFIX.'commandedet as cd'; + $sql .= ' WHERE'; + $sql .= ' ed.fk_origin_line = cd.rowid'; + $sql .= ' AND cd.fk_commande ='.$this->id; //print $sql; dol_syslog(get_class($this)."::getNbOfShipments", LOG_DEBUG); @@ -2099,7 +2099,7 @@ class Commande extends CommonOrder } else { - $this->error=$this->db->lasterror(); + $this->error = $this->db->lasterror(); return -1; } } @@ -2116,17 +2116,17 @@ class Commande extends CommonOrder $this->expeditions = array(); $sql = 'SELECT cd.rowid, cd.fk_product,'; - $sql.= ' sum(ed.qty) as qty'; - $sql.= ' FROM '.MAIN_DB_PREFIX.'expeditiondet as ed,'; - if ($filtre_statut >= 0) $sql.= ' '.MAIN_DB_PREFIX.'expedition as e,'; - $sql.= ' '.MAIN_DB_PREFIX.'commandedet as cd'; - $sql.= ' WHERE'; - if ($filtre_statut >= 0) $sql.= ' ed.fk_expedition = e.rowid AND'; - $sql.= ' ed.fk_origin_line = 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; - $sql.= ' GROUP BY cd.rowid, cd.fk_product'; + $sql .= ' sum(ed.qty) as qty'; + $sql .= ' FROM '.MAIN_DB_PREFIX.'expeditiondet as ed,'; + if ($filtre_statut >= 0) $sql .= ' '.MAIN_DB_PREFIX.'expedition as e,'; + $sql .= ' '.MAIN_DB_PREFIX.'commandedet as cd'; + $sql .= ' WHERE'; + if ($filtre_statut >= 0) $sql .= ' ed.fk_expedition = e.rowid AND'; + $sql .= ' ed.fk_origin_line = 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; + $sql .= ' GROUP BY cd.rowid, cd.fk_product'; //print $sql; dol_syslog(get_class($this)."::loadExpeditions", LOG_DEBUG); @@ -2146,7 +2146,7 @@ class Commande extends CommonOrder } else { - $this->error=$this->db->lasterror(); + $this->error = $this->db->lasterror(); return -1; } } @@ -2163,11 +2163,11 @@ class Commande extends CommonOrder { // phpcs:enable $sql = 'SELECT count(*)'; - $sql.= ' FROM '.MAIN_DB_PREFIX.'expedition as e'; - $sql.= ', '.MAIN_DB_PREFIX.'element_element as el'; - $sql.= ' WHERE el.fk_source = '.$this->id; - $sql.= " AND el.fk_target = e.rowid"; - $sql.= " AND el.targettype = 'shipping'"; + $sql .= ' FROM '.MAIN_DB_PREFIX.'expedition as e'; + $sql .= ', '.MAIN_DB_PREFIX.'element_element as el'; + $sql .= ' WHERE el.fk_source = '.$this->id; + $sql .= " AND el.fk_target = e.rowid"; + $sql .= " AND el.targettype = 'shipping'"; $resql = $this->db->query($sql); if ($resql) @@ -2193,16 +2193,16 @@ class Commande extends CommonOrder $this->stocks = array(); // Tableau des id de produit de la commande - $array_of_product=array(); + $array_of_product = array(); // Recherche total en stock pour chaque produit // TODO $array_of_product est défini vide juste au dessus !! if (count($array_of_product)) { $sql = "SELECT fk_product, sum(ps.reel) as total"; - $sql.= " FROM ".MAIN_DB_PREFIX."product_stock as ps"; - $sql.= " WHERE ps.fk_product IN (".join(',', $array_of_product).")"; - $sql.= ' GROUP BY fk_product '; + $sql .= " FROM ".MAIN_DB_PREFIX."product_stock as ps"; + $sql .= " WHERE ps.fk_product IN (".join(',', $array_of_product).")"; + $sql .= ' GROUP BY fk_product '; $resql = $this->db->query($sql); if ($resql) { @@ -2234,8 +2234,8 @@ class Commande extends CommonOrder $this->db->begin(); $sql = "SELECT fk_product, qty"; - $sql.= " FROM ".MAIN_DB_PREFIX."commandedet"; - $sql.= " WHERE rowid = ".$lineid; + $sql .= " FROM ".MAIN_DB_PREFIX."commandedet"; + $sql .= " WHERE rowid = ".$lineid; $result = $this->db->query($sql); if ($result) @@ -2255,7 +2255,7 @@ class Commande extends CommonOrder if ($line->delete($user) > 0) { - $result=$this->update_price(1); + $result = $this->update_price(1); if ($result > 0) { @@ -2265,14 +2265,14 @@ class Commande extends CommonOrder else { $this->db->rollback(); - $this->error=$this->db->lasterror(); + $this->error = $this->db->lasterror(); return -1; } } else { $this->db->rollback(); - $this->error=$line->error; + $this->error = $line->error; return -1; } } @@ -2285,13 +2285,13 @@ class Commande extends CommonOrder else { $this->db->rollback(); - $this->error=$this->db->lasterror(); + $this->error = $this->db->lasterror(); return -1; } } else { - $this->error='ErrorDeleteLineNotAllowedByObjectStatus'; + $this->error = 'ErrorDeleteLineNotAllowedByObjectStatus'; return -1; } } @@ -2308,57 +2308,57 @@ class Commande extends CommonOrder public function set_remise($user, $remise, $notrigger = 0) { // phpcs:enable - $remise=trim($remise)?trim($remise):0; + $remise = trim($remise) ?trim($remise) : 0; if ($user->rights->commande->creer) { - $error=0; + $error = 0; $this->db->begin(); - $remise=price2num($remise); + $remise = price2num($remise); $sql = 'UPDATE '.MAIN_DB_PREFIX.'commande'; - $sql.= ' SET remise_percent = '.$remise; - $sql.= ' WHERE rowid = '.$this->id.' AND fk_statut = '.self::STATUS_DRAFT.' ;'; + $sql .= ' SET remise_percent = '.$remise; + $sql .= ' WHERE rowid = '.$this->id.' AND fk_statut = '.self::STATUS_DRAFT.' ;'; dol_syslog(__METHOD__, LOG_DEBUG); - $resql=$this->db->query($sql); + $resql = $this->db->query($sql); if (!$resql) { - $this->errors[]=$this->db->error(); + $this->errors[] = $this->db->error(); $error++; } - if (! $error) + if (!$error) { - $this->oldcopy= clone $this; + $this->oldcopy = clone $this; $this->remise_percent = $remise; $this->update_price(1); } - if (! $notrigger && empty($error)) + if (!$notrigger && empty($error)) { // Call trigger - $result=$this->call_trigger('ORDER_MODIFY', $user); + $result = $this->call_trigger('ORDER_MODIFY', $user); 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); + $this->error .= ($this->error ? ', '.$errmsg : $errmsg); } $this->db->rollback(); - return -1*$error; + return -1 * $error; } } } @@ -2376,57 +2376,57 @@ class Commande extends CommonOrder public function set_remise_absolue($user, $remise, $notrigger = 0) { // phpcs:enable - $remise=trim($remise)?trim($remise):0; + $remise = trim($remise) ?trim($remise) : 0; if ($user->rights->commande->creer) { - $error=0; + $error = 0; $this->db->begin(); - $remise=price2num($remise); + $remise = price2num($remise); $sql = 'UPDATE '.MAIN_DB_PREFIX.'commande'; - $sql.= ' SET remise_absolue = '.$remise; - $sql.= ' WHERE rowid = '.$this->id.' AND fk_statut = '.self::STATUS_DRAFT.' ;'; + $sql .= ' SET remise_absolue = '.$remise; + $sql .= ' WHERE rowid = '.$this->id.' AND fk_statut = '.self::STATUS_DRAFT.' ;'; dol_syslog(__METHOD__, LOG_DEBUG); - $resql=$this->db->query($sql); + $resql = $this->db->query($sql); if (!$resql) { - $this->errors[]=$this->db->error(); + $this->errors[] = $this->db->error(); $error++; } - if (! $error) + if (!$error) { - $this->oldcopy= clone $this; + $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('ORDER_MODIFY', $user); + $result = $this->call_trigger('ORDER_MODIFY', $user); 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); + $this->error .= ($this->error ? ', '.$errmsg : $errmsg); } $this->db->rollback(); - return -1*$error; + return -1 * $error; } } } @@ -2446,50 +2446,50 @@ class Commande extends CommonOrder // phpcs:enable if ($user->rights->commande->creer) { - $error=0; + $error = 0; $this->db->begin(); $sql = "UPDATE ".MAIN_DB_PREFIX."commande"; - $sql.= " SET date_commande = ".($date ? "'".$this->db->idate($date)."'" : 'null'); - $sql.= " WHERE rowid = ".$this->id." AND fk_statut = ".self::STATUS_DRAFT; + $sql .= " SET date_commande = ".($date ? "'".$this->db->idate($date)."'" : 'null'); + $sql .= " WHERE rowid = ".$this->id." AND fk_statut = ".self::STATUS_DRAFT; dol_syslog(__METHOD__, LOG_DEBUG); - $resql=$this->db->query($sql); + $resql = $this->db->query($sql); if (!$resql) { - $this->errors[]=$this->db->error(); + $this->errors[] = $this->db->error(); $error++; } - if (! $error) + if (!$error) { - $this->oldcopy= clone $this; + $this->oldcopy = clone $this; $this->date = $date; } - if (! $notrigger && empty($error)) + if (!$notrigger && empty($error)) { // Call trigger - $result=$this->call_trigger('ORDER_MODIFY', $user); + $result = $this->call_trigger('ORDER_MODIFY', $user); 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); + $this->error .= ($this->error ? ', '.$errmsg : $errmsg); } $this->db->rollback(); - return -1*$error; + return -1 * $error; } } else @@ -2512,50 +2512,50 @@ class Commande extends CommonOrder // phpcs:enable if ($user->rights->commande->creer) { - $error=0; + $error = 0; $this->db->begin(); $sql = "UPDATE ".MAIN_DB_PREFIX."commande"; - $sql.= " SET date_livraison = ".($date_livraison ? "'".$this->db->idate($date_livraison)."'" : 'null'); - $sql.= " WHERE rowid = ".$this->id; + $sql .= " SET date_livraison = ".($date_livraison ? "'".$this->db->idate($date_livraison)."'" : 'null'); + $sql .= " WHERE rowid = ".$this->id; dol_syslog(__METHOD__, LOG_DEBUG); - $resql=$this->db->query($sql); + $resql = $this->db->query($sql); if (!$resql) { - $this->errors[]=$this->db->error(); + $this->errors[] = $this->db->error(); $error++; } - if (! $error) + if (!$error) { - $this->oldcopy= clone $this; + $this->oldcopy = clone $this; $this->date_livraison = $date_livraison; } - if (! $notrigger && empty($error)) + if (!$notrigger && empty($error)) { // Call trigger - $result=$this->call_trigger('ORDER_MODIFY', $user); + $result = $this->call_trigger('ORDER_MODIFY', $user); 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); + $this->error .= ($this->error ? ', '.$errmsg : $errmsg); } $this->db->rollback(); - return -1*$error; + return -1 * $error; } } else @@ -2586,23 +2586,23 @@ class Commande extends CommonOrder $ga = array(); $sql = "SELECT s.rowid, s.nom as name, s.client,"; - $sql.= " c.rowid as cid, c.ref"; - 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."commande as c"; - if (! $user->rights->societe->client->voir && ! $socid) $sql .= ", ".MAIN_DB_PREFIX."societe_commerciaux as sc"; - $sql.= " WHERE c.entity IN (".getEntity('commande').")"; - $sql.= " AND c.fk_soc = s.rowid"; - if (! $user->rights->societe->client->voir && ! $socid) //restriction + $sql .= " c.rowid as cid, c.ref"; + 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."commande as c"; + if (!$user->rights->societe->client->voir && !$socid) $sql .= ", ".MAIN_DB_PREFIX."societe_commerciaux as sc"; + $sql .= " WHERE c.entity IN (".getEntity('commande').")"; + $sql .= " AND c.fk_soc = s.rowid"; + if (!$user->rights->societe->client->voir && !$socid) //restriction { - $sql.= " AND s.rowid = sc.fk_soc AND sc.fk_user = " .$user->id; + $sql .= " AND s.rowid = sc.fk_soc AND sc.fk_user = ".$user->id; } - if ($socid) $sql.= " AND s.rowid = ".$socid; - if ($draft) $sql.= " AND c.fk_statut = ".self::STATUS_DRAFT; - if (is_object($excluser)) $sql.= " AND c.fk_user_author <> ".$excluser->id; - $sql.= $this->db->order($sortfield, $sortorder); - $sql.= $this->db->plimit($limit, $offset); + if ($socid) $sql .= " AND s.rowid = ".$socid; + if ($draft) $sql .= " AND c.fk_statut = ".self::STATUS_DRAFT; + if (is_object($excluser)) $sql .= " AND c.fk_user_author <> ".$excluser->id; + $sql .= $this->db->order($sortfield, $sortorder); + $sql .= $this->db->plimit($limit, $offset); - $result=$this->db->query($sql); + $result = $this->db->query($sql); if ($result) { $numc = $this->db->num_rows($result); @@ -2623,7 +2623,7 @@ class Commande extends CommonOrder } else { - $ga[$i]['id'] = $obj->cid; + $ga[$i]['id'] = $obj->cid; $ga[$i]['ref'] = $obj->ref; $ga[$i]['name'] = $obj->name; } @@ -2653,7 +2653,7 @@ class Commande extends CommonOrder dol_syslog('Commande::availability('.$availability_id.')'); if ($this->statut >= self::STATUS_DRAFT) { - $error=0; + $error = 0; $this->db->begin(); @@ -2662,49 +2662,49 @@ class Commande extends CommonOrder $sql .= ' WHERE rowid='.$this->id; dol_syslog(__METHOD__, LOG_DEBUG); - $resql=$this->db->query($sql); + $resql = $this->db->query($sql); if (!$resql) { - $this->errors[]=$this->db->error(); + $this->errors[] = $this->db->error(); $error++; } - if (! $error) + if (!$error) { - $this->oldcopy= clone $this; + $this->oldcopy = clone $this; $this->availability_id = $availability_id; } - if (! $notrigger && empty($error)) + if (!$notrigger && empty($error)) { // Call trigger - $result=$this->call_trigger('ORDER_MODIFY', $user); + $result = $this->call_trigger('ORDER_MODIFY', $user); 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); + $this->error .= ($this->error ? ', '.$errmsg : $errmsg); } $this->db->rollback(); - return -1*$error; + return -1 * $error; } } else { - $error_str='Command status do not meet requirement '.$this->statut; + $error_str = 'Command status do not meet requirement '.$this->statut; dol_syslog(__METHOD__.$error_str, LOG_ERR); - $this->error=$error_str; - $this->errors[]= $this->error; + $this->error = $error_str; + $this->errors[] = $this->error; return -2; } } @@ -2725,7 +2725,7 @@ class Commande extends CommonOrder dol_syslog('Commande::demand_reason('.$demand_reason_id.')'); if ($this->statut >= self::STATUS_DRAFT) { - $error=0; + $error = 0; $this->db->begin(); @@ -2734,49 +2734,49 @@ class Commande extends CommonOrder $sql .= ' WHERE rowid='.$this->id; dol_syslog(__METHOD__, LOG_DEBUG); - $resql=$this->db->query($sql); + $resql = $this->db->query($sql); if (!$resql) { - $this->errors[]=$this->db->error(); + $this->errors[] = $this->db->error(); $error++; } - if (! $error) + if (!$error) { - $this->oldcopy= clone $this; + $this->oldcopy = clone $this; $this->demand_reason_id = $demand_reason_id; } - if (! $notrigger && empty($error)) + if (!$notrigger && empty($error)) { // Call trigger - $result=$this->call_trigger('ORDER_MODIFY', $user); + $result = $this->call_trigger('ORDER_MODIFY', $user); 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); + $this->error .= ($this->error ? ', '.$errmsg : $errmsg); } $this->db->rollback(); - return -1*$error; + return -1 * $error; } } else { - $error_str='order status do not meet requirement '.$this->statut; + $error_str = 'order status do not meet requirement '.$this->statut; dol_syslog(__METHOD__.$error_str, LOG_ERR); - $this->error=$error_str; - $this->errors[]= $this->error; + $this->error = $error_str; + $this->errors[] = $this->error; return -2; } } @@ -2795,49 +2795,49 @@ class Commande extends CommonOrder // phpcs:enable if ($user->rights->commande->creer) { - $error=0; + $error = 0; $this->db->begin(); $sql = 'UPDATE '.MAIN_DB_PREFIX.'commande SET'; - $sql.= ' ref_client = '.(empty($ref_client) ? 'NULL' : '\''.$this->db->escape($ref_client).'\''); - $sql.= ' WHERE rowid = '.$this->id; + $sql .= ' ref_client = '.(empty($ref_client) ? 'NULL' : '\''.$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); + $resql = $this->db->query($sql); if (!$resql) { - $this->errors[]=$this->db->error(); + $this->errors[] = $this->db->error(); $error++; } - if (! $error) + if (!$error) { - $this->oldcopy= clone $this; + $this->oldcopy = clone $this; $this->ref_client = $ref_client; } - if (! $notrigger && empty($error)) + if (!$notrigger && empty($error)) { // Call trigger - $result=$this->call_trigger('ORDER_MODIFY', $user); + $result = $this->call_trigger('ORDER_MODIFY', $user); 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); + $this->error .= ($this->error ? ', '.$errmsg : $errmsg); } $this->db->rollback(); - return -1*$error; + return -1 * $error; } } else @@ -2916,43 +2916,43 @@ class Commande extends CommonOrder $this->db->begin(); $sql = 'UPDATE '.MAIN_DB_PREFIX.'commande SET facture = 0'; - $sql.= ' WHERE rowid = '.$this->id.' AND fk_statut > '.self::STATUS_DRAFT; + $sql .= ' WHERE rowid = '.$this->id.' AND fk_statut > '.self::STATUS_DRAFT; dol_syslog(get_class($this)."::classifyUnBilled", LOG_DEBUG); if ($this->db->query($sql)) { - if (! $error) + if (!$error) { - $this->oldcopy= clone $this; - $this->billed=1; + $this->oldcopy = clone $this; + $this->billed = 1; } // Call trigger - $result=$this->call_trigger('ORDER_CLASSIFY_UNBILLED', $user); + $result = $this->call_trigger('ORDER_CLASSIFY_UNBILLED', $user); if ($result < 0) $error++; // End call triggers - if (! $error) + if (!$error) { - $this->billed=0; + $this->billed = 0; $this->db->commit(); return 1; } else { - foreach($this->errors as $errmsg) + foreach ($this->errors as $errmsg) { dol_syslog(get_class($this)."::classifyUnBilled ".$errmsg, LOG_ERR); - $this->error.=($this->error?', '.$errmsg:$errmsg); + $this->error .= ($this->error ? ', '.$errmsg : $errmsg); } $this->db->rollback(); - return -1*$error; + return -1 * $error; } } else { - $this->error=$this->db->error(); + $this->error = $this->db->error(); $this->db->rollback(); return -1; } @@ -2997,28 +2997,28 @@ class Commande extends CommonOrder if ($this->statut == Commande::STATUS_DRAFT) { // 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_percent)) $remise_percent=0; - if (empty($special_code) || $special_code == 3) $special_code=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_percent)) $remise_percent = 0; + if (empty($special_code) || $special_code == 3) $special_code = 0; if ($date_start && $date_end && $date_start > $date_end) { $langs->load("errors"); - $this->error=$langs->trans('ErrorStartDateGreaterEnd'); + $this->error = $langs->trans('ErrorStartDateGreaterEnd'); return -1; } - $remise_percent=price2num($remise_percent); - $qty=price2num($qty); + $remise_percent = price2num($remise_percent); + $qty = price2num($qty); $pu = price2num($pu); - $pa_ht=price2num($pa_ht); - $pu_ht_devise=price2num($pu_ht_devise); - $txtva=price2num($txtva); - $txlocaltax1=price2num($txlocaltax1); - $txlocaltax2=price2num($txlocaltax2); + $pa_ht = price2num($pa_ht); + $pu_ht_devise = price2num($pu_ht_devise); + $txtva = price2num($txtva); + $txlocaltax1 = price2num($txlocaltax1); + $txlocaltax2 = price2num($txlocaltax2); $this->db->begin(); @@ -3027,17 +3027,17 @@ class Commande extends CommonOrder // TRES IMPORTANT: C'est au moment de l'insertion ligne qu'on doit stocker // la part ht, tva et ttc, et ce au niveau de la ligne qui a son propre taux tva. - $localtaxes_type=getLocalTaxesFromRate($txtva, 0, $this->thirdparty, $mysoc); + $localtaxes_type = getLocalTaxesFromRate($txtva, 0, $this->thirdparty, $mysoc); // Clean vat code - $vat_src_code=''; + $vat_src_code = ''; if (preg_match('/\((.*)\)/', $txtva, $reg)) { $vat_src_code = $reg[1]; - $txtva = preg_replace('/\s*\(.*\)/', '', $txtva); // Remove code into vatrate. + $txtva = preg_replace('/\s*\(.*\)/', '', $txtva); // Remove code into vatrate. } - $tabprice=calcul_price_total($qty, $pu, $remise_percent, $txtva, $txlocaltax1, $txlocaltax2, 0, $price_base_type, $info_bits, $type, $mysoc, $localtaxes_type, 100, $this->multicurrency_tx, $pu_ht_devise); + $tabprice = calcul_price_total($qty, $pu, $remise_percent, $txtva, $txlocaltax1, $txlocaltax2, 0, $price_base_type, $info_bits, $type, $mysoc, $localtaxes_type, 100, $this->multicurrency_tx, $pu_ht_devise); $total_ht = $tabprice[0]; $total_tva = $tabprice[1]; @@ -3077,14 +3077,14 @@ class Commande extends CommonOrder if (!empty($line->fk_product)) { - $product=new Product($this->db); - $result=$product->fetch($line->fk_product); - $product_type=$product->type; + $product = new Product($this->db); + $result = $product->fetch($line->fk_product); + $product_type = $product->type; - if (! empty($conf->global->STOCK_MUST_BE_ENOUGH_FOR_ORDER) && $product_type == 0 && $product->stock_reel < $qty) + if (!empty($conf->global->STOCK_MUST_BE_ENOUGH_FOR_ORDER) && $product_type == 0 && $product->stock_reel < $qty) { $langs->load("errors"); - $this->error=$langs->trans('ErrorStockIsNotEnoughToAddProductOnOrder', $product->ref); + $this->error = $langs->trans('ErrorStockIsNotEnoughToAddProductOnOrder', $product->ref); dol_syslog(get_class($this)."::addline error=Product ".$product->ref.": ".$this->error, LOG_ERR); $this->db->rollback(); return self::STOCK_NOT_ENOUGH_FOR_ORDER; @@ -3104,7 +3104,7 @@ class Commande extends CommonOrder $this->line->rang = $rangmax + 1; } - $this->line->rowid=$rowid; + $this->line->id=$rowid; $this->line->label=$label; $this->line->desc=$desc; $this->line->qty=$qty; @@ -3121,14 +3121,14 @@ class Commande extends CommonOrder $this->line->special_code = $special_code; $this->line->total_ht = $total_ht; $this->line->total_tva = $total_tva; - $this->line->total_localtax1= $total_localtax1; - $this->line->total_localtax2= $total_localtax2; + $this->line->total_localtax1 = $total_localtax1; + $this->line->total_localtax2 = $total_localtax2; $this->line->total_ttc = $total_ttc; $this->line->date_start = $date_start; $this->line->date_end = $date_end; $this->line->product_type = $type; $this->line->fk_parent_line = $fk_parent_line; - $this->line->skip_update_total=$skip_update_total; + $this->line->skip_update_total = $skip_update_total; $this->line->fk_unit = $fk_unit; $this->line->fk_fournprice = $fk_fournprice; @@ -3141,18 +3141,18 @@ class Commande extends CommonOrder $this->line->multicurrency_total_ttc = $multicurrency_total_ttc; // TODO deprecated - $this->line->price=$price; - $this->line->remise=$remise; + $this->line->price = $price; + $this->line->remise = $remise; - if (is_array($array_options) && count($array_options)>0) { - $this->line->array_options=$array_options; + if (is_array($array_options) && count($array_options) > 0) { + $this->line->array_options = $array_options; } - $result=$this->line->update($user, $notrigger); + $result = $this->line->update($user, $notrigger); 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 $this->update_price(1); @@ -3162,7 +3162,7 @@ class Commande extends CommonOrder } else { - $this->error=$this->line->error; + $this->error = $this->line->error; $this->db->rollback(); return -1; @@ -3170,8 +3170,8 @@ class Commande extends CommonOrder } else { - $this->error=get_class($this)."::updateline Order status makes operation forbidden"; - $this->errors=array('OrderStatusMakeOperationForbidden'); + $this->error = get_class($this)."::updateline Order status makes operation forbidden"; + $this->errors = array('OrderStatusMakeOperationForbidden'); return -2; } } @@ -3187,15 +3187,15 @@ class Commande extends CommonOrder { global $conf; - $error=0; + $error = 0; // Clean parameters - if (isset($this->ref)) $this->ref=trim($this->ref); - if (isset($this->ref_client)) $this->ref_client=trim($this->ref_client); - 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->modelpdf)) $this->modelpdf=trim($this->modelpdf); - 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_client)) $this->ref_client = trim($this->ref_client); + 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->modelpdf)) $this->modelpdf = trim($this->modelpdf); + if (isset($this->import_key)) $this->import_key = trim($this->import_key); // Check parameters // Put here code to add control on parameters values @@ -3203,52 +3203,52 @@ class Commande extends CommonOrder // Update request $sql = "UPDATE ".MAIN_DB_PREFIX."commande SET"; - $sql.= " ref=".(isset($this->ref)?"'".$this->db->escape($this->ref)."'":"null").","; - $sql.= " ref_client=".(isset($this->ref_client)?"'".$this->db->escape($this->ref_client)."'":"null").","; - $sql.= " ref_ext=".(isset($this->ref_ext)?"'".$this->db->escape($this->ref_ext)."'":"null").","; - $sql.= " fk_soc=".(isset($this->socid)?$this->socid:"null").","; - $sql.= " date_commande=".(strval($this->date_commande)!='' ? "'".$this->db->idate($this->date_commande)."'" : 'null').","; - $sql.= " date_valid=".(strval($this->date_validation)!='' ? "'".$this->db->idate($this->date_validation)."'" : 'null').","; - $sql.= " tva=".(isset($this->total_tva)?$this->total_tva:"null").","; - $sql.= " localtax1=".(isset($this->total_localtax1)?$this->total_localtax1:"null").","; - $sql.= " localtax2=".(isset($this->total_localtax2)?$this->total_localtax2:"null").","; - $sql.= " total_ht=".(isset($this->total_ht)?$this->total_ht:"null").","; - $sql.= " total_ttc=".(isset($this->total_ttc)?$this->total_ttc:"null").","; - $sql.= " fk_statut=".(isset($this->statut)?$this->statut:"null").","; - $sql.= " fk_user_author=".(isset($this->user_author_id)?$this->user_author_id:"null").","; - $sql.= " fk_user_valid=".(isset($this->user_valid)?$this->user_valid:"null").","; - $sql.= " fk_projet=".(isset($this->fk_project)?$this->fk_project:"null").","; - $sql.= " fk_cond_reglement=".(isset($this->cond_reglement_id)?$this->cond_reglement_id:"null").","; - $sql.= " fk_mode_reglement=".(isset($this->mode_reglement_id)?$this->mode_reglement_id:"null").","; - $sql.= " fk_account=".($this->fk_account>0?$this->fk_account:"null").","; - $sql.= " note_private=".(isset($this->note_private)?"'".$this->db->escape($this->note_private)."'":"null").","; - $sql.= " note_public=".(isset($this->note_public)?"'".$this->db->escape($this->note_public)."'":"null").","; - $sql.= " model_pdf=".(isset($this->modelpdf)?"'".$this->db->escape($this->modelpdf)."'":"null").","; - $sql.= " import_key=".(isset($this->import_key)?"'".$this->db->escape($this->import_key)."'":"null").""; + $sql .= " ref=".(isset($this->ref) ? "'".$this->db->escape($this->ref)."'" : "null").","; + $sql .= " ref_client=".(isset($this->ref_client) ? "'".$this->db->escape($this->ref_client)."'" : "null").","; + $sql .= " ref_ext=".(isset($this->ref_ext) ? "'".$this->db->escape($this->ref_ext)."'" : "null").","; + $sql .= " fk_soc=".(isset($this->socid) ? $this->socid : "null").","; + $sql .= " date_commande=".(strval($this->date_commande) != '' ? "'".$this->db->idate($this->date_commande)."'" : 'null').","; + $sql .= " date_valid=".(strval($this->date_validation) != '' ? "'".$this->db->idate($this->date_validation)."'" : 'null').","; + $sql .= " tva=".(isset($this->total_tva) ? $this->total_tva : "null").","; + $sql .= " localtax1=".(isset($this->total_localtax1) ? $this->total_localtax1 : "null").","; + $sql .= " localtax2=".(isset($this->total_localtax2) ? $this->total_localtax2 : "null").","; + $sql .= " total_ht=".(isset($this->total_ht) ? $this->total_ht : "null").","; + $sql .= " total_ttc=".(isset($this->total_ttc) ? $this->total_ttc : "null").","; + $sql .= " fk_statut=".(isset($this->statut) ? $this->statut : "null").","; + $sql .= " fk_user_author=".(isset($this->user_author_id) ? $this->user_author_id : "null").","; + $sql .= " fk_user_valid=".(isset($this->user_valid) ? $this->user_valid : "null").","; + $sql .= " fk_projet=".(isset($this->fk_project) ? $this->fk_project : "null").","; + $sql .= " fk_cond_reglement=".(isset($this->cond_reglement_id) ? $this->cond_reglement_id : "null").","; + $sql .= " fk_mode_reglement=".(isset($this->mode_reglement_id) ? $this->mode_reglement_id : "null").","; + $sql .= " fk_account=".($this->fk_account > 0 ? $this->fk_account : "null").","; + $sql .= " note_private=".(isset($this->note_private) ? "'".$this->db->escape($this->note_private)."'" : "null").","; + $sql .= " note_public=".(isset($this->note_public) ? "'".$this->db->escape($this->note_public)."'" : "null").","; + $sql .= " model_pdf=".(isset($this->modelpdf) ? "'".$this->db->escape($this->modelpdf)."'" : "null").","; + $sql .= " import_key=".(isset($this->import_key) ? "'".$this->db->escape($this->import_key)."'" : "null").""; - $sql.= " WHERE rowid=".$this->id; + $sql .= " WHERE rowid=".$this->id; $this->db->begin(); dol_syslog(get_class($this)."::update", LOG_DEBUG); $resql = $this->db->query($sql); - if (! $resql) { - $error++; $this->errors[]="Error ".$this->db->lasterror(); + if (!$resql) { + $error++; $this->errors[] = "Error ".$this->db->lasterror(); } - if (! $error && empty($conf->global->MAIN_EXTRAFIELDS_DISABLED) && is_array($this->array_options) && count($this->array_options)>0) + if (!$error && empty($conf->global->MAIN_EXTRAFIELDS_DISABLED) && is_array($this->array_options) && count($this->array_options) > 0) { - $result=$this->insertExtraFields(); + $result = $this->insertExtraFields(); if ($result < 0) { $error++; } } - if (! $error && ! $notrigger) + if (!$error && !$notrigger) { // Call trigger - $result=$this->call_trigger('ORDER_MODIFY', $user); + $result = $this->call_trigger('ORDER_MODIFY', $user); if ($result < 0) $error++; // End call triggers } @@ -3256,13 +3256,13 @@ class Commande extends CommonOrder // Commit or rollback if ($error) { - foreach($this->errors as $errmsg) + foreach ($this->errors as $errmsg) { dol_syslog(get_class($this)."::update ".$errmsg, LOG_ERR); - $this->error.=($this->error?', '.$errmsg:$errmsg); + $this->error .= ($this->error ? ', '.$errmsg : $errmsg); } $this->db->rollback(); - return -1*$error; + return -1 * $error; } else { @@ -3285,14 +3285,14 @@ class Commande extends CommonOrder $error = 0; - dol_syslog(get_class($this) . "::delete ".$this->id, LOG_DEBUG); + dol_syslog(get_class($this)."::delete ".$this->id, LOG_DEBUG); $this->db->begin(); - if (! $error && ! $notrigger) + if (!$error && !$notrigger) { // Call trigger - $result=$this->call_trigger('ORDER_DELETE', $user); + $result = $this->call_trigger('ORDER_DELETE', $user); if ($result < 0) $error++; // End call triggers } @@ -3303,37 +3303,37 @@ class Commande extends CommonOrder $error++; } - if (! $error) + if (!$error) { // Delete order details $sql = 'DELETE FROM '.MAIN_DB_PREFIX."commandedet WHERE fk_commande = ".$this->id; - if (! $this->db->query($sql) ) + if (!$this->db->query($sql)) { $error++; - $this->errors[]=$this->db->lasterror(); + $this->errors[] = $this->db->lasterror(); } } - if (! $error) + if (!$error) { // Delete linked object $res = $this->deleteObjectLinked(); if ($res < 0) $error++; } - if (! $error) + if (!$error) { // Delete linked contacts $res = $this->delete_linked_contact(); if ($res < 0) $error++; } - if (! $error) + if (!$error) { // Remove extrafields - if ((! $error) && (empty($conf->global->MAIN_EXTRAFIELDS_DISABLED))) // For avoid conflicts if trigger used + if ((!$error) && (empty($conf->global->MAIN_EXTRAFIELDS_DISABLED))) // For avoid conflicts if trigger used { - $result=$this->deleteExtraFields(); + $result = $this->deleteExtraFields(); if ($result < 0) { $error++; @@ -3373,9 +3373,9 @@ class Commande extends CommonOrder } if (file_exists($dir)) { - if (! dol_delete_dir_recursive($dir)) + if (!dol_delete_dir_recursive($dir)) { - $this->error=$langs->trans("ErrorCanNotDeleteDir", $dir); + $this->error = $langs->trans("ErrorCanNotDeleteDir", $dir); $this->db->rollback(); return 0; } @@ -3383,19 +3383,19 @@ class Commande extends CommonOrder } } - if (! $error) + if (!$error) { $this->db->commit(); return 1; } else { - foreach($this->errors as $errmsg) + foreach ($this->errors as $errmsg) { - $this->error.=($this->error?', '.$errmsg:$errmsg); + $this->error .= ($this->error ? ', '.$errmsg : $errmsg); } $this->db->rollback(); - return -1*$error; + return -1 * $error; } } @@ -3457,7 +3457,7 @@ class Commande extends CommonOrder } else { - $this->error=$this->db->error(); + $this->error = $this->db->error(); return -1; } } @@ -3471,7 +3471,7 @@ class Commande extends CommonOrder { global $langs; - $label=$langs->trans('OrderSource'.$this->source); + $label = $langs->trans('OrderSource'.$this->source); if ($label == 'OrderSource') return ''; return $label; @@ -3567,11 +3567,11 @@ class Commande extends CommonOrder { global $conf, $langs, $user; - if (! empty($conf->dol_no_mouse_hover)) $notooltip=1; // Force disable tooltips + if (!empty($conf->dol_no_mouse_hover)) $notooltip = 1; // Force disable tooltips - $result=''; + $result = ''; - if (! empty($conf->expedition->enabled) && ($option == '1' || $option == '2')) $url = DOL_URL_ROOT.'/expedition/shipment.php?id='.$this->id; + if (!empty($conf->expedition->enabled) && ($option == '1' || $option == '2')) $url = DOL_URL_ROOT.'/expedition/shipment.php?id='.$this->id; else $url = DOL_URL_ROOT.'/commande/card.php?id='.$this->id; if (!$user->rights->commande->lire) @@ -3580,9 +3580,9 @@ class Commande extends CommonOrder 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'; + $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; @@ -3597,28 +3597,28 @@ class Commande extends CommonOrder $label .= '
'.$langs->trans('AmountHT').': '.price($this->total_ht, 0, $langs, 0, -1, -1, $conf->currency); } if (!empty($this->total_tva)) { - $label .= '
'.$langs->trans('VAT').': '.price($this->total_tva, 0, $langs, 0, -1, -1, $conf->currency); + $label .= '
'.$langs->trans('VAT').': '.price($this->total_tva, 0, $langs, 0, -1, -1, $conf->currency); } if (!empty($this->total_ttc)) { $label .= '
'.$langs->trans('AmountTTC').': '.price($this->total_ttc, 0, $langs, 0, -1, -1, $conf->currency); } } - $linkclose=''; + $linkclose = ''; if (empty($notooltip) && $user->rights->commande->lire) { - if (! empty($conf->global->MAIN_OPTIMIZEFORTEXTBROWSER)) + if (!empty($conf->global->MAIN_OPTIMIZEFORTEXTBROWSER)) { - $label=$langs->trans("ShowOrder"); - $linkclose.=' alt="'.dol_escape_htmltag($label, 1).'"'; + $label = $langs->trans("ShowOrder"); + $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"'; } $linkstart = ''; - $linkend=''; + $linkstart .= $linkclose.'>'; + $linkend = ''; if ($option === 'nolink') { $linkstart = ''; @@ -3626,8 +3626,8 @@ class Commande extends CommonOrder } $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; return $result; @@ -3643,12 +3643,12 @@ class Commande extends CommonOrder public function info($id) { $sql = 'SELECT c.rowid, date_creation as datec, tms as datem,'; - $sql.= ' date_valid as datev,'; - $sql.= ' date_cloture as datecloture,'; - $sql.= ' fk_user_author, fk_user_valid, fk_user_cloture'; - $sql.= ' FROM '.MAIN_DB_PREFIX.'commande as c'; - $sql.= ' WHERE c.rowid = '.$id; - $result=$this->db->query($sql); + $sql .= ' date_valid as datev,'; + $sql .= ' date_cloture as datecloture,'; + $sql .= ' fk_user_author, fk_user_valid, fk_user_cloture'; + $sql .= ' FROM '.MAIN_DB_PREFIX.'commande as c'; + $sql .= ' WHERE c.rowid = '.$id; + $result = $this->db->query($sql); if ($result) { if ($this->db->num_rows($result)) @@ -3659,7 +3659,7 @@ class Commande extends CommonOrder { $cuser = new User($this->db); $cuser->fetch($obj->fk_user_author); - $this->user_creation = $cuser; + $this->user_creation = $cuser; } if ($obj->fk_user_valid) @@ -3673,7 +3673,7 @@ class Commande extends CommonOrder { $cluser = new User($this->db); $cluser->fetch($obj->fk_user_cloture); - $this->user_cloture = $cluser; + $this->user_cloture = $cluser; } $this->date_creation = $this->db->jdate($obj->datec); @@ -3708,8 +3708,8 @@ class Commande extends CommonOrder $num_prods = 0; $prodids = array(); $sql = "SELECT rowid"; - $sql.= " FROM ".MAIN_DB_PREFIX."product"; - $sql.= " WHERE entity IN (".getEntity('product').")"; + $sql .= " FROM ".MAIN_DB_PREFIX."product"; + $sql .= " WHERE entity IN (".getEntity('product').")"; $resql = $this->db->query($sql); if ($resql) { @@ -3724,52 +3724,52 @@ class Commande extends CommonOrder } // Initialise parametres - $this->id=0; + $this->id = 0; $this->ref = 'SPECIMEN'; - $this->specimen=1; + $this->specimen = 1; $this->socid = 1; $this->date = time(); - $this->date_lim_reglement=$this->date+3600*24*30; + $this->date_lim_reglement = $this->date + 3600 * 24 * 30; $this->cond_reglement_code = 'RECEP'; $this->mode_reglement_code = 'CHQ'; $this->availability_code = 'DSP'; $this->demand_reason_code = 'SRC_00'; - $this->note_public='This is a comment (public)'; - $this->note_private='This is a comment (private)'; + $this->note_public = 'This is a comment (public)'; + $this->note_private = 'This is a comment (private)'; // Lines $nbp = 5; $xnbp = 0; while ($xnbp < $nbp) { - $line=new OrderLine($this->db); + $line = new OrderLine($this->db); - $line->desc=$langs->trans("Description")." ".$xnbp; - $line->qty=1; - $line->subprice=100; - $line->price=100; - $line->tva_tx=20; + $line->desc = $langs->trans("Description")." ".$xnbp; + $line->qty = 1; + $line->subprice = 100; + $line->price = 100; + $line->tva_tx = 20; if ($xnbp == 2) { - $line->total_ht=50; - $line->total_ttc=60; - $line->total_tva=10; - $line->remise_percent=50; + $line->total_ht = 50; + $line->total_ttc = 60; + $line->total_tva = 10; + $line->remise_percent = 50; } else { - $line->total_ht=100; - $line->total_ttc=120; - $line->total_tva=20; - $line->remise_percent=0; + $line->total_ht = 100; + $line->total_ttc = 120; + $line->total_tva = 20; + $line->remise_percent = 0; } if ($num_prods > 0) { $prodid = mt_rand(1, $num_prods); - $line->fk_product=$prodids[$prodid]; - $line->product_ref='SPECIMEN'; + $line->fk_product = $prodids[$prodid]; + $line->product_ref = 'SPECIMEN'; } - $this->lines[$xnbp]=$line; + $this->lines[$xnbp] = $line; $this->total_ht += $line->total_ht; $this->total_tva += $line->total_tva; @@ -3818,7 +3818,7 @@ class Commande extends CommonOrder else { dol_print_error($this->db); - $this->error=$this->db->error(); + $this->error = $this->db->error(); return -1; } } @@ -3892,8 +3892,8 @@ class Commande extends CommonOrder { global $conf; - if (! ($this->statut > Commande::STATUS_DRAFT && $this->statut < Commande::STATUS_CLOSED)) { - return false; // Never late if not inside this status range + if (!($this->statut > Commande::STATUS_DRAFT && $this->statut < Commande::STATUS_CLOSED)) { + return false; // Never late if not inside this status range } $now = dol_now(); @@ -3910,9 +3910,9 @@ class Commande extends CommonOrder { global $conf, $langs; - if (empty($this->date_livraison)) $text=$langs->trans("OrderDate").' '.dol_print_date($this->date_commande, 'day'); - else $text=$text=$langs->trans("DeliveryDate").' '.dol_print_date($this->date_livraison, 'day'); - $text.=' '.($conf->commande->client->warning_delay>0?'+':'-').' '.round(abs($conf->commande->client->warning_delay)/3600/24, 1).' '.$langs->trans("days").' < '.$langs->trans("Today"); + if (empty($this->date_livraison)) $text = $langs->trans("OrderDate").' '.dol_print_date($this->date_commande, 'day'); + else $text = $text = $langs->trans("DeliveryDate").' '.dol_print_date($this->date_livraison, 'day'); + $text .= ' '.($conf->commande->client->warning_delay > 0 ? '+' : '-').' '.round(abs($conf->commande->client->warning_delay) / 3600 / 24, 1).' '.$langs->trans("days").' < '.$langs->trans("Today"); return $text; } @@ -3927,9 +3927,9 @@ class OrderLine extends CommonOrderLine /** * @var string ID to identify managed object */ - public $element='commandedet'; + public $element = 'commandedet'; - public $table_element='commandedet'; + public $table_element = 'commandedet'; public $oldline; @@ -3988,7 +3988,7 @@ class OrderLine extends CommonOrderLine */ public function __construct($db) { - $this->db= $db; + $this->db = $db; } /** @@ -4000,21 +4000,21 @@ class OrderLine extends CommonOrderLine public function fetch($rowid) { $sql = 'SELECT cd.rowid, cd.fk_commande, cd.fk_parent_line, cd.fk_product, cd.product_type, cd.label as custom_label, cd.description, cd.price, cd.qty, cd.tva_tx, cd.localtax1_tx, cd.localtax2_tx,'; - $sql.= ' cd.remise, cd.remise_percent, cd.fk_remise_except, cd.subprice,'; - $sql.= ' cd.info_bits, cd.total_ht, cd.total_tva, cd.total_localtax1, cd.total_localtax2, cd.total_ttc, cd.fk_product_fournisseur_price as fk_fournprice, cd.buy_price_ht as pa_ht, cd.rang, cd.special_code,'; - $sql.= ' cd.fk_unit,'; - $sql.= ' cd.fk_multicurrency, cd.multicurrency_code, cd.multicurrency_subprice, cd.multicurrency_total_ht, cd.multicurrency_total_tva, cd.multicurrency_total_ttc,'; - $sql.= ' p.ref as product_ref, p.label as product_libelle, p.description as product_desc, p.tobatch as product_tobatch,'; - $sql.= ' cd.date_start, cd.date_end'; - $sql.= ' FROM '.MAIN_DB_PREFIX.'commandedet as cd'; - $sql.= ' LEFT JOIN '.MAIN_DB_PREFIX.'product as p ON cd.fk_product = p.rowid'; - $sql.= ' WHERE cd.rowid = '.$rowid; + $sql .= ' cd.remise, cd.remise_percent, cd.fk_remise_except, cd.subprice,'; + $sql .= ' cd.info_bits, cd.total_ht, cd.total_tva, cd.total_localtax1, cd.total_localtax2, cd.total_ttc, cd.fk_product_fournisseur_price as fk_fournprice, cd.buy_price_ht as pa_ht, cd.rang, cd.special_code,'; + $sql .= ' cd.fk_unit,'; + $sql .= ' cd.fk_multicurrency, cd.multicurrency_code, cd.multicurrency_subprice, cd.multicurrency_total_ht, cd.multicurrency_total_tva, cd.multicurrency_total_ttc,'; + $sql .= ' p.ref as product_ref, p.label as product_libelle, p.description as product_desc, p.tobatch as product_tobatch,'; + $sql .= ' cd.date_start, cd.date_end'; + $sql .= ' FROM '.MAIN_DB_PREFIX.'commandedet as cd'; + $sql .= ' LEFT JOIN '.MAIN_DB_PREFIX.'product as p ON cd.fk_product = p.rowid'; + $sql .= ' WHERE cd.rowid = '.$rowid; $result = $this->db->query($sql); if ($result) { $objp = $this->db->fetch_object($result); $this->rowid = $objp->rowid; - $this->id = $objp->rowid; + $this->id = $objp->rowid; $this->fk_commande = $objp->fk_commande; $this->fk_parent_line = $objp->fk_parent_line; $this->label = $objp->custom_label; @@ -4032,24 +4032,24 @@ class OrderLine extends CommonOrderLine $this->fk_product = $objp->fk_product; $this->product_type = $objp->product_type; $this->info_bits = $objp->info_bits; - $this->special_code = $objp->special_code; + $this->special_code = $objp->special_code; $this->total_ht = $objp->total_ht; $this->total_tva = $objp->total_tva; $this->total_localtax1 = $objp->total_localtax1; $this->total_localtax2 = $objp->total_localtax2; $this->total_ttc = $objp->total_ttc; - $this->fk_fournprice = $objp->fk_fournprice; + $this->fk_fournprice = $objp->fk_fournprice; $marginInfos = getMarginInfos($objp->subprice, $objp->remise_percent, $objp->tva_tx, $objp->localtax1_tx, $objp->localtax2_tx, $this->fk_fournprice, $objp->pa_ht); $this->pa_ht = $marginInfos[0]; $this->marge_tx = $marginInfos[1]; $this->marque_tx = $marginInfos[2]; - $this->special_code = $objp->special_code; - $this->rang = $objp->rang; + $this->special_code = $objp->special_code; + $this->rang = $objp->rang; - $this->ref = $objp->product_ref; // deprecated - $this->product_ref = $objp->product_ref; - $this->libelle = $objp->product_libelle; // deprecated - $this->product_label = $objp->product_libelle; + $this->ref = $objp->product_ref; // deprecated + $this->product_ref = $objp->product_ref; + $this->libelle = $objp->product_libelle; // deprecated + $this->product_label = $objp->product_libelle; $this->product_desc = $objp->product_desc; $this->product_tobatch = $objp->product_tobatch; $this->fk_unit = $objp->fk_unit; @@ -4057,8 +4057,8 @@ class OrderLine extends CommonOrderLine $this->date_start = $this->db->jdate($objp->date_start); $this->date_end = $this->db->jdate($objp->date_end); - $this->fk_multicurrency = $objp->fk_multicurrency; - $this->multicurrency_code = $objp->multicurrency_code; + $this->fk_multicurrency = $objp->fk_multicurrency; + $this->multicurrency_code = $objp->multicurrency_code; $this->multicurrency_subprice = $objp->multicurrency_subprice; $this->multicurrency_total_ht = $objp->multicurrency_total_ht; $this->multicurrency_total_tva = $objp->multicurrency_total_tva; @@ -4135,10 +4135,10 @@ class OrderLine extends CommonOrderLine } } - if (! $error && ! $notrigger) + if (!$error && !$notrigger) { // Call trigger - $result=$this->call_trigger('LINEORDER_DELETE', $user); + $result = $this->call_trigger('LINEORDER_DELETE', $user); if ($result < 0) $error++; // End call triggers } @@ -4148,17 +4148,17 @@ class OrderLine extends CommonOrderLine 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); + $this->error .= ($this->error ? ', '.$errmsg : $errmsg); } $this->db->rollback(); - return -1*$error; + return -1 * $error; } else { - $this->error=$this->db->lasterror(); + $this->error = $this->db->lasterror(); return -1; } } @@ -4174,27 +4174,27 @@ class OrderLine extends CommonOrderLine { global $langs, $conf; - $error=0; + $error = 0; $pa_ht_isemptystring = (empty($this->pa_ht) && $this->pa_ht == ''); // If true, we can use a default value. If this->pa_ht = '0', we must use '0'. 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; // if buy price not defined, define buyprice as configured in margin admin if ($this->pa_ht == 0 && $pa_ht_isemptystring) @@ -4267,11 +4267,11 @@ class OrderLine extends CommonOrderLine $resql=$this->db->query($sql); if ($resql) { - $this->rowid=$this->db->last_insert_id(MAIN_DB_PREFIX.'commandedet'); + $this->id=$this->db->last_insert_id(MAIN_DB_PREFIX.'commandedet'); + $this->rowid = $this->id; if (empty($conf->global->MAIN_EXTRAFIELDS_DISABLED)) // For avoid conflicts if trigger used { - $this->id=$this->rowid; $result=$this->insertExtraFields(); if ($result < 0) { @@ -4292,17 +4292,17 @@ class OrderLine extends CommonOrderLine 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); + $this->error .= ($this->error ? ', '.$errmsg : $errmsg); } $this->db->rollback(); - return -1*$error; + return -1 * $error; } else { - $this->error=$this->db->error(); + $this->error = $this->db->error(); $this->db->rollback(); return -2; } @@ -4317,30 +4317,30 @@ class OrderLine extends CommonOrderLine */ public function update(User $user, $notrigger = 0) { - global $conf,$langs; + global $conf, $langs; - $error=0; + $error = 0; $pa_ht_isemptystring = (empty($this->pa_ht) && $this->pa_ht == ''); // If true, we can use a default value. If this->pa_ht = '0', we must use '0'. // 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->qty)) $this->qty=0; - if (empty($this->total_localtax1)) $this->total_localtax1=0; - if (empty($this->total_localtax2)) $this->total_localtax2=0; - if (empty($this->marque_tx)) $this->marque_tx=0; - if (empty($this->marge_tx)) $this->marge_tx=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->product_type)) $this->product_type=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->qty)) $this->qty = 0; + if (empty($this->total_localtax1)) $this->total_localtax1 = 0; + if (empty($this->total_localtax2)) $this->total_localtax2 = 0; + if (empty($this->marque_tx)) $this->marque_tx = 0; + if (empty($this->marge_tx)) $this->marge_tx = 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->product_type)) $this->product_type = 0; + if (empty($this->fk_parent_line)) $this->fk_parent_line = 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 && $pa_ht_isemptystring) @@ -4359,64 +4359,64 @@ class OrderLine extends CommonOrderLine // Mise a jour ligne en base $sql = "UPDATE ".MAIN_DB_PREFIX."commandedet SET"; - $sql.= " description='".$this->db->escape($this->desc)."'"; - $sql.= " , label=".(! empty($this->label)?"'".$this->db->escape($this->label)."'":"null"); - $sql.= " , vat_src_code=".(! empty($this->vat_src_code)?"'".$this->db->escape($this->vat_src_code)."'":"''"); - $sql.= " , tva_tx=".price2num($this->tva_tx); - $sql.= " , localtax1_tx=".price2num($this->localtax1_tx); - $sql.= " , localtax2_tx=".price2num($this->localtax2_tx); - $sql.= " , localtax1_type='".$this->db->escape($this->localtax1_type)."'"; - $sql.= " , localtax2_type='".$this->db->escape($this->localtax2_type)."'"; - $sql.= " , qty=".price2num($this->qty); - $sql.= " , subprice=".price2num($this->subprice).""; - $sql.= " , remise_percent=".price2num($this->remise_percent).""; - $sql.= " , price=".price2num($this->price).""; // TODO A virer - $sql.= " , remise=".price2num($this->remise).""; // TODO A virer + $sql .= " description='".$this->db->escape($this->desc)."'"; + $sql .= " , label=".(!empty($this->label) ? "'".$this->db->escape($this->label)."'" : "null"); + $sql .= " , vat_src_code=".(!empty($this->vat_src_code) ? "'".$this->db->escape($this->vat_src_code)."'" : "''"); + $sql .= " , tva_tx=".price2num($this->tva_tx); + $sql .= " , localtax1_tx=".price2num($this->localtax1_tx); + $sql .= " , localtax2_tx=".price2num($this->localtax2_tx); + $sql .= " , localtax1_type='".$this->db->escape($this->localtax1_type)."'"; + $sql .= " , localtax2_type='".$this->db->escape($this->localtax2_type)."'"; + $sql .= " , qty=".price2num($this->qty); + $sql .= " , subprice=".price2num($this->subprice).""; + $sql .= " , remise_percent=".price2num($this->remise_percent).""; + $sql .= " , price=".price2num($this->price).""; // TODO A virer + $sql .= " , remise=".price2num($this->remise).""; // TODO A virer if (empty($this->skip_update_total)) { - $sql.= " , total_ht=".price2num($this->total_ht).""; - $sql.= " , total_tva=".price2num($this->total_tva).""; - $sql.= " , total_ttc=".price2num($this->total_ttc).""; - $sql.= " , total_localtax1=".price2num($this->total_localtax1); - $sql.= " , total_localtax2=".price2num($this->total_localtax2); + $sql .= " , total_ht=".price2num($this->total_ht).""; + $sql .= " , total_tva=".price2num($this->total_tva).""; + $sql .= " , total_ttc=".price2num($this->total_ttc).""; + $sql .= " , total_localtax1=".price2num($this->total_localtax1); + $sql .= " , total_localtax2=".price2num($this->total_localtax2); } - $sql.= " , fk_product_fournisseur_price=".(! empty($this->fk_fournprice)?$this->fk_fournprice:"null"); - $sql.= " , buy_price_ht='".price2num($this->pa_ht)."'"; - $sql.= " , info_bits=".$this->info_bits; - $sql.= " , special_code=".$this->special_code; - $sql.= " , date_start=".(! empty($this->date_start)?"'".$this->db->idate($this->date_start)."'":"null"); - $sql.= " , date_end=".(! empty($this->date_end)?"'".$this->db->idate($this->date_end)."'":"null"); - $sql.= " , product_type=".$this->product_type; - $sql.= " , fk_parent_line=".(! empty($this->fk_parent_line)?$this->fk_parent_line:"null"); - if (! empty($this->rang)) $sql.= ", rang=".$this->rang; - $sql.= " , fk_unit=".(!$this->fk_unit ? 'NULL' : $this->fk_unit); + $sql .= " , fk_product_fournisseur_price=".(!empty($this->fk_fournprice) ? $this->fk_fournprice : "null"); + $sql .= " , buy_price_ht='".price2num($this->pa_ht)."'"; + $sql .= " , info_bits=".$this->info_bits; + $sql .= " , special_code=".$this->special_code; + $sql .= " , date_start=".(!empty($this->date_start) ? "'".$this->db->idate($this->date_start)."'" : "null"); + $sql .= " , date_end=".(!empty($this->date_end) ? "'".$this->db->idate($this->date_end)."'" : "null"); + $sql .= " , product_type=".$this->product_type; + $sql .= " , fk_parent_line=".(!empty($this->fk_parent_line) ? $this->fk_parent_line : "null"); + if (!empty($this->rang)) $sql .= ", rang=".$this->rang; + $sql .= " , fk_unit=".(!$this->fk_unit ? 'NULL' : $this->fk_unit); // Multicurrency - $sql.= " , multicurrency_subprice=".price2num($this->multicurrency_subprice).""; - $sql.= " , multicurrency_total_ht=".price2num($this->multicurrency_total_ht).""; - $sql.= " , multicurrency_total_tva=".price2num($this->multicurrency_total_tva).""; - $sql.= " , multicurrency_total_ttc=".price2num($this->multicurrency_total_ttc).""; + $sql .= " , multicurrency_subprice=".price2num($this->multicurrency_subprice).""; + $sql .= " , multicurrency_total_ht=".price2num($this->multicurrency_total_ht).""; + $sql .= " , multicurrency_total_tva=".price2num($this->multicurrency_total_tva).""; + $sql .= " , multicurrency_total_ttc=".price2num($this->multicurrency_total_ttc).""; - $sql.= " WHERE rowid = ".$this->rowid; + $sql .= " WHERE rowid = ".$this->rowid; dol_syslog(get_class($this)."::update", LOG_DEBUG); - $resql=$this->db->query($sql); + $resql = $this->db->query($sql); if ($resql) { if (empty($conf->global->MAIN_EXTRAFIELDS_DISABLED)) // For avoid conflicts if trigger used { - $this->id=$this->rowid; - $result=$this->insertExtraFields(); + $this->id = $this->rowid; + $result = $this->insertExtraFields(); if ($result < 0) { $error++; } } - if (! $error && ! $notrigger) + if (!$error && !$notrigger) { // Call trigger - $result=$this->call_trigger('LINEORDER_UPDATE', $user); + $result = $this->call_trigger('LINEORDER_UPDATE', $user); if ($result < 0) $error++; // End call triggers } @@ -4426,17 +4426,17 @@ class OrderLine extends CommonOrderLine return 1; } - foreach($this->errors as $errmsg) + foreach ($this->errors as $errmsg) { dol_syslog(get_class($this)."::update ".$errmsg, LOG_ERR); - $this->error.=($this->error?', '.$errmsg:$errmsg); + $this->error .= ($this->error ? ', '.$errmsg : $errmsg); } $this->db->rollback(); - return -1*$error; + return -1 * $error; } else { - $this->error=$this->db->error(); + $this->error = $this->db->error(); $this->db->rollback(); return -2; } @@ -4455,21 +4455,21 @@ class OrderLine extends CommonOrderLine $this->db->begin(); // 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."commandedet SET"; - $sql.= " total_ht='".price2num($this->total_ht)."'"; - $sql.= ",total_tva='".price2num($this->total_tva)."'"; - $sql.= ",total_localtax1='".price2num($this->total_localtax1)."'"; - $sql.= ",total_localtax2='".price2num($this->total_localtax2)."'"; - $sql.= ",total_ttc='".price2num($this->total_ttc)."'"; - $sql.= " WHERE rowid = ".$this->rowid; + $sql .= " total_ht='".price2num($this->total_ht)."'"; + $sql .= ",total_tva='".price2num($this->total_tva)."'"; + $sql .= ",total_localtax1='".price2num($this->total_localtax1)."'"; + $sql .= ",total_localtax2='".price2num($this->total_localtax2)."'"; + $sql .= ",total_ttc='".price2num($this->total_ttc)."'"; + $sql .= " WHERE rowid = ".$this->rowid; dol_syslog("OrderLine::update_total", LOG_DEBUG); - $resql=$this->db->query($sql); + $resql = $this->db->query($sql); if ($resql) { $this->db->commit(); @@ -4477,7 +4477,7 @@ class OrderLine extends CommonOrderLine } else { - $this->error=$this->db->error(); + $this->error = $this->db->error(); $this->db->rollback(); return -2; } diff --git a/htdocs/commande/contact.php b/htdocs/commande/contact.php index 97890c9d2ef..10aaf0fd2ac 100644 --- a/htdocs/commande/contact.php +++ b/htdocs/commande/contact.php @@ -83,7 +83,7 @@ elseif ($action == 'swapstatut' && $user->rights->commande->creer) { if ($object->fetch($id)) { - $result=$object->swapContactStatus(GETPOST('ligne')); + $result = $object->swapContactStatus(GETPOST('ligne')); } else { @@ -124,8 +124,8 @@ llxHeader('', $langs->trans('Order'), 'EN:Customers_Orders|FR:Commandes_Clients| $form = new Form($db); $formcompany = new FormCompany($db); $formother = new FormOther($db); -$contactstatic=new Contact($db); -$userstatic=new User($db); +$contactstatic = new Contact($db); +$userstatic = new User($db); /* *************************************************************************** */ @@ -134,7 +134,7 @@ $userstatic=new User($db); /* */ /* *************************************************************************** */ -if ($id > 0 || ! empty($ref)) +if ($id > 0 || !empty($ref)) { $langs->trans("OrderCard"); @@ -200,10 +200,10 @@ if ($id > 0 || ! empty($ref)) print '
'; // 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) + $dirtpls = array_merge($conf->modules_parts['tpl'], array('/core/tpl')); + foreach ($dirtpls as $reldir) { - $res=@include dol_buildpath($reldir.'/contacts.tpl.php'); + $res = @include dol_buildpath($reldir.'/contacts.tpl.php'); if ($res) break; } } diff --git a/htdocs/commande/customer.php b/htdocs/commande/customer.php index bcb445c546c..f6594b5694a 100644 --- a/htdocs/commande/customer.php +++ b/htdocs/commande/customer.php @@ -123,7 +123,7 @@ if ($resql) print ''; - print '
'; + print '
'; print ''; print_liste_field_titre("Company", $_SERVER["PHP_SELF"], "s.nom", "", "", 'valign="center"', $sortfield, $sortorder); diff --git a/htdocs/commande/document.php b/htdocs/commande/document.php index 565583e1fae..8d5afb985a3 100644 --- a/htdocs/commande/document.php +++ b/htdocs/commande/document.php @@ -31,9 +31,9 @@ require_once DOL_DOCUMENT_ROOT.'/core/lib/order.lib.php'; require_once DOL_DOCUMENT_ROOT.'/core/lib/files.lib.php'; require_once DOL_DOCUMENT_ROOT.'/core/lib/images.lib.php'; require_once DOL_DOCUMENT_ROOT.'/core/class/html.formfile.class.php'; -require_once DOL_DOCUMENT_ROOT .'/commande/class/commande.class.php'; -if (! empty($conf->projet->enabled)) { - require_once DOL_DOCUMENT_ROOT . '/projet/class/project.class.php'; +require_once DOL_DOCUMENT_ROOT.'/commande/class/commande.class.php'; +if (!empty($conf->projet->enabled)) { + require_once DOL_DOCUMENT_ROOT.'/projet/class/project.class.php'; } // Load translation files required by the page @@ -49,7 +49,7 @@ if ($user->socid) { $socid = $user->socid; } -$result=restrictedArea($user, 'commande', $id, ''); +$result = restrictedArea($user, 'commande', $id, ''); // Get parameters $sortfield = GETPOST("sortfield", 'alpha'); @@ -76,10 +76,10 @@ $object = new Commande($db); if ($object->fetch($id)) { $object->fetch_thirdparty(); - $upload_dir = $conf->commande->multidir_output[$object->entity] . "/" . dol_sanitizeFileName($object->ref); + $upload_dir = $conf->commande->multidir_output[$object->entity]."/".dol_sanitizeFileName($object->ref); } -include_once DOL_DOCUMENT_ROOT . '/core/actions_linkedfiles.inc.php'; +include_once DOL_DOCUMENT_ROOT.'/core/actions_linkedfiles.inc.php'; /* @@ -90,7 +90,7 @@ llxHeader('', $langs->trans('Order'), 'EN:Customers_Orders|FR:Commandes_Clients| $form = new Form($db); -if ($id > 0 || ! empty($ref)) +if ($id > 0 || !empty($ref)) { if ($object->fetch($id, $ref)) { @@ -179,8 +179,8 @@ if ($id > 0 || ! empty($ref)) $modulepart = 'commande'; $permission = $user->rights->commande->creer; $permtoedit = $user->rights->commande->creer; - $param = '&id=' . $object->id.'&entity=' . (! empty($object->entity)?$object->entity:$conf->entity); - include_once DOL_DOCUMENT_ROOT . '/core/tpl/document_actions_post_headers.tpl.php'; + $param = '&id='.$object->id.'&entity='.(!empty($object->entity) ? $object->entity : $conf->entity); + include_once DOL_DOCUMENT_ROOT.'/core/tpl/document_actions_post_headers.tpl.php'; } else { diff --git a/htdocs/commande/index.php b/htdocs/commande/index.php index da1a4fc55df..d097b39b644 100644 --- a/htdocs/commande/index.php +++ b/htdocs/commande/index.php @@ -3,6 +3,7 @@ * Copyright (C) 2004-2011 Laurent Destailleur * Copyright (C) 2005-2012 Regis Houssin * Copyright (C) 2019 Nicolas ZABOURI + * Copyright (C) 2019 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 @@ -26,9 +27,9 @@ require '../main.inc.php'; 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.'/core/class/notify.class.php'; require_once DOL_DOCUMENT_ROOT.'/societe/class/client.class.php'; -require_once DOL_DOCUMENT_ROOT .'/commande/class/commande.class.php'; +require_once DOL_DOCUMENT_ROOT.'/commande/class/commande.class.php'; if (!$user->rights->commande->lire) accessforbidden(); @@ -41,7 +42,7 @@ $hookmanager->initHooks(array('ordersindex')); $langs->loadLangs(array('orders', 'bills')); // Security check -$socid=GETPOST('socid', 'int'); +$socid = GETPOST('socid', 'int'); if ($user->socid > 0) { $action = ''; @@ -54,11 +55,11 @@ if ($user->socid > 0) * View */ -$commandestatic=new Commande($db); -$companystatic=new Societe($db); +$commandestatic = new Commande($db); +$companystatic = new Societe($db); $form = new Form($db); $formfile = new FormFile($db); -$help_url="EN:Module_Customers_Orders|FR:Module_Commandes_Clients|ES:Módulo_Pedidos_de_clientes"; +$help_url = "EN:Module_Customers_Orders|FR:Module_Commandes_Clients|ES:Módulo_Pedidos_de_clientes"; llxHeader("", $langs->trans("Orders"), $help_url); @@ -68,17 +69,18 @@ print load_fiche_titre($langs->trans("OrdersArea"), '', 'commercial'); 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 orders - $var=false; + $var = false; print ''; print ''; - print '
'; + print '
'; + print '
'; print ''; print ''; - print "
'.$langs->trans("Search").'
'; print $langs->trans("CustomerOrder").':

\n"; + print "

\n"; } @@ -87,14 +89,14 @@ if (! empty($conf->global->MAIN_SEARCH_FORM_ON_HOME_AREAS)) // This is usele */ $sql = "SELECT count(c.rowid), c.fk_statut"; -$sql.= " FROM ".MAIN_DB_PREFIX."societe as s"; -$sql.= ", ".MAIN_DB_PREFIX."commande as c"; -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('societe').")"; -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 c.fk_statut"; +$sql .= " FROM ".MAIN_DB_PREFIX."societe as s"; +$sql .= ", ".MAIN_DB_PREFIX."commande as c"; +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('societe').")"; +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 c.fk_statut"; $resql = $db->query($sql); if ($resql) @@ -102,10 +104,10 @@ if ($resql) $num = $db->num_rows($resql); $i = 0; - $total=0; - $totalinprocess=0; - $dataseries=array(); - $vals=array(); + $total = 0; + $totalinprocess = 0; + $dataseries = array(); + $vals = array(); // -1=Canceled, 0=Draft, 1=Validated, 2=Accepted/On process, 3=Closed (Sent/Received, billed or not) while ($i < $num) { @@ -123,7 +125,8 @@ if ($resql) $i++; } $db->free($resql); - print ''; + print '
'; + print '
'; print ''."\n"; $listofstatus=array(0,1,2,3,-1); foreach ($listofstatus as $status) @@ -142,7 +145,7 @@ if ($resql) $dolgraph->SetType(array('pie')); $dolgraph->setWidth('100%'); $dolgraph->draw('idgraphstatus'); - print $dolgraph->show($total?0:1); + print $dolgraph->show($total ? 0 : 1); print ''; } @@ -152,7 +155,7 @@ if ($resql) { print ''; print ''; - print ''; @@ -161,7 +164,7 @@ if ($resql) } //if ($totalinprocess != $total) print ''; - print "
'.$langs->trans("Statistics").' - '.$langs->trans("CustomersOrders").'
'.$commandestatic->LibStatut($status, $bool, 0).''.(isset($vals[$status.$bool])?$vals[$status.$bool]:0).' '; + print ''.(isset($vals[$status.$bool]) ? $vals[$status.$bool] : 0).' '; print $commandestatic->LibStatut($status, $bool, 3); print ''; print '
'.$langs->trans("Total").''.$total.'

"; + print "

"; } else { @@ -172,25 +175,26 @@ else /* * Draft orders */ -if (! empty($conf->commande->enabled)) +if (!empty($conf->commande->enabled)) { $sql = "SELECT c.rowid, c.ref, s.nom as name, s.rowid as socid"; - $sql.= ", s.client"; - $sql.= ", s.code_client"; - $sql.= ", s.canvas"; - $sql.= " FROM ".MAIN_DB_PREFIX."commande as c"; - $sql.= ", ".MAIN_DB_PREFIX."societe as s"; - 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('commande').")"; - $sql.= " AND c.fk_statut = 0"; - 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; + $sql .= ", s.client"; + $sql .= ", s.code_client"; + $sql .= ", s.canvas"; + $sql .= " FROM ".MAIN_DB_PREFIX."commande as c"; + $sql .= ", ".MAIN_DB_PREFIX."societe as s"; + 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('commande').")"; + $sql .= " AND c.fk_statut = 0"; + 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; - $resql=$db->query($sql); + $resql = $db->query($sql); if ($resql) { - print ''; + print '
'; + print '
'; print ''; print ''; $langs->load("orders"); @@ -203,14 +207,14 @@ if (! empty($conf->commande->enabled)) { $obj = $db->fetch_object($resql); - $commandestatic->id=$obj->rowid; - $commandestatic->ref=$obj->ref; + $commandestatic->id = $obj->rowid; + $commandestatic->ref = $obj->ref; - $companystatic->id=$obj->socid; - $companystatic->name=$obj->name; - $companystatic->client=$obj->client; - $companystatic->code_client=$obj->code_client; - $companystatic->canvas=$obj->canvas; + $companystatic->id = $obj->socid; + $companystatic->name = $obj->name; + $companystatic->client = $obj->client; + $companystatic->code_client = $obj->code_client; + $companystatic->canvas = $obj->canvas; print ''; print ''; } - print "
'.$langs->trans("DraftOrders").'
'; @@ -226,7 +230,7 @@ if (! empty($conf->commande->enabled)) { print '
'.$langs->trans("NoOrder").'

"; + print "

"; } } @@ -234,32 +238,33 @@ if (! empty($conf->commande->enabled)) print '
'; -$max=5; +$max = 5; /* * Last modified orders */ $sql = "SELECT c.rowid, c.entity, c.ref, c.fk_statut, c.facture, c.date_cloture as datec, c.tms as datem,"; -$sql.= " s.nom as name, s.rowid as socid"; -$sql.= ", s.client"; -$sql.= ", s.code_client"; -$sql.= ", s.canvas"; -$sql.= " FROM ".MAIN_DB_PREFIX."commande as c,"; -$sql.= " ".MAIN_DB_PREFIX."societe as s"; -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('commande').")"; +$sql .= " s.nom as name, s.rowid as socid"; +$sql .= ", s.client"; +$sql .= ", s.code_client"; +$sql .= ", s.canvas"; +$sql .= " FROM ".MAIN_DB_PREFIX."commande as c,"; +$sql .= " ".MAIN_DB_PREFIX."societe as s"; +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('commande').")"; //$sql.= " AND c.fk_statut > 2"; 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; -$sql.= " ORDER BY c.tms DESC"; -$sql.= $db->plimit($max, 0); +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); +$resql = $db->query($sql); if ($resql) { - print ''; + print '
'; + print '
'; print ''; print ''; @@ -275,14 +280,14 @@ if ($resql) print ''; print '
'.$langs->trans("LastModifiedOrders", $max).'
'; - $commandestatic->id=$obj->rowid; - $commandestatic->ref=$obj->ref; + $commandestatic->id = $obj->rowid; + $commandestatic->ref = $obj->ref; - $companystatic->id=$obj->socid; - $companystatic->name=$obj->name; - $companystatic->client=$obj->client; - $companystatic->code_client=$obj->code_client; - $companystatic->canvas=$obj->canvas; + $companystatic->id = $obj->socid; + $companystatic->name = $obj->name; + $companystatic->client = $obj->client; + $companystatic->code_client = $obj->code_client; + $companystatic->canvas = $obj->canvas; print ''; print ''; print '
'; @@ -294,9 +299,9 @@ if ($resql) print ''; - $filename=dol_sanitizeFileName($obj->ref); - $filedir=$conf->commande->multidir_output[$obj->entity] . '/' . dol_sanitizeFileName($obj->ref); - $urlsource=$_SERVER['PHP_SELF'].'?id='.$obj->rowid; + $filename = dol_sanitizeFileName($obj->ref); + $filedir = $conf->commande->multidir_output[$obj->entity].'/'.dol_sanitizeFileName($obj->ref); + $urlsource = $_SERVER['PHP_SELF'].'?id='.$obj->rowid; print $formfile->getDocumentsLink($commandestatic->element, $filename, $filedir); print '
'; @@ -311,7 +316,7 @@ if ($resql) $i++; } } - print "

"; + print "

"; } else dol_print_error($db); @@ -319,28 +324,28 @@ else dol_print_error($db); /* * Orders to process */ -if (! empty($conf->commande->enabled)) +if (!empty($conf->commande->enabled)) { $sql = "SELECT c.rowid, c.entity, c.ref, c.fk_statut, c.facture, s.nom as name, s.rowid as socid"; - $sql.= ", s.client"; - $sql.= ", s.code_client"; - $sql.= ", s.canvas"; - $sql.=" FROM ".MAIN_DB_PREFIX."commande as c"; - $sql.= ", ".MAIN_DB_PREFIX."societe as s"; - 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('commande').")"; - $sql.= " AND c.fk_statut = 1"; - 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; - $sql.= " ORDER BY c.rowid DESC"; + $sql .= ", s.client"; + $sql .= ", s.code_client"; + $sql .= ", s.canvas"; + $sql .= " FROM ".MAIN_DB_PREFIX."commande as c"; + $sql .= ", ".MAIN_DB_PREFIX."societe as s"; + 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('commande').")"; + $sql .= " AND c.fk_statut = 1"; + 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; + $sql .= " ORDER BY c.rowid DESC"; - $resql=$db->query($sql); + $resql = $db->query($sql); if ($resql) { $num = $db->num_rows($resql); - - print ''; + print '
'; + print '
'; print ''; print ''; @@ -354,14 +359,14 @@ if (! empty($conf->commande->enabled)) print ''; print '
'.$langs->trans("OrdersToProcess").' '.$num.'
'; - $commandestatic->id=$obj->rowid; - $commandestatic->ref=$obj->ref; + $commandestatic->id = $obj->rowid; + $commandestatic->ref = $obj->ref; - $companystatic->id=$obj->socid; - $companystatic->name=$obj->name; - $companystatic->client=$obj->client; - $companystatic->code_client=$obj->code_client; - $companystatic->canvas=$obj->canvas; + $companystatic->id = $obj->socid; + $companystatic->name = $obj->name; + $companystatic->client = $obj->client; + $companystatic->code_client = $obj->code_client; + $companystatic->canvas = $obj->canvas; print ''; print ''; print '
'; @@ -373,9 +378,9 @@ if (! empty($conf->commande->enabled)) print ''; - $filename=dol_sanitizeFileName($obj->ref); - $filedir=$conf->commande->multidir_output[$obj->entity] . '/' . dol_sanitizeFileName($obj->ref); - $urlsource=$_SERVER['PHP_SELF'].'?id='.$obj->rowid; + $filename = dol_sanitizeFileName($obj->ref); + $filedir = $conf->commande->multidir_output[$obj->entity].'/'.dol_sanitizeFileName($obj->ref); + $urlsource = $_SERVER['PHP_SELF'].'?id='.$obj->rowid; print $formfile->getDocumentsLink($commandestatic->element, $filename, $filedir); print '
'; @@ -392,7 +397,7 @@ if (! empty($conf->commande->enabled)) } } - print "

"; + print "

"; } else dol_print_error($db); } @@ -400,28 +405,29 @@ if (! empty($conf->commande->enabled)) /* * Orders thar are in a shipping process */ -if (! empty($conf->commande->enabled)) +if (!empty($conf->commande->enabled)) { $sql = "SELECT c.rowid, c.entity, c.ref, c.fk_statut, c.facture, s.nom as name, s.rowid as socid"; - $sql.= ", s.client"; - $sql.= ", s.code_client"; - $sql.= ", s.canvas"; - $sql.= " FROM ".MAIN_DB_PREFIX."commande as c"; - $sql.= ", ".MAIN_DB_PREFIX."societe as s"; - 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('commande').")"; - $sql.= " AND c.fk_statut = 2 "; - 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; - $sql.= " ORDER BY c.rowid DESC"; + $sql .= ", s.client"; + $sql .= ", s.code_client"; + $sql .= ", s.canvas"; + $sql .= " FROM ".MAIN_DB_PREFIX."commande as c"; + $sql .= ", ".MAIN_DB_PREFIX."societe as s"; + 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('commande').")"; + $sql .= " AND c.fk_statut = 2 "; + 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; + $sql .= " ORDER BY c.rowid DESC"; - $resql=$db->query($sql); + $resql = $db->query($sql); if ($resql) { $num = $db->num_rows($resql); - print ''; + print '
'; + print '
'; print ''; print ''; @@ -435,14 +441,14 @@ if (! empty($conf->commande->enabled)) print ''; print '
'.$langs->trans("OnProcessOrders").' '.$num.'
'; - $commandestatic->id=$obj->rowid; - $commandestatic->ref=$obj->ref; + $commandestatic->id = $obj->rowid; + $commandestatic->ref = $obj->ref; - $companystatic->id=$obj->socid; - $companystatic->name=$obj->name; - $companystatic->client=$obj->client; - $companystatic->code_client=$obj->code_client; - $companystatic->canvas=$obj->canvas; + $companystatic->id = $obj->socid; + $companystatic->name = $obj->name; + $companystatic->client = $obj->client; + $companystatic->code_client = $obj->code_client; + $companystatic->canvas = $obj->canvas; print ''; print ''; print '
'; @@ -454,9 +460,9 @@ if (! empty($conf->commande->enabled)) print ''; - $filename=dol_sanitizeFileName($obj->ref); - $filedir=$conf->commande->multidir_output[$obj->entity] . '/' . dol_sanitizeFileName($obj->ref); - $urlsource=$_SERVER['PHP_SELF'].'?id='.$obj->rowid; + $filename = dol_sanitizeFileName($obj->ref); + $filedir = $conf->commande->multidir_output[$obj->entity].'/'.dol_sanitizeFileName($obj->ref); + $urlsource = $_SERVER['PHP_SELF'].'?id='.$obj->rowid; print $formfile->getDocumentsLink($commandestatic->element, $filename, $filedir); print '
'; @@ -472,7 +478,7 @@ if (! empty($conf->commande->enabled)) $i++; } } - print "

"; + print "

"; } else dol_print_error($db); } diff --git a/htdocs/commande/info.php b/htdocs/commande/info.php index 4ca81f77771..d509d3711b2 100644 --- a/htdocs/commande/info.php +++ b/htdocs/commande/info.php @@ -27,8 +27,8 @@ require '../main.inc.php'; require_once DOL_DOCUMENT_ROOT.'/core/lib/functions2.lib.php'; require_once DOL_DOCUMENT_ROOT.'/commande/class/commande.class.php'; require_once DOL_DOCUMENT_ROOT.'/core/lib/order.lib.php'; -if (! empty($conf->projet->enabled)) { - require_once DOL_DOCUMENT_ROOT . '/projet/class/project.class.php'; +if (!empty($conf->projet->enabled)) { + require_once DOL_DOCUMENT_ROOT.'/projet/class/project.class.php'; } if (!$user->rights->commande->lire) accessforbidden(); diff --git a/htdocs/commande/list.php b/htdocs/commande/list.php index dadc25737b6..1de1e64e0c7 100644 --- a/htdocs/commande/list.php +++ b/htdocs/commande/list.php @@ -47,54 +47,54 @@ require_once DOL_DOCUMENT_ROOT.'/product/class/product.class.php'; require_once DOL_DOCUMENT_ROOT.'/projet/class/project.class.php'; // Load translation files required by the page -$langs->loadLangs(array("orders",'sendings','deliveries','companies','compta','bills')); +$langs->loadLangs(array("orders", 'sendings', 'deliveries', 'companies', 'compta', 'bills')); -$action=GETPOST('action', 'aZ09'); -$massaction=GETPOST('massaction', 'alpha'); -$show_files=GETPOST('show_files', 'int'); -$confirm=GETPOST('confirm', 'alpha'); +$action = GETPOST('action', 'aZ09'); +$massaction = GETPOST('massaction', 'alpha'); +$show_files = GETPOST('show_files', 'int'); +$confirm = GETPOST('confirm', 'alpha'); $toselect = GETPOST('toselect', 'array'); -$contextpage=GETPOST('contextpage', 'aZ')?GETPOST('contextpage', 'aZ'):'orderlist'; +$contextpage = GETPOST('contextpage', 'aZ') ?GETPOST('contextpage', 'aZ') : 'orderlist'; -$search_orderyear=GETPOST("search_orderyear", "int"); -$search_ordermonth=GETPOST("search_ordermonth", "int"); -$search_orderday=GETPOST("search_orderday", "int"); -$search_deliveryyear=GETPOST("search_deliveryyear", "int"); -$search_deliverymonth=GETPOST("search_deliverymonth", "int"); -$search_deliveryday=GETPOST("search_deliveryday", "int"); -$search_product_category=GETPOST('search_product_category', 'int'); -$search_ref=GETPOST('search_ref', 'alpha')!=''?GETPOST('search_ref', 'alpha'):GETPOST('sref', 'alpha'); -$search_ref_customer=GETPOST('search_ref_customer', 'alpha'); -$search_company=GETPOST('search_company', 'alpha'); -$search_town=GETPOST('search_town', 'alpha'); -$search_zip=GETPOST('search_zip', 'alpha'); -$search_state=trim(GETPOST("search_state")); -$search_country=GETPOST("search_country", 'int'); -$search_type_thirdparty=GETPOST("search_type_thirdparty", 'int'); -$sall=trim((GETPOST('search_all', 'alphanohtml')!='')?GETPOST('search_all', 'alphanohtml'):GETPOST('sall', 'alphanohtml')); -$socid=GETPOST('socid', 'int'); -$search_user=GETPOST('search_user', 'int'); -$search_sale=GETPOST('search_sale', 'int'); -$search_total_ht=GETPOST('search_total_ht', 'alpha'); -$search_total_ttc=GETPOST('search_total_ttc', 'alpha'); -$search_categ_cus=trim(GETPOST("search_categ_cus", 'int')); +$search_orderyear = GETPOST("search_orderyear", "int"); +$search_ordermonth = GETPOST("search_ordermonth", "int"); +$search_orderday = GETPOST("search_orderday", "int"); +$search_deliveryyear = GETPOST("search_deliveryyear", "int"); +$search_deliverymonth = GETPOST("search_deliverymonth", "int"); +$search_deliveryday = GETPOST("search_deliveryday", "int"); +$search_product_category = GETPOST('search_product_category', 'int'); +$search_ref = GETPOST('search_ref', 'alpha') != '' ?GETPOST('search_ref', 'alpha') : GETPOST('sref', 'alpha'); +$search_ref_customer = GETPOST('search_ref_customer', 'alpha'); +$search_company = GETPOST('search_company', 'alpha'); +$search_town = GETPOST('search_town', 'alpha'); +$search_zip = GETPOST('search_zip', 'alpha'); +$search_state = trim(GETPOST("search_state")); +$search_country = GETPOST("search_country", 'int'); +$search_type_thirdparty = GETPOST("search_type_thirdparty", 'int'); +$sall = trim((GETPOST('search_all', 'alphanohtml') != '') ?GETPOST('search_all', 'alphanohtml') : GETPOST('sall', 'alphanohtml')); +$socid = GETPOST('socid', 'int'); +$search_user = GETPOST('search_user', 'int'); +$search_sale = GETPOST('search_sale', 'int'); +$search_total_ht = GETPOST('search_total_ht', 'alpha'); +$search_total_ttc = GETPOST('search_total_ttc', 'alpha'); +$search_categ_cus = trim(GETPOST("search_categ_cus", 'int')); $optioncss = GETPOST('optioncss', 'alpha'); $billed = GETPOST('billed', 'int'); -$viewstatut=GETPOST('viewstatut'); -$search_btn=GETPOST('button_search', 'alpha'); -$search_remove_btn=GETPOST('button_removefilter', 'alpha'); -$search_project_ref=GETPOST('search_project_ref', 'alpha'); -$search_project=GETPOST('search_project', 'alpha'); +$viewstatut = GETPOST('viewstatut'); +$search_btn = GETPOST('button_search', 'alpha'); +$search_remove_btn = GETPOST('button_removefilter', 'alpha'); +$search_project_ref = GETPOST('search_project_ref', 'alpha'); +$search_project = GETPOST('search_project', 'alpha'); // Security check -$id = (GETPOST('orderid')?GETPOST('orderid', 'int'):GETPOST('id', 'int')); -if ($user->socid) $socid=$user->socid; +$id = (GETPOST('orderid') ?GETPOST('orderid', 'int') : GETPOST('id', 'int')); +if ($user->socid) $socid = $user->socid; $result = restrictedArea($user, 'commande', $id, ''); -$diroutputmassaction=$conf->commande->multidir_output[$conf->entity] . '/temp/massgeneration/'.$user->id; +$diroutputmassaction = $conf->commande->multidir_output[$conf->entity].'/temp/massgeneration/'.$user->id; // Load variable for pagination -$limit = GETPOST('limit', 'int')?GETPOST('limit', 'int'):$conf->liste_limit; +$limit = GETPOST('limit', 'int') ?GETPOST('limit', 'int') : $conf->liste_limit; $sortfield = GETPOST("sortfield", 'alpha'); $sortorder = GETPOST("sortorder", 'alpha'); $page = GETPOST("page", 'int'); @@ -102,8 +102,8 @@ if (empty($page) || $page == -1 || !empty($search_btn) || !empty($search_remove_ $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'; // Initialize technical object to manage hooks of page. Note that conf->hooks_modules contains array of hook context $object = new Commande($db); @@ -112,7 +112,7 @@ $extrafields = new ExtraFields($db); // fetch optionals attributes and labels $extrafields->fetch_name_optionals_label('commande'); -$search_array_options=$extrafields->getOptionalsFromPost($object->table_element, '', 'search_'); +$search_array_options = $extrafields->getOptionalsFromPost($object->table_element, '', 'search_'); // List of fields to search into when doing a "search in all" $fieldstosearchall = array( @@ -123,14 +123,14 @@ $fieldstosearchall = array( 's.name_alias'=>"AliasNameShort", 'c.note_public'=>'NotePublic', ); -if (empty($user->socid)) $fieldstosearchall["c.note_private"]="NotePrivate"; +if (empty($user->socid)) $fieldstosearchall["c.note_private"] = "NotePrivate"; -$checkedtypetiers=0; -$arrayfields=array( +$checkedtypetiers = 0; +$arrayfields = array( 'c.ref'=>array('label'=>"Ref", 'checked'=>1), 'c.ref_client'=>array('label'=>"RefCustomerOrder", 'checked'=>1), - 'p.ref'=>array('label'=>"ProjectRef", 'checked'=>1, 'enabled'=>(empty($conf->projet->enabled)?0:1)), - 'p.title'=>array('label'=>"ProjectLabel", 'checked'=>0, 'enabled'=>(empty($conf->projet->enabled)?0:1)), + 'p.ref'=>array('label'=>"ProjectRef", 'checked'=>1, 'enabled'=>(empty($conf->projet->enabled) ? 0 : 1)), + 'p.title'=>array('label'=>"ProjectLabel", 'checked'=>0, 'enabled'=>(empty($conf->projet->enabled) ? 0 : 1)), 's.nom'=>array('label'=>"ThirdParty", 'checked'=>1), 's.town'=>array('label'=>"Town", 'checked'=>1), 's.zip'=>array('label'=>"Zip", 'checked'=>1), @@ -151,10 +151,10 @@ $arrayfields=array( // 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) + 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], 'checked'=>(($extrafields->attributes[$object->table_element]['list'][$key]<0)?0:1), 'position'=>$extrafields->attributes[$object->table_element]['pos'][$key], 'enabled'=>(abs($extrafields->attributes[$object->table_element]['list'][$key])!=3 && $extrafields->attributes[$object->table_element]['perms'][$key])); + if (!empty($extrafields->attributes[$object->table_element]['list'][$key])) + $arrayfields["ef.".$key] = array('label'=>$extrafields->attributes[$object->table_element]['label'][$key], 'checked'=>(($extrafields->attributes[$object->table_element]['list'][$key] < 0) ? 0 : 1), 'position'=>$extrafields->attributes[$object->table_element]['pos'][$key], 'enabled'=>(abs($extrafields->attributes[$object->table_element]['list'][$key]) != 3 && $extrafields->attributes[$object->table_element]['perms'][$key])); } } $object->fields = dol_sort_array($object->fields, 'position'); @@ -166,11 +166,11 @@ $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 +$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)) @@ -181,49 +181,49 @@ if (empty($reshook)) // Purge search criteria if (GETPOST('button_removefilter_x', 'alpha') || GETPOST('button_removefilter.x', 'alpha') || GETPOST('button_removefilter', 'alpha')) // All tests are required to be compatible with all browsers { - $search_categ=''; - $search_user=''; - $search_sale=''; - $search_product_category=''; - $search_ref=''; - $search_ref_customer=''; - $search_company=''; - $search_town=''; - $search_zip=""; - $search_state=""; - $search_type=''; - $search_country=''; - $search_type_thirdparty=''; - $search_total_ht=''; - $search_total_vat=''; - $search_total_ttc=''; - $search_orderyear=''; - $search_ordermonth=''; - $search_orderday=''; - $search_deliveryday=''; - $search_deliverymonth=''; - $search_deliveryyear=''; - $search_project_ref=''; - $search_project=''; - $viewstatut=''; - $billed=''; - $toselect=''; - $search_array_options=array(); - $search_categ_cus=0; + $search_categ = ''; + $search_user = ''; + $search_sale = ''; + $search_product_category = ''; + $search_ref = ''; + $search_ref_customer = ''; + $search_company = ''; + $search_town = ''; + $search_zip = ""; + $search_state = ""; + $search_type = ''; + $search_country = ''; + $search_type_thirdparty = ''; + $search_total_ht = ''; + $search_total_vat = ''; + $search_total_ttc = ''; + $search_orderyear = ''; + $search_ordermonth = ''; + $search_orderday = ''; + $search_deliveryday = ''; + $search_deliverymonth = ''; + $search_deliveryyear = ''; + $search_project_ref = ''; + $search_project = ''; + $viewstatut = ''; + $billed = ''; + $toselect = ''; + $search_array_options = array(); + $search_categ_cus = 0; } 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')) { - $massaction=''; // Protection to avoid mass action if we force a new search during a mass action confirmation + $massaction = ''; // Protection to avoid mass action if we force a new search during a mass action confirmation } // Mass actions - $objectclass='Commande'; - $objectlabel='Orders'; + $objectclass = 'Commande'; + $objectlabel = 'Orders'; $permissiontoread = $user->rights->commande->lire; $permissiontodelete = $user->rights->commande->supprimer; $uploaddir = $conf->commande->multidir_output[$conf->entity]; - $trigger_name='ORDER_SENTBYMAIL'; + $trigger_name = 'ORDER_SENTBYMAIL'; include DOL_DOCUMENT_ROOT.'/core/actions_massactions.inc.php'; } @@ -232,77 +232,77 @@ if (empty($reshook)) * View */ -$now=dol_now(); +$now = dol_now(); $form = new Form($db); $formother = new FormOther($db); $formfile = new FormFile($db); $companystatic = new Societe($db); -$formcompany=new FormCompany($db); -$projectstatic=new Project($db); +$formcompany = new FormCompany($db); +$projectstatic = new Project($db); -$title=$langs->trans("Orders"); -$help_url="EN:Module_Customers_Orders|FR:Module_Commandes_Clients|ES:Módulo_Pedidos_de_clientes"; +$title = $langs->trans("Orders"); +$help_url = "EN:Module_Customers_Orders|FR:Module_Commandes_Clients|ES:Módulo_Pedidos_de_clientes"; // llxHeader('',$title,$help_url); $sql = 'SELECT'; if ($sall || $search_product_category > 0) $sql = 'SELECT DISTINCT'; -$sql.= ' s.rowid as socid, s.nom as name, s.email, s.town, s.zip, s.fk_pays, s.client, s.code_client,'; -$sql.= " typent.code as typent_code,"; -$sql.= " state.code_departement as state_code, state.nom as state_name,"; -$sql.= ' c.rowid, c.ref, c.total_ht, c.tva as total_tva, c.total_ttc, c.ref_client,'; -$sql.= ' c.date_valid, c.date_commande, c.note_private, c.date_livraison as date_delivery, c.fk_statut, c.facture as billed,'; -$sql.= ' c.date_creation as date_creation, c.tms as date_update, c.date_cloture as date_cloture,'; -$sql.= " p.rowid as project_id, p.ref as project_ref, p.title as project_label"; +$sql .= ' s.rowid as socid, s.nom as name, s.email, s.town, s.zip, s.fk_pays, s.client, s.code_client,'; +$sql .= " typent.code as typent_code,"; +$sql .= " state.code_departement as state_code, state.nom as state_name,"; +$sql .= ' c.rowid, c.ref, c.total_ht, c.tva as total_tva, c.total_ttc, c.ref_client,'; +$sql .= ' c.date_valid, c.date_commande, c.note_private, c.date_livraison as date_delivery, c.fk_statut, c.facture as billed,'; +$sql .= ' c.date_creation as date_creation, c.tms as date_update, c.date_cloture as date_cloture,'; +$sql .= " p.rowid as project_id, p.ref as project_ref, p.title as project_label"; 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 : ''); +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 : ''); // 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.'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 -$sql.= ', '.MAIN_DB_PREFIX.'commande as c'; -if (is_array($extrafields->attributes[$object->table_element]['label']) && count($extrafields->attributes[$object->table_element]['label'])) $sql.= " LEFT JOIN ".MAIN_DB_PREFIX."commande_extrafields as ef on (c.rowid = ef.fk_object)"; -if ($sall || $search_product_category > 0) $sql.= ' LEFT JOIN '.MAIN_DB_PREFIX.'commandedet as pd ON c.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."projet as p ON p.rowid = c.fk_projet"; +$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.'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 +$sql .= ', '.MAIN_DB_PREFIX.'commande as c'; +if (is_array($extrafields->attributes[$object->table_element]['label']) && count($extrafields->attributes[$object->table_element]['label'])) $sql .= " LEFT JOIN ".MAIN_DB_PREFIX."commande_extrafields as ef on (c.rowid = ef.fk_object)"; +if ($sall || $search_product_category > 0) $sql .= ' LEFT JOIN '.MAIN_DB_PREFIX.'commandedet as pd ON c.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."projet as p ON p.rowid = c.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_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 .= ", ".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('commande').')'; -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; +$sql .= ' WHERE c.fk_soc = s.rowid'; +$sql .= ' AND c.entity IN ('.getEntity('commande').')'; +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('c.ref', $search_ref); -if ($search_ref_customer) $sql.= natural_search('c.ref_client', $search_ref_customer); +if ($search_ref_customer) $sql .= natural_search('c.ref_client', $search_ref_customer); if ($sall) $sql .= natural_search(array_keys($fieldstosearchall), $sall); -if ($billed != '' && $billed >= 0) $sql.=' AND c.facture = '.$billed; +if ($billed != '' && $billed >= 0) $sql .= ' AND c.facture = '.$billed; if ($viewstatut <> '') { if ($viewstatut < 4 && $viewstatut > -3) { - if ($viewstatut == 1 && empty($conf->expedition->enabled)) $sql.= ' AND c.fk_statut IN (1,2)'; // If module expedition disabled, we include order with status 'sending in process' into 'validated' - else $sql.= ' AND c.fk_statut = '.$viewstatut; // brouillon, validee, en cours, annulee + if ($viewstatut == 1 && empty($conf->expedition->enabled)) $sql .= ' AND c.fk_statut IN (1,2)'; // If module expedition disabled, we include order with status 'sending in process' into 'validated' + else $sql .= ' AND c.fk_statut = '.$viewstatut; // brouillon, validee, en cours, annulee } if ($viewstatut == 4) { - $sql.= ' AND c.facture = 1'; // invoice created + $sql .= ' AND c.facture = 1'; // invoice created } if ($viewstatut == -2) // To process { //$sql.= ' AND c.fk_statut IN (1,2,3) AND c.facture = 0'; - $sql.= " AND ((c.fk_statut IN (1,2)) OR (c.fk_statut = 3 AND c.facture = 0))"; // If status is 2 and facture=1, it must be selected + $sql .= " AND ((c.fk_statut IN (1,2)) OR (c.fk_statut = 3 AND c.facture = 0))"; // If status is 2 and facture=1, it must be selected } if ($viewstatut == -3) // To bill { @@ -311,30 +311,30 @@ if ($viewstatut <> '') $sql .= ' AND ((c.fk_statut IN (1,2)) OR (c.fk_statut = 3 AND c.facture = 0))'; // validated, in process or closed but not billed } } -$sql.= dolSqlDateFilter("c.date_commande", $search_orderday, $search_ordermonth, $search_orderyear); -$sql.= dolSqlDateFilter("c.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); +$sql .= dolSqlDateFilter("c.date_commande", $search_orderday, $search_ordermonth, $search_orderyear); +$sql .= dolSqlDateFilter("c.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 (".$search_country.')'; if ($search_type_thirdparty) $sql .= " AND s.fk_typent IN (".$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 = " .$search_sale; -if ($search_user > 0) $sql.= " AND ec.fk_c_type_contact = tc.rowid AND tc.element='commande' AND tc.source='internal' AND ec.element_id = c.rowid AND ec.fk_socpeople = ".$search_user; -if ($search_total_ht != '') $sql.= natural_search('c.total_ht', $search_total_ht, 1); -if ($search_total_ttc != '') $sql.= natural_search('c.total_ttc', $search_total_ttc, 1); -if ($search_project_ref != '') $sql.= natural_search("p.ref", $search_project_ref); -if ($search_project != '') $sql.= natural_search("p.title", $search_project); -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_sale > 0) $sql .= " AND s.rowid = sc.fk_soc AND sc.fk_user = ".$search_sale; +if ($search_user > 0) $sql .= " AND ec.fk_c_type_contact = tc.rowid AND tc.element='commande' AND tc.source='internal' AND ec.element_id = c.rowid AND ec.fk_socpeople = ".$search_user; +if ($search_total_ht != '') $sql .= natural_search('c.total_ht', $search_total_ht, 1); +if ($search_total_ttc != '') $sql .= natural_search('c.total_ttc', $search_total_ttc, 1); +if ($search_project_ref != '') $sql .= natural_search("p.ref", $search_project_ref); +if ($search_project != '') $sql .= natural_search("p.title", $search_project); +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"; // Add where from extra fields include DOL_DOCUMENT_ROOT.'/core/tpl/extrafields_list_search_sql.tpl.php'; // Add where from hooks -$parameters=array(); -$reshook=$hookmanager->executeHooks('printFieldListWhere', $parameters); // Note that $action and $object may have been modified by hook -$sql.=$hookmanager->resPrint; +$parameters = array(); +$reshook = $hookmanager->executeHooks('printFieldListWhere', $parameters); // Note that $action and $object may have been modified by hook +$sql .= $hookmanager->resPrint; -$sql.= $db->order($sortfield, $sortorder); +$sql .= $db->order($sortfield, $sortorder); // Count total nb of records $nbtotalofrecords = ''; @@ -350,7 +350,7 @@ if (empty($conf->global->MAIN_DISABLE_FULL_SCANLIST)) } } -$sql.= $db->plimit($limit + 1, $offset); +$sql .= $db->plimit($limit + 1, $offset); //print $sql; $resql = $db->query($sql); @@ -360,7 +360,7 @@ if ($resql) { $soc = new Societe($db); $soc->fetch($socid); - $title = $langs->trans('ListOfOrders') . ' - '.$soc->name; + $title = $langs->trans('ListOfOrders').' - '.$soc->name; if (empty($search_company)) $search_company = $soc->name; } else @@ -368,27 +368,27 @@ if ($resql) $title = $langs->trans('ListOfOrders'); } if (strval($viewstatut) == '0') - $title.=' - '.$langs->trans('StatusOrderDraftShort'); + $title .= ' - '.$langs->trans('StatusOrderDraftShort'); if ($viewstatut == 1) - $title.=' - '.$langs->trans('StatusOrderValidatedShort'); + $title .= ' - '.$langs->trans('StatusOrderValidatedShort'); if ($viewstatut == 2) - $title.=' - '.$langs->trans('StatusOrderSentShort'); + $title .= ' - '.$langs->trans('StatusOrderSentShort'); if ($viewstatut == 3) - $title.=' - '.$langs->trans('StatusOrderToBillShort'); + $title .= ' - '.$langs->trans('StatusOrderToBillShort'); if ($viewstatut == 4) - $title.=' - '.$langs->trans('StatusOrderProcessedShort'); + $title .= ' - '.$langs->trans('StatusOrderProcessedShort'); if ($viewstatut == -1) - $title.=' - '.$langs->trans('StatusOrderCanceledShort'); + $title .= ' - '.$langs->trans('StatusOrderCanceledShort'); if ($viewstatut == -2) - $title.=' - '.$langs->trans('StatusOrderToProcessShort'); + $title .= ' - '.$langs->trans('StatusOrderToProcessShort'); if ($viewstatut == -3) - $title.=' - '.$langs->trans('StatusOrderValidated').', '.(empty($conf->expedition->enabled)?'':$langs->trans("StatusOrderSent").', ').$langs->trans('StatusOrderToBill'); + $title .= ' - '.$langs->trans('StatusOrderValidated').', '.(empty($conf->expedition->enabled) ? '' : $langs->trans("StatusOrderSent").', ').$langs->trans('StatusOrderToBill'); $num = $db->num_rows($resql); - $arrayofselected=is_array($toselect)?$toselect:array(); + $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; @@ -398,58 +398,58 @@ if ($resql) llxHeader('', $title, $help_url); - $param=''; + $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 ($viewstatut != '') $param.='&viewstatut='.urlencode($viewstatut); - 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 ($search_town != '') $param.='&search_town='.urlencode($search_town); - if ($search_zip != '') $param.='&search_zip='.urlencode($search_zip); - if ($search_state != '') $param.='&search_state='.urlencode($search_state); - if ($search_country != '') $param.='&search_country='.urlencode($search_country); - if ($search_type_thirdparty != '') $param.='&search_type_thirdparty='.urlencode($search_type_thirdparty); - if ($search_product_category != '') $param.='&search_product_category='.urlencode($search_product_category); - if ($search_categ_cus > 0) $param.='&search_categ_cus='.urlencode($search_categ_cus); - 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 ($viewstatut != '') $param .= '&viewstatut='.urlencode($viewstatut); + 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 ($search_town != '') $param .= '&search_town='.urlencode($search_town); + if ($search_zip != '') $param .= '&search_zip='.urlencode($search_zip); + if ($search_state != '') $param .= '&search_state='.urlencode($search_state); + if ($search_country != '') $param .= '&search_country='.urlencode($search_country); + if ($search_type_thirdparty != '') $param .= '&search_type_thirdparty='.urlencode($search_type_thirdparty); + if ($search_product_category != '') $param .= '&search_product_category='.urlencode($search_product_category); + if ($search_categ_cus > 0) $param .= '&search_categ_cus='.urlencode($search_categ_cus); + if ($show_files) $param .= '&show_files='.urlencode($show_files); + if ($optioncss != '') $param .= '&optioncss='.urlencode($optioncss); + if ($billed != '') $param .= '&billed='.urlencode($billed); // Add $param from extra fields include DOL_DOCUMENT_ROOT.'/core/tpl/extrafields_list_search_param.tpl.php'; // List of mass actions available - $arrayofmassactions = array( + $arrayofmassactions = array( 'generate_doc'=>$langs->trans("ReGeneratePDF"), 'builddoc'=>$langs->trans("PDFMerge"), 'cancelorders'=>$langs->trans("Cancel"), 'presend'=>$langs->trans("SendByMail"), ); - if($user->rights->facture->creer) $arrayofmassactions['createbills']=$langs->trans("CreateInvoiceForThisCustomer"); - if ($user->rights->commande->supprimer) $arrayofmassactions['predelete']=''.$langs->trans("Delete"); - if (in_array($massaction, array('presend','predelete','createbills'))) $arrayofmassactions=array(); - $massactionbutton=$form->selectMassAction('', $arrayofmassactions); + if ($user->rights->facture->creer) $arrayofmassactions['createbills'] = $langs->trans("CreateInvoiceForThisCustomer"); + if ($user->rights->commande->supprimer) $arrayofmassactions['predelete'] = ''.$langs->trans("Delete"); + if (in_array($massaction, array('presend', 'predelete', 'createbills'))) $arrayofmassactions = array(); + $massactionbutton = $form->selectMassAction('', $arrayofmassactions); - $newcardbutton=''; + $newcardbutton = ''; if ($contextpage == 'orderlist' && $user->rights->commande->creer) { - $newcardbutton.= dolGetButtonTitle($langs->trans('NewOrder'), '', 'fa fa-plus-circle', DOL_URL_ROOT.'/commande/card.php?action=create'); + $newcardbutton .= dolGetButtonTitle($langs->trans('NewOrder'), '', 'fa fa-plus-circle', DOL_URL_ROOT.'/commande/card.php?action=create'); } // Lines of title fields @@ -468,10 +468,10 @@ if ($resql) print_barre_liste($title, $page, $_SERVER["PHP_SELF"], $param, $sortfield, $sortorder, $massactionbutton, $num, $nbtotalofrecords, 'commercial', 0, $newcardbutton, '', $limit); - $topicmail="SendOrderRef"; - $modelmail="order_send"; - $objecttmp=new Commande($db); - $trackid='ord'.$object->id; + $topicmail = "SendOrderRef"; + $modelmail = "order_send"; + $objecttmp = new Commande($db); + $trackid = 'ord'.$object->id; include DOL_DOCUMENT_ROOT.'/core/tpl/massactions_pre.tpl.php'; if ($massaction == 'createbills') @@ -501,7 +501,7 @@ if ($resql) print $langs->trans('ValidateInvoices'); print '
'; - if (! empty($conf->stock->enabled) && ! empty($conf->global->STOCK_CALCULATE_ON_BILL)) + if (!empty($conf->stock->enabled) && !empty($conf->global->STOCK_CALCULATE_ON_BILL)) { print $form->selectyesno('validate_invoices', 0, 1, 1); print ' ('.$langs->trans("AutoValidationNotPossibleWhenStockIsDecreasedOnInvoiceValidation").')'; @@ -510,7 +510,7 @@ if ($resql) { print $form->selectyesno('validate_invoices', 0, 1); } - if (! empty($conf->workflow->enabled) && ! empty($conf->global->WORKFLOW_INVOICE_AMOUNT_CLASSIFY_BILLED_ORDER)) print '     '.$langs->trans("IfValidateInvoiceIsNoOrderStayUnbilled").''; + if (!empty($conf->workflow->enabled) && !empty($conf->global->WORKFLOW_INVOICE_AMOUNT_CLASSIFY_BILLED_ORDER)) print '     '.$langs->trans("IfValidateInvoiceIsNoOrderStayUnbilled").''; else print '     '.$langs->trans("OptionToSetOrderBilledNotEnabled").''; print '
'."\n"; + print '
'."\n"; print ''; // Ref - if (! empty($arrayfields['c.ref']['checked'])) + if (!empty($arrayfields['c.ref']['checked'])) { print ''; } // Ref customer - if (! empty($arrayfields['c.ref_client']['checked'])) + if (!empty($arrayfields['c.ref_client']['checked'])) { print ''; } // Project ref - if (! empty($arrayfields['p.ref']['checked'])) + if (!empty($arrayfields['p.ref']['checked'])) { print ''; } // Project title - if (! empty($arrayfields['p.title']['checked'])) + if (!empty($arrayfields['p.title']['checked'])) { print ''; } // Thirpdarty - if (! empty($arrayfields['s.nom']['checked'])) + if (!empty($arrayfields['s.nom']['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 ''; } // Date order - if (! empty($arrayfields['c.date_commande']['checked'])) + if (!empty($arrayfields['c.date_commande']['checked'])) { print ''; } - if (! empty($arrayfields['c.date_delivery']['checked'])) + if (!empty($arrayfields['c.date_delivery']['checked'])) { print ''; } - if (! empty($arrayfields['c.total_ht']['checked'])) + if (!empty($arrayfields['c.total_ht']['checked'])) { // Amount print ''; } - if (! empty($arrayfields['c.total_vat']['checked'])) + if (!empty($arrayfields['c.total_vat']['checked'])) { // Amount print ''; } - if (! empty($arrayfields['c.total_ttc']['checked'])) + if (!empty($arrayfields['c.total_ttc']['checked'])) { // Amount print ''; } // Date modification - if (! empty($arrayfields['c.tms']['checked'])) + if (!empty($arrayfields['c.tms']['checked'])) { print ''; } // Date cloture - if (! empty($arrayfields['c.date_cloture']['checked'])) + if (!empty($arrayfields['c.date_cloture']['checked'])) { print ''; } // Status - if (! empty($arrayfields['c.fk_statut']['checked'])) + if (!empty($arrayfields['c.fk_statut']['checked'])) { print ''; } // Status billed - if (! empty($arrayfields['c.facture']['checked'])) + if (!empty($arrayfields['c.facture']['checked'])) { print ''; @@ -737,54 +737,54 @@ if ($resql) // Fields title 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_client']['checked'])) print_liste_field_titre($arrayfields['c.ref_client']['label'], $_SERVER["PHP_SELF"], 'c.ref_client', '', $param, '', $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.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['c.date_commande']['checked'])) print_liste_field_titre($arrayfields['c.date_commande']['label'], $_SERVER["PHP_SELF"], 'c.date_commande', '', $param, '', $sortfield, $sortorder, 'center '); - if (! empty($arrayfields['c.date_delivery']['checked'])) print_liste_field_titre($arrayfields['c.date_delivery']['label'], $_SERVER["PHP_SELF"], 'c.date_livraison', '', $param, '', $sortfield, $sortorder, 'center '); - if (! empty($arrayfields['c.total_ht']['checked'])) print_liste_field_titre($arrayfields['c.total_ht']['label'], $_SERVER["PHP_SELF"], 'c.total_ht', '', $param, '', $sortfield, $sortorder, 'right '); - if (! empty($arrayfields['c.total_vat']['checked'])) print_liste_field_titre($arrayfields['c.total_vat']['label'], $_SERVER["PHP_SELF"], 'c.tva', '', $param, '', $sortfield, $sortorder, 'right '); - if (! empty($arrayfields['c.total_ttc']['checked'])) print_liste_field_titre($arrayfields['c.total_ttc']['label'], $_SERVER["PHP_SELF"], 'c.total_ttc', '', $param, '', $sortfield, $sortorder, 'right '); + 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_client']['checked'])) print_liste_field_titre($arrayfields['c.ref_client']['label'], $_SERVER["PHP_SELF"], 'c.ref_client', '', $param, '', $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.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['c.date_commande']['checked'])) print_liste_field_titre($arrayfields['c.date_commande']['label'], $_SERVER["PHP_SELF"], 'c.date_commande', '', $param, '', $sortfield, $sortorder, 'center '); + if (!empty($arrayfields['c.date_delivery']['checked'])) print_liste_field_titre($arrayfields['c.date_delivery']['label'], $_SERVER["PHP_SELF"], 'c.date_livraison', '', $param, '', $sortfield, $sortorder, 'center '); + if (!empty($arrayfields['c.total_ht']['checked'])) print_liste_field_titre($arrayfields['c.total_ht']['label'], $_SERVER["PHP_SELF"], 'c.total_ht', '', $param, '', $sortfield, $sortorder, 'right '); + if (!empty($arrayfields['c.total_vat']['checked'])) print_liste_field_titre($arrayfields['c.total_vat']['label'], $_SERVER["PHP_SELF"], 'c.tva', '', $param, '', $sortfield, $sortorder, 'right '); + if (!empty($arrayfields['c.total_ttc']['checked'])) print_liste_field_titre($arrayfields['c.total_ttc']['label'], $_SERVER["PHP_SELF"], 'c.total_ttc', '', $param, '', $sortfield, $sortorder, 'right '); // 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 + $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['c.datec']['checked'])) print_liste_field_titre($arrayfields['c.datec']['label'], $_SERVER["PHP_SELF"], "c.date_creation", "", $param, '', $sortfield, $sortorder, 'center nowrap '); - if (! empty($arrayfields['c.tms']['checked'])) print_liste_field_titre($arrayfields['c.tms']['label'], $_SERVER["PHP_SELF"], "c.tms", "", $param, '', $sortfield, $sortorder, 'center nowrap '); - if (! empty($arrayfields['c.date_cloture']['checked'])) print_liste_field_titre($arrayfields['c.date_cloture']['label'], $_SERVER["PHP_SELF"], "c.date_cloture", "", $param, '', $sortfield, $sortorder, 'center nowrap '); - if (! empty($arrayfields['c.fk_statut']['checked'])) print_liste_field_titre($arrayfields['c.fk_statut']['label'], $_SERVER["PHP_SELF"], "c.fk_statut", "", $param, '', $sortfield, $sortorder, 'right '); - if (! empty($arrayfields['c.facture']['checked'])) print_liste_field_titre($arrayfields['c.facture']['label'], $_SERVER["PHP_SELF"], 'c.facture', '', $param, '', $sortfield, $sortorder, 'center '); + if (!empty($arrayfields['c.datec']['checked'])) print_liste_field_titre($arrayfields['c.datec']['label'], $_SERVER["PHP_SELF"], "c.date_creation", "", $param, '', $sortfield, $sortorder, 'center nowrap '); + if (!empty($arrayfields['c.tms']['checked'])) print_liste_field_titre($arrayfields['c.tms']['label'], $_SERVER["PHP_SELF"], "c.tms", "", $param, '', $sortfield, $sortorder, 'center nowrap '); + if (!empty($arrayfields['c.date_cloture']['checked'])) print_liste_field_titre($arrayfields['c.date_cloture']['label'], $_SERVER["PHP_SELF"], "c.date_cloture", "", $param, '', $sortfield, $sortorder, 'center nowrap '); + if (!empty($arrayfields['c.fk_statut']['checked'])) print_liste_field_titre($arrayfields['c.fk_statut']['label'], $_SERVER["PHP_SELF"], "c.fk_statut", "", $param, '', $sortfield, $sortorder, 'right '); + if (!empty($arrayfields['c.facture']['checked'])) print_liste_field_titre($arrayfields['c.facture']['label'], $_SERVER["PHP_SELF"], 'c.facture', '', $param, '', $sortfield, $sortorder, 'center '); print_liste_field_titre($selectedfields, $_SERVER["PHP_SELF"], "", '', $param, '', $sortfield, $sortorder, 'maxwidthsearch center '); print ''."\n"; - $total=0; - $subtotal=0; - $productstat_cache=array(); - $getNomUrl_cache=array(); + $total = 0; + $subtotal = 0; + $productstat_cache = array(); + $getNomUrl_cache = array(); $generic_commande = new Commande($db); $generic_product = new Product($db); - $i=0; - $totalarray=array(); + $i = 0; + $totalarray = array(); while ($i < min($num, $limit)) { $obj = $db->fetch_object($resql); - $notshippable=0; + $notshippable = 0; $warning = 0; - $text_info=''; - $text_warning=''; - $nbprod=0; + $text_info = ''; + $text_warning = ''; + $nbprod = 0; $companystatic->id = $obj->socid; $companystatic->code_client = $obj->code_client; @@ -795,8 +795,8 @@ if ($resql) $getNomUrl_cache[$obj->socid] = $companystatic->getNomUrl(1, 'customer'); } - $generic_commande->id=$obj->rowid; - $generic_commande->ref=$obj->ref; + $generic_commande->id = $obj->rowid; + $generic_commande->ref = $obj->ref; $generic_commande->statut = $obj->fk_statut; $generic_commande->date = $db->jdate($obj->date_commande); $generic_commande->date_livraison = $db->jdate($obj->date_delivery); @@ -805,21 +805,21 @@ if ($resql) $generic_commande->total_tva = $obj->total_tva; $generic_commande->total_ttc = $obj->total_ttc; - $projectstatic->id=$obj->project_id; - $projectstatic->ref=$obj->project_ref; - $projectstatic->title=$obj->project_label; + $projectstatic->id = $obj->project_id; + $projectstatic->ref = $obj->project_ref; + $projectstatic->title = $obj->project_label; print ''; // Ref - if (! empty($arrayfields['c.ref']['checked'])) + if (!empty($arrayfields['c.ref']['checked'])) { print ''; - if (! $i) $totalarray['nbfield']++; + if (!$i) $totalarray['nbfield']++; } // Ref customer - if (! empty($arrayfields['c.ref_client']['checked'])) + if (!empty($arrayfields['c.ref_client']['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 label - 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 '
'; 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, 0, 0, 0, '', 0, 0, 0, (empty($conf->global->SOCIETE_SORT_ON_TYPEENT)?'ASC':$conf->global->SOCIETE_SORT_ON_TYPEENT)); + print $form->selectarray("search_type_thirdparty", $formcompany->typent_array(0), $search_type_thirdparty, 0, 0, 0, '', 0, 0, 0, (empty($conf->global->SOCIETE_SORT_ON_TYPEENT) ? 'ASC' : $conf->global->SOCIETE_SORT_ON_TYPEENT)); 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_orderyear?$search_orderyear:-1, 'search_orderyear', 1, 20, 5); + $formother->select_year($search_orderyear ? $search_orderyear : -1, 'search_orderyear', 1, 20, 5); 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_deliveryyear?$search_deliveryyear:-1, 'search_deliveryyear', 1, 20, 5); + $formother->select_year($search_deliveryyear ? $search_deliveryyear : -1, 'search_deliveryyear', 1, 20, 5); print ''; print ''; print ''; print ''; print ''; @@ -684,32 +684,32 @@ if ($resql) // Extra fields include DOL_DOCUMENT_ROOT.'/core/tpl/extrafields_list_search_input.tpl.php'; // Fields from hook - $parameters=array('arrayfields'=>$arrayfields); - $reshook=$hookmanager->executeHooks('printFieldListOption', $parameters); // Note that $action and $object may have been modified by hook + $parameters = array('arrayfields'=>$arrayfields); + $reshook = $hookmanager->executeHooks('printFieldListOption', $parameters); // Note that $action and $object may have been modified by hook print $hookmanager->resPrint; // Date creation - if (! empty($arrayfields['c.datec']['checked'])) + if (!empty($arrayfields['c.datec']['checked'])) { print ''; print ''; print ''; print ''; - $liststatus=array( + $liststatus = array( Commande::STATUS_DRAFT=>$langs->trans("StatusOrderDraftShort"), Commande::STATUS_VALIDATED=>$langs->trans("StatusOrderValidated"), Commande::STATUS_SHIPMENTONPROCESS=>$langs->trans("StatusOrderSentShort"), @@ -721,7 +721,7 @@ if ($resql) print ''; print $form->selectyesno('billed', $billed, 1, 0, 1); @@ -729,7 +729,7 @@ if ($resql) } // Action column print ''; - $searchpicto=$form->showFilterButtons(); + $searchpicto = $form->showFilterButtons(); print $searchpicto; print '
'; - $generic_commande->lines=array(); + $generic_commande->lines = array(); $generic_commande->getLinesArray(); - print $generic_commande->getNomUrl(1, ($viewstatut != 2?0:$obj->fk_statut), 0, 0, 0, 1); + print $generic_commande->getNomUrl(1, ($viewstatut != 2 ? 0 : $obj->fk_statut), 0, 0, 0, 1); // Show shippable Icon (create subloop, so may be slow) if ($conf->stock->enabled) @@ -828,7 +828,7 @@ if ($resql) if (($obj->fk_statut > 0) && ($obj->fk_statut < 3)) { $numlines = count($generic_commande->lines); // Loop on each line of order - for ($lig=0; $lig < $numlines; $lig++) + for ($lig = 0; $lig < $numlines; $lig++) { if ($generic_commande->lines[$lig]->product_type == 0 && $generic_commande->lines[$lig]->fk_product > 0) // If line is a product and not a service { @@ -860,11 +860,11 @@ if ($resql) } else { // Detailed code, looks bugged // stock order and stock order_supplier - $stock_order=0; - $stock_order_supplier=0; - if (! empty($conf->global->STOCK_CALCULATE_ON_SHIPMENT) || ! empty($conf->global->STOCK_CALCULATE_ON_SHIPMENT_CLOSE)) // What about other options ? + $stock_order = 0; + $stock_order_supplier = 0; + if (!empty($conf->global->STOCK_CALCULATE_ON_SHIPMENT) || !empty($conf->global->STOCK_CALCULATE_ON_SHIPMENT_CLOSE)) // What about other options ? { - if (! empty($conf->commande->enabled)) + if (!empty($conf->commande->enabled)) { if (empty($productstat_cache[$generic_commande->lines[$lig]->fk_product]['stats_order_customer'])) { $generic_product->load_stats_commande(0, '1,2'); @@ -872,9 +872,9 @@ if ($resql) } else { $generic_product->stats_commande['qty'] = $productstat_cache[$generic_commande->lines[$lig]->fk_product]['stats_order_customer']; } - $stock_order=$generic_product->stats_commande['qty']; + $stock_order = $generic_product->stats_commande['qty']; } - if (! empty($conf->fournisseur->enabled)) + if (!empty($conf->fournisseur->enabled)) { if (empty($productstat_cache[$generic_commande->lines[$lig]->fk_product]['stats_order_supplier'])) { $generic_product->load_stats_commande_fournisseur(0, '3'); @@ -882,25 +882,25 @@ if ($resql) } else { $generic_product->stats_commande_fournisseur['qty'] = $productstat_cache[$generic_commande->lines[$lig]->fk_product]['stats_order_supplier']; } - $stock_order_supplier=$generic_product->stats_commande_fournisseur['qty']; + $stock_order_supplier = $generic_product->stats_commande_fournisseur['qty']; } } $text_info .= $generic_commande->lines[$lig]->qty.' X '.$generic_commande->lines[$lig]->ref.' '.dol_trunc($generic_commande->lines[$lig]->product_label, 25); $text_stock_reel = $generic_product->stock_reel.'/'.$stock_order; - if ($stock_order > $generic_product->stock_reel && ! ($generic_product->stock_reel < $generic_commande->lines[$lig]->qty)) { + if ($stock_order > $generic_product->stock_reel && !($generic_product->stock_reel < $generic_commande->lines[$lig]->qty)) { $warning++; - $text_warning.=''.$langs->trans('Available').' : '.$text_stock_reel.''; + $text_warning .= ''.$langs->trans('Available').' : '.$text_stock_reel.''; } if ($generic_product->stock_reel < $generic_commande->lines[$lig]->qty) { $notshippable++; - $text_info.=''.$langs->trans('Available').' : '.$text_stock_reel.''; + $text_info .= ''.$langs->trans('Available').' : '.$text_stock_reel.''; } else { - $text_info.=''.$langs->trans('Available').' : '.$text_stock_reel.''; + $text_info .= ''.$langs->trans('Available').' : '.$text_stock_reel.''; } - if (! empty($conf->fournisseur->enabled)) { - $text_info.= ' '.$langs->trans('SupplierOrder').' : '.$stock_order_supplier.'
'; + if (!empty($conf->fournisseur->enabled)) { + $text_info .= ' '.$langs->trans('SupplierOrder').' : '.$stock_order_supplier.'
'; } else { - $text_info.= '
'; + $text_info .= '
'; } } } @@ -934,24 +934,24 @@ if ($resql) print ''; } - $filename=dol_sanitizeFileName($obj->ref); - $filedir=$conf->commande->multidir_output[$conf->entity] . '/' . dol_sanitizeFileName($obj->ref); - $urlsource=$_SERVER['PHP_SELF'].'?id='.$obj->rowid; + $filename = dol_sanitizeFileName($obj->ref); + $filedir = $conf->commande->multidir_output[$conf->entity].'/'.dol_sanitizeFileName($obj->ref); + $urlsource = $_SERVER['PHP_SELF'].'?id='.$obj->rowid; print $formfile->getDocumentsLink($generic_commande->element, $filename, $filedir); print '
'.$obj->ref_client.''; if ($obj->project_id > 0) @@ -959,11 +959,11 @@ if ($resql) print $projectstatic->getNomUrl(1); } print ''; if ($obj->project_id > 0) @@ -971,17 +971,17 @@ if ($resql) print $projectstatic->title; } print ''; print $getNomUrl_cache[$obj->socid]; // If module invoices enabled and user with invoice creation permissions - if (! empty($conf->facture->enabled) && ! empty($conf->global->ORDER_BILLING_ALL_CUSTOMER)) + if (!empty($conf->facture->enabled) && !empty($conf->global->ORDER_BILLING_ALL_CUSTOMER)) { if ($user->rights->facture->creer) { @@ -1143,8 +1143,8 @@ if ($resql) $db->free($resql); - $parameters=array('arrayfields'=>$arrayfields, 'sql'=>$sql); - $reshook=$hookmanager->executeHooks('printFieldListFooter', $parameters); // Note that $action and $object may have been modified by hook + $parameters = array('arrayfields'=>$arrayfields, 'sql'=>$sql); + $reshook = $hookmanager->executeHooks('printFieldListFooter', $parameters); // Note that $action and $object may have been modified by hook print $hookmanager->resPrint; print '
'."\n"; @@ -1152,16 +1152,16 @@ if ($resql) print ''."\n"; - $hidegeneratedfilelistifempty=1; - if ($massaction == 'builddoc' || $action == 'remove_file' || $show_files) $hidegeneratedfilelistifempty=0; + $hidegeneratedfilelistifempty = 1; + if ($massaction == 'builddoc' || $action == 'remove_file' || $show_files) $hidegeneratedfilelistifempty = 0; // Show list of available documents - $urlsource=$_SERVER['PHP_SELF'].'?sortfield='.$sortfield.'&sortorder='.$sortorder; - $urlsource.=str_replace('&', '&', $param); + $urlsource = $_SERVER['PHP_SELF'].'?sortfield='.$sortfield.'&sortorder='.$sortorder; + $urlsource .= str_replace('&', '&', $param); - $filedir=$diroutputmassaction; - $genallowed=$user->rights->commande->lire; - $delallowed=$user->rights->commande->creer; + $filedir = $diroutputmassaction; + $genallowed = $user->rights->commande->lire; + $delallowed = $user->rights->commande->creer; print $formfile->showdocuments('massfilesarea_orders', '', $filedir, $urlsource, 0, $delallowed, '', 1, 1, 0, 48, 1, $param, $title, '', '', '', null, $hidegeneratedfilelistifempty); } diff --git a/htdocs/commande/note.php b/htdocs/commande/note.php index 5b8fe052b06..3c6b1c37de3 100644 --- a/htdocs/commande/note.php +++ b/htdocs/commande/note.php @@ -71,7 +71,7 @@ llxHeader('', $langs->trans('Order'), 'EN:Customers_Orders|FR:Commandes_Clients| $form = new Form($db); -if ($id > 0 || ! empty($ref)) +if ($id > 0 || !empty($ref)) { $object->fetch_thirdparty(); @@ -134,7 +134,7 @@ if ($id > 0 || ! empty($ref)) print '
'; - $cssclass="titlefield"; + $cssclass = "titlefield"; include DOL_DOCUMENT_ROOT.'/core/tpl/notes.tpl.php'; print ''; diff --git a/htdocs/commande/orderstoinvoice.php b/htdocs/commande/orderstoinvoice.php index 35756a56487..20014e58767 100644 --- a/htdocs/commande/orderstoinvoice.php +++ b/htdocs/commande/orderstoinvoice.php @@ -36,50 +36,50 @@ require_once DOL_DOCUMENT_ROOT.'/core/class/html.formfile.class.php'; require_once DOL_DOCUMENT_ROOT.'/core/class/html.formother.class.php'; require_once DOL_DOCUMENT_ROOT.'/core/lib/date.lib.php'; require_once DOL_DOCUMENT_ROOT.'/core/lib/report.lib.php'; -if (! empty($conf->projet->enabled)) { +if (!empty($conf->projet->enabled)) { require_once DOL_DOCUMENT_ROOT.'/core/class/html.formprojet.class.php'; } // Load translation files required by the page $langs->loadLangs(array("orders", "deliveries", "companies")); -if (! $user->rights->facture->creer) +if (!$user->rights->facture->creer) accessforbidden(); -$id = (GETPOST('id')?GETPOST('id', 'int'):GETPOST("facid", "int")); // For backward compatibility +$id = (GETPOST('id') ?GETPOST('id', 'int') : GETPOST("facid", "int")); // For backward compatibility $ref = GETPOST('ref', 'alpha'); $action = GETPOST('action', 'alpha'); $confirm = GETPOST('confirm', 'alpha'); $sref = GETPOST('sref', 'alpha'); -$sref_client = GETPOST('sref_client', 'alpha'); -$sall = trim((GETPOST('search_all', 'alphanohtml')!='')?GETPOST('search_all', 'alphanohtml'):GETPOST('sall', 'alphanohtml')); -$socid = GETPOST('socid', 'int'); -$selected = GETPOST('orders_to_invoice'); +$sref_client = GETPOST('sref_client', 'alpha'); +$sall = trim((GETPOST('search_all', 'alphanohtml') != '') ?GETPOST('search_all', 'alphanohtml') : GETPOST('sall', 'alphanohtml')); +$socid = GETPOST('socid', 'int'); +$selected = GETPOST('orders_to_invoice'); $sortfield = GETPOST("sortfield", 'alpha'); $sortorder = GETPOST("sortorder", 'alpha'); -$viewstatut = GETPOST('viewstatut', 'alpha'); +$viewstatut = GETPOST('viewstatut', 'alpha'); $error = 0; -if (! $sortfield) $sortfield='c.rowid'; -if (! $sortorder) $sortorder='DESC'; +if (!$sortfield) $sortfield = 'c.rowid'; +if (!$sortorder) $sortorder = 'DESC'; $now = dol_now(); -$date_start = dol_mktime(0, 0, 0, $_REQUEST["date_startmonth"], $_REQUEST["date_startday"], $_REQUEST["date_startyear"]); // Date for local PHP server +$date_start = dol_mktime(0, 0, 0, $_REQUEST["date_startmonth"], $_REQUEST["date_startday"], $_REQUEST["date_startyear"]); // Date for local PHP server $date_end = dol_mktime(23, 59, 59, $_REQUEST["date_endmonth"], $_REQUEST["date_endday"], $_REQUEST["date_endyear"]); -$date_starty = dol_mktime(0, 0, 0, $_REQUEST["date_start_delymonth"], $_REQUEST["date_start_delyday"], $_REQUEST["date_start_delyyear"]); // Date for local PHP server +$date_starty = dol_mktime(0, 0, 0, $_REQUEST["date_start_delymonth"], $_REQUEST["date_start_delyday"], $_REQUEST["date_start_delyyear"]); // Date for local PHP server $date_endy = dol_mktime(23, 59, 59, $_REQUEST["date_end_delymonth"], $_REQUEST["date_end_delyday"], $_REQUEST["date_end_delyyear"]); $extrafields = new ExtraFields($db); -$object=new Facture($db); +$object = new Facture($db); // fetch optionals attributes and labels $extrafields->fetch_name_optionals_label($object->table_element); if ($action == 'create') { - if (! is_array($selected)) + if (!is_array($selected)) { $error++; setEventMessages($langs->trans('Error_OrderNotChecked'), null, 'errors'); @@ -93,7 +93,7 @@ if ($action == 'create') // Initialize technical object to manage hooks of page. Note that conf->hooks_modules contains array of hook context include_once DOL_DOCUMENT_ROOT.'/core/class/hookmanager.class.php'; -$hookmanager=new HookManager($db); +$hookmanager = new HookManager($db); $hookmanager->initHooks(array('orderstoinvoice')); @@ -107,7 +107,7 @@ if (($action == 'create' || $action == 'add') && !$error) require_once DOL_DOCUMENT_ROOT.'/core/class/discount.class.php'; require_once DOL_DOCUMENT_ROOT.'/core/lib/functions2.lib.php'; require_once DOL_DOCUMENT_ROOT.'/core/lib/invoice.lib.php'; - if (! empty($conf->projet->enabled)) require_once DOL_DOCUMENT_ROOT.'/projet/class/project.class.php'; + if (!empty($conf->projet->enabled)) require_once DOL_DOCUMENT_ROOT.'/projet/class/project.class.php'; $langs->load('bills'); $langs->load('products'); @@ -118,8 +118,8 @@ if (($action == 'create' || $action == 'add') && !$error) $n = count($orders_id); $i = 0; - $originid=$orders_id[0]; - $_GET['originid']=$orders_id[0]; + $originid = $orders_id[0]; + $_GET['originid'] = $orders_id[0]; } if (isset($_POST['orders_to_invoice'])) { @@ -189,23 +189,23 @@ if (($action == 'create' || $action == 'add') && !$error) $id = $object->create($user); $object->fetch_thirdparty(); - if ($id>0) + if ($id > 0) { - foreach($orders_id as $origin => $origin_id) + foreach ($orders_id as $origin => $origin_id) { - $origin_id = (! empty($origin_id) ? $origin_id : $object->origin_id); + $origin_id = (!empty($origin_id) ? $origin_id : $object->origin_id); $db->begin(); $sql = "INSERT INTO ".MAIN_DB_PREFIX."element_element ("; - $sql.= "fk_source"; - $sql.= ", sourcetype"; - $sql.= ", fk_target"; - $sql.= ", targettype"; - $sql.= ") VALUES ("; - $sql.= $origin_id; - $sql.= ", '".$object->origin."'"; - $sql.= ", ".$id; - $sql.= ", '".$object->element."'"; - $sql.= ")"; + $sql .= "fk_source"; + $sql .= ", sourcetype"; + $sql .= ", fk_target"; + $sql .= ", targettype"; + $sql .= ") VALUES ("; + $sql .= $origin_id; + $sql .= ", '".$object->origin."'"; + $sql .= ", ".$id; + $sql .= ", '".$object->element."'"; + $sql .= ")"; if ($db->query($sql)) { @@ -222,7 +222,7 @@ if (($action == 'create' || $action == 'add') && !$error) include_once DOL_DOCUMENT_ROOT.'/commande/class/commande.class.php'; $objectsrc = new Commande($db); dol_syslog("Try to find source object origin=".$object->origin." originid=".$object->origin_id." to add lines"); - $result=$objectsrc->fetch($orders_id[$ii]); + $result = $objectsrc->fetch($orders_id[$ii]); if ($result > 0) { if ($closeOrders) @@ -236,26 +236,26 @@ if (($action == 'create' || $action == 'add') && !$error) $objectsrc->fetch_lines(); $lines = $objectsrc->lines; } - $fk_parent_line=0; - $num=count($lines); - for ($i=0;$i<$num;$i++) + $fk_parent_line = 0; + $num = count($lines); + for ($i = 0; $i < $num; $i++) { - $desc=($lines[$i]->desc?$lines[$i]->desc:$lines[$i]->libelle); + $desc = ($lines[$i]->desc ? $lines[$i]->desc : $lines[$i]->libelle); if ($lines[$i]->subprice < 0) { // Negative line, we create a discount line $discount = new DiscountAbsolute($db); - $discount->fk_soc=$object->socid; - $discount->amount_ht=abs($lines[$i]->total_ht); - $discount->amount_tva=abs($lines[$i]->total_tva); - $discount->amount_ttc=abs($lines[$i]->total_ttc); - $discount->tva_tx=$lines[$i]->tva_tx; - $discount->fk_user=$user->id; - $discount->description=$desc; - $discountid=$discount->create($user); + $discount->fk_soc = $object->socid; + $discount->amount_ht = abs($lines[$i]->total_ht); + $discount->amount_tva = abs($lines[$i]->total_tva); + $discount->amount_ttc = abs($lines[$i]->total_ttc); + $discount->tva_tx = $lines[$i]->tva_tx; + $discount->fk_user = $user->id; + $discount->description = $desc; + $discountid = $discount->create($user); if ($discountid > 0) { - $result=$object->insert_discount($discountid); + $result = $object->insert_discount($discountid); //$result=$discount->link_to_invoice($lineid,$id); } else @@ -268,17 +268,17 @@ if (($action == 'create' || $action == 'add') && !$error) else { // Positive line - $product_type=($lines[$i]->product_type?$lines[$i]->product_type:0); + $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; + $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; //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; + $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; // 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) { @@ -320,11 +320,11 @@ if (($action == 'create' || $action == 'add') && !$error) ); if ($result > 0) { - $lineid=$result; + $lineid = $result; } else { - $lineid=0; + $lineid = 0; $error++; break; } @@ -354,7 +354,7 @@ if (($action == 'create' || $action == 'add') && !$error) } // End of object creation, we show it - if ($id > 0 && ! $error) + if ($id > 0 && !$error) { $db->commit(); header('Location: '.DOL_URL_ROOT.'/compta/facture/card.php?facid='.$id); @@ -363,9 +363,9 @@ if (($action == 'create' || $action == 'add') && !$error) else { $db->rollback(); - $action='create'; - $_GET["origin"]=$_POST["origin"]; - $_GET["originid"]=$_POST["originid"]; + $action = 'create'; + $_GET["origin"] = $_POST["origin"]; + $_GET["originid"] = $_POST["originid"]; setEventMessages($object->error, $object->errors, 'errors'); $error++; } @@ -385,27 +385,27 @@ $companystatic = new Societe($db); // Mode creation if ($action == 'create' && !$error) { - $facturestatic=new Facture($db); + $facturestatic = new Facture($db); llxHeader(); print load_fiche_titre($langs->trans('NewBill')); $soc = new Societe($db); - if ($socid) $res=$soc->fetch($socid); + if ($socid) $res = $soc->fetch($socid); if ($res) { $cond_reglement_id = $soc->cond_reglement_id; $mode_reglement_id = $soc->mode_reglement_id; - $remise_percent = $soc->remise_percent; + $remise_percent = $soc->remise_percent; } - $remise_absolue = 0; - $dateinvoice = empty($conf->global->MAIN_AUTOFILL_DATE)?-1:''; + $remise_absolue = 0; + $dateinvoice = empty($conf->global->MAIN_AUTOFILL_DATE) ?-1 : ''; - $absolute_discount=$soc->getAvailableDiscounts(); + $absolute_discount = $soc->getAvailableDiscounts(); print '
'; print ''; print ''; - print '' ."\n"; + print ''."\n"; print ''; print ''; print ''; @@ -415,7 +415,7 @@ if ($action == 'create' && !$error) dol_fiche_head(); - print ''; + print '
'; // Ref print ''; @@ -433,9 +433,9 @@ if ($action == 'create' && !$error) // Standard invoice print ''."\n"; print '
'.$langs->trans('Ref').''.$langs->trans('Draft').'
'; - print ''; + print ''; print ''; - $desc=$html->textwithpicto($langs->trans("InvoiceStandardAsk"), $langs->transnoentities("InvoiceStandardDesc"), 1); + $desc = $html->textwithpicto($langs->trans("InvoiceStandardAsk"), $langs->transnoentities("InvoiceStandardDesc"), 1); print $desc; print '
'; @@ -446,16 +446,16 @@ if ($action == 'create' && !$error) print '
'.$langs->trans('PaymentConditionsShort').''; - $html->select_conditions_paiements(isset($_POST['cond_reglement_id'])?$_POST['cond_reglement_id']:$cond_reglement_id, 'cond_reglement_id'); + $html->select_conditions_paiements(isset($_POST['cond_reglement_id']) ? $_POST['cond_reglement_id'] : $cond_reglement_id, 'cond_reglement_id'); print '
'.$langs->trans('PaymentMode').''; - $html->select_types_paiements(isset($_POST['mode_reglement_id'])?$_POST['mode_reglement_id']:$mode_reglement_id, 'mode_reglement_id'); + $html->select_types_paiements(isset($_POST['mode_reglement_id']) ? $_POST['mode_reglement_id'] : $mode_reglement_id, 'mode_reglement_id'); print '
'.$langs->trans('Project').''; @@ -468,7 +468,7 @@ if ($action == 'create' && !$error) $listoforders = array(); foreach ($selected as $sel) { - $result=$objectsrc->fetch($sel); + $result = $objectsrc->fetch($sel); if ($result > 0) { $listoforders[] = $objectsrc->ref; @@ -476,12 +476,12 @@ if ($action == 'create' && !$error) } // Other attributes - $parameters=array('objectsrc' => $objectsrc, 'idsrc' => $listoforders); - $reshook=$hookmanager->executeHooks('formObjectOptions', $parameters, $object, $action); // Note that $action and $object may have been modified by hook + $parameters = array('objectsrc' => $objectsrc, 'idsrc' => $listoforders); + $reshook = $hookmanager->executeHooks('formObjectOptions', $parameters, $object, $action); // Note that $action and $object may have been modified by hook print $hookmanager->resPrint; if (empty($reshook)) { - $object=new Facture($db); + $object = new Facture($db); print $object->showOptionals($extrafields, 'edit'); } @@ -489,7 +489,7 @@ if ($action == 'create' && !$error) print '
'.$langs->trans('Model').''; include_once DOL_DOCUMENT_ROOT.'/core/modules/facture/modules_facture.php'; - $liste=ModelePDFFactures::liste_modeles($db); + $liste = ModelePDFFactures::liste_modeles($db); print $html->selectarray('model', $liste, $conf->global->FACTURE_ADDON_PDF); print "
'; + print '
'; print ''; print_liste_field_titre('Ref', $_SERVER["PHP_SELF"], 'c.ref', '', '&socid='.$socid, '', $sortfield, $sortorder); print_liste_field_titre('RefCustomerOrder', $_SERVER["PHP_SELF"], 'c.ref_client', '', '&socid='.$socid, '', $sortfield, $sortorder); @@ -664,8 +664,8 @@ if (($action != 'create' && $action != 'add') || ($action == 'create' && $error) print ''; print ''; print '
'; - $generic_commande->id=$objp->rowid; - $generic_commande->ref=$objp->ref; + $generic_commande->id = $objp->rowid; + $generic_commande->ref = $objp->ref; $generic_commande->statut = $objp->fk_statut; $generic_commande->date_commande = $db->jdate($objp->date_commande); $generic_commande->date_livraison = $db->jdate($objp->date_livraison); @@ -682,9 +682,9 @@ if (($action != 'create' && $action != 'add') || ($action == 'create' && $error) print ''; - $filename=dol_sanitizeFileName($objp->ref); - $filedir=$conf->commande->multidir_output[$objp->entity] . '/' . dol_sanitizeFileName($objp->ref); - $urlsource=$_SERVER['PHP_SELF'].'?id='.$objp->rowid; + $filename = dol_sanitizeFileName($objp->ref); + $filedir = $conf->commande->multidir_output[$objp->entity].'/'.dol_sanitizeFileName($objp->ref); + $urlsource = $_SERVER['PHP_SELF'].'?id='.$objp->rowid; print $formfile->getDocumentsLink($generic_commande->element, $filename, $filedir); print '
'; print '
'; print ''; - print '
'; +print '
'; print ''; // Company print '
'.$langs->trans("Filter").'
'.$langs->trans("ThirdParty").''; @@ -299,7 +299,7 @@ print '

'; print '
'; -print ''; +print '
'; print ''; print ''; print ''; @@ -350,7 +350,7 @@ print '
'; // Show graphs -print '
'.$langs->trans("Year").''.$langs->trans("NbOfOrders").'
'; +print ''; print ''; print '
'; if ($mesg) { print $mesg; } else { print $px1->show(); diff --git a/htdocs/compta/accounting-files.php b/htdocs/compta/accounting-files.php index f9d7e44794c..1d238a7b852 100644 --- a/htdocs/compta/accounting-files.php +++ b/htdocs/compta/accounting-files.php @@ -34,24 +34,24 @@ require_once DOL_DOCUMENT_ROOT.'/fourn/class/fournisseur.facture.class.php'; $langs->loadLangs(array("accountancy", "bills", "companies", "salaries", "compta")); -$date_start =GETPOST('date_start', 'alpha'); -$date_startDay= GETPOST('date_startday', 'int'); -$date_startMonth= GETPOST('date_startmonth', 'int'); -$date_startYear= GETPOST('date_startyear', 'int'); -$date_start=($date_startDay)?dol_mktime(0, 0, 0, $date_startMonth, $date_startDay, $date_startYear):strtotime($date_start); -$date_stop =GETPOST('date_stop', 'alpha'); -$date_stopDay= GETPOST('date_stopday', 'int'); -$date_stopMonth= GETPOST('date_stopmonth', 'int'); -$date_stopYear= GETPOST('date_stopyear', 'int'); +$date_start = GETPOST('date_start', 'alpha'); +$date_startDay = GETPOST('date_startday', 'int'); +$date_startMonth = GETPOST('date_startmonth', 'int'); +$date_startYear = GETPOST('date_startyear', 'int'); +$date_start = ($date_startDay) ?dol_mktime(0, 0, 0, $date_startMonth, $date_startDay, $date_startYear) : strtotime($date_start); +$date_stop = GETPOST('date_stop', 'alpha'); +$date_stopDay = GETPOST('date_stopday', 'int'); +$date_stopMonth = GETPOST('date_stopmonth', 'int'); +$date_stopYear = GETPOST('date_stopyear', 'int'); //FIXME doldate -$date_stop=($date_stopDay)?dol_mktime(23, 59, 59, $date_stopMonth, $date_stopDay, $date_stopYear):strtotime($date_stop); -$action =GETPOST('action', 'alpha'); +$date_stop = ($date_stopDay) ?dol_mktime(23, 59, 59, $date_stopMonth, $date_stopDay, $date_stopYear) : strtotime($date_stop); +$action = GETPOST('action', 'alpha'); // Initialize technical object to manage hooks of page. Note that conf->hooks_modules contains array of hook context -$hookmanager->initHooks(array('comptafileslist','globallist')); +$hookmanager->initHooks(array('comptafileslist', 'globallist')); // Load variable for pagination -$limit = GETPOST('limit', 'int')?GETPOST('limit', 'int'):$conf->liste_limit; +$limit = GETPOST('limit', 'int') ?GETPOST('limit', 'int') : $conf->liste_limit; $sortfield = GETPOST('sortfield', 'alpha'); $sortorder = GETPOST('sortorder', 'alpha'); $page = GETPOST('page', 'int'); @@ -59,11 +59,11 @@ if (empty($page) || $page == -1) { $page = 0; } // If $page is not defined, $offset = $limit * $page; $pageprev = $page - 1; $pagenext = $page + 1; -if (! $sortfield) $sortfield="date,item"; // Set here default search field -if (! $sortorder) $sortorder="DESC"; +if (!$sortfield) $sortfield = "date,item"; // Set here default search field +if (!$sortorder) $sortorder = "DESC"; -$arrayfields=array( +$arrayfields = array( 'type'=>array('label'=>"Type", 'checked'=>1), 'date'=>array('label'=>"Date", 'checked'=>1), //... @@ -77,7 +77,7 @@ if ($user->socid > 0) { accessforbidden(); } -$entity = GETPOST('entity', 'int')?GETPOST('entity', 'int'):$conf->entity; +$entity = GETPOST('entity', 'int') ?GETPOST('entity', 'int') : $conf->entity; /* @@ -89,9 +89,9 @@ $entity = GETPOST('entity', 'int')?GETPOST('entity', 'int'):$conf->entity; //$reshook = $hookmanager->executeHooks('doActions', $parameters, $object); // Note that $object may have been modified by some hooks //if ($reshook < 0) setEventMessages($hookmanager->error, $hookmanager->errors, 'errors'); -$filesarray=array(); -$result=false; -if (($action=="searchfiles" || $action=="dl" )) { +$filesarray = array(); +$result = false; +if (($action == "searchfiles" || $action == "dl")) { if (empty($date_start)) { setEventMessages($langs->trans("ErrorFieldRequired", $langs->transnoentitiesnoconv("DateStart")), null, 'errors'); @@ -103,159 +103,159 @@ if (($action=="searchfiles" || $action=="dl" )) { $error++; } - if (! $error) + if (!$error) { - $wheretail=" '".$db->idate($date_start)."' AND '".$db->idate($date_stop)."'"; + $wheretail = " '".$db->idate($date_start)."' AND '".$db->idate($date_stop)."'"; - $sql="SELECT t.rowid as id, t.ref, t.paye as paid, total as total_ht, total_ttc, tva as total_vat, fk_soc, t.datef as date, 'Invoice' as item, s.nom as thirdparty_name, s.code_client as thirdparty_code, c.code as country_code, s.tva_intra as vatnum"; - $sql.=" FROM ".MAIN_DB_PREFIX."facture as t LEFT JOIN ".MAIN_DB_PREFIX."societe as s ON s.rowid = t.fk_soc LEFT JOIN ".MAIN_DB_PREFIX."c_country as c ON c.rowid = s.fk_pays"; - $sql.=" WHERE datef between ".$wheretail; - $sql.=" AND t.entity IN (".($entity==1?'0,1':$entity).')'; - $sql.=" AND t.fk_statut <> ".Facture::STATUS_DRAFT; - $sql.=" UNION ALL"; - $sql.=" SELECT t.rowid as id, t.ref, paye as paid, total_ht, total_ttc, total_tva as total_vat, fk_soc, datef as date, 'SupplierInvoice' as item, s.nom as thirdparty_name, s.code_fournisseur as thirdparty_code, c.code as country_code, s.tva_intra as vatnum"; - $sql.=" FROM ".MAIN_DB_PREFIX."facture_fourn as t LEFT JOIN ".MAIN_DB_PREFIX."societe as s ON s.rowid = t.fk_soc LEFT JOIN ".MAIN_DB_PREFIX."c_country as c ON c.rowid = s.fk_pays"; - $sql.=" WHERE datef between ".$wheretail; - $sql.=" AND t.entity IN (".($entity==1?'0,1':$entity).')'; - $sql.=" AND t.fk_statut <> ".FactureFournisseur::STATUS_DRAFT; - $sql.=" UNION ALL"; - $sql.=" SELECT t.rowid as id, t.ref, paid, total_ht, total_ttc, total_tva as total_vat, fk_user_author as fk_soc, date_fin as date, 'ExpenseReport' as item, CONCAT(CONCAT(u.lastname, ' '), u.firstname) as thirdparty_name, '' as thirdparty_code, c.code as country_code, '' as vatnum"; - $sql.=" FROM ".MAIN_DB_PREFIX."expensereport as t LEFT JOIN ".MAIN_DB_PREFIX."user as u ON u.rowid = t.fk_user_author LEFT JOIN ".MAIN_DB_PREFIX."c_country as c ON c.rowid = u.fk_country"; - $sql.=" WHERE date_fin between ".$wheretail; - $sql.=" AND t.entity IN (".($entity==1?'0,1':$entity).')'; - $sql.=" AND t.fk_statut <> ".ExpenseReport::STATUS_DRAFT; - $sql.=" UNION ALL"; - $sql.=" SELECT t.rowid as id, t.ref, paid, amount as total_ht, amount as total_ttc, 0 as total_vat, 0 as fk_soc, datedon as date, 'Donation' as item, t.societe as thirdparty_name, '' as thirdparty_code, c.code as country_code, '' as vatnum"; - $sql.=" FROM ".MAIN_DB_PREFIX."don as t LEFT JOIN ".MAIN_DB_PREFIX."c_country as c ON c.rowid = t.fk_country"; - $sql.=" WHERE datedon between ".$wheretail; - $sql.=" AND t.entity IN (".($entity==1?'0,1':$entity).')'; - $sql.=" AND t.fk_statut <> ".Don::STATUS_DRAFT; - $sql.=" UNION ALL"; - $sql.=" SELECT t.rowid as id, t.label as ref, 1 as paid, amount as total_ht, amount as total_ttc, 0 as total_vat, t.fk_user as fk_soc, datep as date, 'SalaryPayment' as item, CONCAT(CONCAT(u.lastname, ' '), u.firstname) as thirdparty_name, '' as thirdparty_code, c.code as country_code, '' as vatnum"; - $sql.=" FROM ".MAIN_DB_PREFIX."payment_salary as t LEFT JOIN ".MAIN_DB_PREFIX."user as u ON u.rowid = t.fk_user LEFT JOIN ".MAIN_DB_PREFIX."c_country as c ON c.rowid = u.fk_country"; - $sql.=" WHERE datep between ".$wheretail; - $sql.=" AND t.entity IN (".($entity==1?'0,1':$entity).')'; + $sql = "SELECT t.rowid as id, t.ref, t.paye as paid, total as total_ht, total_ttc, tva as total_vat, fk_soc, t.datef as date, 'Invoice' as item, s.nom as thirdparty_name, s.code_client as thirdparty_code, c.code as country_code, s.tva_intra as vatnum"; + $sql .= " FROM ".MAIN_DB_PREFIX."facture as t LEFT JOIN ".MAIN_DB_PREFIX."societe as s ON s.rowid = t.fk_soc LEFT JOIN ".MAIN_DB_PREFIX."c_country as c ON c.rowid = s.fk_pays"; + $sql .= " WHERE datef between ".$wheretail; + $sql .= " AND t.entity IN (".($entity == 1 ? '0,1' : $entity).')'; + $sql .= " AND t.fk_statut <> ".Facture::STATUS_DRAFT; + $sql .= " UNION ALL"; + $sql .= " SELECT t.rowid as id, t.ref, paye as paid, total_ht, total_ttc, total_tva as total_vat, fk_soc, datef as date, 'SupplierInvoice' as item, s.nom as thirdparty_name, s.code_fournisseur as thirdparty_code, c.code as country_code, s.tva_intra as vatnum"; + $sql .= " FROM ".MAIN_DB_PREFIX."facture_fourn as t LEFT JOIN ".MAIN_DB_PREFIX."societe as s ON s.rowid = t.fk_soc LEFT JOIN ".MAIN_DB_PREFIX."c_country as c ON c.rowid = s.fk_pays"; + $sql .= " WHERE datef between ".$wheretail; + $sql .= " AND t.entity IN (".($entity == 1 ? '0,1' : $entity).')'; + $sql .= " AND t.fk_statut <> ".FactureFournisseur::STATUS_DRAFT; + $sql .= " UNION ALL"; + $sql .= " SELECT t.rowid as id, t.ref, paid, total_ht, total_ttc, total_tva as total_vat, fk_user_author as fk_soc, date_fin as date, 'ExpenseReport' as item, CONCAT(CONCAT(u.lastname, ' '), u.firstname) as thirdparty_name, '' as thirdparty_code, c.code as country_code, '' as vatnum"; + $sql .= " FROM ".MAIN_DB_PREFIX."expensereport as t LEFT JOIN ".MAIN_DB_PREFIX."user as u ON u.rowid = t.fk_user_author LEFT JOIN ".MAIN_DB_PREFIX."c_country as c ON c.rowid = u.fk_country"; + $sql .= " WHERE date_fin between ".$wheretail; + $sql .= " AND t.entity IN (".($entity == 1 ? '0,1' : $entity).')'; + $sql .= " AND t.fk_statut <> ".ExpenseReport::STATUS_DRAFT; + $sql .= " UNION ALL"; + $sql .= " SELECT t.rowid as id, t.ref, paid, amount as total_ht, amount as total_ttc, 0 as total_vat, 0 as fk_soc, datedon as date, 'Donation' as item, t.societe as thirdparty_name, '' as thirdparty_code, c.code as country_code, '' as vatnum"; + $sql .= " FROM ".MAIN_DB_PREFIX."don as t LEFT JOIN ".MAIN_DB_PREFIX."c_country as c ON c.rowid = t.fk_country"; + $sql .= " WHERE datedon between ".$wheretail; + $sql .= " AND t.entity IN (".($entity == 1 ? '0,1' : $entity).')'; + $sql .= " AND t.fk_statut <> ".Don::STATUS_DRAFT; + $sql .= " UNION ALL"; + $sql .= " SELECT t.rowid as id, t.label as ref, 1 as paid, amount as total_ht, amount as total_ttc, 0 as total_vat, t.fk_user as fk_soc, datep as date, 'SalaryPayment' as item, CONCAT(CONCAT(u.lastname, ' '), u.firstname) as thirdparty_name, '' as thirdparty_code, c.code as country_code, '' as vatnum"; + $sql .= " FROM ".MAIN_DB_PREFIX."payment_salary as t LEFT JOIN ".MAIN_DB_PREFIX."user as u ON u.rowid = t.fk_user LEFT JOIN ".MAIN_DB_PREFIX."c_country as c ON c.rowid = u.fk_country"; + $sql .= " WHERE datep between ".$wheretail; + $sql .= " AND t.entity IN (".($entity == 1 ? '0,1' : $entity).')'; //$sql.=" AND fk_statut <> ".PaymentSalary::STATUS_DRAFT; - $sql.=" UNION ALL"; - $sql.=" SELECT t.rowid as id, t.libelle as ref, paye as paid, amount as total_ht, amount as total_ttc, 0 as total_tva, 0 as fk_soc, date_creation as date, 'SocialContributions' as item, '' as thirdparty_name, '' as thirdparty_code, '' as country_code, '' as vatnum"; - $sql.=" FROM ".MAIN_DB_PREFIX."chargesociales as t"; - $sql.=" WHERE date_creation between ".$wheretail; - $sql.=" AND t.entity IN (".($entity==1?'0,1':$entity).')'; + $sql .= " UNION ALL"; + $sql .= " SELECT t.rowid as id, t.libelle as ref, paye as paid, amount as total_ht, amount as total_ttc, 0 as total_tva, 0 as fk_soc, date_creation as date, 'SocialContributions' as item, '' as thirdparty_name, '' as thirdparty_code, '' as country_code, '' as vatnum"; + $sql .= " FROM ".MAIN_DB_PREFIX."chargesociales as t"; + $sql .= " WHERE date_creation between ".$wheretail; + $sql .= " AND t.entity IN (".($entity == 1 ? '0,1' : $entity).')'; //$sql.=" AND fk_statut <> ".ChargeSociales::STATUS_DRAFT; - $sql.= $db->order($sortfield, $sortorder); + $sql .= $db->order($sortfield, $sortorder); //print $sql; $resd = $db->query($sql); - $files=array(); - $link=''; + $files = array(); + $link = ''; if ($resd) { $numd = $db->num_rows($resd); - $tmpinvoice=new Facture($db); - $tmpinvoicesupplier=new FactureFournisseur($db); - $tmpdonation=new Don($db); + $tmpinvoice = new Facture($db); + $tmpinvoicesupplier = new FactureFournisseur($db); + $tmpdonation = new Don($db); - $upload_dir =''; - $i=0; + $upload_dir = ''; + $i = 0; while ($i < $numd) { $objd = $db->fetch_object($resd); - switch($objd->item) + switch ($objd->item) { case "Invoice": $subdir = ''; - $subdir.=($subdir ? '/' : '').dol_sanitizeFileName($objd->ref); + $subdir .= ($subdir ? '/' : '').dol_sanitizeFileName($objd->ref); $upload_dir = $conf->facture->dir_output.'/'.$subdir; - $link="document.php?modulepart=facture&file=".str_replace('/', '%2F', $subdir).'%2F'; + $link = "document.php?modulepart=facture&file=".str_replace('/', '%2F', $subdir).'%2F'; break; case "SupplierInvoice": $tmpinvoicesupplier->fetch($objd->id); - $subdir = get_exdir($tmpinvoicesupplier->id, 2, 0, 1, $tmpinvoicesupplier, 'invoice_supplier'); // TODO Use first file - $subdir.=($subdir ? '/' : '').dol_sanitizeFileName($objd->ref); + $subdir = get_exdir($tmpinvoicesupplier->id, 2, 0, 1, $tmpinvoicesupplier, 'invoice_supplier'); // TODO Use first file + $subdir .= ($subdir ? '/' : '').dol_sanitizeFileName($objd->ref); $upload_dir = $conf->fournisseur->facture->dir_output.'/'.$subdir; - $link="document.php?modulepart=facture_fournisseur&file=".str_replace('/', '%2F', $subdir).'%2F'; + $link = "document.php?modulepart=facture_fournisseur&file=".str_replace('/', '%2F', $subdir).'%2F'; break; case "ExpenseReport": $subdir = ''; - $subdir.=($subdir ? '/' : '').dol_sanitizeFileName($objd->ref); + $subdir .= ($subdir ? '/' : '').dol_sanitizeFileName($objd->ref); $upload_dir = $conf->expensereport->dir_output.'/'.$subdir; - $link="document.php?modulepart=expensereport&file=".str_replace('/', '%2F', $subdir).'%2F'; + $link = "document.php?modulepart=expensereport&file=".str_replace('/', '%2F', $subdir).'%2F'; break; case "SalaryPayment": $subdir = ''; - $subdir.=($subdir ? '/' : '').dol_sanitizeFileName($objd->id); + $subdir .= ($subdir ? '/' : '').dol_sanitizeFileName($objd->id); $upload_dir = $conf->salaries->dir_output.'/'.$subdir; - $link="document.php?modulepart=salaries&file=".str_replace('/', '%2F', $subdir).'%2F'; + $link = "document.php?modulepart=salaries&file=".str_replace('/', '%2F', $subdir).'%2F'; break; case "Donation": $tmpdonation->fetch($objp->id); - $subdir=get_exdir(0, 0, 0, 0, $tmpdonation, 'donation'); - $subdir.=($subdir ? '/' : '').dol_sanitizeFileName($objd->id); - $upload_dir = $conf->don->dir_output . '/' . $subdir; - $link="document.php?modulepart=don&file=".str_replace('/', '%2F', $subdir).'%2F'; + $subdir = get_exdir(0, 0, 0, 0, $tmpdonation, 'donation'); + $subdir .= ($subdir ? '/' : '').dol_sanitizeFileName($objd->id); + $upload_dir = $conf->don->dir_output.'/'.$subdir; + $link = "document.php?modulepart=don&file=".str_replace('/', '%2F', $subdir).'%2F'; break; case "SocialContributions": $subdir = ''; - $subdir.=($subdir ? '/' : '').dol_sanitizeFileName($objd->id); - $upload_dir = $conf->tax->dir_output . '/' . $subdir; - $link="document.php?modulepart=tax&file=".str_replace('/', '%2F', $subdir).'%2F'; + $subdir .= ($subdir ? '/' : '').dol_sanitizeFileName($objd->id); + $upload_dir = $conf->tax->dir_output.'/'.$subdir; + $link = "document.php?modulepart=tax&file=".str_replace('/', '%2F', $subdir).'%2F'; break; default: - $subdir=''; - $upload_dir=''; - $link=''; + $subdir = ''; + $upload_dir = ''; + $link = ''; break; } if (!empty($upload_dir)) { - $result=true; - $files=dol_dir_list($upload_dir, "files", 0, '', '(\.meta|_preview\.png)$', '', SORT_ASC, 1); + $result = true; + $files = dol_dir_list($upload_dir, "files", 0, '', '(\.meta|_preview\.png)$', '', SORT_ASC, 1); //var_dump($upload_dir); if (count($files) < 1) { - $nofile['id']=$objd->id; - $nofile['date']=$db->idate($objd->date); - $nofile['paid']=$objd->paid; - $nofile['amount_ht']=$objd->total_ht; - $nofile['amount_ttc']=$objd->total_ttc; - $nofile['amount_vat']=$objd->total_vat; - $nofile['ref']=($objd->ref ? $objd->ref : $objd->id); - $nofile['fk']=$objd->fk_soc; - $nofile['item']=$objd->item; - $nofile['thirdparty_name']=$objd->thirdparty_name; - $nofile['thirdparty_code']=$objd->thirdparty_code; - $nofile['country_code']=$objd->country_code; - $nofile['vatnum']=$objd->vatnum; + $nofile['id'] = $objd->id; + $nofile['date'] = $db->idate($objd->date); + $nofile['paid'] = $objd->paid; + $nofile['amount_ht'] = $objd->total_ht; + $nofile['amount_ttc'] = $objd->total_ttc; + $nofile['amount_vat'] = $objd->total_vat; + $nofile['ref'] = ($objd->ref ? $objd->ref : $objd->id); + $nofile['fk'] = $objd->fk_soc; + $nofile['item'] = $objd->item; + $nofile['thirdparty_name'] = $objd->thirdparty_name; + $nofile['thirdparty_code'] = $objd->thirdparty_code; + $nofile['country_code'] = $objd->country_code; + $nofile['vatnum'] = $objd->vatnum; - $filesarray[]=$nofile; + $filesarray[] = $nofile; } else { foreach ($files as $key => $file) { - $file['id']=$objd->id; - $file['date']=$db->idate($objd->date); - $file['paid']=$objd->paid; - $file['amount_ht']=$objd->total_ht; - $file['amount_ttc']=$objd->total_ttc; - $file['amount_vat']=$objd->total_vat; - $file['ref']=($objd->ref ? $objd->ref : $objd->id); - $file['fk']=$objd->fk_soc; - $file['item']=$objd->item; + $file['id'] = $objd->id; + $file['date'] = $db->idate($objd->date); + $file['paid'] = $objd->paid; + $file['amount_ht'] = $objd->total_ht; + $file['amount_ttc'] = $objd->total_ttc; + $file['amount_vat'] = $objd->total_vat; + $file['ref'] = ($objd->ref ? $objd->ref : $objd->id); + $file['fk'] = $objd->fk_soc; + $file['item'] = $objd->item; - $file['thirdparty_name']=$objd->thirdparty_name; - $file['thirdparty_code']=$objd->thirdparty_code; - $file['country_code']=$objd->country_code; - $file['vatnum']=$objd->vatnum; + $file['thirdparty_name'] = $objd->thirdparty_name; + $file['thirdparty_code'] = $objd->thirdparty_code; + $file['country_code'] = $objd->country_code; + $file['vatnum'] = $objd->vatnum; - $file['link']=$link.$file['name']; + $file['link'] = $link.$file['name']; $file['relpathnamelang'] = $langs->trans($file['item']).'/'.$file['name']; - $filesarray[]=$file; + $filesarray[] = $file; } } } @@ -284,9 +284,9 @@ if (empty($dirfortmpfile)) } -if ($result && $action == "dl" && ! $error) +if ($result && $action == "dl" && !$error) { - if (! extension_loaded('zip')) + if (!extension_loaded('zip')) { setEventMessages('PHPZIPExtentionNotLoaded', null, 'errors'); exit; @@ -295,41 +295,41 @@ if ($result && $action == "dl" && ! $error) dol_mkdir($dirfortmpfile); $log = $langs->transnoentitiesnoconv("Type"); - $log .= ',' . $langs->transnoentitiesnoconv("Date"); - $log .= ',' . $langs->transnoentitiesnoconv("Ref"); - $log .= ',' . $langs->transnoentitiesnoconv("TotalHT"); - $log .= ',' . $langs->transnoentitiesnoconv("TotalTTC"); - $log .= ',' . $langs->transnoentitiesnoconv("TotalVAT"); - $log .= ',' . $langs->transnoentitiesnoconv("Paid"); + $log .= ','.$langs->transnoentitiesnoconv("Date"); + $log .= ','.$langs->transnoentitiesnoconv("Ref"); + $log .= ','.$langs->transnoentitiesnoconv("TotalHT"); + $log .= ','.$langs->transnoentitiesnoconv("TotalTTC"); + $log .= ','.$langs->transnoentitiesnoconv("TotalVAT"); + $log .= ','.$langs->transnoentitiesnoconv("Paid"); $log .= ',filename,item_id'; - $log .= ',' . $langs->transnoentitiesnoconv("ThirdParty"); - $log .= ',' . $langs->transnoentitiesnoconv("Code"); - $log .= ',' . $langs->transnoentitiesnoconv("Country"); - $log .= ',' . $langs->transnoentitiesnoconv("VATIntra")."\n"; + $log .= ','.$langs->transnoentitiesnoconv("ThirdParty"); + $log .= ','.$langs->transnoentitiesnoconv("Code"); + $log .= ','.$langs->transnoentitiesnoconv("Country"); + $log .= ','.$langs->transnoentitiesnoconv("VATIntra")."\n"; $zipname = $dirfortmpfile.'/'.dol_print_date($date_start, 'dayrfc')."-".dol_print_date($date_stop, 'dayrfc').'_export.zip'; dol_delete_file($zipname); $zip = new ZipArchive; - $res = $zip->open($zipname, ZipArchive::OVERWRITE|ZipArchive::CREATE); + $res = $zip->open($zipname, ZipArchive::OVERWRITE | ZipArchive::CREATE); if ($res) { foreach ($filesarray as $key => $file) { if (file_exists($file["fullname"])) $zip->addFile($file["fullname"], $file["relpathnamelang"]); $log .= $file['item']; - $log .= ',' . dol_print_date($file['date'], 'dayrfc'); - $log .= ',' . $file['ref']; - $log .= ',' . $file['amount_ht']; - $log .= ',' . $file['amount_ttc']; - $log .= ',' . $file['amount_vat']; - $log .= ',' . $file['paid']; - $log .= ',' . $file["name"]; - $log .= ',' . $file['fk']; - $log .= ',' . $file['thirdparty_name']; - $log .= ',' . $file['thirdparty_code']; - $log .= ',' . $file['country_code']; - $log .= ',"' . $file['vatnum'].'"'."\n"; + $log .= ','.dol_print_date($file['date'], 'dayrfc'); + $log .= ','.$file['ref']; + $log .= ','.$file['amount_ht']; + $log .= ','.$file['amount_ttc']; + $log .= ','.$file['amount_vat']; + $log .= ','.$file['paid']; + $log .= ','.$file["name"]; + $log .= ','.$file['fk']; + $log .= ','.$file['thirdparty_name']; + $log .= ','.$file['thirdparty_code']; + $log .= ','.$file['country_code']; + $log .= ',"'.$file['vatnum'].'"'."\n"; } $zip->addFromString('transactions.csv', $log); $zip->close(); @@ -337,7 +337,7 @@ if ($result && $action == "dl" && ! $error) ///Then download the zipped file. header('Content-Type: application/zip'); header('Content-disposition: attachment; filename='.basename($zipname)); - header('Content-Length: ' . filesize($zipname)); + header('Content-Length: '.filesize($zipname)); readfile($zipname); dol_delete_file($zipname); @@ -356,13 +356,13 @@ if ($result && $action == "dl" && ! $error) */ $form = new Form($db); -$userstatic=new User($db); +$userstatic = new User($db); -$title=$langs->trans("ComptaFiles").' - '.$langs->trans("List"); +$title = $langs->trans("ComptaFiles").' - '.$langs->trans("List"); llxHeader('', $title, $help_url); -$h=0; +$h = 0; $head[$h][0] = $_SERVER["PHP_SELF"].$varlink; $head[$h][1] = $langs->trans("AccountantFiles"); $head[$h][2] = 'AccountancyFiles'; @@ -376,7 +376,7 @@ print $langs->trans("ReportPeriod").': '.$form->selectDate($date_start, 'date_st print ' - '.$form->selectDate($date_stop, 'date_stop', 0, 0, 0, "", 1, 1, 0)."\n"; // Export is for current company only ! -if (! empty($conf->multicompany->enabled) && is_object($mc)) +if (!empty($conf->multicompany->enabled) && is_object($mc)) { print '('.$langs->trans("Entity").' : '; $mc->dao->getEntities(); @@ -393,13 +393,13 @@ dol_fiche_end(); if (!empty($date_start) && !empty($date_stop)) { - $param='action=searchfiles'; - $param.='&date_startday='.GETPOST('date_startday', 'int'); - $param.='&date_startmonth='.GETPOST('date_startmonth', 'int'); - $param.='&date_startyear='.GETPOST('date_startyear', 'int'); - $param.='&date_stopday='.GETPOST('date_stopday', 'int'); - $param.='&date_stopmonth='.GETPOST('date_stopmonth', 'int'); - $param.='&date_stopyear='.GETPOST('date_stopyear', 'int'); + $param = 'action=searchfiles'; + $param .= '&date_startday='.GETPOST('date_startday', 'int'); + $param .= '&date_startmonth='.GETPOST('date_startmonth', 'int'); + $param .= '&date_startyear='.GETPOST('date_startyear', 'int'); + $param .= '&date_stopday='.GETPOST('date_stopday', 'int'); + $param .= '&date_stopmonth='.GETPOST('date_stopmonth', 'int'); + $param .= '&date_stopyear='.GETPOST('date_stopyear', 'int'); print ''."\n"; print ''; @@ -422,8 +422,8 @@ if (!empty($date_start) && !empty($date_stop)) print '
'; - print '
'; // You can use div-table-responsive-no-min if you dont need reserved height for your table - print ''; + print '
'; // You can use div-table-responsive-no-min if you dont need reserved height for your table + print '
'; print ''; print_liste_field_titre($arrayfields['type']['label'], $_SERVER["PHP_SELF"], "type", "", $param, '', $sortfield, $sortorder, 'nowrap '); print_liste_field_titre($arrayfields['date']['label'], $_SERVER["PHP_SELF"], "date", "", $param, '', $sortfield, $sortorder, 'center nowrap '); @@ -457,7 +457,7 @@ if (!empty($date_start) && !empty($date_stop)) $totalCredit = 0; // Display array - foreach($TData as $data) + foreach ($TData as $data) { $html_class = ''; //if (!empty($data['fk_facture'])) $html_class = 'facid-'.$data['fk_facture']; diff --git a/htdocs/compta/bank/account_statement_document.php b/htdocs/compta/bank/account_statement_document.php new file mode 100644 index 00000000000..2af8ea7de22 --- /dev/null +++ b/htdocs/compta/bank/account_statement_document.php @@ -0,0 +1,156 @@ + + * Copyright (C) 2004-2008 Laurent Destailleur + * Copyright (C) 2005 Marc Barilley / Ocebo + * Copyright (C) 2005-2017 Regis Houssin + * Copyright (C) 2019 Nicolas ZABOURI + * + * This program is free software; you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation; either version 2 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + */ + +/** + * \file htdocs/compta/bank/document.php + * \ingroup banque + * \brief Page de gestion des documents attaches a un compte bancaire + */ +require '../../main.inc.php'; +require_once DOL_DOCUMENT_ROOT."/core/lib/bank.lib.php"; +require_once DOL_DOCUMENT_ROOT."/core/lib/files.lib.php"; +require_once DOL_DOCUMENT_ROOT."/core/lib/images.lib.php"; +require_once DOL_DOCUMENT_ROOT."/core/class/html.formfile.class.php"; +require_once DOL_DOCUMENT_ROOT.'/compta/bank/class/account.class.php'; + +global $conf, $db, $langs; +// Load translation files required by the page +$langs->loadLangs(array('banks', 'companies', 'other')); + +$id = (GETPOST('id', 'int') ? GETPOST('id', 'int') : GETPOST('account', 'int')); +$ref = GETPOST('ref', 'alpha'); +$action = GETPOST('action', 'alpha'); +$confirm = GETPOST('confirm', 'alpha'); +$num = (GETPOST('num', 'alpha') ? GETPOST('num', 'alpha') : GETPOST('sectionid', 'alpha')); + +$mesg = ''; +if (isset($_SESSION['DolMessage'])) { + $mesg = $_SESSION['DolMessage']; + unset($_SESSION['DolMessage']); +} + +// Security check +if ($user->socid) { + $action = ''; + $socid = $user->socid; +} +if ($user->socid) + $socid = $user->socid; + +// Get parameters +$sortfield = GETPOST("sortfield", 'alpha'); +$sortorder = GETPOST("sortorder", 'alpha'); +$page = GETPOST("page", 'int'); +if (empty($page) || $page == -1) { $page = 0; } +$offset = $conf->liste_limit * $page; +$pageprev = $page - 1; +$pagenext = $page + 1; +if (!$sortorder) + $sortorder = "ASC"; +if (!$sortfield) + $sortfield = "name"; + +$object = new Account($db); +if ($id > 0 || !empty($ref)) $object->fetch($id, $ref); + +$result = restrictedArea($user, 'banque', $object->id, 'bank_account', '', ''); + + +/* + * Actions + */ + +if (!empty($num)) +{ + $object->fetch_thirdparty(); + $upload_dir = $conf->bank->dir_output."/".$id."/statement/".dol_sanitizeFileName($num); +} +$backtopage = $_SERVER['PHP_SELF']."?account=".$id."&num=".$num; +include_once DOL_DOCUMENT_ROOT.'/core/actions_linkedfiles.inc.php'; + + +/* + * View + */ + +$title = $langs->trans("FinancialAccount").' - '.$langs->trans("Documents"); +$helpurl = ""; +llxHeader('', $title, $helpurl); + +$form = new Form($db); + +if ($id > 0 || !empty($ref)) { + if ($object->fetch($id, $ref)) { + $upload_dir = $conf->bank->dir_output."/".$id."/statement/".dol_sanitizeFileName($num); + + // Onglets + $head = account_statement_prepare_head($object, $num); + dol_fiche_head($head, 'document', $langs->trans("FinancialAccount"), -1, 'account'); + + + // Build file list + $filearray = dol_dir_list($upload_dir, "files", 0, '', '\.meta$', $sortfield, (strtolower($sortorder) == 'desc' ? SORT_DESC : SORT_ASC), 1); + $totalsize = 0; + foreach ($filearray as $key => $file) { + $totalsize += $file['size']; + } + + $morehtmlref = ''; + + + $title = $langs->trans("AccountStatement").' '.$num.' - '.$langs->trans("BankAccount").' '.$object->getNomUrl(1, 'receipts'); + print load_fiche_titre($title, '', 'title_bank.png'); + + + print '
'; + print '
'; + + print '
'; + print ''; + print ''; + print "
'.$langs->trans("NbOfAttachedFiles").''.count($filearray).'
'.$langs->trans("TotalSizeOfAttachedFiles").''.dol_print_size($totalsize, 1, 1).'
\n"; + + print '
'; + + dol_fiche_end(); + + + $modulepart = 'bank'; + $permission = $user->rights->banque->modifier; + $permtoedit = $user->rights->banque->modifier; + $param = '&id='.$object->id.'&num='.$num; + $uri = '&num='.$num; + $relativepathwithnofile = $id."/statement/".$num."/"; + include_once DOL_DOCUMENT_ROOT.'/core/tpl/document_actions_post_headers.tpl.php'; + } + else { + dol_print_error($db); + } +} +else { + Header('Location: index.php'); + exit; +} + +// End of page +llxFooter(); +$db->close(); diff --git a/htdocs/compta/bank/annuel.php b/htdocs/compta/bank/annuel.php index b5839db2200..1f6e5e6620c 100644 --- a/htdocs/compta/bank/annuel.php +++ b/htdocs/compta/bank/annuel.php @@ -32,28 +32,28 @@ require_once DOL_DOCUMENT_ROOT.'/core/class/dolgraph.class.php'; // Load translation files required by the page $langs->loadLangs(array('banks', 'categories')); -$WIDTH=DolGraph::getDefaultGraphSizeForStats('width', 380); // Large for one graph in a smarpthone. -$HEIGHT=DolGraph::getDefaultGraphSizeForStats('height', 160); +$WIDTH = DolGraph::getDefaultGraphSizeForStats('width', 380); // Large for one graph in a smarpthone. +$HEIGHT = DolGraph::getDefaultGraphSizeForStats('height', 160); -$id=GETPOST('account')?GETPOST('account', 'alpha'):GETPOST('id'); -$ref=GETPOST('ref'); +$id = GETPOST('account') ?GETPOST('account', 'alpha') : GETPOST('id'); +$ref = GETPOST('ref'); // Security check -$fieldvalue = (! empty($id) ? $id : (! empty($ref) ? $ref :'')); -$fieldtype = (! empty($ref) ? 'ref' :'rowid'); -if ($user->socid) $socid=$user->socid; -$result=restrictedArea($user, 'banque', $fieldvalue, 'bank_account&bank_account', '', '', $fieldtype); +$fieldvalue = (!empty($id) ? $id : (!empty($ref) ? $ref : '')); +$fieldtype = (!empty($ref) ? 'ref' : 'rowid'); +if ($user->socid) $socid = $user->socid; +$result = restrictedArea($user, 'banque', $fieldvalue, 'bank_account&bank_account', '', '', $fieldtype); -$year_start=GETPOST('year_start'); +$year_start = GETPOST('year_start'); $year_current = strftime("%Y", time()); -if (! $year_start) +if (!$year_start) { $year_start = $year_current - 2; $year_end = $year_current; } else { - $year_end=$year_start+2; + $year_end = $year_start + 2; } @@ -70,15 +70,15 @@ $form = new Form($db); // Get account informations $object = new Account($db); -if ($id > 0 && ! preg_match('/,/', $id)) // if for a particular account and not a list +if ($id > 0 && !preg_match('/,/', $id)) // if for a particular account and not a list { - $result=$object->fetch($id); - $id=$object->id; + $result = $object->fetch($id); + $id = $object->id; } -if (! empty($ref)) +if (!empty($ref)) { - $result=$object->fetch(0, $ref); - $id=$object->id; + $result = $object->fetch(0, $ref); + $id = $object->id; } @@ -86,17 +86,17 @@ if (! empty($ref)) // plutot que sur llx_paiement + llx_paiementfourn $sql = "SELECT SUM(b.amount)"; -$sql.= ", date_format(b.dateo,'%Y-%m') as dm"; -$sql.= " FROM ".MAIN_DB_PREFIX."bank as b"; -$sql.= ", ".MAIN_DB_PREFIX."bank_account as ba"; -$sql.= " WHERE b.fk_account = ba.rowid"; -$sql.= " AND ba.entity IN (".getEntity('bank_account').")"; -$sql.= " AND b.amount >= 0"; -if (! empty($id)) +$sql .= ", date_format(b.dateo,'%Y-%m') as dm"; +$sql .= " FROM ".MAIN_DB_PREFIX."bank as b"; +$sql .= ", ".MAIN_DB_PREFIX."bank_account as ba"; +$sql .= " WHERE b.fk_account = ba.rowid"; +$sql .= " AND ba.entity IN (".getEntity('bank_account').")"; +$sql .= " AND b.amount >= 0"; +if (!empty($id)) $sql .= " AND b.fk_account IN (".$db->escape($id).")"; -$sql.= " GROUP BY dm"; +$sql .= " GROUP BY dm"; -$resql=$db->query($sql); +$resql = $db->query($sql); if ($resql) { $num = $db->num_rows($resql); @@ -114,17 +114,17 @@ else } $sql = "SELECT SUM(b.amount)"; -$sql.= ", date_format(b.dateo,'%Y-%m') as dm"; -$sql.= " FROM ".MAIN_DB_PREFIX."bank as b"; -$sql.= ", ".MAIN_DB_PREFIX."bank_account as ba"; -$sql.= " WHERE b.fk_account = ba.rowid"; -$sql.= " AND ba.entity IN (".getEntity('bank_account').")"; -$sql.= " AND b.amount <= 0"; -if (! empty($id)) +$sql .= ", date_format(b.dateo,'%Y-%m') as dm"; +$sql .= " FROM ".MAIN_DB_PREFIX."bank as b"; +$sql .= ", ".MAIN_DB_PREFIX."bank_account as ba"; +$sql .= " WHERE b.fk_account = ba.rowid"; +$sql .= " AND ba.entity IN (".getEntity('bank_account').")"; +$sql .= " AND b.amount <= 0"; +if (!empty($id)) $sql .= " AND b.fk_account IN (".$db->escape($id).")"; -$sql.= " GROUP BY dm"; +$sql .= " GROUP BY dm"; -$resql=$db->query($sql); +$resql = $db->query($sql); if ($resql) { $num = $db->num_rows($resql); @@ -143,31 +143,31 @@ else // Onglets -$head=bank_prepare_head($object); +$head = bank_prepare_head($object); dol_fiche_head($head, 'annual', $langs->trans("FinancialAccount"), 0, 'account'); -$title=$langs->trans("FinancialAccount")." : ".$object->label; -$link=($year_start?"".img_previous('', 'class="valignbottom"')." ".$langs->trans("Year")." ".img_next('', 'class="valignbottom"')."":""); +$title = $langs->trans("FinancialAccount")." : ".$object->label; +$link = ($year_start ? "".img_previous('', 'class="valignbottom"')." ".$langs->trans("Year")." ".img_next('', 'class="valignbottom"')."" : ""); $linkback = ''.$langs->trans("BackToList").''; if (!empty($id)) { - if (! preg_match('/,/', $id)) + if (!preg_match('/,/', $id)) { dol_banner_tab($object, 'ref', $linkback, 1, 'ref', 'ref', $morehtmlref, '', 0, '', '', 1); } else { - $bankaccount=new Account($db); - $listid=explode(',', $id); - foreach($listid as $key => $aId) + $bankaccount = new Account($db); + $listid = explode(',', $id); + foreach ($listid as $key => $aId) { $bankaccount->fetch($aId); - $bankaccount->label=$bankaccount->ref; + $bankaccount->label = $bankaccount->ref; print $bankaccount->getNomUrl(1); - if ($key < (count($listid)-1)) print ', '; + if ($key < (count($listid) - 1)) print ', '; } } } @@ -182,11 +182,11 @@ dol_fiche_end(); // Affiche tableau print load_fiche_titre('', $link, ''); -print '
'; // You can use div-table-responsive-no-min if you dont need reserved height for your table -print ''; +print '
'; // You can use div-table-responsive-no-min if you dont need reserved height for your table +print '
'; print ''; -for ($annee = $year_start ; $annee <= $year_end ; $annee++) +for ($annee = $year_start; $annee <= $year_end; $annee++) { print ''; } @@ -194,33 +194,33 @@ print ''; print ''; print ''; -for ($annee = $year_start ; $annee <= $year_end ; $annee++) +for ($annee = $year_start; $annee <= $year_end; $annee++) { print ''; } print ''; -for ($mois = 1 ; $mois < 13 ; $mois++) +for ($mois = 1; $mois < 13; $mois++) { print ''; print ""; - for ($annee = $year_start ; $annee <= $year_end ; $annee++) + for ($annee = $year_start; $annee <= $year_end; $annee++) { $case = sprintf("%04s-%02s", $annee, $mois); print '"; print '"; } @@ -229,7 +229,7 @@ for ($mois = 1 ; $mois < 13 ; $mois++) // Total debit-credit print '"; -for ($annee = $year_start ; $annee <= $year_end ; $annee++) +for ($annee = $year_start; $annee <= $year_end; $annee++) { print ''; } @@ -242,27 +242,27 @@ print '
'; // Current balance -$balance=0; +$balance = 0; $sql = "SELECT SUM(b.amount) as total"; -$sql.= " FROM ".MAIN_DB_PREFIX."bank as b"; -$sql.= ", ".MAIN_DB_PREFIX."bank_account as ba"; -$sql.= " WHERE b.fk_account = ba.rowid"; -$sql.= " AND ba.entity IN (".getEntity('bank_account').")"; -if (! empty($id)) - $sql.= " AND b.fk_account IN (".$db->escape($id).")"; +$sql .= " FROM ".MAIN_DB_PREFIX."bank as b"; +$sql .= ", ".MAIN_DB_PREFIX."bank_account as ba"; +$sql .= " WHERE b.fk_account = ba.rowid"; +$sql .= " AND ba.entity IN (".getEntity('bank_account').")"; +if (!empty($id)) + $sql .= " AND b.fk_account IN (".$db->escape($id).")"; -$resql=$db->query($sql); +$resql = $db->query($sql); if ($resql) { $obj = $db->fetch_object($resql); - if ($obj) $balance=$obj->total; + if ($obj) $balance = $obj->total; } else { dol_print_error($db); } -print '
'.$langs->trans("Month").''.$annee.'
 '.$langs->trans("Debit").''.$langs->trans("Credit").'
".dol_print_date(dol_mktime(1, 1, 1, $mois, 1, 2000), "%B")." '; - if ($decaiss[$case]>0) + if ($decaiss[$case] > 0) { print price($decaiss[$case]); - $totsorties[$annee]+=$decaiss[$case]; + $totsorties[$annee] += $decaiss[$case]; } print " '; - if ($encaiss[$case]>0) + if ($encaiss[$case] > 0) { print price($encaiss[$case]); - $totentrees[$annee]+=$encaiss[$case]; + $totentrees[$annee] += $encaiss[$case]; } print "
'.$langs->trans("Total")."'.price($totsorties[$annee]).''.price($totentrees[$annee]).'
'; +print '
'; print '"; print ''; @@ -274,7 +274,7 @@ print "
'.$langs->trans("CurrentBalance")."'.price($balance).'
"; $year = $year_end; -$result=dol_mkdir($conf->bank->dir_temp); +$result = dol_mkdir($conf->bank->dir_temp); if ($result < 0) { $langs->load("errors"); @@ -285,11 +285,11 @@ else { // Calcul de $min et $max $sql = "SELECT MIN(b.datev) as min, MAX(b.datev) as max"; - $sql.= " FROM ".MAIN_DB_PREFIX."bank as b"; - $sql.= ", ".MAIN_DB_PREFIX."bank_account as ba"; - $sql.= " WHERE b.fk_account = ba.rowid"; - $sql.= " AND ba.entity IN (".getEntity('bank_account').")"; - if ($id && $_GET["option"]!='all') $sql.= " AND b.fk_account IN (".$id.")"; + $sql .= " FROM ".MAIN_DB_PREFIX."bank as b"; + $sql .= ", ".MAIN_DB_PREFIX."bank_account as ba"; + $sql .= " WHERE b.fk_account = ba.rowid"; + $sql .= " AND ba.entity IN (".getEntity('bank_account').")"; + if ($id && $_GET["option"] != 'all') $sql .= " AND b.fk_account IN (".$id.")"; $resql = $db->query($sql); if ($resql) @@ -303,7 +303,7 @@ else { dol_print_error($db); } - $log="graph.php: min=".$min." max=".$max; + $log = "graph.php: min=".$min." max=".$max; dol_syslog($log); // CRED PART @@ -312,18 +312,18 @@ else $tblyear[1] = array(); $tblyear[2] = array(); - for ($annee=0;$annee<3;$annee++) + for ($annee = 0; $annee < 3; $annee++) { $sql = "SELECT date_format(b.datev,'%m')"; - $sql.= ", SUM(b.amount)"; - $sql.= " FROM ".MAIN_DB_PREFIX."bank as b"; - $sql.= ", ".MAIN_DB_PREFIX."bank_account as ba"; - $sql.= " WHERE b.fk_account = ba.rowid"; - $sql.= " AND ba.entity IN (".getEntity('bank_account').")"; - $sql.= " AND b.datev >= '".($year-$annee)."-01-01 00:00:00'"; - $sql.= " AND b.datev <= '".($year-$annee)."-12-31 23:59:59'"; - $sql.= " AND b.amount > 0"; - if ($id && $_GET["option"]!='all') $sql.= " AND b.fk_account IN (".$id.")"; + $sql .= ", SUM(b.amount)"; + $sql .= " FROM ".MAIN_DB_PREFIX."bank as b"; + $sql .= ", ".MAIN_DB_PREFIX."bank_account as ba"; + $sql .= " WHERE b.fk_account = ba.rowid"; + $sql .= " AND ba.entity IN (".getEntity('bank_account').")"; + $sql .= " AND b.datev >= '".($year - $annee)."-01-01 00:00:00'"; + $sql .= " AND b.datev <= '".($year - $annee)."-12-31 23:59:59'"; + $sql .= " AND b.amount > 0"; + if ($id && $_GET["option"] != 'all') $sql .= " AND b.fk_account IN (".$id.")"; $sql .= " GROUP BY date_format(b.datev,'%m');"; $resql = $db->query($sql); @@ -350,38 +350,38 @@ else $data_year_1 = array(); $data_year_2 = array(); - for ($i = 0 ; $i < 12 ; $i++) + for ($i = 0; $i < 12; $i++) { - $data_year_0[$i] = isset($tblyear[0][substr("0".($i+1), -2)]) ? $tblyear[0][substr("0".($i+1), -2)] : 0; - $data_year_1[$i] = isset($tblyear[1][substr("0".($i+1), -2)]) ? $tblyear[1][substr("0".($i+1), -2)] : 0; - $data_year_2[$i] = isset($tblyear[2][substr("0".($i+1), -2)]) ? $tblyear[2][substr("0".($i+1), -2)] : 0; - $labels[$i] = $langs->transnoentitiesnoconv("MonthVeryShort".sprintf("%02d", $i+1)); + $data_year_0[$i] = isset($tblyear[0][substr("0".($i + 1), -2)]) ? $tblyear[0][substr("0".($i + 1), -2)] : 0; + $data_year_1[$i] = isset($tblyear[1][substr("0".($i + 1), -2)]) ? $tblyear[1][substr("0".($i + 1), -2)] : 0; + $data_year_2[$i] = isset($tblyear[2][substr("0".($i + 1), -2)]) ? $tblyear[2][substr("0".($i + 1), -2)] : 0; + $labels[$i] = $langs->transnoentitiesnoconv("MonthVeryShort".sprintf("%02d", $i + 1)); $datamin[$i] = 0; } // Fabrication tableau 4b - $file= $conf->bank->dir_temp."/credmovement".$id."-".$year.".png"; - $fileurl=DOL_URL_ROOT.'/viewimage.php?modulepart=banque_temp&file='."/credmovement".$id."-".$year.".png"; - $title=$langs->transnoentities("Credit").' - '.$langs->transnoentities("Year").': '.($year-2).' - '.($year-1)." - ".$year; - $graph_datas=array(); - for($i=0;$i<12;$i++) + $file = $conf->bank->dir_temp."/credmovement".$id."-".$year.".png"; + $fileurl = DOL_URL_ROOT.'/viewimage.php?modulepart=banque_temp&file='."/credmovement".$id."-".$year.".png"; + $title = $langs->transnoentities("Credit").' - '.$langs->transnoentities("Year").': '.($year - 2).' - '.($year - 1)." - ".$year; + $graph_datas = array(); + for ($i = 0; $i < 12; $i++) { - $graph_datas[$i]=array($labels[$i], $data_year_0[$i], $data_year_1[$i], $data_year_2[$i]); + $graph_datas[$i] = array($labels[$i], $data_year_0[$i], $data_year_1[$i], $data_year_2[$i]); } $px1 = new DolGraph(); $px1->SetData($graph_datas); - $px1->SetLegend(array(($year),($year-1),($year-2))); + $px1->SetLegend(array(($year), ($year - 1), ($year - 2))); $px1->SetLegendWidthMin(180); - $px1->SetMaxValue($px1->GetCeilMaxValue()<0?0:$px1->GetCeilMaxValue()); - $px1->SetMinValue($px1->GetFloorMinValue()>0?0:$px1->GetFloorMinValue()); + $px1->SetMaxValue($px1->GetCeilMaxValue() < 0 ? 0 : $px1->GetCeilMaxValue()); + $px1->SetMinValue($px1->GetFloorMinValue() > 0 ? 0 : $px1->GetFloorMinValue()); $px1->SetTitle($title); $px1->SetWidth($WIDTH); $px1->SetHeight($HEIGHT); - $px1->SetType(array('line','line','line')); + $px1->SetType(array('line', 'line', 'line')); $px1->SetShading(3); $px1->setBgColor('onglet'); - $px1->setBgColorGrid(array(255,255,255)); + $px1->setBgColorGrid(array(255, 255, 255)); $px1->SetHorizTickIncrement(1); $px1->draw($file, $fileurl); @@ -399,18 +399,18 @@ else $tblyear[1] = array(); $tblyear[2] = array(); - for ($annee=0;$annee<3;$annee++) + for ($annee = 0; $annee < 3; $annee++) { $sql = "SELECT date_format(b.datev,'%m')"; - $sql.= ", SUM(b.amount)"; - $sql.= " FROM ".MAIN_DB_PREFIX."bank as b"; - $sql.= ", ".MAIN_DB_PREFIX."bank_account as ba"; - $sql.= " WHERE b.fk_account = ba.rowid"; - $sql.= " AND ba.entity IN (".getEntity('bank_account').")"; - $sql.= " AND b.datev >= '".($year-$annee)."-01-01 00:00:00'"; - $sql.= " AND b.datev <= '".($year-$annee)."-12-31 23:59:59'"; - $sql.= " AND b.amount < 0"; - if ($id && $_GET["option"]!='all') $sql.= " AND b.fk_account IN (".$id.")"; + $sql .= ", SUM(b.amount)"; + $sql .= " FROM ".MAIN_DB_PREFIX."bank as b"; + $sql .= ", ".MAIN_DB_PREFIX."bank_account as ba"; + $sql .= " WHERE b.fk_account = ba.rowid"; + $sql .= " AND ba.entity IN (".getEntity('bank_account').")"; + $sql .= " AND b.datev >= '".($year - $annee)."-01-01 00:00:00'"; + $sql .= " AND b.datev <= '".($year - $annee)."-12-31 23:59:59'"; + $sql .= " AND b.amount < 0"; + if ($id && $_GET["option"] != 'all') $sql .= " AND b.fk_account IN (".$id.")"; $sql .= " GROUP BY date_format(b.datev,'%m');"; $resql = $db->query($sql); @@ -437,37 +437,37 @@ else $data_year_1 = array(); $data_year_2 = array(); - for ($i = 0 ; $i < 12 ; $i++) + for ($i = 0; $i < 12; $i++) { - $data_year_0[$i] = isset($tblyear[0][substr("0".($i+1), -2)]) ? $tblyear[0][substr("0".($i+1), -2)] : 0; - $data_year_1[$i] = isset($tblyear[1][substr("0".($i+1), -2)]) ? $tblyear[1][substr("0".($i+1), -2)] : 0; - $data_year_2[$i] = isset($tblyear[2][substr("0".($i+1), -2)]) ? $tblyear[2][substr("0".($i+1), -2)] : 0; - $labels[$i] = $langs->transnoentitiesnoconv("MonthVeryShort".sprintf("%02d", $i+1)); + $data_year_0[$i] = isset($tblyear[0][substr("0".($i + 1), -2)]) ? $tblyear[0][substr("0".($i + 1), -2)] : 0; + $data_year_1[$i] = isset($tblyear[1][substr("0".($i + 1), -2)]) ? $tblyear[1][substr("0".($i + 1), -2)] : 0; + $data_year_2[$i] = isset($tblyear[2][substr("0".($i + 1), -2)]) ? $tblyear[2][substr("0".($i + 1), -2)] : 0; + $labels[$i] = $langs->transnoentitiesnoconv("MonthVeryShort".sprintf("%02d", $i + 1)); $datamin[$i] = 0; } - $file= $conf->bank->dir_temp."/debmovement".$id."-".$year.".png"; - $fileurl= DOL_URL_ROOT.'/viewimage.php?modulepart=banque_temp&file='."/debmovement".$id."-".$year.".png"; - $title=$langs->transnoentities("Debit").' - '.$langs->transnoentities("Year").': '.($year-2).' - '.($year-1)." - ".$year; - $graph_datas=array(); - for($i=0;$i<12;$i++) + $file = $conf->bank->dir_temp."/debmovement".$id."-".$year.".png"; + $fileurl = DOL_URL_ROOT.'/viewimage.php?modulepart=banque_temp&file='."/debmovement".$id."-".$year.".png"; + $title = $langs->transnoentities("Debit").' - '.$langs->transnoentities("Year").': '.($year - 2).' - '.($year - 1)." - ".$year; + $graph_datas = array(); + for ($i = 0; $i < 12; $i++) { - $graph_datas[$i]=array($labels[$i], $data_year_0[$i], $data_year_1[$i], $data_year_2[$i]); + $graph_datas[$i] = array($labels[$i], $data_year_0[$i], $data_year_1[$i], $data_year_2[$i]); } $px2 = new DolGraph(); $px2->SetData($graph_datas); - $px2->SetLegend(array(($year),($year-1),($year-2))); + $px2->SetLegend(array(($year), ($year - 1), ($year - 2))); $px2->SetLegendWidthMin(180); - $px2->SetMaxValue($px2->GetCeilMaxValue()<0?0:$px2->GetCeilMaxValue()); - $px2->SetMinValue($px2->GetFloorMinValue()>0?0:$px2->GetFloorMinValue()); + $px2->SetMaxValue($px2->GetCeilMaxValue() < 0 ? 0 : $px2->GetCeilMaxValue()); + $px2->SetMinValue($px2->GetFloorMinValue() > 0 ? 0 : $px2->GetFloorMinValue()); $px2->SetTitle($title); $px2->SetWidth($WIDTH); $px2->SetHeight($HEIGHT); - $px2->SetType(array('line','line','line')); + $px2->SetType(array('line', 'line', 'line')); $px2->SetShading(3); $px2->setBgColor('onglet'); - $px2->setBgColorGrid(array(255,255,255)); + $px2->setBgColorGrid(array(255, 255, 255)); $px2->SetHorizTickIncrement(1); $px2->draw($file, $fileurl); @@ -479,9 +479,9 @@ else unset($tblyear[1]); unset($tblyear[2]); - print '
'; // do not use class="center" here, it will have no effect for the js graph inside. + print '
'; // do not use class="center" here, it will have no effect for the js graph inside. print $show1; - print '
'; // do not use class="center" here, it will have no effect for the js graph inside. + print '
'; // do not use class="center" here, it will have no effect for the js graph inside. print $show2; print '
'; print '
'; diff --git a/htdocs/compta/bank/bankentries_list.php b/htdocs/compta/bank/bankentries_list.php index d23f5126375..bfbafc93bd5 100644 --- a/htdocs/compta/bank/bankentries_list.php +++ b/htdocs/compta/bank/bankentries_list.php @@ -52,51 +52,51 @@ require_once DOL_DOCUMENT_ROOT.'/loan/class/loan.class.php'; require_once DOL_DOCUMENT_ROOT.'/fourn/class/paiementfourn.class.php'; // Load translation files required by the page -$langs->loadLangs(array("banks","bills","categories","companies","margins","salaries","loan","donations","trips","members","compta","accountancy")); +$langs->loadLangs(array("banks", "bills", "categories", "companies", "margins", "salaries", "loan", "donations", "trips", "members", "compta", "accountancy")); $id = GETPOST('id', 'int'); $ref = GETPOST('ref', 'alpha'); -$action=GETPOST('action', 'alpha'); -$cancel=GETPOST('cancel', 'alpha'); -$confirm=GETPOST('confirm', 'alpha'); -$contextpage='banktransactionlist'.(empty($object->ref)?'':'-'.$object->id); +$action = GETPOST('action', 'alpha'); +$cancel = GETPOST('cancel', 'alpha'); +$confirm = GETPOST('confirm', 'alpha'); +$contextpage = 'banktransactionlist'.(empty($object->ref) ? '' : '-'.$object->id); // Security check -$fieldvalue = (! empty($id) ? $id : (! empty($ref) ? $ref :'')); -$fieldtype = (! empty($ref) ? 'ref' :'rowid'); +$fieldvalue = (!empty($id) ? $id : (!empty($ref) ? $ref : '')); +$fieldtype = (!empty($ref) ? 'ref' : 'rowid'); if ($fielvalue) { - if ($user->socid) $socid=$user->socid; - $result=restrictedArea($user, 'banque', $fieldvalue, 'bank_account&bank_account', '', '', $fieldtype); + if ($user->socid) $socid = $user->socid; + $result = restrictedArea($user, 'banque', $fieldvalue, 'bank_account&bank_account', '', '', $fieldtype); } else { - if ($user->socid) $socid=$user->socid; - $result=restrictedArea($user, 'banque'); + if ($user->socid) $socid = $user->socid; + $result = restrictedArea($user, 'banque'); } $dateop = dol_mktime(12, 0, 0, GETPOST("opmonth", 'int'), GETPOST("opday", 'int'), GETPOST("opyear", 'int')); -$search_debit=GETPOST("search_debit", 'alpha'); -$search_credit=GETPOST("search_credit", 'alpha'); -$search_type=GETPOST("search_type", 'alpha'); -$search_account=GETPOST("search_account", 'int')?GETPOST("search_account", 'int'):GETPOST("account", 'int'); -$search_accountancy_code=GETPOST('search_accountancy_code', 'alpha')?GETPOST('search_accountancy_code', 'alpha'):GETPOST('accountancy_code', 'alpha'); -$search_bid=GETPOST("search_bid", "int")?GETPOST("search_bid", "int"):GETPOST("bid", "int"); -$search_ref=GETPOST('search_ref', 'alpha'); -$search_description=GETPOST("search_description", 'alpha'); +$search_debit = GETPOST("search_debit", 'alpha'); +$search_credit = GETPOST("search_credit", 'alpha'); +$search_type = GETPOST("search_type", 'alpha'); +$search_account = GETPOST("search_account", 'int') ?GETPOST("search_account", 'int') : GETPOST("account", 'int'); +$search_accountancy_code = GETPOST('search_accountancy_code', 'alpha') ?GETPOST('search_accountancy_code', 'alpha') : GETPOST('accountancy_code', 'alpha'); +$search_bid = GETPOST("search_bid", "int") ?GETPOST("search_bid", "int") : GETPOST("bid", "int"); +$search_ref = GETPOST('search_ref', 'alpha'); +$search_description = GETPOST("search_description", 'alpha'); $search_dt_start = dol_mktime(0, 0, 0, GETPOST('search_start_dtmonth', 'int'), GETPOST('search_start_dtday', 'int'), GETPOST('search_start_dtyear', 'int')); $search_dt_end = dol_mktime(0, 0, 0, GETPOST('search_end_dtmonth', 'int'), GETPOST('search_end_dtday', 'int'), GETPOST('search_end_dtyear', 'int')); $search_dv_start = dol_mktime(0, 0, 0, GETPOST('search_start_dvmonth', 'int'), GETPOST('search_start_dvday', 'int'), GETPOST('search_start_dvyear', 'int')); $search_dv_end = dol_mktime(0, 0, 0, GETPOST('search_end_dvmonth', 'int'), GETPOST('search_end_dvday', 'int'), GETPOST('search_end_dvyear', 'int')); -$search_thirdparty=GETPOST("search_thirdparty", 'alpha')?GETPOST("search_thirdparty", 'alpha'):GETPOST("thirdparty", 'alpha'); -$search_req_nb=GETPOST("req_nb", 'alpha'); -$search_num_releve=GETPOST("search_num_releve", 'alpha'); -$search_conciliated=GETPOST("search_conciliated", 'int'); -$num_releve=GETPOST("num_releve", "alpha"); -$cat=GETPOST("cat"); -if (empty($dateop)) $dateop=-1; +$search_thirdparty = GETPOST("search_thirdparty", 'alpha') ?GETPOST("search_thirdparty", 'alpha') : GETPOST("thirdparty", 'alpha'); +$search_req_nb = GETPOST("req_nb", 'alpha'); +$search_num_releve = GETPOST("search_num_releve", 'alpha'); +$search_conciliated = GETPOST("search_conciliated", 'int'); +$num_releve = GETPOST("num_releve", "alpha"); +$cat = GETPOST("cat"); +if (empty($dateop)) $dateop = -1; -$limit = GETPOST('limit', 'int')?GETPOST('limit', 'int'):$conf->liste_limit; +$limit = GETPOST('limit', 'int') ?GETPOST('limit', 'int') : $conf->liste_limit; $sortfield = GETPOST("sortfield", 'alpha'); $sortorder = GETPOST("sortorder", 'alpha'); $page = GETPOST("page", 'int'); @@ -106,24 +106,24 @@ if (empty($page) || $page == -1) { $page = 0; } // If $page is not defined, $offset = $limit * $page; $pageprev = $page - 1; $pagenext = $page + 1; -if (! $sortorder) $sortorder='desc,desc,desc'; -if (! $sortfield) $sortfield='b.datev,b.dateo,b.rowid'; +if (!$sortorder) $sortorder = 'desc,desc,desc'; +if (!$sortfield) $sortfield = 'b.datev,b.dateo,b.rowid'; -$mode_balance_ok=false; +$mode_balance_ok = false; //if (($sortfield == 'b.datev' || $sortfield == 'b.datev,b.dateo,b.rowid')) // TODO Manage balance when account not selected if (($sortfield == 'b.datev' || $sortfield == 'b.datev,b.dateo,b.rowid')) { $sortfield = 'b.datev,b.dateo,b.rowid'; - if ($id > 0 || ! empty($ref) || $search_account > 0) $mode_balance_ok = true; + if ($id > 0 || !empty($ref) || $search_account > 0) $mode_balance_ok = true; } $object = new Account($db); -if ($id > 0 || ! empty($ref)) +if ($id > 0 || !empty($ref)) { - $result=$object->fetch($id, $ref); - $search_account = $object->id; // Force the search field on id of account + $result = $object->fetch($id, $ref); + $search_account = $object->id; // Force the search field on id of account - if (! ($object->id > 0) ) + if (!($object->id > 0)) { $langs->load("errors"); print($langs->trans('ErrorRecordNotFound')); @@ -138,9 +138,9 @@ $extrafields = new ExtraFields($db); // fetch optionals attributes and labels $extrafields->fetch_name_optionals_label('banktransaction'); -$search_array_options=$extrafields->getOptionalsFromPost('banktransaction', '', 'search_'); +$search_array_options = $extrafields->getOptionalsFromPost('banktransaction', '', 'search_'); -$arrayfields=array( +$arrayfields = array( 'b.rowid'=>array('label'=>$langs->trans("Ref"), 'checked'=>1), 'b.label'=>array('label'=>$langs->trans("Description"), 'checked'=>1), 'b.dateo'=>array('label'=>$langs->trans("DateOperationShort"), 'checked'=>1), @@ -148,21 +148,21 @@ $arrayfields=array( 'type'=>array('label'=>$langs->trans("Type"), 'checked'=>1), 'b.num_chq'=>array('label'=>$langs->trans("Numero"), 'checked'=>1), 'bu.label'=>array('label'=>$langs->trans("ThirdParty"), 'checked'=>1, 'position'=>500), - 'ba.ref'=>array('label'=>$langs->trans("BankAccount"), 'checked'=>(($id > 0 || ! empty($ref))?0:1), 'position'=>1000), + 'ba.ref'=>array('label'=>$langs->trans("BankAccount"), 'checked'=>(($id > 0 || !empty($ref)) ? 0 : 1), 'position'=>1000), 'b.debit'=>array('label'=>$langs->trans("Debit"), 'checked'=>1, 'position'=>600), 'b.credit'=>array('label'=>$langs->trans("Credit"), 'checked'=>1, 'position'=>605), 'balancebefore'=>array('label'=>$langs->trans("BalanceBefore"), 'checked'=>0, 'position'=>1000), 'balance'=>array('label'=>$langs->trans("Balance"), 'checked'=>1, 'position'=>1001), 'b.num_releve'=>array('label'=>$langs->trans("AccountStatement"), 'checked'=>1, 'position'=>1010), - 'b.conciliated'=>array('label'=>$langs->trans("Conciliated"), 'enabled'=> $object->rappro, 'checked'=>($action == 'reconcile'?1:0), 'position'=>1020), + 'b.conciliated'=>array('label'=>$langs->trans("Conciliated"), 'enabled'=> $object->rappro, 'checked'=>($action == 'reconcile' ? 1 : 0), 'position'=>1020), ); // Extra fields if (is_array($extrafields->attributes[$object->table_element]['label']) && count($extrafields->attributes[$object->table_element]['label']) > 0) { - foreach($extrafields->attributes[$object->table_element]['label'] as $key => $val) + foreach ($extrafields->attributes[$object->table_element]['label'] as $key => $val) { - if (! empty($extrafields->attributes[$object->table_element]['list'][$key])) - $arrayfields["ef.".$key]=array('label'=>$extrafields->attributes[$object->table_element]['label'][$key], 'checked'=>(($extrafields->attributes[$object->table_element]['list'][$key]<0)?0:1), 'position'=>$extrafields->attributes[$object->table_element]['pos'][$key], 'enabled'=>(abs($extrafields->attributes[$object->table_element]['list'][$key])!=3 && $extrafields->attributes[$object->table_element]['perms'][$key])); + if (!empty($extrafields->attributes[$object->table_element]['list'][$key])) + $arrayfields["ef.".$key] = array('label'=>$extrafields->attributes[$object->table_element]['label'][$key], 'checked'=>(($extrafields->attributes[$object->table_element]['list'][$key] < 0) ? 0 : 1), 'position'=>$extrafields->attributes[$object->table_element]['pos'][$key], 'enabled'=>(abs($extrafields->attributes[$object->table_element]['list'][$key]) != 3 && $extrafields->attributes[$object->table_element]['perms'][$key])); } } $object->fields = dol_sort_array($object->fields, 'position'); @@ -174,41 +174,41 @@ $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(); -$reshook=$hookmanager->executeHooks('doActions', $parameters, $object, $action); // Note that $action and $object may have been modified by some hooks +$parameters = array(); +$reshook = $hookmanager->executeHooks('doActions', $parameters, $object, $action); // Note that $action and $object may have been modified by some hooks if ($reshook < 0) setEventMessages($hookmanager->error, $hookmanager->errors, 'errors'); include DOL_DOCUMENT_ROOT.'/core/actions_changeselectedfields.inc.php'; if (GETPOST('button_removefilter_x', 'alpha') || GETPOST('button_removefilter.x', 'alpha') || GETPOST('button_removefilter', 'alpha')) // All tests are required to be compatible with all browsers { - $search_dt_start=''; - $search_dt_end=''; - $search_dv_start=''; - $search_dv_end=''; - $search_type=""; - $search_debit=""; - $search_credit=""; - $search_bid=""; - $search_ref=""; - $search_req_nb=''; - $search_description=''; - $search_thirdparty=''; - $search_num_releve=''; - $search_conciliated=''; - $thirdparty=''; + $search_dt_start = ''; + $search_dt_end = ''; + $search_dv_start = ''; + $search_dv_end = ''; + $search_type = ""; + $search_debit = ""; + $search_credit = ""; + $search_bid = ""; + $search_ref = ""; + $search_req_nb = ''; + $search_description = ''; + $search_thirdparty = ''; + $search_num_releve = ''; + $search_conciliated = ''; + $thirdparty = ''; - $search_account=""; - if ($id > 0 || ! empty($ref)) $search_account=$object->id; + $search_account = ""; + if ($id > 0 || !empty($ref)) $search_account = $object->id; } if (empty($reshook)) { - $objectclass='Account'; - $objectlabel='BankTransaction'; + $objectclass = 'Account'; + $objectlabel = 'BankTransaction'; $permissiontoread = $user->rights->banque->lire; $permissiontodelete = $user->rights->banque->supprimer; $uploaddir = $conf->bank->dir_output; @@ -218,23 +218,23 @@ if (empty($reshook)) // Conciliation if ((GETPOST('confirm_savestatement', 'alpha') || GETPOST('confirm_reconcile', 'alpha')) && $user->rights->banque->consolidate) { - $error=0; + $error = 0; // Definition, nettoyage parametres - $num_releve=trim(GETPOST("num_releve", "alpha")); + $num_releve = trim(GETPOST("num_releve", "alpha")); if ($num_releve) { - $bankline=new AccountLine($db); + $bankline = new AccountLine($db); if (isset($_POST['rowid']) && is_array($_POST['rowid'])) { - foreach($_POST['rowid'] as $row) + foreach ($_POST['rowid'] as $row) { if ($row > 0) { - $result=$bankline->fetch($row); - $bankline->num_releve=$num_releve; //$_POST["num_releve"]; - $result=$bankline->update_conciliation($user, GETPOST("cat"), GETPOST('confirm_reconcile', 'alpha')?1:0); // If we confirm_reconcile, we set flag 'rappro' to 1. + $result = $bankline->fetch($row); + $bankline->num_releve = $num_releve; //$_POST["num_releve"]; + $result = $bankline->update_conciliation($user, GETPOST("cat"), GETPOST('confirm_reconcile', 'alpha') ? 1 : 0); // If we confirm_reconcile, we set flag 'rappro' to 1. if ($result < 0) { setEventMessages($bankline->error, $bankline->errors, 'errors'); @@ -258,30 +258,30 @@ if ((GETPOST('confirm_savestatement', 'alpha') || GETPOST('confirm_reconcile', ' setEventMessages($langs->trans("ErrorPleaseTypeBankTransactionReportName"), null, 'errors'); } - if (! $error) + if (!$error) { - $param='action=reconcile&contextpage=banktransactionlist&id='.$id.'&search_account='.$id; - $param.='&search_conciliated='.urlencode($search_conciliated); - if ($page) $param.='&page='.urlencode($page); - if ($offset) $param.='&offset='.urlencode($offset); - if ($search_thirdparty) $param.='&search_thirdparty='.urlencode($search_thirdparty); - if ($search_num_releve) $param.='&search_num_releve='.urlencode($search_num_releve); - if ($search_description) $param.='&search_description='.urlencode($search_description); - if ($search_start_dt) $param.='&search_start_dt='.urlencode($search_start_dt); - if ($search_end_dt) $param.='&search_end_dt='.urlencode($search_end_dt); - if ($search_start_dv) $param.='&search_start_dv='.urlencode($search_start_dv); - if ($search_end_dv) $param.='&search_end_dv='.urlencode($search_end_dv); - if ($search_type) $param.='&search_type='.urlencode($search_type); - if ($search_debit) $param.='&search_debit='.urlencode($search_debit); - if ($search_credit) $param.='&search_credit='.urlencode($search_credit); - $param.='&sortfield='.urlencode($sortfield).'&sortorder='.urlencode($sortorder); - header('Location: '.$_SERVER["PHP_SELF"].'?'.$param); // To avoid to submit twice and allow the back button + $param = 'action=reconcile&contextpage=banktransactionlist&id='.$id.'&search_account='.$id; + $param .= '&search_conciliated='.urlencode($search_conciliated); + if ($page) $param .= '&page='.urlencode($page); + if ($offset) $param .= '&offset='.urlencode($offset); + if ($search_thirdparty) $param .= '&search_thirdparty='.urlencode($search_thirdparty); + if ($search_num_releve) $param .= '&search_num_releve='.urlencode($search_num_releve); + if ($search_description) $param .= '&search_description='.urlencode($search_description); + if ($search_start_dt) $param .= '&search_start_dt='.urlencode($search_start_dt); + if ($search_end_dt) $param .= '&search_end_dt='.urlencode($search_end_dt); + if ($search_start_dv) $param .= '&search_start_dv='.urlencode($search_start_dv); + if ($search_end_dv) $param .= '&search_end_dv='.urlencode($search_end_dv); + if ($search_type) $param .= '&search_type='.urlencode($search_type); + if ($search_debit) $param .= '&search_debit='.urlencode($search_debit); + if ($search_credit) $param .= '&search_credit='.urlencode($search_credit); + $param .= '&sortfield='.urlencode($sortfield).'&sortorder='.urlencode($sortorder); + header('Location: '.$_SERVER["PHP_SELF"].'?'.$param); // To avoid to submit twice and allow the back button exit; } } -if (GETPOST('save') && ! $cancel && $user->rights->banque->modifier) +if (GETPOST('save') && !$cancel && $user->rights->banque->modifier) { $error = 0; @@ -302,23 +302,23 @@ if (GETPOST('save') && ! $cancel && $user->rights->banque->modifier) $bankaccountid = $id; if (GETPOST('add_account', 'int') > 0) $bankaccountid = GETPOST('add_account', 'int'); - if (! $dateop) { + if (!$dateop) { $error++; setEventMessages($langs->trans("ErrorFieldRequired", $langs->transnoentitiesnoconv("Date")), null, 'errors'); } - if (! $operation) { + if (!$operation) { $error++; setEventMessages($langs->trans("ErrorFieldRequired", $langs->transnoentitiesnoconv("Type")), null, 'errors'); } - if (! $label) { + if (!$label) { $error++; setEventMessages($langs->trans("ErrorFieldRequired", $langs->transnoentitiesnoconv("Label")), null, 'errors'); } - if (! $amount) { + if (!$amount) { $error++; setEventMessages($langs->trans("ErrorFieldRequired", $langs->transnoentitiesnoconv("Amount")), null, 'errors'); } - if (! $bankaccountid > 0) + if (!$bankaccountid > 0) { $error++; setEventMessages($langs->trans("ErrorFieldRequired", $langs->transnoentitiesnoconv("BankAccount")), null, 'errors'); @@ -329,7 +329,7 @@ if (GETPOST('save') && ! $cancel && $user->rights->banque->modifier) $error++; }*/ - if (! $error && ! empty($conf->global->BANK_USE_OLD_VARIOUS_PAYMENT)) + if (!$error && !empty($conf->global->BANK_USE_OLD_VARIOUS_PAYMENT)) { $objecttmp = new Account($db); $objecttmp->fetch($bankaccountid); @@ -347,15 +347,15 @@ if (GETPOST('save') && ! $cancel && $user->rights->banque->modifier) } else { - $action='addline'; + $action = 'addline'; } } if ($action == 'confirm_delete' && $confirm == 'yes' && $user->rights->banque->modifier) { - $accline=new AccountLine($db); - $result=$accline->fetch(GETPOST("rowid")); - $result=$accline->delete($user); + $accline = new AccountLine($db); + $result = $accline->fetch(GETPOST("rowid")); + $result = $accline->delete($user); } @@ -368,52 +368,52 @@ $form = new Form($db); $formother = new FormOther($db); $formaccounting = new FormAccounting($db); -$companystatic=new Societe($db); -$bankaccountstatic=new Account($db); +$companystatic = new Societe($db); +$bankaccountstatic = new Account($db); -$banktransferstatic=new BonPrelevement($db); -$societestatic=new Societe($db); -$userstatic=new User($db); -$chargestatic=new ChargeSociales($db); -$loanstatic=new Loan($db); -$memberstatic=new Adherent($db); -$paymentstatic=new Paiement($db); -$paymentsupplierstatic=new PaiementFourn($db); -$paymentvatstatic=new TVA($db); -$paymentsalstatic=new PaymentSalary($db); -$paymentvariousstatic=new PaymentVarious($db); -$donstatic=new Don($db); -$paymentexpensereportstatic=new PaymentExpenseReport($db); -$bankstatic=new Account($db); -$banklinestatic=new AccountLine($db); +$banktransferstatic = new BonPrelevement($db); +$societestatic = new Societe($db); +$userstatic = new User($db); +$chargestatic = new ChargeSociales($db); +$loanstatic = new Loan($db); +$memberstatic = new Adherent($db); +$paymentstatic = new Paiement($db); +$paymentsupplierstatic = new PaiementFourn($db); +$paymentvatstatic = new TVA($db); +$paymentsalstatic = new PaymentSalary($db); +$paymentvariousstatic = new PaymentVarious($db); +$donstatic = new Don($db); +$paymentexpensereportstatic = new PaymentExpenseReport($db); +$bankstatic = new Account($db); +$banklinestatic = new AccountLine($db); $now = dol_now(); // Must be before button action -$param=''; -if (! empty($contextpage) && $contextpage != $_SERVER["PHP_SELF"]) $param.='&contextpage='.urlencode($contextpage); -if ($limit > 0 && $limit != $conf->liste_limit) $param.='&limit='.urlencode($limit); -if ($id > 0) $param.='&id='.urlencode($id); -if (!empty($ref)) $param.='&ref='.urlencode($ref); -if (!empty($search_ref)) $param.='&search_ref='.urlencode($search_ref); -if (!empty($search_description)) $param.='&search_description='.urlencode($search_description); -if (!empty($search_type)) $param.='&type='.urlencode($search_type); -if (!empty($search_thirdparty)) $param.='&search_thirdparty='.urlencode($search_thirdparty); -if (!empty($search_debit)) $param.='&search_debit='.urlencode($search_debit); -if (!empty($search_credit)) $param.='&search_credit='.urlencode($search_credit); -if (!empty($search_account)) $param.='&search_account='.urlencode($search_account); -if (!empty($search_num_releve)) $param.='&search_num_releve='.urlencode($search_num_releve); -if ($search_conciliated != '' && $search_conciliated != '-1') $param.='&search_conciliated='.urlencode($search_conciliated); -if ($search_bid > 0) $param.='&search_bid='.urlencode($search_bid); -if (dol_strlen($search_dt_start) > 0) $param .= '&search_start_dtmonth=' . GETPOST('search_start_dtmonth', 'int') . '&search_start_dtday=' . GETPOST('search_start_dtday', 'int') . '&search_start_dtyear=' . GETPOST('search_start_dtyear', 'int'); -if (dol_strlen($search_dt_end) > 0) $param .= '&search_end_dtmonth=' . GETPOST('search_end_dtmonth', 'int') . '&search_end_dtday=' . GETPOST('search_end_dtday', 'int') . '&search_end_dtyear=' . GETPOST('search_end_dtyear', 'int'); -if (dol_strlen($search_dv_start) > 0) $param .= '&search_start_dvmonth=' . GETPOST('search_start_dvmonth', 'int') . '&search_start_dvday=' . GETPOST('search_start_dvday', 'int') . '&search_start_dvyear=' . GETPOST('search_start_dvyear', 'int'); -if (dol_strlen($search_dv_end) > 0) $param .= '&search_end_dvmonth=' . GETPOST('search_end_dvmonth', 'int') . '&search_end_dvday=' . GETPOST('search_end_dvday', 'int') . '&search_end_dvyear=' . GETPOST('search_end_dvyear', 'int'); -if ($search_req_nb) $param.='&req_nb='.urlencode($search_req_nb); -if (GETPOST("search_thirdparty", 'int')) $param.='&thirdparty='.urlencode(GETPOST("search_thirdparty", 'int')); -if ($optioncss != '') $param.='&optioncss='.urlencode($optioncss); -if ($action == 'reconcile') $param.='&action=reconcile'; +$param = ''; +if (!empty($contextpage) && $contextpage != $_SERVER["PHP_SELF"]) $param .= '&contextpage='.urlencode($contextpage); +if ($limit > 0 && $limit != $conf->liste_limit) $param .= '&limit='.urlencode($limit); +if ($id > 0) $param .= '&id='.urlencode($id); +if (!empty($ref)) $param .= '&ref='.urlencode($ref); +if (!empty($search_ref)) $param .= '&search_ref='.urlencode($search_ref); +if (!empty($search_description)) $param .= '&search_description='.urlencode($search_description); +if (!empty($search_type)) $param .= '&type='.urlencode($search_type); +if (!empty($search_thirdparty)) $param .= '&search_thirdparty='.urlencode($search_thirdparty); +if (!empty($search_debit)) $param .= '&search_debit='.urlencode($search_debit); +if (!empty($search_credit)) $param .= '&search_credit='.urlencode($search_credit); +if (!empty($search_account)) $param .= '&search_account='.urlencode($search_account); +if (!empty($search_num_releve)) $param .= '&search_num_releve='.urlencode($search_num_releve); +if ($search_conciliated != '' && $search_conciliated != '-1') $param .= '&search_conciliated='.urlencode($search_conciliated); +if ($search_bid > 0) $param .= '&search_bid='.urlencode($search_bid); +if (dol_strlen($search_dt_start) > 0) $param .= '&search_start_dtmonth='.GETPOST('search_start_dtmonth', 'int').'&search_start_dtday='.GETPOST('search_start_dtday', 'int').'&search_start_dtyear='.GETPOST('search_start_dtyear', 'int'); +if (dol_strlen($search_dt_end) > 0) $param .= '&search_end_dtmonth='.GETPOST('search_end_dtmonth', 'int').'&search_end_dtday='.GETPOST('search_end_dtday', 'int').'&search_end_dtyear='.GETPOST('search_end_dtyear', 'int'); +if (dol_strlen($search_dv_start) > 0) $param .= '&search_start_dvmonth='.GETPOST('search_start_dvmonth', 'int').'&search_start_dvday='.GETPOST('search_start_dvday', 'int').'&search_start_dvyear='.GETPOST('search_start_dvyear', 'int'); +if (dol_strlen($search_dv_end) > 0) $param .= '&search_end_dvmonth='.GETPOST('search_end_dvmonth', 'int').'&search_end_dvday='.GETPOST('search_end_dvday', 'int').'&search_end_dvyear='.GETPOST('search_end_dvyear', 'int'); +if ($search_req_nb) $param .= '&req_nb='.urlencode($search_req_nb); +if (GETPOST("search_thirdparty", 'int')) $param .= '&thirdparty='.urlencode(GETPOST("search_thirdparty", 'int')); +if ($optioncss != '') $param .= '&optioncss='.urlencode($optioncss); +if ($action == 'reconcile') $param .= '&action=reconcile'; // Add $param from extra fields include DOL_DOCUMENT_ROOT.'/core/tpl/extrafields_list_search_param.tpl.php'; @@ -421,7 +421,7 @@ $options = array(); $buttonreconcile = ''; -if ($id > 0 || ! empty($ref)) +if ($id > 0 || !empty($ref)) { $title = $langs->trans("FinancialAccount").' - '.$langs->trans("Transactions"); $helpurl = ""; @@ -436,7 +436,7 @@ if ($id > 0 || ! empty($ref)) } // Bank card - $head=bank_prepare_head($object); + $head = bank_prepare_head($object); dol_fiche_head($head, 'journal', $langs->trans("FinancialAccount"), 0, 'account'); $linkback = ''.$langs->trans("BackToList").''; @@ -471,43 +471,43 @@ else } $sql = "SELECT b.rowid, b.dateo as do, b.datev as dv, b.amount, b.label, b.rappro as conciliated, b.num_releve, b.num_chq,"; -$sql.= " b.fk_account, b.fk_type,"; -$sql.= " ba.rowid as bankid, ba.ref as bankref,"; -$sql.= " bu.url_id,"; -$sql.= " s.nom, s.name_alias, s.client, s.fournisseur, s.email, s.code_client, s.code_fournisseur, s.code_compta, s.code_compta_fournisseur"; +$sql .= " b.fk_account, b.fk_type,"; +$sql .= " ba.rowid as bankid, ba.ref as bankref,"; +$sql .= " bu.url_id,"; +$sql .= " s.nom, s.name_alias, s.client, s.fournisseur, s.email, s.code_client, s.code_fournisseur, s.code_compta, s.code_compta_fournisseur"; // 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 : ''); +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 : ''); } // 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 "; -if ($search_bid>0) $sql.= MAIN_DB_PREFIX."bank_class as l,"; -$sql.= " ".MAIN_DB_PREFIX."bank_account as ba,"; -$sql.= " ".MAIN_DB_PREFIX."bank as b"; -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 (b.rowid = ef.fk_object)"; -$sql.= " LEFT JOIN ".MAIN_DB_PREFIX."bank_url as bu ON bu.fk_bank = b.rowid AND type = 'company'"; -$sql.= " LEFT JOIN ".MAIN_DB_PREFIX."societe as s ON bu.url_id = s.rowid"; -$sql.= " WHERE b.fk_account = ba.rowid"; -$sql.= " AND ba.entity IN (".getEntity('bank_account').")"; -if ($search_account > 0) $sql.=" AND b.fk_account = ".$search_account; +$parameters = array(); +$reshook = $hookmanager->executeHooks('printFieldListSelect', $parameters); // Note that $action and $object may have been modified by hook +$sql .= $hookmanager->resPrint; +$sql .= " FROM "; +if ($search_bid > 0) $sql .= MAIN_DB_PREFIX."bank_class as l,"; +$sql .= " ".MAIN_DB_PREFIX."bank_account as ba,"; +$sql .= " ".MAIN_DB_PREFIX."bank as b"; +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 (b.rowid = ef.fk_object)"; +$sql .= " LEFT JOIN ".MAIN_DB_PREFIX."bank_url as bu ON bu.fk_bank = b.rowid AND type = 'company'"; +$sql .= " LEFT JOIN ".MAIN_DB_PREFIX."societe as s ON bu.url_id = s.rowid"; +$sql .= " WHERE b.fk_account = ba.rowid"; +$sql .= " AND ba.entity IN (".getEntity('bank_account').")"; +if ($search_account > 0) $sql .= " AND b.fk_account = ".$search_account; // Search period criteria -if (dol_strlen($search_dt_start)>0) $sql .= " AND b.dateo >= '" . $db->idate($search_dt_start) . "'"; -if (dol_strlen($search_dt_end)>0) $sql .= " AND b.dateo <= '" . $db->idate($search_dt_end) . "'"; +if (dol_strlen($search_dt_start) > 0) $sql .= " AND b.dateo >= '".$db->idate($search_dt_start)."'"; +if (dol_strlen($search_dt_end) > 0) $sql .= " AND b.dateo <= '".$db->idate($search_dt_end)."'"; // Search period criteria -if (dol_strlen($search_dv_start)>0) $sql .= " AND b.datev >= '" . $db->idate($search_dv_start) . "'"; -if (dol_strlen($search_dv_end)>0) $sql .= " AND b.datev <= '" . $db->idate($search_dv_end) . "'"; -if ($search_ref) $sql.=natural_search("b.rowid", $search_ref, 1); -if ($search_req_nb) $sql.= natural_search("b.num_chq", $search_req_nb); -if ($search_num_releve) $sql.= natural_search("b.num_releve", $search_num_releve); -if ($search_conciliated != '' && $search_conciliated != '-1') $sql.= " AND b.rappro = ".$search_conciliated; -if ($search_thirdparty) $sql.= natural_search("s.nom", $search_thirdparty); +if (dol_strlen($search_dv_start) > 0) $sql .= " AND b.datev >= '".$db->idate($search_dv_start)."'"; +if (dol_strlen($search_dv_end) > 0) $sql .= " AND b.datev <= '".$db->idate($search_dv_end)."'"; +if ($search_ref) $sql .= natural_search("b.rowid", $search_ref, 1); +if ($search_req_nb) $sql .= natural_search("b.num_chq", $search_req_nb); +if ($search_num_releve) $sql .= natural_search("b.num_releve", $search_num_releve); +if ($search_conciliated != '' && $search_conciliated != '-1') $sql .= " AND b.rappro = ".$search_conciliated; +if ($search_thirdparty) $sql .= natural_search("s.nom", $search_thirdparty); if ($search_description) { $search_description_to_use = $search_description; - $arrayoffixedlabels=array( + $arrayoffixedlabels = array( 'payment_salary', 'CustomerInvoicePayment', 'CustomerInvoicePaymentBack', 'SupplierInvoicePayment', 'SupplierInvoicePaymentBack', @@ -517,32 +517,32 @@ if ($search_description) 'SubscriptionPayment', 'WithdrawalPayment' ); - foreach($arrayoffixedlabels as $keyforlabel) + foreach ($arrayoffixedlabels as $keyforlabel) { $translatedlabel = $langs->transnoentitiesnoconv($keyforlabel); if (preg_match('/'.$search_description.'/i', $translatedlabel)) { - $search_description_to_use.="|".$keyforlabel; + $search_description_to_use .= "|".$keyforlabel; } } - $sql.= natural_search("b.label", $search_description_to_use); // Warning some text are just translation keys, not translated strings + $sql .= natural_search("b.label", $search_description_to_use); // Warning some text are just translation keys, not translated strings } -if ($search_bid > 0) $sql.= " AND b.rowid=l.lineid AND l.fk_categ=".$search_bid; -if (! empty($search_type)) $sql.= " AND b.fk_type = '".$db->escape($search_type)."' "; +if ($search_bid > 0) $sql .= " AND b.rowid=l.lineid AND l.fk_categ=".$search_bid; +if (!empty($search_type)) $sql .= " AND b.fk_type = '".$db->escape($search_type)."' "; // Search criteria amount $search_debit = price2num(str_replace('-', '', $search_debit)); $search_credit = price2num(str_replace('-', '', $search_credit)); -if ($search_debit) $sql.= natural_search('- b.amount', $search_debit, 1); -if ($search_credit) $sql.= natural_search('b.amount', $search_credit, 1); +if ($search_debit) $sql .= natural_search('- b.amount', $search_debit, 1); +if ($search_credit) $sql .= natural_search('b.amount', $search_credit, 1); // Add where from extra fields include DOL_DOCUMENT_ROOT.'/core/tpl/extrafields_list_search_sql.tpl.php'; // Add where from hooks -$parameters=array(); -$reshook=$hookmanager->executeHooks('printFieldListWhere', $parameters); // Note that $action and $object may have been modified by hook -$sql.=$hookmanager->resPrint; +$parameters = array(); +$reshook = $hookmanager->executeHooks('printFieldListWhere', $parameters); // Note that $action and $object may have been modified by hook +$sql .= $hookmanager->resPrint; -$sql.= $db->order($sortfield, $sortorder); +$sql .= $db->order($sortfield, $sortorder); $nbtotalofrecords = ''; $nbtotalofpages = 0; @@ -550,10 +550,10 @@ if (empty($conf->global->MAIN_DISABLE_FULL_SCANLIST)) { $result = $db->query($sql); $nbtotalofrecords = $db->num_rows($result); - $nbtotalofpages = ceil($nbtotalofrecords/$limit); + $nbtotalofpages = ceil($nbtotalofrecords / $limit); } -if (($id > 0 || ! empty($ref)) && ((string) $page == '')) +if (($id > 0 || !empty($ref)) && ((string) $page == '')) { // We open a list of transaction of a dedicated account and no page was set by defaut // We force on last page. @@ -564,22 +564,22 @@ if (($id > 0 || ! empty($ref)) && ((string) $page == '')) if ($page >= $nbtotalofpages) { // If we made a search and result has low page than the page number we were on - $page = ($nbtotalofpages -1); + $page = ($nbtotalofpages - 1); $offset = $limit * $page; if ($page < 0) $page = 0; } // If not account defined $mode_balance_ok=false -if (empty($search_account)) $mode_balance_ok=false; +if (empty($search_account)) $mode_balance_ok = false; // If a search is done $mode_balance_ok=false -if (! empty($search_ref)) $mode_balance_ok=false; -if (! empty($req_nb)) $mode_balance_ok=false; -if (! empty($search_type)) $mode_balance_ok=false; -if (! empty($debit)) $mode_balance_ok=false; -if (! empty($credit)) $mode_balance_ok=false; -if (! empty($thirdparty)) $mode_balance_ok=false; +if (!empty($search_ref)) $mode_balance_ok = false; +if (!empty($req_nb)) $mode_balance_ok = false; +if (!empty($search_type)) $mode_balance_ok = false; +if (!empty($debit)) $mode_balance_ok = false; +if (!empty($credit)) $mode_balance_ok = false; +if (!empty($thirdparty)) $mode_balance_ok = false; -$sql.= $db->plimit($limit+1, $offset); +$sql .= $db->plimit($limit + 1, $offset); //print $sql; dol_syslog('compta/bank/bankentries_list.php', LOG_DEBUG); $resql = $db->query($sql); @@ -587,21 +587,21 @@ if ($resql) { $num = $db->num_rows($resql); - $arrayofselected=is_array($toselect)?$toselect:array(); + $arrayofselected = is_array($toselect) ? $toselect : array(); // List of mass actions available - $arrayofmassactions = array( + $arrayofmassactions = array( //'presend'=>$langs->trans("SendByMail"), //'builddoc'=>$langs->trans("PDFMerge"), ); //if ($user->rights->bank->supprimer) $arrayofmassactions['predelete']=''.$langs->trans("Delete"); - if (in_array($massaction, array('presend','predelete'))) $arrayofmassactions=array(); - $massactionbutton=$form->selectMassAction('', $arrayofmassactions); + if (in_array($massaction, array('presend', 'predelete'))) $arrayofmassactions = array(); + $massactionbutton = $form->selectMassAction('', $arrayofmassactions); // Confirmation delete if ($action == 'delete') { - $text=$langs->trans('ConfirmDeleteTransaction'); + $text = $langs->trans('ConfirmDeleteTransaction'); print $form->formconfirm($_SERVER['PHP_SELF'].'?id='.$object->id.'&rowid='.GETPOST("rowid"), $langs->trans('DeleteTransaction'), $text, 'confirm_delete', null, '', 1); } @@ -610,7 +610,7 @@ if ($resql) if ($optioncss != '') print ''; print ''; print ''; - print ''; + print ''; print ''; print ''; print ''; @@ -624,7 +624,7 @@ if ($resql) { print '
'; print ''.$langs->trans("InputReceiptNumber").': '; - print ''; // The only default value is value we just entered + print ''; // The only default value is value we just entered print '
'; if (is_array($options) && count($options)) { @@ -640,31 +640,31 @@ if ($resql) print '
'; // Show last bank statements - $nbmax=15; // We accept to show last 15 receipts (so we can have more than one year) - $liste=""; + $nbmax = 15; // We accept to show last 15 receipts (so we can have more than one year) + $liste = ""; $sql = "SELECT DISTINCT num_releve FROM ".MAIN_DB_PREFIX."bank"; - $sql.= " WHERE fk_account=".$object->id." AND num_releve IS NOT NULL"; - $sql.= $db->order("num_releve", "DESC"); - $sql.= $db->plimit($nbmax+1); + $sql .= " WHERE fk_account=".$object->id." AND num_releve IS NOT NULL"; + $sql .= $db->order("num_releve", "DESC"); + $sql .= $db->plimit($nbmax + 1); print '
'; print $langs->trans("LastAccountStatements").' : '; - $resqlr=$db->query($sql); + $resqlr = $db->query($sql); if ($resqlr) { - $numr=$db->num_rows($resqlr); - $i=0; - $last_ok=0; + $numr = $db->num_rows($resqlr); + $i = 0; + $last_ok = 0; while (($i < $numr) && ($i < $nbmax)) { $objr = $db->fetch_object($resqlr); - if (! $last_ok) { + if (!$last_ok) { $last_releve = $objr->num_releve; - $last_ok=1; + $last_ok = 1; } $i++; - $liste=''.$objr->num_releve.'   '.$liste; + $liste = ''.$objr->num_releve.'   '.$liste; } - if ($numr >= $nbmax) $liste="...   ".$liste; + if ($numr >= $nbmax) $liste = "...   ".$liste; print $liste; if ($numr <= 0) print ''.$langs->trans("None").''; } @@ -674,11 +674,11 @@ if ($resql) } // Using BANK_REPORT_LAST_NUM_RELEVE to automatically report last num (or not) - if (! empty($conf->global->BANK_REPORT_LAST_NUM_RELEVE)) + if (!empty($conf->global->BANK_REPORT_LAST_NUM_RELEVE)) { print ' '; } @@ -686,11 +686,11 @@ if ($resql) } // Form to add a transaction with no invoice - if ($user->rights->banque->modifier && $action == 'addline' && ! empty($conf->global->BANK_USE_OLD_VARIOUS_PAYMENT)) + if ($user->rights->banque->modifier && $action == 'addline' && !empty($conf->global->BANK_USE_OLD_VARIOUS_PAYMENT)) { print load_fiche_titre($langs->trans("AddBankRecordLong"), '', ''); - print ''; + print '
'; print ''; print ''; @@ -723,11 +723,11 @@ if ($resql) } print ''; print ''; print ''; print ''; print ''; //} print ''; @@ -778,7 +778,7 @@ if ($resql) $i = 0; // Title - $bankcateg=new BankCateg($db); + $bankcateg = new BankCateg($db); $newcardbutton = ''; if ($action != 'addline' && $action != 'reconcile') @@ -800,63 +800,63 @@ if ($resql) } } - $morehtml='
'; - $morehtml.= ' "; // ' Page '; - $morehtml.=''; - $morehtml.='/'.$nbtotalofpages.' '; - $morehtml.='
'; + $morehtml = '
'; + $morehtml .= ' "; // ' Page '; + $morehtml .= ''; + $morehtml .= '/'.$nbtotalofpages.' '; + $morehtml .= '
'; if ($action != 'addline' && $action != 'reconcile') { - $morehtml.=$buttonreconcile; + $morehtml .= $buttonreconcile; } - $morehtml.=$newcardbutton; + $morehtml .= $newcardbutton; - $picto='title_bank'; - if ($id > 0 || ! empty($ref)) $picto=''; + $picto = 'title_bank'; + if ($id > 0 || !empty($ref)) $picto = ''; print_barre_liste($langs->trans("BankTransactions"), $page, $_SERVER["PHP_SELF"], $param, $sortfield, $sortorder, $massactionbutton, $num, $nbtotalofrecords, $picto, 0, $morehtml, '', $limit); // We can add page now to param - if ($page != '') $param.='&page='.urlencode($page); + if ($page != '') $param .= '&page='.urlencode($page); $moreforfilter = ''; - $moreforfilter.='
'; + $moreforfilter .= '
'; $moreforfilter .= $langs->trans('DateOperationShort').' : '; - $moreforfilter .= '
'.$langs->trans('From') . ' '; + $moreforfilter .= '
'.$langs->trans('From').' '; $moreforfilter .= $form->selectDate($search_dt_start, 'search_start_dt', 0, 0, 1, "search_form", 1, 0).'
'; //$moreforfilter .= ' - '; - $moreforfilter .= '
'.$langs->trans('to') . ' ' . $form->selectDate($search_dt_end, 'search_end_dt', 0, 0, 1, "search_form", 1, 0).'
'; + $moreforfilter .= '
'.$langs->trans('to').' '.$form->selectDate($search_dt_end, 'search_end_dt', 0, 0, 1, "search_form", 1, 0).'
'; $moreforfilter .= '
'; - $moreforfilter.='
'; + $moreforfilter .= '
'; $moreforfilter .= $langs->trans('DateValueShort').' : '; - $moreforfilter .= '
'.$langs->trans('From') . ' '; + $moreforfilter .= '
'.$langs->trans('From').' '; $moreforfilter .= $form->selectDate($search_dv_start, 'search_start_dv', 0, 0, 1, "search_form", 1, 0).'
'; //$moreforfilter .= ' - '; - $moreforfilter .= '
'.$langs->trans('to') . ' ' . $form->selectDate($search_dv_end, 'search_end_dv', 0, 0, 1, "search_form", 1, 0).'
'; + $moreforfilter .= '
'.$langs->trans('to').' '.$form->selectDate($search_dv_end, 'search_end_dv', 0, 0, 1, "search_form", 1, 0).'
'; $moreforfilter .= '
'; - if (! empty($conf->categorie->enabled)) + if (!empty($conf->categorie->enabled)) { // Categories - if (! empty($conf->categorie->enabled) && ! empty($user->rights->categorie->lire)) + if (!empty($conf->categorie->enabled) && !empty($user->rights->categorie->lire)) { $langs->load('categories'); // Bank line - $moreforfilter.='
'; - $moreforfilter.=$langs->trans('RubriquesTransactions').' : '; + $moreforfilter .= '
'; + $moreforfilter .= $langs->trans('RubriquesTransactions').' : '; $cate_arbo = $form->select_all_categories(Categorie::TYPE_BANK_LINE, $search_bid, 'parent', null, null, 1); - $moreforfilter.=$form->selectarray('search_bid', $cate_arbo, $search_bid, 1); - $moreforfilter.='
'; + $moreforfilter .= $form->selectarray('search_bid', $cate_arbo, $search_bid, 1); + $moreforfilter .= '
'; } } - $parameters=array(); - $reshook=$hookmanager->executeHooks('printFieldPreListTitle', $parameters); // Note that $action and $object may have been modified by hook + $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; @@ -957,39 +957,39 @@ if ($resql) print '
'; print ''; print "\n"; // Fields title print ''; - if (! empty($arrayfields['b.rowid']['checked'])) print_liste_field_titre($arrayfields['b.rowid']['label'], $_SERVER['PHP_SELF'], 'b.rowid', '', $param, '', $sortfield, $sortorder); - if (! empty($arrayfields['b.label']['checked'])) print_liste_field_titre($arrayfields['b.label']['label'], $_SERVER['PHP_SELF'], 'b.label', '', $param, '', $sortfield, $sortorder); - if (! empty($arrayfields['b.dateo']['checked'])) print_liste_field_titre($arrayfields['b.dateo']['label'], $_SERVER['PHP_SELF'], 'b.dateo', '', $param, '', $sortfield, $sortorder, "center "); - if (! empty($arrayfields['b.datev']['checked'])) print_liste_field_titre($arrayfields['b.datev']['label'], $_SERVER['PHP_SELF'], 'b.datev,b.dateo,b.rowid', '', $param, 'align="center"', $sortfield, $sortorder); - if (! empty($arrayfields['type']['checked'])) print_liste_field_titre($arrayfields['type']['label'], $_SERVER['PHP_SELF'], '', '', $param, 'align="center"', $sortfield, $sortorder); - if (! empty($arrayfields['b.num_chq']['checked'])) print_liste_field_titre($arrayfields['b.num_chq']['label'], $_SERVER['PHP_SELF'], 'b.num_chq', '', $param, '', $sortfield, $sortorder, "center "); - if (! empty($arrayfields['bu.label']['checked'])) print_liste_field_titre($arrayfields['bu.label']['label'], $_SERVER['PHP_SELF'], 'bu.label', '', $param, '', $sortfield, $sortorder); - if (! empty($arrayfields['ba.ref']['checked'])) print_liste_field_titre($arrayfields['ba.ref']['label'], $_SERVER['PHP_SELF'], 'ba.ref', '', $param, '', $sortfield, $sortorder); - if (! empty($arrayfields['b.debit']['checked'])) print_liste_field_titre($arrayfields['b.debit']['label'], $_SERVER['PHP_SELF'], 'b.amount', '', $param, '', $sortfield, $sortorder, "right "); - if (! empty($arrayfields['b.credit']['checked'])) print_liste_field_titre($arrayfields['b.credit']['label'], $_SERVER['PHP_SELF'], 'b.amount', '', $param, '', $sortfield, $sortorder, "right "); - if (! empty($arrayfields['balancebefore']['checked'])) print_liste_field_titre($arrayfields['balancebefore']['label'], $_SERVER['PHP_SELF'], '', '', $param, '', $sortfield, $sortorder, "right "); - if (! empty($arrayfields['balance']['checked'])) print_liste_field_titre($arrayfields['balance']['label'], $_SERVER['PHP_SELF'], '', '', $param, '', $sortfield, $sortorder, "right "); - if (! empty($arrayfields['b.num_releve']['checked'])) print_liste_field_titre($arrayfields['b.num_releve']['label'], $_SERVER['PHP_SELF'], 'b.num_releve', '', $param, '', $sortfield, $sortorder, "center "); - if (! empty($arrayfields['b.conciliated']['checked'])) print_liste_field_titre($arrayfields['b.conciliated']['label'], $_SERVER['PHP_SELF'], 'b.rappro', '', $param, '', $sortfield, $sortorder, "center "); + if (!empty($arrayfields['b.rowid']['checked'])) print_liste_field_titre($arrayfields['b.rowid']['label'], $_SERVER['PHP_SELF'], 'b.rowid', '', $param, '', $sortfield, $sortorder); + if (!empty($arrayfields['b.label']['checked'])) print_liste_field_titre($arrayfields['b.label']['label'], $_SERVER['PHP_SELF'], 'b.label', '', $param, '', $sortfield, $sortorder); + if (!empty($arrayfields['b.dateo']['checked'])) print_liste_field_titre($arrayfields['b.dateo']['label'], $_SERVER['PHP_SELF'], 'b.dateo', '', $param, '', $sortfield, $sortorder, "center "); + if (!empty($arrayfields['b.datev']['checked'])) print_liste_field_titre($arrayfields['b.datev']['label'], $_SERVER['PHP_SELF'], 'b.datev,b.dateo,b.rowid', '', $param, 'align="center"', $sortfield, $sortorder); + if (!empty($arrayfields['type']['checked'])) print_liste_field_titre($arrayfields['type']['label'], $_SERVER['PHP_SELF'], '', '', $param, 'align="center"', $sortfield, $sortorder); + if (!empty($arrayfields['b.num_chq']['checked'])) print_liste_field_titre($arrayfields['b.num_chq']['label'], $_SERVER['PHP_SELF'], 'b.num_chq', '', $param, '', $sortfield, $sortorder, "center "); + if (!empty($arrayfields['bu.label']['checked'])) print_liste_field_titre($arrayfields['bu.label']['label'], $_SERVER['PHP_SELF'], 'bu.label', '', $param, '', $sortfield, $sortorder); + if (!empty($arrayfields['ba.ref']['checked'])) print_liste_field_titre($arrayfields['ba.ref']['label'], $_SERVER['PHP_SELF'], 'ba.ref', '', $param, '', $sortfield, $sortorder); + if (!empty($arrayfields['b.debit']['checked'])) print_liste_field_titre($arrayfields['b.debit']['label'], $_SERVER['PHP_SELF'], 'b.amount', '', $param, '', $sortfield, $sortorder, "right "); + if (!empty($arrayfields['b.credit']['checked'])) print_liste_field_titre($arrayfields['b.credit']['label'], $_SERVER['PHP_SELF'], 'b.amount', '', $param, '', $sortfield, $sortorder, "right "); + if (!empty($arrayfields['balancebefore']['checked'])) print_liste_field_titre($arrayfields['balancebefore']['label'], $_SERVER['PHP_SELF'], '', '', $param, '', $sortfield, $sortorder, "right "); + if (!empty($arrayfields['balance']['checked'])) print_liste_field_titre($arrayfields['balance']['label'], $_SERVER['PHP_SELF'], '', '', $param, '', $sortfield, $sortorder, "right "); + if (!empty($arrayfields['b.num_releve']['checked'])) print_liste_field_titre($arrayfields['b.num_releve']['label'], $_SERVER['PHP_SELF'], 'b.num_releve', '', $param, '', $sortfield, $sortorder, "center "); + if (!empty($arrayfields['b.conciliated']['checked'])) print_liste_field_titre($arrayfields['b.conciliated']['label'], $_SERVER['PHP_SELF'], 'b.rappro', '', $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 + $parameters = array('arrayfields'=>$arrayfields, 'param'=>$param, 'sortfield'=>$sortfield, 'sortorder'=>$sortorder); + $reshook = $hookmanager->executeHooks('printFieldListTitle', $parameters); // Note that $action and $object may have been modified by hook print $hookmanager->resPrint; print_liste_field_titre('', $_SERVER["PHP_SELF"], "", '', '', 'class="right"', $sortfield, $sortorder, 'maxwidthsearch '); print_liste_field_titre($selectedfields, $_SERVER["PHP_SELF"], "", '', '', 'align="center"', $sortfield, $sortorder, 'maxwidthsearch '); print "\n"; - $balance = 0; // For balance - $balancebefore = 0; // For balance + $balance = 0; // For balance + $balancebefore = 0; // For balance $balancecalculated = false; $posconciliatecol = 0; $cachebankaccount = array(); @@ -997,15 +997,15 @@ if ($resql) // Loop on each record $sign = 1; - $totalarray=array(); + $totalarray = array(); while ($i < min($num, $limit)) { $objp = $db->fetch_object($resql); // If we are in a situation where we need/can show balance, we calculate the start of balance - if (! $balancecalculated && (! empty($arrayfields['balancebefore']['checked']) || ! empty($arrayfields['balance']['checked'])) && $mode_balance_ok) + if (!$balancecalculated && (!empty($arrayfields['balancebefore']['checked']) || !empty($arrayfields['balance']['checked'])) && $mode_balance_ok) { - if (! $search_account) + if (!$search_account) { dol_print_error('', 'account is not defined but $mode_balance_ok is true'); exit; @@ -1014,14 +1014,14 @@ if ($resql) // Loop on each record before $sign = 1; $i = 0; - $sqlforbalance='SELECT SUM(b.amount) as previoustotal'; - $sqlforbalance.= " FROM "; - $sqlforbalance.= " ".MAIN_DB_PREFIX."bank_account as ba,"; - $sqlforbalance.= " ".MAIN_DB_PREFIX."bank as b"; - $sqlforbalance.= " WHERE b.fk_account = ba.rowid"; - $sqlforbalance.= " AND ba.entity IN (".getEntity('bank_account').")"; - $sqlforbalance.= " AND b.fk_account = ".$search_account; - $sqlforbalance.= " AND (b.datev < '" . $db->idate($db->jdate($objp->dv)) . "' OR (b.datev = '" . $db->idate($db->jdate($objp->dv)) . "' AND (b.dateo < '".$db->idate($db->jdate($objp->do))."' OR (b.dateo = '".$db->idate($db->jdate($objp->do))."' AND b.rowid < ".$objp->rowid."))))"; + $sqlforbalance = 'SELECT SUM(b.amount) as previoustotal'; + $sqlforbalance .= " FROM "; + $sqlforbalance .= " ".MAIN_DB_PREFIX."bank_account as ba,"; + $sqlforbalance .= " ".MAIN_DB_PREFIX."bank as b"; + $sqlforbalance .= " WHERE b.fk_account = ba.rowid"; + $sqlforbalance .= " AND ba.entity IN (".getEntity('bank_account').")"; + $sqlforbalance .= " AND b.fk_account = ".$search_account; + $sqlforbalance .= " AND (b.datev < '".$db->idate($db->jdate($objp->dv))."' OR (b.datev = '".$db->idate($db->jdate($objp->dv))."' AND (b.dateo < '".$db->idate($db->jdate($objp->do))."' OR (b.dateo = '".$db->idate($db->jdate($objp->do))."' AND b.rowid < ".$objp->rowid."))))"; $resqlforbalance = $db->query($sqlforbalance); //print $sqlforbalance; if ($resqlforbalance) @@ -1043,24 +1043,24 @@ if ($resql) } else dol_print_error($db); - $balancecalculated=true; + $balancecalculated = true; // Output a line with start balance if ($user->rights->banque->consolidate && $action == 'reconcile') { - $tmpnbfieldbeforebalance=0; - $tmpnbfieldafterbalance=0; - $balancefieldfound=0; - foreach($arrayfields as $key => $val) + $tmpnbfieldbeforebalance = 0; + $tmpnbfieldafterbalance = 0; + $balancefieldfound = 0; + foreach ($arrayfields as $key => $val) { if ($key == 'balancebefore' || $key == 'balance') { $balancefieldfound++; continue; } - if (! empty($arrayfields[$key]['checked'])) + if (!empty($arrayfields[$key]['checked'])) { - if (! $balancefieldfound) $tmpnbfieldbeforebalance++; + if (!$balancefieldfound) $tmpnbfieldbeforebalance++; else $tmpnbfieldafterbalance++; } } @@ -1068,13 +1068,13 @@ if ($resql) $element = 'banktransaction'; if (is_array($extrafields->attributes[$element]['label']) && count($extrafields->attributes[$element]['label'])) { - foreach($extrafields->attributes[$element]['label'] as $key => $val) + foreach ($extrafields->attributes[$element]['label'] as $key => $val) { - if (! empty($arrayfields["ef.".$key]['checked'])) + if (!empty($arrayfields["ef.".$key]['checked'])) { - if (! empty($arrayfields[$key]['checked'])) + if (!empty($arrayfields[$key]['checked'])) { - if (! $balancefieldfound) $tmpnbfieldbeforebalance++; + if (!$balancefieldfound) $tmpnbfieldbeforebalance++; else $tmpnbfieldafterbalance++; } } @@ -1089,13 +1089,13 @@ if ($resql) print ''; } - if (! empty($arrayfields['balancebefore']['checked'])) + if (!empty($arrayfields['balancebefore']['checked'])) { print ''; } - if (! empty($arrayfields['balance']['checked'])) + if (!empty($arrayfields['balance']['checked'])) { print ''; // Ref - if (! empty($arrayfields['b.rowid']['checked'])) + if (!empty($arrayfields['b.rowid']['checked'])) { print ''; - if (! $i) $totalarray['nbfield']++; + if (!$i) $totalarray['nbfield']++; } // Description - if (! empty($arrayfields['b.label']['checked'])) + if (!empty($arrayfields['b.label']['checked'])) { print "'; - if (! $i) $totalarray['nbfield']++; + if (!$i) $totalarray['nbfield']++; } // Date ope - if (! empty($arrayfields['b.dateo']['checked'])) + if (!empty($arrayfields['b.dateo']['checked'])) { print '\n"; - if (! $i) $totalarray['nbfield']++; + if (!$i) $totalarray['nbfield']++; } // Date value - if (! empty($arrayfields['b.datev']['checked'])) + if (!empty($arrayfields['b.datev']['checked'])) { print '\n"; - if (! $i) $totalarray['nbfield']++; + if (!$i) $totalarray['nbfield']++; } // Payment type - if (! empty($arrayfields['type']['checked'])) + if (!empty($arrayfields['type']['checked'])) { print '\n"; - if (! $i) $totalarray['nbfield']++; + if (!$i) $totalarray['nbfield']++; } // Num cheque - if (! empty($arrayfields['b.num_chq']['checked'])) + if (!empty($arrayfields['b.num_chq']['checked'])) { - print '\n"; - if (! $i) $totalarray['nbfield']++; + print '\n"; + if (!$i) $totalarray['nbfield']++; } // Third party - if (! empty($arrayfields['bu.label']['checked'])) + if (!empty($arrayfields['bu.label']['checked'])) { print "'; - if (! $i) $totalarray['nbfield']++; + if (!$i) $totalarray['nbfield']++; } // Bank account - if (! empty($arrayfields['ba.ref']['checked'])) + if (!empty($arrayfields['ba.ref']['checked'])) { print '\n"; - if (! $i) $totalarray['nbfield']++; + if (!$i) $totalarray['nbfield']++; } // Debit - if (! empty($arrayfields['b.debit']['checked'])) + if (!empty($arrayfields['b.debit']['checked'])) { print '\n"; - if (! $i) $totalarray['nbfield']++; - if (! $i) $totalarray['totaldebfield']=$totalarray['nbfield']; + if (!$i) $totalarray['nbfield']++; + if (!$i) $totalarray['totaldebfield'] = $totalarray['nbfield']; } // Credit - if (! empty($arrayfields['b.credit']['checked'])) + if (!empty($arrayfields['b.credit']['checked'])) { print '\n"; - if (! $i) $totalarray['nbfield']++; - if (! $i) $totalarray['totalcredfield']=$totalarray['nbfield']; + if (!$i) $totalarray['nbfield']++; + if (!$i) $totalarray['totalcredfield'] = $totalarray['nbfield']; } // Balance before - if (! empty($arrayfields['balancebefore']['checked'])) + if (!empty($arrayfields['balancebefore']['checked'])) { if ($mode_balance_ok) { @@ -1446,10 +1446,10 @@ if ($resql) { print ''; } - if (! $i) $totalarray['nbfield']++; + if (!$i) $totalarray['nbfield']++; } // Balance - if (! empty($arrayfields['balance']['checked'])) + if (!empty($arrayfields['balance']['checked'])) { if ($mode_balance_ok) { @@ -1466,10 +1466,10 @@ if ($resql) { print ''; } - if (! $i) $totalarray['nbfield']++; + if (!$i) $totalarray['nbfield']++; } - if (! empty($arrayfields['b.num_releve']['checked'])) + if (!empty($arrayfields['b.num_releve']['checked'])) { print ''; - if (! $i) + if (!$i) { $totalarray['nbfield']++; $posconciliatecol = $totalarray['nbfield']; } } - if (! empty($arrayfields['b.conciliated']['checked'])) + if (!empty($arrayfields['b.conciliated']['checked'])) { print ''; - if (! $i) $totalarray['nbfield']++; + if (!$i) $totalarray['nbfield']++; } // Action edit/delete @@ -1539,18 +1539,18 @@ if ($resql) } } print ''; - if (! $i) $totalarray['nbfield']++; + if (!$i) $totalarray['nbfield']++; // Action column print ''; - if (! $i) $totalarray['nbfield']++; + if (!$i) $totalarray['nbfield']++; print ""; @@ -1561,7 +1561,7 @@ if ($resql) if (isset($totalarray['totaldebfield']) || isset($totalarray['totalcredfield'])) { print ''; - $i=0; + $i = 0; while ($i < $totalarray['nbfield']) { $i++; @@ -1575,7 +1575,7 @@ if ($resql) elseif ($i == $posconciliatecol) { print ''; } else print ''; @@ -1586,9 +1586,9 @@ if ($resql) // If no record found if ($num == 0) { - $colspan=1; - foreach($arrayfields as $key => $val) { if (! empty($val['checked'])) $colspan++; } - print ''; + $colspan = 1; + foreach ($arrayfields as $key => $val) { if (!empty($val['checked'])) $colspan++; } + print ''; } print "
'.$langs->trans("Description").''; - print $form->selectDate(empty($dateop)?-1:$dateop, 'op', 0, 0, 0, 'transaction'); + print $form->selectDate(empty($dateop) ?-1 : $dateop, 'op', 0, 0, 0, 'transaction'); print ' '; - $form->select_types_paiements((GETPOST('operation')?GETPOST('operation'):($object->courant == Account::TYPE_CASH ? 'LIQ' : '')), 'operation', '1,2', 2, 1); + $form->select_types_paiements((GETPOST('operation') ?GETPOST('operation') : ($object->courant == Account::TYPE_CASH ? 'LIQ' : '')), 'operation', '1,2', 2, 1); print ''; print ''; @@ -735,7 +735,7 @@ if ($resql) //if (! $search_account > 0) //{ print ''; - $form->select_comptes(GETPOST('add_account', 'int')?GETPOST('add_account', 'int'):$search_account, 'add_account', 0, '', 1, ($id > 0 || ! empty($ref)?' disabled="disabled"':'')); + $form->select_comptes(GETPOST('add_account', 'int') ?GETPOST('add_account', 'int') : $search_account, 'add_account', 0, '', 1, ($id > 0 || !empty($ref) ? ' disabled="disabled"' : '')); print ''; print ''; - $searchpicto=$form->showFilterAndCheckAddButtons($massactionbutton?1:0, 'checkforselect', 1); + $searchpicto = $form->showFilterAndCheckAddButtons($massactionbutton ? 1 : 0, 'checkforselect', 1); print $searchpicto; print '
'; print price(price2num($balance, 'MT'), 1, $langs); print ''; print price(price2num($balance, 'MT'), 1, $langs); @@ -1120,12 +1120,12 @@ if ($resql) if ($sortfield == 'b.datev,b.dateo,b.rowid' && $sortorder == 'desc,desc,desc') { - $balance = price2num($balancebefore, 'MT'); // balance = balancebefore of previous line (sort is desc) + $balance = price2num($balancebefore, 'MT'); // balance = balancebefore of previous line (sort is desc) $balancebefore = price2num($balancebefore - ($sign * $objp->amount), 'MT'); } else { - $balancebefore = price2num($balance, 'MT'); // balancebefore = balance of previous line (sort is asc) + $balancebefore = price2num($balance, 'MT'); // balancebefore = balance of previous line (sort is asc) $balance = price2num($balance + ($sign * $objp->amount), 'MT'); } @@ -1133,7 +1133,7 @@ if ($resql) { $bankaccounttmp = new Account($db); $bankaccounttmp->fetch($objp->bankid); - $cachebankaccount[$objp->bankid]=$bankaccounttmp; + $cachebankaccount[$objp->bankid] = $bankaccounttmp; $bankaccount = $bankaccounttmp; } else @@ -1149,159 +1149,159 @@ if ($resql) if (empty($conf->global->BANK_COLORIZE_MOVEMENT_COLOR1)) { $color = '#fca955'; } else { - $color = '#' . $conf->global->BANK_COLORIZE_MOVEMENT_COLOR1; + $color = '#'.$conf->global->BANK_COLORIZE_MOVEMENT_COLOR1; } - $backgroundcolor = 'style="background-color: ' . $color . ';"'; + $backgroundcolor = 'style="background-color: '.$color.';"'; } else { if (empty($conf->global->BANK_COLORIZE_MOVEMENT_COLOR2)) { $color = '#7fdb86'; } else { - $color = '#' . $conf->global->BANK_COLORIZE_MOVEMENT_COLOR2; + $color = '#'.$conf->global->BANK_COLORIZE_MOVEMENT_COLOR2; } - $backgroundcolor = 'style="background-color: ' . $color . ';"'; + $backgroundcolor = 'style="background-color: '.$color.';"'; } } print '
'; print "rowid.'&save_lastsearch_values=1">'.img_object($langs->trans("ShowPayment").': '.$objp->rowid, 'account', 'class="classfortooltip"').' '.$objp->rowid."   "; print '"; //print "rowid."&account=".$objp->fk_account."\">"; - $reg=array(); - preg_match('/\((.+)\)/i', $objp->label, $reg); // Si texte entoure de parenthee on tente recherche de traduction - if ($reg[1] && $langs->trans($reg[1])!=$reg[1]) print $langs->trans($reg[1]); + $reg = array(); + preg_match('/\((.+)\)/i', $objp->label, $reg); // Si texte entoure de parenthee on tente recherche de traduction + if ($reg[1] && $langs->trans($reg[1]) != $reg[1]) print $langs->trans($reg[1]); else print dol_trunc($objp->label, 40); //print " "; // Add links after description $links = $bankaccountstatic->get_url($objp->rowid); - $cachebankaccount=array(); - foreach($links as $key=>$val) + $cachebankaccount = array(); + foreach ($links as $key=>$val) { - if ($links[$key]['type']=='withdraw') + if ($links[$key]['type'] == 'withdraw') { - $banktransferstatic->id=$links[$key]['url_id']; - $banktransferstatic->ref=$links[$key]['label']; + $banktransferstatic->id = $links[$key]['url_id']; + $banktransferstatic->ref = $links[$key]['label']; print ' '.$banktransferstatic->getNomUrl(0); } - elseif ($links[$key]['type']=='payment') + elseif ($links[$key]['type'] == 'payment') { - $paymentstatic->id=$links[$key]['url_id']; - $paymentstatic->ref=$links[$key]['url_id']; // FIXME This is id, not ref of payment + $paymentstatic->id = $links[$key]['url_id']; + $paymentstatic->ref = $links[$key]['url_id']; // FIXME This is id, not ref of payment print ' '.$paymentstatic->getNomUrl(2); } - elseif ($links[$key]['type']=='payment_supplier') + elseif ($links[$key]['type'] == 'payment_supplier') { - $paymentsupplierstatic->id=$links[$key]['url_id']; - $paymentsupplierstatic->ref=$links[$key]['url_id']; // FIXME This is id, not ref of payment + $paymentsupplierstatic->id = $links[$key]['url_id']; + $paymentsupplierstatic->ref = $links[$key]['url_id']; // FIXME This is id, not ref of payment print ' '.$paymentsupplierstatic->getNomUrl(2); } - elseif ($links[$key]['type']=='payment_sc') + elseif ($links[$key]['type'] == 'payment_sc') { print ''; print ' '.img_object($langs->trans('ShowPayment'), 'payment').' '; //print $langs->trans("SocialContributionPayment"); print ''; } - elseif ($links[$key]['type']=='payment_vat') + elseif ($links[$key]['type'] == 'payment_vat') { - $paymentvatstatic->id=$links[$key]['url_id']; - $paymentvatstatic->ref=$links[$key]['url_id']; + $paymentvatstatic->id = $links[$key]['url_id']; + $paymentvatstatic->ref = $links[$key]['url_id']; print ' '.$paymentvatstatic->getNomUrl(2); } - elseif ($links[$key]['type']=='payment_salary') + elseif ($links[$key]['type'] == 'payment_salary') { - $paymentsalstatic->id=$links[$key]['url_id']; - $paymentsalstatic->ref=$links[$key]['url_id']; + $paymentsalstatic->id = $links[$key]['url_id']; + $paymentsalstatic->ref = $links[$key]['url_id']; print ' '.$paymentsalstatic->getNomUrl(2); } - elseif ($links[$key]['type']=='payment_loan') + elseif ($links[$key]['type'] == 'payment_loan') { print ''; print ' '.img_object($langs->trans('ShowPayment'), 'payment').' '; print ''; } - elseif ($links[$key]['type']=='payment_donation') + elseif ($links[$key]['type'] == 'payment_donation') { print ''; print ' '.img_object($langs->trans('ShowPayment'), 'payment').' '; print ''; } - elseif ($links[$key]['type']=='payment_expensereport') + elseif ($links[$key]['type'] == 'payment_expensereport') { - $paymentexpensereportstatic->id=$links[$key]['url_id']; - $paymentexpensereportstatic->ref=$links[$key]['url_id']; + $paymentexpensereportstatic->id = $links[$key]['url_id']; + $paymentexpensereportstatic->ref = $links[$key]['url_id']; print ' '.$paymentexpensereportstatic->getNomUrl(2); } - elseif ($links[$key]['type']=='payment_various') + elseif ($links[$key]['type'] == 'payment_various') { - $paymentvariousstatic->id=$links[$key]['url_id']; - $paymentvariousstatic->ref=$links[$key]['url_id']; + $paymentvariousstatic->id = $links[$key]['url_id']; + $paymentvariousstatic->ref = $links[$key]['url_id']; print ' '.$paymentvariousstatic->getNomUrl(2); } - elseif ($links[$key]['type']=='banktransfert') + elseif ($links[$key]['type'] == 'banktransfert') { // Do not show link to transfer since there is no transfer card (avoid confusion). Can already be accessed from transaction detail. if ($objp->amount > 0) { $banklinestatic->fetch($links[$key]['url_id']); - $bankstatic->id=$banklinestatic->fk_account; - $bankstatic->label=$banklinestatic->bank_account_ref; + $bankstatic->id = $banklinestatic->fk_account; + $bankstatic->label = $banklinestatic->bank_account_ref; print ' ('.$langs->trans("TransferFrom").' '; print $bankstatic->getNomUrl(1, 'transactions'); print ' '.$langs->trans("toward").' '; - $bankstatic->id=$objp->bankid; - $bankstatic->label=$objp->bankref; + $bankstatic->id = $objp->bankid; + $bankstatic->label = $objp->bankref; print $bankstatic->getNomUrl(1, ''); print ')'; } else { - $bankstatic->id=$objp->bankid; - $bankstatic->label=$objp->bankref; + $bankstatic->id = $objp->bankid; + $bankstatic->label = $objp->bankref; print ' ('.$langs->trans("TransferFrom").' '; print $bankstatic->getNomUrl(1, ''); print ' '.$langs->trans("toward").' '; $banklinestatic->fetch($links[$key]['url_id']); - $bankstatic->id=$banklinestatic->fk_account; - $bankstatic->label=$banklinestatic->bank_account_ref; + $bankstatic->id = $banklinestatic->fk_account; + $bankstatic->label = $banklinestatic->bank_account_ref; print $bankstatic->getNomUrl(1, 'transactions'); print ')'; } //var_dump($links); } - elseif ($links[$key]['type']=='company') + elseif ($links[$key]['type'] == 'company') { } - elseif ($links[$key]['type']=='user') + elseif ($links[$key]['type'] == 'user') { } - elseif ($links[$key]['type']=='member') + elseif ($links[$key]['type'] == 'member') { } - elseif ($links[$key]['type']=='sc') + elseif ($links[$key]['type'] == 'sc') { } else { // Show link with label $links[$key]['label'] - if (! empty($objp->label) && ! empty($links[$key]['label'])) print ' - '; + if (!empty($objp->label) && !empty($links[$key]['label'])) print ' - '; print ''; if (preg_match('/^\((.*)\)$/i', $links[$key]['label'], $reg)) { // Label generique car entre parentheses. On l'affiche en le traduisant - if ($reg[1]=='paiement') $reg[1]='Payment'; + if ($reg[1] == 'paiement') $reg[1] = 'Payment'; print ' '.$langs->trans($reg[1]); } else @@ -1312,75 +1312,75 @@ if ($resql) } } print ''; print ''.dol_print_date($db->jdate($objp->do), "day").""; print ' '; print ''; print ''; - print img_edit_remove() . " "; + print img_edit_remove()." "; print ''; - print img_edit_add() .""; + print img_edit_add().""; print ''; print "'; print ''.dol_print_date($db->jdate($objp->dv), "day").""; print ' '; print ''; print ''; - print img_edit_remove() . " "; + print img_edit_remove()." "; print ''; - print img_edit_add() .""; + print img_edit_add().""; print ''; print "'; - $labeltype=($langs->trans("PaymentTypeShort".$objp->fk_type)!="PaymentTypeShort".$objp->fk_type)?$langs->trans("PaymentTypeShort".$objp->fk_type):$langs->getLabelFromKey($db, $objp->fk_type, 'c_paiement', 'code', 'libelle', '', 1); + $labeltype = ($langs->trans("PaymentTypeShort".$objp->fk_type) != "PaymentTypeShort".$objp->fk_type) ? $langs->trans("PaymentTypeShort".$objp->fk_type) : $langs->getLabelFromKey($db, $objp->fk_type, 'c_paiement', 'code', 'libelle', '', 1); if ($labeltype == 'SOLD') print ' '; //$langs->trans("InitialBankBalance"); else print $labeltype; print "'.($objp->num_chq?$objp->num_chq:"")."'.($objp->num_chq ? $objp->num_chq : "").""; if ($objp->url_id) { - $companystatic->id=$objp->url_id; - $companystatic->name=$objp->nom; - $companystatic->name_alias=$objp->name_alias; - $companystatic->client=$objp->client; - $companystatic->email=$objp->email; - $companystatic->fournisseur=$objp->fournisseur; - $companystatic->code_client=$objp->code_client; - $companystatic->code_fournisseur=$objp->code_fournisseur; - $companystatic->code_compta=$objp->code_compta; - $companystatic->code_compta_fournisseur=$objp->code_compta_fournisseur; + $companystatic->id = $objp->url_id; + $companystatic->name = $objp->nom; + $companystatic->name_alias = $objp->name_alias; + $companystatic->client = $objp->client; + $companystatic->email = $objp->email; + $companystatic->fournisseur = $objp->fournisseur; + $companystatic->code_client = $objp->code_client; + $companystatic->code_fournisseur = $objp->code_fournisseur; + $companystatic->code_compta = $objp->code_compta; + $companystatic->code_compta_fournisseur = $objp->code_compta_fournisseur; print $companystatic->getNomUrl(1); } else @@ -1388,20 +1388,20 @@ if ($resql) print ' '; } print ''; print $bankaccount->getNomUrl(1); print "'; if ($objp->amount < 0) @@ -1410,12 +1410,12 @@ if ($resql) $totalarray['totaldeb'] += $objp->amount; } print "'; if ($objp->amount > 0) @@ -1424,12 +1424,12 @@ if ($resql) $totalarray['totalcred'] += $objp->amount; } print "--'; // Transaction reconciliated or edit link @@ -1479,26 +1479,26 @@ if ($resql) { print ''.$objp->num_releve.''; } - if (! $objp->conciliated && $action == 'reconcile') + if (!$objp->conciliated && $action == 'reconcile') { if ($objp->num_releve) print ' '; - print 'rowid])?' checked':'').'>'; + print 'rowid]) ? ' checked' : '').'>'; } } print ''; - print $objp->conciliated?$langs->trans("Yes"):$langs->trans("No"); + print $objp->conciliated ? $langs->trans("Yes") : $langs->trans("No"); print ''; if ($massactionbutton || $massaction) // If we are in select mode (massactionbutton defined) or if we have already selected and sent an action ($massaction) defined { - $selected=0; - if (in_array($obj->rowid, $arrayofselected)) $selected=1; - print ''; + $selected = 0; + if (in_array($obj->rowid, $arrayofselected)) $selected = 1; + print ''; } print '
'; - if ($user->rights->banque->consolidate && $action == 'reconcile') print ''; + if ($user->rights->banque->consolidate && $action == 'reconcile') print ''; print '
'.$langs->trans("NoRecordFound").'
'.$langs->trans("NoRecordFound").'
"; diff --git a/htdocs/compta/bank/budget.php b/htdocs/compta/bank/budget.php index c9c5a0f77fe..967227f9e89 100644 --- a/htdocs/compta/bank/budget.php +++ b/htdocs/compta/bank/budget.php @@ -46,7 +46,7 @@ llxHeader(); // List movements bu category for bank transactions print load_fiche_titre($langs->trans("BankTransactionByCategories"), '', 'title_bank.png'); -print ''; +print '
'; print ""; print ''; print ''; diff --git a/htdocs/compta/bank/card.php b/htdocs/compta/bank/card.php index 702d3bbc113..7e14516e4cd 100644 --- a/htdocs/compta/bank/card.php +++ b/htdocs/compta/bank/card.php @@ -29,28 +29,28 @@ */ require '../../main.inc.php'; -require_once DOL_DOCUMENT_ROOT . '/core/lib/bank.lib.php'; -require_once DOL_DOCUMENT_ROOT . '/core/lib/company.lib.php'; -require_once DOL_DOCUMENT_ROOT . '/core/class/html.formcompany.class.php'; -require_once DOL_DOCUMENT_ROOT . '/core/class/html.formbank.class.php'; -require_once DOL_DOCUMENT_ROOT . '/compta/bank/class/account.class.php'; -require_once DOL_DOCUMENT_ROOT . '/core/class/extrafields.class.php'; -if (! empty($conf->categorie->enabled)) require_once DOL_DOCUMENT_ROOT . '/categories/class/categorie.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 . '/accountancy/class/accountingjournal.class.php'; +require_once DOL_DOCUMENT_ROOT.'/core/lib/bank.lib.php'; +require_once DOL_DOCUMENT_ROOT.'/core/lib/company.lib.php'; +require_once DOL_DOCUMENT_ROOT.'/core/class/html.formcompany.class.php'; +require_once DOL_DOCUMENT_ROOT.'/core/class/html.formbank.class.php'; +require_once DOL_DOCUMENT_ROOT.'/compta/bank/class/account.class.php'; +require_once DOL_DOCUMENT_ROOT.'/core/class/extrafields.class.php'; +if (!empty($conf->categorie->enabled)) require_once DOL_DOCUMENT_ROOT.'/categories/class/categorie.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.'/accountancy/class/accountingjournal.class.php'; // Load translation files required by the page -$langs->loadLangs(array("banks","bills","categories","companies","compta")); +$langs->loadLangs(array("banks", "bills", "categories", "companies", "compta")); $action = GETPOST('action', 'aZ09'); $cancel = GETPOST('cancel', 'alpha'); // Security check -$id = GETPOST("id", 'int') ? GETPOST("id", 'int'): GETPOST('ref', 'alpha'); +$id = GETPOST("id", 'int') ? GETPOST("id", 'int') : GETPOST('ref', 'alpha'); $fieldid = GETPOSTISSET("ref") ? 'ref' : 'rowid'; -$result=restrictedArea($user, 'banque', $id, 'bank_account&bank_account', '', '', $fieldid); +$result = restrictedArea($user, 'banque', $id, 'bank_account&bank_account', '', '', $fieldid); $object = new Account($db); $extrafields = new ExtraFields($db); @@ -59,17 +59,17 @@ $extrafields = new ExtraFields($db); $extrafields->fetch_name_optionals_label($object->table_element); // Initialize technical object to manage hooks of page. Note that conf->hooks_modules contains array of hook context -$hookmanager->initHooks(array('bankcard','globalcard')); +$hookmanager->initHooks(array('bankcard', 'globalcard')); /* * Actions */ -if ($cancel) $action=''; +if ($cancel) $action = ''; if ($action == 'add') { - $error=0; + $error = 0; $db->begin(); @@ -92,10 +92,10 @@ if ($action == 'add') $object->iban = trim($_POST["iban"]); $object->domiciliation = trim(GETPOST("domiciliation", "nohtml")); - $object->proprio = trim(GETPOST("proprio", 'alphanohtml')); + $object->proprio = trim(GETPOST("proprio", 'alphanohtml')); $object->owner_address = trim(GETPOST("owner_address", 'nohtml')); - $account_number = GETPOST('account_number', 'alphanohtml'); + $account_number = GETPOST('account_number', 'alphanohtml'); if (empty($account_number) || $account_number == '-1') { $object->account_number = ''; @@ -124,26 +124,26 @@ if ($action == 'add') if ($conf->global->MAIN_BANK_ACCOUNTANCY_CODE_ALWAYS_REQUIRED && empty($object->account_number)) { setEventMessages($langs->transnoentitiesnoconv("ErrorFieldRequired", $langs->transnoentitiesnoconv("AccountancyCode")), null, 'errors'); - $action='create'; // Force chargement page en mode creation + $action = 'create'; // Force chargement page en mode creation $error++; } if (empty($object->ref)) { setEventMessages($langs->transnoentitiesnoconv("ErrorFieldRequired", $langs->transnoentitiesnoconv("Ref")), null, 'errors'); - $action='create'; // Force chargement page en mode creation + $action = 'create'; // Force chargement page en mode creation $error++; } if (empty($object->label)) { setEventMessages($langs->transnoentitiesnoconv("ErrorFieldRequired", $langs->transnoentitiesnoconv("LabelBankCashAccount")), null, 'errors'); - $action='create'; // Force chargement page en mode creation + $action = 'create'; // Force chargement page en mode creation $error++; } // Fill array 'array_options' with data from add form $ret = $extrafields->setOptionalsFromPost(null, $object); - if (! $error) + if (!$error) { $id = $object->create($user); if ($id > 0) @@ -152,19 +152,19 @@ if ($action == 'add') $categories = GETPOST('categories', 'array'); $object->setCategories($categories); - $_GET["id"]=$id; // Force chargement page en mode visu + $_GET["id"] = $id; // Force chargement page en mode visu - $action=''; + $action = ''; } else { $error++; setEventMessages($object->error, $object->errors, 'errors'); - $action='create'; // Force chargement page en mode creation + $action = 'create'; // Force chargement page en mode creation } } - if (! $error) + if (!$error) { $db->commit(); } @@ -176,7 +176,7 @@ if ($action == 'add') if ($action == 'update') { - $error=0; + $error = 0; // Update account $object = new Account($db); @@ -198,10 +198,10 @@ if ($action == 'update') $object->iban = trim($_POST["iban"]); $object->domiciliation = trim(GETPOST("domiciliation", "nohtml")); - $object->proprio = trim(GETPOST("proprio", 'alphanohtml')); + $object->proprio = trim(GETPOST("proprio", 'alphanohtml')); $object->owner_address = trim(GETPOST("owner_address", 'nohtml')); - $account_number = GETPOST('account_number', 'alpha'); + $account_number = GETPOST('account_number', 'alpha'); if (empty($account_number) || $account_number == '-1') { $object->account_number = ''; @@ -225,31 +225,31 @@ if ($action == 'update') if ($conf->global->MAIN_BANK_ACCOUNTANCY_CODE_ALWAYS_REQUIRED && empty($object->account_number)) { setEventMessages($langs->transnoentitiesnoconv("ErrorFieldRequired", $langs->transnoentitiesnoconv("AccountancyCode")), null, 'errors'); - $action='edit'; // Force chargement page en mode creation + $action = 'edit'; // Force chargement page en mode creation $error++; } if (empty($object->ref)) { setEventMessages($langs->transnoentitiesnoconv("ErrorFieldRequired", $langs->transnoentitiesnoconv("Ref")), null, 'errors'); - $action='edit'; // Force chargement page en mode creation + $action = 'edit'; // Force chargement page en mode creation $error++; } if (empty($object->label)) { setEventMessages($langs->transnoentitiesnoconv("ErrorFieldRequired", $langs->transnoentitiesnoconv("LabelBankCashAccount")), null, 'errors'); - $action='edit'; // Force chargement page en mode creation + $action = 'edit'; // Force chargement page en mode creation $error++; } $db->begin(); - if (! $error) + if (!$error) { // Fill array 'array_options' with data from add form $ret = $extrafields->setOptionalsFromPost(null, $object); } - if (! $error) + if (!$error) { $result = $object->update($user); if ($result >= 0) @@ -258,17 +258,17 @@ if ($action == 'update') $categories = GETPOST('categories', 'array'); $object->setCategories($categories); - $_GET["id"]=$_POST["id"]; // Force chargement page en mode visu + $_GET["id"] = $_POST["id"]; // Force chargement page en mode visu } else { $error++; setEventMessages($object->error, $object->errors, 'errors'); - $action='edit'; // Force chargement page edition + $action = 'edit'; // Force chargement page edition } } - if (! $error) + if (!$error) { $db->commit(); } @@ -294,7 +294,7 @@ if ($action == 'confirm_delete' && $_POST["confirm"] == "yes" && $user->rights-> else { setEventMessages($object->error, $object->errors, 'errors'); - $action=''; + $action = ''; } } @@ -306,11 +306,11 @@ if ($action == 'confirm_delete' && $_POST["confirm"] == "yes" && $user->rights-> $form = new Form($db); $formbank = new FormBank($db); $formcompany = new FormCompany($db); -if (! empty($conf->accounting->enabled)) $formaccounting = new FormAccounting($db); +if (!empty($conf->accounting->enabled)) $formaccounting = new FormAccounting($db); -$countrynotdefined=$langs->trans("ErrorSetACountryFirst").' ('.$langs->trans("SeeAbove").')'; +$countrynotdefined = $langs->trans("ErrorSetACountryFirst").' ('.$langs->trans("SeeAbove").')'; -$title = $langs->trans("FinancialAccount") . " - " . $langs->trans("Card"); +$title = $langs->trans("FinancialAccount")." - ".$langs->trans("Card"); $helpurl = ""; llxHeader("", $title, $helpurl); @@ -319,7 +319,7 @@ llxHeader("", $title, $helpurl); if ($action == 'create') { - $object=new Account($db); + $object = new Account($db); print load_fiche_titre($langs->trans("NewFinancialAccount"), '', 'title_bank.png'); @@ -346,11 +346,11 @@ if ($action == 'create') dol_fiche_head(''); - print '
'.$langs->trans("Rubrique").''.$langs->trans("Nb").'
'; + print '
'; // Ref print ''; - print ''; + print ''; // Label print ''; @@ -359,15 +359,15 @@ if ($action == 'create') // Type print ''; print ''; // Currency print ''; print ''; @@ -375,17 +375,17 @@ if ($action == 'create') // Status print ''; print ''; // Country - $selectedcode=''; + $selectedcode = ''; if (isset($_POST["account_country_id"])) { - $selectedcode=$_POST["account_country_id"]?$_POST["account_country_id"]:$object->country_code; + $selectedcode = $_POST["account_country_id"] ? $_POST["account_country_id"] : $object->country_code; } - elseif (empty($selectedcode)) $selectedcode=$mysoc->country_code; - $object->country_code = getCountry($selectedcode, 2); // Force country code on account to have following field on bank fields matching country rules + elseif (empty($selectedcode)) $selectedcode = $mysoc->country_code; + $object->country_code = getCountry($selectedcode, 2); // Force country code on account to have following field on bank fields matching country rules print ''; print ''; // Other attributes - $parameters=array(); - $reshook=$hookmanager->executeHooks('formObjectOptions', $parameters, $object, $action); // Note that $action and $object may have been modified by hook + $parameters = array(); + $reshook = $hookmanager->executeHooks('formObjectOptions', $parameters, $object, $action); // Note that $action and $object may have been modified by hook print $hookmanager->resPrint; if (empty($reshook)) { - print $object->showOptionals($extrafields, 'edit'); + print $object->showOptionals($extrafields, 'edit', $parameters); } print '
'.$langs->trans("Ref").'ref).'" maxlength="12" autofocus>
ref).'" maxlength="12" autofocus>
'.$langs->trans("LabelBankCashAccount").'
'.$langs->trans("AccountType").''; - $formbank->selectTypeOfBankAccount(isset($_POST["type"])?$_POST["type"]: Account::TYPE_CURRENT, "type"); + $formbank->selectTypeOfBankAccount(isset($_POST["type"]) ? $_POST["type"] : Account::TYPE_CURRENT, "type"); print '
'.$langs->trans("Currency").''; - $selectedcode=$object->currency_code; - if (! $selectedcode) $selectedcode=$conf->currency; - print $form->selectCurrency((isset($_POST["account_currency_code"])?$_POST["account_currency_code"]:$selectedcode), 'account_currency_code'); + $selectedcode = $object->currency_code; + if (!$selectedcode) $selectedcode = $conf->currency; + print $form->selectCurrency((isset($_POST["account_currency_code"]) ? $_POST["account_currency_code"] : $selectedcode), 'account_currency_code'); //print $langs->trans("Currency".$conf->currency); //print ''; print '
'.$langs->trans("Status").''; - print $form->selectarray("clos", $object->status, (GETPOST("clos", 'int')!=''?GETPOST("clos", 'int'):$object->clos)); + print $form->selectarray("clos", $object->status, (GETPOST("clos", 'int') != '' ?GETPOST("clos", 'int') : $object->clos)); print '
'.$langs->trans("BankAccountCountry").''; @@ -397,7 +397,7 @@ if ($action == 'create') print '
'.$langs->trans('State').''; if ($selectedcode) { - $formcompany->select_departement(isset($_POST["account_state_id"])?$_POST["account_state_id"]:'', $selectedcode, 'account_state_id'); + $formcompany->select_departement(isset($_POST["account_state_id"]) ? $_POST["account_state_id"] : '', $selectedcode, 'account_state_id'); } else { @@ -420,7 +420,7 @@ if ($action == 'create') $cats = $c->containing($object->id, Categorie::TYPE_ACCOUNT); if (is_array($cats)) { - foreach($cats as $cat) { + foreach ($cats as $cat) { $arrayselected[] = $cat->id; } } @@ -433,28 +433,28 @@ if ($action == 'create') print ''; // Editor wysiwyg require_once DOL_DOCUMENT_ROOT.'/core/class/doleditor.class.php'; - $doleditor=new DolEditor('account_comment', (GETPOST("account_comment")?GETPOST("account_comment"):$object->comment), '', 90, 'dolibarr_notes', '', false, true, $conf->global->FCKEDITOR_ENABLE_SOCIETE, ROWS_4, '90%'); + $doleditor = new DolEditor('account_comment', (GETPOST("account_comment") ?GETPOST("account_comment") : $object->comment), '', 90, 'dolibarr_notes', '', false, true, $conf->global->FCKEDITOR_ENABLE_SOCIETE, ROWS_4, '90%'); $doleditor->Create(); print '
'; print '
'; - print ''; + print '
'; // Sold print ''; - print ''; + print ''; print ''; print ''; print ''; - print ''; + print ''; print ''; - print ''; + print ''; print '
'.$langs->trans("InitialBankBalance").'solde)).'">
solde)).'">
'.$langs->trans("Date").''; @@ -462,21 +462,21 @@ if ($action == 'create') print '
'.$langs->trans("BalanceMinimalAllowed").'min_allowed).'">
min_allowed).'">
'.$langs->trans("BalanceMinimalDesired").'min_desired).'">
min_desired).'">
'; print '
'; if ($_POST["type"] == Account::TYPE_SAVINGS || $_POST["type"] == Account::TYPE_CURRENT) { - print ''; + print '
'; // If bank account print ''; - print ''; + print ''; print ''; // Show fields of bank account @@ -500,44 +500,44 @@ if ($action == 'create') } print ''; - print ''; + print ''; print ''; } $ibankey = FormBank::getIBANLabel($object); - $bickey="BICNumber"; - if ($object->getCountryCode() == 'IN') $bickey="SWIFT"; + $bickey = "BICNumber"; + if ($object->getCountryCode() == 'IN') $bickey = "SWIFT"; // IBAN print ''; - print ''; + print ''; print ''; - print ''; + print ''; print '"; print ''; - print ''; print '"; print '
'.$langs->trans("BankName").'
'.$langs->trans($val).'
'.$langs->trans($ibankey).'
'.$langs->trans($bickey).'
'.$langs->trans("BankAccountDomiciliation").''; print "
'.$langs->trans("BankAccountOwner").''; + print ''; print '
'.$langs->trans("BankAccountOwnerAddress").''; print "
'; print '
'; } - print ''; + print '
'; // Accountancy code - $fieldrequired=''; - if (! empty($conf->global->MAIN_BANK_ACCOUNTANCY_CODE_ALWAYS_REQUIRED)) $fieldrequired='fieldrequired '; + $fieldrequired = ''; + if (!empty($conf->global->MAIN_BANK_ACCOUNTANCY_CODE_ALWAYS_REQUIRED)) $fieldrequired = 'fieldrequired '; - if (! empty($conf->accounting->enabled)) + if (!empty($conf->accounting->enabled)) { print ''; print ''; - print ''; + print ''; } // Accountancy journal - if (! empty($conf->accounting->enabled)) + if (!empty($conf->accounting->enabled)) { print ''; print ''; print ''; // Conciliate print ''; print ''; print ''; @@ -648,7 +648,7 @@ else // Accountancy code print ''; print ''; // Accountancy journal - if (! empty($conf->accounting->enabled)) + if (!empty($conf->accounting->enabled)) { print ''; print '
'.$langs->trans("AccountancyCode").''; @@ -547,11 +547,11 @@ if ($action == 'create') else { print '
'.$langs->trans("AccountancyCode").'account_number).'">
account_number).'">
'.$langs->trans("AccountancyJournal").''; @@ -564,9 +564,9 @@ if ($action == 'create') dol_fiche_end(); print '
'; - print ''; + print ''; print '     '; - print ''; + print ''; print '
'; print ''; @@ -588,11 +588,11 @@ else if ($_GET["ref"]) { $object->fetch(0, $_GET["ref"]); - $_GET["id"]=$object->id; + $_GET["id"] = $object->id; } // Show tabs - $head=bank_prepare_head($object); + $head = bank_prepare_head($object); dol_fiche_head($head, 'bankname', $langs->trans("FinancialAccount"), -1, 'account'); $formconfirm = ''; @@ -608,7 +608,7 @@ else $linkback = ''.$langs->trans("BackToList").''; - $morehtmlref=''; + $morehtmlref = ''; dol_banner_tab($object, 'ref', $linkback, 1, 'ref', 'ref', $morehtmlref); @@ -625,18 +625,18 @@ else // Currency print '
'.$langs->trans("Currency").''; - $selectedcode=$object->currency_code; - if (! $selectedcode) $selectedcode=$conf->currency; + $selectedcode = $object->currency_code; + if (!$selectedcode) $selectedcode = $conf->currency; print $langs->trans("Currency".$selectedcode); print '
'.$langs->trans("Conciliable").''; - $conciliate=$object->canBeConciliated(); + $conciliate = $object->canBeConciliated(); if ($conciliate == -2) print $langs->trans("No").' ('.$langs->trans("CashAccount").')'; elseif ($conciliate == -3) print $langs->trans("No").' ('.$langs->trans("Closed").')'; - else print ($object->rappro==1 ? $langs->trans("Yes") : ($langs->trans("No").' ('.$langs->trans("ConciliationDisabled").')')); + else print ($object->rappro == 1 ? $langs->trans("Yes") : ($langs->trans("No").' ('.$langs->trans("ConciliationDisabled").')')); print '
'.$langs->trans("BalanceMinimalAllowed").'
'.$langs->trans("AccountancyCode").''; - if (! empty($conf->accounting->enabled)) { + if (!empty($conf->accounting->enabled)) { $accountingaccount = new AccountingAccount($db); $accountingaccount->fetch('', $object->account_number, 1); @@ -659,7 +659,7 @@ else print '
'.$langs->trans("AccountancyJournal").''; @@ -675,7 +675,7 @@ else // Other attributes $cols = 2; - include DOL_DOCUMENT_ROOT . '/core/tpl/extrafields_view.tpl.php'; + include DOL_DOCUMENT_ROOT.'/core/tpl/extrafields_view.tpl.php'; print '
'; @@ -725,13 +725,13 @@ else } $ibankey = FormBank::getIBANLabel($object); - $bickey="BICNumber"; - if ($object->getCountryCode() == 'IN') $bickey="SWIFT"; + $bickey = "BICNumber"; + if ($object->getCountryCode() == 'IN') $bickey = "SWIFT"; print '
'.$langs->trans($ibankey).''.$object->iban.' '; - if (! empty($object->iban)) { - if (! checkIbanForAccount($object)) { + if (!empty($object->iban)) { + if (!checkIbanForAccount($object)) { print img_picto($langs->trans("IbanNotValid"), 'warning'); } else { print img_picto($langs->trans("IbanValid"), 'info'); @@ -741,8 +741,8 @@ else print '
'.$langs->trans($bickey).''.$object->bic.' '; - if (! empty($object->bic)) { - if (! checkSwiftForAccount($object)) { + if (!empty($object->bic)) { + if (!checkSwiftForAccount($object)) { print img_picto($langs->trans("SwiftNotValid"), 'warning'); } else { print img_picto($langs->trans("SwiftValid"), 'info'); @@ -783,7 +783,7 @@ else print 'id.'">'.$langs->trans("Modify").''; } - $canbedeleted=$object->can_be_deleted(); // Renvoi vrai si compte sans mouvements + $canbedeleted = $object->can_be_deleted(); // Renvoi vrai si compte sans mouvements if ($user->rights->banque->configurer && $canbedeleted) { print 'id.'">'.$langs->trans("Delete").''; @@ -833,20 +833,20 @@ else //print '
'; - print ''; + print '
'; // Ref print ''; - print ''; + print ''; // Label print ''; - print ''; + print ''; // Type print ''; print ''; // Currency @@ -854,9 +854,9 @@ else print ''; print ''; print ''; @@ -864,15 +864,15 @@ else // Status print ''; print ''; // Country - $object->country_id=$object->country_id?$object->country_id:$mysoc->country_id; - $selectedcode=$object->country_code; - if (isset($_POST["account_country_id"])) $selectedcode=$_POST["account_country_id"]; - elseif (empty($selectedcode)) $selectedcode=$mysoc->country_code; - $object->country_code = getCountry($selectedcode, 2); // Force country code on account to have following field on bank fields matching country rules + $object->country_id = $object->country_id ? $object->country_id : $mysoc->country_id; + $selectedcode = $object->country_code; + if (isset($_POST["account_country_id"])) $selectedcode = $_POST["account_country_id"]; + elseif (empty($selectedcode)) $selectedcode = $mysoc->country_code; + $object->country_code = getCountry($selectedcode, 2); // Force country code on account to have following field on bank fields matching country rules print ''; print ''; print ''; // Balance print ''; - print ''; + print ''; print ''; - print ''; + print ''; // Web print ''; - print ''; // Tags-Categories @@ -920,8 +920,11 @@ else $cate_arbo = $form->select_all_categories(Categorie::TYPE_ACCOUNT, '', 'parent', 64, 0, 1); $c = new Categorie($db); $cats = $c->containing($object->id, Categorie::TYPE_ACCOUNT); - foreach($cats as $cat) { - $arrayselected[] = $cat->id; + if (is_array($cats)) + { + foreach($cats as $cat) { + $arrayselected[] = $cat->id; + } } print $form->multiselectarray('categories', $cate_arbo, $arrayselected, '', 0, '', 0, '100%'); print ""; @@ -932,17 +935,17 @@ else print ''; // Other attributes - $parameters=array(); - $reshook=$hookmanager->executeHooks('formObjectOptions', $parameters, $object, $action); // Note that $action and $object may have been modified by hook + $parameters = array(); + $reshook = $hookmanager->executeHooks('formObjectOptions', $parameters, $object, $action); // Note that $action and $object may have been modified by hook print $hookmanager->resPrint; if (empty($reshook)) { - print $object->showOptionals($extrafields, 'edit'); + print $object->showOptionals($extrafields, 'edit', $parameters); } print '
'.$langs->trans("Ref").'ref).'">
ref).'">
'.$langs->trans("Label").'label).'">
label).'">
'.$langs->trans("AccountType").''; - $formbank->selectTypeOfBankAccount((isset($_POST["type"])?$_POST["type"]:$object->type), "type"); + $formbank->selectTypeOfBankAccount((isset($_POST["type"]) ? $_POST["type"] : $object->type), "type"); print '
'; - $selectedcode=$object->currency_code; - if (! $selectedcode) $selectedcode=$conf->currency; - print $form->selectCurrency((isset($_POST["account_currency_code"])?$_POST["account_currency_code"]:$selectedcode), 'account_currency_code'); + $selectedcode = $object->currency_code; + if (!$selectedcode) $selectedcode = $conf->currency; + print $form->selectCurrency((isset($_POST["account_currency_code"]) ? $_POST["account_currency_code"] : $selectedcode), 'account_currency_code'); //print $langs->trans("Currency".$conf->currency); //print ''; print '
'.$langs->trans("Status").''; - print $form->selectarray("clos", $object->status, (isset($_POST["clos"])?$_POST["clos"]:$object->clos)); + print $form->selectarray("clos", $object->status, (isset($_POST["clos"]) ? $_POST["clos"] : $object->clos)); print '
'.$langs->trans("Country").''; @@ -884,7 +884,7 @@ else print '
'.$langs->trans('State').''; if ($selectedcode) { - print $formcompany->select_state(isset($_POST["account_state_id"])?$_POST["account_state_id"]:$object->state_id, $selectedcode, 'account_state_id'); + print $formcompany->select_state(isset($_POST["account_state_id"]) ? $_POST["account_state_id"] : $object->state_id, $selectedcode, 'account_state_id'); } else { @@ -895,22 +895,22 @@ else // Conciliable print '
'.$langs->trans("Conciliable").''; - $conciliate=$object->canBeConciliated(); + $conciliate = $object->canBeConciliated(); if ($conciliate == -2) print $langs->trans("No").' ('.$langs->trans("CashAccount").')'; elseif ($conciliate == -3) print $langs->trans("No").' ('.$langs->trans("Closed").')'; - else print ' 0)?'':' checked="checked"').'"> '.$langs->trans("DisableConciliation"); + else print ' 0) ? '' : ' checked="checked"').'"> '.$langs->trans("DisableConciliation"); print '
'.$langs->trans("BalanceMinimalAllowed").'min_allowed).'">
min_allowed).'">
'.$langs->trans("BalanceMinimalDesired").'min_desired).'">
min_desired).'">
'.$langs->trans("Web").'url).'">'; + print 'url).'">'; print '
'; // Editor wysiwyg require_once DOL_DOCUMENT_ROOT.'/core/class/doleditor.class.php'; - $doleditor=new DolEditor('account_comment', (GETPOST("account_comment")?GETPOST("account_comment"):$object->comment), '', 90, 'dolibarr_notes', '', false, true, $conf->global->FCKEDITOR_ENABLE_SOCIETE, ROWS_4, '95%'); + $doleditor = new DolEditor('account_comment', (GETPOST("account_comment") ?GETPOST("account_comment") : $object->comment), '', 90, 'dolibarr_notes', '', false, true, $conf->global->FCKEDITOR_ENABLE_SOCIETE, ROWS_4, '95%'); $doleditor->Create(); print '
'; @@ -951,7 +954,7 @@ else //print '
'; - print ''; + print '
'; // Accountancy code $tdextra = ' class="titlefieldcreate"'; @@ -970,7 +973,7 @@ else print ''; // Accountancy journal - if (! empty($conf->accounting->enabled)) + if (!empty($conf->accounting->enabled)) { print ''; print '
'.$langs->trans("AccountancyJournal").''; @@ -986,7 +989,7 @@ else //print '
'; - print ''; + print '
'; // If bank account print ''; @@ -1019,8 +1022,8 @@ else } $ibankey = FormBank::getIBANLabel($object); - $bickey="BICNumber"; - if ($object->getCountryCode() == 'IN') $bickey="SWIFT"; + $bickey = "BICNumber"; + if ($object->getCountryCode() == 'IN') $bickey = "SWIFT"; // IBAN print ''; diff --git a/htdocs/compta/bank/categ.php b/htdocs/compta/bank/categ.php index 683f04bc84c..a343d09ddc2 100644 --- a/htdocs/compta/bank/categ.php +++ b/htdocs/compta/bank/categ.php @@ -33,8 +33,8 @@ require_once DOL_DOCUMENT_ROOT.'/compta/bank/class/bankcateg.class.php'; // Load translation files required by the page $langs->loadLangs(array('banks', 'categories')); -$action=GETPOST('action', 'aZ09'); -$optioncss = GETPOST('optioncss', 'aZ'); // Option for the css output (always '' except when 'print') +$action = GETPOST('action', 'aZ09'); +$optioncss = GETPOST('optioncss', 'aZ'); // Option for the css output (always '' except when 'print') if (!$user->rights->banque->configurer) accessforbidden(); @@ -92,8 +92,8 @@ print ''; print ''; */ -print '
'; // You can use div-table-responsive-no-min if you dont need reserved height for your table -print '
'.$langs->trans("BankName").'
'.$langs->trans($ibankey).'
'; +print '
'; // You can use div-table-responsive-no-min if you dont need reserved height for your table +print '
'; print ''; print ''; print "\n"; @@ -109,9 +109,9 @@ if ($action != 'edit') $sql = "SELECT rowid, label"; -$sql.= " FROM ".MAIN_DB_PREFIX."bank_categ"; -$sql.= " WHERE entity = ".$conf->entity; -$sql.= " ORDER BY label"; +$sql .= " FROM ".MAIN_DB_PREFIX."bank_categ"; +$sql .= " WHERE entity = ".$conf->entity; +$sql .= " ORDER BY label"; $result = $db->query($sql); if ($result) @@ -125,7 +125,7 @@ if ($result) print ''; print ''; - if (GETPOST('action', 'aZ09') == 'edit' && GETPOST("categid")== $objp->rowid) + if (GETPOST('action', 'aZ09') == 'edit' && GETPOST("categid") == $objp->rowid) { print "
'.$langs->trans("Ref").''.$langs->trans("Label").'
'.$objp->rowid.'"; print ''; diff --git a/htdocs/compta/bank/class/account.class.php b/htdocs/compta/bank/class/account.class.php index 57cff121010..ec29e4e5240 100644 --- a/htdocs/compta/bank/class/account.class.php +++ b/htdocs/compta/bank/class/account.class.php @@ -28,7 +28,7 @@ * \ingroup bank * \brief File of class to manage bank accounts */ -require_once DOL_DOCUMENT_ROOT .'/core/class/commonobject.class.php'; +require_once DOL_DOCUMENT_ROOT.'/core/class/commonobject.class.php'; /** @@ -92,7 +92,7 @@ class Account extends CommonObject * Does it need to be conciliated? * @var int */ - public $rappro=1; + public $rappro = 1; /** * Webpage @@ -315,18 +315,18 @@ class Account extends CommonObject { // phpcs:enable $sql = "INSERT INTO ".MAIN_DB_PREFIX."bank_url ("; - $sql.= "fk_bank"; - $sql.= ", url_id"; - $sql.= ", url"; - $sql.= ", label"; - $sql.= ", type"; - $sql.= ") VALUES ("; - $sql.= "'".$line_id."'"; - $sql.= ", '".$url_id."'"; - $sql.= ", '".$url."'"; - $sql.= ", '".$this->db->escape($label)."'"; - $sql.= ", '".$type."'"; - $sql.= ")"; + $sql .= "fk_bank"; + $sql .= ", url_id"; + $sql .= ", url"; + $sql .= ", label"; + $sql .= ", type"; + $sql .= ") VALUES ("; + $sql .= "'".$line_id."'"; + $sql .= ", '".$url_id."'"; + $sql .= ", '".$url."'"; + $sql .= ", '".$this->db->escape($label)."'"; + $sql .= ", '".$type."'"; + $sql .= ")"; dol_syslog(get_class($this)."::add_url_line", LOG_DEBUG); if ($this->db->query($sql)) @@ -336,7 +336,7 @@ class Account extends CommonObject } else { - $this->error=$this->db->lasterror(); + $this->error = $this->db->lasterror(); return -1; } } @@ -357,20 +357,20 @@ class Account extends CommonObject $lines = array(); // Check parameters - if (! empty($fk_bank) && (! empty($url_id) || ! empty($type))) + if (!empty($fk_bank) && (!empty($url_id) || !empty($type))) { - $this->error="ErrorBadParameter"; + $this->error = "ErrorBadParameter"; return -1; } $sql = "SELECT fk_bank, url_id, url, label, type"; - $sql.= " FROM ".MAIN_DB_PREFIX."bank_url"; + $sql .= " FROM ".MAIN_DB_PREFIX."bank_url"; if ($fk_bank > 0) { - $sql.= " WHERE fk_bank = ".$fk_bank; + $sql .= " WHERE fk_bank = ".$fk_bank; } - else { $sql.= " WHERE url_id = ".$url_id." AND type = '".$type."'"; + else { $sql .= " WHERE url_id = ".$url_id." AND type = '".$type."'"; } - $sql.= " ORDER BY type, label"; + $sql .= " ORDER BY type, label"; dol_syslog(get_class($this)."::get_url", LOG_DEBUG); $result = $this->db->query($sql); @@ -420,25 +420,25 @@ class Account extends CommonObject { // Deprecation warning if (is_numeric($oper)) { - dol_syslog(__METHOD__ . ": using numeric operations is deprecated", LOG_WARNING); + dol_syslog(__METHOD__.": using numeric operations is deprecated", LOG_WARNING); } // Clean parameters - $emetteur=trim($emetteur); - $banque=trim($banque); + $emetteur = trim($emetteur); + $banque = trim($banque); - $now=dol_now(); + $now = dol_now(); if (is_numeric($oper)) // Clean operation to have a code instead of a rowid { $sql = "SELECT code FROM ".MAIN_DB_PREFIX."c_paiement"; - $sql.= " WHERE id=".$oper; - $sql.= " AND entity IN (".getEntity('c_paiement').")"; - $resql=$this->db->query($sql); + $sql .= " WHERE id=".$oper; + $sql .= " AND entity IN (".getEntity('c_paiement').")"; + $resql = $this->db->query($sql); if ($resql) { - $obj=$this->db->fetch_object($resql); - $oper=$obj->code; + $obj = $this->db->fetch_object($resql); + $oper = $obj->code; } else { @@ -448,19 +448,19 @@ class Account extends CommonObject } // Check parameters - if (! $oper) + if (!$oper) { - $this->error="oper not defined"; + $this->error = "oper not defined"; return -1; } - if (! $this->rowid) + if (!$this->rowid) { - $this->error="this->rowid not defined"; + $this->error = "this->rowid not defined"; return -2; } if ($this->courant == Account::TYPE_CASH && $oper != 'LIQ') { - $this->error="ErrorCashAccountAcceptsOnlyCashMoney"; + $this->error = "ErrorCashAccountAcceptsOnlyCashMoney"; return -3; } @@ -492,7 +492,7 @@ class Account extends CommonObject } if ($accline->insert() > 0) { - if ($categorie>0) { + if ($categorie > 0) { $sql = "INSERT INTO ".MAIN_DB_PREFIX."bank_class ("; $sql .= "lineid, fk_categ"; $sql .= ") VALUES ("; @@ -525,32 +525,32 @@ class Account extends CommonObject */ public function create(User $user, $notrigger = 0) { - global $langs,$conf, $hookmanager; + global $langs, $conf, $hookmanager; - $error=0; + $error = 0; // Clean parameters - if (! $this->min_allowed) $this->min_allowed=0; - if (! $this->min_desired) $this->min_desired=0; - $this->state_id = ($this->state_id?$this->state_id:$this->state_id); - $this->country_id = ($this->country_id?$this->country_id:$this->country_id); + if (!$this->min_allowed) $this->min_allowed = 0; + if (!$this->min_desired) $this->min_desired = 0; + $this->state_id = ($this->state_id ? $this->state_id : $this->state_id); + $this->country_id = ($this->country_id ? $this->country_id : $this->country_id); // Check parameters if (empty($this->country_id)) { - $this->error=$langs->transnoentitiesnoconv("ErrorFieldRequired", $langs->transnoentitiesnoconv("Country")); + $this->error = $langs->transnoentitiesnoconv("ErrorFieldRequired", $langs->transnoentitiesnoconv("Country")); dol_syslog(get_class($this)."::create ".$this->error, LOG_ERR); return -1; } if (empty($this->ref)) { - $this->error=$langs->transnoentitiesnoconv("ErrorFieldRequired", $langs->transnoentitiesnoconv("Ref")); + $this->error = $langs->transnoentitiesnoconv("ErrorFieldRequired", $langs->transnoentitiesnoconv("Ref")); dol_syslog(get_class($this)."::create ".$this->error, LOG_ERR); return -1; } if (empty($this->date_solde)) { - $this->error=$langs->transnoentitiesnoconv("ErrorFieldRequired", $langs->transnoentitiesnoconv("DateInitialBalance")); + $this->error = $langs->transnoentitiesnoconv("ErrorFieldRequired", $langs->transnoentitiesnoconv("DateInitialBalance")); dol_syslog(get_class($this)."::create ".$this->error, LOG_ERR); return -1; } @@ -558,67 +558,67 @@ class Account extends CommonObject // Chargement librairie pour acces fonction controle RIB require_once DOL_DOCUMENT_ROOT.'/core/lib/bank.lib.php'; - $now=dol_now(); + $now = dol_now(); $this->db->begin(); $sql = "INSERT INTO ".MAIN_DB_PREFIX."bank_account ("; - $sql.= "datec"; - $sql.= ", ref"; - $sql.= ", label"; - $sql.= ", entity"; - $sql.= ", account_number"; - $sql.= ", fk_accountancy_journal"; - $sql.= ", bank"; - $sql.= ", code_banque"; - $sql.= ", code_guichet"; - $sql.= ", number"; - $sql.= ", cle_rib"; - $sql.= ", bic"; - $sql.= ", iban_prefix"; - $sql.= ", domiciliation"; - $sql.= ", proprio"; - $sql.= ", owner_address"; - $sql.= ", currency_code"; - $sql.= ", rappro"; - $sql.= ", min_allowed"; - $sql.= ", min_desired"; - $sql.= ", comment"; - $sql.= ", state_id"; - $sql.= ", fk_pays"; - $sql.= ") VALUES ("; - $sql.= "'".$this->db->idate($now)."'"; - $sql.= ", '".$this->db->escape($this->ref)."'"; - $sql.= ", '".$this->db->escape($this->label)."'"; - $sql.= ", ".$conf->entity; - $sql.= ", '".$this->db->escape($this->account_number)."'"; - $sql.= ", ".($this->fk_accountancy_journal > 0 ? $this->db->escape($this->fk_accountancy_journal) : "null"); - $sql.= ", '".$this->db->escape($this->bank)."'"; - $sql.= ", '".$this->db->escape($this->code_banque)."'"; - $sql.= ", '".$this->db->escape($this->code_guichet)."'"; - $sql.= ", '".$this->db->escape($this->number)."'"; - $sql.= ", '".$this->db->escape($this->cle_rib)."'"; - $sql.= ", '".$this->db->escape($this->bic)."'"; - $sql.= ", '".$this->db->escape($this->iban)."'"; - $sql.= ", '".$this->db->escape($this->domiciliation)."'"; - $sql.= ", '".$this->db->escape($this->proprio)."'"; - $sql.= ", '".$this->db->escape($this->owner_address)."'"; - $sql.= ", '".$this->db->escape($this->currency_code)."'"; - $sql.= ", ".$this->rappro; - $sql.= ", ".price2num($this->min_allowed); - $sql.= ", ".price2num($this->min_desired); - $sql.= ", '".$this->db->escape($this->comment)."'"; - $sql.= ", ".($this->state_id>0?$this->state_id:"null"); - $sql.= ", ".$this->country_id; - $sql.= ")"; + $sql .= "datec"; + $sql .= ", ref"; + $sql .= ", label"; + $sql .= ", entity"; + $sql .= ", account_number"; + $sql .= ", fk_accountancy_journal"; + $sql .= ", bank"; + $sql .= ", code_banque"; + $sql .= ", code_guichet"; + $sql .= ", number"; + $sql .= ", cle_rib"; + $sql .= ", bic"; + $sql .= ", iban_prefix"; + $sql .= ", domiciliation"; + $sql .= ", proprio"; + $sql .= ", owner_address"; + $sql .= ", currency_code"; + $sql .= ", rappro"; + $sql .= ", min_allowed"; + $sql .= ", min_desired"; + $sql .= ", comment"; + $sql .= ", state_id"; + $sql .= ", fk_pays"; + $sql .= ") VALUES ("; + $sql .= "'".$this->db->idate($now)."'"; + $sql .= ", '".$this->db->escape($this->ref)."'"; + $sql .= ", '".$this->db->escape($this->label)."'"; + $sql .= ", ".$conf->entity; + $sql .= ", '".$this->db->escape($this->account_number)."'"; + $sql .= ", ".($this->fk_accountancy_journal > 0 ? $this->db->escape($this->fk_accountancy_journal) : "null"); + $sql .= ", '".$this->db->escape($this->bank)."'"; + $sql .= ", '".$this->db->escape($this->code_banque)."'"; + $sql .= ", '".$this->db->escape($this->code_guichet)."'"; + $sql .= ", '".$this->db->escape($this->number)."'"; + $sql .= ", '".$this->db->escape($this->cle_rib)."'"; + $sql .= ", '".$this->db->escape($this->bic)."'"; + $sql .= ", '".$this->db->escape($this->iban)."'"; + $sql .= ", '".$this->db->escape($this->domiciliation)."'"; + $sql .= ", '".$this->db->escape($this->proprio)."'"; + $sql .= ", '".$this->db->escape($this->owner_address)."'"; + $sql .= ", '".$this->db->escape($this->currency_code)."'"; + $sql .= ", ".$this->rappro; + $sql .= ", ".price2num($this->min_allowed); + $sql .= ", ".price2num($this->min_desired); + $sql .= ", '".$this->db->escape($this->comment)."'"; + $sql .= ", ".($this->state_id > 0 ? $this->state_id : "null"); + $sql .= ", ".$this->country_id; + $sql .= ")"; dol_syslog(get_class($this)."::create", LOG_DEBUG); - $resql=$this->db->query($sql); + $resql = $this->db->query($sql); if ($resql) { $this->id = $this->db->last_insert_id(MAIN_DB_PREFIX."bank_account"); - $result=$this->update($user, 1); + $result = $this->update($user, 1); if ($result > 0) { $accline = new AccountLine($this->db); @@ -637,16 +637,16 @@ class Account extends CommonObject $this->errors = $accline->errors; } - if (! $error) + if (!$error) { - $result=$this->insertExtraFields(); + $result = $this->insertExtraFields(); if ($result < 0) $error++; } - if (! $error && ! $notrigger) + if (!$error && !$notrigger) { // Call trigger - $result=$this->call_trigger('BANKACCOUNT_CREATE', $user); + $result = $this->call_trigger('BANKACCOUNT_CREATE', $user); if ($result < 0) $error++; // End call triggers } @@ -660,16 +660,16 @@ class Account extends CommonObject { if ($this->db->errno() == 'DB_ERROR_RECORD_ALREADY_EXISTS') { - $this->error=$langs->trans("ErrorBankLabelAlreadyExists"); + $this->error = $langs->trans("ErrorBankLabelAlreadyExists"); $error++; } else { - $this->error=$this->db->error()." sql=".$sql; + $this->error = $this->db->error()." sql=".$sql; $error++; } } - if (! $error) + if (!$error) { $this->db->commit(); return $this->id; @@ -677,7 +677,7 @@ class Account extends CommonObject else { $this->db->rollback(); - return -1*$error; + return -1 * $error; } } @@ -690,63 +690,63 @@ class Account extends CommonObject */ public function update(User $user, $notrigger = 0) { - global $langs,$conf, $hookmanager; + global $langs, $conf, $hookmanager; - $error=0; + $error = 0; $this->db->begin(); // Clean parameters - $this->state_id = ($this->state_id?$this->state_id:$this->state_id); - $this->country_id = ($this->country_id?$this->country_id:$this->country_id); + $this->state_id = ($this->state_id ? $this->state_id : $this->state_id); + $this->country_id = ($this->country_id ? $this->country_id : $this->country_id); // Check parameters if (empty($this->country_id)) { - $this->error=$langs->transnoentitiesnoconv("ErrorFieldRequired", $langs->transnoentitiesnoconv("Country")); + $this->error = $langs->transnoentitiesnoconv("ErrorFieldRequired", $langs->transnoentitiesnoconv("Country")); dol_syslog(get_class($this)."::update ".$this->error, LOG_ERR); return -1; } if (empty($this->ref)) { - $this->error=$langs->transnoentitiesnoconv("ErrorFieldRequired", $langs->transnoentitiesnoconv("Ref")); + $this->error = $langs->transnoentitiesnoconv("ErrorFieldRequired", $langs->transnoentitiesnoconv("Ref")); dol_syslog(get_class($this)."::update ".$this->error, LOG_ERR); return -1; } - if (! $this->label) $this->label = "???"; + if (!$this->label) $this->label = "???"; $sql = "UPDATE ".MAIN_DB_PREFIX."bank_account SET "; - $sql.= " ref = '".$this->db->escape($this->ref)."'"; - $sql.= ",label = '".$this->db->escape($this->label)."'"; + $sql .= " ref = '".$this->db->escape($this->ref)."'"; + $sql .= ",label = '".$this->db->escape($this->label)."'"; - $sql.= ",courant = ".$this->courant; - $sql.= ",clos = ".$this->clos; - $sql.= ",rappro = ".$this->rappro; - $sql.= ",url = ".($this->url?"'".$this->db->escape($this->url)."'":"null"); - $sql.= ",account_number = '".$this->db->escape($this->account_number)."'"; - $sql.= ",fk_accountancy_journal = ".($this->fk_accountancy_journal > 0 ? $this->db->escape($this->fk_accountancy_journal) : "null"); - $sql.= ",bank = '".$this->db->escape($this->bank)."'"; - $sql.= ",code_banque='".$this->db->escape($this->code_banque)."'"; - $sql.= ",code_guichet='".$this->db->escape($this->code_guichet)."'"; - $sql.= ",number='".$this->db->escape($this->number)."'"; - $sql.= ",cle_rib='".$this->db->escape($this->cle_rib)."'"; - $sql.= ",bic='".$this->db->escape($this->bic)."'"; - $sql.= ",iban_prefix = '".$this->db->escape($this->iban)."'"; - $sql.= ",domiciliation='".$this->db->escape($this->domiciliation)."'"; - $sql.= ",proprio = '".$this->db->escape($this->proprio)."'"; - $sql.= ",owner_address = '".$this->db->escape($this->owner_address)."'"; + $sql .= ",courant = ".$this->courant; + $sql .= ",clos = ".$this->clos; + $sql .= ",rappro = ".$this->rappro; + $sql .= ",url = ".($this->url ? "'".$this->db->escape($this->url)."'" : "null"); + $sql .= ",account_number = '".$this->db->escape($this->account_number)."'"; + $sql .= ",fk_accountancy_journal = ".($this->fk_accountancy_journal > 0 ? $this->db->escape($this->fk_accountancy_journal) : "null"); + $sql .= ",bank = '".$this->db->escape($this->bank)."'"; + $sql .= ",code_banque='".$this->db->escape($this->code_banque)."'"; + $sql .= ",code_guichet='".$this->db->escape($this->code_guichet)."'"; + $sql .= ",number='".$this->db->escape($this->number)."'"; + $sql .= ",cle_rib='".$this->db->escape($this->cle_rib)."'"; + $sql .= ",bic='".$this->db->escape($this->bic)."'"; + $sql .= ",iban_prefix = '".$this->db->escape($this->iban)."'"; + $sql .= ",domiciliation='".$this->db->escape($this->domiciliation)."'"; + $sql .= ",proprio = '".$this->db->escape($this->proprio)."'"; + $sql .= ",owner_address = '".$this->db->escape($this->owner_address)."'"; - $sql.= ",currency_code = '".$this->db->escape($this->currency_code)."'"; + $sql .= ",currency_code = '".$this->db->escape($this->currency_code)."'"; - $sql.= ",min_allowed = ".($this->min_allowed != '' ? price2num($this->min_allowed) : "null"); - $sql.= ",min_desired = ".($this->min_desired != '' ? price2num($this->min_desired) : "null"); - $sql.= ",comment = '".$this->db->escape($this->comment)."'"; + $sql .= ",min_allowed = ".($this->min_allowed != '' ? price2num($this->min_allowed) : "null"); + $sql .= ",min_desired = ".($this->min_desired != '' ? price2num($this->min_desired) : "null"); + $sql .= ",comment = '".$this->db->escape($this->comment)."'"; - $sql.= ",state_id = ".($this->state_id>0?$this->state_id:"null"); - $sql.= ",fk_pays = ".$this->country_id; + $sql .= ",state_id = ".($this->state_id > 0 ? $this->state_id : "null"); + $sql .= ",fk_pays = ".$this->country_id; - $sql.= " WHERE rowid = ".$this->id; + $sql .= " WHERE rowid = ".$this->id; dol_syslog(get_class($this)."::update", LOG_DEBUG); $result = $this->db->query($sql); @@ -755,17 +755,17 @@ class Account extends CommonObject // Actions on extra fields (by external module or standard code) if (empty($conf->global->MAIN_EXTRAFIELDS_DISABLED)) // For avoid conflicts if trigger used { - if (! $error) + if (!$error) { - $result=$this->insertExtraFields(); + $result = $this->insertExtraFields(); if ($result < 0) $error++; } } - if (! $error && ! $notrigger) + if (!$error && !$notrigger) { // Call trigger - $result=$this->call_trigger('BANKACCOUNT_UPDATE', $user); + $result = $this->call_trigger('BANKACCOUNT_UPDATE', $user); if ($result < 0) $error++; // End call triggers } @@ -773,11 +773,11 @@ class Account extends CommonObject else { $error++; - $this->error=$this->db->lasterror(); + $this->error = $this->db->lasterror(); dol_print_error($this->db); } - if (! $error) + if (!$error) { $this->db->commit(); return $this->id; @@ -785,7 +785,7 @@ class Account extends CommonObject else { $this->db->rollback(); - return -1*$error; + return -1 * $error; } } @@ -800,11 +800,11 @@ class Account extends CommonObject public function update_bban(User $user = null) { // phpcs:enable - global $conf,$langs; + global $conf, $langs; // Clean parameters - $this->state_id = ($this->state_id?$this->state_id:$this->state_id); - $this->country_id = ($this->country_id?$this->country_id:$this->country_id); + $this->state_id = ($this->state_id ? $this->state_id : $this->state_id); + $this->country_id = ($this->country_id ? $this->country_id : $this->country_id); // Chargement librairie pour acces fonction controle RIB require_once DOL_DOCUMENT_ROOT.'/core/lib/bank.lib.php'; @@ -812,27 +812,27 @@ class Account extends CommonObject dol_syslog(get_class($this)."::update_bban $this->code_banque,$this->code_guichet,$this->number,$this->cle_rib,$this->iban"); // Check parameters - if (! $this->ref) + if (!$this->ref) { - $this->error=$langs->transnoentitiesnoconv("ErrorFieldRequired", $langs->trans("Ref")); + $this->error = $langs->transnoentitiesnoconv("ErrorFieldRequired", $langs->trans("Ref")); return -2; } $sql = "UPDATE ".MAIN_DB_PREFIX."bank_account SET "; - $sql.= " bank = '".$this->db->escape($this->bank)."'"; - $sql.= ",code_banque='".$this->db->escape($this->code_banque)."'"; - $sql.= ",code_guichet='".$this->db->escape($this->code_guichet)."'"; - $sql.= ",number='".$this->db->escape($this->number)."'"; - $sql.= ",cle_rib='".$this->db->escape($this->cle_rib)."'"; - $sql.= ",bic='".$this->db->escape($this->bic)."'"; - $sql.= ",iban_prefix = '".$this->db->escape($this->iban)."'"; - $sql.= ",domiciliation='".$this->db->escape($this->domiciliation)."'"; - $sql.= ",proprio = '".$this->db->escape($this->proprio)."'"; - $sql.= ",owner_address = '".$this->db->escape($this->owner_address)."'"; - $sql.= ",state_id = ".($this->state_id>0?$this->state_id:"null"); - $sql.= ",fk_pays = ".$this->country_id; - $sql.= " WHERE rowid = ".$this->id; - $sql.= " AND entity = ".$conf->entity; + $sql .= " bank = '".$this->db->escape($this->bank)."'"; + $sql .= ",code_banque='".$this->db->escape($this->code_banque)."'"; + $sql .= ",code_guichet='".$this->db->escape($this->code_guichet)."'"; + $sql .= ",number='".$this->db->escape($this->number)."'"; + $sql .= ",cle_rib='".$this->db->escape($this->cle_rib)."'"; + $sql .= ",bic='".$this->db->escape($this->bic)."'"; + $sql .= ",iban_prefix = '".$this->db->escape($this->iban)."'"; + $sql .= ",domiciliation='".$this->db->escape($this->domiciliation)."'"; + $sql .= ",proprio = '".$this->db->escape($this->proprio)."'"; + $sql .= ",owner_address = '".$this->db->escape($this->owner_address)."'"; + $sql .= ",state_id = ".($this->state_id > 0 ? $this->state_id : "null"); + $sql .= ",fk_pays = ".$this->country_id; + $sql .= " WHERE rowid = ".$this->id; + $sql .= " AND entity = ".$conf->entity; dol_syslog(get_class($this)."::update_bban", LOG_DEBUG); @@ -843,7 +843,7 @@ class Account extends CommonObject } else { - $this->error=$this->db->lasterror(); + $this->error = $this->db->lasterror(); dol_print_error($this->db); return -1; } @@ -863,26 +863,26 @@ class Account extends CommonObject if (empty($id) && empty($ref)) { - $this->error="ErrorBadParameters"; + $this->error = "ErrorBadParameters"; return -1; } $sql = "SELECT ba.rowid, ba.ref, ba.label, ba.bank, ba.number, ba.courant, ba.clos, ba.rappro, ba.url,"; - $sql.= " ba.code_banque, ba.code_guichet, ba.cle_rib, ba.bic, ba.iban_prefix as iban,"; - $sql.= " ba.domiciliation, ba.proprio, ba.owner_address, ba.state_id, ba.fk_pays as country_id,"; - $sql.= " ba.account_number, ba.fk_accountancy_journal, ba.currency_code,"; - $sql.= " ba.min_allowed, ba.min_desired, ba.comment,"; - $sql.= " ba.datec as date_creation, ba.tms as date_update,"; - $sql.= ' c.code as country_code, c.label as country,'; - $sql.= ' d.code_departement as state_code, d.nom as state'; - $sql.= ' , aj.code as accountancy_journal'; - $sql.= " FROM ".MAIN_DB_PREFIX."bank_account as ba"; - $sql.= ' LEFT JOIN '.MAIN_DB_PREFIX.'c_country as c ON ba.fk_pays = c.rowid'; - $sql.= ' LEFT JOIN '.MAIN_DB_PREFIX.'c_departements as d ON ba.state_id = d.rowid'; - $sql.= ' LEFT JOIN ' . MAIN_DB_PREFIX . 'accounting_journal as aj ON aj.rowid=ba.fk_accountancy_journal'; - $sql.= " WHERE ba.entity IN (".getEntity($this->element).")"; - if ($id) $sql.= " AND ba.rowid = ".$id; - if ($ref) $sql.= " AND ba.ref = '".$this->db->escape($ref)."'"; + $sql .= " ba.code_banque, ba.code_guichet, ba.cle_rib, ba.bic, ba.iban_prefix as iban,"; + $sql .= " ba.domiciliation, ba.proprio, ba.owner_address, ba.state_id, ba.fk_pays as country_id,"; + $sql .= " ba.account_number, ba.fk_accountancy_journal, ba.currency_code,"; + $sql .= " ba.min_allowed, ba.min_desired, ba.comment,"; + $sql .= " ba.datec as date_creation, ba.tms as date_update,"; + $sql .= ' c.code as country_code, c.label as country,'; + $sql .= ' d.code_departement as state_code, d.nom as state'; + $sql .= ' , aj.code as accountancy_journal'; + $sql .= " FROM ".MAIN_DB_PREFIX."bank_account as ba"; + $sql .= ' LEFT JOIN '.MAIN_DB_PREFIX.'c_country as c ON ba.fk_pays = c.rowid'; + $sql .= ' LEFT JOIN '.MAIN_DB_PREFIX.'c_departements as d ON ba.state_id = d.rowid'; + $sql .= ' LEFT JOIN '.MAIN_DB_PREFIX.'accounting_journal as aj ON aj.rowid=ba.fk_accountancy_journal'; + $sql .= " WHERE ba.entity IN (".getEntity($this->element).")"; + if ($id) $sql .= " AND ba.rowid = ".$id; + if ($ref) $sql .= " AND ba.ref = '".$this->db->escape($ref)."'"; dol_syslog(get_class($this)."::fetch", LOG_DEBUG); $result = $this->db->query($sql); @@ -926,7 +926,7 @@ class Account extends CommonObject $this->accountancy_journal = $obj->accountancy_journal; $this->currency_code = $obj->currency_code; - $this->account_currency_code = $obj->currency_code; + $this->account_currency_code = $obj->currency_code; $this->min_allowed = $obj->min_allowed; $this->min_desired = $obj->min_desired; $this->comment = $obj->comment; @@ -947,8 +947,8 @@ class Account extends CommonObject } else { - $this->error=$this->db->lasterror; - $this->errors[]=$this->error; + $this->error = $this->db->lasterror; + $this->errors[] = $this->error; return -1; } } @@ -966,12 +966,12 @@ class Account extends CommonObject public function setCategories($categories) { // Handle single category - if (! is_array($categories)) { + if (!is_array($categories)) { $categories = array($categories); } // Get current categories - require_once DOL_DOCUMENT_ROOT . '/categories/class/categorie.class.php'; + require_once DOL_DOCUMENT_ROOT.'/categories/class/categorie.class.php'; $c = new Categorie($this->db); $existing = $c->containing($this->id, Categorie::TYPE_ACCOUNT, 'id'); @@ -985,7 +985,7 @@ class Account extends CommonObject } // Process - foreach($to_del as $del) { + foreach ($to_del as $del) { if ($c->fetch($del) > 0) { $c->del_type($this, Categorie::TYPE_ACCOUNT); } @@ -1009,15 +1009,15 @@ class Account extends CommonObject { global $conf; - $error=0; + $error = 0; $this->db->begin(); // Delete link between tag and bank account - if (! $error) + if (!$error) { $sql = "DELETE FROM ".MAIN_DB_PREFIX."categorie_account"; - $sql.= " WHERE fk_account = ".$this->id; + $sql .= " WHERE fk_account = ".$this->id; $resql = $this->db->query($sql); if (!$resql) @@ -1027,10 +1027,10 @@ class Account extends CommonObject } } - if (! $error) + if (!$error) { $sql = "DELETE FROM ".MAIN_DB_PREFIX."bank_account"; - $sql.= " WHERE rowid = ".$this->rowid; + $sql .= " WHERE rowid = ".$this->rowid; dol_syslog(get_class($this)."::delete", LOG_DEBUG); $result = $this->db->query($sql); @@ -1039,7 +1039,7 @@ class Account extends CommonObject // Remove extrafields if ((empty($conf->global->MAIN_EXTRAFIELDS_DISABLED))) // For avoid conflicts if trigger used { - $result=$this->deleteExtraFields(); + $result = $this->deleteExtraFields(); if ($result < 0) { $error++; @@ -1054,7 +1054,7 @@ class Account extends CommonObject } } - if (! $error) + if (!$error) { $this->db->commit(); return 1; @@ -1115,16 +1115,16 @@ class Account extends CommonObject public function can_be_deleted() { // phpcs:enable - $can_be_deleted=false; + $can_be_deleted = false; $sql = "SELECT COUNT(rowid) as nb"; - $sql.= " FROM ".MAIN_DB_PREFIX."bank"; - $sql.= " WHERE fk_account=".$this->id; + $sql .= " FROM ".MAIN_DB_PREFIX."bank"; + $sql .= " WHERE fk_account=".$this->id; $resql = $this->db->query($sql); if ($resql) { - $obj=$this->db->fetch_object($resql); - if ($obj->nb <= 1) $can_be_deleted=true; // Juste le solde + $obj = $this->db->fetch_object($resql); + if ($obj->nb <= 1) $can_be_deleted = true; // Juste le solde } else { dol_print_error($this->db); @@ -1151,24 +1151,24 @@ class Account extends CommonObject */ public function solde($option = 0) { - $solde=0; + $solde = 0; $sql = "SELECT sum(amount) as amount"; - $sql.= " FROM ".MAIN_DB_PREFIX."bank"; - $sql.= " WHERE fk_account = ".$this->id; - if ($option == 1) $sql.= " AND dateo <= '".$this->db->idate(dol_now())."'"; + $sql .= " FROM ".MAIN_DB_PREFIX."bank"; + $sql .= " WHERE fk_account = ".$this->id; + if ($option == 1) $sql .= " AND dateo <= '".$this->db->idate(dol_now())."'"; $resql = $this->db->query($sql); if ($resql) { if ($this->db->num_rows($resql)) { - $obj=$this->db->fetch_object($resql); + $obj = $this->db->fetch_object($resql); $solde = $obj->amount; } $this->db->free($resql); } else { - $this->errors[]=$this->db->lasterror; + $this->errors[] = $this->db->lasterror; return -1; } @@ -1228,7 +1228,7 @@ class Account extends CommonObject else { dol_print_error($this->db); - $this->error=$this->db->error(); + $this->error = $this->db->error(); return -1; } } @@ -1287,14 +1287,14 @@ class Account extends CommonObject return 0; } - $nb=0; + $nb = 0; $sql = "SELECT COUNT(ba.rowid) as nb"; - $sql.= " FROM ".MAIN_DB_PREFIX."bank_account as ba"; - $sql.= " WHERE ba.rappro > 0 and ba.clos = 0"; - $sql.= " AND ba.entity IN (".getEntity('bank_account').")"; - if (empty($conf->global->BANK_CAN_RECONCILIATE_CASHACCOUNT)) $sql.= " AND ba.courant != 2"; - $resql=$db->query($sql); + $sql .= " FROM ".MAIN_DB_PREFIX."bank_account as ba"; + $sql .= " WHERE ba.rappro > 0 and ba.clos = 0"; + $sql .= " AND ba.entity IN (".getEntity('bank_account').")"; + if (empty($conf->global->BANK_CAN_RECONCILIATE_CASHACCOUNT)) $sql .= " AND ba.courant != 2"; + $resql = $db->query($sql); if ($resql) { $obj = $db->fetch_object($resql); @@ -1319,23 +1319,23 @@ class Account extends CommonObject { global $conf, $langs, $user; - $result=''; - $label = '' . $langs->trans("ShowAccount") . ''; - $label .= '
' . $langs->trans('BankAccount') . ': ' . $this->label; - $label .= '
' . $langs->trans('AccountNumber') . ': ' . $this->number; - $label .= '
' . $langs->trans("AccountCurrency") . ': ' . $this->currency_code; + $result = ''; + $label = ''.$langs->trans("ShowAccount").''; + $label .= '
'.$langs->trans('BankAccount').': '.$this->label; + $label .= '
'.$langs->trans('AccountNumber').': '.$this->number; + $label .= '
'.$langs->trans("AccountCurrency").': '.$this->currency_code; if (empty($user->rights->banque->lire) || !empty($user->socid)) { $option = 'nolink'; } - if (! empty($conf->accounting->enabled)) + if (!empty($conf->accounting->enabled)) { include_once DOL_DOCUMENT_ROOT.'/core/lib/accounting.lib.php'; $langs->load("accountancy"); - $label .= '
' . $langs->trans('AccountAccounting') . ': ' . length_accountg($this->account_number); - $label .= '
' . $langs->trans('AccountancyJournal') . ': ' . $this->accountancy_journal; + $label .= '
'.$langs->trans('AccountAccounting').': '.length_accountg($this->account_number); + $label .= '
'.$langs->trans('AccountancyJournal').': '.$this->accountancy_journal; } $linkclose = '" title="'.dol_escape_htmltag($label, 1).'" class="classfortooltip">'; @@ -1352,9 +1352,9 @@ class Account extends CommonObject 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'; + $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'; } $linkstart = 'ref.($option == 'reflabel' && $this->label ? ' - '.$this->label : ''); + 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.($option == 'reflabel' && $this->label ? ' - '.$this->label : ''); $result .= $linkend; return $result; @@ -1384,13 +1384,13 @@ class Account extends CommonObject */ public function verif() { - require_once DOL_DOCUMENT_ROOT . '/core/lib/bank.lib.php'; + require_once DOL_DOCUMENT_ROOT.'/core/lib/bank.lib.php'; $this->error_number = 0; // Call function to check BAN - if (! checkIbanForAccount($this) || ! checkSwiftForAccount($this)) + if (!checkIbanForAccount($this) || !checkSwiftForAccount($this)) { $this->error_number = 12; $this->error_message = 'IBANSWIFTControlError'; @@ -1421,26 +1421,26 @@ class Account extends CommonObject global $mysoc; // We return country code of bank account - if (! empty($this->country_code)) return $this->country_code; + if (!empty($this->country_code)) return $this->country_code; // For backward compatibility, we try to guess country from other information - if (! empty($this->iban)) + if (!empty($this->iban)) { // If IBAN defined, we can know country of account from it if (preg_match("/^([a-zA-Z][a-zA-Z])/i", $this->iban, $reg)) return $reg[1]; } // If this class is linked to a third party - if (! empty($this->socid)) + if (!empty($this->socid)) { - require_once DOL_DOCUMENT_ROOT .'/societe/class/societe.class.php'; - $company=new Societe($this->db); - $result=$company->fetch($this->socid); - if (! empty($company->country_code)) return $company->country_code; + require_once DOL_DOCUMENT_ROOT.'/societe/class/societe.class.php'; + $company = new Societe($this->db); + $result = $company->fetch($this->socid); + if (!empty($company->country_code)) return $company->country_code; } // We return country code of managed company - if (! empty($mysoc->country_code)) return $mysoc->country_code; + if (!empty($mysoc->country_code)) return $mysoc->country_code; return ''; } @@ -1455,10 +1455,10 @@ class Account extends CommonObject */ public function useDetailedBBAN() { - $country_code=$this->getCountryCode(); + $country_code = $this->getCountryCode(); - if (in_array($country_code, array('FR','ES','GA','IT','NC'))) return 1; // France, Spain, Gabon, ... - Not valid for CH - if (in_array($country_code, array('AU','BE','CA','DE','DK','GR','GB','ID','IE','IR','KR','NL','NZ','UK','US'))) return 2; // Australia, England... + if (in_array($country_code, array('FR', 'ES', 'GA', 'IT', 'NC'))) return 1; // France, Spain, Gabon, ... - Not valid for CH + if (in_array($country_code, array('AU', 'BE', 'CA', 'DE', 'DK', 'GR', 'GB', 'ID', 'IE', 'IR', 'KR', 'NL', 'NZ', 'UK', 'US'))) return 2; // Australia, England... return 0; } @@ -1469,41 +1469,41 @@ class Account extends CommonObject */ public function needIBAN() { - $country_code=$this->getCountryCode(); + $country_code = $this->getCountryCode(); - $country_code_in_EEC=array( - 'AT', // Austria - 'BE', // Belgium - 'BG', // Bulgaria - 'CY', // Cyprus - 'CZ', // Czech republic - 'DE', // Germany - 'DK', // Danemark - 'EE', // Estonia - 'ES', // Spain - 'FI', // Finland - 'FR', // France - 'GB', // United Kingdom - 'GR', // Greece - 'HR', // Croatia - 'NL', // Holland - 'HU', // Hungary - 'IE', // Ireland - 'IM', // Isle of Man - Included in UK - 'IT', // Italy - 'LT', // Lithuania - 'LU', // Luxembourg - 'LV', // Latvia - 'MC', // Monaco - Included in France - 'MT', // Malta + $country_code_in_EEC = array( + 'AT', // Austria + 'BE', // Belgium + 'BG', // Bulgaria + 'CY', // Cyprus + 'CZ', // Czech republic + 'DE', // Germany + 'DK', // Danemark + 'EE', // Estonia + 'ES', // Spain + 'FI', // Finland + 'FR', // France + 'GB', // United Kingdom + 'GR', // Greece + 'HR', // Croatia + 'NL', // Holland + 'HU', // Hungary + 'IE', // Ireland + 'IM', // Isle of Man - Included in UK + 'IT', // Italy + 'LT', // Lithuania + 'LU', // Luxembourg + 'LV', // Latvia + 'MC', // Monaco - Included in France + 'MT', // Malta //'NO', // Norway - 'PL', // Poland - 'PT', // Portugal - 'RO', // Romania - 'SE', // Sweden - 'SK', // Slovakia - 'SI', // Slovenia - 'UK', // United Kingdom + 'PL', // Poland + 'PT', // Portugal + 'RO', // Romania + 'SE', // Sweden + 'SK', // Slovakia + 'SI', // Slovenia + 'UK', // United Kingdom //'CH', // Switzerland - No. Swizerland in not in EEC ); @@ -1541,23 +1541,23 @@ class Account extends CommonObject $detailedBBAN = $this->useDetailedBBAN(); if ($detailedBBAN == 0) { - $fieldarray= array( + $fieldarray = array( 'BankAccountNumber' ); } elseif ($detailedBBAN == 2) { - $fieldarray= array( + $fieldarray = array( 'BankCode', 'BankAccountNumber' ); } else { - $fieldarray=self::getAccountNumberOrder(); + $fieldarray = self::getAccountNumberOrder(); } //if ($this->needIBAN()) { // return always IBAN and BIC (this was old behaviour) if ($includeibanbic) { - $fieldarray[]='IBAN'; - $fieldarray[]='BIC'; + $fieldarray[] = 'IBAN'; + $fieldarray[] = 'BIC'; } //} @@ -1647,7 +1647,7 @@ class AccountLine extends CommonObject /** * @var string Error code (or message) */ - public $error=''; + public $error = ''; /** * @var DoliDB Database handler. @@ -1657,12 +1657,12 @@ class AccountLine extends CommonObject /** * @var string ID to identify managed object */ - public $element='bank'; + public $element = 'bank'; /** * @var string Name of table without prefix where object is stored */ - public $table_element='bank'; + public $table_element = 'bank'; /** * @var string String with name of icon for myobject. Must be the part after the 'object_' into object_myobject.png @@ -1724,10 +1724,10 @@ class AccountLine extends CommonObject */ public $fk_type; - public $rappro; // Is it conciliated - public $num_releve; // If conciliated, what is bank statement - public $num_chq; // Num of cheque - public $bank_chq; // Bank of cheque + public $rappro; // Is it conciliated + public $num_releve; // If conciliated, what is bank statement + public $num_chq; // Num of cheque + public $bank_chq; // Bank of cheque /** * @var int ID of cheque receipt @@ -1739,7 +1739,7 @@ class AccountLine extends CommonObject */ public $fk_account; - public $bank_account_label; // Label of bank account + public $bank_account_label; // Label of bank account /** * Issuer @@ -1773,55 +1773,55 @@ class AccountLine extends CommonObject if (empty($rowid) && empty($ref) && empty($num)) return -1; $sql = "SELECT b.rowid, b.datec, b.datev, b.dateo, b.amount, b.label as label, b.fk_account,"; - $sql.= " b.fk_user_author, b.fk_user_rappro,"; - $sql.= " b.fk_type, b.num_releve, b.num_chq, b.rappro, b.note,"; - $sql.= " b.fk_bordereau, b.banque, b.emetteur,"; + $sql .= " b.fk_user_author, b.fk_user_rappro,"; + $sql .= " b.fk_type, b.num_releve, b.num_chq, b.rappro, b.note,"; + $sql .= " b.fk_bordereau, b.banque, b.emetteur,"; //$sql.= " b.author"; // Is this used ? - $sql.= " ba.ref as bank_account_ref, ba.label as bank_account_label"; - $sql.= " FROM ".MAIN_DB_PREFIX."bank as b,"; - $sql.= " ".MAIN_DB_PREFIX."bank_account as ba"; - $sql.= " WHERE b.fk_account = ba.rowid"; - $sql.= " AND ba.entity IN (".getEntity('bank_account').")"; - if ($num) $sql.= " AND b.num_chq='".$this->db->escape($num)."'"; - elseif ($ref) $sql.= " AND b.rowid='".$this->db->escape($ref)."'"; - else $sql.= " AND b.rowid=".$rowid; + $sql .= " ba.ref as bank_account_ref, ba.label as bank_account_label"; + $sql .= " FROM ".MAIN_DB_PREFIX."bank as b,"; + $sql .= " ".MAIN_DB_PREFIX."bank_account as ba"; + $sql .= " WHERE b.fk_account = ba.rowid"; + $sql .= " AND ba.entity IN (".getEntity('bank_account').")"; + if ($num) $sql .= " AND b.num_chq='".$this->db->escape($num)."'"; + elseif ($ref) $sql .= " AND b.rowid='".$this->db->escape($ref)."'"; + else $sql .= " AND b.rowid=".$rowid; dol_syslog(get_class($this)."::fetch", LOG_DEBUG); $result = $this->db->query($sql); if ($result) { - $ret=0; + $ret = 0; $obj = $this->db->fetch_object($result); if ($obj) { - $this->id = $obj->rowid; + $this->id = $obj->rowid; $this->rowid = $obj->rowid; - $this->ref = $obj->rowid; + $this->ref = $obj->rowid; $this->datec = $obj->datec; $this->datev = $obj->datev; $this->dateo = $obj->dateo; - $this->amount = $obj->amount; + $this->amount = $obj->amount; $this->label = $obj->label; $this->note = $obj->note; $this->fk_user_author = $obj->fk_user_author; $this->fk_user_rappro = $obj->fk_user_rappro; - $this->fk_type = $obj->fk_type; // Type of transaction - $this->rappro = $obj->rappro; - $this->num_releve = $obj->num_releve; + $this->fk_type = $obj->fk_type; // Type of transaction + $this->rappro = $obj->rappro; + $this->num_releve = $obj->num_releve; - $this->num_chq = $obj->num_chq; - $this->bank_chq = $obj->banque; - $this->fk_bordereau = $obj->fk_bordereau; + $this->num_chq = $obj->num_chq; + $this->bank_chq = $obj->banque; + $this->fk_bordereau = $obj->fk_bordereau; - $this->fk_account = $obj->fk_account; + $this->fk_account = $obj->fk_account; $this->bank_account_ref = $obj->bank_account_ref; $this->bank_account_label = $obj->bank_account_label; - $ret=1; + $ret = 1; } $this->db->free($result); return $ret; @@ -1858,7 +1858,7 @@ class AccountLine extends CommonObject $sql .= ", '".$this->db->idate($this->datev)."'"; $sql .= ", '".$this->db->escape($this->label)."'"; $sql .= ", ".price2num($this->amount); - $sql .= ", ".($this->fk_user_author > 0 ? $this->fk_user_author :"null"); + $sql .= ", ".($this->fk_user_author > 0 ? $this->fk_user_author : "null"); $sql .= ", ".($this->num_chq ? "'".$this->db->escape($this->num_chq)."'" : "null"); $sql .= ", '".$this->db->escape($this->fk_account)."'"; $sql .= ", '".$this->db->escape($this->fk_type)."'"; @@ -1889,19 +1889,19 @@ class AccountLine extends CommonObject */ public function delete(User $user = null) { - $nbko=0; + $nbko = 0; if ($this->rappro) { // Protection to avoid any delete of consolidated lines - $this->error="ErrorDeleteNotPossibleLineIsConsolidated"; + $this->error = "ErrorDeleteNotPossibleLineIsConsolidated"; return -1; } $this->db->begin(); // Delete urls - $result=$this->delete_urls($user); + $result = $this->delete_urls($user); if ($result < 0) { $nbko++; @@ -1910,14 +1910,14 @@ class AccountLine extends CommonObject $sql = "DELETE FROM ".MAIN_DB_PREFIX."bank_class WHERE lineid=".(int) $this->rowid; dol_syslog(get_class($this)."::delete", LOG_DEBUG); $result = $this->db->query($sql); - if (! $result) $nbko++; + if (!$result) $nbko++; $sql = "DELETE FROM ".MAIN_DB_PREFIX."bank WHERE rowid=".(int) $this->rowid; dol_syslog(get_class($this)."::delete", LOG_DEBUG); $result = $this->db->query($sql); - if (! $result) $nbko++; + if (!$result) $nbko++; - if (! $nbko) + if (!$nbko) { $this->db->commit(); return 1; @@ -1940,12 +1940,12 @@ class AccountLine extends CommonObject public function delete_urls(User $user = null) { // phpcs:enable - $nbko=0; + $nbko = 0; if ($this->rappro) { // Protection to avoid any delete of consolidated lines - $this->error="ErrorDeleteNotPossibleLineIsConsolidated"; + $this->error = "ErrorDeleteNotPossibleLineIsConsolidated"; return -1; } @@ -1954,9 +1954,9 @@ class AccountLine extends CommonObject $sql = "DELETE FROM ".MAIN_DB_PREFIX."bank_url WHERE fk_bank=".(int) $this->rowid; dol_syslog(get_class($this)."::delete_urls", LOG_DEBUG); $result = $this->db->query($sql); - if (! $result) $nbko++; + if (!$result) $nbko++; - if (! $nbko) + if (!$nbko) { $this->db->commit(); return 1; @@ -1981,10 +1981,10 @@ class AccountLine extends CommonObject $this->db->begin(); $sql = "UPDATE ".MAIN_DB_PREFIX."bank SET"; - $sql.= " amount = ".price2num($this->amount).","; - $sql.= " datev='".$this->db->idate($this->datev)."',"; - $sql.= " dateo='".$this->db->idate($this->dateo)."'"; - $sql.= " WHERE rowid = ".$this->rowid; + $sql .= " amount = ".price2num($this->amount).","; + $sql .= " datev='".$this->db->idate($this->datev)."',"; + $sql .= " dateo='".$this->db->idate($this->dateo)."'"; + $sql .= " WHERE rowid = ".$this->rowid; dol_syslog(get_class($this)."::update", LOG_DEBUG); $resql = $this->db->query($sql); @@ -1996,7 +1996,7 @@ class AccountLine extends CommonObject else { $this->db->rollback(); - $this->error=$this->db->error(); + $this->error = $this->db->error(); return -1; } } @@ -2014,39 +2014,39 @@ class AccountLine extends CommonObject public function update_conciliation(User $user, $cat, $conciliated = 1) { // phpcs:enable - global $conf,$langs; + global $conf, $langs; $this->db->begin(); // Check statement field - if (! empty($conf->global->BANK_STATEMENT_REGEX_RULE)) + if (!empty($conf->global->BANK_STATEMENT_REGEX_RULE)) { - if (! preg_match('/'.$conf->global->BANK_STATEMENT_REGEX_RULE.'/', $this->num_releve)) + if (!preg_match('/'.$conf->global->BANK_STATEMENT_REGEX_RULE.'/', $this->num_releve)) { - $this->errors[]=$langs->trans("ErrorBankStatementNameMustFollowRegex", $conf->global->BANK_STATEMENT_REGEX_RULE); + $this->errors[] = $langs->trans("ErrorBankStatementNameMustFollowRegex", $conf->global->BANK_STATEMENT_REGEX_RULE); return -1; } } $sql = "UPDATE ".MAIN_DB_PREFIX."bank SET"; - $sql.= " rappro = ".$conciliated; - $sql.= ", num_releve = '".$this->db->escape($this->num_releve)."'"; - if ($conciliated) $sql.= ", fk_user_rappro = ".$user->id; - $sql.= " WHERE rowid = ".$this->id; + $sql .= " rappro = ".$conciliated; + $sql .= ", num_releve = '".$this->db->escape($this->num_releve)."'"; + if ($conciliated) $sql .= ", fk_user_rappro = ".$user->id; + $sql .= " WHERE rowid = ".$this->id; dol_syslog(get_class($this)."::update_conciliation", LOG_DEBUG); $resql = $this->db->query($sql); if ($resql) { - if (! empty($cat)) + if (!empty($cat)) { $sql = "INSERT INTO ".MAIN_DB_PREFIX."bank_class ("; - $sql.= "lineid"; - $sql.= ", fk_categ"; - $sql.= ") VALUES ("; - $sql.= $this->id; - $sql.= ", ".$cat; - $sql.= ")"; + $sql .= "lineid"; + $sql .= ", fk_categ"; + $sql .= ") VALUES ("; + $sql .= $this->id; + $sql .= ", ".$cat; + $sql .= ")"; dol_syslog(get_class($this)."::update_conciliation", LOG_DEBUG); $this->db->query($sql); @@ -2054,7 +2054,7 @@ class AccountLine extends CommonObject // No error check. Can fail if category already affected } - $this->rappro=1; + $this->rappro = 1; $this->db->commit(); return 1; @@ -2082,12 +2082,12 @@ class AccountLine extends CommonObject $resql = $this->db->query($sql); if ($resql) { - $obj=$this->db->fetch_object($resql); - $newdate=$this->db->jdate($obj->datev)+(3600*24*$sign); + $obj = $this->db->fetch_object($resql); + $newdate = $this->db->jdate($obj->datev) + (3600 * 24 * $sign); $sql = "UPDATE ".MAIN_DB_PREFIX."bank SET"; - $sql.= " datev = '".$this->db->idate($newdate)."'"; - $sql.= " WHERE rowid = ".$rowid; + $sql .= " datev = '".$this->db->idate($newdate)."'"; + $sql .= " WHERE rowid = ".$rowid; $result = $this->db->query($sql); if ($result) @@ -2149,12 +2149,12 @@ class AccountLine extends CommonObject $resql = $this->db->query($sql); if ($resql) { - $obj=$this->db->fetch_object($resql); - $newdate=$this->db->jdate($obj->dateo)+(3600*24*$sign); + $obj = $this->db->fetch_object($resql); + $newdate = $this->db->jdate($obj->dateo) + (3600 * 24 * $sign); $sql = "UPDATE ".MAIN_DB_PREFIX."bank SET"; - $sql.= " dateo = '".$this->db->idate($newdate)."'"; - $sql.= " WHERE rowid = ".$rowid; + $sql .= " dateo = '".$this->db->idate($newdate)."'"; + $sql .= " WHERE rowid = ".$rowid; $result = $this->db->query($sql); if ($result) @@ -2210,11 +2210,11 @@ class AccountLine extends CommonObject public function info($id) { $sql = 'SELECT b.rowid, b.datec, b.tms as datem,'; - $sql.= ' b.fk_user_author, b.fk_user_rappro'; - $sql.= ' FROM '.MAIN_DB_PREFIX.'bank as b'; - $sql.= ' WHERE b.rowid = '.$id; + $sql .= ' b.fk_user_author, b.fk_user_rappro'; + $sql .= ' FROM '.MAIN_DB_PREFIX.'bank as b'; + $sql .= ' WHERE b.rowid = '.$id; - $result=$this->db->query($sql); + $result = $this->db->query($sql); if ($result) { if ($this->db->num_rows($result)) @@ -2226,7 +2226,7 @@ class AccountLine extends CommonObject { $cuser = new User($this->db); $cuser->fetch($obj->fk_user_author); - $this->user_creation = $cuser; + $this->user_creation = $cuser; } if ($obj->fk_user_rappro) { @@ -2261,32 +2261,32 @@ class AccountLine extends CommonObject { global $langs; - $result=''; - $label=$langs->trans("ShowTransaction").': '.$this->rowid; + $result = ''; + $label = $langs->trans("ShowTransaction").': '.$this->rowid; $linkstart = ''; - $linkend=''; + $linkend = ''; $result .= $linkstart; - if ($withpicto) $result.=img_object(($notooltip?'':$label), ($this->picto?$this->picto:'account'), ($notooltip?(($withpicto != 2) ? 'class="paddingright"' : ''):'class="'.(($withpicto != 2) ? 'paddingright ' : '').'classfortooltip"'), 0, 0, $notooltip?0:1); - if ($withpicto != 2) $result.=($this->ref?$this->ref:$this->rowid); + if ($withpicto) $result .= img_object(($notooltip ? '' : $label), ($this->picto ? $this->picto : 'account'), ($notooltip ? (($withpicto != 2) ? 'class="paddingright"' : '') : 'class="'.(($withpicto != 2) ? 'paddingright ' : '').'classfortooltip"'), 0, 0, $notooltip ? 0 : 1); + if ($withpicto != 2) $result .= ($this->ref ? $this->ref : $this->rowid); $result .= $linkend; - if ($option == 'showall' || $option == 'showconciliated') $result.=' ('; + if ($option == 'showall' || $option == 'showconciliated') $result .= ' ('; if ($option == 'showall') { - $result.=$langs->trans("BankAccount").': '; - $accountstatic=new Account($this->db); - $accountstatic->id=$this->fk_account; - $accountstatic->ref=$this->bank_account_ref; - $accountstatic->label=$this->bank_account_label; - $result.=$accountstatic->getNomUrl(0).', '; + $result .= $langs->trans("BankAccount").': '; + $accountstatic = new Account($this->db); + $accountstatic->id = $this->fk_account; + $accountstatic->ref = $this->bank_account_ref; + $accountstatic->label = $this->bank_account_label; + $result .= $accountstatic->getNomUrl(0).', '; } if ($option == 'showall' || $option == 'showconciliated') { - $result.=$langs->trans("BankLineConciliated").': '; - $result.=yn($this->rappro); + $result .= $langs->trans("BankLineConciliated").': '; + $result .= yn($this->rappro); } - if ($option == 'showall' || $option == 'showconciliated') $result.=')'; + if ($option == 'showall' || $option == 'showconciliated') $result .= ')'; return $result; } diff --git a/htdocs/compta/bank/class/paymentvarious.class.php b/htdocs/compta/bank/class/paymentvarious.class.php index ca3acd59e42..050bd5f3b65 100644 --- a/htdocs/compta/bank/class/paymentvarious.class.php +++ b/htdocs/compta/bank/class/paymentvarious.class.php @@ -378,7 +378,7 @@ class PaymentVarious extends CommonObject $sql.= "'".$this->db->idate($this->datep)."'"; $sql.= ", '".$this->db->idate($this->datev)."'"; $sql.= ", '".$this->db->escape($this->sens)."'"; - $sql.= ", ".$this->amount; + $sql.= ", ".price2num($this->amount); $sql.= ", '".$this->db->escape($this->type_payment)."'"; $sql.= ", '".$this->db->escape($this->num_payment)."'"; if ($this->note) $sql.= ", '".$this->db->escape($this->note)."'"; diff --git a/htdocs/compta/bank/document.php b/htdocs/compta/bank/document.php index 1a250a83b10..b70a3ba2c77 100644 --- a/htdocs/compta/bank/document.php +++ b/htdocs/compta/bank/document.php @@ -25,11 +25,11 @@ * \brief Page de gestion des documents attaches a un compte bancaire */ require '../../main.inc.php'; -require_once DOL_DOCUMENT_ROOT . "/core/lib/bank.lib.php"; -require_once DOL_DOCUMENT_ROOT . "/core/lib/files.lib.php"; -require_once DOL_DOCUMENT_ROOT . "/core/lib/images.lib.php"; -require_once DOL_DOCUMENT_ROOT . "/core/class/html.formfile.class.php"; -require_once DOL_DOCUMENT_ROOT . '/compta/bank/class/account.class.php'; +require_once DOL_DOCUMENT_ROOT."/core/lib/bank.lib.php"; +require_once DOL_DOCUMENT_ROOT."/core/lib/files.lib.php"; +require_once DOL_DOCUMENT_ROOT."/core/lib/images.lib.php"; +require_once DOL_DOCUMENT_ROOT."/core/class/html.formfile.class.php"; +require_once DOL_DOCUMENT_ROOT.'/compta/bank/class/account.class.php'; // Load translation files required by the page $langs->loadLangs(array('banks', 'companies', 'other')); @@ -79,10 +79,10 @@ $result = restrictedArea($user, 'banque', $object->id, 'bank_account', '', ''); if ($object->id > 0) { $object->fetch_thirdparty(); - $upload_dir = $conf->bank->dir_output . "/" . dol_sanitizeFileName($object->ref); + $upload_dir = $conf->bank->dir_output."/".dol_sanitizeFileName($object->ref); } -include_once DOL_DOCUMENT_ROOT . '/core/actions_linkedfiles.inc.php'; +include_once DOL_DOCUMENT_ROOT.'/core/actions_linkedfiles.inc.php'; /* @@ -108,7 +108,7 @@ if ($id > 0 || !empty($ref)) { $filearray = dol_dir_list($upload_dir, "files", 0, '', '\.meta$', $sortfield, (strtolower($sortorder) == 'desc' ? SORT_DESC : SORT_ASC), 1); $totalsize = 0; foreach ($filearray as $key => $file) { - $totalsize+=$file['size']; + $totalsize += $file['size']; } $morehtmlref = ''; @@ -122,8 +122,8 @@ if ($id > 0 || !empty($ref)) { print '
'; print ''; - print ''; - print ''; + print ''; + print ''; print "
' . $langs->trans("NbOfAttachedFiles") . '' . count($filearray) . '
' . $langs->trans("TotalSizeOfAttachedFiles") . '' .dol_print_size($totalsize, 1, 1).'
'.$langs->trans("NbOfAttachedFiles").''.count($filearray).'
'.$langs->trans("TotalSizeOfAttachedFiles").''.dol_print_size($totalsize, 1, 1).'
\n"; print ''; @@ -134,8 +134,8 @@ if ($id > 0 || !empty($ref)) { $modulepart = 'bank'; $permission = $user->rights->banque->modifier; $permtoedit = $user->rights->banque->modifier; - $param = '&id=' . $object->id; - include_once DOL_DOCUMENT_ROOT . '/core/tpl/document_actions_post_headers.tpl.php'; + $param = '&id='.$object->id; + include_once DOL_DOCUMENT_ROOT.'/core/tpl/document_actions_post_headers.tpl.php'; } else { dol_print_error($db); diff --git a/htdocs/compta/bank/line.php b/htdocs/compta/bank/line.php index 7e96ddf31be..cdab5006ef9 100644 --- a/htdocs/compta/bank/line.php +++ b/htdocs/compta/bank/line.php @@ -314,7 +314,7 @@ if ($result) print '
'; print '
'; - print ''; + print '
'; $i++; @@ -639,7 +639,7 @@ if ($result) print '
'; - print '
'; + print '
'; print '"; if ($user->rights->banque->consolidate) diff --git a/htdocs/compta/bank/list.php b/htdocs/compta/bank/list.php index 2244a73b02a..3a9db058c91 100644 --- a/htdocs/compta/bank/list.php +++ b/htdocs/compta/bank/list.php @@ -64,8 +64,8 @@ if (empty($page) || $page == -1) { $page = 0; } // If $page is not defined, $offset = $limit * $page; $pageprev = $page - 1; $pagenext = $page + 1; -if (! $sortfield) $sortfield='b.label'; -if (! $sortorder) $sortorder='ASC'; +if (!$sortfield) $sortfield = 'b.label'; +if (!$sortorder) $sortorder = 'ASC'; // Initialize technical object to manage hooks of page. Note that conf->hooks_modules contains array of hook context $object = new Account($db); @@ -82,14 +82,14 @@ $fieldstosearchall = array( 'b.label'=>'Label', ); -$checkedtypetiers=0; -$arrayfields=array( +$checkedtypetiers = 0; +$arrayfields = array( 'b.ref'=>array('label'=>$langs->trans("BankAccounts"), 'checked'=>1), 'accountype'=>array('label'=>$langs->trans("Type"), 'checked'=>1), 'b.label'=>array('label'=>$langs->trans("Label"), 'checked'=>1), 'b.number'=>array('label'=>$langs->trans("AccountIdShort"), 'checked'=>1), - 'b.account_number'=>array('label'=>$langs->trans("AccountAccounting"), 'checked'=>(! empty($conf->accounting->enabled) || ! empty($conf->accounting->enabled))), - 'b.fk_accountancy_journal'=>array('label'=>$langs->trans("AccountancyJournal"), 'checked'=>(! empty($conf->accounting->enabled) || ! empty($conf->accounting->enabled))), + 'b.account_number'=>array('label'=>$langs->trans("AccountAccounting"), 'checked'=>(!empty($conf->accounting->enabled) || !empty($conf->accounting->enabled))), + 'b.fk_accountancy_journal'=>array('label'=>$langs->trans("AccountancyJournal"), 'checked'=>(!empty($conf->accounting->enabled) || !empty($conf->accounting->enabled))), 'toreconcile'=>array('label'=>$langs->trans("TransactionsToConciliate"), 'checked'=>1), 'b.currency_code'=>array('label'=>$langs->trans("Currency"), 'checked'=>0), 'b.datec'=>array('label'=>$langs->trans("DateCreation"), 'checked'=>0, 'position'=>500), @@ -114,11 +114,11 @@ $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 +$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'); include DOL_DOCUMENT_ROOT.'/core/actions_changeselectedfields.inc.php'; @@ -126,10 +126,10 @@ 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 { - $search_ref=''; - $search_label=''; - $search_number=''; - $search_status=''; + $search_ref = ''; + $search_label = ''; + $search_number = ''; + $search_status = ''; } @@ -179,7 +179,7 @@ if (empty($conf->global->MAIN_DISABLE_FULL_SCANLIST)) $nbtotalofrecords = $db->num_rows($result); } -$sql.= $db->plimit($limit + 1, $offset); +$sql .= $db->plimit($limit + 1, $offset); $resql = $db->query($sql); if ($resql) @@ -198,41 +198,41 @@ else dol_print_error($db); -$help_url='EN:Module_Banks_and_Cash|FR:Module_Banques_et_Caisses|ES:Módulo_Bancos_y_Cajas'; +$help_url = 'EN:Module_Banks_and_Cash|FR:Module_Banques_et_Caisses|ES:Módulo_Bancos_y_Cajas'; llxHeader('', $title, $help_url); -$link=''; +$link = ''; $num_rows = count($accounts); -$arrayofselected=is_array($toselect)?$toselect:array(); +$arrayofselected = is_array($toselect) ? $toselect : array(); -$param=''; -if (! empty($contextpage) && $contextpage != $_SERVER["PHP_SELF"]) $param.='&contextpage='.$contextpage; -if ($limit > 0 && $limit != $conf->liste_limit) $param.='&limit='.$limit; -if ($search_ref != '') $param.='&search_ref='.$search_ref; -if ($search_label != '') $param.='&search_label='.$search_label; -if ($search_number != '') $param.='&search_number='.$search_number; -if ($search_status != '') $param.='&search_status='.$search_status; -if ($show_files) $param.='&show_files=' .$show_files; -if ($optioncss != '') $param.='&optioncss='.$optioncss; +$param = ''; +if (!empty($contextpage) && $contextpage != $_SERVER["PHP_SELF"]) $param .= '&contextpage='.$contextpage; +if ($limit > 0 && $limit != $conf->liste_limit) $param .= '&limit='.$limit; +if ($search_ref != '') $param .= '&search_ref='.$search_ref; +if ($search_label != '') $param .= '&search_label='.$search_label; +if ($search_number != '') $param .= '&search_number='.$search_number; +if ($search_status != '') $param .= '&search_status='.$search_status; +if ($show_files) $param .= '&show_files='.$show_files; +if ($optioncss != '') $param .= '&optioncss='.$optioncss; // Add $param from extra fields include DOL_DOCUMENT_ROOT.'/core/tpl/extrafields_list_search_param.tpl.php'; // List of mass actions available -$arrayofmassactions = array( +$arrayofmassactions = array( // 'presend'=>$langs->trans("SendByMail"), // 'builddoc'=>$langs->trans("PDFMerge"), ); -if ($user->rights->banque->supprimer) $arrayofmassactions['predelete']=''.$langs->trans("Delete"); -if (in_array($massaction, array('presend','predelete'))) $arrayofmassactions=array(); -$massactionbutton=$form->selectMassAction('', $arrayofmassactions); +if ($user->rights->banque->supprimer) $arrayofmassactions['predelete'] = ''.$langs->trans("Delete"); +if (in_array($massaction, array('presend', 'predelete'))) $arrayofmassactions = array(); +$massactionbutton = $form->selectMassAction('', $arrayofmassactions); -$newcardbutton=''; +$newcardbutton = ''; if ($user->rights->banque->configurer) { - $newcardbutton.= dolGetButtonTitle($langs->trans('NewFinancialAccount'), '', 'fa fa-plus-circle', 'card.php?action=create'); + $newcardbutton .= dolGetButtonTitle($langs->trans('NewFinancialAccount'), '', 'fa fa-plus-circle', 'card.php?action=create'); } @@ -249,89 +249,89 @@ print ''; print_barre_liste($title, $page, $_SERVER["PHP_SELF"], $param, $sortfield, $sortorder, '', $num, $nbtotalofrecords, 'bank', 0, $newcardbutton, '', $limit, 1); -$topicmail="Information"; +$topicmail = "Information"; //$modelmail="subscription"; -$objecttmp=new Account($db); +$objecttmp = new Account($db); //$trackid='sub'.$object->id; include DOL_DOCUMENT_ROOT.'/core/tpl/massactions_pre.tpl.php'; if ($sall) { - foreach($fieldstosearchall as $key => $val) $fieldstosearchall[$key]=$langs->trans($val); - print '
'.$langs->trans("FilterOnInto", $sall) . join(', ', $fieldstosearchall).'
'; + foreach ($fieldstosearchall as $key => $val) $fieldstosearchall[$key] = $langs->trans($val); + print '
'.$langs->trans("FilterOnInto", $sall).join(', ', $fieldstosearchall).'
'; } -$moreforfilter=''; +$moreforfilter = ''; // Bank accounts -$parameters=array(); -$reshook=$hookmanager->executeHooks('printFieldPreListTitle', $parameters); // Note that $action and $object may have been modified by hook +$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($moreforfilter)) +if (!empty($moreforfilter)) { print '
'; print $moreforfilter; print '
'; } -$varpage=empty($contextpage)?$_SERVER["PHP_SELF"]:$contextpage; -$selectedfields=$form->multiSelectArrayWithCheckbox('selectedfields', $arrayfields, $varpage); // This also change content of $arrayfields +$varpage = empty($contextpage) ? $_SERVER["PHP_SELF"] : $contextpage; +$selectedfields = $form->multiSelectArrayWithCheckbox('selectedfields', $arrayfields, $varpage); // This also change content of $arrayfields print '
'; -print '
'.$langs->trans("Conciliation")."
'."\n"; +print '
'."\n"; print ''; // Ref -if (! empty($arrayfields['b.ref']['checked'])) +if (!empty($arrayfields['b.ref']['checked'])) { print ''; } // Label -if (! empty($arrayfields['b.label']['checked'])) +if (!empty($arrayfields['b.label']['checked'])) { print ''; } // Account type -if (! empty($arrayfields['accountype']['checked'])) +if (!empty($arrayfields['accountype']['checked'])) { print ''; } // Bank number -if (! empty($arrayfields['b.number']['checked'])) +if (!empty($arrayfields['b.number']['checked'])) { print ''; } // Account number -if (! empty($arrayfields['b.account_number']['checked'])) +if (!empty($arrayfields['b.account_number']['checked'])) { print ''; } // Accountancy journal -if (! empty($arrayfields['b.fk_accountancy_journal']['checked'])) +if (!empty($arrayfields['b.fk_accountancy_journal']['checked'])) { print ''; } // Transactions to reconcile -if (! empty($arrayfields['toreconcile']['checked'])) +if (!empty($arrayfields['toreconcile']['checked'])) { print ''; } // Currency -if (! empty($arrayfields['b.currency_code']['checked'])) +if (!empty($arrayfields['b.currency_code']['checked'])) { print ''; @@ -340,26 +340,26 @@ if (! empty($arrayfields['b.currency_code']['checked'])) include DOL_DOCUMENT_ROOT.'/core/tpl/extrafields_list_search_input.tpl.php'; // Fields from hook -$parameters=array('arrayfields'=>$arrayfields); -$reshook=$hookmanager->executeHooks('printFieldListOption', $parameters); // Note that $action and $object may have been modified by hook +$parameters = array('arrayfields'=>$arrayfields); +$reshook = $hookmanager->executeHooks('printFieldListOption', $parameters); // Note that $action and $object may have been modified by hook print $hookmanager->resPrint; // Date creation -if (! empty($arrayfields['b.datec']['checked'])) +if (!empty($arrayfields['b.datec']['checked'])) { print ''; } // Date modification -if (! empty($arrayfields['b.tms']['checked'])) +if (!empty($arrayfields['b.tms']['checked'])) { print ''; } // Status -if (! empty($arrayfields['b.clos']['checked'])) +if (!empty($arrayfields['b.clos']['checked'])) { print ''; } // Balance -if (! empty($arrayfields['balance']['checked'])) +if (!empty($arrayfields['balance']['checked'])) { print ''; } // Action column print ''; print ''; // Fields title print ''; -if (! empty($arrayfields['b.ref']['checked'])) print_liste_field_titre($arrayfields['b.ref']['label'], $_SERVER["PHP_SELF"], 'b.ref', '', $param, '', $sortfield, $sortorder); -if (! empty($arrayfields['b.label']['checked'])) print_liste_field_titre($arrayfields['b.label']['label'], $_SERVER["PHP_SELF"], 'b.label', '', $param, '', $sortfield, $sortorder); -if (! empty($arrayfields['accountype']['checked'])) print_liste_field_titre($arrayfields['accountype']['label'], $_SERVER["PHP_SELF"], '', '', $param, '', $sortfield, $sortorder); -if (! empty($arrayfields['b.number']['checked'])) print_liste_field_titre($arrayfields['b.number']['label'], $_SERVER["PHP_SELF"], 'b.number', '', $param, '', $sortfield, $sortorder); -if (! empty($arrayfields['b.account_number']['checked'])) print_liste_field_titre($arrayfields['b.account_number']['label'], $_SERVER["PHP_SELF"], 'b.account_number', '', $param, '', $sortfield, $sortorder); -if (! empty($arrayfields['b.fk_accountancy_journal']['checked'])) print_liste_field_titre($arrayfields['b.fk_accountancy_journal']['label'], $_SERVER["PHP_SELF"], 'b.fk_accountancy_journal', '', $param, '', $sortfield, $sortorder); -if (! empty($arrayfields['b.currency_code']['checked'])) print_liste_field_titre($arrayfields['b.currency_code']['label'], $_SERVER["PHP_SELF"], 'b.currency_code', '', $param, '', $sortfield, $sortorder, 'center '); -if (! empty($arrayfields['toreconcile']['checked'])) print_liste_field_titre($arrayfields['toreconcile']['label'], $_SERVER["PHP_SELF"], '', '', $param, '', $sortfield, $sortorder, 'center '); +if (!empty($arrayfields['b.ref']['checked'])) print_liste_field_titre($arrayfields['b.ref']['label'], $_SERVER["PHP_SELF"], 'b.ref', '', $param, '', $sortfield, $sortorder); +if (!empty($arrayfields['b.label']['checked'])) print_liste_field_titre($arrayfields['b.label']['label'], $_SERVER["PHP_SELF"], 'b.label', '', $param, '', $sortfield, $sortorder); +if (!empty($arrayfields['accountype']['checked'])) print_liste_field_titre($arrayfields['accountype']['label'], $_SERVER["PHP_SELF"], '', '', $param, '', $sortfield, $sortorder); +if (!empty($arrayfields['b.number']['checked'])) print_liste_field_titre($arrayfields['b.number']['label'], $_SERVER["PHP_SELF"], 'b.number', '', $param, '', $sortfield, $sortorder); +if (!empty($arrayfields['b.account_number']['checked'])) print_liste_field_titre($arrayfields['b.account_number']['label'], $_SERVER["PHP_SELF"], 'b.account_number', '', $param, '', $sortfield, $sortorder); +if (!empty($arrayfields['b.fk_accountancy_journal']['checked'])) print_liste_field_titre($arrayfields['b.fk_accountancy_journal']['label'], $_SERVER["PHP_SELF"], 'b.fk_accountancy_journal', '', $param, '', $sortfield, $sortorder); +if (!empty($arrayfields['b.currency_code']['checked'])) print_liste_field_titre($arrayfields['b.currency_code']['label'], $_SERVER["PHP_SELF"], 'b.currency_code', '', $param, '', $sortfield, $sortorder, 'center '); +if (!empty($arrayfields['toreconcile']['checked'])) print_liste_field_titre($arrayfields['toreconcile']['label'], $_SERVER["PHP_SELF"], '', '', $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 +$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['b.datec']['checked'])) print_liste_field_titre($arrayfields['b.datec']['label'], $_SERVER["PHP_SELF"], "b.datec", "", $param, '', $sortfield, $sortorder, 'center nowrap '); -if (! empty($arrayfields['b.tms']['checked'])) print_liste_field_titre($arrayfields['b.tms']['label'], $_SERVER["PHP_SELF"], "b.tms", "", $param, '', $sortfield, $sortorder, 'center nowrap '); -if (! empty($arrayfields['b.clos']['checked'])) print_liste_field_titre($arrayfields['b.clos']['label'], $_SERVER["PHP_SELF"], 'b.clos', '', $param, '', $sortfield, $sortorder, 'center '); -if (! empty($arrayfields['balance']['checked'])) print_liste_field_titre($arrayfields['balance']['label'], $_SERVER["PHP_SELF"], '', '', $param, '', $sortfield, $sortorder, 'right '); +if (!empty($arrayfields['b.datec']['checked'])) print_liste_field_titre($arrayfields['b.datec']['label'], $_SERVER["PHP_SELF"], "b.datec", "", $param, '', $sortfield, $sortorder, 'center nowrap '); +if (!empty($arrayfields['b.tms']['checked'])) print_liste_field_titre($arrayfields['b.tms']['label'], $_SERVER["PHP_SELF"], "b.tms", "", $param, '', $sortfield, $sortorder, 'center nowrap '); +if (!empty($arrayfields['b.clos']['checked'])) print_liste_field_titre($arrayfields['b.clos']['label'], $_SERVER["PHP_SELF"], 'b.clos', '', $param, '', $sortfield, $sortorder, 'center '); +if (!empty($arrayfields['balance']['checked'])) print_liste_field_titre($arrayfields['balance']['label'], $_SERVER["PHP_SELF"], '', '', $param, '', $sortfield, $sortorder, 'right '); print_liste_field_titre($selectedfields, $_SERVER["PHP_SELF"], "", '', '', '', $sortfield, $sortorder, 'center maxwidthsearch '); print "\n"; -$total = array(); $found = 0; $i=0; $lastcurrencycode=''; +$total = array(); $found = 0; $i = 0; $lastcurrencycode = ''; foreach ($accounts as $key=>$type) { @@ -488,26 +488,26 @@ foreach ($accounts as $key=>$type) print ''; } print ''; - if (! $i) $totalarray['nbfield']++; + if (!$i) $totalarray['nbfield']++; } // Currency - if (! empty($arrayfields['b.currency_code']['checked'])) + if (!empty($arrayfields['b.currency_code']['checked'])) { print ''; - if (! $i) $totalarray['nbfield']++; + if (!$i) $totalarray['nbfield']++; } // Transactions to reconcile - if (! empty($arrayfields['toreconcile']['checked'])) + if (!empty($arrayfields['toreconcile']['checked'])) { print ''; - if (! $i) $totalarray['nbfield']++; + if (!$i) $totalarray['nbfield']++; print ''; @@ -586,10 +586,10 @@ foreach ($accounts as $key=>$type) } // If no record found -if (! $found) +if (!$found) { - $colspan=1; - foreach($arrayfields as $key => $val) { if (! empty($val['checked'])) $colspan++; } + $colspan = 1; + foreach ($arrayfields as $key => $val) { if (!empty($val['checked'])) $colspan++; } print ''; } diff --git a/htdocs/compta/bank/releve.php b/htdocs/compta/bank/releve.php index cb029902372..8920d5eff9b 100644 --- a/htdocs/compta/bank/releve.php +++ b/htdocs/compta/bank/releve.php @@ -4,6 +4,7 @@ * Copyright (C) 2005-2013 Regis Houssin * Copyright (C) 2015 Jean-François Ferry * Copyright (C) 2017 Patrick Delcroix + * Copyright (C) 2019 Nicolas ZABOURI * * 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 @@ -42,38 +43,38 @@ require_once DOL_DOCUMENT_ROOT.'/core/lib/files.lib.php'; require_once DOL_DOCUMENT_ROOT.'/core/lib/functions.lib.php'; // Load translation files required by the page -$langs->loadLangs(array("banks","categories","companies","bills","trips")); +$langs->loadLangs(array("banks", "categories", "companies", "bills", "trips")); -$action=GETPOST('action', 'alpha'); -$id=GETPOST('account', 'int'); -$ref=GETPOST('ref', 'alpha'); -$dvid=GETPOST('dvid', 'alpha'); -$numref=GETPOST('num', 'alpha'); -$ve=GETPOST("ve", 'alpha'); -$brref=GETPOST('brref', 'alpha'); -$oldbankreceipt=GETPOST('oldbankreceipt', 'alpha'); -$newbankreceipt=GETPOST('newbankreceipt', 'alpha'); +$action = GETPOST('action', 'alpha'); +$id = GETPOST('account', 'int'); +$ref = GETPOST('ref', 'alpha'); +$dvid = GETPOST('dvid', 'alpha'); +$numref = GETPOST('num', 'alpha'); +$ve = GETPOST("ve", 'alpha'); +$brref = GETPOST('brref', 'alpha'); +$oldbankreceipt = GETPOST('oldbankreceipt', 'alpha'); +$newbankreceipt = GETPOST('newbankreceipt', 'alpha'); // Security check -$fieldid = (! empty($ref)?$ref:$id); -$fieldname = isset($ref)?'ref':'rowid'; -if ($user->socid) $socid=$user->socid; -$result=restrictedArea($user, 'banque', $fieldid, 'bank_account', '', '', $fieldname); +$fieldid = (!empty($ref) ? $ref : $id); +$fieldname = isset($ref) ? 'ref' : 'rowid'; +if ($user->socid) $socid = $user->socid; +$result = restrictedArea($user, 'banque', $fieldid, 'bank_account', '', '', $fieldname); -if ($user->rights->banque->consolidate && $action == 'dvnext' && ! empty($dvid)) +if ($user->rights->banque->consolidate && $action == 'dvnext' && !empty($dvid)) { $al = new AccountLine($db); $al->datev_next($dvid); } -if ($user->rights->banque->consolidate && $action == 'dvprev' && ! empty($dvid)) +if ($user->rights->banque->consolidate && $action == 'dvprev' && !empty($dvid)) { $al = new AccountLine($db); $al->datev_previous($dvid); } -$limit = GETPOST('limit', 'int')?GETPOST('limit', 'int'):$conf->liste_limit; +$limit = GETPOST('limit', 'int') ?GETPOST('limit', 'int') : $conf->liste_limit; $sortfield = GETPOST("sortfield", 'alpha'); $sortorder = GETPOST("sortorder", 'alpha'); $page = GETPOST("page", 'int'); @@ -83,31 +84,31 @@ if (empty($page) || $page == -1) { $page = 0; } // If $page is not defined, $offset = $limit * $page; $pageprev = $page - 1; $pagenext = $page + 1; -if (! $sortorder) $sortorder="ASC"; -if (! $sortfield) $sortfield="s.nom"; +if (!$sortorder) $sortorder = "ASC"; +if (!$sortfield) $sortfield = "s.nom"; $object = new Account($db); -if ($id > 0 || ! empty($ref)) +if ($id > 0 || !empty($ref)) { - $result=$object->fetch($id, $ref); - $account = $object->id; // Force the search field on id of account + $result = $object->fetch($id, $ref); + $account = $object->id; // Force the search field on id of account } // Initialize technical object to manage context to save list fields -$contextpage='banktransactionlist'.(empty($object->ref)?'':'-'.$object->id); +$contextpage = 'banktransactionlist'.(empty($object->ref) ? '' : '-'.$object->id); // Define number of receipt to show (current, previous or next one ?) -$found=false; +$found = false; if ($_GET["rel"] == 'prev') { // Recherche valeur pour num = numero releve precedent $sql = "SELECT DISTINCT(b.num_releve) as num"; - $sql.= " FROM ".MAIN_DB_PREFIX."bank as b"; - $sql.= " WHERE b.num_releve < '".$db->escape($numref)."'"; - $sql.= " AND b.fk_account = ".$object->id; - $sql.= " ORDER BY b.num_releve DESC"; + $sql .= " FROM ".MAIN_DB_PREFIX."bank as b"; + $sql .= " WHERE b.num_releve < '".$db->escape($numref)."'"; + $sql .= " AND b.fk_account = ".$object->id; + $sql .= " ORDER BY b.num_releve DESC"; dol_syslog("htdocs/compta/bank/releve.php", LOG_DEBUG); $resql = $db->query($sql); @@ -118,7 +119,7 @@ if ($_GET["rel"] == 'prev') { $obj = $db->fetch_object($resql); $numref = $obj->num; - $found=true; + $found = true; } } } @@ -126,10 +127,10 @@ elseif ($_GET["rel"] == 'next') { // Recherche valeur pour num = numero releve precedent $sql = "SELECT DISTINCT(b.num_releve) as num"; - $sql.= " FROM ".MAIN_DB_PREFIX."bank as b"; - $sql.= " WHERE b.num_releve > '".$db->escape($numref)."'"; - $sql.= " AND b.fk_account = ".$object->id; - $sql.= " ORDER BY b.num_releve ASC"; + $sql .= " FROM ".MAIN_DB_PREFIX."bank as b"; + $sql .= " WHERE b.num_releve > '".$db->escape($numref)."'"; + $sql .= " AND b.fk_account = ".$object->id; + $sql .= " ORDER BY b.num_releve ASC"; dol_syslog("htdocs/compta/bank/releve.php", LOG_DEBUG); $resql = $db->query($sql); @@ -140,29 +141,29 @@ elseif ($_GET["rel"] == 'next') { $obj = $db->fetch_object($resql); $numref = $obj->num; - $found=true; + $found = true; } } } else { // On veut le releve num - $found=true; + $found = true; } $sql = "SELECT b.rowid, b.dateo as do, b.datev as dv,"; -$sql.= " b.amount, b.label, b.rappro, b.num_releve, b.num_chq, b.fk_type,"; -$sql.= " b.fk_bordereau,"; -$sql.= " bc.ref,"; -$sql.= " ba.rowid as bankid, ba.ref as bankref, ba.label as banklabel"; -$sql.= " FROM ".MAIN_DB_PREFIX."bank_account as ba"; -$sql.= ", ".MAIN_DB_PREFIX."bank as b"; -$sql.= ' LEFT JOIN '.MAIN_DB_PREFIX.'bordereau_cheque as bc ON bc.rowid=b.fk_bordereau'; -$sql.= " WHERE b.num_releve='".$db->escape($numref)."'"; -if (empty($numref)) $sql.= " OR b.num_releve is null"; -$sql.= " AND b.fk_account = ".$object->id; -$sql.= " AND b.fk_account = ba.rowid"; -$sql.= $db->order("b.datev, b.datec", "ASC"); // We add date of creation to have correct order when everything is done the same day +$sql .= " b.amount, b.label, b.rappro, b.num_releve, b.num_chq, b.fk_type,"; +$sql .= " b.fk_bordereau,"; +$sql .= " bc.ref,"; +$sql .= " ba.rowid as bankid, ba.ref as bankref, ba.label as banklabel"; +$sql .= " FROM ".MAIN_DB_PREFIX."bank_account as ba"; +$sql .= ", ".MAIN_DB_PREFIX."bank as b"; +$sql .= ' LEFT JOIN '.MAIN_DB_PREFIX.'bordereau_cheque as bc ON bc.rowid=b.fk_bordereau'; +$sql .= " WHERE b.num_releve='".$db->escape($numref)."'"; +if (empty($numref)) $sql .= " OR b.num_releve is null"; +$sql .= " AND b.fk_account = ".$object->id; +$sql .= " AND b.fk_account = ba.rowid"; +$sql .= $db->order("b.datev, b.datec", "ASC"); // We add date of creation to have correct order when everything is done the same day $sqlrequestforbankline = $sql; @@ -172,14 +173,14 @@ $sqlrequestforbankline = $sql; * Actions */ -if ($action == 'confirm_editbankreceipt' && ! empty($oldbankreceipt) && ! empty($newbankreceipt)) +if ($action == 'confirm_editbankreceipt' && !empty($oldbankreceipt) && !empty($newbankreceipt)) { // TODO Add a test to check newbankreceipt does not exists yet $sqlupdate = 'UPDATE '.MAIN_DB_PREFIX.'bank SET num_releve = "'.$db->escape($newbankreceipt).'" WHERE num_releve = "'.$db->escape($oldbankreceipt).'"'; $result = $db->query($sqlupdate); if ($result < 0) dol_print_error($db); - $action='view'; + $action = 'view'; } @@ -192,33 +193,33 @@ $helpurl = ""; llxHeader('', $title, $helpurl); $form = new Form($db); -$societestatic=new Societe($db); -$chargestatic=new ChargeSociales($db); -$memberstatic=new Adherent($db); -$paymentstatic=new Paiement($db); -$paymentsupplierstatic=new PaiementFourn($db); -$paymentvatstatic=new TVA($db); -$bankstatic=new Account($db); -$banklinestatic=new AccountLine($db); +$societestatic = new Societe($db); +$chargestatic = new ChargeSociales($db); +$memberstatic = new Adherent($db); +$paymentstatic = new Paiement($db); +$paymentsupplierstatic = new PaiementFourn($db); +$paymentvatstatic = new TVA($db); +$bankstatic = new Account($db); +$banklinestatic = new AccountLine($db); $remisestatic = new RemiseCheque($db); // Must be before button action -$param=''; -if (! empty($contextpage) && $contextpage != $_SERVER["PHP_SELF"]) $param.='&contextpage='.$contextpage; -if ($limit > 0 && $limit != $conf->liste_limit) $param.='&limit='.$limit; -if ($id > 0) $param.='&id='.urlencode($id); +$param = ''; +if (!empty($contextpage) && $contextpage != $_SERVER["PHP_SELF"]) $param .= '&contextpage='.$contextpage; +if ($limit > 0 && $limit != $conf->liste_limit) $param .= '&limit='.$limit; +if ($id > 0) $param .= '&id='.urlencode($id); if (empty($numref)) { - $sortfield='numr'; - $sortorder='DESC'; + $sortfield = 'numr'; + $sortorder = 'DESC'; // List of all standing receipts $sql = "SELECT DISTINCT(b.num_releve) as numr"; - $sql.= " FROM ".MAIN_DB_PREFIX."bank as b"; - $sql.= " WHERE b.fk_account = ".$object->id; - $sql.=$db->order($sortfield, $sortorder); + $sql .= " FROM ".MAIN_DB_PREFIX."bank as b"; + $sql .= " WHERE b.fk_account = ".$object->id; + $sql .= $db->order($sortfield, $sortorder); // Count total nb of records $nbtotalofrecords = ''; @@ -228,7 +229,7 @@ if (empty($numref)) $nbtotalofrecords = $db->num_rows($result); } - $sql.= $db->plimit($conf->liste_limit+1, $offset); + $sql .= $db->plimit($conf->liste_limit + 1, $offset); $result = $db->query($sql); if ($result) @@ -237,7 +238,7 @@ if (empty($numref)) $i = 0; // Onglets - $head=bank_prepare_head($object); + $head = bank_prepare_head($object); dol_fiche_head($head, 'statement', $langs->trans("FinancialAccount"), 0, 'account'); $linkback = ''.$langs->trans("BackToList").''; @@ -270,7 +271,7 @@ if (empty($numref)) print ''; print ''; - print '
'; print ''; print ''; print ''; print ''; print ''; print ''; print ''; print ''; print ''; print ''; print ''; print ''; print ''; - $array=array( + $array = array( 'opened'=>$langs->trans("Opened"), 'closed'=>$langs->trans("Closed") ); @@ -367,42 +367,42 @@ if (! empty($arrayfields['b.clos']['checked'])) print ''; -$searchpicto=$form->showFilterAndCheckAddButtons($massactionbutton?1:0, 'checkforselect', 1); +$searchpicto = $form->showFilterAndCheckAddButtons($massactionbutton ? 1 : 0, 'checkforselect', 1); print $searchpicto; print '
'; print $objecttmp->currency_code; print ''; if ($objecttmp->rappro) { - $result=$objecttmp->load_board($user, $objecttmp->id); - if ($result<0) { + $result = $objecttmp->load_board($user, $objecttmp->id); + if ($result < 0) { setEventMessages($objecttmp->error, $objecttmp->errors, 'errors'); } else { print ''.$result->nbtodo.''; @@ -571,12 +571,12 @@ foreach ($accounts as $key=>$type) print ''; if ($massactionbutton || $massaction) // If we are in select mode (massactionbutton defined) or if we have already selected and sent an action ($massaction) defined { - $selected=0; - if (in_array($objecttmp->id, $arrayofselected)) $selected=1; - print ''; + $selected = 0; + if (in_array($objecttmp->id, $arrayofselected)) $selected = 1; + print ''; } print '
'.$langs->trans("NoRecordFound").'
'; + print '
'; print ''; print ''; print ''; @@ -278,14 +279,14 @@ if (empty($numref)) print ''; print ''; - $balancestart=array(); - $content=array(); + $balancestart = array(); + $content = array(); while ($i < min($numrows, $conf->liste_limit)) { $objp = $db->fetch_object($result); - if (! isset($objp->numr)) + if (!isset($objp->numr)) { // } @@ -308,13 +309,13 @@ if (empty($numref)) // Calculate start amount $sql = "SELECT sum(b.amount) as amount"; - $sql.= " FROM ".MAIN_DB_PREFIX."bank as b"; - $sql.= " WHERE b.num_releve < '".$db->escape($objp->numr)."'"; - $sql.= " AND b.fk_account = ".$object->id; - $resql=$db->query($sql); + $sql .= " FROM ".MAIN_DB_PREFIX."bank as b"; + $sql .= " WHERE b.num_releve < '".$db->escape($objp->numr)."'"; + $sql .= " AND b.fk_account = ".$object->id; + $resql = $db->query($sql); if ($resql) { - $obj=$db->fetch_object($resql); + $obj = $db->fetch_object($resql); $balancestart[$objp->numr] = $obj->amount; $db->free($resql); } @@ -322,17 +323,17 @@ if (empty($numref)) // Calculate end amount $sql = "SELECT sum(b.amount) as amount"; - $sql.= " FROM ".MAIN_DB_PREFIX."bank as b"; - $sql.= " WHERE b.num_releve = '".$db->escape($objp->numr)."'"; - $sql.= " AND b.fk_account = ".$object->id; - $resql=$db->query($sql); + $sql .= " FROM ".MAIN_DB_PREFIX."bank as b"; + $sql .= " WHERE b.num_releve = '".$db->escape($objp->numr)."'"; + $sql .= " AND b.fk_account = ".$object->id; + $resql = $db->query($sql); if ($resql) { - $obj=$db->fetch_object($resql); + $obj = $db->fetch_object($resql); $content[$objp->numr] = $obj->amount; $db->free($resql); } - print ''; + print ''; print '\n"; print ''; // Type and num if ($objp->fk_type == 'SOLD') { - $type_label=' '; + $type_label = ' '; } else { - $type_label=($langs->trans("PaymentTypeShort".$objp->fk_type)!="PaymentTypeShort".$objp->fk_type)?$langs->trans("PaymentTypeShort".$objp->fk_type):$objp->fk_type; + $type_label = ($langs->trans("PaymentTypeShort".$objp->fk_type) != "PaymentTypeShort".$objp->fk_type) ? $langs->trans("PaymentTypeShort".$objp->fk_type) : $objp->fk_type; } - $link=''; - if ($objp->fk_bordereau>0) { + $link = ''; + if ($objp->fk_bordereau > 0) { $remisestatic->id = $objp->fk_bordereau; $remisestatic->ref = $objp->ref; $link = ' '.$remisestatic->getNomUrl(1); } - print ''; + print ''; // Description print '
'.$langs->trans("Ref").''.$langs->trans("InitialBankBalance").'
'.price(($balancestart[$objp->numr]+$content[$objp->numr]), '', $langs, 1, -1, -1, $conf->currency).''.price(($balancestart[$objp->numr] + $content[$objp->numr]), '', $langs, 1, -1, -1, $conf->currency).''; if ($user->rights->banque->consolidate && $action != 'editbankreceipt') { @@ -360,16 +361,21 @@ else * Show list of bank statements */ - $mesprevnext=''; - $mesprevnext.=''; + // Onglets + $head = account_statement_prepare_head($object, $numref); + dol_fiche_head($head, 'statement', $langs->trans("FinancialAccount"), 0, 'account'); - $title=$langs->trans("AccountStatement").' '.$numref.' - '.$langs->trans("BankAccount").' '.$object->getNomUrl(1, 'receipts'); + + $mesprevnext = ''; + $mesprevnext .= ''; + + $title = $langs->trans("AccountStatement").' '.$numref.' - '.$langs->trans("BankAccount").' '.$object->getNomUrl(1, 'receipts'); print load_fiche_titre($title, $mesprevnext, 'title_bank.png'); //print_barre_liste($title, $page, $_SERVER["PHP_SELF"], $param, $sortfield, $sortorder, $massactionbutton, 0, $nbtotalofrecords, 'title_bank.png', 0, '', '', 0, 1); @@ -392,14 +398,14 @@ else // Calcul du solde de depart du releve $sql = "SELECT sum(b.amount) as amount"; - $sql.= " FROM ".MAIN_DB_PREFIX."bank as b"; - $sql.= " WHERE b.num_releve < '".$db->escape($numref)."'"; - $sql.= " AND b.fk_account = ".$object->id; + $sql .= " FROM ".MAIN_DB_PREFIX."bank as b"; + $sql .= " WHERE b.num_releve < '".$db->escape($numref)."'"; + $sql .= " AND b.fk_account = ".$object->id; - $resql=$db->query($sql); + $resql = $db->query($sql); if ($resql) { - $obj=$db->fetch_object($resql); + $obj = $db->fetch_object($resql); $total = $obj->amount; $db->free($resql); } @@ -431,142 +437,142 @@ else // Date de valeur print ''; - print dol_print_date($db->jdate($objp->dv), "day") .' '; + print dol_print_date($db->jdate($objp->dv), "day").' '; print ''; - print img_edit_remove() . " "; + print img_edit_remove()." "; print ''; - print img_edit_add() .""; + print img_edit_add().""; print "'.$type_label.' '.($objp->num_chq?$objp->num_chq:'').$link.''.$type_label.' '.($objp->num_chq ? $objp->num_chq : '').$link.''; - $reg=array(); - preg_match('/\((.+)\)/i', $objp->label, $reg); // Si texte entoure de parenthese on tente recherche de traduction - if ($reg[1] && $langs->trans($reg[1])!=$reg[1]) print $langs->trans($reg[1]); + $reg = array(); + preg_match('/\((.+)\)/i', $objp->label, $reg); // Si texte entoure de parenthese on tente recherche de traduction + if ($reg[1] && $langs->trans($reg[1]) != $reg[1]) print $langs->trans($reg[1]); else print $objp->label; print ''; /* * Ajout les liens (societe, company...) */ - $newline=1; + $newline = 1; $links = $object->get_url($objp->rowid); - foreach($links as $key=>$val) + foreach ($links as $key=>$val) { - if (! $newline) print ' - '; + if (!$newline) print ' - '; else print '
'; - if ($links[$key]['type']=='payment') + if ($links[$key]['type'] == 'payment') { - $paymentstatic->id=$links[$key]['url_id']; - $paymentstatic->ref=$langs->trans("Payment"); + $paymentstatic->id = $links[$key]['url_id']; + $paymentstatic->ref = $langs->trans("Payment"); print ' '.$paymentstatic->getNomUrl(1); - $newline=0; + $newline = 0; } - elseif ($links[$key]['type']=='payment_supplier') + elseif ($links[$key]['type'] == 'payment_supplier') { - $paymentsupplierstatic->id=$links[$key]['url_id']; - $paymentsupplierstatic->ref=$langs->trans("Payment"); + $paymentsupplierstatic->id = $links[$key]['url_id']; + $paymentsupplierstatic->ref = $langs->trans("Payment"); print ' '.$paymentsupplierstatic->getNomUrl(1); - $newline=0; + $newline = 0; } - elseif ($links[$key]['type']=='payment_sc') + elseif ($links[$key]['type'] == 'payment_sc') { print ''; print ' '.img_object($langs->trans('ShowPayment'), 'payment').' '; print $langs->trans("SocialContributionPayment"); print ''; - $newline=0; + $newline = 0; } - elseif ($links[$key]['type']=='payment_vat') + elseif ($links[$key]['type'] == 'payment_vat') { - $paymentvatstatic->id=$links[$key]['url_id']; - $paymentvatstatic->ref=$langs->trans("Payment"); + $paymentvatstatic->id = $links[$key]['url_id']; + $paymentvatstatic->ref = $langs->trans("Payment"); print ' '.$paymentvatstatic->getNomUrl(1); } - elseif ($links[$key]['type']=='payment_salary') + elseif ($links[$key]['type'] == 'payment_salary') { print ''; print ' '.img_object($langs->trans('ShowPayment'), 'payment').' '; print $langs->trans("Payment"); print ''; - $newline=0; + $newline = 0; } - elseif ($links[$key]['type']=='banktransfert') { + elseif ($links[$key]['type'] == 'banktransfert') { // Do not show link to transfer since there is no transfer card (avoid confusion). Can already be accessed from transaction detail. if ($objp->amount > 0) { $banklinestatic->fetch($links[$key]['url_id']); - $bankstatic->id=$banklinestatic->fk_account; - $bankstatic->label=$banklinestatic->bank_account_label; + $bankstatic->id = $banklinestatic->fk_account; + $bankstatic->label = $banklinestatic->bank_account_label; print ' ('.$langs->trans("from").' '; print $bankstatic->getNomUrl(1, 'transactions'); print ' '.$langs->trans("toward").' '; - $bankstatic->id=$objp->bankid; - $bankstatic->label=$objp->bankref; + $bankstatic->id = $objp->bankid; + $bankstatic->label = $objp->bankref; print $bankstatic->getNomUrl(1, ''); print ')'; } else { - $bankstatic->id=$objp->bankid; - $bankstatic->label=$objp->bankref; + $bankstatic->id = $objp->bankid; + $bankstatic->label = $objp->bankref; print ' ('.$langs->trans("from").' '; print $bankstatic->getNomUrl(1, ''); print ' '.$langs->trans("toward").' '; $banklinestatic->fetch($links[$key]['url_id']); - $bankstatic->id=$banklinestatic->fk_account; - $bankstatic->label=$banklinestatic->bank_account_label; + $bankstatic->id = $banklinestatic->fk_account; + $bankstatic->label = $banklinestatic->bank_account_label; print $bankstatic->getNomUrl(1, 'transactions'); print ')'; } } - elseif ($links[$key]['type']=='company') { + elseif ($links[$key]['type'] == 'company') { $societestatic->id = $links[$key]['url_id']; $societestatic->name = $links[$key]['label']; print $societestatic->getNomUrl(1, 'company', 24); - $newline=0; + $newline = 0; } - elseif ($links[$key]['type']=='member') { + elseif ($links[$key]['type'] == 'member') { print ''; print img_object($langs->trans('ShowMember'), 'user').' '; print $links[$key]['label']; print ''; - $newline=0; + $newline = 0; } - elseif ($links[$key]['type']=='user') { + elseif ($links[$key]['type'] == 'user') { print ''; print img_object($langs->trans('ShowUser'), 'user').' '; print $links[$key]['label']; print ''; - $newline=0; + $newline = 0; } - elseif ($links[$key]['type']=='sc') { + elseif ($links[$key]['type'] == 'sc') { print ''; print img_object($langs->trans('ShowBill'), 'bill').' '; print $langs->trans("SocialContribution"); print ''; - $newline=0; + $newline = 0; } else { print ''; print $links[$key]['label']; print ''; - $newline=0; + $newline = 0; } } @@ -574,18 +580,18 @@ else if ($ve) { $sql = "SELECT label"; - $sql.= " FROM ".MAIN_DB_PREFIX."bank_categ as ct"; - $sql.= ", ".MAIN_DB_PREFIX."bank_class as cl"; - $sql.= " WHERE ct.rowid = cl.fk_categ"; - $sql.= " AND ct.entity = ".$conf->entity; - $sql.= " AND cl.lineid = ".$objp->rowid; + $sql .= " FROM ".MAIN_DB_PREFIX."bank_categ as ct"; + $sql .= ", ".MAIN_DB_PREFIX."bank_class as cl"; + $sql .= " WHERE ct.rowid = cl.fk_categ"; + $sql .= " AND ct.entity = ".$conf->entity; + $sql .= " AND cl.lineid = ".$objp->rowid; $resc = $db->query($sql); if ($resc) { $numc = $db->num_rows($resc); $ii = 0; - if ($numc && ! $newline) print '
'; + if ($numc && !$newline) print '
'; while ($ii < $numc) { $objc = $db->fetch_object($resc); diff --git a/htdocs/compta/bank/transfer.php b/htdocs/compta/bank/transfer.php index ad21fe07df4..7ce6763b8e0 100644 --- a/htdocs/compta/bank/transfer.php +++ b/htdocs/compta/bank/transfer.php @@ -238,7 +238,7 @@ print ''; print ''; -print ''; +print '
'; print ''; print ''; print ''; diff --git a/htdocs/compta/bank/various_payment/card.php b/htdocs/compta/bank/various_payment/card.php index 30472729d92..ab93b2f0f97 100644 --- a/htdocs/compta/bank/various_payment/card.php +++ b/htdocs/compta/bank/various_payment/card.php @@ -30,7 +30,7 @@ require_once DOL_DOCUMENT_ROOT.'/compta/bank/class/account.class.php'; require_once DOL_DOCUMENT_ROOT.'/core/class/html.formaccounting.class.php'; require_once DOL_DOCUMENT_ROOT.'/accountancy/class/accountingaccount.class.php'; require_once DOL_DOCUMENT_ROOT.'/accountancy/class/accountingjournal.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,12 +48,11 @@ $backtopage = GETPOST('backtopage', 'alpha'); $accountid = GETPOST("accountid") > 0 ? GETPOST("accountid", "int") : 0; $label = GETPOST("label", "alpha"); $sens = GETPOST("sens", "int"); -$amount = GETPOST("amount", "alpha"); +$amount = price2num(GETPOST("amount", "alpha")); $paymenttype = GETPOST("paymenttype", "int"); $accountancy_code = GETPOST("accountancy_code", "alpha"); $subledger_account = GETPOST("subledger_account", "alpha"); $projectid = (GETPOST('projectid', 'int') ? GETPOST('projectid', 'int') : GETPOST('fk_project', 'int')); -$category_transaction = GETPOST("category_transaction", 'alpha'); // Security check $socid = GETPOST("socid", "int"); @@ -86,39 +85,39 @@ if (empty($reshook)) { if ($action != 'addlink') { - $urltogo=$backtopage?$backtopage:dol_buildpath('/compta/bank/various_payment/list.php', 1); + $urltogo = $backtopage ? $backtopage : dol_buildpath('/compta/bank/various_payment/list.php', 1); header("Location: ".$urltogo); exit; } - if ($id > 0 || ! empty($ref)) $ret = $object->fetch($id, $ref); - $action=''; + if ($id > 0 || !empty($ref)) $ret = $object->fetch($id, $ref); + $action = ''; } if ($action == 'add') { - $error=0; + $error = 0; - $datep=dol_mktime(12, 0, 0, GETPOST("datepmonth", 'int'), GETPOST("datepday", 'int'), GETPOST("datepyear", 'int')); - $datev=dol_mktime(12, 0, 0, GETPOST("datevmonth", 'int'), GETPOST("datevday", 'int'), GETPOST("datevyear", 'int')); - if (empty($datev)) $datev=$datep; + $datep = dol_mktime(12, 0, 0, GETPOST("datepmonth", 'int'), GETPOST("datepday", 'int'), GETPOST("datepyear", 'int')); + $datev = dol_mktime(12, 0, 0, GETPOST("datevmonth", 'int'), GETPOST("datevday", 'int'), GETPOST("datevyear", 'int')); + if (empty($datev)) $datev = $datep; - $object->ref=''; // TODO - $object->accountid=GETPOST("accountid", 'int') > 0 ? GETPOST("accountid", "int") : 0; - $object->datev=$datev; - $object->datep=$datep; - $object->amount=price2num(GETPOST("amount", 'alpha')); - $object->label=GETPOST("label", 'none'); - $object->note=GETPOST("note", 'none'); - $object->type_payment=GETPOST("paymenttype", 'int') > 0 ? GETPOST("paymenttype", "int") : 0; - $object->num_payment=GETPOST("num_payment", 'alpha'); - $object->fk_user_author=$user->id; - $object->category_transaction=GETPOST("category_transaction", 'alpha'); + $object->ref = ''; // TODO + $object->accountid = GETPOST("accountid", 'int') > 0 ? GETPOST("accountid", "int") : 0; + $object->datev = $datev; + $object->datep = $datep; + $object->amount = price2num(GETPOST("amount", 'alpha')); + $object->label = GETPOST("label", 'none'); + $object->note = GETPOST("note", 'none'); + $object->type_payment = GETPOST("paymenttype", 'int') > 0 ? GETPOST("paymenttype", "int") : 0; + $object->num_payment = GETPOST("num_payment", 'alpha'); + $object->fk_user_author = $user->id; + $object->category_transaction = GETPOST("category_transaction", 'alpha'); - $object->accountancy_code=GETPOST("accountancy_code") > 0 ? GETPOST("accountancy_code", "alpha") : ""; - $object->subledger_account=GETPOST("subledger_account") > 0 ? GETPOST("subledger_account", "alpha") : ""; + $object->accountancy_code = GETPOST("accountancy_code") > 0 ? GETPOST("accountancy_code", "alpha") : ""; + $object->subledger_account = GETPOST("subledger_account") > 0 ? GETPOST("subledger_account", "alpha") : ""; - $object->sens=GETPOST('sens'); - $object->fk_project= GETPOST('fk_project', 'int'); + $object->sens = GETPOST('sens'); + $object->fk_project = GETPOST('fk_project', 'int'); if (empty($datep) || empty($datev)) { @@ -138,29 +137,29 @@ if (empty($reshook)) setEventMessages($langs->trans("ErrorFieldRequired", $langs->transnoentitiesnoconv("Amount")), null, 'errors'); $error++; } - if (! empty($conf->banque->enabled) && ! $object->accountid > 0) + if (!empty($conf->banque->enabled) && !$object->accountid > 0) { $langs->load('errors'); setEventMessages($langs->trans("ErrorFieldRequired", $langs->transnoentitiesnoconv("BankAccount")), null, 'errors'); $error++; } // TODO Remove this and allow instead to edit a various payment to enter accounting code - if (! empty($conf->accounting->enabled) && ! $object->accountancy_code) + if (!empty($conf->accounting->enabled) && !$object->accountancy_code) { $langs->load('errors'); setEventMessages($langs->trans("ErrorFieldRequired", $langs->transnoentitiesnoconv("AccountAccounting")), null, 'errors'); $error++; } - if (! $error) + if (!$error) { $db->begin(); - $ret=$object->create($user); + $ret = $object->create($user); if ($ret > 0) { $db->commit(); - $urltogo=($backtopage ? $backtopage : DOL_URL_ROOT.'/compta/bank/various_payment/list.php'); + $urltogo = ($backtopage ? $backtopage : DOL_URL_ROOT.'/compta/bank/various_payment/list.php'); header("Location: ".$urltogo); exit; } @@ -168,29 +167,29 @@ if (empty($reshook)) { $db->rollback(); setEventMessages($object->error, $object->errors, 'errors'); - $action="create"; + $action = "create"; } } - $action='create'; + $action = 'create'; } if ($action == 'delete') { - $result=$object->fetch($id); + $result = $object->fetch($id); if ($object->rappro == 0) { $db->begin(); - $ret=$object->delete($user); + $ret = $object->delete($user); 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) + $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) @@ -201,7 +200,7 @@ if (empty($reshook)) } else { - $object->error=$accountline->error; + $object->error = $accountline->error; $db->rollback(); setEventMessages($object->error, $object->errors, 'errors'); } @@ -227,8 +226,8 @@ if (empty($reshook)) llxHeader("", $langs->trans("VariousPayment")); $form = new Form($db); -if (! empty($conf->accounting->enabled)) $formaccounting = new FormAccounting($db); -if (! empty($conf->projet->enabled)) $formproject = new FormProjets($db); +if (!empty($conf->accounting->enabled)) $formaccounting = new FormAccounting($db); +if (!empty($conf->projet->enabled)) $formproject = new FormProjets($db); if ($id) { @@ -267,30 +266,30 @@ if ($action == 'create') dol_fiche_head('', ''); - print '
'.$langs->trans("TransferFrom").''.$langs->trans("TransferTo").''.$langs->trans("Date").''.$langs->trans("Description").''.$langs->trans("Amount").'
'; + print '
'; // Date payment print ''; // Date value for bank print ''; // Label print ''; // Sens print ''; @@ -301,11 +300,11 @@ if ($action == 'create') print ''; // Bank - if (! empty($conf->banque->enabled)) + if (!empty($conf->banque->enabled)) { print ''; } @@ -316,7 +315,7 @@ if ($action == 'create') print ''; // Number - if (! empty($conf->banque->enabled)) + if (!empty($conf->banque->enabled)) { // Number print ''; } // Other attributes - $parameters=array(); - $reshook=$hookmanager->executeHooks('formObjectOptions', $parameters, $object, $action); // Note that $action and $object may have been modified by hook + $parameters = array(); + $reshook = $hookmanager->executeHooks('formObjectOptions', $parameters, $object, $action); // Note that $action and $object may have been modified by hook print $hookmanager->resPrint; - print ''; - // Category if (is_array($options) && count($options) && $conf->categorie->enabled) { @@ -356,7 +353,7 @@ if ($action == 'create') } // Accountancy account - if (! empty($conf->accounting->enabled)) + if (!empty($conf->accounting->enabled)) { // TODO Remove the fieldrequired and allow instead to edit a various payment to enter accounting code print ''; @@ -372,11 +369,11 @@ if ($action == 'create') } // Subledger account - if (! empty($conf->accounting->enabled)) + if (!empty($conf->accounting->enabled)) { print ''; print ''; - print ''; + print ''; + print ''; print ''; // Multicurrency Amount VAT - print ''; - print ''; + print ''; + print ''; print ''; // Multicurrency Amount TTC - print ''; - print ''; + print ''; + print ''; print ''; } // Total $alert = ''; - if (! empty($conf->global->ORDER_MANAGE_MIN_AMOUNT) && $object->total_ht < $object->thirdparty->supplier_order_min_amount) { - $alert = ' ' . img_warning($langs->trans('OrderMinAmount').': '.price($object->thirdparty->supplier_order_min_amount)); + if (!empty($conf->global->ORDER_MANAGE_MIN_AMOUNT) && $object->total_ht < $object->thirdparty->supplier_order_min_amount) { + $alert = ' '.img_warning($langs->trans('OrderMinAmount').': '.price($object->thirdparty->supplier_order_min_amount)); } print ''; print ''; @@ -2235,13 +2232,13 @@ elseif (! empty($object->id)) print ''; // Amount Local Taxes - if ($mysoc->localtax1_assuj=="1" || $object->total_localtax1 != 0) //Localtax1 + if ($mysoc->localtax1_assuj == "1" || $object->total_localtax1 != 0) //Localtax1 { print ''; print ''; print ''; } - if ($mysoc->localtax2_assuj=="1" || $object->total_localtax2 != 0) //Localtax2 + if ($mysoc->localtax2_assuj == "1" || $object->total_localtax2 != 0) //Localtax2 { print ''; print ''; @@ -2266,14 +2263,14 @@ elseif (! empty($object->id)) print '

'; - 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'); @@ -2286,16 +2283,16 @@ elseif (! empty($object->id)) //$result = $object->getLinesArray(); - print ' + print ' - + '; - if (! empty($conf->use_javascript_ajax) && $object->statut == 0) { - include DOL_DOCUMENT_ROOT . '/core/tpl/ajaxrow.tpl.php'; + if (!empty($conf->use_javascript_ajax) && $object->statut == 0) { + include DOL_DOCUMENT_ROOT.'/core/tpl/ajaxrow.tpl.php'; } print '
'; @@ -2303,13 +2300,13 @@ elseif (! empty($object->id)) // Add free products/services form 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. + $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_NOPRICEDEFINED)) $senderissupplier=2; - 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); @@ -2345,15 +2342,15 @@ elseif (! empty($object->id)) // modified by hook if (empty($reshook)) { - $object->fetchObjectLinked(); // Links are used to show or not button, so we load them now. + $object->fetchObjectLinked(); // Links are used to show or not button, so we load them now. // Validate if ($object->statut == 0 && $num > 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))) + 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))) { - $tmpbuttonlabel=$langs->trans('Validate'); + $tmpbuttonlabel = $langs->trans('Validate'); if ($user->rights->fournisseur->commande->approuver && empty($conf->global->SUPPLIER_ORDER_NO_DIRECT_APPROVE)) $tmpbuttonlabel = $langs->trans("ValidateAndApprove"); print ''; @@ -2381,7 +2378,7 @@ elseif (! empty($object->id)) { if ($user->rights->fournisseur->commande->approuver) { - if (! empty($conf->global->SUPPLIER_ORDER_3_STEPS_TO_BE_APPROVED) && $conf->global->MAIN_FEATURES_LEVEL > 0 && $object->total_ht >= $conf->global->SUPPLIER_ORDER_3_STEPS_TO_BE_APPROVED && ! empty($object->user_approve_id)) + if (!empty($conf->global->SUPPLIER_ORDER_3_STEPS_TO_BE_APPROVED) && $conf->global->MAIN_FEATURES_LEVEL > 0 && $object->total_ht >= $conf->global->SUPPLIER_ORDER_3_STEPS_TO_BE_APPROVED && !empty($object->user_approve_id)) { print ''.$langs->trans("ApproveOrder").''; } @@ -2397,13 +2394,13 @@ elseif (! empty($object->id)) } // Second approval (if option SUPPLIER_ORDER_3_STEPS_TO_BE_APPROVED is set) - if (! empty($conf->global->SUPPLIER_ORDER_3_STEPS_TO_BE_APPROVED) && $conf->global->MAIN_FEATURES_LEVEL > 0 && $object->total_ht >= $conf->global->SUPPLIER_ORDER_3_STEPS_TO_BE_APPROVED) + if (!empty($conf->global->SUPPLIER_ORDER_3_STEPS_TO_BE_APPROVED) && $conf->global->MAIN_FEATURES_LEVEL > 0 && $object->total_ht >= $conf->global->SUPPLIER_ORDER_3_STEPS_TO_BE_APPROVED) { if ($object->statut == CommandeFournisseur::STATUS_VALIDATED) { if ($user->rights->fournisseur->commande->approve2) { - if (! empty($object->user_approve_id2)) + if (!empty($object->user_approve_id2)) { print ''.$langs->trans("Approve2Order").''; } @@ -2444,20 +2441,20 @@ elseif (! empty($object->id)) // Reopen if (in_array($object->statut, array(CommandeFournisseur::STATUS_ACCEPTED))) { - $buttonshown=0; - if (! $buttonshown && $user->rights->fournisseur->commande->approuver) + $buttonshown = 0; + if (!$buttonshown && $user->rights->fournisseur->commande->approuver) { 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 ''.$langs->trans("Disapprove").''; $buttonshown++; } } - if (! $buttonshown && $user->rights->fournisseur->commande->approve2 && ! empty($conf->global->SUPPLIER_ORDER_3_STEPS_TO_BE_APPROVED)) + if (!$buttonshown && $user->rights->fournisseur->commande->approve2 && !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 ''.$langs->trans("Disapprove").''; } @@ -2473,13 +2470,13 @@ elseif (! empty($object->id)) // 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))) { - if (in_array($object->statut, array(3,4,5))) { + if (in_array($object->statut, array(3, 4, 5))) { if ($conf->fournisseur->enabled && $user->rights->fournisseur->commande->receptionner) { - print ''; + print ''; } else { - print ''; + print ''; } } } @@ -2508,7 +2505,7 @@ elseif (! empty($object->id)) // 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 (!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) { @@ -2541,7 +2538,7 @@ elseif (! empty($object->id)) } // 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 ''.$langs->trans('CreateRemoteOrder').''; } @@ -2562,7 +2559,7 @@ elseif (! empty($object->id)) } // Delete - if (! empty($user->rights->fournisseur->commande->supprimer) || ($object->statut == CommandeFournisseur::STATUS_DRAFT && ! empty($user->rights->fournisseur->commande->creer))) + if (!empty($user->rights->fournisseur->commande->supprimer) || ($object->statut == CommandeFournisseur::STATUS_DRAFT && !empty($user->rights->fournisseur->commande->creer))) { print ''.$langs->trans("Delete").''; } @@ -2585,7 +2582,7 @@ elseif (! empty($object->id)) //print '
'; print ''; @@ -2612,25 +2609,25 @@ elseif (! empty($object->id)) // Generated documents $comfournref = dol_sanitizeFileName($object->ref); - $file = $conf->fournisseur->dir_output . '/commande/' . $comfournref . '/' . $comfournref . '.pdf'; - $relativepath = $comfournref.'/'.$comfournref.'.pdf'; - $filedir = $conf->fournisseur->dir_output . '/commande/' . $comfournref; - $urlsource=$_SERVER["PHP_SELF"]."?id=".$object->id; - $genallowed=$user->rights->fournisseur->commande->lire; - $delallowed=$user->rights->fournisseur->commande->creer; + $file = $conf->fournisseur->dir_output.'/commande/'.$comfournref.'/'.$comfournref.'.pdf'; + $relativepath = $comfournref.'/'.$comfournref.'.pdf'; + $filedir = $conf->fournisseur->dir_output.'/commande/'.$comfournref; + $urlsource = $_SERVER["PHP_SELF"]."?id=".$object->id; + $genallowed = $user->rights->fournisseur->commande->lire; + $delallowed = $user->rights->fournisseur->commande->creer; print $formfile->showdocuments('commande_fournisseur', $comfournref, $filedir, $urlsource, $genallowed, $delallowed, $object->modelpdf, 1, 0, 0, 0, 0, '', '', '', $object->thirdparty->default_lang); - $somethingshown=$formfile->numoffiles; + $somethingshown = $formfile->numoffiles; // Show links to link elements - $linktoelem = $form->showLinkToObjectBlock($object, null, array('supplier_order','order_supplier')); + $linktoelem = $form->showLinkToObjectBlock($object, null, array('supplier_order', 'order_supplier')); $somethingshown = $form->showLinkedObjectBlock($object, $linktoelem); print '
'; if ($action == 'classifyreception') { - if ($user->rights->fournisseur->commande->receptionner && ($object->statut == CommandeFournisseur::STATUS_ORDERSENT || $object->statut == CommandeFournisseur::STATUS_RECEIVED_PARTIALLY)) + if ($user->rights->fournisseur->commande->receptionner && ($object->statut == CommandeFournisseur::STATUS_ORDERSENT || $object->statut == CommandeFournisseur::STATUS_RECEIVED_PARTIALLY)) { // Set status to received (action=livraison) print ''."\n"; @@ -2667,8 +2664,8 @@ elseif (! empty($object->id)) // List of actions on element include_once DOL_DOCUMENT_ROOT.'/core/class/html.formactions.class.php'; - $formactions=new FormActions($db); - $somethingshown = $formactions->showactions($object, 'order_supplier', $socid, 1, 'listaction'.($genallowed?'largetitle':'')); + $formactions = new FormActions($db); + $somethingshown = $formactions->showactions($object, 'order_supplier', $socid, 1, 'listaction'.($genallowed ? 'largetitle' : '')); print '
'; } @@ -2676,7 +2673,7 @@ elseif (! empty($object->id)) /* * 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; @@ -2750,7 +2747,7 @@ elseif (! empty($object->id)) //Create SOAP client and connect it to user $soapclient_user = new nusoap_client($ws_url."/webservices/server_user.php"); - $soapclient_user->soap_defencoding='UTF-8'; + $soapclient_user->soap_defencoding = 'UTF-8'; $soapclient_user->decodeUTF8(false); //Get the thirdparty associated to user @@ -2773,7 +2770,7 @@ elseif (! empty($object->id)) { //Create SOAP client and connect it to product/service $soapclient_product = new nusoap_client($ws_url."/webservices/server_productorservice.php"); - $soapclient_product->soap_defencoding='UTF-8'; + $soapclient_product->soap_defencoding = 'UTF-8'; $soapclient_product->decodeUTF8(false); // Iterate each line and get the reference that uses the supplier of that product/service @@ -2821,9 +2818,9 @@ elseif (! empty($object->id)) $product_fourn = new ProductFournisseur($db); $product_fourn_list = $product_fourn->list_product_fournisseur_price($line->fk_product); - if (count($product_fourn_list)>0) + if (count($product_fourn_list) > 0) { - foreach($product_fourn_list as $product_fourn_line) + 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) { @@ -2888,10 +2885,10 @@ elseif (! empty($object->id)) } // Presend form - $modelmail='order_supplier_send'; - $defaulttopic='SendOrderRef'; + $modelmail = 'order_supplier_send'; + $defaulttopic = 'SendOrderRef'; $diroutput = $conf->fournisseur->commande->dir_output; - $autocopy='MAIN_MAIL_AUTOCOPY_SUPPLIER_ORDER_TO'; + $autocopy = 'MAIN_MAIL_AUTOCOPY_SUPPLIER_ORDER_TO'; $trackid = 'sor'.$object->id; include DOL_DOCUMENT_ROOT.'/core/tpl/card_presend.tpl.php'; diff --git a/htdocs/fourn/commande/contact.php b/htdocs/fourn/commande/contact.php index 63a2935212e..3f8a7693e12 100644 --- a/htdocs/fourn/commande/contact.php +++ b/htdocs/fourn/commande/contact.php @@ -85,7 +85,7 @@ elseif ($action == 'swapstatut' && $user->rights->fournisseur->commande->creer) { if ($object->fetch($id)) { - $result=$object->swapContactStatus(GETPOST('ligne')); + $result = $object->swapContactStatus(GETPOST('ligne')); } else { @@ -114,13 +114,13 @@ elseif ($action == 'deletecontact' && $user->rights->fournisseur->commande->cree /* * View */ -$help_url='EN:Module_Suppliers_Orders|FR:CommandeFournisseur|ES:Módulo_Pedidos_a_proveedores'; +$help_url = 'EN:Module_Suppliers_Orders|FR:CommandeFournisseur|ES:Módulo_Pedidos_a_proveedores'; llxHeader('', $langs->trans("Order"), $help_url); $form = new Form($db); $formcompany = new FormCompany($db); -$contactstatic=new Contact($db); -$userstatic=new User($db); +$contactstatic = new Contact($db); +$userstatic = new User($db); /* *************************************************************************** */ @@ -129,7 +129,7 @@ $userstatic=new User($db); /* */ /* *************************************************************************** */ -if ($id > 0 || ! empty($ref)) +if ($id > 0 || !empty($ref)) { $langs->trans("OrderCard"); diff --git a/htdocs/fourn/commande/dispatch.php b/htdocs/fourn/commande/dispatch.php index 0d9782b3683..7990e6f8083 100644 --- a/htdocs/fourn/commande/dispatch.php +++ b/htdocs/fourn/commande/dispatch.php @@ -31,19 +31,19 @@ */ require '../../main.inc.php'; -require_once DOL_DOCUMENT_ROOT . '/core/modules/supplier_order/modules_commandefournisseur.php'; -require_once DOL_DOCUMENT_ROOT . '/product/stock/class/entrepot.class.php'; -require_once DOL_DOCUMENT_ROOT . '/core/lib/fourn.lib.php'; -require_once DOL_DOCUMENT_ROOT . '/fourn/class/fournisseur.commande.class.php'; -require_once DOL_DOCUMENT_ROOT . '/fourn/class/fournisseur.commande.dispatch.class.php'; -require_once DOL_DOCUMENT_ROOT . '/product/class/html.formproduct.class.php'; -if (! empty($conf->projet->enabled)) - require_once DOL_DOCUMENT_ROOT . '/projet/class/project.class.php'; +require_once DOL_DOCUMENT_ROOT.'/core/modules/supplier_order/modules_commandefournisseur.php'; +require_once DOL_DOCUMENT_ROOT.'/product/stock/class/entrepot.class.php'; +require_once DOL_DOCUMENT_ROOT.'/core/lib/fourn.lib.php'; +require_once DOL_DOCUMENT_ROOT.'/fourn/class/fournisseur.commande.class.php'; +require_once DOL_DOCUMENT_ROOT.'/fourn/class/fournisseur.commande.dispatch.class.php'; +require_once DOL_DOCUMENT_ROOT.'/product/class/html.formproduct.class.php'; +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")); +$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 @@ -68,7 +68,7 @@ if ($_GET["projectid"]) $object = new CommandeFournisseur($db); -if ($id > 0 || ! empty($ref)) { +if ($id > 0 || !empty($ref)) { $result = $object->fetch($id, $ref); if ($result < 0) { setEventMessages($object->error, $object->errors, 'errors'); @@ -84,26 +84,26 @@ if ($id > 0 || ! empty($ref)) { * Actions */ -$parameters=array(); -$reshook=$hookmanager->executeHooks('doActions', $parameters, $object, $action); // Note that $action and $object may have been modified by some hooks +$parameters = array(); +$reshook = $hookmanager->executeHooks('doActions', $parameters, $object, $action); // Note that $action and $object may have been modified by some hooks if ($reshook < 0) setEventMessages($hookmanager->error, $hookmanager->errors, 'errors'); -if ($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; + $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) { @@ -113,16 +113,16 @@ 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'); - $error ++; + $error++; $action = ''; } } - if (! $error) + if (!$error) { $db->commit(); } @@ -132,40 +132,40 @@ if ($action == 'checkdispatchline' && ! ((empty($conf->global->MAIN_USE_ADVANCED } } -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; + $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'); - $error ++; + $error++; $action = ''; } } - if (! $error) + if (!$error) { $result = $object->calcAndSetStatusDispatch($user); if ($result < 0) { setEventMessages($object->error, $object->errors, 'errors'); - $error ++; + $error++; $action = ''; } } - if (! $error) + if (!$error) { $db->commit(); } @@ -175,40 +175,40 @@ if ($action == 'uncheckdispatchline' && ! ((empty($conf->global->MAIN_USE_ADVANC } } -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; + $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'); - $error ++; + $error++; $action = ''; } } - if (! $error) + if (!$error) { $result = $object->calcAndSetStatusDispatch($user); if ($result < 0) { setEventMessages($object->error, $object->errors, 'errors'); - $error ++; + $error++; $action = ''; } } - if (! $error) + if (!$error) { $db->commit(); } @@ -229,54 +229,54 @@ if ($action == 'dispatch' && $user->rights->fournisseur->commande->receptionner) // without batch module enabled if (preg_match('/^product_([0-9]+)_([0-9]+)$/i', $key, $reg)) { - $pos ++; + $pos++; // $numline=$reg[2] + 1; // line of product $numline = $pos; - $prod = "product_" . $reg[1] . '_' . $reg[2]; - $qty = "qty_" . $reg[1] . '_' . $reg[2]; - $ent = "entrepot_" . $reg[1] . '_' . $reg[2]; - $pu = "pu_" . $reg[1] . '_' . $reg[2]; // This is unit price including discount - $fk_commandefourndet = "fk_commandefourndet_" . $reg[1] . '_' . $reg[2]; + $prod = "product_".$reg[1].'_'.$reg[2]; + $qty = "qty_".$reg[1].'_'.$reg[2]; + $ent = "entrepot_".$reg[1].'_'.$reg[2]; + $pu = "pu_".$reg[1].'_'.$reg[2]; // This is unit price including discount + $fk_commandefourndet = "fk_commandefourndet_".$reg[1].'_'.$reg[2]; - if (! empty($conf->global->SUPPLIER_ORDER_CAN_UPDATE_BUYINGPRICE_DURING_RECEIPT)) { + if (!empty($conf->global->SUPPLIER_ORDER_CAN_UPDATE_BUYINGPRICE_DURING_RECEIPT)) { if (empty($conf->multicurrency->enabled) && empty($conf->dynamicprices->enabled)) { - $dto = GETPOST("dto_" . $reg[1] . '_' . $reg[2]); - if (! empty($dto)) { - $unit_price = price2num(GETPOST("pu_" . $reg[1]) * (100 - $dto) / 100, 'MU'); + $dto = GETPOST("dto_".$reg[1].'_'.$reg[2]); + if (!empty($dto)) { + $unit_price = price2num(GETPOST("pu_".$reg[1]) * (100 - $dto) / 100, 'MU'); } - $saveprice = "saveprice_" . $reg[1] . '_' . $reg[2]; + $saveprice = "saveprice_".$reg[1].'_'.$reg[2]; } } // We ask to move a qty if (GETPOST($qty) != 0) { - if (! (GETPOST($ent, 'int') > 0)) { - dol_syslog('No dispatch for line ' . $key . ' as no warehouse was chosen.'); - $text = $langs->transnoentities('Warehouse') . ', ' . $langs->transnoentities('Line') . ' ' . ($numline); + if (!(GETPOST($ent, 'int') > 0)) { + dol_syslog('No dispatch for line '.$key.' as no warehouse was chosen.'); + $text = $langs->transnoentities('Warehouse').', '.$langs->transnoentities('Line').' '.($numline); setEventMessages($langs->trans('ErrorFieldRequired', $text), null, 'errors'); - $error ++; + $error++; } - if (! $error) { + if (!$error) { $result = $object->dispatchProduct($user, GETPOST($prod, 'int'), GETPOST($qty), GETPOST($ent, 'int'), GETPOST($pu), GETPOST('comment'), '', '', '', GETPOST($fk_commandefourndet, 'int'), $notrigger); if ($result < 0) { setEventMessages($object->error, $object->errors, 'errors'); - $error ++; + $error++; } - if (! $error && ! empty($conf->global->SUPPLIER_ORDER_CAN_UPDATE_BUYINGPRICE_DURING_RECEIPT)) { + if (!$error && !empty($conf->global->SUPPLIER_ORDER_CAN_UPDATE_BUYINGPRICE_DURING_RECEIPT)) { if (empty($conf->multicurrency->enabled) && empty($conf->dynamicprices->enabled)) { - $dto = GETPOST("dto_" . $reg[1] . '_' . $reg[2]); + $dto = GETPOST("dto_".$reg[1].'_'.$reg[2]); //update supplier price if (isset($_POST[$saveprice])) { // TODO Use class - $sql = "UPDATE " . MAIN_DB_PREFIX . "product_fournisseur_price"; - $sql .= " SET unitprice='" . GETPOST($pu) . "'"; - $sql .= ", price=" . GETPOST($pu) . "*quantity"; - $sql .= ", remise_percent='" . $dto . "'"; - $sql .= " WHERE fk_soc=" . $object->socid; - $sql .= " AND fk_product=" . GETPOST($prod, 'int'); + $sql = "UPDATE ".MAIN_DB_PREFIX."product_fournisseur_price"; + $sql .= " SET unitprice='".GETPOST($pu)."'"; + $sql .= ", price=".GETPOST($pu)."*quantity"; + $sql .= ", remise_percent='".$dto."'"; + $sql .= " WHERE fk_soc=".$object->socid; + $sql .= " AND fk_product=".GETPOST($prod, 'int'); $resql = $db->query($sql); } @@ -288,58 +288,58 @@ if ($action == 'dispatch' && $user->rights->fournisseur->commande->receptionner) // with batch module enabled if (preg_match('/^product_batch_([0-9]+)_([0-9]+)$/i', $key, $reg)) { - $pos ++; + $pos++; // eat-by date dispatch // $numline=$reg[2] + 1; // line of product $numline = $pos; - $prod = 'product_batch_' . $reg[1] . '_' . $reg[2]; - $qty = 'qty_' . $reg[1] . '_' . $reg[2]; - $ent = 'entrepot_' . $reg[1] . '_' . $reg[2]; - $pu = 'pu_' . $reg[1] . '_' . $reg[2]; - $fk_commandefourndet = 'fk_commandefourndet_' . $reg[1] . '_' . $reg[2]; - $lot = 'lot_number_' . $reg[1] . '_' . $reg[2]; - $dDLUO = dol_mktime(12, 0, 0, $_POST['dluo_' . $reg[1] . '_' . $reg[2] . 'month'], $_POST['dluo_' . $reg[1] . '_' . $reg[2] . 'day'], $_POST['dluo_' . $reg[1] . '_' . $reg[2] . 'year']); - $dDLC = dol_mktime(12, 0, 0, $_POST['dlc_' . $reg[1] . '_' . $reg[2] . 'month'], $_POST['dlc_' . $reg[1] . '_' . $reg[2] . 'day'], $_POST['dlc_' . $reg[1] . '_' . $reg[2] . 'year']); + $prod = 'product_batch_'.$reg[1].'_'.$reg[2]; + $qty = 'qty_'.$reg[1].'_'.$reg[2]; + $ent = 'entrepot_'.$reg[1].'_'.$reg[2]; + $pu = 'pu_'.$reg[1].'_'.$reg[2]; + $fk_commandefourndet = 'fk_commandefourndet_'.$reg[1].'_'.$reg[2]; + $lot = 'lot_number_'.$reg[1].'_'.$reg[2]; + $dDLUO = dol_mktime(12, 0, 0, $_POST['dluo_'.$reg[1].'_'.$reg[2].'month'], $_POST['dluo_'.$reg[1].'_'.$reg[2].'day'], $_POST['dluo_'.$reg[1].'_'.$reg[2].'year']); + $dDLC = dol_mktime(12, 0, 0, $_POST['dlc_'.$reg[1].'_'.$reg[2].'month'], $_POST['dlc_'.$reg[1].'_'.$reg[2].'day'], $_POST['dlc_'.$reg[1].'_'.$reg[2].'year']); - $fk_commandefourndet = 'fk_commandefourndet_' . $reg[1] . '_' . $reg[2]; + $fk_commandefourndet = 'fk_commandefourndet_'.$reg[1].'_'.$reg[2]; // We ask to move a qty if (GETPOST($qty) > 0) { - if (! (GETPOST($ent, 'int') > 0)) { - dol_syslog('No dispatch for line ' . $key . ' as no warehouse was chosen.'); - $text = $langs->transnoentities('Warehouse') . ', ' . $langs->transnoentities('Line') . ' ' . ($numline) . '-' . ($reg[1] + 1); + if (!(GETPOST($ent, 'int') > 0)) { + dol_syslog('No dispatch for line '.$key.' as no warehouse was chosen.'); + $text = $langs->transnoentities('Warehouse').', '.$langs->transnoentities('Line').' '.($numline).'-'.($reg[1] + 1); setEventMessages($langs->trans('ErrorFieldRequired', $text), null, 'errors'); - $error ++; + $error++; } - if (! (GETPOST($lot, 'alpha') || $dDLUO || $dDLC)) { - dol_syslog('No dispatch for line ' . $key . ' as serial/eat-by/sellby date are not set'); - $text = $langs->transnoentities('atleast1batchfield') . ', ' . $langs->transnoentities('Line') . ' ' . ($numline) . '-' . ($reg[1] + 1); + if (!(GETPOST($lot, 'alpha') || $dDLUO || $dDLC)) { + dol_syslog('No dispatch for line '.$key.' as serial/eat-by/sellby date are not set'); + $text = $langs->transnoentities('atleast1batchfield').', '.$langs->transnoentities('Line').' '.($numline).'-'.($reg[1] + 1); setEventMessages($langs->trans('ErrorFieldRequired', $text), null, 'errors'); - $error ++; + $error++; } - if (! $error) { + if (!$error) { $result = $object->dispatchProduct($user, GETPOST($prod, 'int'), GETPOST($qty), GETPOST($ent, 'int'), GETPOST($pu), GETPOST('comment'), $dDLC, $dDLUO, GETPOST($lot, 'alpha'), GETPOST($fk_commandefourndet, 'int'), $notrigger); if ($result < 0) { setEventMessages($object->error, $object->errors, 'errors'); - $error ++; + $error++; } } } } } - if (! $error) { - $result = $object->calcAndSetStatusDispatch($user, GETPOST('closeopenorder')?1:0, GETPOST('comment')); + if (!$error) { + $result = $object->calcAndSetStatusDispatch($user, GETPOST('closeopenorder') ? 1 : 0, GETPOST('comment')); if ($result < 0) { setEventMessages($object->error, $object->errors, 'errors'); - $error ++; + $error++; } } - if (! $notrigger && ! $error) { + if (!$notrigger && !$error) { global $conf, $langs, $user; // Call trigger @@ -348,14 +348,14 @@ if ($action == 'dispatch' && $user->rights->fournisseur->commande->receptionner) if ($result < 0) { setEventMessages($object->error, $object->errors, 'errors'); - $error ++; + $error++; } } - if ($result >= 0 && ! $error) { + if ($result >= 0 && !$error) { $db->commit(); - header("Location: dispatch.php?id=" . $id); + header("Location: dispatch.php?id=".$id); exit(); } else { $db->rollback(); @@ -374,10 +374,10 @@ $formproduct = new FormProduct($db); $warehouse_static = new Entrepot($db); $supplierorderdispatch = new CommandeFournisseurDispatch($db); -$help_url='EN:Module_Suppliers_Orders|FR:CommandeFournisseur|ES:Módulo_Pedidos_a_proveedores'; +$help_url = 'EN:Module_Suppliers_Orders|FR:CommandeFournisseur|ES:Módulo_Pedidos_a_proveedores'; llxHeader('', $langs->trans("Order"), $help_url, '', 0, 0, array('/fourn/js/lib_dispatch.js')); -if ($id > 0 || ! empty($ref)) { +if ($id > 0 || !empty($ref)) { $soc = new Societe($db); $soc->fetch($object->socid); @@ -392,49 +392,49 @@ if ($id > 0 || ! empty($ref)) { // Supplier order card - $linkback = ''.$langs->trans("BackToList").''; + $linkback = ''.$langs->trans("BackToList").''; - $morehtmlref='
'; + $morehtmlref = '
'; // Ref supplier - $morehtmlref.=$form->editfieldkey("RefSupplier", 'ref_supplier', $object->ref_supplier, $object, 0, 'string', '', 0, 1); - $morehtmlref.=$form->editfieldval("RefSupplier", 'ref_supplier', $object->ref_supplier, $object, 0, 'string', '', null, null, '', 1); + $morehtmlref .= $form->editfieldkey("RefSupplier", 'ref_supplier', $object->ref_supplier, $object, 0, 'string', '', 0, 1); + $morehtmlref .= $form->editfieldval("RefSupplier", 'ref_supplier', $object->ref_supplier, $object, 0, 'string', '', null, null, '', 1); // Thirdparty - $morehtmlref.='
'.$langs->trans('ThirdParty') . ' : ' . $object->thirdparty->getNomUrl(1); + $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').' '; if ($user->rights->fournisseur->commande->creer) { if ($action != 'classify') { //$morehtmlref.='' . img_edit($langs->transnoentitiesnoconv('SetProject')) . ' : '; - $morehtmlref.=' : '; + $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.=''; + $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); + $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)) { + if (!empty($object->fk_project)) { $proj = new Project($db); $proj->fetch($object->fk_project); - $morehtmlref.=''; - $morehtmlref.=$proj->ref; - $morehtmlref.=''; + $morehtmlref .= ''; + $morehtmlref .= $proj->ref; + $morehtmlref .= ''; } else { - $morehtmlref.=''; + $morehtmlref .= ''; } } } - $morehtmlref.='
'; + $morehtmlref .= '
'; dol_banner_tab($object, 'ref', $linkback, 1, 'ref', 'ref', $morehtmlref); @@ -447,20 +447,20 @@ if ($id > 0 || ! empty($ref)) { // Date if ($object->methode_commande_id > 0) { - print '"; if ($object->methode_commande) { - print ''; + print ''; } } // Author - print ''; - print ''; + print ''; + print ''; print ''; $parameters = array(); @@ -474,7 +474,7 @@ if ($id > 0 || ! empty($ref)) { print '
'; $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 @@ -488,22 +488,22 @@ if ($id > 0 || ! empty($ref)) { $entrepot = new Entrepot($db); $listwarehouses = $entrepot->list_array(1); - if(empty($conf->reception->enabled))print ''; + if (empty($conf->reception->enabled))print ''; else print ''; - print ''; - if(empty($conf->reception->enabled))print ''; + print ''; + if (empty($conf->reception->enabled))print ''; else print ''; print '
'; - print '
'; print $form->editfieldkey('DatePayment', 'datep', '', $object, 0, 'string', '', 1).''; - print $form->selectDate((empty($datep)?-1:$datep), "datep", '', '', '', 'add', 1, 1); + print $form->selectDate((empty($datep) ?-1 : $datep), "datep", '', '', '', 'add', 1, 1); print '
'; print $form->editfieldkey('DateValue', 'datev', '', $object, 0).''; - print $form->selectDate((empty($datev)?-1:$datev), "datev", '', '', '', 'add', 1, 1); + print $form->selectDate((empty($datev) ?-1 : $datev), "datev", '', '', '', 'add', 1, 1); print '
'; print $form->editfieldkey('Label', 'label', '', $object, 0, 'string', '', 1).''; - print ''; + print ''; print '
'; print $form->editfieldkey('Sens', 'sens', '', $object, 0, 'string', '', 1).''; - $sensarray=array( '0' => $langs->trans("Debit"), '1' => $langs->trans("Credit")); + $sensarray = array('0' => $langs->trans("Debit"), '1' => $langs->trans("Credit")); print $form->selectarray('sens', $sensarray, $sens); print '
'; print $form->editfieldkey('BankAccount', 'selectaccountid', '', $object, 0, 'string', '', 1).''; - $form->select_comptes($accountid, "accountid", 0, '', 1); // Affiche liste des comptes courant + $form->select_comptes($accountid, "accountid", 0, '', 1); // Affiche liste des comptes courant print '
'.$langs->trans("Project").''; - $numproject=$formproject->select_projects(-1, $projectid, 'fk_project', 0, 0, 1, 1); + $numproject = $formproject->select_projects(-1, $projectid, 'fk_project', 0, 0, 1, 1); print '
'.$langs->trans("AccountAccounting").'
'.$langs->trans("SubledgerAccount").''; - if (! empty($conf->global->ACCOUNTANCY_COMBO_FOR_AUX)) + if (!empty($conf->global->ACCOUNTANCY_COMBO_FOR_AUX)) { print $formaccounting->select_auxaccount($subledger_account, 'subledger_account', 1, ''); } @@ -459,7 +456,7 @@ if ($id) print '
'; print '
'; - print ''; + print '
'; // Label print ''; @@ -485,7 +482,7 @@ if ($id) print ''; - if (! empty($conf->banque->enabled)) + if (!empty($conf->banque->enabled)) { if ($object->fk_account > 0) { - $bankline=new AccountLine($db); + $bankline = new AccountLine($db); $bankline->fetch($object->fk_bank); print ''; @@ -520,8 +517,8 @@ if ($id) } // Other attributes - $parameters=array('socid'=>$object->id); - include DOL_DOCUMENT_ROOT . '/core/tpl/extrafields_view.tpl.php'; + $parameters = array('socid'=>$object->id); + include DOL_DOCUMENT_ROOT.'/core/tpl/extrafields_view.tpl.php'; print '
'.$langs->trans("Label").''.$object->label.'
'; print $langs->trans("AccountAccounting"); print ''; - if (! empty($conf->accounting->enabled)) + if (!empty($conf->accounting->enabled)) { $accountingaccount = new AccountingAccount($db); $accountingaccount->fetch('', $object->accountancy_code, 1); @@ -503,11 +500,11 @@ if ($id) print $object->subledger_account; print '
'; @@ -543,7 +540,7 @@ if ($id) // Delete if (empty($object->rappro)) { - if (! empty($user->rights->banque->modifier)) + if (!empty($user->rights->banque->modifier)) { print ''; } diff --git a/htdocs/compta/bank/various_payment/document.php b/htdocs/compta/bank/various_payment/document.php index 7070946e2c7..6e8fb2a65ea 100644 --- a/htdocs/compta/bank/various_payment/document.php +++ b/htdocs/compta/bank/various_payment/document.php @@ -50,22 +50,22 @@ if (empty($page) || $page == -1) { $page = 0; } // If $page is not defined, $offset = $conf->liste_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 PaymentVarious($db); $object->fetch($id, $ref); $upload_dir = $conf->bank->dir_output.'/'.dol_sanitizeFileName($object->id); -$modulepart='banque'; +$modulepart = 'banque'; /* * Actions */ -include_once DOL_DOCUMENT_ROOT . '/core/actions_linkedfiles.inc.php'; +include_once DOL_DOCUMENT_ROOT.'/core/actions_linkedfiles.inc.php'; /* @@ -125,11 +125,11 @@ if ($object->id) print '
'; // 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) + $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) { - $totalsize+=$file['size']; + $totalsize += $file['size']; } print ''; @@ -146,8 +146,8 @@ if ($object->id) $modulepart = 'banque'; $permission = $user->rights->banque->modifier; - $param = '&id=' . $object->id; - include_once DOL_DOCUMENT_ROOT . '/core/tpl/document_actions_post_headers.tpl.php'; + $param = '&id='.$object->id; + include_once DOL_DOCUMENT_ROOT.'/core/tpl/document_actions_post_headers.tpl.php'; } else { diff --git a/htdocs/compta/bank/various_payment/list.php b/htdocs/compta/bank/various_payment/list.php index d73d6d8a391..d279041e2af 100644 --- a/htdocs/compta/bank/various_payment/list.php +++ b/htdocs/compta/bank/various_payment/list.php @@ -175,7 +175,7 @@ if ($result) print_barre_liste($langs->trans("VariousPayments"), $page, $_SERVER["PHP_SELF"], $param, $sortfield, $sortorder, '', $num, $totalnboflines, 'invoicing', 0, $newcardbutton, '', $limit); print '
'; - print '
'."\n"; + print '
'."\n"; print ''; @@ -200,7 +200,7 @@ if ($result) print ''; // Account - if (! empty($conf->banque->enabled)) + if (!empty($conf->banque->enabled)) { print ''; } @@ -236,23 +236,23 @@ if ($result) print_liste_field_titre("Label", $_SERVER["PHP_SELF"], "v.label", "", $param, '', $sortfield, $sortorder, 'left '); print_liste_field_titre("DatePayment", $_SERVER["PHP_SELF"], "v.datep,v.rowid", "", $param, '', $sortfield, $sortorder, 'center '); print_liste_field_titre("PaymentMode", $_SERVER["PHP_SELF"], "type", "", $param, '', $sortfield, $sortorder, 'left '); - if (! empty($conf->banque->enabled)) print_liste_field_titre("BankAccount", $_SERVER["PHP_SELF"], "ba.label", "", $param, "", $sortfield, $sortorder); - if (! empty($conf->accounting->enabled)) print_liste_field_titre("AccountAccounting", $_SERVER["PHP_SELF"], "v.accountancy_code", "", $param, '', $sortfield, $sortorder, 'left '); + if (!empty($conf->banque->enabled)) print_liste_field_titre("BankAccount", $_SERVER["PHP_SELF"], "ba.label", "", $param, "", $sortfield, $sortorder); + if (!empty($conf->accounting->enabled)) print_liste_field_titre("AccountAccounting", $_SERVER["PHP_SELF"], "v.accountancy_code", "", $param, '', $sortfield, $sortorder, 'left '); print_liste_field_titre("Debit", $_SERVER["PHP_SELF"], "v.amount", "", $param, '', $sortfield, $sortorder, 'right '); print_liste_field_titre("Credit", $_SERVER["PHP_SELF"], "v.amount", "", $param, '', $sortfield, $sortorder, 'right '); print_liste_field_titre('', $_SERVER["PHP_SELF"], "", '', '', '', $sortfield, $sortorder, 'maxwidthsearch '); print "\n"; - $totalarray=array(); + $totalarray = array(); while ($i < min($num, $limit)) { $obj = $db->fetch_object($result); print ''; - $variousstatic->id=$obj->rowid; - $variousstatic->ref=$obj->rowid; + $variousstatic->id = $obj->rowid; + $variousstatic->ref = $obj->rowid; // Ref print "\n"; @@ -271,24 +271,24 @@ if ($result) if (! $i) $totalarray['nbfield']++; // Account - if (! empty($conf->banque->enabled)) + if (!empty($conf->banque->enabled)) { print ''; @@ -2092,16 +2089,16 @@ elseif (! empty($object->id)) print $form->editfieldkey('CurrencyRate', 'multicurrency_tx', '', $object, 0); print ''; if ($action != 'editmulticurrencyrate' && $object->statut == $object::STATUS_DRAFT && $object->multicurrency_code && $object->multicurrency_code != $conf->currency) - print ''; + print ''; print '
'; $form->select_comptes($search_account, 'search_account', 0, '', 1); @@ -208,11 +208,11 @@ if ($result) } // Accounting account - if (! empty($conf->accounting->enabled)) + if (!empty($conf->accounting->enabled)) { print ''; print '
'; - print $formaccounting->select_account($search_accountancy_code, 'search_accountancy_code', 1, array (), 1, 1, 'maxwidth200'); + print $formaccounting->select_account($search_accountancy_code, 'search_accountancy_code', 1, array(), 1, 1, 'maxwidth200'); print '
'; print '
".$variousstatic->getNomUrl(1)."'; if ($obj->bid > 0) { - $accountstatic->id=$obj->bid; - $accountstatic->ref=$obj->bref; - $accountstatic->number=$obj->bnumber; + $accountstatic->id = $obj->bid; + $accountstatic->ref = $obj->bref; + $accountstatic->number = $obj->bnumber; - if (! empty($conf->accounting->enabled)) { - $accountstatic->account_number=$obj->bank_account_number; + if (!empty($conf->accounting->enabled)) { + $accountstatic->account_number = $obj->bank_account_number; $accountingjournal = new AccountingJournal($db); $accountingjournal->fetch($obj->accountancy_journal); $accountstatic->accountancy_journal = $accountingjournal->getNomUrl(0, 1, 1, '', 1); } - $accountstatic->label=$obj->blabel; + $accountstatic->label = $obj->blabel; print $accountstatic->getNomUrl(1); } else print ' '; @@ -297,7 +297,7 @@ if ($result) } // Accounting account - if (! empty($conf->accounting->enabled)) { + if (!empty($conf->accounting->enabled)) { $accountingaccount = new AccountingAccount($db); $accountingaccount->fetch('', $obj->accountancy_code, 1); @@ -332,9 +332,9 @@ if ($result) $i++; } - $colspan=4; - if (! empty($conf->banque->enabled)) $colspan++; - if (! empty($conf->accounting->enabled)) $colspan++; + $colspan = 4; + if (!empty($conf->banque->enabled)) $colspan++; + if (!empty($conf->accounting->enabled)) $colspan++; // Show total line include DOL_DOCUMENT_ROOT.'/core/tpl/list_print_total.tpl.php'; diff --git a/htdocs/compta/cashcontrol/cashcontrol_card.php b/htdocs/compta/cashcontrol/cashcontrol_card.php index 706f24d00d4..ef88c586ede 100644 --- a/htdocs/compta/cashcontrol/cashcontrol_card.php +++ b/htdocs/compta/cashcontrol/cashcontrol_card.php @@ -31,20 +31,20 @@ require '../../main.inc.php'; require_once DOL_DOCUMENT_ROOT.'/compta/bank/class/account.class.php'; require_once DOL_DOCUMENT_ROOT.'/compta/cashcontrol/class/cashcontrol.class.php'; -$langs->loadLangs(array("install","cashdesk","admin","banks")); +$langs->loadLangs(array("install", "cashdesk", "admin", "banks")); -$id=GETPOST('id', 'int'); +$id = GETPOST('id', 'int'); $ref = GETPOST('ref', 'alpha'); -$action=GETPOST('action', 'aZ09'); +$action = GETPOST('action', 'aZ09'); $categid = GETPOST('categid'); $label = GETPOST("label"); -$now=dol_now(); -$syear = (GETPOSTISSET('closeyear')?GETPOST('closeyear', 'int'):dol_print_date($now, "%Y")); -$smonth = (GETPOSTISSET('closemonth')?GETPOST('closemonth', 'int'):dol_print_date($now, "%m")); -$sday = (GETPOSTISSET('closeday')?GETPOST('closeday', 'int'):dol_print_date($now, "%d")); +$now = dol_now(); +$syear = (GETPOSTISSET('closeyear') ?GETPOST('closeyear', 'int') : dol_print_date($now, "%Y")); +$smonth = (GETPOSTISSET('closemonth') ?GETPOST('closemonth', 'int') : dol_print_date($now, "%m")); +$sday = (GETPOSTISSET('closeday') ?GETPOST('closeday', 'int') : dol_print_date($now, "%d")); -$limit = GETPOST('limit', 'int')?GETPOST('limit', 'int'):$conf->liste_limit; +$limit = GETPOST('limit', 'int') ?GETPOST('limit', 'int') : $conf->liste_limit; $sortfield = GETPOST("sortfield", 'alpha'); $sortorder = GETPOST("sortorder", 'alpha'); $page = GETPOST("page", 'int'); @@ -52,30 +52,30 @@ if (empty($page) || $page == -1) { $page = 0; } // If $page is not defined, $offset = $limit * $page; $pageprev = $page - 1; $pagenext = $page + 1; -if (! $sortfield) $sortfield='rowid'; -if (! $sortorder) $sortorder='ASC'; +if (!$sortfield) $sortfield = 'rowid'; +if (!$sortorder) $sortorder = 'ASC'; // Security check -if (! $user->rights->cashdesk->use && ! $user->rights->takepos->use) +if (!$user->rights->cashdesk->use && !$user->rights->takepos->use) { accessforbidden(); } -$arrayofpaymentmode=array('cash'=>'Cash', 'cheque'=>'Cheque', 'card'=>'CreditCard'); +$arrayofpaymentmode = array('cash'=>'Cash', 'cheque'=>'Cheque', 'card'=>'CreditCard'); -$arrayofposavailable=array(); -if (! empty($conf->cashdesk->enabled)) $arrayofposavailable['cashdesk']=$langs->trans('CashDesk').' (cashdesk)'; -if (! empty($conf->takepos->enabled)) $arrayofposavailable['takepos']=$langs->trans('TakePOS').' (takepos)'; +$arrayofposavailable = array(); +if (!empty($conf->cashdesk->enabled)) $arrayofposavailable['cashdesk'] = $langs->trans('CashDesk').' (cashdesk)'; +if (!empty($conf->takepos->enabled)) $arrayofposavailable['takepos'] = $langs->trans('TakePOS').' (takepos)'; // TODO Add hook here to allow other POS to add themself -$object= new CashControl($db); +$object = new CashControl($db); $extrafields = new ExtraFields($db); // fetch optionals attributes and labels $extrafields->fetch_name_optionals_label($object->table_element); // Initialize technical object to manage hooks of page. Note that conf->hooks_modules contains array of hook context -$hookmanager->initHooks(array('cashcontrolcard','globalcard')); +$hookmanager->initHooks(array('cashcontrolcard', 'globalcard')); /* @@ -86,7 +86,7 @@ $permissiontoadd = ($user->rights->cashdesk->use || $user->rights->takepos->use) $permissiontodelete = ($user->rights->cashdesk->use || $user->rights->takepos->use) || ($permissiontoadd && $object->status == 0); if (empty($backtopage)) $backtopage = dol_buildpath('/compta/cashcontrol/cashcontrol_card.php', 1).'?id='.($id > 0 ? $id : '__ID__'); $backurlforlist = dol_buildpath('/compta/cashcontrol/cashcontrol_list.php', 1); -$triggermodname = 'CACHCONTROL_MODIFY'; // Name of trigger action code to execute when we modify record +$triggermodname = 'CACHCONTROL_MODIFY'; // Name of trigger action code to execute when we modify record if (empty($conf->global->CASHDESK_ID_BANKACCOUNT_CASH) && empty($conf->global->CASHDESK_ID_BANKACCOUNT_CASH1)) { @@ -99,70 +99,70 @@ if (GETPOST('cancel', 'alpha')) $action = 'create'; } -if ($action=="start") +if ($action == "start") { - $error=0; - if (! GETPOST('posmodule', 'alpha') || GETPOST('posmodule', 'alpha') == '-1') + $error = 0; + if (!GETPOST('posmodule', 'alpha') || GETPOST('posmodule', 'alpha') == '-1') { setEventMessages($langs->trans("ErrorFieldRequired", $langs->transnoentitiesnoconv("Module")), null, 'errors'); - $action='create'; + $action = 'create'; $error++; } if (GETPOST('posnumber', 'alpha') == '') { setEventMessages($langs->trans("ErrorFieldRequired", $langs->transnoentitiesnoconv("CashDesk")), null, 'errors'); - $action='create'; + $action = 'create'; $error++; } - if (! GETPOST('closeyear', 'alpha') || GETPOST('closeyear', 'alpha') == '-1') + if (!GETPOST('closeyear', 'alpha') || GETPOST('closeyear', 'alpha') == '-1') { setEventMessages($langs->trans("ErrorFieldRequired", $langs->transnoentitiesnoconv("Year")), null, 'errors'); - $action='create'; + $action = 'create'; $error++; } } -elseif ($action=="add") +elseif ($action == "add") { if (GETPOST('opening', 'alpha') == '') { setEventMessages($langs->trans("ErrorFieldRequired", $langs->transnoentitiesnoconv("InitialBankBalance")), null, 'errors'); - $action='start'; + $action = 'start'; $error++; } - $error=0; - foreach($arrayofpaymentmode as $key=>$val) + $error = 0; + foreach ($arrayofpaymentmode as $key=>$val) { $object->$key = price2num(GETPOST($key.'_amount', 'alpha')); } - if (! $error) + if (!$error) { $object->day_close = GETPOST('closeday', 'int'); $object->month_close = GETPOST('closemonth', 'int'); $object->year_close = GETPOST('closeyear', 'int'); - $object->opening=price2num(GETPOST('opening', 'alpha')); - $object->posmodule=GETPOST('posmodule', 'alpha'); - $object->posnumber=GETPOST('posnumber', 'alpha'); + $object->opening = price2num(GETPOST('opening', 'alpha')); + $object->posmodule = GETPOST('posmodule', 'alpha'); + $object->posnumber = GETPOST('posnumber', 'alpha'); $db->begin(); - $id=$object->create($user); + $id = $object->create($user); if ($id > 0) { $db->commit(); - $action="view"; + $action = "view"; } else { $db->rollback; - $action="view"; + $action = "view"; } } } -if ($action=="close") +if ($action == "close") { $object->fetch($id); @@ -176,21 +176,21 @@ if ($action=="close") setEventMessages($langs->trans("CashFenceDone"), null); } - $action="view"; + $action = "view"; } // Action to delete -if ($action == 'confirm_delete' && ! empty($permissiontodelete)) +if ($action == 'confirm_delete' && !empty($permissiontodelete)) { $object->fetch($id); - if (! ($object->id > 0)) + if (!($object->id > 0)) { dol_print_error('', 'Error, object must be fetched before being deleted'); exit; } - $result=$object->delete($user); + $result = $object->delete($user); //var_dump($result); if ($result > 0) { @@ -201,7 +201,7 @@ if ($action == 'confirm_delete' && ! empty($permissiontodelete)) } else { - if (! empty($object->errors)) setEventMessages(null, $object->errors, 'errors'); + if (!empty($object->errors)) setEventMessages(null, $object->errors, 'errors'); else setEventMessages($object->error, null, 'errors'); } } @@ -211,15 +211,15 @@ if ($action == 'confirm_delete' && ! empty($permissiontodelete)) * View */ -$form=new Form($db); +$form = new Form($db); -if ($action=="create" || $action=="start") +if ($action == "create" || $action == "start") { llxHeader(); - $initialbalanceforterminal=array(); - $theoricalamountforterminal=array(); - $theoricalnbofinvoiceforterminal=array(); + $initialbalanceforterminal = array(); + $theoricalamountforterminal = array(); + $theoricalnbofinvoiceforterminal = array(); if (GETPOST('posnumber', 'alpha') != '' && GETPOST('posnumber', 'alpha') != '' && GETPOST('posnumber', 'alpha') != '-1') { @@ -227,16 +227,16 @@ if ($action=="create" || $action=="start") $terminalid = GETPOST('posnumber', 'alpha'); $terminaltouse = $terminalid; - if ($terminaltouse == '1' && $posmodule=='cashdesk') $terminaltouse = ''; + if ($terminaltouse == '1' && $posmodule == 'cashdesk') $terminaltouse = ''; - if ($posmodule=='cashdesk' && $terminaltouse != '' && $terminaltouse != '1') { + if ($posmodule == 'cashdesk' && $terminaltouse != '' && $terminaltouse != '1') { $terminaltouse = ''; setEventMessages($langs->trans("OnlyTerminal1IsAvailableForCashDeskModule"), null, 'errors'); $error++; } // Calculate $initialbalanceforterminal for terminal 0 - foreach($arrayofpaymentmode as $key => $val) + foreach ($arrayofpaymentmode as $key => $val) { if ($key != 'cash') { @@ -245,18 +245,18 @@ if ($action=="create" || $action=="start") } // Get the bank account dedicated to this point of sale module/terminal - $vartouse='CASHDESK_ID_BANKACCOUNT_CASH'.$terminaltouse; - $bankid = $conf->global->$vartouse; // This value is ok for 'Terminal 0' for module 'CashDesk' and 'TakePos' (they manage only 1 terminal) + $vartouse = 'CASHDESK_ID_BANKACCOUNT_CASH'.$terminaltouse; + $bankid = $conf->global->$vartouse; // This value is ok for 'Terminal 0' for module 'CashDesk' and 'TakePos' (they manage only 1 terminal) // Hook to get the good bank id according to posmodule and posnumber. // @TODO add hook here if ($bankid > 0) { $sql = "SELECT SUM(amount) as total FROM ".MAIN_DB_PREFIX."bank"; - $sql.= " WHERE fk_account = ".$bankid; - if ($syear && ! $smonth) $sql.= " AND dateo < '".$db->idate(dol_get_first_day($syear, 1))."'"; - elseif ($syear && $smonth && ! $sday) $sql.= " AND dateo < '".$db->idate(dol_get_first_day($syear, $smonth))."'"; - elseif ($syear && $smonth && $sday) $sql.= " AND dateo < '".$db->idate(dol_mktime(0, 0, 0, $smonth, $sday, $syear))."'"; + $sql .= " WHERE fk_account = ".$bankid; + if ($syear && !$smonth) $sql .= " AND dateo < '".$db->idate(dol_get_first_day($syear, 1))."'"; + elseif ($syear && $smonth && !$sday) $sql .= " AND dateo < '".$db->idate(dol_get_first_day($syear, $smonth))."'"; + elseif ($syear && $smonth && $sday) $sql .= " AND dateo < '".$db->idate(dol_mktime(0, 0, 0, $smonth, $sday, $syear))."'"; else dol_print_error('', 'Year not defined'); $resql = $db->query($sql); @@ -275,28 +275,28 @@ if ($action=="create" || $action=="start") } // Calculate $theoricalamountforterminal for terminal 0 - foreach($arrayofpaymentmode as $key => $val) + foreach ($arrayofpaymentmode as $key => $val) { /*$sql = "SELECT SUM(amount) as total FROM ".MAIN_DB_PREFIX."bank"; $sql.= " WHERE fk_account = ".$bankid;*/ $sql = "SELECT SUM(pf.amount) as total, COUNT(*) as nb"; - $sql.= " FROM ".MAIN_DB_PREFIX."paiement_facture as pf, ".MAIN_DB_PREFIX."facture as f, ".MAIN_DB_PREFIX."paiement as p, ".MAIN_DB_PREFIX."c_paiement as cp"; - $sql.= " WHERE pf.fk_facture = f.rowid AND p.rowid = pf.fk_paiement AND cp.id = p.fk_paiement"; - $sql.= " AND f.module_source = '".$db->escape($posmodule)."'"; - $sql.= " AND f.pos_source = '".$db->escape($terminalid)."'"; - $sql.= " AND f.paye = 1"; - $sql.= " AND p.entity IN (".getEntity('facture').")"; - if ($key == 'cash') $sql.=" AND cp.code = 'LIQ'"; - elseif ($key == 'cheque') $sql.=" AND cp.code = 'CHQ'"; - elseif ($key == 'card') $sql.=" AND cp.code = 'CB'"; + $sql .= " FROM ".MAIN_DB_PREFIX."paiement_facture as pf, ".MAIN_DB_PREFIX."facture as f, ".MAIN_DB_PREFIX."paiement as p, ".MAIN_DB_PREFIX."c_paiement as cp"; + $sql .= " WHERE pf.fk_facture = f.rowid AND p.rowid = pf.fk_paiement AND cp.id = p.fk_paiement"; + $sql .= " AND f.module_source = '".$db->escape($posmodule)."'"; + $sql .= " AND f.pos_source = '".$db->escape($terminalid)."'"; + $sql .= " AND f.paye = 1"; + $sql .= " AND p.entity IN (".getEntity('facture').")"; + if ($key == 'cash') $sql .= " AND cp.code = 'LIQ'"; + elseif ($key == 'cheque') $sql .= " AND cp.code = 'CHQ'"; + elseif ($key == 'card') $sql .= " AND cp.code = 'CB'"; else { dol_print_error('Value for key = '.$key.' not supported'); exit; } - if ($syear && ! $smonth) $sql.= " AND datef BETWEEN '".$db->idate(dol_get_first_day($syear, 1))."' AND '".$db->idate(dol_get_last_day($syear, 12))."'"; - elseif ($syear && $smonth && ! $sday) $sql.= " AND datef BETWEEN '".$db->idate(dol_get_first_day($syear, $smonth))."' AND '".$db->idate(dol_get_last_day($syear, $smonth))."'"; - elseif ($syear && $smonth && $sday) $sql.= " AND datef BETWEEN '".$db->idate(dol_mktime(0, 0, 0, $smonth, $sday, $syear))."' AND '".$db->idate(dol_mktime(23, 59, 59, $smonth, $sday, $syear))."'"; + if ($syear && !$smonth) $sql .= " AND datef BETWEEN '".$db->idate(dol_get_first_day($syear, 1))."' AND '".$db->idate(dol_get_last_day($syear, 12))."'"; + elseif ($syear && $smonth && !$sday) $sql .= " AND datef BETWEEN '".$db->idate(dol_get_first_day($syear, $smonth))."' AND '".$db->idate(dol_get_last_day($syear, $smonth))."'"; + elseif ($syear && $smonth && $sday) $sql .= " AND datef BETWEEN '".$db->idate(dol_mktime(0, 0, 0, $smonth, $sday, $syear))."' AND '".$db->idate(dol_mktime(23, 59, 59, $smonth, $sday, $syear))."'"; else dol_print_error('', 'Year not defined'); $resql = $db->query($sql); @@ -327,7 +327,7 @@ if ($action=="create" || $action=="start") { print ''; } - print ''; + print '
'; print ''; print ''; print ''; @@ -337,53 +337,53 @@ if ($action=="create" || $action=="start") print ''; print "\n"; - $disabled=0; - $prefix='close'; + $disabled = 0; + $prefix = 'close'; print ''; - print ''; + print ''; print ''; // Year print ''; // Month print ''; // Day print ''; // Button Start @@ -407,7 +407,7 @@ if ($action=="create" || $action=="start") print '
'; - print '
'.$langs->trans("Module").''.$langs->trans("CashDesk").' ID
'.$form->selectarray('posmodule', $arrayofposavailable, GETPOST('posmodule', 'alpha'), (count($arrayofposavailable)>1?1:0)).''.$form->selectarray('posmodule', $arrayofposavailable, GETPOST('posmodule', 'alpha'), (count($arrayofposavailable) > 1 ? 1 : 0)).''; - $array=array(1=>"1", 2=>"2", 3=>"3", 4=>"4", 5=>"5", 6=>"6", 7=>"7", 8=>"8", 9=>"9"); - $selectedposnumber=0; $showempty=1; + $array = array(1=>"1", 2=>"2", 3=>"3", 4=>"4", 5=>"5", 6=>"6", 7=>"7", 8=>"8", 9=>"9"); + $selectedposnumber = 0; $showempty = 1; if ($conf->global->TAKEPOS_NUM_TERMINALS == '1') { - $selectedposnumber=1; $showempty=0; + $selectedposnumber = 1; $showempty = 0; } - print $form->selectarray('posnumber', $array, GETPOSTISSET('posnumber')?GETPOST('posnumber', 'int'):$selectedposnumber, $showempty); + print $form->selectarray('posnumber', $array, GETPOSTISSET('posnumber') ?GETPOST('posnumber', 'int') : $selectedposnumber, $showempty); //print ''; print ''; - $retstring=''; - for ($year = $syear - 10; $year < $syear + 10 ; $year++) + $retstring = ''; + for ($year = $syear - 10; $year < $syear + 10; $year++) { - $retstring.=''; + $retstring .= ''; } - $retstring.="\n"; + $retstring .= "\n"; print $retstring; print ''; - $retstring=''; - $retstring.=''; - for ($month = 1 ; $month <= 12 ; $month++) + $retstring = ''; + $retstring .= ''; + for ($month = 1; $month <= 12; $month++) { - $retstring.='"; + $retstring .= '"; } - $retstring.=""; + $retstring .= ""; print $retstring; print ''; - $retstring=''; - $retstring.=''; - for ($day = 1 ; $day <= 31; $day++) + $retstring = ''; + $retstring .= ''; + for ($day = 1; $day <= 31; $day++) { - $retstring.=''; + $retstring .= ''; } - $retstring.=""; + $retstring .= ""; print $retstring; print '
'; + print '
'; print ''; print ''; @@ -425,10 +425,10 @@ if ($action=="create" || $action=="start") print ''; - $i=0; - foreach($arrayofpaymentmode as $key => $val) + $i = 0; + foreach ($arrayofpaymentmode as $key => $val) { - print ''; $i++; @@ -442,10 +442,10 @@ if ($action=="create" || $action=="start") print ''; // Amount per payment type - $i=0; - foreach($arrayofpaymentmode as $key => $val) + $i = 0; + foreach ($arrayofpaymentmode as $key => $val) { - print ''; $i++; @@ -461,10 +461,10 @@ if ($action=="create" || $action=="start") print price($initialbalanceforterminal[$terminalid]['cash']).'
'; print ''; // Amount per payment type - $i=0; - foreach($arrayofpaymentmode as $key => $val) + $i = 0; + foreach ($arrayofpaymentmode as $key => $val) { - print ''; $i++; @@ -477,14 +477,14 @@ if ($action=="create" || $action=="start") print ''; // Initial amount print ''; // Amount per payment type - $i=0; - foreach($arrayofpaymentmode as $key => $val) + $i = 0; + foreach ($arrayofpaymentmode as $key => $val) { - print ''; $i++; } @@ -500,23 +500,23 @@ if ($action=="create" || $action=="start") print ''; } -if (empty($action) || $action=="view") +if (empty($action) || $action == "view") { $object->fetch($id); llxHeader('', $langs->trans("CashControl")); - $head=array(); + $head = array(); $head[0][0] = DOL_URL_ROOT.'/compta/cashcontrol/cashcontrol_card.php?id='.$object->id; $head[0][1] = $langs->trans("Card"); $head[0][2] = 'cashcontrol'; dol_fiche_head($head, 'cashcontrol', $langs->trans("CashControl"), -1, 'cashcontrol'); - $linkback = '' . $langs->trans("BackToList") . ''; + $linkback = ''.$langs->trans("BackToList").''; - $morehtmlref='
'; - $morehtmlref.='
'; + $morehtmlref = '
'; + $morehtmlref .= '
'; dol_banner_tab($object, 'id', $linkback, 1, 'rowid', 'rowid', $morehtmlref); @@ -563,7 +563,7 @@ if (empty($action) || $action=="view") print price($object->opening, 0, $langs, 1, -1, -1, $conf->currency); print ""; - foreach($arrayofpaymentmode as $key => $val) + foreach ($arrayofpaymentmode as $key => $val) { print ''; // Relative and absolute discounts - if (! empty($conf->global->FACTURE_DEPOSITS_ARE_JUST_PAYMENTS)) { + if (!empty($conf->global->FACTURE_DEPOSITS_ARE_JUST_PAYMENTS)) { $filterabsolutediscount = "fk_invoice_supplier_source IS NULL"; // If we want deposit to be substracted to payments only and not to total of final invoice $filtercreditnote = "fk_invoice_supplier_source IS NOT NULL"; // If we want deposit to be substracted to payments only and not to total of final invoice } else { @@ -2014,11 +2011,11 @@ elseif (! empty($object->id)) $absolute_discount = price2num($absolute_discount, 'MT'); $absolute_creditnote = price2num($absolute_creditnote, 'MT'); - print ''; @@ -2063,7 +2060,7 @@ elseif (! empty($object->id)) print ''; // Multicurrency - if (! empty($conf->multicurrency->enabled)) + if (!empty($conf->multicurrency->enabled)) { // Multicurrency code print ''; @@ -2072,13 +2069,13 @@ elseif (! empty($object->id)) print $form->editfieldkey('Currency', 'multicurrency_code', '', $object, 0); print ''; if ($action != 'editmulticurrencycode' && $object->statut == $object::STATUS_DRAFT) - print ''; + print ''; print '
'.$langs->trans("Cash"); //print '
'.$langs->trans("TheoricalAmount").'
'.$langs->trans("RealAmount"); print '
'.$langs->trans($val); + print ''.$langs->trans($val); //print '
'.$langs->trans("TheoricalAmount").'
'.$langs->trans("RealAmount"); print '
'; print ''; + print ''; print $theoricalnbofinvoiceforterminal[$terminalid][$key]; print ''; + print ''; print price($theoricalamountforterminal[$terminalid][$key]).'
'; print '
'.$langs->trans("RealAmount").''; - print ''; + print ''; print ''; - print ''; + print ''; + print ''; print '
'.$langs->trans($val).''; print price($object->$key, 0, $langs, 1, -1, -1, $conf->currency); @@ -578,12 +578,12 @@ if (empty($action) || $action=="view") dol_fiche_end(); print '
'; - print ''; + print ''; if ($object->status == CashControl::STATUS_DRAFT) { - print ''; + print ''; - print ''; + print ''; } print '
'; diff --git a/htdocs/compta/cashcontrol/cashcontrol_list.php b/htdocs/compta/cashcontrol/cashcontrol_list.php index 7a40d6638ee..c32c11226dd 100644 --- a/htdocs/compta/cashcontrol/cashcontrol_list.php +++ b/htdocs/compta/cashcontrol/cashcontrol_list.php @@ -47,22 +47,22 @@ require_once DOL_DOCUMENT_ROOT.'/core/lib/date.lib.php'; require_once DOL_DOCUMENT_ROOT.'/core/lib/company.lib.php'; // Load translation files required by the page -$langs->loadLangs(array("banks","other")); +$langs->loadLangs(array("banks", "other")); -$action = GETPOST('action', 'aZ09')?GETPOST('action', 'aZ09'):'view'; // The action 'add', 'create', 'edit', 'update', 'view', ... -$massaction = GETPOST('massaction', 'alpha'); // The bulk action (combo box choice into lists) -$show_files = GETPOST('show_files', 'int'); // Show files area generated by bulk actions ? -$confirm = GETPOST('confirm', 'alpha'); // Result of a confirmation -$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'):'cashcontrol'; // 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') +$action = GETPOST('action', 'aZ09') ?GETPOST('action', 'aZ09') : 'view'; // The action 'add', 'create', 'edit', 'update', 'view', ... +$massaction = GETPOST('massaction', 'alpha'); // The bulk action (combo box choice into lists) +$show_files = GETPOST('show_files', 'int'); // Show files area generated by bulk actions ? +$confirm = GETPOST('confirm', 'alpha'); // Result of a confirmation +$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') : 'cashcontrol'; // 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') -$id = GETPOST('id', 'int'); +$id = GETPOST('id', 'int'); // Load variable for pagination -$limit = GETPOST('limit', 'int')?GETPOST('limit', 'int'):$conf->liste_limit; +$limit = GETPOST('limit', 'int') ?GETPOST('limit', 'int') : $conf->liste_limit; $sortfield = GETPOST('sortfield', 'alpha'); $sortorder = GETPOST('sortorder', 'alpha'); $page = GETPOST('page', 'int'); @@ -74,22 +74,22 @@ $pagenext = $page + 1; //if (! $sortorder) $sortorder="DESC"; // Initialize technical objects -$object=new CashControl($db); +$object = new CashControl($db); $extrafields = new ExtraFields($db); -$diroutputmassaction=$conf->monmodule->dir_output . '/temp/massgeneration/'.$user->id; -$hookmanager->initHooks(array('cashcontrol')); // Note that conf->hooks_modules contains array +$diroutputmassaction = $conf->monmodule->dir_output.'/temp/massgeneration/'.$user->id; +$hookmanager->initHooks(array('cashcontrol')); // 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_'); +$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 -$socid=0; +$socid = 0; if ($user->socid > 0) // Protection if external user { //$socid = $user->socid; @@ -98,34 +98,34 @@ if ($user->socid > 0) // Protection if external user //$result = restrictedArea($user, 'monmodule', $id, ''); // Initialize array of search criterias -$search_all=trim(GETPOST("search_all", 'alpha')); -$search=array(); -foreach($object->fields as $key => $val) +$search_all = trim(GETPOST("search_all", 'alpha')); +$search = array(); +foreach ($object->fields as $key => $val) { - if (GETPOST('search_'.$key, 'alpha')) $search[$key]=GETPOST('search_'.$key, 'alpha'); + 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) +foreach ($object->fields as $key => $val) { - if ($val['searchall']) $fieldstosearchall['t.'.$key]=$val['label']; + if ($val['searchall']) $fieldstosearchall['t.'.$key] = $val['label']; } // Definition of fields for list -$arrayfields=array(); -foreach($object->fields as $key => $val) +$arrayfields = array(); +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'], 'position'=>$val['position']); + if (!empty($val['visible'])) $arrayfields['t.'.$key] = array('label'=>$val['label'], 'checked'=>(($val['visible'] < 0) ? 0 : 1), 'enabled'=>$val['enabled'], '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) + 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], 'checked'=>(($extrafields->attributes[$object->table_element]['list'][$key]<0)?0:1), 'position'=>$extrafields->attributes[$object->table_element]['pos'][$key], 'enabled'=>(abs($extrafields->attributes[$object->table_element]['list'][$key])!=3 && $extrafields->attributes[$object->table_element]['perms'][$key])); + if (!empty($extrafields->attributes[$object->table_element]['list'][$key])) + $arrayfields["ef.".$key] = array('label'=>$extrafields->attributes[$object->table_element]['label'][$key], 'checked'=>(($extrafields->attributes[$object->table_element]['list'][$key] < 0) ? 0 : 1), 'position'=>$extrafields->attributes[$object->table_element]['pos'][$key], 'enabled'=>(abs($extrafields->attributes[$object->table_element]['list'][$key]) != 3 && $extrafields->attributes[$object->table_element]['perms'][$key])); } } $object->fields = dol_sort_array($object->fields, 'position'); @@ -137,11 +137,11 @@ $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(); -$reshook=$hookmanager->executeHooks('doActions', $parameters, $object, $action); // Note that $action and $object may have been modified by some hooks +$parameters = array(); +$reshook = $hookmanager->executeHooks('doActions', $parameters, $object, $action); // Note that $action and $object may have been modified by some hooks if ($reshook < 0) setEventMessages($hookmanager->error, $hookmanager->errors, 'errors'); if (empty($reshook)) @@ -150,24 +150,24 @@ if (empty($reshook)) 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 { - foreach($object->fields as $key => $val) + foreach ($object->fields as $key => $val) { - $search[$key]=''; + $search[$key] = ''; } - $toselect=''; - $search_array_options=array(); + $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')) { - $massaction=''; // Protection to avoid mass action if we force a new search during a mass action confirmation + $massaction = ''; // Protection to avoid mass action if we force a new search during a mass action confirmation } // Mass actions - $objectclass='CashControl'; - $objectlabel='CashControl'; + $objectclass = 'CashControl'; + $objectlabel = 'CashControl'; $permissiontoread = ($user->rights->cashdesk->use || $user->rights->takepos->use); $permissiontodelete = ($user->rights->cashdesk->use || $user->rights->takepos->use); @@ -181,49 +181,49 @@ if (empty($reshook)) * View */ -$form=new Form($db); +$form = new Form($db); -$now=dol_now(); +$now = dol_now(); //$help_url="EN:Module_pos_cash_fence|FR:Module_pos_cash_fence_FR|ES:Módulo_pos_cash_fence"; -$help_url=''; +$help_url = ''; $title = $langs->trans('CashControl'); // Build and execute select // -------------------------------------------------------------------- $sql = 'SELECT '; -foreach($object->fields as $key => $val) +foreach ($object->fields as $key => $val) { - $sql.='t.'.$key.', '; + $sql .= 't.'.$key.', '; } // Add fields from extrafields -if (! empty($extrafields->attributes[$object->table_element]['label'])) +if (!empty($extrafields->attributes[$object->table_element]['label'])) { - foreach ($extrafields->attributes[$object->table_element]['label'] as $key => $val) $sql.=($extrafields->attributes[$object->table_element]['type'][$key] != 'separate' ? "ef.".$key.' as options_'.$key.', ' : ''); + foreach ($extrafields->attributes[$object->table_element]['label'] as $key => $val) $sql .= ($extrafields->attributes[$object->table_element]['type'][$key] != 'separate' ? "ef.".$key.' as options_'.$key.', ' : ''); } // Add fields from hooks -$parameters=array(); -$reshook=$hookmanager->executeHooks('printFieldListSelect', $parameters, $object); // Note that $action and $object may have been modified by hook -$sql.=$hookmanager->resPrint; -$sql=preg_replace('/, $/', '', $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) +$parameters = array(); +$reshook = $hookmanager->executeHooks('printFieldListSelect', $parameters, $object); // Note that $action and $object may have been modified by hook +$sql .= $hookmanager->resPrint; +$sql = preg_replace('/, $/', '', $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; - $mode_search=(($object->isInt($object->fields[$key]) || $object->isFloat($object->fields[$key])) ? 1 : 0); - if ($search[$key] != '') $sql.=natural_search($key, $search[$key], (($key == 'status')?2:$mode_search)); + $mode_search = (($object->isInt($object->fields[$key]) || $object->isFloat($object->fields[$key])) ? 1 : 0); + 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 -$parameters=array(); -$reshook=$hookmanager->executeHooks('printFieldListWhere', $parameters, $object); // Note that $action and $object may have been modified by hook -$sql.=$hookmanager->resPrint; +$parameters = array(); +$reshook = $hookmanager->executeHooks('printFieldListWhere', $parameters, $object); // Note that $action and $object may have been modified by hook +$sql .= $hookmanager->resPrint; /* If a group by is required $sql.= " GROUP BY " @@ -241,7 +241,7 @@ $sql.=$hookmanager->resPrint; $sql=preg_replace('/, $/','', $sql); */ -$sql.=$db->order($sortfield, $sortorder); +$sql .= $db->order($sortfield, $sortorder); // Count total nb of records $nbtotalofrecords = ''; @@ -262,10 +262,10 @@ if (is_numeric($nbtotalofrecords) && $limit > $nbtotalofrecords) } else { - $sql.= $db->plimit($limit+1, $offset); + $sql .= $db->plimit($limit + 1, $offset); - $resql=$db->query($sql); - if (! $resql) + $resql = $db->query($sql); + if (!$resql) { dol_print_error($db); exit; @@ -275,7 +275,7 @@ else } // Direct jump if only one record found -if ($num == 1 && ! empty($conf->global->MAIN_SEARCH_DIRECT_OPEN_IF_ONLY_ONE) && $search_all) +if ($num == 1 && !empty($conf->global->MAIN_SEARCH_DIRECT_OPEN_IF_ONLY_ONE) && $search_all) { $obj = $db->fetch_object($resql); $id = $obj->rowid; @@ -304,27 +304,27 @@ jQuery(document).ready(function() { }); '; -$arrayofselected=is_array($toselect)?$toselect:array(); +$arrayofselected = is_array($toselect) ? $toselect : array(); -$param=''; -if (! empty($contextpage) && $contextpage != $_SERVER["PHP_SELF"]) $param.='&contextpage='.urlencode($contextpage); -if ($limit > 0 && $limit != $conf->liste_limit) $param.='&limit='.urlencode($limit); -foreach($search as $key => $val) +$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) { - $param.= '&search_'.$key.'='.urlencode($search[$key]); + $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'; // List of mass actions available -$arrayofmassactions = array( +$arrayofmassactions = array( //'presend'=>$langs->trans("SendByMail"), //'builddoc'=>$langs->trans("PDFMerge"), ); //if ($user->rights->monmodule->delete) $arrayofmassactions['predelete']=''.$langs->trans("Delete"); -if (GETPOST('nomassaction', 'int') || in_array($massaction, array('presend','predelete'))) $arrayofmassactions=array(); -$massactionbutton=$form->selectMassAction('', $arrayofmassactions); +if (GETPOST('nomassaction', 'int') || in_array($massaction, array('presend', 'predelete'))) $arrayofmassactions = array(); +$massactionbutton = $form->selectMassAction('', $arrayofmassactions); print '
'; if ($optioncss != '') print ''; @@ -343,16 +343,16 @@ $newcardbutton = dolGetButtonTitle($langs->trans('New'), '', 'fa fa-plus-circle' print_barre_liste($title, $page, $_SERVER["PHP_SELF"], $param, $sortfield, $sortorder, $massactionbutton, $num, $nbtotalofrecords, 'cash-register', 0, $newcardbutton, '', $limit); // Add code for pre mass action (confirmation or email presend form) -$topicmail="SendCashControlRef"; -$modelmail="cashcontrol"; -$objecttmp=new CashControl($db); -$trackid='xxxx'.$object->id; +$topicmail = "SendCashControlRef"; +$modelmail = "cashcontrol"; +$objecttmp = new CashControl($db); +$trackid = 'xxxx'.$object->id; include DOL_DOCUMENT_ROOT.'/core/tpl/massactions_pre.tpl.php'; if ($sall) { - foreach($fieldstosearchall as $key => $val) $fieldstosearchall[$key]=$langs->trans($val); - print '
'.$langs->trans("FilterOnInto", $sall) . join(', ', $fieldstosearchall).'
'; + foreach ($fieldstosearchall as $key => $val) $fieldstosearchall[$key] = $langs->trans($val); + print '
'.$langs->trans("FilterOnInto", $sall).join(', ', $fieldstosearchall).'
'; } $moreforfilter = ''; @@ -360,39 +360,39 @@ $moreforfilter = ''; $moreforfilter.= $langs->trans('MyFilter') . ': '; $moreforfilter.= '';*/ -$parameters=array(); -$reshook=$hookmanager->executeHooks('printFieldPreListTitle', $parameters, $object); // Note that $action and $object may have been modified by hook +$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($moreforfilter)) +if (!empty($moreforfilter)) { print '
'; print $moreforfilter; print '
'; } -$varpage=empty($contextpage)?$_SERVER["PHP_SELF"]:$contextpage; -$selectedfields=$form->multiSelectArrayWithCheckbox('selectedfields', $arrayfields, $varpage); // This also change content of $arrayfields -$selectedfields.=(count($arrayofmassactions) ? $form->showCheckAddButtons('checkforselect', 1) : ''); +$varpage = empty($contextpage) ? $_SERVER["PHP_SELF"] : $contextpage; +$selectedfields = $form->multiSelectArrayWithCheckbox('selectedfields', $arrayfields, $varpage); // This also change content of $arrayfields +$selectedfields .= (count($arrayofmassactions) ? $form->showCheckAddButtons('checkforselect', 1) : ''); -print '
'; // You can use div-table-responsive-no-min if you dont need reserved height for your table -print ''."\n"; +print '
'; // You can use div-table-responsive-no-min if you dont need reserved height for your table +print '
'."\n"; // Fields title search // -------------------------------------------------------------------- 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'])) + $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'])) { - print ''; @@ -402,12 +402,12 @@ foreach($object->fields as $key => $val) include DOL_DOCUMENT_ROOT.'/core/tpl/extrafields_list_search_input.tpl.php'; // Fields from hook -$parameters=array('arrayfields'=>$arrayfields); -$reshook=$hookmanager->executeHooks('printFieldListOption', $parameters, $object); // Note that $action and $object may have been modified by hook +$parameters = array('arrayfields'=>$arrayfields); +$reshook = $hookmanager->executeHooks('printFieldListOption', $parameters, $object); // Note that $action and $object may have been modified by hook print $hookmanager->resPrint; // Action column print ''; print ''."\n"; @@ -416,79 +416,79 @@ 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'])) + $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'])) { - print getTitleFieldOfList($arrayfields['t.'.$key]['label'], 0, $_SERVER['PHP_SELF'], 't.'.$key, '', $param, ($cssforfield?'class="'.$cssforfield.'"':''), $sortfield, $sortorder, ($cssforfield?$cssforfield.' ':''))."\n"; + print getTitleFieldOfList($arrayfields['t.'.$key]['label'], 0, $_SERVER['PHP_SELF'], 't.'.$key, '', $param, ($cssforfield ? 'class="'.$cssforfield.'"' : ''), $sortfield, $sortorder, ($cssforfield ? $cssforfield.' ' : ''))."\n"; } } // 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, $object); // Note that $action and $object may have been modified by hook +$parameters = array('arrayfields'=>$arrayfields, 'param'=>$param, 'sortfield'=>$sortfield, 'sortorder'=>$sortorder); +$reshook = $hookmanager->executeHooks('printFieldListTitle', $parameters, $object); // Note that $action and $object may have been modified by hook print $hookmanager->resPrint; print getTitleFieldOfList($selectedfields, 0, $_SERVER["PHP_SELF"], '', '', '', 'align="center"', $sortfield, $sortorder, 'maxwidthsearch ')."\n"; print ''."\n"; // Detect if we need a fetch on each output line -$needToFetchEachLine=0; +$needToFetchEachLine = 0; if (is_array($extrafields->attributes[$object->table_element]['computed']) && count($extrafields->attributes[$object->table_element]['computed']) > 0) { foreach ($extrafields->attributes[$object->table_element]['computed'] as $key => $val) { - if (preg_match('/\$object/', $val)) $needToFetchEachLine++; // There is at least one compute field that use $object + if (preg_match('/\$object/', $val)) $needToFetchEachLine++; // There is at least one compute field that use $object } } // Loop on record // -------------------------------------------------------------------- -$i=0; -$totalarray=array(); +$i = 0; +$totalarray = array(); while ($i < min($num, $limit)) { $obj = $db->fetch_object($resql); - if (empty($obj)) break; // Should not happen + if (empty($obj)) break; // Should not happen // Store properties in $object $object->id = $obj->rowid; - foreach($object->fields as $key => $val) + foreach ($object->fields as $key => $val) { if (property_exists($obj, $key)) $object->$key = $obj->$key; } // 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'; + $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('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($val['type'], array('double(24,8)', 'double(6,3)', 'integer', 'real', 'price')) && $key != 'status') $cssforfield .= ($cssforfield ? ' ' : '').'right'; - if (! empty($arrayfields['t.'.$key]['checked'])) + if (!empty($arrayfields['t.'.$key]['checked'])) { print ''; if ($key == 'status') print $object->getLibStatut(5); - elseif (in_array($val['type'], array('date','datetime','timestamp'))) print $object->showOutputField($val, $key, $db->jdate($obj->$key), ''); + elseif (in_array($val['type'], array('date', 'datetime', 'timestamp'))) print $object->showOutputField($val, $key, $db->jdate($obj->$key), ''); else print $object->showOutputField($val, $key, $obj->$key, ''); print ''; - if (! $i) $totalarray['nbfield']++; - if (! empty($val['isameasure'])) + if (!$i) $totalarray['nbfield']++; + if (!empty($val['isameasure'])) { - if (! $i) $totalarray['pos'][$totalarray['nbfield']]='t.'.$key; + if (!$i) $totalarray['pos'][$totalarray['nbfield']] = 't.'.$key; $totalarray['val']['t.'.$key] += $obj->$key; } } @@ -496,19 +496,19 @@ while ($i < min($num, $limit)) // Extra fields include DOL_DOCUMENT_ROOT.'/core/tpl/extrafields_list_print_fields.tpl.php'; // Fields from hook - $parameters=array('arrayfields'=>$arrayfields, 'obj'=>$obj); - $reshook=$hookmanager->executeHooks('printFieldListValue', $parameters, $object); // Note that $action and $object may have been modified by hook + $parameters = array('arrayfields'=>$arrayfields, 'obj'=>$obj); + $reshook = $hookmanager->executeHooks('printFieldListValue', $parameters, $object); // Note that $action and $object may have been modified by hook print $hookmanager->resPrint; // Action column print ''; - if (! $i) $totalarray['nbfield']++; + if (!$i) $totalarray['nbfield']++; print ''; @@ -522,15 +522,15 @@ include DOL_DOCUMENT_ROOT.'/core/tpl/list_print_total.tpl.php'; // If no record found if ($num == 0) { - $colspan=1; - foreach($arrayfields as $key => $val) { if (! empty($val['checked'])) $colspan++; } + $colspan = 1; + foreach ($arrayfields as $key => $val) { if (!empty($val['checked'])) $colspan++; } print ''; } $db->free($resql); -$parameters=array('arrayfields'=>$arrayfields, 'sql'=>$sql); -$reshook=$hookmanager->executeHooks('printFieldListFooter', $parameters, $object); // Note that $action and $object may have been modified by hook +$parameters = array('arrayfields'=>$arrayfields, 'sql'=>$sql); +$reshook = $hookmanager->executeHooks('printFieldListFooter', $parameters, $object); // Note that $action and $object may have been modified by hook print $hookmanager->resPrint; print '
'; + print ''; if (is_array($val['arrayofkeyval'])) print $form->selectarray('search_'.$key, $val['arrayofkeyval'], $search[$key], $val['notnull'], 0, 0, '', 1, 0, 0, '', 'maxwidth75'); else print ''; print ''; -$searchpicto=$form->showFilterButtons(); +$searchpicto = $form->showFilterButtons(); print $searchpicto; print '
'; if ($massactionbutton || $massaction) // If we are in select mode (massactionbutton defined) or if we have already selected and sent an action ($massaction) defined { - $selected=0; - if (in_array($obj->rowid, $arrayofselected)) $selected=1; - print ''; + $selected = 0; + if (in_array($obj->rowid, $arrayofselected)) $selected = 1; + print ''; } print '
'.$langs->trans("NoRecordFound").'
'."\n"; @@ -540,19 +540,19 @@ print ''."\n"; if (in_array('builddoc', $arrayofmassactions) && ($nbtotalofrecords === '' || $nbtotalofrecords)) { - $hidegeneratedfilelistifempty=1; - if ($massaction == 'builddoc' || $action == 'remove_file' || $show_files) $hidegeneratedfilelistifempty=0; + $hidegeneratedfilelistifempty = 1; + 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); // Show list of available documents - $urlsource=$_SERVER['PHP_SELF'].'?sortfield='.$sortfield.'&sortorder='.$sortorder; - $urlsource.=str_replace('&', '&', $param); + $urlsource = $_SERVER['PHP_SELF'].'?sortfield='.$sortfield.'&sortorder='.$sortorder; + $urlsource .= str_replace('&', '&', $param); - $filedir=$diroutputmassaction; - $genallowed=$user->rights->monmodule->read; - $delallowed=$user->rights->monmodule->create; + $filedir = $diroutputmassaction; + $genallowed = $user->rights->monmodule->read; + $delallowed = $user->rights->monmodule->create; print $formfile->showdocuments('massfilesarea_monmodule', '', $filedir, $urlsource, 0, $delallowed, '', 1, 1, 0, 48, 1, $param, $title, '', '', '', null, $hidegeneratedfilelistifempty); } diff --git a/htdocs/compta/cashcontrol/class/cashcontrol.class.php b/htdocs/compta/cashcontrol/class/cashcontrol.class.php index 00d77987d08..ad792db0826 100644 --- a/htdocs/compta/cashcontrol/class/cashcontrol.class.php +++ b/htdocs/compta/cashcontrol/class/cashcontrol.class.php @@ -86,6 +86,10 @@ class CashControl extends CommonObject public $cash; public $cheque; public $card; + + /** + * @var integer|string $date_valid + */ public $date_valid; /** @@ -93,7 +97,9 @@ class CashControl extends CommonObject */ public $date_creation; - + /** + * @var integer|string $date_modification + */ public $date_modification; const STATUS_DRAFT = 0; diff --git a/htdocs/compta/charges/index.php b/htdocs/compta/charges/index.php index 5fe9853ec54..fd270cba3f1 100644 --- a/htdocs/compta/charges/index.php +++ b/htdocs/compta/charges/index.php @@ -45,17 +45,17 @@ $hookmanager->initHooks(array('specialexpensesindex')); $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 != 'sconly') { $year=date("Y", time()); } +$mode = GETPOST("mode", 'alpha'); +$year = GETPOST("year", 'int'); +$filtre = GETPOST("filtre", 'alpha'); +if (!$year && $mode != 'sconly') { $year = date("Y", time()); } $search_account = GETPOST('search_account', 'int'); -$limit = GETPOST('limit', 'int')?GETPOST('limit', 'int'):$conf->liste_limit; +$limit = GETPOST('limit', 'int') ?GETPOST('limit', 'int') : $conf->liste_limit; $sortfield = GETPOST("sortfield", 'alpha'); $sortorder = GETPOST("sortorder", 'alpha'); $page = GETPOST("page", 'int'); @@ -63,8 +63,8 @@ if (empty($page) || $page == -1) { $page = 0; } // If $page is not defined, $offset = $limit * $page; $pageprev = $page - 1; $pagenext = $page + 1; -if (! $sortfield) $sortfield="cs.date_ech"; -if (! $sortorder) $sortorder="DESC"; +if (!$sortfield) $sortfield = "cs.date_ech"; +if (!$sortorder) $sortorder = "DESC"; /* @@ -72,22 +72,22 @@ if (! $sortorder) $sortorder="DESC"; */ $tva_static = new Tva($db); -$socialcontrib=new ChargeSociales($db); -$payment_sc_static=new PaymentSocialContribution($db); +$socialcontrib = new ChargeSociales($db); +$payment_sc_static = new PaymentSocialContribution($db); $sal_static = new PaymentSalary($db); $accountstatic = new Account($db); llxHeader('', $langs->trans("SpecialExpensesArea")); -$title=$langs->trans("SpecialExpensesArea"); -if ($mode == 'sconly') $title=$langs->trans("SocialContributionsPayments"); +$title = $langs->trans("SpecialExpensesArea"); +if ($mode == 'sconly') $title = $langs->trans("SocialContributionsPayments"); -$param=''; -if (! empty($contextpage) && $contextpage != $_SERVER["PHP_SELF"]) $param.='&contextpage='.$contextpage; -if ($limit > 0 && $limit != $conf->liste_limit) $param.='&limit='.$limit; -if ($mode == 'sconly') $param='&mode=sconly'; -if ($sortfield) $param.='&sortfield='.$sortfield; -if ($sortorder) $param.='&sortorder='.$sortorder; +$param = ''; +if (!empty($contextpage) && $contextpage != $_SERVER["PHP_SELF"]) $param .= '&contextpage='.$contextpage; +if ($limit > 0 && $limit != $conf->liste_limit) $param .= '&limit='.$limit; +if ($mode == 'sconly') $param = '&mode=sconly'; +if ($sortfield) $param .= '&sortfield='.$sortfield; +if ($sortorder) $param .= '&sortorder='.$sortorder; print '
'; @@ -101,7 +101,7 @@ print ''; if ($mode != 'sconly') { - $center=($year?''.img_previous($langs->trans("Previous"), 'class="valignbottom"')." ".$langs->trans("Year").' '.$year.' '.img_next($langs->trans("Next"), 'class="valignbottom"')."":""); + $center = ($year ? ''.img_previous($langs->trans("Previous"), 'class="valignbottom"')." ".$langs->trans("Year").' '.$year.' '.img_next($langs->trans("Next"), 'class="valignbottom"')."" : ""); print_barre_liste($title, $page, $_SERVER["PHP_SELF"], $param, $sortfield, $sortorder, $center, $num, $totalnboflines, 'title_accountancy', 0, '', '', $limit, 1); } else @@ -109,7 +109,7 @@ else 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 ($mode != 'sconly') { @@ -117,15 +117,15 @@ if ($mode != 'sconly') print "
"; } -if (! empty($conf->tax->enabled) && $user->rights->tax->charges->lire) +if (!empty($conf->tax->enabled) && $user->rights->tax->charges->lire) { // Social contributions only if ($mode != 'sconly') { - print load_fiche_titre($langs->trans("SocialContributionsPayments").($year?' ('.$langs->trans("Year").' '.$year.')':''), '', ''); + print load_fiche_titre($langs->trans("SocialContributionsPayments").($year ? ' ('.$langs->trans("Year").' '.$year.')' : ''), '', ''); } - print ''; + print '
'; print ''; print_liste_field_titre("PeriodEndDate", $_SERVER["PHP_SELF"], "cs.date_ech", "", $param, 'width="140px"', $sortfield, $sortorder); print_liste_field_titre("Label", $_SERVER["PHP_SELF"], "c.libelle", "", $param, '', $sortfield, $sortorder); @@ -134,23 +134,23 @@ if (! empty($conf->tax->enabled) && $user->rights->tax->charges->lire) print_liste_field_titre("RefPayment", $_SERVER["PHP_SELF"], "pc.rowid", "", $param, '', $sortfield, $sortorder); print_liste_field_titre("DatePayment", $_SERVER["PHP_SELF"], "pc.datep", "", $param, 'align="center"', $sortfield, $sortorder); print_liste_field_titre("Type", $_SERVER["PHP_SELF"], "pct.code", "", $param, '', $sortfield, $sortorder); - if (! empty($conf->banque->enabled)) print_liste_field_titre("Account", $_SERVER["PHP_SELF"], "ba.label", "", $param, "", $sortfield, $sortorder); + if (!empty($conf->banque->enabled)) print_liste_field_titre("Account", $_SERVER["PHP_SELF"], "ba.label", "", $param, "", $sortfield, $sortorder); print_liste_field_titre("PayedByThisPayment", $_SERVER["PHP_SELF"], "pc.amount", "", $param, 'class="right"', $sortfield, $sortorder); print "\n"; $sql = "SELECT c.id, c.libelle as label,"; - $sql.= " cs.rowid, cs.libelle, cs.fk_type as type, cs.periode, cs.date_ech, cs.amount as total,"; - $sql.= " pc.rowid as pid, pc.datep, pc.amount as totalpaye, pc.num_paiement as num_payment, pc.fk_bank,"; - $sql.= " pct.code as payment_code,"; - $sql.= " ba.rowid as bid, ba.ref as bref, ba.number as bnumber, ba.account_number, ba.fk_accountancy_journal, ba.label as blabel"; - $sql.= " FROM ".MAIN_DB_PREFIX."c_chargesociales as c,"; - $sql.= " ".MAIN_DB_PREFIX."chargesociales as cs"; - $sql.= " LEFT JOIN ".MAIN_DB_PREFIX."paiementcharge as pc ON pc.fk_charge = cs.rowid"; - $sql.= " LEFT JOIN ".MAIN_DB_PREFIX."c_paiement as pct ON pc.fk_typepaiement = pct.id"; - $sql.= " LEFT JOIN ".MAIN_DB_PREFIX."bank as b ON pc.fk_bank = b.rowid"; - $sql.= " LEFT JOIN ".MAIN_DB_PREFIX."bank_account as ba ON b.fk_account = ba.rowid"; - $sql.= " WHERE cs.fk_type = c.id"; - $sql.= " AND cs.entity IN (".getEntity("tax").")"; + $sql .= " cs.rowid, cs.libelle, cs.fk_type as type, cs.periode, cs.date_ech, cs.amount as total,"; + $sql .= " pc.rowid as pid, pc.datep, pc.amount as totalpaye, pc.num_paiement as num_payment, pc.fk_bank,"; + $sql .= " pct.code as payment_code,"; + $sql .= " ba.rowid as bid, ba.ref as bref, ba.number as bnumber, ba.account_number, ba.fk_accountancy_journal, ba.label as blabel"; + $sql .= " FROM ".MAIN_DB_PREFIX."c_chargesociales as c,"; + $sql .= " ".MAIN_DB_PREFIX."chargesociales as cs"; + $sql .= " LEFT JOIN ".MAIN_DB_PREFIX."paiementcharge as pc ON pc.fk_charge = cs.rowid"; + $sql .= " LEFT JOIN ".MAIN_DB_PREFIX."c_paiement as pct ON pc.fk_typepaiement = pct.id"; + $sql .= " LEFT JOIN ".MAIN_DB_PREFIX."bank as b ON pc.fk_bank = b.rowid"; + $sql .= " LEFT JOIN ".MAIN_DB_PREFIX."bank_account as ba ON b.fk_account = ba.rowid"; + $sql .= " WHERE cs.fk_type = c.id"; + $sql .= " AND cs.entity IN (".getEntity("tax").")"; if ($year > 0) { $sql .= " AND ("; @@ -160,12 +160,12 @@ if (! empty($conf->tax->enabled) && $user->rights->tax->charges->lire) $sql .= " OR (cs.periode IS NULL AND cs.date_ech between '".$db->idate(dol_get_first_day($year))."' AND '".$db->idate(dol_get_last_day($year))."')"; $sql .= ")"; } - if (preg_match('/^cs\./', $sortfield) || preg_match('/^c\./', $sortfield) || preg_match('/^pc\./', $sortfield) || preg_match('/^pct\./', $sortfield)) $sql.= $db->order($sortfield, $sortorder); + if (preg_match('/^cs\./', $sortfield) || preg_match('/^c\./', $sortfield) || preg_match('/^pc\./', $sortfield) || preg_match('/^pct\./', $sortfield)) $sql .= $db->order($sortfield, $sortorder); //$sql.= $db->plimit($limit+1,$offset); //print $sql; dol_syslog("compta/charges/index.php: select payment", LOG_DEBUG); - $resql=$db->query($sql); + $resql = $db->query($sql); if ($resql) { $num = $db->num_rows($resql); @@ -179,14 +179,14 @@ if (! empty($conf->tax->enabled) && $user->rights->tax->charges->lire) $obj = $db->fetch_object($resql); print ''; // Date - $date=$obj->periode; - if (empty($date)) $date=$obj->date_ech; + $date = $obj->periode; + if (empty($date)) $date = $obj->date_ech; print ''; // Label print ''; // Type @@ -194,8 +194,8 @@ if (! empty($conf->tax->enabled) && $user->rights->tax->charges->lire) // Expected to pay print ''; // Ref payment - $payment_sc_static->id=$obj->pid; - $payment_sc_static->ref=$obj->pid; + $payment_sc_static->id = $obj->pid; + $payment_sc_static->ref = $obj->pid; print '\n"; // Date payment print ''; @@ -204,18 +204,18 @@ if (! empty($conf->tax->enabled) && $user->rights->tax->charges->lire) if ($obj->payment_code) print $langs->trans("PaymentTypeShort".$obj->payment_code).' '; print $obj->num_payment.''; // Account - if (! empty($conf->banque->enabled)) + if (!empty($conf->banque->enabled)) { print ''; - print ''; // A total here has no sense + print ''; // A total here has no sense print ''; print ''; print ''; - if (! empty($conf->banque->enabled)) print ''; + if (!empty($conf->banque->enabled)) print ''; print '"; print ""; } @@ -249,39 +249,39 @@ if (! empty($conf->tax->enabled) && $user->rights->tax->charges->lire) } // VAT -if (! empty($conf->tax->enabled) && $user->rights->tax->charges->lire) +if (!empty($conf->tax->enabled) && $user->rights->tax->charges->lire) { - if (! $mode || $mode != 'sconly') + if (!$mode || $mode != 'sconly') { print "
"; $tva = new Tva($db); - print load_fiche_titre($langs->trans("VATPayments").($year?' ('.$langs->trans("Year").' '.$year.')':''), '', ''); + print load_fiche_titre($langs->trans("VATPayments").($year ? ' ('.$langs->trans("Year").' '.$year.')' : ''), '', ''); $sql = "SELECT pv.rowid, pv.amount, pv.label, pv.datev as dm, pv.fk_bank,"; - $sql.= " pct.code as payment_code,"; - $sql.= " ba.rowid as bid, ba.ref as bref, ba.number as bnumber, ba.account_number, ba.fk_accountancy_journal, ba.label as blabel"; - $sql.= " FROM ".MAIN_DB_PREFIX."tva as pv"; - $sql.= " LEFT JOIN ".MAIN_DB_PREFIX."bank as b ON pv.fk_bank = b.rowid"; - $sql.= " LEFT JOIN ".MAIN_DB_PREFIX."bank_account as ba ON b.fk_account = ba.rowid"; - $sql.= " LEFT JOIN ".MAIN_DB_PREFIX."c_paiement as pct ON pv.fk_typepayment = pct.id"; - $sql.= " WHERE pv.entity IN (".getEntity("tax").")"; + $sql .= " pct.code as payment_code,"; + $sql .= " ba.rowid as bid, ba.ref as bref, ba.number as bnumber, ba.account_number, ba.fk_accountancy_journal, ba.label as blabel"; + $sql .= " FROM ".MAIN_DB_PREFIX."tva as pv"; + $sql .= " LEFT JOIN ".MAIN_DB_PREFIX."bank as b ON pv.fk_bank = b.rowid"; + $sql .= " LEFT JOIN ".MAIN_DB_PREFIX."bank_account as ba ON b.fk_account = ba.rowid"; + $sql .= " LEFT JOIN ".MAIN_DB_PREFIX."c_paiement as pct ON pv.fk_typepayment = pct.id"; + $sql .= " WHERE pv.entity IN (".getEntity("tax").")"; if ($year > 0) { // 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 - $sql.= " AND pv.datev between '".$db->idate(dol_get_first_day($year, 1, false))."' AND '".$db->idate(dol_get_last_day($year, 12, false))."'"; + $sql .= " AND pv.datev between '".$db->idate(dol_get_first_day($year, 1, false))."' AND '".$db->idate(dol_get_last_day($year, 12, false))."'"; } - if (preg_match('/^pv\./', $sortfield)) $sql.= $db->order($sortfield, $sortorder); + if (preg_match('/^pv\./', $sortfield)) $sql .= $db->order($sortfield, $sortorder); $result = $db->query($sql); if ($result) { $num = $db->num_rows($result); $i = 0; - $total = 0 ; - print '
'.dol_print_date($date, 'day').''; - $socialcontrib->id=$obj->rowid; - $socialcontrib->ref=$obj->label; - $socialcontrib->label=$obj->label; + $socialcontrib->id = $obj->rowid; + $socialcontrib->ref = $obj->label; + $socialcontrib->label = $obj->label; print $socialcontrib->getNomUrl(1, '20'); print ''.price($obj->total).''.$payment_sc_static->getNomUrl(1)."'.dol_print_date($db->jdate($obj->datep), 'day').''; if ($obj->fk_bank > 0) { //$accountstatic->fetch($obj->fk_bank); - $accountstatic->id=$obj->bid; - $accountstatic->ref=$obj->bref; - $accountstatic->number=$obj->bnumber; - $accountstatic->accountancy_number=$obj->account_number; - $accountstatic->accountancy_journal=$obj->accountancy_journal; - $accountstatic->label=$obj->blabel; + $accountstatic->id = $obj->bid; + $accountstatic->ref = $obj->bref; + $accountstatic->number = $obj->bnumber; + $accountstatic->accountancy_number = $obj->account_number; + $accountstatic->accountancy_journal = $obj->accountancy_journal; + $accountstatic->label = $obj->blabel; print $accountstatic->getNomUrl(1); } else print ' '; @@ -233,11 +233,11 @@ if (! empty($conf->tax->enabled) && $user->rights->tax->charges->lire) $i++; } print '
'.$langs->trans("Total").'   '.price($totalpaye)."
'; + $total = 0; + print '
'; print ''; print_liste_field_titre("PeriodEndDate", $_SERVER["PHP_SELF"], "pv.datev", "", $param, 'width="140px"', $sortfield, $sortorder); print_liste_field_titre("Label", $_SERVER["PHP_SELF"], "pv.label", "", $param, '', $sortfield, $sortorder); @@ -289,10 +289,10 @@ if (! empty($conf->tax->enabled) && $user->rights->tax->charges->lire) print_liste_field_titre("RefPayment", $_SERVER["PHP_SELF"], "pv.rowid", "", $param, '', $sortfield, $sortorder); print_liste_field_titre("DatePayment", $_SERVER["PHP_SELF"], "pv.datev", "", $param, 'align="center"', $sortfield, $sortorder); print_liste_field_titre("Type", $_SERVER["PHP_SELF"], "pct.code", "", $param, '', $sortfield, $sortorder); - if (! empty($conf->banque->enabled)) print_liste_field_titre("Account", $_SERVER["PHP_SELF"], "ba.label", "", $param, "", $sortfield, $sortorder); + if (!empty($conf->banque->enabled)) print_liste_field_titre("Account", $_SERVER["PHP_SELF"], "ba.label", "", $param, "", $sortfield, $sortorder); print_liste_field_titre("PayedByThisPayment", $_SERVER["PHP_SELF"], "pv.amount", "", $param, 'class="right"', $sortfield, $sortorder); print "\n"; - $var=1; + $var = 1; while ($i < $num) { $obj = $db->fetch_object($result); @@ -308,8 +308,8 @@ if (! empty($conf->tax->enabled) && $user->rights->tax->charges->lire) print '"; // Ref payment - $tva_static->id=$obj->rowid; - $tva_static->ref=$obj->rowid; + $tva_static->id = $obj->rowid; + $tva_static->ref = $obj->rowid; print '\n"; // Date @@ -321,18 +321,18 @@ if (! empty($conf->tax->enabled) && $user->rights->tax->charges->lire) print $obj->num_payment.''; // Account - if (! empty($conf->banque->enabled)) + if (!empty($conf->banque->enabled)) { print '
'.price($obj->amount)."'.$tva_static->getNomUrl(1)."'; if ($obj->fk_bank > 0) { //$accountstatic->fetch($obj->fk_bank); - $accountstatic->id=$obj->bid; - $accountstatic->ref=$obj->bref; - $accountstatic->number=$obj->bnumber; - $accountstatic->accountancy_number=$obj->account_number; - $accountstatic->accountancy_journal=$obj->accountancy_journal; - $accountstatic->label=$obj->blabel; + $accountstatic->id = $obj->bid; + $accountstatic->ref = $obj->bref; + $accountstatic->number = $obj->bnumber; + $accountstatic->accountancy_number = $obj->account_number; + $accountstatic->accountancy_journal = $obj->accountancy_journal; + $accountstatic->label = $obj->blabel; print $accountstatic->getNomUrl(1); } else print ' '; @@ -365,56 +365,56 @@ if (! empty($conf->tax->enabled) && $user->rights->tax->charges->lire) } // Localtax -if($mysoc->localtax1_assuj=="1" && $mysoc->localtax2_assuj=="1") +if ($mysoc->localtax1_assuj == "1" && $mysoc->localtax2_assuj == "1") { - $j=1; - $numlt=3; + $j = 1; + $numlt = 3; } -elseif($mysoc->localtax1_assuj=="1") +elseif ($mysoc->localtax1_assuj == "1") { - $j=1; - $numlt=2; + $j = 1; + $numlt = 2; } -elseif($mysoc->localtax2_assuj=="1") +elseif ($mysoc->localtax2_assuj == "1") { - $j=2; - $numlt=3; + $j = 2; + $numlt = 3; } else { - $j=0; - $numlt=0; + $j = 0; + $numlt = 0; } -while($j<$numlt) +while ($j < $numlt) { - if (! $mode || $mode != 'sconly') + if (!$mode || $mode != 'sconly') { print "
"; $tva = new Tva($db); - print load_fiche_titre($langs->transcountry(($j==1?"LT1Payments":"LT2Payments"), $mysoc->country_code).($year?' ('.$langs->trans("Year").' '.$year.')':''), '', ''); + print load_fiche_titre($langs->transcountry(($j == 1 ? "LT1Payments" : "LT2Payments"), $mysoc->country_code).($year ? ' ('.$langs->trans("Year").' '.$year.')' : ''), '', ''); $sql = "SELECT pv.rowid, pv.amount, pv.label, pv.datev as dm, pv.datep as dp"; - $sql.= " FROM ".MAIN_DB_PREFIX."localtax as pv"; - $sql.= " WHERE pv.entity = ".$conf->entity." AND localtaxtype = ".$j ; + $sql .= " FROM ".MAIN_DB_PREFIX."localtax as pv"; + $sql .= " WHERE pv.entity = ".$conf->entity." AND localtaxtype = ".$j; if ($year > 0) { // 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 - $sql.= " AND pv.datev between '".$db->idate(dol_get_first_day($year, 1, false))."' AND '".$db->idate(dol_get_last_day($year, 12, false))."'"; + $sql .= " AND pv.datev between '".$db->idate(dol_get_first_day($year, 1, false))."' AND '".$db->idate(dol_get_last_day($year, 12, false))."'"; } - if (preg_match('/^pv/', $sortfield)) $sql.= $db->order($sortfield, $sortorder); + if (preg_match('/^pv/', $sortfield)) $sql .= $db->order($sortfield, $sortorder); $result = $db->query($sql); if ($result) { $num = $db->num_rows($result); $i = 0; - $total = 0 ; - print ''; + $total = 0; + print '
'; print ''; print_liste_field_titre("PeriodEndDate", $_SERVER["PHP_SELF"], "pv.datev", "", $param, 'width="120"', $sortfield, $sortorder); print_liste_field_titre("Label", $_SERVER["PHP_SELF"], "pv.label", "", $param, '', $sortfield, $sortorder); @@ -435,8 +435,8 @@ while($j<$numlt) print "\n"; // Ref payment - $tva_static->id=$obj->rowid; - $tva_static->ref=$obj->rowid; + $tva_static->id = $obj->rowid; + $tva_static->ref = $obj->rowid; print '\n"; print '\n"; @@ -462,47 +462,47 @@ while($j<$numlt) // Payment Salary -if (! empty($conf->salaries->enabled) && ! empty($user->rights->salaries->read)) +if (!empty($conf->salaries->enabled) && !empty($user->rights->salaries->read)) { - if (! $mode || $mode != 'sconly') + if (!$mode || $mode != 'sconly') { $sal = new PaymentSalary($db); print "
"; - print load_fiche_titre($langs->trans("SalariesPayments").($year?' ('.$langs->trans("Year").' '.$year.')':''), '', ''); + print load_fiche_titre($langs->trans("SalariesPayments").($year ? ' ('.$langs->trans("Year").' '.$year.')' : ''), '', ''); $sql = "SELECT s.rowid, s.amount, s.label, s.datep as datep, s.datev as datev, s.datesp, s.dateep, s.salary, s.fk_bank, u.salary as current_salary,"; - $sql.= " pct.code as payment_code,"; - $sql.= " ba.rowid as bid, ba.ref as bref, ba.number as bnumber, ba.account_number, ba.fk_accountancy_journal, ba.label as blabel"; - $sql.= " FROM ".MAIN_DB_PREFIX."payment_salary as s"; - $sql.= " LEFT JOIN ".MAIN_DB_PREFIX."bank as b ON s.fk_bank = b.rowid"; - $sql.= " LEFT JOIN ".MAIN_DB_PREFIX."bank_account as ba ON b.fk_account = ba.rowid"; - $sql.= " LEFT JOIN ".MAIN_DB_PREFIX."c_paiement as pct ON s.fk_typepayment = pct.id"; - $sql.= " , ".MAIN_DB_PREFIX."user as u"; - $sql.= " WHERE s.entity IN (".getEntity('user').")"; - $sql.= " AND u.rowid = s.fk_user"; + $sql .= " pct.code as payment_code,"; + $sql .= " ba.rowid as bid, ba.ref as bref, ba.number as bnumber, ba.account_number, ba.fk_accountancy_journal, ba.label as blabel"; + $sql .= " FROM ".MAIN_DB_PREFIX."payment_salary as s"; + $sql .= " LEFT JOIN ".MAIN_DB_PREFIX."bank as b ON s.fk_bank = b.rowid"; + $sql .= " LEFT JOIN ".MAIN_DB_PREFIX."bank_account as ba ON b.fk_account = ba.rowid"; + $sql .= " LEFT JOIN ".MAIN_DB_PREFIX."c_paiement as pct ON s.fk_typepayment = pct.id"; + $sql .= " , ".MAIN_DB_PREFIX."user as u"; + $sql .= " WHERE s.entity IN (".getEntity('user').")"; + $sql .= " AND u.rowid = s.fk_user"; if ($year > 0) { - $sql.= " AND (s.datesp between '".$db->idate(dol_get_first_day($year, 1, false))."' AND '".$db->idate(dol_get_last_day($year, 12, false))."'"; - $sql.= " OR s.dateep between '".$db->idate(dol_get_first_day($year, 1, false))."' AND '".$db->idate(dol_get_last_day($year, 12, false))."')"; + $sql .= " AND (s.datesp between '".$db->idate(dol_get_first_day($year, 1, false))."' AND '".$db->idate(dol_get_last_day($year, 12, false))."'"; + $sql .= " OR s.dateep between '".$db->idate(dol_get_first_day($year, 1, false))."' AND '".$db->idate(dol_get_last_day($year, 12, false))."')"; } - if (preg_match('/^s\./', $sortfield)) $sql.= $db->order($sortfield, $sortorder); + if (preg_match('/^s\./', $sortfield)) $sql .= $db->order($sortfield, $sortorder); $result = $db->query($sql); if ($result) { $num = $db->num_rows($result); $i = 0; - $total = 0 ; - print '
".$obj->label."'.$tva_static->getNomUrl(1)."'.dol_print_date($db->jdate($obj->dp), 'day')."
'; + $total = 0; + print '
'; print ''; print_liste_field_titre("PeriodEndDate", $_SERVER["PHP_SELF"], "s.dateep", "", $param, 'width="140px"', $sortfield, $sortorder); print_liste_field_titre("Label", $_SERVER["PHP_SELF"], "s.label", "", $param, '', $sortfield, $sortorder); print_liste_field_titre("RefPayment", $_SERVER["PHP_SELF"], "s.rowid", "", $param, '', $sortfield, $sortorder); print_liste_field_titre("DatePayment", $_SERVER["PHP_SELF"], "s.datep", "", $param, 'align="center"', $sortfield, $sortorder); print_liste_field_titre("Type", $_SERVER["PHP_SELF"], "pct.code", "", $param, '', $sortfield, $sortorder); - if (! empty($conf->banque->enabled)) print_liste_field_titre("Account", $_SERVER["PHP_SELF"], "ba.label", "", $param, "", $sortfield, $sortorder); + if (!empty($conf->banque->enabled)) print_liste_field_titre("Account", $_SERVER["PHP_SELF"], "ba.label", "", $param, "", $sortfield, $sortorder); print_liste_field_titre("PayedByThisPayment", $_SERVER["PHP_SELF"], "s.amount", "", $param, 'class="right"', $sortfield, $sortorder); print "\n"; @@ -520,8 +520,8 @@ if (! empty($conf->salaries->enabled) && ! empty($user->rights->salaries->read)) print "\n"; // Ref payment - $sal_static->id=$obj->rowid; - $sal_static->ref=$obj->rowid; + $sal_static->id = $obj->rowid; + $sal_static->ref = $obj->rowid; print '\n"; // Date @@ -533,18 +533,18 @@ if (! empty($conf->salaries->enabled) && ! empty($user->rights->salaries->read)) print $obj->num_payment.''; // Account - if (! empty($conf->banque->enabled)) + if (!empty($conf->banque->enabled)) { print ''; // Auto generate documents - if (! empty($conf->global->INVOICE_REC_CAN_DISABLE_DOCUMENT_FILE_GENERATION)) + if (!empty($conf->global->INVOICE_REC_CAN_DISABLE_DOCUMENT_FILE_GENERATION)) { print ''; print ''; print ''; print ''; @@ -1681,25 +1681,25 @@ else // Lines - print ' - - + print ' + + - + '; - if (! empty($conf->use_javascript_ajax) && $object->statut == 0) { - include DOL_DOCUMENT_ROOT . '/core/tpl/ajaxrow.tpl.php'; + if (!empty($conf->use_javascript_ajax) && $object->statut == 0) { + include DOL_DOCUMENT_ROOT.'/core/tpl/ajaxrow.tpl.php'; } print '
'; print '
".$obj->label."'.$sal_static->getNomUrl(1)."'; if ($obj->fk_bank > 0) { //$accountstatic->fetch($obj->fk_bank); - $accountstatic->id=$obj->bid; - $accountstatic->ref=$obj->bref; - $accountstatic->number=$obj->bnumber; - $accountstatic->accountancy_number=$obj->account_number; - $accountstatic->accountancy_journal=$obj->accountancy_journal; - $accountstatic->label=$obj->blabel; + $accountstatic->id = $obj->bid; + $accountstatic->ref = $obj->bref; + $accountstatic->number = $obj->bnumber; + $accountstatic->accountancy_number = $obj->account_number; + $accountstatic->accountancy_journal = $obj->accountancy_journal; + $accountstatic->label = $obj->blabel; print $accountstatic->getNomUrl(1); } else print ' '; diff --git a/htdocs/compta/clients.php b/htdocs/compta/clients.php index 15f3504268b..8cfeeda613e 100644 --- a/htdocs/compta/clients.php +++ b/htdocs/compta/clients.php @@ -141,7 +141,7 @@ if ($resql) print ''; - print ''; + print '
'; print ''; print_liste_field_titre("Company", $_SERVER["PHP_SELF"], "s.nom", "", "", 'valign="center"', $sortfield, $sortorder); diff --git a/htdocs/compta/deplacement/card.php b/htdocs/compta/deplacement/card.php index dd56e611545..5f469a2cef6 100644 --- a/htdocs/compta/deplacement/card.php +++ b/htdocs/compta/deplacement/card.php @@ -29,7 +29,7 @@ require '../../main.inc.php'; require_once DOL_DOCUMENT_ROOT.'/core/lib/trip.lib.php'; require_once DOL_DOCUMENT_ROOT.'/compta/deplacement/class/deplacement.class.php'; require_once DOL_DOCUMENT_ROOT.'/core/class/html.formfile.class.php'; -if (! empty($conf->projet->enabled)) +if (!empty($conf->projet->enabled)) { require_once DOL_DOCUMENT_ROOT.'/projet/class/project.class.php'; } @@ -40,7 +40,7 @@ $langs->load("trips"); // Security check $id = GETPOST('id', 'int'); -if ($user->socid) $socid=$user->socid; +if ($user->socid) $socid = $user->socid; $result = restrictedArea($user, 'deplacement', $id, ''); $action = GETPOST('action', 'alpha'); @@ -49,16 +49,16 @@ $confirm = GETPOST('confirm', 'alpha'); $object = new Deplacement($db); // Initialize technical object to manage hooks of page. Note that conf->hooks_modules contains array of hook context -$hookmanager->initHooks(array('tripsandexpensescard','globalcard')); +$hookmanager->initHooks(array('tripsandexpensescard', 'globalcard')); -$permissionnote=$user->rights->deplacement->creer; // Used by the include of actions_setnotes.inc.php +$permissionnote = $user->rights->deplacement->creer; // Used by the include of actions_setnotes.inc.php /* * Actions */ -include DOL_DOCUMENT_ROOT.'/core/actions_setnotes.inc.php'; // Must be include, not includ_once +include DOL_DOCUMENT_ROOT.'/core/actions_setnotes.inc.php'; // Must be include, not includ_once if ($action == 'validate' && $user->rights->deplacement->creer) { @@ -68,7 +68,7 @@ if ($action == 'validate' && $user->rights->deplacement->creer) $result = $object->setStatut(1); if ($result > 0) { - header("Location: " . $_SERVER["PHP_SELF"] . "?id=" . $id); + header("Location: ".$_SERVER["PHP_SELF"]."?id=".$id); exit; } else @@ -86,7 +86,7 @@ elseif ($action == 'classifyrefunded' && $user->rights->deplacement->creer) $result = $object->setStatut(2); if ($result > 0) { - header("Location: " . $_SERVER["PHP_SELF"] . "?id=" . $id); + header("Location: ".$_SERVER["PHP_SELF"]."?id=".$id); exit; } else @@ -98,7 +98,7 @@ elseif ($action == 'classifyrefunded' && $user->rights->deplacement->creer) elseif ($action == 'confirm_delete' && $confirm == "yes" && $user->rights->deplacement->supprimer) { - $result=$object->delete($id); + $result = $object->delete($id); if ($result >= 0) { header("Location: index.php"); @@ -112,20 +112,20 @@ elseif ($action == 'confirm_delete' && $confirm == "yes" && $user->rights->depla elseif ($action == 'add' && $user->rights->deplacement->creer) { - if (! GETPOST('cancel', 'alpha')) + if (!GETPOST('cancel', 'alpha')) { - $error=0; + $error = 0; $object->date = dol_mktime(12, 0, 0, GETPOST('remonth', 'int'), GETPOST('reday', 'int'), GETPOST('reyear', 'int')); - $object->km = price2num(GETPOST('km', 'alpha'), 'MU'); // Not 'int', it may be a formated amount + $object->km = price2num(GETPOST('km', 'alpha'), 'MU'); // Not 'int', it may be a formated amount $object->type = GETPOST('type', 'alpha'); - $object->socid = GETPOST('socid', 'int'); - $object->fk_user = GETPOST('fk_user', 'int'); - $object->note_private = GETPOST('note_private', 'alpha'); + $object->socid = GETPOST('socid', 'int'); + $object->fk_user = GETPOST('fk_user', 'int'); + $object->note_private = GETPOST('note_private', 'alpha'); $object->note_public = GETPOST('note_public', 'alpha'); $object->statut = 0; - if (! $object->date) + if (!$object->date) { setEventMessages($langs->trans("ErrorFieldRequired", $langs->transnoentitiesnoconv("Date")), null, 'errors'); $error++; @@ -135,30 +135,30 @@ elseif ($action == 'add' && $user->rights->deplacement->creer) setEventMessages($langs->trans("ErrorFieldRequired", $langs->transnoentitiesnoconv("Type")), null, 'errors'); $error++; } - if (! ($object->fk_user > 0)) + if (!($object->fk_user > 0)) { setEventMessages($langs->trans("ErrorFieldRequired", $langs->transnoentitiesnoconv("Person")), null, 'errors'); $error++; } - if (! $error) + if (!$error) { $id = $object->create($user); if ($id > 0) { - header("Location: " . $_SERVER["PHP_SELF"] . "?id=" . $id); + header("Location: ".$_SERVER["PHP_SELF"]."?id=".$id); exit; } else { setEventMessages($object->error, $object->errors, 'errors'); - $action='create'; + $action = 'create'; } } else { - $action='create'; + $action = 'create'; } } else @@ -171,23 +171,23 @@ elseif ($action == 'add' && $user->rights->deplacement->creer) // Update record elseif ($action == 'update' && $user->rights->deplacement->creer) { - if (! GETPOST('cancel', 'alpha')) + if (!GETPOST('cancel', 'alpha')) { $result = $object->fetch($id); $object->date = dol_mktime(12, 0, 0, GETPOST('remonth', 'int'), GETPOST('reday', 'int'), GETPOST('reyear', 'int')); - $object->km = price2num(GETPOST('km', 'alpha'), 'MU'); // Not 'int', it may be a formated amount + $object->km = price2num(GETPOST('km', 'alpha'), 'MU'); // Not 'int', it may be a formated amount $object->type = GETPOST('type', 'alpha'); - $object->socid = GETPOST('socid', 'int'); - $object->fk_user = GETPOST('fk_user', 'int'); - $object->note_private = GETPOST('note_private', 'alpha'); - $object->note_public = GETPOST('note_public', 'alpha'); + $object->socid = GETPOST('socid', 'int'); + $object->fk_user = GETPOST('fk_user', 'int'); + $object->note_private = GETPOST('note_private', 'alpha'); + $object->note_public = GETPOST('note_public', 'alpha'); $result = $object->update($user); if ($result > 0) { - header("Location: " . $_SERVER["PHP_SELF"] . "?id=" . $id); + header("Location: ".$_SERVER["PHP_SELF"]."?id=".$id); exit; } else @@ -197,7 +197,7 @@ elseif ($action == 'update' && $user->rights->deplacement->creer) } else { - header("Location: " . $_SERVER["PHP_SELF"] . "?id=" . $id); + header("Location: ".$_SERVER["PHP_SELF"]."?id=".$id); exit; } } @@ -206,22 +206,22 @@ elseif ($action == 'update' && $user->rights->deplacement->creer) elseif ($action == 'classin' && $user->rights->deplacement->creer) { $object->fetch($id); - $result=$object->setProject(GETPOST('projectid', 'int')); + $result = $object->setProject(GETPOST('projectid', 'int')); if ($result < 0) dol_print_error($db, $object->error); } // Set fields elseif ($action == 'setdated' && $user->rights->deplacement->creer) { - $dated=dol_mktime(GETPOST('datedhour', 'int'), GETPOST('datedmin', 'int'), GETPOST('datedsec', 'int'), GETPOST('datedmonth', 'int'), GETPOST('datedday', 'int'), GETPOST('datedyear', 'int')); + $dated = dol_mktime(GETPOST('datedhour', 'int'), GETPOST('datedmin', 'int'), GETPOST('datedsec', 'int'), GETPOST('datedmonth', 'int'), GETPOST('datedday', 'int'), GETPOST('datedyear', 'int')); $object->fetch($id); - $result=$object->setValueFrom('dated', $dated, '', '', 'date', '', $user, 'DEPLACEMENT_MODIFY'); + $result = $object->setValueFrom('dated', $dated, '', '', 'date', '', $user, 'DEPLACEMENT_MODIFY'); if ($result < 0) dol_print_error($db, $object->error); } elseif ($action == 'setkm' && $user->rights->deplacement->creer) { $object->fetch($id); - $result=$object->setValueFrom('km', GETPOST('km', 'int'), '', null, 'text', '', $user, 'DEPLACEMENT_MODIFY'); + $result = $object->setValueFrom('km', GETPOST('km', 'int'), '', null, 'text', '', $user, 'DEPLACEMENT_MODIFY'); if ($result < 0) dol_print_error($db, $object->error); } @@ -246,11 +246,11 @@ if ($action == 'create') $datec = dol_mktime(12, 0, 0, GETPOST('remonth', 'int'), GETPOST('reday', 'int'), GETPOST('reyear', 'int')); - print '' . "\n"; + print ''."\n"; print ''; print ''; - print '
'; + print '
'; print ""; print '"; print ''; // Km - print ''; + print ''; // Company print ""; @@ -300,8 +300,8 @@ if ($action == 'create') } // Other attributes - $parameters=array(); - $reshook=$hookmanager->executeHooks('formObjectOptions', $parameters, $object, $action); // Note that $action and $object may have been modified by hook + $parameters = array(); + $reshook = $hookmanager->executeHooks('formObjectOptions', $parameters, $object, $action); // Note that $action and $object may have been modified by hook print $hookmanager->resPrint; print '
'.$langs->trans("Type").''; @@ -264,11 +264,11 @@ if ($action == 'create') print "
'.$langs->trans("Date").''; - print $form->selectDate($datec?$datec:-1, '', '', '', '', 'add', 1, 1); + print $form->selectDate($datec ? $datec : -1, '', '', '', '', 'add', 1, 1); print '
'.$langs->trans("FeesKilometersOrAmout").'
'.$langs->trans("FeesKilometersOrAmout").'
'; @@ -334,12 +334,12 @@ elseif ($id) $soc->fetch($object->socid); } - print '' . "\n"; + print ''."\n"; print ''; print ''; print ''; - print ''; + print '
'; // Ref print ""; @@ -350,13 +350,13 @@ elseif ($id) // Type print ""; print ''; // Who print ""; print ''; // Date @@ -397,8 +397,8 @@ elseif ($id) } // Other attributes - $parameters=array(); - $reshook=$hookmanager->executeHooks('formObjectOptions', $parameters, $object, $action); // Note that $action and $object may have been modified by hook + $parameters = array(); + $reshook = $hookmanager->executeHooks('formObjectOptions', $parameters, $object, $action); // Note that $action and $object may have been modified by hook print $hookmanager->resPrint; print '
'.$langs->trans("Type").''; - $form->select_type_fees(GETPOST('type', 'int')?GETPOST('type', 'int'):$object->type, 'type', 0); + $form->select_type_fees(GETPOST('type', 'int') ?GETPOST('type', 'int') : $object->type, 'type', 0); print '
'.$langs->trans("Person").''; - print $form->select_dolusers(GETPOST('fk_user', 'int')?GETPOST('fk_user', 'int'):$object->fk_user, 'fk_user', 0, '', 0, '', '', 0, 0, 0, '', 0, '', 'maxwidth300'); + print $form->select_dolusers(GETPOST('fk_user', 'int') ?GETPOST('fk_user', 'int') : $object->fk_user, 'fk_user', 0, '', 0, '', '', 0, 0, 0, '', 0, '', 'maxwidth300'); print '
'; @@ -426,9 +426,9 @@ elseif ($id) $soc = new Societe($db); if ($object->socid) $soc->fetch($object->socid); - print ''; + print '
'; - $linkback = ''.$langs->trans("BackToList").''; + $linkback = ''.$langs->trans("BackToList").''; // Ref print ''; @@ -472,7 +472,7 @@ elseif ($id) print ''; // Project - if (! empty($conf->projet->enabled)) + if (!empty($conf->projet->enabled)) { $langs->load('projects'); print ''; @@ -505,8 +505,8 @@ elseif ($id) print ''; // Other attributes - $parameters=array('socid'=>$object->id); - include DOL_DOCUMENT_ROOT . '/core/tpl/extrafields_view.tpl.php'; + $parameters = array('socid'=>$object->id); + include DOL_DOCUMENT_ROOT.'/core/tpl/extrafields_view.tpl.php'; print "
'.$langs->trans("Ref").''; @@ -446,7 +446,7 @@ elseif ($id) // Who print '
'.$langs->trans("Person").''; - $userfee=new User($db); + $userfee = new User($db); $userfee->fetch($object->fk_user); print $userfee->getNomUrl(1); print '
'.$langs->trans("Status").''.$object->getLibStatut(4).'

"; diff --git a/htdocs/compta/deplacement/document.php b/htdocs/compta/deplacement/document.php index 96c8013c18c..2829e257b3b 100644 --- a/htdocs/compta/deplacement/document.php +++ b/htdocs/compta/deplacement/document.php @@ -55,22 +55,22 @@ if (empty($page) || $page == -1) { $page = 0; } // If $page is not defined, $offset = $conf->liste_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 Deplacement($db); $object->fetch($id, $ref); $upload_dir = $conf->deplacement->dir_output.'/'.dol_sanitizeFileName($object->ref); -$modulepart='trip'; +$modulepart = 'trip'; /* * Actions */ -include_once DOL_DOCUMENT_ROOT . '/core/actions_linkedfiles.inc.php'; +include_once DOL_DOCUMENT_ROOT.'/core/actions_linkedfiles.inc.php'; /* @@ -86,23 +86,23 @@ if ($object->id) { $object->fetch_thirdparty(); - $head=trip_prepare_head($object); + $head = trip_prepare_head($object); dol_fiche_head($head, 'documents', $langs->trans("TripCard"), 0, 'trip'); // 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) + $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) { - $totalsize+=$file['size']; + $totalsize += $file['size']; } print ''; - $linkback = ''.$langs->trans("BackToList").''; + $linkback = ''.$langs->trans("BackToList").''; // Ref print '
'.$langs->trans("Ref").''; @@ -120,8 +120,8 @@ if ($object->id) $modulepart = 'deplacement'; $permission = $user->rights->deplacement->creer; - $param = '&id=' . $object->id; - include_once DOL_DOCUMENT_ROOT . '/core/tpl/document_actions_post_headers.tpl.php'; + $param = '&id='.$object->id; + include_once DOL_DOCUMENT_ROOT.'/core/tpl/document_actions_post_headers.tpl.php'; } else { diff --git a/htdocs/compta/deplacement/index.php b/htdocs/compta/deplacement/index.php index 659744a2ba0..fde600aff8f 100644 --- a/htdocs/compta/deplacement/index.php +++ b/htdocs/compta/deplacement/index.php @@ -97,7 +97,7 @@ print '
'; // Statistics -print ''; +print '
'; print ''; print ''; print "\n"; @@ -160,7 +160,7 @@ if ($result) $i = 0; - print '
'.$langs->trans("Statistics").'
'; + print '
'; print ''; print ''; print ''; diff --git a/htdocs/compta/deplacement/list.php b/htdocs/compta/deplacement/list.php index 6d5d952d104..3f92e9127da 100644 --- a/htdocs/compta/deplacement/list.php +++ b/htdocs/compta/deplacement/list.php @@ -120,7 +120,7 @@ if ($resql) $i = 0; print ''."\n"; - print '
'.$langs->trans("BoxTitleLastModifiedExpenses", min($max, $num)).''.$langs->trans("FeesKilometersOrAmout").'
'; + print '
'; print ""; print_liste_field_titre("Ref", $_SERVER["PHP_SELF"], "d.rowid", "", "&socid=$socid", '', $sortfield, $sortorder); print_liste_field_titre("Type", $_SERVER["PHP_SELF"], "d.type", "", "&socid=$socid", '', $sortfield, $sortorder); diff --git a/htdocs/compta/deplacement/stats/index.php b/htdocs/compta/deplacement/stats/index.php index ccb2ecb60fe..d313224cf53 100644 --- a/htdocs/compta/deplacement/stats/index.php +++ b/htdocs/compta/deplacement/stats/index.php @@ -228,7 +228,7 @@ print '
'; // Show filter box print ''; print ''; -print '
'; +print '
'; print ''; // Company print ''; // Multicurrency rate @@ -1381,19 +1381,19 @@ else print '
'.$langs->trans("Filter").'
'.$langs->trans("ThirdParty").''; @@ -253,7 +253,7 @@ print ''; print '

'; print '
'; -print ''; +print '
'; print ''; print ''; print ''; @@ -291,7 +291,7 @@ print '
'; // Show graphs -print '
'.$langs->trans("Year").''.$langs->trans("Number").'
'; // Multicurrency - if (! empty($conf->multicurrency->enabled)) + if (!empty($conf->multicurrency->enabled)) { // Multicurrency code print ''; @@ -1364,13 +1364,13 @@ else print '
'; +print ''; if ($action != 'editmode' && $user->rights->facture->creer) - print ''; + print ''; print '
'; if ($mesg) { print $mesg; } else { print $px1->show(); diff --git a/htdocs/compta/facture/card-rec.php b/htdocs/compta/facture/card-rec.php index bde69045bb7..e5139b061aa 100644 --- a/htdocs/compta/facture/card-rec.php +++ b/htdocs/compta/facture/card-rec.php @@ -34,14 +34,14 @@ require '../../main.inc.php'; require_once DOL_DOCUMENT_ROOT.'/compta/facture/class/facture-rec.class.php'; require_once DOL_DOCUMENT_ROOT.'/product/class/product.class.php'; require_once DOL_DOCUMENT_ROOT.'/core/class/html.formother.class.php'; -if (! empty($conf->projet->enabled)) { - include_once DOL_DOCUMENT_ROOT . '/projet/class/project.class.php'; +if (!empty($conf->projet->enabled)) { + include_once DOL_DOCUMENT_ROOT.'/projet/class/project.class.php'; //include_once DOL_DOCUMENT_ROOT . '/core/class/html.formprojet.class.php'; } -require_once DOL_DOCUMENT_ROOT . '/core/class/html.formprojet.class.php'; -require_once DOL_DOCUMENT_ROOT . '/core/class/doleditor.class.php'; -require_once DOL_DOCUMENT_ROOT . '/core/lib/invoice.lib.php'; -require_once DOL_DOCUMENT_ROOT . '/core/class/extrafields.class.php'; +require_once DOL_DOCUMENT_ROOT.'/core/class/html.formprojet.class.php'; +require_once DOL_DOCUMENT_ROOT.'/core/class/doleditor.class.php'; +require_once DOL_DOCUMENT_ROOT.'/core/lib/invoice.lib.php'; +require_once DOL_DOCUMENT_ROOT.'/core/class/extrafields.class.php'; // Load translation files required by the page $langs->loadLangs(array('bills', 'compta', 'admin', 'other', 'products')); @@ -52,29 +52,29 @@ $show_files = GETPOST('show_files', 'int'); $confirm = GETPOST('confirm', 'alpha'); $cancel = GETPOST('cancel', 'alpha'); $toselect = GETPOST('toselect', 'array'); -$contextpage= GETPOST('contextpage', 'aZ')?GETPOST('contextpage', 'aZ'):'invoicetemplatelist'; // To manage different context of search +$contextpage = GETPOST('contextpage', 'aZ') ?GETPOST('contextpage', 'aZ') : 'invoicetemplatelist'; // To manage different context of search // Security check -$id=(GETPOST('facid', 'int')?GETPOST('facid', 'int'):GETPOST('id', 'int')); -$lineid=GETPOST('lineid', 'int'); -$ref=GETPOST('ref', 'alpha'); -if ($user->socid) $socid=$user->socid; +$id = (GETPOST('facid', 'int') ?GETPOST('facid', 'int') : GETPOST('id', 'int')); +$lineid = GETPOST('lineid', 'int'); +$ref = GETPOST('ref', 'alpha'); +if ($user->socid) $socid = $user->socid; $objecttype = 'facture_rec'; if ($action == "create" || $action == "add") $objecttype = ''; $result = restrictedArea($user, 'facture', $id, $objecttype); $projectid = GETPOST('projectid', 'int'); -$year_date_when=GETPOST('year_date_when'); -$month_date_when=GETPOST('month_date_when'); +$year_date_when = GETPOST('year_date_when'); +$month_date_when = GETPOST('month_date_when'); -$limit = GETPOST('limit', 'int')?GETPOST('limit', 'int'):$conf->liste_limit; +$limit = GETPOST('limit', 'int') ?GETPOST('limit', 'int') : $conf->liste_limit; $sortfield = GETPOST("sortfield", 'alpha'); $sortorder = GETPOST("sortorder", 'alpha'); $page = GETPOST("page", 'int'); 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; @@ -89,26 +89,26 @@ if (($id > 0 || $ref) && $action != 'create' && $action != 'add') } // Initialize technical object to manage hooks of page. Note that conf->hooks_modules contains array of hook context -$hookmanager->initHooks(array('invoicereccard','globalcard')); +$hookmanager->initHooks(array('invoicereccard', 'globalcard')); $extrafields = new ExtraFields($db); // fetch optionals attributes and labels $extrafields->fetch_name_optionals_label($object->table_element); -$search_array_options=$extrafields->getOptionalsFromPost($object->table_element, '', 'search_'); +$search_array_options = $extrafields->getOptionalsFromPost($object->table_element, '', 'search_'); $permissionnote = $user->rights->facture->creer; // Used by the include of actions_setnotes.inc.php -$permissiondellink=$user->rights->facture->creer; // Used by the include of actions_dellink.inc.php +$permissiondellink = $user->rights->facture->creer; // Used by the include of actions_dellink.inc.php $permissiontoedit = $user->rights->facture->creer; // Used by the include of actions_lineupdonw.inc.php $usercanread = $user->rights->facture->lire; $usercancreate = $user->rights->facture->creer; $usercanissuepayment = $user->rights->facture->paiement; $usercandelete = $user->rights->facture->supprimer; -$usercanvalidate = ((empty($conf->global->MAIN_USE_ADVANCED_PERMS) && $usercancreate) || (! empty($conf->global->MAIN_USE_ADVANCED_PERMS) && ! empty($user->rights->facture->invoice_advance->validate))); +$usercanvalidate = ((empty($conf->global->MAIN_USE_ADVANCED_PERMS) && $usercancreate) || (!empty($conf->global->MAIN_USE_ADVANCED_PERMS) && !empty($user->rights->facture->invoice_advance->validate))); $usercansend = (empty($conf->global->MAIN_USE_ADVANCED_PERMS) || $user->rights->facture->invoice_advance->send); $usercanreopen = (empty($conf->global->MAIN_USE_ADVANCED_PERMS) || $user->rights->facture->invoice_advance->reopen); -$usercanunvalidate = ((empty($conf->global->MAIN_USE_ADVANCED_PERMS) && ! empty($usercancreate)) || (! empty($conf->global->MAIN_USE_ADVANCED_PERMS) && ! empty($user->rights->facture->invoice_advance->unvalidate))); +$usercanunvalidate = ((empty($conf->global->MAIN_USE_ADVANCED_PERMS) && !empty($usercancreate)) || (!empty($conf->global->MAIN_USE_ADVANCED_PERMS) && !empty($user->rights->facture->invoice_advance->unvalidate))); $usercanproductignorepricemin = ((!empty($conf->global->MAIN_USE_ADVANCED_PERMS) && empty($user->rights->produit->ignore_price_min_advance)) || empty($conf->global->MAIN_USE_ADVANCED_PERMS)); $usercancreatemargin = $user->rights->margins->creer; @@ -122,8 +122,8 @@ $now = dol_now(); * 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 @@ -131,17 +131,17 @@ if ($reshook < 0) setEventMessages($hookmanager->error, $hookmanager->errors, 'e if (empty($reshook)) { - if (GETPOST('cancel', 'alpha')) $action=''; + if (GETPOST('cancel', 'alpha')) $action = ''; // Selection of new fields include DOL_DOCUMENT_ROOT.'/core/actions_changeselectedfields.inc.php'; // Set note - include DOL_DOCUMENT_ROOT.'/core/actions_setnotes.inc.php'; // Must be include, not include_once + include DOL_DOCUMENT_ROOT.'/core/actions_setnotes.inc.php'; // Must be include, not include_once - include DOL_DOCUMENT_ROOT.'/core/actions_dellink.inc.php'; // Must be include, not include_once + include DOL_DOCUMENT_ROOT.'/core/actions_dellink.inc.php'; // Must be include, not include_once - include DOL_DOCUMENT_ROOT.'/core/actions_lineupdown.inc.php'; // Must be include, not include_once + include DOL_DOCUMENT_ROOT.'/core/actions_lineupdown.inc.php'; // Must be include, not include_once // Mass actions /*$objectclass='MyObject'; @@ -154,20 +154,20 @@ if (empty($reshook)) // Create predefined invoice if ($action == 'add') { - if (! GETPOST('titre', 'nohtml')) + if (!GETPOST('titre', 'nohtml')) { setEventMessages($langs->transnoentities("ErrorFieldRequired", $langs->trans("Title")), null, 'errors'); $action = "create"; $error++; } - $frequency=GETPOST('frequency', 'int'); - $reyear=GETPOST('reyear', 'int'); - $remonth=GETPOST('remonth', 'int'); - $reday=GETPOST('reday', 'int'); - $rehour=GETPOST('rehour', 'int'); - $remin=GETPOST('remin', 'int'); - $nb_gen_max=GETPOST('nb_gen_max', 'int'); + $frequency = GETPOST('frequency', 'int'); + $reyear = GETPOST('reyear', 'int'); + $remonth = GETPOST('remonth', 'int'); + $reday = GETPOST('reday', 'int'); + $rehour = GETPOST('rehour', 'int'); + $remin = GETPOST('remin', 'int'); + $nb_gen_max = GETPOST('nb_gen_max', 'int'); //if (empty($nb_gen_max)) $nb_gen_max =0; if (GETPOST('frequency', 'int')) @@ -186,12 +186,12 @@ if (empty($reshook)) } } - if (! $error) + if (!$error) { - $object->titre = GETPOST('titre', 'nohtml'); // deprecated + $object->titre = GETPOST('titre', 'nohtml'); // deprecated $object->title = GETPOST('titre', 'nohtml'); $object->note_private = GETPOST('note_private', 'none'); - $object->note_public = GETPOST('note_public', 'none'); + $object->note_public = GETPOST('note_public', 'none'); $object->modelpdf = GETPOST('modelpdf', 'alpha'); $object->usenewprice = GETPOST('usenewprice', 'alpha'); @@ -213,7 +213,7 @@ if (empty($reshook)) $srcObject->fetchObjectLinked(); - if (! empty($srcObject->linkedObjectsIds['contrat'])) + if (!empty($srcObject->linkedObjectsIds['contrat'])) { $contractidid = reset($srcObject->linkedObjectsIds['contrat']); @@ -231,7 +231,7 @@ if (empty($reshook)) $result = $object->create($user, $oldinvoice->id); if ($result > 0) { - $result=$oldinvoice->delete($user, 1); + $result = $oldinvoice->delete($user, 1); if ($result < 0) { $error++; @@ -246,11 +246,11 @@ if (empty($reshook)) $action = "create"; } - if (! $error) + if (!$error) { $db->commit(); - header("Location: " . $_SERVER['PHP_SELF'] . '?facid=' . $object->id); + header("Location: ".$_SERVER['PHP_SELF'].'?facid='.$object->id); exit; } else @@ -269,7 +269,7 @@ if (empty($reshook)) { $object->delete($user); - header("Location: " . DOL_URL_ROOT.'/compta/facture/invoicetemplate_list.php'); + header("Location: ".DOL_URL_ROOT.'/compta/facture/invoicetemplate_list.php'); exit; } @@ -278,12 +278,12 @@ if (empty($reshook)) // Set condition if ($action == 'setconditions' && $user->rights->facture->creer) { - $result=$object->setPaymentTerms(GETPOST('cond_reglement_id', 'int')); + $result = $object->setPaymentTerms(GETPOST('cond_reglement_id', 'int')); } // Set mode elseif ($action == 'setmode' && $user->rights->facture->creer) { - $result=$object->setPaymentMethods(GETPOST('mode_reglement_id', 'int')); + $result = $object->setPaymentMethods(GETPOST('mode_reglement_id', 'int')); } // Set project elseif ($action == 'classin' && $user->rights->facture->creer) @@ -294,10 +294,10 @@ if (empty($reshook)) elseif ($action == 'setref' && $user->rights->facture->creer) { //var_dump(GETPOST('ref', 'alpha'));exit; - $result=$object->setValueFrom('titre', GETPOST('ref', 'alpha'), '', null, 'text', '', $user, 'BILLREC_MODIFY'); + $result = $object->setValueFrom('titre', GETPOST('ref', 'alpha'), '', null, 'text', '', $user, 'BILLREC_MODIFY'); if ($result > 0) { - $object->titre = GETPOST('ref', 'alpha'); // deprecated + $object->titre = GETPOST('ref', 'alpha'); // deprecated $object->title = GETPOST('ref', 'alpha'); $object->ref = $object->title; } @@ -306,7 +306,7 @@ if (empty($reshook)) // Set bank account elseif ($action == 'setbankaccount' && $user->rights->facture->creer) { - $result=$object->setBankAccount(GETPOST('fk_account', 'int')); + $result = $object->setBankAccount(GETPOST('fk_account', 'int')); } // Set frequency and unit frequency elseif ($action == 'setfrequency' && $user->rights->facture->creer) @@ -353,7 +353,7 @@ if (empty($reshook)) $error++; } - if (! $error) + if (!$error) { $db->commit(); } @@ -377,7 +377,7 @@ if (empty($reshook)) $error++; } - if (! $error) + if (!$error) { $db->commit(); } @@ -405,19 +405,19 @@ if (empty($reshook)) $db->begin(); - $line=new FactureLigneRec($db); + $line = new FactureLigneRec($db); // For triggers $line->id = $lineid; if ($line->delete($user) > 0) { - $result=$object->update_price(1); + $result = $object->update_price(1); if ($result > 0) { $db->commit(); - $object->fetch($object->id); // Reload lines + $object->fetch($object->id); // Reload lines } else { @@ -439,7 +439,7 @@ if (empty($reshook)) $ret = $extrafields->setOptionalsFromPost(null, $object, GETPOST('attribute', 'none')); if ($ret < 0) $error++; - if (! $error) + if (!$error) { $result = $object->insertExtraFields('BILLREC_MODIFY'); if ($result < 0) @@ -457,24 +457,24 @@ if (empty($reshook)) $error = 0; // Set if we used free entry or predefined product - $predef=''; - $product_desc=(GETPOST('dp_desc')?GETPOST('dp_desc'):''); + $predef = ''; + $product_desc = (GETPOST('dp_desc') ?GETPOST('dp_desc') : ''); $price_ht = GETPOST('price_ht'); $price_ht_devise = GETPOST('multicurrency_price_ht'); $prod_entry_mode = GETPOST('prod_entry_mode', 'alpha'); if ($prod_entry_mode == 'free') { - $idprod=0; + $idprod = 0; $tva_tx = (GETPOST('tva_tx', 'alpha') ? GETPOST('tva_tx', 'alpha') : 0); } else { - $idprod=GETPOST('idprod', 'int'); + $idprod = GETPOST('idprod', 'int'); $tva_tx = ''; } - $qty = GETPOST('qty' . $predef); - $remise_percent = GETPOST('remise_percent' . $predef); + $qty = GETPOST('qty'.$predef); + $remise_percent = GETPOST('remise_percent'.$predef); // Extrafields $extralabelsline = $extrafields->fetch_name_optionals_label($object->table_element_line); @@ -484,38 +484,38 @@ if (empty($reshook)) { // Get extra fields foreach ($extralabelsline as $key => $value) { - unset($_POST["options_" . $key . $predef]); + unset($_POST["options_".$key.$predef]); } } if (empty($idprod) && ($price_ht < 0) && ($qty < 0)) { setEventMessages($langs->trans('ErrorBothFieldCantBeNegative', $langs->transnoentitiesnoconv('UnitPriceHT'), $langs->transnoentitiesnoconv('Qty')), null, 'errors'); - $error ++; + $error++; } if ($prod_entry_mode == 'free' && empty($idprod) && GETPOST('type') < 0) { setEventMessages($langs->trans('ErrorFieldRequired', $langs->transnoentitiesnoconv('Type')), null, 'errors'); - $error ++; + $error++; } - if ($prod_entry_mode == 'free' && empty($idprod) && (! ($price_ht >= 0) || $price_ht == '')) // Unit price can be 0 but not '' + if ($prod_entry_mode == 'free' && empty($idprod) && (!($price_ht >= 0) || $price_ht == '')) // Unit price can be 0 but not '' { setEventMessages($langs->trans("ErrorFieldRequired", $langs->transnoentitiesnoconv("UnitPriceHT")), null, 'errors'); - $error ++; + $error++; } if ($qty == '') { setEventMessages($langs->trans('ErrorFieldRequired', $langs->transnoentitiesnoconv('Qty')), null, 'errors'); - $error ++; + $error++; } if ($prod_entry_mode == 'free' && empty($idprod) && empty($product_desc)) { setEventMessages($langs->trans('ErrorFieldRequired', $langs->transnoentitiesnoconv('Description')), null, 'errors'); - $error ++; + $error++; } if ($qty < 0) { $langs->load("errors"); setEventMessages($langs->trans('ErrorQtyForCustomerInvoiceCantBeNegative'), null, 'errors'); - $error ++; + $error++; } - if (! $error && ($qty >= 0) && (! empty($product_desc) || ! empty($idprod))) + if (!$error && ($qty >= 0) && (!empty($product_desc) || !empty($idprod))) { $ret = $object->fetch($id); if ($ret < 0) { @@ -525,8 +525,8 @@ if (empty($reshook)) $ret = $object->fetch_thirdparty(); // 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')); + $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')); $price_base_type = (GETPOST('price_base_type', 'alpha') ? GETPOST('price_base_type', 'alpha') : 'HT'); // Define special_code for special lines @@ -538,7 +538,7 @@ if (empty($reshook)) // Ecrase $tva_tx par celui du produit // Ecrase $base_price_type par celui du produit // Replaces $fk_unit with the product's - if (! empty($idprod)) + if (!empty($idprod)) { $prod = new Product($db); $prod->fetch($idprod); @@ -548,7 +548,7 @@ 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; // Search the correct price into loaded array product_price_by_qty using id of array retrieved into POST['pqp']. $pqp = (GETPOST('pbq', 'int') ? GETPOST('pbq', 'int') : 0); @@ -566,7 +566,7 @@ if (empty($reshook)) $tmpprodvat = price2num(preg_replace('/\s*\(.*\)/', '', $prod->tva_tx)); // if price ht was forced (ie: from gui when calculated by margin rate and cost price). TODO Why this ? - if (! empty($price_ht)) + if (!empty($price_ht)) { $pu_ht = price2num($price_ht, 'MU'); $pu_ttc = price2num($pu_ht * (1 + ($tmpvat / 100)), 'MU'); @@ -588,7 +588,7 @@ if (empty($reshook)) $desc = ''; // 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)) { $outputlangs = $langs; $newlang = ''; @@ -596,13 +596,13 @@ if (empty($reshook)) $newlang = GETPOST('lang_id', 'aZ09'); if (empty($newlang)) $newlang = $object->thirdparty->default_lang; - if (! empty($newlang)) + 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 { @@ -612,27 +612,27 @@ if (empty($reshook)) $desc = dol_concatdesc($desc, $product_desc); // Add custom code and origin country into description - if (empty($conf->global->MAIN_PRODUCT_DISABLE_CUSTOMCOUNTRYCODE) && (! empty($prod->customcode) || ! empty($prod->country_code))) + if (empty($conf->global->MAIN_PRODUCT_DISABLE_CUSTOMCOUNTRYCODE) && (!empty($prod->customcode) || !empty($prod->country_code))) { $tmptxt = '('; // 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)) { $outputlangs = $langs; $newlang = ''; if (empty($newlang) && GETPOST('lang_id', 'alpha')) $newlang = GETPOST('lang_id', 'alpha'); if (empty($newlang)) $newlang = $object->thirdparty->default_lang; - if (! empty($newlang)) { + if (!empty($newlang)) { $outputlangs = new Translate("", $conf); $outputlangs->setDefaultLang($newlang); $outputlangs->load('products'); } - if (! empty($prod->customcode)) $tmptxt .= $outputlangs->transnoentitiesnoconv("CustomCode") . ': ' . $prod->customcode; - if (! empty($prod->customcode) && ! empty($prod->country_code)) $tmptxt .= ' - '; - if (! empty($prod->country_code)) $tmptxt .= $outputlangs->transnoentitiesnoconv("CountryOrigin") . ': ' . getCountry($prod->country_code, 0, $db, $outputlangs, 0); + if (!empty($prod->customcode)) $tmptxt .= $outputlangs->transnoentitiesnoconv("CustomCode").': '.$prod->customcode; + if (!empty($prod->customcode) && !empty($prod->country_code)) $tmptxt .= ' - '; + if (!empty($prod->country_code)) $tmptxt .= $outputlangs->transnoentitiesnoconv("CountryOrigin").': '.getCountry($prod->country_code, 0, $db, $outputlangs, 0); } else { - if (! empty($prod->customcode)) $tmptxt .= $langs->transnoentitiesnoconv("CustomCode") . ': ' . $prod->customcode; - if (! empty($prod->customcode) && ! empty($prod->country_code)) $tmptxt .= ' - '; - if (! empty($prod->country_code)) $tmptxt .= $langs->transnoentitiesnoconv("CountryOrigin") . ': ' . getCountry($prod->country_code, 0, $db, $langs, 0); + if (!empty($prod->customcode)) $tmptxt .= $langs->transnoentitiesnoconv("CustomCode").': '.$prod->customcode; + if (!empty($prod->customcode) && !empty($prod->country_code)) $tmptxt .= ' - '; + if (!empty($prod->country_code)) $tmptxt .= $langs->transnoentitiesnoconv("CountryOrigin").': '.getCountry($prod->country_code, 0, $db, $langs, 0); } $tmptxt .= ')'; $desc = dol_concatdesc($desc, $tmptxt); @@ -647,19 +647,19 @@ if (empty($reshook)) $pu_ttc = price2num(GETPOST('price_ttc'), 'MU'); $tva_npr = (preg_match('/\*/', $tva_tx) ? 1 : 0); $tva_tx = str_replace('*', '', $tva_tx); - if (empty($tva_tx)) $tva_npr=0; + if (empty($tva_tx)) $tva_npr = 0; $label = (GETPOST('product_label') ? GETPOST('product_label') : ''); $desc = $product_desc; $type = GETPOST('type'); - $fk_unit= GETPOST('units', 'alpha'); + $fk_unit = GETPOST('units', 'alpha'); } $date_start_fill = GETPOST('date_start_fill', 'int'); $date_end_fill = GETPOST('date_end_fill', 'int'); // Margin - $fournprice = price2num(GETPOST('fournprice' . $predef) ? GETPOST('fournprice' . $predef) : ''); - $buyingprice = price2num(GETPOST('buying_price' . $predef) != '' ? GETPOST('buying_price' . $predef) : ''); // If buying_price is '0', we must keep this value + $fournprice = price2num(GETPOST('fournprice'.$predef) ? GETPOST('fournprice'.$predef) : ''); + $buyingprice = price2num(GETPOST('buying_price'.$predef) != '' ? GETPOST('buying_price'.$predef) : ''); // If buying_price is '0', we must keep this value // Local Taxes $localtax1_tx = get_localtax($tva_tx, 1, $object->thirdparty, $mysoc, $tva_npr); @@ -669,7 +669,7 @@ if (empty($reshook)) if ($tva_npr) $info_bits |= 0x01; - if ($usercanproductignorepricemin && (! empty($price_min) && (price2num($pu_ht) * (1 - price2num($remise_percent) / 100) < price2num($price_min)))) { + if ($usercanproductignorepricemin && (!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)); setEventMessages($mesg, null, 'errors'); } @@ -698,7 +698,7 @@ if (empty($reshook)) $result = $object->generateDocument($model, $outputlangs, $hidedetails, $hidedesc, $hideref); if ($result < 0) setEventMessages($object->error, $object->errors, 'errors'); }*/ - $object->fetch($object->id); // Reload lines + $object->fetch($object->id); // Reload lines unset($_POST['prod_entry_mode']); @@ -749,9 +749,9 @@ if (empty($reshook)) } } - elseif ($action == 'updateline' && $usercancreate && ! GETPOST('cancel', 'alpha')) + elseif ($action == 'updateline' && $usercancreate && !GETPOST('cancel', 'alpha')) { - if (! $object->fetch($id) > 0) dol_print_error($db); + if (!$object->fetch($id) > 0) dol_print_error($db); $object->fetch_thirdparty(); // Clean parameters @@ -776,7 +776,7 @@ if (empty($reshook)) // Add buying price $fournprice = price2num(GETPOST('fournprice') ? GETPOST('fournprice') : ''); - $buyingprice = price2num(GETPOST('buying_price') != '' ? GETPOST('buying_price') : ''); // If buying_price is '0', we muste keep this value + $buyingprice = price2num(GETPOST('buying_price') != '' ? GETPOST('buying_price') : ''); // If buying_price is '0', we muste keep this value // Extrafields $extralabelsline = $extrafields->fetch_name_optionals_label($object->table_element_line); @@ -785,8 +785,8 @@ if (empty($reshook)) $objectline = new FactureLigneRec($db); if ($objectline->fetch(GETPOST('lineid', 'int'))) { - $objectline->array_options=$array_options; - $result=$objectline->insertExtraFields(); + $objectline->array_options = $array_options; + $result = $objectline->insertExtraFields(); if ($result < 0) { setEventMessages($langs->trans('Error').$result, null, 'errors'); @@ -801,13 +801,13 @@ if (empty($reshook)) // Get extra fields foreach ($extralabelsline as $key => $value) { - unset($_POST["options_" . $key]); + unset($_POST["options_".$key]); } } // Define special_code for special lines - $special_code=GETPOST('special_code', 'int'); - if (! GETPOST('qty', 'alpha')) $special_code=3; + $special_code = GETPOST('special_code', 'int'); + if (!GETPOST('qty', 'alpha')) $special_code = 3; /*$line = new FactureLigne($db); $line->fetch(GETPOST('lineid')); @@ -823,7 +823,7 @@ if (empty($reshook)) // Check minimum price $productid = GETPOST('productid', 'int'); - if (! empty($productid)) + if (!empty($productid)) { $product = new Product($db); $product->fetch($productid); @@ -831,16 +831,16 @@ if (empty($reshook)) $type = $product->type; $price_min = $product->price_min; - if (! empty($conf->global->PRODUIT_MULTIPRICES) && ! empty($object->thirdparty->price_level)) + if (!empty($conf->global->PRODUIT_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') : ''); // Check price is not lower than minimum (check is done only for standard or replacement invoices) - if (((!empty($conf->global->MAIN_USE_ADVANCED_PERMS) && empty($user->rights->produit->ignore_price_min_advance)) || empty($conf->global->MAIN_USE_ADVANCED_PERMS) )&& (($object->type == Facture::TYPE_STANDARD || $object->type == Facture::TYPE_REPLACEMENT) && $price_min && (price2num($pu_ht) * (1 - price2num(GETPOST('remise_percent')) / 100) < price2num($price_min)))) + if (((!empty($conf->global->MAIN_USE_ADVANCED_PERMS) && empty($user->rights->produit->ignore_price_min_advance)) || empty($conf->global->MAIN_USE_ADVANCED_PERMS)) && (($object->type == Facture::TYPE_STANDARD || $object->type == Facture::TYPE_REPLACEMENT) && $price_min && (price2num($pu_ht) * (1 - price2num(GETPOST('remise_percent')) / 100) < price2num($price_min)))) { setEventMessages($langs->trans("CantBeLessThanMinPrice", price(price2num($price_min, 'MU'), 0, $langs, 0, 0, - 1, $conf->currency)), null, 'errors'); - $error ++; + $error++; } } else { $type = GETPOST('type', 'int'); @@ -849,20 +849,20 @@ if (empty($reshook)) // Check parameters if (GETPOST('type', 'int') < 0) { setEventMessages($langs->trans("ErrorFieldRequired", $langs->transnoentitiesnoconv("Type")), null, 'errors'); - $error ++; + $error++; } } if ($qty < 0) { $langs->load("errors"); setEventMessages($langs->trans('ErrorQtyForCustomerInvoiceCantBeNegative'), null, 'errors'); - $error ++; + $error++; } $date_start_fill = GETPOST('date_start_fill', 'int'); $date_end_fill = GETPOST('date_end_fill', 'int'); // Update line - if (! $error) + if (!$error) { $result = $object->updateline( GETPOST('lineid'), @@ -910,7 +910,7 @@ if (empty($reshook)) $object->generateDocument($object->modelpdf, $outputlangs, $hidedetails, $hidedesc, $hideref); }*/ - $object->fetch($object->id); // Reload lines + $object->fetch($object->id); // Reload lines unset($_POST['qty']); unset($_POST['type']); @@ -965,13 +965,13 @@ 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); $now = dol_now(); -$tmparray=dol_getdate($now); -$today = dol_mktime(23, 59, 59, $tmparray['mon'], $tmparray['mday'], $tmparray['year']); // Today is last second of current day +$tmparray = dol_getdate($now); +$today = dol_mktime(23, 59, 59, $tmparray['mon'], $tmparray['mday'], $tmparray['year']); // Today is last second of current day /* @@ -981,7 +981,7 @@ if ($action == 'create') { print load_fiche_titre($langs->trans("CreateRepeatableInvoice"), '', 'invoicing'); - $object = new Facture($db); // Source invoice + $object = new Facture($db); // Source invoice $product_static = new Product($db); if ($object->fetch($id, $ref) > 0) @@ -995,11 +995,11 @@ if ($action == 'create') dol_fiche_head(null, '', '', 0); - $rowspan=4; - if (! empty($conf->projet->enabled)) $rowspan++; + $rowspan = 4; + if (!empty($conf->projet->enabled)) $rowspan++; if ($object->fk_account > 0) $rowspan++; - print ''; + print '
'; $object->fetch_thirdparty(); @@ -1012,8 +1012,8 @@ if ($action == 'create') print ''; print ''; - $note_public=GETPOST('note_public', 'none')?GETPOST('note_public', 'none'):$object->note_public; - $note_private=GETPOST('note_private', 'none')?GETPOST('note_private', 'none'):$object->note_private; + $note_public = GETPOST('note_public', 'none') ?GETPOST('note_public', 'none') : $object->note_public; + $note_private = GETPOST('note_private', 'none') ?GETPOST('note_private', 'none') : $object->note_private; // Help of substitution key $substitutionarray = getCommonSubstitutionArray($langs, 2, null, $object); @@ -1025,18 +1025,18 @@ if ($action == 'create') $substitutionarray['__INVOICE_MONTH_TEXT__'] = $langs->trans("TextMonthOfInvoice").' ('.$langs->trans("Example").': '.dol_print_date($object->date, '%B').')'; $substitutionarray['__INVOICE_NEXT_MONTH_TEXT__'] = $langs->trans("TextNextMonthOfInvoice").' ('.$langs->trans("Example").': '.dol_print_date(dol_time_plus_duree($object->date, 1, 'm'), '%B').')'; $substitutionarray['__INVOICE_PREVIOUS_YEAR__'] = $langs->trans("PreviousYearOfInvoice").' ('.$langs->trans("Example").': '.dol_print_date(dol_time_plus_duree($object->date, -1, 'y'), '%Y').')'; - $substitutionarray['__INVOICE_YEAR__'] = $langs->trans("YearOfInvoice").' ('.$langs->trans("Example").': '.dol_print_date($object->date, '%Y').')'; + $substitutionarray['__INVOICE_YEAR__'] = $langs->trans("YearOfInvoice").' ('.$langs->trans("Example").': '.dol_print_date($object->date, '%Y').')'; $substitutionarray['__INVOICE_NEXT_YEAR__'] = $langs->trans("NextYearOfInvoice").' ('.$langs->trans("Example").': '.dol_print_date(dol_time_plus_duree($object->date, 1, 'y'), '%Y').')'; // Only on template invoices $substitutionarray['__INVOICE_DATE_NEXT_INVOICE_BEFORE_GEN__'] = $langs->trans("DateNextInvoiceBeforeGen").' ('.$langs->trans("Example").': '.dol_print_date($object->date_when, 'dayhour').')'; $substitutionarray['__INVOICE_DATE_NEXT_INVOICE_AFTER_GEN__'] = $langs->trans("DateNextInvoiceAfterGen").' ('.$langs->trans("Example").': '.dol_print_date(dol_time_plus_duree($object->date_when, $object->frequency, $object->unit_frequency), 'dayhour').')'; $htmltext = ''.$langs->trans("FollowingConstantsWillBeSubstituted").':
'; - foreach($substitutionarray as $key => $val) + foreach ($substitutionarray as $key => $val) { - $htmltext.=$key.' = '.$langs->trans($val).'
'; + $htmltext .= $key.' = '.$langs->trans($val).'
'; } - $htmltext.='
'; + $htmltext .= ''; // Public note print ''; @@ -1075,13 +1075,13 @@ if ($action == 'create') print ""; // Project - if (! empty($conf->projet->enabled) && is_object($object->thirdparty) && $object->thirdparty->id > 0) + if (!empty($conf->projet->enabled) && is_object($object->thirdparty) && $object->thirdparty->id > 0) { - $projectid = GETPOST('projectid')?GETPOST('projectid'):$object->fk_project; + $projectid = GETPOST('projectid') ?GETPOST('projectid') : $object->fk_project; $langs->load('projects'); - print ''; } @@ -1095,7 +1095,7 @@ if ($action == 'create') // Model pdf print ""; @@ -1111,11 +1111,11 @@ if ($action == 'create') dol_fiche_head(null, '', '', 0); - print '
'.$langs->trans("Customer").''.$object->thirdparty->getNomUrl(1, 'customer').'
' . $langs->trans('Project') . ''; + print '
'.$langs->trans('Project').''; $numprojet = $formproject->select_projects($object->thirdparty->id, $projectid, 'projectid', 0, 0, 1, 0, 0, 0, 0, '', 0, 0, ''); - print '   thirdparty->id.(!empty($id)?'&id='.$id:'')).'">' . $langs->trans("AddProject") . ''; + print '   thirdparty->id.(!empty($id) ? '&id='.$id : '')).'">'.$langs->trans("AddProject").''; print '
".$langs->trans('Model').""; - include_once DOL_DOCUMENT_ROOT . '/core/modules/facture/modules_facture.php'; + include_once DOL_DOCUMENT_ROOT.'/core/modules/facture/modules_facture.php'; $list = ModelePDFFactures::liste_modeles($db); print $form->selectarray('modelpdf', $list, $conf->global->FACTURE_ADDON_PDF); print "
'; + print '
'; // Frequency + unit print '"; // Date next run @@ -1131,15 +1131,15 @@ if ($action == 'create') // Auto validate the invoice print ""; // Auto generate document - if (! empty($conf->global->INVOICE_REC_CAN_DISABLE_DOCUMENT_FILE_GENERATION)) + if (!empty($conf->global->INVOICE_REC_CAN_DISABLE_DOCUMENT_FILE_GENERATION)) { print ""; } @@ -1167,12 +1167,12 @@ if ($action == 'create') print '
'; print '
'.$form->textwithpicto($langs->trans("Frequency"), $langs->transnoentitiesnoconv('toolTipFrequency')).""; - print " ".$form->selectarray('unit_frequency', array('d'=>$langs->trans('Day'), 'm'=>$langs->trans('Month'), 'y'=>$langs->trans('Year')), (GETPOST('unit_frequency')?GETPOST('unit_frequency'):'m')); + print " ".$form->selectarray('unit_frequency', array('d'=>$langs->trans('Day'), 'm'=>$langs->trans('Month'), 'y'=>$langs->trans('Year')), (GETPOST('unit_frequency') ?GETPOST('unit_frequency') : 'm')); print "
".$langs->trans("StatusOfGeneratedInvoices").""; - $select = array('0'=>$langs->trans('BillStatusDraft'),'1'=>$langs->trans('BillStatusValidated')); + $select = array('0'=>$langs->trans('BillStatusDraft'), '1'=>$langs->trans('BillStatusValidated')); print $form->selectarray('auto_validate', $select, GETPOST('auto_validate')); print "
".$langs->trans("StatusOfGeneratedDocuments").""; - $select = array('0'=>$langs->trans('DoNotGenerateDoc'),'1'=>$langs->trans('AutoGenerateDoc')); + $select = array('0'=>$langs->trans('DoNotGenerateDoc'), '1'=>$langs->trans('AutoGenerateDoc')); print $form->selectarray('generate_pdf', $select, GETPOST('generate_pdf')); print "
'; // Show object lines - if (! empty($object->lines)) + if (!empty($object->lines)) { - $disableedit=1; - $disablemove=1; - $disableremove=1; - $object->printObjectLines('', $mysoc, $object->thirdparty, $lineid, 0); // No date selector for template invoice + $disableedit = 1; + $disablemove = 1; + $disableremove = 1; + $object->printObjectLines('', $mysoc, $object->thirdparty, $lineid, 0); // No date selector for template invoice } print "
\n"; @@ -1193,7 +1193,7 @@ if ($action == 'create') print '
'; print '     '; - print ''; + print ''; print '
'; print "\n"; } @@ -1213,12 +1213,12 @@ else // Confirmation de la suppression d'une ligne produit if ($action == 'ask_deleteline') { - $formconfirm = $form->formconfirm($_SERVER["PHP_SELF"] . '?id=' . $object->id . '&lineid=' . $lineid, $langs->trans('DeleteProductLine'), $langs->trans('ConfirmDeleteProductLine'), 'confirm_deleteline', '', 'no', 1); + $formconfirm = $form->formconfirm($_SERVER["PHP_SELF"].'?id='.$object->id.'&lineid='.$lineid, $langs->trans('DeleteProductLine'), $langs->trans('ConfirmDeleteProductLine'), 'confirm_deleteline', '', 'no', 1); } // Confirm delete of repeatable invoice if ($action == 'ask_deleteinvoice') { - $formconfirm = $form->formconfirm($_SERVER["PHP_SELF"] . '?id=' . $object->id, $langs->trans('DeleteRepeatableInvoice'), $langs->trans('ConfirmDeleteRepeatableInvoice'), 'confirm_deleteinvoice', '', 'no', 1); + $formconfirm = $form->formconfirm($_SERVER["PHP_SELF"].'?id='.$object->id, $langs->trans('DeleteRepeatableInvoice'), $langs->trans('ConfirmDeleteRepeatableInvoice'), 'confirm_deleteinvoice', '', 'no', 1); } print $formconfirm; @@ -1226,58 +1226,58 @@ else $author = new User($db); $author->fetch($object->user_author); - $head=invoice_rec_prepare_head($object); + $head = invoice_rec_prepare_head($object); - dol_fiche_head($head, 'card', $langs->trans("RepeatableInvoice"), -1, 'bill'); // Add a div + dol_fiche_head($head, 'card', $langs->trans("RepeatableInvoice"), -1, 'bill'); // Add a div // Recurring invoice content - $linkback = '' . $langs->trans("BackToList") . ''; + $linkback = ''.$langs->trans("BackToList").''; - $morehtmlref=''; - if ($action != 'editref') $morehtmlref.=$form->editfieldkey($object->ref, 'ref', $object->ref, $object, $user->rights->facture->creer, '', '', 0, 2); - else $morehtmlref.= $form->editfieldval('', 'ref', $object->ref, $object, $user->rights->facture->creer, 'string'); + $morehtmlref = ''; + if ($action != 'editref') $morehtmlref .= $form->editfieldkey($object->ref, 'ref', $object->ref, $object, $user->rights->facture->creer, '', '', 0, 2); + else $morehtmlref .= $form->editfieldval('', 'ref', $object->ref, $object, $user->rights->facture->creer, 'string'); - $morehtmlref.='
'; + $morehtmlref .= '
'; // Ref customer //$morehtmlref.=$form->editfieldkey("RefCustomer", 'ref_client', $object->ref_client, $object, $user->rights->facture->creer, 'string', '', 0, 1); //$morehtmlref.=$form->editfieldval("RefCustomer", 'ref_client', $object->ref_client, $object, $user->rights->facture->creer, 'string', '', null, null, '', 1); // Thirdparty - $morehtmlref.=$langs->trans('ThirdParty') . ' : ' . $object->thirdparty->getNomUrl(1); + $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').' '; if ($user->rights->facture->creer) { if ($action != 'classify') { - $morehtmlref.='' . img_edit($langs->transnoentitiesnoconv('SetProject')) . ' : '; + $morehtmlref .= ''.img_edit($langs->transnoentitiesnoconv('SetProject')).' : '; } if ($action == 'classify') { //$morehtmlref.=$form->form_project($_SERVER['PHP_SELF'] . '?id=' . $object->id, $object->socid, $object->fk_project, 'projectid', 0, 0, 1, 1); - $morehtmlref.='
'; - $morehtmlref.=''; - $morehtmlref.=''; - $morehtmlref.=$formproject->select_projects($object->socid, $object->fk_project, 'projectid', $maxlength, 0, 1, 0, 1, 0, 0, '', 1); - $morehtmlref.=''; - $morehtmlref.='
'; + $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); + $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)) { + if (!empty($object->fk_project)) { $proj = new Project($db); $proj->fetch($object->fk_project); - $morehtmlref.=''; - $morehtmlref.=$proj->ref; - $morehtmlref.=''; + $morehtmlref .= ''; + $morehtmlref .= $proj->ref; + $morehtmlref .= ''; } else { - $morehtmlref.=''; + $morehtmlref .= ''; } } } - $morehtmlref.='
'; + $morehtmlref .= '
'; dol_banner_tab($object, 'ref', $linkback, 1, 'titre', 'none', $morehtmlref, '', 0, '', $morehtmlright); @@ -1285,7 +1285,7 @@ else print '
'; print '
'; - print ''; + print '
'; print '"; @@ -1299,13 +1299,13 @@ else // Amount Local Taxes if (($mysoc->localtax1_assuj == "1" && $mysoc->useLocalTax(1)) || $object->total_localtax1 != 0) // Localtax1 { - print ''; - print ''; + print ''; + print ''; } if (($mysoc->localtax2_assuj == "1" && $mysoc->useLocalTax(2)) || $object->total_localtax2 != 0) // Localtax2 { - print ''; - print ''; + print ''; + print ''; } print ''; @@ -1318,18 +1318,18 @@ else print $langs->trans('PaymentConditionsShort'); print ''; if ($action != 'editconditions' && $user->rights->facture->creer) - print ''; + print ''; print '
'.$langs->trans("Author").''.$author->getFullName($langs)."
' . $langs->transcountry("AmountLT1", $mysoc->country_code) . '' . price($object->total_localtax1, 1, '', 1, - 1, - 1, $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) . '
'.$langs->transcountry("AmountLT2", $mysoc->country_code).''.price($object->total_localtax2, 1, '', 1, - 1, - 1, $conf->currency).'
'.$langs->trans("AmountTTC").''.price($object->total_ttc, '', $langs, 1, -1, -1, $conf->currency).'id . '">' . img_edit($langs->trans('SetConditions'), 1) . 'id.'">'.img_edit($langs->trans('SetConditions'), 1).'
'; print '
'; if ($object->type != Facture::TYPE_CREDIT_NOTE) { if ($action == 'editconditions') { - $form->form_conditions_reglement($_SERVER['PHP_SELF'] . '?facid=' . $object->id, $object->cond_reglement_id, 'cond_reglement_id'); + $form->form_conditions_reglement($_SERVER['PHP_SELF'].'?facid='.$object->id, $object->cond_reglement_id, 'cond_reglement_id'); } else { - $form->form_conditions_reglement($_SERVER['PHP_SELF'] . '?facid=' . $object->id, $object->cond_reglement_id, 'none'); + $form->form_conditions_reglement($_SERVER['PHP_SELF'].'?facid='.$object->id, $object->cond_reglement_id, 'none'); } } else { print ' '; @@ -1342,7 +1342,7 @@ else print $langs->trans('PaymentMode'); print 'id . '">' . img_edit($langs->trans('SetMode'), 1) . 'id.'">'.img_edit($langs->trans('SetMode'), 1).'
'; print '
'; if ($action == 'editmode') @@ -1356,7 +1356,7 @@ else print '
'; - if ($usercancreate && $action != 'editmulticurrencycode' && ! empty($object->brouillon)) { - print ''; + if ($usercancreate && $action != 'editmulticurrencycode' && !empty($object->brouillon)) { + print ''; } print '
'; print $form->editfieldkey('Currency', 'multicurrency_code', '', $object, 0); print 'id . '">' . img_edit($langs->transnoentitiesnoconv('SetMultiCurrencyCode'), 1) . 'id.'">'.img_edit($langs->transnoentitiesnoconv('SetMultiCurrencyCode'), 1).'
'; print '
'; - $htmlname = (($usercancreate && $action == 'editmulticurrencycode')?'multicurrency_code':'none'); - $form->form_multicurrency_code($_SERVER['PHP_SELF'] . '?id=' . $object->id, $object->multicurrency_code, $htmlname); + $htmlname = (($usercancreate && $action == 'editmulticurrencycode') ? 'multicurrency_code' : 'none'); + $form->form_multicurrency_code($_SERVER['PHP_SELF'].'?id='.$object->id, $object->multicurrency_code, $htmlname); print '
'; - if ($usercancreate && $action != 'editmulticurrencyrate' && ! empty($object->brouillon) && $object->multicurrency_code && $object->multicurrency_code != $conf->currency) { - print ''; + 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) . 'id.'">'.img_edit($langs->transnoentitiesnoconv('SetMultiCurrencyCode'), 1).'
'; print '
'; if ($action == 'editmulticurrencyrate' || $action == 'actualizemulticurrencyrate') { - if($action == 'actualizemulticurrencyrate') { + if ($action == 'actualizemulticurrencyrate') { list($object->fk_multicurrency, $object->multicurrency_tx) = MultiCurrency::getIdAndTxFromCode($object->db, $object->multicurrency_code); } - $form->form_multicurrency_rate($_SERVER['PHP_SELF'] . '?id=' . $object->id, $object->multicurrency_tx, ($usercancreate?'multicurrency_tx':'none'), $object->multicurrency_code); + $form->form_multicurrency_rate($_SERVER['PHP_SELF'].'?id='.$object->id, $object->multicurrency_tx, ($usercancreate ? 'multicurrency_tx' : 'none'), $object->multicurrency_code); } else { - $form->form_multicurrency_rate($_SERVER['PHP_SELF'] . '?id=' . $object->id, $object->multicurrency_tx, 'none', $object->multicurrency_code); - if($object->statut == $object::STATUS_DRAFT && $object->multicurrency_code && $object->multicurrency_code != $conf->currency) { + $form->form_multicurrency_rate($_SERVER['PHP_SELF'].'?id='.$object->id, $object->multicurrency_tx, 'none', $object->multicurrency_code); + if ($object->statut == $object::STATUS_DRAFT && $object->multicurrency_code && $object->multicurrency_code != $conf->currency) { print '
        '; print ''.$langs->trans("ActualizeCurrency").''; print '
'; @@ -1404,8 +1404,8 @@ else } // Help of substitution key - $dateexample=dol_now(); - if (! empty($object->frequency) && ! empty($object->date_when)) $dateexample=$object->date_when; + $dateexample = dol_now(); + if (!empty($object->frequency) && !empty($object->date_when)) $dateexample = $object->date_when; $substitutionarray = getCommonSubstitutionArray($langs, 2, null, $object); @@ -1416,18 +1416,18 @@ else $substitutionarray['__INVOICE_MONTH_TEXT__'] = $langs->trans("TextMonthOfInvoice").' ('.$langs->trans("Example").': '.dol_print_date($dateexample, '%B').')'; $substitutionarray['__INVOICE_NEXT_MONTH_TEXT__'] = $langs->trans("TextNextMonthOfInvoice").' ('.$langs->trans("Example").': '.dol_print_date(dol_time_plus_duree($dateexample, 1, 'm'), '%B').')'; $substitutionarray['__INVOICE_PREVIOUS_YEAR__'] = $langs->trans("PreviousYearOfInvoice").' ('.$langs->trans("Example").': '.dol_print_date(dol_time_plus_duree($dateexample, -1, 'y'), '%Y').')'; - $substitutionarray['__INVOICE_YEAR__'] = $langs->trans("YearOfInvoice").' ('.$langs->trans("Example").': '.dol_print_date($dateexample, '%Y').')'; + $substitutionarray['__INVOICE_YEAR__'] = $langs->trans("YearOfInvoice").' ('.$langs->trans("Example").': '.dol_print_date($dateexample, '%Y').')'; $substitutionarray['__INVOICE_NEXT_YEAR__'] = $langs->trans("NextYearOfInvoice").' ('.$langs->trans("Example").': '.dol_print_date(dol_time_plus_duree($dateexample, 1, 'y'), '%Y').')'; // Only on template invoices - $substitutionarray['__INVOICE_DATE_NEXT_INVOICE_BEFORE_GEN__'] = $langs->trans("DateNextInvoiceBeforeGen").' ('.$langs->trans("Example").': '.dol_print_date(($object->date_when?$object->date_when:dol_now()), 'dayhour').')'; - $substitutionarray['__INVOICE_DATE_NEXT_INVOICE_AFTER_GEN__'] = $langs->trans("DateNextInvoiceAfterGen").' ('.$langs->trans("Example").': '.dol_print_date(dol_time_plus_duree(($object->date_when?$object->date_when:dol_now()), $object->frequency, $object->unit_frequency), 'dayhour').')'; + $substitutionarray['__INVOICE_DATE_NEXT_INVOICE_BEFORE_GEN__'] = $langs->trans("DateNextInvoiceBeforeGen").' ('.$langs->trans("Example").': '.dol_print_date(($object->date_when ? $object->date_when : dol_now()), 'dayhour').')'; + $substitutionarray['__INVOICE_DATE_NEXT_INVOICE_AFTER_GEN__'] = $langs->trans("DateNextInvoiceAfterGen").' ('.$langs->trans("Example").': '.dol_print_date(dol_time_plus_duree(($object->date_when ? $object->date_when : dol_now()), $object->frequency, $object->unit_frequency), 'dayhour').')'; $htmltext = ''.$langs->trans("FollowingConstantsWillBeSubstituted").':
'; - foreach($substitutionarray as $key => $val) + foreach ($substitutionarray as $key => $val) { - $htmltext.=$key.' = '.$langs->trans($val).'
'; + $htmltext .= $key.' = '.$langs->trans($val).'
'; } - $htmltext.='
'; + $htmltext .= ''; // Note public print '
'; @@ -1480,11 +1480,11 @@ else print ''; if ($action == 'editmodelpdf') { - include_once DOL_DOCUMENT_ROOT . '/core/modules/facture/modules_facture.php'; + include_once DOL_DOCUMENT_ROOT.'/core/modules/facture/modules_facture.php'; $list = array(); $models = ModelePDFFactures::liste_modeles($db); foreach ($models as $k => $model) { - $list[] = str_replace(':', '|', $k) . ':' . $model; + $list[] = str_replace(':', '|', $k).':'.$model; } $select = 'select;'.implode(',', $list); print $form->editfieldval($langs->trans("Model"), 'modelpdf', $object->modelpdf, $object, $user->rights->facture->creer, $select); @@ -1498,7 +1498,7 @@ else // Other attributes $cols = 2; - include DOL_DOCUMENT_ROOT . '/core/tpl/extrafields_view.tpl.php'; + include DOL_DOCUMENT_ROOT.'/core/tpl/extrafields_view.tpl.php'; print '
'; @@ -1514,7 +1514,7 @@ else $title = $langs->trans("Recurrence"); //print load_fiche_titre($title, '', 'calendar'); - print ''; + print '
'; print ''; @@ -1524,17 +1524,17 @@ else print $langs->trans('Frequency'); print ''; if ($action != 'editfrequency' && $user->rights->facture->creer) - print ''; + print ''; print '
'.$title.'
id . '">' . img_edit($langs->trans('Edit'), 1) . 'id.'">'.img_edit($langs->trans('Edit'), 1).'
'; print '
'; if ($action == 'editfrequency') { - print '
'; + print ''; print ''; print ''; print ''; print ''; print ''; print '
'; - print " ".$form->selectarray('unit_frequency', array('d'=>$langs->trans('Day'), 'm'=>$langs->trans('Month'), 'y'=>$langs->trans('Year')), ($object->unit_frequency?$object->unit_frequency:'m')); + print " ".$form->selectarray('unit_frequency', array('d'=>$langs->trans('Day'), 'm'=>$langs->trans('Month'), 'y'=>$langs->trans('Year')), ($object->unit_frequency ? $object->unit_frequency : 'm')); print '
'; @@ -1568,9 +1568,9 @@ else print $form->editfieldval($langs->trans("NextDateToExecution"), 'date_when', $object->date_when, $object, $user->rights->facture->creer, 'day', $object->date_when, null, '', '', 0, 'strikeIfMaxNbGenReached'); } //var_dump(dol_print_date($object->date_when+60, 'dayhour').' - '.dol_print_date($now, 'dayhour')); - if (! $object->isMaxNbGenReached()) + if (!$object->isMaxNbGenReached()) { - if (! $object->suspended && $action != 'editdate_when' && $object->frequency > 0 && $object->date_when && $object->date_when < $now) print img_warning($langs->trans("Late")); + if (!$object->suspended && $action != 'editdate_when' && $object->frequency > 0 && $object->date_when && $object->date_when < $now) print img_warning($langs->trans("Late")); } else { @@ -1592,7 +1592,7 @@ else print '
'; 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); + print $form->editfieldval($langs->trans("MaxPeriodNumber"), 'nb_gen_max', $object->nb_gen_max ? $object->nb_gen_max : '', $object, $user->rights->facture->creer); } else { @@ -1615,7 +1615,7 @@ else } print '
'; @@ -1656,7 +1656,7 @@ else // Nb of generation already done print '
'.$langs->trans("NbOfGenerationDone").''; - print $object->nb_gen_done?$object->nb_gen_done:'0'; + print $object->nb_gen_done ? $object->nb_gen_done : '0'; print '
'; // Show object lines - if (! empty($object->lines)) + if (!empty($object->lines)) { //$disableedit=1; //$disablemove=1; - $ret = $object->printObjectLines($action, $mysoc, $object->thirdparty, $lineid, 0); // No date selector for template invoice + $ret = $object->printObjectLines($action, $mysoc, $object->thirdparty, $lineid, 0); // No date selector for template invoice } // Form to add new line @@ -1708,7 +1708,7 @@ else if ($action != 'editline') { // Add free products/services - $object->formAddObjectLine(0, $mysoc, $object->thirdparty); // No date selector for template invoice + $object->formAddObjectLine(0, $mysoc, $object->thirdparty); // No date selector for template invoice $parameters = array(); $reshook = $hookmanager->executeHooks('formAddObjectLine', $parameters, $object, $action); // Note that $action and $object may have been modified by hook @@ -1732,7 +1732,7 @@ else { if ($user->rights->facture->creer) { - if (! empty($object->frequency) && $object->nb_gen_max > 0 && ($object->nb_gen_done >= $object->nb_gen_max)) + if (!empty($object->frequency) && $object->nb_gen_max > 0 && ($object->nb_gen_done >= $object->nb_gen_max)) { print ''; } diff --git a/htdocs/compta/facture/card.php b/htdocs/compta/facture/card.php index d462d3cc444..b6997922e2a 100644 --- a/htdocs/compta/facture/card.php +++ b/htdocs/compta/facture/card.php @@ -37,38 +37,38 @@ */ require '../../main.inc.php'; -require_once DOL_DOCUMENT_ROOT . '/compta/facture/class/facture.class.php'; -require_once DOL_DOCUMENT_ROOT . '/compta/facture/class/facture-rec.class.php'; -require_once DOL_DOCUMENT_ROOT . '/compta/bank/class/account.class.php'; -require_once DOL_DOCUMENT_ROOT . '/compta/paiement/class/paiement.class.php'; -require_once DOL_DOCUMENT_ROOT . '/core/modules/facture/modules_facture.php'; -require_once DOL_DOCUMENT_ROOT . '/core/class/discount.class.php'; -require_once DOL_DOCUMENT_ROOT . '/core/class/html.formfile.class.php'; -require_once DOL_DOCUMENT_ROOT . '/core/class/html.formother.class.php'; -require_once DOL_DOCUMENT_ROOT . '/core/class/html.formmargin.class.php'; -require_once DOL_DOCUMENT_ROOT . '/core/lib/invoice.lib.php'; -require_once DOL_DOCUMENT_ROOT . '/core/lib/functions2.lib.php'; -require_once DOL_DOCUMENT_ROOT . '/core/lib/date.lib.php'; -require_once DOL_DOCUMENT_ROOT . '/core/class/extrafields.class.php'; -if (! empty($conf->commande->enabled)) - require_once DOL_DOCUMENT_ROOT . '/commande/class/commande.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'; +require_once DOL_DOCUMENT_ROOT.'/compta/facture/class/facture.class.php'; +require_once DOL_DOCUMENT_ROOT.'/compta/facture/class/facture-rec.class.php'; +require_once DOL_DOCUMENT_ROOT.'/compta/bank/class/account.class.php'; +require_once DOL_DOCUMENT_ROOT.'/compta/paiement/class/paiement.class.php'; +require_once DOL_DOCUMENT_ROOT.'/core/modules/facture/modules_facture.php'; +require_once DOL_DOCUMENT_ROOT.'/core/class/discount.class.php'; +require_once DOL_DOCUMENT_ROOT.'/core/class/html.formfile.class.php'; +require_once DOL_DOCUMENT_ROOT.'/core/class/html.formother.class.php'; +require_once DOL_DOCUMENT_ROOT.'/core/class/html.formmargin.class.php'; +require_once DOL_DOCUMENT_ROOT.'/core/lib/invoice.lib.php'; +require_once DOL_DOCUMENT_ROOT.'/core/lib/functions2.lib.php'; +require_once DOL_DOCUMENT_ROOT.'/core/lib/date.lib.php'; +require_once DOL_DOCUMENT_ROOT.'/core/class/extrafields.class.php'; +if (!empty($conf->commande->enabled)) + require_once DOL_DOCUMENT_ROOT.'/commande/class/commande.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'; } -require_once DOL_DOCUMENT_ROOT . '/core/class/doleditor.class.php'; +require_once DOL_DOCUMENT_ROOT.'/core/class/doleditor.class.php'; 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'; } // Load translation files required by the page -$langs->loadLangs(array('bills','companies','compta','products','banks','main','withdrawals')); -if (! empty($conf->incoterm->enabled)) $langs->load('incoterm'); -if (! empty($conf->margin->enabled)) $langs->load('margins'); +$langs->loadLangs(array('bills', 'companies', 'compta', 'products', 'banks', 'main', 'withdrawals')); +if (!empty($conf->incoterm->enabled)) $langs->load('incoterm'); +if (!empty($conf->margin->enabled)) $langs->load('margins'); $projectid = (GETPOST('projectid', 'int') ? GETPOST('projectid', 'int') : 0); @@ -86,37 +86,37 @@ $search_montant_ht = GETPOST('search_montant_ht', 'alpha'); $search_montant_ttc = GETPOST('search_montant_ttc', 'alpha'); $origin = GETPOST('origin', 'alpha'); $originid = (GETPOST('originid', 'int') ? GETPOST('originid', 'int') : GETPOST('origin_id', 'int')); // For backward compatibility -$fac_rec=GETPOST('fac_rec', 'int'); +$fac_rec = GETPOST('fac_rec', 'int'); // PDF -$hidedetails = (GETPOST('hidedetails', 'int') ? GETPOST('hidedetails', 'int') : (! empty($conf->global->MAIN_GENERATE_DOCUMENTS_HIDE_DETAILS) ? 1 : 0)); -$hidedesc = (GETPOST('hidedesc', 'int') ? GETPOST('hidedesc', 'int') : (! empty($conf->global->MAIN_GENERATE_DOCUMENTS_HIDE_DESC) ? 1 : 0)); -$hideref = (GETPOST('hideref', 'int') ? GETPOST('hideref', 'int') : (! empty($conf->global->MAIN_GENERATE_DOCUMENTS_HIDE_REF) ? 1 : 0)); +$hidedetails = (GETPOST('hidedetails', 'int') ? GETPOST('hidedetails', 'int') : (!empty($conf->global->MAIN_GENERATE_DOCUMENTS_HIDE_DETAILS) ? 1 : 0)); +$hidedesc = (GETPOST('hidedesc', 'int') ? GETPOST('hidedesc', 'int') : (!empty($conf->global->MAIN_GENERATE_DOCUMENTS_HIDE_DESC) ? 1 : 0)); +$hideref = (GETPOST('hideref', 'int') ? GETPOST('hideref', 'int') : (!empty($conf->global->MAIN_GENERATE_DOCUMENTS_HIDE_REF) ? 1 : 0)); // Nombre de ligne pour choix de produit/service predefinis $NBLINES = 4; -$usehm = (! empty($conf->global->MAIN_USE_HOURMIN_IN_DATE_RANGE) ? $conf->global->MAIN_USE_HOURMIN_IN_DATE_RANGE : 0); +$usehm = (!empty($conf->global->MAIN_USE_HOURMIN_IN_DATE_RANGE) ? $conf->global->MAIN_USE_HOURMIN_IN_DATE_RANGE : 0); $object = new Facture($db); $extrafields = new ExtraFields($db); // Load object -if ($id > 0 || ! empty($ref)) { +if ($id > 0 || !empty($ref)) { $ret = $object->fetch($id, $ref, '', '', $conf->global->INVOICE_USE_SITUATION); } // Initialize technical object to manage hooks of page. Note that conf->hooks_modules contains array of hook context -$hookmanager->initHooks(array('invoicecard','globalcard')); +$hookmanager->initHooks(array('invoicecard', 'globalcard')); $usercanread = $user->rights->facture->lire; $usercancreate = $user->rights->facture->creer; $usercanissuepayment = $user->rights->facture->paiement; $usercandelete = $user->rights->facture->supprimer; -$usercanvalidate = ((empty($conf->global->MAIN_USE_ADVANCED_PERMS) && $usercancreate) || (! empty($conf->global->MAIN_USE_ADVANCED_PERMS) && ! empty($user->rights->facture->invoice_advance->validate))); +$usercanvalidate = ((empty($conf->global->MAIN_USE_ADVANCED_PERMS) && $usercancreate) || (!empty($conf->global->MAIN_USE_ADVANCED_PERMS) && !empty($user->rights->facture->invoice_advance->validate))); $usercansend = (empty($conf->global->MAIN_USE_ADVANCED_PERMS) || $user->rights->facture->invoice_advance->send); $usercanreopen = (empty($conf->global->MAIN_USE_ADVANCED_PERMS) || $user->rights->facture->invoice_advance->reopen); -$usercanunvalidate = ((empty($conf->global->MAIN_USE_ADVANCED_PERMS) && ! empty($usercancreate)) || (! empty($conf->global->MAIN_USE_ADVANCED_PERMS) && ! empty($user->rights->facture->invoice_advance->unvalidate))); +$usercanunvalidate = ((empty($conf->global->MAIN_USE_ADVANCED_PERMS) && !empty($usercancreate)) || (!empty($conf->global->MAIN_USE_ADVANCED_PERMS) && !empty($user->rights->facture->invoice_advance->unvalidate))); $usercanproductignorepricemin = ((!empty($conf->global->MAIN_USE_ADVANCED_PERMS) && empty($user->rights->produit->ignore_price_min_advance)) || empty($conf->global->MAIN_USE_ADVANCED_PERMS)); $usercancreatemargin = $user->rights->margins->creer; @@ -124,12 +124,12 @@ $usercanreadallmargin = $user->rights->margins->liretous; $usercancreatewithdrarequest = $user->rights->prelevement->bons->creer; $permissionnote = $usercancreate; // Used by the include of actions_setnotes.inc.php -$permissiondellink = $usercancreate; // Used by the include of actions_dellink.inc.php +$permissiondellink = $usercancreate; // Used by the include of actions_dellink.inc.php $permissiontoedit = $usercancreate; // Used by the include of actions_lineupdonw.inc.php $permissiontoadd = $usercancreate; // Used by the include of actions_addupdatedelete.inc.php // Security check -$fieldid = (! empty($ref) ? 'ref' : 'rowid'); +$fieldid = (!empty($ref) ? 'ref' : 'rowid'); if ($user->socid) $socid = $user->socid; $isdraft = (($object->statut == Facture::STATUS_DRAFT) ? 1 : 0); $result = restrictedArea($user, 'facture', $id, '', '', 'fk_soc', $fieldid, $isdraft); @@ -146,30 +146,30 @@ if (empty($reshook)) { if ($cancel) { - if (! empty($backtopage)) + if (!empty($backtopage)) { header("Location: ".$backtopage); exit; } - $action=''; + $action = ''; } include DOL_DOCUMENT_ROOT.'/core/actions_setnotes.inc.php'; // Must be include, not include_once - include DOL_DOCUMENT_ROOT.'/core/actions_dellink.inc.php'; // Must be include, not include_once + include DOL_DOCUMENT_ROOT.'/core/actions_dellink.inc.php'; // Must be include, not include_once - include DOL_DOCUMENT_ROOT.'/core/actions_lineupdown.inc.php'; // Must be include, not include_once + include DOL_DOCUMENT_ROOT.'/core/actions_lineupdown.inc.php'; // Must be include, not include_once // Action clone object if ($action == 'confirm_clone' && $confirm == 'yes' && $permissiontoadd) { - $objectutil = dol_clone($object, 1); // To avoid to denaturate loaded object when setting some properties for clone. We use native clone to keep this->db valid. + $objectutil = dol_clone($object, 1); // To avoid to denaturate loaded object when setting some properties for clone. We use native clone to keep this->db valid. $objectutil->date = dol_mktime(12, 0, 0, GETPOST('newdatemonth', 'int'), GETPOST('newdateday', 'int'), GETPOST('newdateyear', 'int')); $objectutil->socid = $socid; $result = $objectutil->createFromClone($user, $id); if ($result > 0) { - header("Location: " . $_SERVER['PHP_SELF'] . '?facid=' . $result); + header("Location: ".$_SERVER['PHP_SELF'].'?facid='.$result); exit(); } else { $langs->load("errors"); @@ -185,7 +185,7 @@ if (empty($reshook)) if ($object->statut == Facture::STATUS_CLOSED || ($object->statut == Facture::STATUS_ABANDONED && ($object->close_code != 'replaced' || $object->getIdReplacingInvoice() == 0)) || ($object->statut == Facture::STATUS_VALIDATED && $object->paye == 1)) { // ($object->statut == 1 && $object->paye == 1) should not happened but can be found when data are corrupted $result = $object->set_unpaid($user); if ($result > 0) { - header('Location: ' . $_SERVER["PHP_SELF"] . '?facid=' . $id); + header('Location: '.$_SERVER["PHP_SELF"].'?facid='.$id); exit(); } else { setEventMessages($object->error, $object->errors, 'errors'); @@ -207,18 +207,18 @@ if (empty($reshook)) $qualified_for_stock_change = $object->hasProductsOrServices(1); } - $isErasable=$object->is_erasable(); + $isErasable = $object->is_erasable(); if (($usercandelete && $isErasable > 0) || ($usercancreate && $isErasable == 1)) { $result = $object->delete($user, 0, $idwarehouse); if ($result > 0) { - header('Location: ' . DOL_URL_ROOT . '/compta/facture/list.php?restore_lastsearch_values=1'); + header('Location: '.DOL_URL_ROOT.'/compta/facture/list.php?restore_lastsearch_values=1'); exit(); } else { setEventMessages($object->error, $object->errors, 'errors'); - $action=''; + $action = ''; } } } @@ -234,11 +234,11 @@ if (empty($reshook)) // 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)) $newlang = $object->thirdparty->default_lang; - if (! empty($newlang)) { + if (!empty($newlang)) { $outputlangs = new Translate("", $conf); $outputlangs->setDefaultLang($newlang); $outputlangs->load('products'); @@ -248,7 +248,7 @@ if (empty($reshook)) $result = $object->generateDocument($object->modelpdf, $outputlangs, $hidedetails, $hidedesc, $hideref); } if ($result >= 0) { - header('Location: ' . $_SERVER["PHP_SELF"] . '?facid=' . $id); + header('Location: '.$_SERVER["PHP_SELF"].'?facid='.$id); exit(); } } else { @@ -294,7 +294,7 @@ if (empty($reshook)) $object->fetch($id); $object->setValueFrom('fk_soc', $socid, '', null, 'int', '', $user, 'BILL_MODIFY'); - header('Location: ' . $_SERVER["PHP_SELF"] . '?facid=' . $id); + header('Location: '.$_SERVER["PHP_SELF"].'?facid='.$id); exit(); } @@ -365,7 +365,7 @@ if (empty($reshook)) header('Location: '.$_SERVER["PHP_SELF"].'?facid='.$id.'&action=editinvoicedate'); exit; } - $object->date=$date; + $object->date = $date; $new_date_lim_reglement = $object->calculate_date_lim_reglement(); if ($new_date_lim_reglement > $old_date_lim_reglement) $object->date_lim_reglement = $new_date_lim_reglement; if ($object->date_lim_reglement < $object->date) $object->date_lim_reglement = $object->date; @@ -377,7 +377,7 @@ if (empty($reshook)) { $object->fetch($id); $date_pointoftax = dol_mktime(12, 0, 0, $_POST['date_pointoftaxmonth'], $_POST['date_pointoftaxday'], $_POST['date_pointoftaxyear']); - $object->date_pointoftax=$date_pointoftax; + $object->date_pointoftax = $date_pointoftax; $result = $object->update($user); if ($result < 0) dol_print_error($db, $object->error); } @@ -430,7 +430,7 @@ if (empty($reshook)) // bank account elseif ($action == 'setbankaccount' && $usercancreate) { - $result=$object->setBankAccount(GETPOST('fk_account', 'int')); + $result = $object->setBankAccount(GETPOST('fk_account', 'int')); } elseif ($action == 'setremisepercent' && $usercancreate) @@ -444,7 +444,7 @@ if (empty($reshook)) // POST[remise_id] or POST[remise_id_for_payment] // We use the credit to reduce amount of invoice - if (! empty($_POST["remise_id"])) { + if (!empty($_POST["remise_id"])) { $ret = $object->fetch($id); if ($ret > 0) { $result = $object->insert_discount($_POST["remise_id"]); @@ -456,9 +456,9 @@ 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'; + require_once DOL_DOCUMENT_ROOT.'/core/class/discount.class.php'; $discount = new DiscountAbsolute($db); $discount->fetch($_POST["remise_id_for_payment"]); @@ -471,7 +471,7 @@ if (empty($reshook)) setEventMessages($langs->trans("ErrorDiscountLargerThanRemainToPaySplitItBefore"), null, 'errors'); } - if (! $error) + if (!$error) { $result = $discount->link_to_invoice(0, $id); if ($result < 0) { @@ -486,7 +486,7 @@ if (empty($reshook)) $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 (!empty($newlang)) { $outputlangs = new Translate("", $conf); $outputlangs->setDefaultLang($newlang); } @@ -514,12 +514,12 @@ if (empty($reshook)) // Check parameters // Check for mandatory fields in thirdparty (defined into setup) - $array_to_check=array('IDPROF1','IDPROF2','IDPROF3','IDPROF4','IDPROF5','IDPROF6','EMAIL'); - foreach($array_to_check as $key) + $array_to_check = array('IDPROF1', 'IDPROF2', 'IDPROF3', 'IDPROF4', 'IDPROF5', 'IDPROF6', 'EMAIL'); + foreach ($array_to_check as $key) { - $keymin=strtolower($key); - $i=(int) preg_replace('/[^0-9]/', '', $key); - $vallabel=$object->thirdparty->$keymin; + $keymin = strtolower($key); + $i = (int) preg_replace('/[^0-9]/', '', $key); + $vallabel = $object->thirdparty->$keymin; if ($i > 0) { @@ -528,8 +528,8 @@ if (empty($reshook)) // Check for mandatory prof id (but only if country is other than ours) if ($mysoc->country_id > 0 && $object->thirdparty->country_id == $mysoc->country_id) { - $idprof_mandatory ='SOCIETE_'.$key.'_INVOICE_MANDATORY'; - if (! $vallabel && ! empty($conf->global->$idprof_mandatory)) + $idprof_mandatory = 'SOCIETE_'.$key.'_INVOICE_MANDATORY'; + if (!$vallabel && !empty($conf->global->$idprof_mandatory)) { $langs->load("errors"); $error++; @@ -544,7 +544,7 @@ if (empty($reshook)) if ($key == 'EMAIL') { // Check for mandatory - if (! empty($conf->global->SOCIETE_EMAIL_INVOICE_MANDATORY) && ! isValidEMail($object->thirdparty->email)) + if (!empty($conf->global->SOCIETE_EMAIL_INVOICE_MANDATORY) && !isValidEMail($object->thirdparty->email)) { $langs->load("errors"); $error++; @@ -555,15 +555,15 @@ if (empty($reshook)) } // Check for mandatory fields in invoice - $array_to_check=array('REF_CUSTOMER'=>'RefCustomer'); - foreach($array_to_check as $key => $val) + $array_to_check = array('REF_CUSTOMER'=>'RefCustomer'); + foreach ($array_to_check as $key => $val) { - $keymin=strtolower($key); - $vallabel=$object->$keymin; + $keymin = strtolower($key); + $vallabel = $object->$keymin; // Check for mandatory - $keymandatory ='INVOICE_'.$key.'_MANDATORY_FOR_VALIDATION'; - if (! $vallabel && ! empty($conf->global->$keymandatory)) + $keymandatory = 'INVOICE_'.$key.'_MANDATORY_FOR_VALIDATION'; + if (!$vallabel && !empty($conf->global->$keymandatory)) { $langs->load("errors"); $error++; @@ -572,7 +572,7 @@ if (empty($reshook)) } // Check for warehouse - if ($object->type != Facture::TYPE_DEPOSIT && ! empty($conf->global->STOCK_CALCULATE_ON_BILL)) + if ($object->type != Facture::TYPE_DEPOSIT && !empty($conf->global->STOCK_CALCULATE_ON_BILL)) { $qualified_for_stock_change = 0; if (empty($conf->global->STOCK_SUPPORTS_SERVICES)) { @@ -583,7 +583,7 @@ if (empty($reshook)) if ($qualified_for_stock_change) { - if (! $idwarehouse || $idwarehouse == - 1) { + if (!$idwarehouse || $idwarehouse == - 1) { $error++; setEventMessages($langs->trans('ErrorFieldRequired', $langs->transnoentitiesnoconv("Warehouse")), null, 'errors'); $action = ''; @@ -591,7 +591,7 @@ if (empty($reshook)) } } - if (! $error) + if (!$error) { $result = $object->validate($user, '', $idwarehouse); if ($result >= 0) @@ -603,12 +603,12 @@ if (empty($reshook)) $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 (!empty($newlang)) { $outputlangs = new Translate("", $conf); $outputlangs->setDefaultLang($newlang); $outputlangs->load('products'); } - $model=$object->modelpdf; + $model = $object->modelpdf; $ret = $object->fetch($id); // Reload to get new records $result = $object->generateDocument($model, $outputlangs, $hidedetails, $hidedesc, $hideref); @@ -632,7 +632,7 @@ if (empty($reshook)) $object->fetch_thirdparty(); // Check parameters - if ($object->type != Facture::TYPE_DEPOSIT && ! empty($conf->global->STOCK_CALCULATE_ON_BILL)) + if ($object->type != Facture::TYPE_DEPOSIT && !empty($conf->global->STOCK_CALCULATE_ON_BILL)) { $qualified_for_stock_change = 0; if (empty($conf->global->STOCK_SUPPORTS_SERVICES)) { @@ -643,7 +643,7 @@ if (empty($reshook)) if ($qualified_for_stock_change) { - if (! $idwarehouse || $idwarehouse == - 1) { + if (!$idwarehouse || $idwarehouse == - 1) { $error++; setEventMessages($langs->trans('ErrorFieldRequired', $langs->transnoentitiesnoconv("Warehouse")), null, 'errors'); $action = ''; @@ -651,11 +651,11 @@ if (empty($reshook)) } } - if (! $error) { + if (!$error) { // On verifie si la facture a des paiements $sql = 'SELECT pf.amount'; - $sql .= ' FROM ' . MAIN_DB_PREFIX . 'paiement_facture as pf'; - $sql .= ' WHERE pf.fk_facture = ' . $object->id; + $sql .= ' FROM '.MAIN_DB_PREFIX.'paiement_facture as pf'; + $sql .= ' WHERE pf.fk_facture = '.$object->id; $result = $db->query($sql); if ($result) { @@ -665,7 +665,7 @@ if (empty($reshook)) while ($i < $num) { $objp = $db->fetch_object($result); $totalpaye += $objp->amount; - $i ++; + $i++; } } else { dol_print_error($db, ''); @@ -679,10 +679,10 @@ if (empty($reshook)) // On verifie si aucun paiement n'a ete effectue if ($ventilExportCompta == 0) { - if (! empty($conf->global->INVOICE_CAN_ALWAYS_BE_EDITED) || ($resteapayer == $object->total_ttc && empty($object->paye))) + if (!empty($conf->global->INVOICE_CAN_ALWAYS_BE_EDITED) || ($resteapayer == $object->total_ttc && empty($object->paye))) { - $result=$object->setDraft($user, $idwarehouse); - if ($result<0) setEventMessages($object->error, $object->errors, 'errors'); + $result = $object->setDraft($user, $idwarehouse); + if ($result < 0) setEventMessages($object->error, $object->errors, 'errors'); // Define output language if (empty($conf->global->MAIN_DISABLE_PDF_AUTOUPDATE)) @@ -691,12 +691,12 @@ if (empty($reshook)) $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 (!empty($newlang)) { $outputlangs = new Translate("", $conf); $outputlangs->setDefaultLang($newlang); $outputlangs->load('products'); } - $model=$object->modelpdf; + $model = $object->modelpdf; $ret = $object->fetch($id); // Reload to get new records $object->generateDocument($model, $outputlangs, $hidedetails, $hidedesc, $hideref); @@ -711,7 +711,7 @@ if (empty($reshook)) { $object->fetch($id); $result = $object->set_paid($user); - if ($result<0) setEventMessages($object->error, $object->errors, 'errors'); + if ($result < 0) setEventMessages($object->error, $object->errors, 'errors'); } // Classif "paid partialy" elseif ($action == 'confirm_paid_partially' && $confirm == 'yes' && $usercanissuepayment) { @@ -720,7 +720,7 @@ if (empty($reshook)) $close_note = GETPOST("close_note", 'none'); if ($close_code) { $result = $object->set_paid($user, $close_code, $close_note); - if ($result<0) setEventMessages($object->error, $object->errors, 'errors'); + if ($result < 0) setEventMessages($object->error, $object->errors, 'errors'); } else { setEventMessages($langs->trans("ErrorFieldRequired", $langs->transnoentitiesnoconv("Reason")), null, 'errors'); } @@ -731,7 +731,7 @@ if (empty($reshook)) $close_note = GETPOST("close_note", 'none'); if ($close_code) { $result = $object->set_canceled($user, $close_code, $close_note); - if ($result<0) setEventMessages($object->error, $object->errors, 'errors'); + if ($result < 0) setEventMessages($object->error, $object->errors, 'errors'); } else { setEventMessages($langs->trans("ErrorFieldRequired", $langs->transnoentitiesnoconv("Reason")), null, 'errors'); } @@ -745,12 +745,12 @@ if (empty($reshook)) //$object->fetch_lines(); // Already done into fetch // Check if there is already a discount (protection to avoid duplicate creation when resubmit post) - $discountcheck=new DiscountAbsolute($db); - $result=$discountcheck->fetch(0, $object->id); + $discountcheck = new DiscountAbsolute($db); + $result = $discountcheck->fetch(0, $object->id); - $canconvert=0; - if ($object->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 (($object->type == Facture::TYPE_CREDIT_NOTE || $object->type == Facture::TYPE_STANDARD) && $object->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) + $canconvert = 0; + if ($object->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 (($object->type == Facture::TYPE_CREDIT_NOTE || $object->type == Facture::TYPE_STANDARD) && $object->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) { $db->begin(); @@ -796,13 +796,13 @@ if (empty($reshook)) // Total payments $sql = 'SELECT SUM(pf.amount) as total_paiements'; - $sql.= ' FROM '.MAIN_DB_PREFIX.'paiement_facture as pf, '.MAIN_DB_PREFIX.'paiement as p'; - $sql.= ' LEFT JOIN '.MAIN_DB_PREFIX.'c_paiement as c ON p.fk_paiement = c.id'; - $sql.= ' WHERE pf.fk_facture = '.$object->id; - $sql.= ' AND pf.fk_paiement = p.rowid'; - $sql.= ' AND p.entity IN ('.getEntity('invoice').')'; + $sql .= ' FROM '.MAIN_DB_PREFIX.'paiement_facture as pf, '.MAIN_DB_PREFIX.'paiement as p'; + $sql .= ' LEFT JOIN '.MAIN_DB_PREFIX.'c_paiement as c ON p.fk_paiement = c.id'; + $sql .= ' WHERE pf.fk_facture = '.$object->id; + $sql .= ' AND pf.fk_paiement = p.rowid'; + $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; @@ -811,8 +811,8 @@ if (empty($reshook)) $total_creditnote_and_deposit = 0; $sql = "SELECT re.rowid, re.amount_ht, re.amount_tva, re.amount_ttc,"; $sql .= " re.description, re.fk_facture_source"; - $sql .= " FROM " . MAIN_DB_PREFIX . "societe_remise_except as re"; - $sql .= " WHERE fk_facture = " . $object->id; + $sql .= " FROM ".MAIN_DB_PREFIX."societe_remise_except as re"; + $sql .= " WHERE fk_facture = ".$object->id; $resql = $db->query($sql); if (!empty($resql)) { while ($obj = $db->fetch_object($resql)) { @@ -853,7 +853,7 @@ if (empty($reshook)) if (empty($error)) { - if($object->type != Facture::TYPE_DEPOSIT) { + if ($object->type != Facture::TYPE_DEPOSIT) { // Classe facture $result = $object->set_paid($user); if ($result >= 0) @@ -884,9 +884,9 @@ if (empty($reshook)) if ($object->statut == Facture::STATUS_VALIDATED && $object->paye == 0) { $paiement = new Paiement($db); - $result=$paiement->fetch(GETPOST('paiement_id')); + $result = $paiement->fetch(GETPOST('paiement_id')); if ($result > 0) { - $result=$paiement->delete(); // If fetch ok and found + $result = $paiement->delete(); // If fetch ok and found header("Location: ".$_SERVER['PHP_SELF']."?id=".$id); } if ($result < 0) { @@ -920,32 +920,32 @@ if (empty($reshook)) setEventMessages($langs->trans("ErrorFieldRequired", $langs->transnoentitiesnoconv("Date")), null, 'errors'); } - if (! ($_POST['fac_replacement'] > 0)) { + if (!($_POST['fac_replacement'] > 0)) { $error++; setEventMessages($langs->trans("ErrorFieldRequired", $langs->transnoentitiesnoconv("ReplaceInvoice")), null, 'errors'); } $date_pointoftax = dol_mktime(12, 0, 0, $_POST['date_pointoftaxmonth'], $_POST['date_pointoftaxday'], $_POST['date_pointoftaxyear']); - if (! $error) { + if (!$error) { // This is a replacement invoice $result = $object->fetch($_POST['fac_replacement']); $object->fetch_thirdparty(); - $object->date = $dateinvoice; - $object->date_pointoftax = $date_pointoftax; + $object->date = $dateinvoice; + $object->date_pointoftax = $date_pointoftax; $object->note_public = trim(GETPOST('note_public', 'none')); // We do not copy the private note $object->ref_client = $_POST['ref_client']; - $object->ref_int = $_POST['ref_int']; - $object->modelpdf = $_POST['model']; + $object->ref_int = $_POST['ref_int']; + $object->modelpdf = $_POST['model']; $object->fk_project = $_POST['projectid']; $object->cond_reglement_id = $_POST['cond_reglement_id']; $object->mode_reglement_id = $_POST['mode_reglement_id']; - $object->fk_account = GETPOST('fk_account', 'int'); + $object->fk_account = GETPOST('fk_account', 'int'); $object->remise_absolue = $_POST['remise_absolue']; $object->remise_percent = $_POST['remise_percent']; - $object->fk_incoterms = GETPOST('incoterm_id', 'int'); + $object->fk_incoterms = GETPOST('incoterm_id', 'int'); $object->location_incoterms = GETPOST('location_incoterms', 'alpha'); $object->multicurrency_code = GETPOST('multicurrency_code', 'alpha'); $object->multicurrency_tx = GETPOST('originmulticurrency_tx', 'int'); @@ -965,7 +965,7 @@ if (empty($reshook)) if ($_POST['type'] == Facture::TYPE_CREDIT_NOTE) { $sourceinvoice = GETPOST('fac_avoir'); - 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'); @@ -980,27 +980,27 @@ if (empty($reshook)) $date_pointoftax = dol_mktime(12, 0, 0, $_POST['date_pointoftaxmonth'], $_POST['date_pointoftaxday'], $_POST['date_pointoftaxyear']); - if (! $error) + if (!$error) { if (!empty($originentity)) { $object->entity = $originentity; } - $object->socid = GETPOST('socid', 'int'); - $object->number = $_POST['ref']; - $object->date = $dateinvoice; - $object->date_pointoftax = $date_pointoftax; + $object->socid = GETPOST('socid', 'int'); + $object->number = $_POST['ref']; + $object->date = $dateinvoice; + $object->date_pointoftax = $date_pointoftax; $object->note_public = trim(GETPOST('note_public', 'none')); // We do not copy the private note $object->ref_client = $_POST['ref_client']; - $object->ref_int = $_POST['ref_int']; - $object->modelpdf = $_POST['model']; + $object->ref_int = $_POST['ref_int']; + $object->modelpdf = $_POST['model']; $object->fk_project = $_POST['projectid']; $object->cond_reglement_id = 0; $object->mode_reglement_id = $_POST['mode_reglement_id']; - $object->fk_account = GETPOST('fk_account', 'int'); + $object->fk_account = GETPOST('fk_account', 'int'); $object->remise_absolue = $_POST['remise_absolue']; $object->remise_percent = $_POST['remise_percent']; - $object->fk_incoterms = GETPOST('incoterm_id', 'int'); + $object->fk_incoterms = GETPOST('incoterm_id', 'int'); $object->location_incoterms = GETPOST('location_incoterms', 'alpha'); $object->multicurrency_code = GETPOST('multicurrency_code', 'alpha'); $object->multicurrency_tx = GETPOST('originmulticurrency_tx', 'int'); @@ -1010,24 +1010,24 @@ if (empty($reshook)) $object->type = Facture::TYPE_CREDIT_NOTE; $facture_source = new Facture($db); // fetch origin object - if ($facture_source->fetch($object->fk_facture_source)>0) + if ($facture_source->fetch($object->fk_facture_source) > 0) { if ($facture_source->type == Facture::TYPE_SITUATION) { - $object->situation_counter = $facture_source->situation_counter; + $object->situation_counter = $facture_source->situation_counter; $object->situation_cycle_ref = $facture_source->situation_cycle_ref; $facture_source->fetchPreviousNextSituationInvoice(); } } $id = $object->create($user); - if (GETPOST('invoiceAvoirWithLines', 'int')==1 && $id>0) + if (GETPOST('invoiceAvoirWithLines', 'int') == 1 && $id > 0) { if (!empty($facture_source->lines)) { $fk_parent_line = 0; - foreach($facture_source->lines as $line) + foreach ($facture_source->lines as $line) { // Extrafields if (empty($conf->global->MAIN_EXTRAFIELDS_DISABLED) && method_exists($line, 'fetch_optionals')) { @@ -1043,21 +1043,21 @@ if (empty($reshook)) - if($facture_source->type == Facture::TYPE_SITUATION) + if ($facture_source->type == Facture::TYPE_SITUATION) { $source_fk_prev_id = $line->fk_prev_id; // temporary storing situation invoice fk_prev_id $line->fk_prev_id = $line->id; // Credit note line need to be linked to the situation invoice it is create from - if(!empty($facture_source->tab_previous_situation_invoice)) + if (!empty($facture_source->tab_previous_situation_invoice)) { // search the last invoice in cycle $lineIndex = count($facture_source->tab_previous_situation_invoice) - 1; $searchPreviousInvoice = true; - while( $searchPreviousInvoice ) + while ($searchPreviousInvoice) { - if($facture_source->tab_previous_situation_invoice[$lineIndex]->type == Facture::TYPE_SITUATION || $lineIndex < 1) + if ($facture_source->tab_previous_situation_invoice[$lineIndex]->type == Facture::TYPE_SITUATION || $lineIndex < 1) { - $searchPreviousInvoice=false; // find, exit; + $searchPreviousInvoice = false; // find, exit; break; } else @@ -1068,9 +1068,9 @@ if (empty($reshook)) $maxPrevSituationPercent = 0; - foreach($facture_source->tab_previous_situation_invoice[$lineIndex]->lines as $prevLine) + foreach ($facture_source->tab_previous_situation_invoice[$lineIndex]->lines as $prevLine) { - if($prevLine->id == $source_fk_prev_id) + if ($prevLine->id == $source_fk_prev_id) { $maxPrevSituationPercent = max($maxPrevSituationPercent, $prevLine->situation_percent); @@ -1081,8 +1081,8 @@ if (empty($reshook)) $line->total_localtax1 = $line->total_localtax1 - $prevLine->total_localtax1; $line->total_localtax2 = $line->total_localtax2 - $prevLine->total_localtax2; - $line->multicurrency_subprice = $line->multicurrency_subprice - $prevLine->multicurrency_subprice; - $line->multicurrency_total_ht = $line->multicurrency_total_ht - $prevLine->multicurrency_total_ht; + $line->multicurrency_subprice = $line->multicurrency_subprice - $prevLine->multicurrency_subprice; + $line->multicurrency_total_ht = $line->multicurrency_total_ht - $prevLine->multicurrency_total_ht; $line->multicurrency_total_tva = $line->multicurrency_total_tva - $prevLine->multicurrency_total_tva; $line->multicurrency_total_ttc = $line->multicurrency_total_ttc - $prevLine->multicurrency_total_ttc; } @@ -1097,7 +1097,7 @@ if (empty($reshook)) $line->fk_parent_line = $fk_parent_line; $line->subprice = -$line->subprice; // invert price for object - $line->pa_ht = $line->pa_ht; // we choosed to have buy/cost price always positive, so no revert of sign here + $line->pa_ht = $line->pa_ht; // we choosed to have buy/cost price always positive, so no revert of sign here $line->total_ht = -$line->total_ht; $line->total_tva = -$line->total_tva; $line->total_ttc = -$line->total_ttc; @@ -1109,7 +1109,7 @@ if (empty($reshook)) $line->multicurrency_total_tva = -$line->multicurrency_total_tva; $line->multicurrency_total_ttc = -$line->multicurrency_total_ttc; - $result = $line->insert(0, 1); // When creating credit note with same lines than source, we must ignore error if discount alreayd linked + $result = $line->insert(0, 1); // When creating credit note with same lines than source, we must ignore error if discount alreayd linked $object->lines[] = $line; // insert new line in current object @@ -1123,9 +1123,9 @@ if (empty($reshook)) } } - if(GETPOST('invoiceAvoirWithPaymentRestAmount', 'int')==1 && $id>0) + if (GETPOST('invoiceAvoirWithPaymentRestAmount', 'int') == 1 && $id > 0) { - 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(); @@ -1137,12 +1137,12 @@ if (empty($reshook)) } // Add link between credit note and origin - if(! empty($object->fk_facture_source)) { + if (!empty($object->fk_facture_source)) { $facture_source->fetch($object->fk_facture_source); $facture_source->fetchObjectLinked(); - if(! empty($facture_source->linkedObjectsIds)) { - foreach($facture_source->linkedObjectsIds as $sourcetype => $TIds) { + if (!empty($facture_source->linkedObjectsIds)) { + foreach ($facture_source->linkedObjectsIds as $sourcetype => $TIds) { $object->add_object_linked($sourcetype, current($TIds)); } } @@ -1162,26 +1162,26 @@ if (empty($reshook)) $date_pointoftax = dol_mktime(12, 0, 0, $_POST['date_pointoftaxmonth'], $_POST['date_pointoftaxday'], $_POST['date_pointoftaxyear']); - if (! $error) + if (!$error) { - $object->socid = GETPOST('socid', 'int'); + $object->socid = GETPOST('socid', 'int'); $object->type = $_POST['type']; $object->number = $_POST['ref']; $object->date = $dateinvoice; $object->date_pointoftax = $date_pointoftax; - $object->note_public = trim(GETPOST('note_public', 'none')); + $object->note_public = trim(GETPOST('note_public', 'none')); $object->note_private = trim(GETPOST('note_private', 'none')); $object->ref_client = $_POST['ref_client']; - $object->ref_int = $_POST['ref_int']; + $object->ref_int = $_POST['ref_int']; $object->modelpdf = $_POST['model']; - $object->fk_project = $_POST['projectid']; - $object->cond_reglement_id = ($_POST['type'] == 3?1:$_POST['cond_reglement_id']); + $object->fk_project = $_POST['projectid']; + $object->cond_reglement_id = ($_POST['type'] == 3 ? 1 : $_POST['cond_reglement_id']); $object->mode_reglement_id = $_POST['mode_reglement_id']; - $object->fk_account = GETPOST('fk_account', 'int'); - $object->amount = $_POST['amount']; + $object->fk_account = GETPOST('fk_account', 'int'); + $object->amount = $_POST['amount']; $object->remise_absolue = $_POST['remise_absolue']; $object->remise_percent = $_POST['remise_percent']; - $object->fk_incoterms = GETPOST('incoterm_id', 'int'); + $object->fk_incoterms = GETPOST('incoterm_id', 'int'); $object->location_incoterms = GETPOST('location_incoterms', 'alpha'); $object->multicurrency_code = GETPOST('multicurrency_code', 'alpha'); $object->multicurrency_tx = GETPOST('originmulticurrency_tx', 'int'); @@ -1189,7 +1189,7 @@ if (empty($reshook)) // Source facture $object->fac_rec = GETPOST('fac_rec', 'int'); - $id = $object->create($user); // This include recopy of links from recurring invoice and recurring invoice lines + $id = $object->create($user); // This include recopy of links from recurring invoice and recurring invoice lines } } @@ -1211,27 +1211,27 @@ if (empty($reshook)) $date_pointoftax = dol_mktime(12, 0, 0, $_POST['date_pointoftaxmonth'], $_POST['date_pointoftaxday'], $_POST['date_pointoftaxyear']); - if (! $error) + if (!$error) { // Si facture standard - $object->socid = GETPOST('socid', 'int'); + $object->socid = GETPOST('socid', 'int'); $object->type = GETPOST('type'); - $object->number = $_POST['ref']; + $object->number = $_POST['ref']; $object->date = $dateinvoice; - $object->date_pointoftax = $date_pointoftax; + $object->date_pointoftax = $date_pointoftax; $object->note_public = trim(GETPOST('note_public', 'none')); - $object->note_private = trim(GETPOST('note_private', 'none')); + $object->note_private = trim(GETPOST('note_private', 'none')); $object->ref_client = $_POST['ref_client']; - $object->ref_int = $_POST['ref_int']; - $object->modelpdf = $_POST['model']; + $object->ref_int = $_POST['ref_int']; + $object->modelpdf = $_POST['model']; $object->fk_project = $_POST['projectid']; - $object->cond_reglement_id = ($_POST['type'] == 3?1:$_POST['cond_reglement_id']); + $object->cond_reglement_id = ($_POST['type'] == 3 ? 1 : $_POST['cond_reglement_id']); $object->mode_reglement_id = $_POST['mode_reglement_id']; - $object->fk_account = GETPOST('fk_account', 'int'); - $object->amount = $_POST['amount']; + $object->fk_account = GETPOST('fk_account', 'int'); + $object->amount = $_POST['amount']; $object->remise_absolue = $_POST['remise_absolue']; $object->remise_percent = $_POST['remise_percent']; - $object->fk_incoterms = GETPOST('incoterm_id', 'int'); + $object->fk_incoterms = GETPOST('incoterm_id', 'int'); $object->location_incoterms = GETPOST('location_incoterms', 'alpha'); $object->multicurrency_code = GETPOST('multicurrency_code', 'alpha'); $object->multicurrency_tx = GETPOST('originmulticurrency_tx', 'int'); @@ -1243,11 +1243,11 @@ if (empty($reshook)) $object->situation_cycle_ref = $object->newCycle(); - $object->retained_warranty = GETPOST('retained_warranty', 'int'); - $object->retained_warranty_fk_cond_reglement = GETPOST('retained_warranty_fk_cond_reglement', 'int'); + $object->retained_warranty = GETPOST('retained_warranty', 'int'); + $object->retained_warranty_fk_cond_reglement = GETPOST('retained_warranty_fk_cond_reglement', 'int'); $retained_warranty_date_limit = GETPOST('retained_warranty_date_limit'); - if(!empty($retained_warranty_date_limit) && $db->jdate($retained_warranty_date_limit)){ + if (!empty($retained_warranty_date_limit) && $db->jdate($retained_warranty_date_limit)) { $object->retained_warranty_date_limit = $db->jdate($retained_warranty_date_limit); } $object->retained_warranty_date_limit = !empty($object->retained_warranty_date_limit) ? $object->retained_warranty_date_limit : $object->calculate_date_lim_reglement($object->retained_warranty_fk_cond_reglement); @@ -1256,7 +1256,7 @@ if (empty($reshook)) $object->fetch_thirdparty(); // 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; @@ -1291,32 +1291,32 @@ if (empty($reshook)) // link with order if it is a shipping invoice if ($object->origin == 'shipping') { - require_once DOL_DOCUMENT_ROOT . '/expedition/class/expedition.class.php'; + require_once DOL_DOCUMENT_ROOT.'/expedition/class/expedition.class.php'; $exp = new Expedition($db); $exp->fetch($object->origin_id); $exp->fetchObjectLinked(); if (is_array($exp->linkedObjectsIds['commande']) && count($exp->linkedObjectsIds['commande']) > 0) { - foreach ($exp->linkedObjectsIds['commande'] as $key => $value){ + foreach ($exp->linkedObjectsIds['commande'] as $key => $value) { $object->linked_objects['commande'] = $value; } } } - 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']); } - $id = $object->create($user); // This include class to add_object_linked() and add add_contact() + $id = $object->create($user); // This include class to add_object_linked() and add add_contact() if ($id > 0) { - dol_include_once('/' . $element . '/class/' . $subelement . '.class.php'); + dol_include_once('/'.$element.'/class/'.$subelement.'.class.php'); $classname = ucfirst($subelement); $srcobject = new $classname($db); - dol_syslog("Try to find source object origin=" . $object->origin . " originid=" . $object->origin_id . " to add lines or deposit lines"); + dol_syslog("Try to find source object origin=".$object->origin." originid=".$object->origin_id." to add lines or deposit lines"); $result = $srcobject->fetch($object->origin_id); // If deposit invoice @@ -1334,8 +1334,8 @@ if (empty($reshook)) $TTotalByTva = array(); foreach ($srcobject->lines as &$line) { - if(! empty($line->special_code)) continue; - $TTotalByTva[$line->tva_tx] += $line->total_ttc ; + if (!empty($line->special_code)) continue; + $TTotalByTva[$line->tva_tx] += $line->total_ttc; } foreach ($TTotalByTva as $tva => &$total) @@ -1358,20 +1358,20 @@ if (empty($reshook)) { $totalamount = 0; $lines = $srcobject->lines; - $numlines=count($lines); - for ($i=0; $i<$numlines; $i++) + $numlines = count($lines); + for ($i = 0; $i < $numlines; $i++) { - $qualified=1; - if (empty($lines[$i]->qty)) $qualified=0; // We discard qty=0, it is an option - if (! empty($lines[$i]->special_code)) $qualified=0; // We discard special_code (frais port, ecotaxe, option, ...) - if ($qualified){ + $qualified = 1; + if (empty($lines[$i]->qty)) $qualified = 0; // We discard qty=0, it is an option + if (!empty($lines[$i]->special_code)) $qualified = 0; // We discard special_code (frais port, ecotaxe, option, ...) + if ($qualified) { $totalamount += $lines[$i]->total_ht; // Fixme : is it not for the customer ? Shouldn't we take total_ttc ? $tva_tx = $lines[$i]->tva_tx; $amountdeposit[$tva_tx] += ($lines[$i]->total_ht * $valuedeposit) / 100; } } - if($totalamount == 0) { + if ($totalamount == 0) { $amountdeposit[0] = 0; } } else { @@ -1386,33 +1386,33 @@ if (empty($reshook)) { if (empty($amount)) continue; - $arraylist = array('amount' => 'FixAmount','variable' => 'VarAmount'); + $arraylist = array('amount' => 'FixAmount', 'variable' => 'VarAmount'); $descline = $langs->trans('Deposit'); //$descline.= ' - '.$langs->trans($arraylist[$typeamount]); - if ($typeamount=='amount') { - $descline.= ' ('. price($valuedeposit, '', $langs, 0, - 1, - 1, (!empty($object->multicurrency_code) ? $object->multicurrency_code : $conf->currency)).')'; - } elseif ($typeamount=='variable') { - $descline.= ' ('. $valuedeposit.'%)'; + if ($typeamount == 'amount') { + $descline .= ' ('.price($valuedeposit, '', $langs, 0, - 1, - 1, (!empty($object->multicurrency_code) ? $object->multicurrency_code : $conf->currency)).')'; + } elseif ($typeamount == 'variable') { + $descline .= ' ('.$valuedeposit.'%)'; } - $descline.= ' - '.$srcobject->ref; + $descline .= ' - '.$srcobject->ref; $result = $object->addline( $descline, - $amount, // subprice - 1, // quantity - $tva, // vat rate - 0, // localtax1_tx - 0, // localtax2_tx - (empty($conf->global->INVOICE_PRODUCTID_DEPOSIT)?0:$conf->global->INVOICE_PRODUCTID_DEPOSIT), // fk_product - 0, // remise_percent - 0, // date_start - 0, // date_end + $amount, // subprice + 1, // quantity + $tva, // vat rate + 0, // localtax1_tx + 0, // localtax2_tx + (empty($conf->global->INVOICE_PRODUCTID_DEPOSIT) ? 0 : $conf->global->INVOICE_PRODUCTID_DEPOSIT), // fk_product + 0, // remise_percent + 0, // date_start + 0, // date_end 0, - $lines[$i]->info_bits, // info_bits + $lines[$i]->info_bits, // info_bits 0, 'HT', 0, - 0, // product_type + 0, // product_type 1, $lines[$i]->special_code, $object->origin, @@ -1444,19 +1444,19 @@ if (empty($reshook)) $lines = $srcobject->lines; } - $fk_parent_line=0; - $num=count($lines); - for ($i=0;$i<$num;$i++) + $fk_parent_line = 0; + $num = count($lines); + for ($i = 0; $i < $num; $i++) { // Don't add lines with qty 0 when coming from a shipment including all order lines - if($srcobject->element == 'shipping' && $conf->global->SHIPMENT_GETS_ALL_ORDER_PRODUCTS && $lines[$i]->qty == 0) continue; + if ($srcobject->element == 'shipping' && $conf->global->SHIPMENT_GETS_ALL_ORDER_PRODUCTS && $lines[$i]->qty == 0) continue; // Don't add closed lines when coming from a contract (Set constant to '0,5' to exclude also inactive lines) - if (! isset($conf->global->CONTRACT_EXCLUDE_SERVICES_STATUS_FOR_INVOICE)) $conf->global->CONTRACT_EXCLUDE_SERVICES_STATUS_FOR_INVOICE = '5'; + if (!isset($conf->global->CONTRACT_EXCLUDE_SERVICES_STATUS_FOR_INVOICE)) $conf->global->CONTRACT_EXCLUDE_SERVICES_STATUS_FOR_INVOICE = '5'; if ($srcobject->element == 'contrat' && in_array($lines[$i]->statut, explode(',', $conf->global->CONTRACT_EXCLUDE_SERVICES_STATUS_FOR_INVOICE))) continue; - $label=(! empty($lines[$i]->label)?$lines[$i]->label:''); - $desc=(! empty($lines[$i]->desc)?$lines[$i]->desc:$lines[$i]->libelle); - if ($object->situation_counter == 1) $lines[$i]->situation_percent = 0; + $label = (!empty($lines[$i]->label) ? $lines[$i]->label : ''); + $desc = (!empty($lines[$i]->desc) ? $lines[$i]->desc : $lines[$i]->libelle); + if ($object->situation_counter == 1) $lines[$i]->situation_percent = 0; if ($lines[$i]->subprice < 0 && empty($conf->global->INVOICE_KEEP_DISCOUNT_LINES_AS_IN_ORIGIN)) { @@ -1511,7 +1511,7 @@ if (empty($reshook)) } $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.')'; // View third's localtaxes for NOW and do not use value from origin. // TODO Is this really what we want ? Yes if source if template invoice but what if proposal or order ? @@ -1590,13 +1590,13 @@ if (empty($reshook)) { // If some invoice's lines coming from page $id = $object->create($user); - for ($i = 1; $i <= $NBLINES; $i ++) { - if ($_POST['idprod' . $i]) { + for ($i = 1; $i <= $NBLINES; $i++) { + if ($_POST['idprod'.$i]) { $product = new Product($db); - $product->fetch($_POST['idprod' . $i]); - $startday = dol_mktime(12, 0, 0, $_POST['date_start' . $i . 'month'], $_POST['date_start' . $i . 'day'], $_POST['date_start' . $i . 'year']); - $endday = dol_mktime(12, 0, 0, $_POST['date_end' . $i . 'month'], $_POST['date_end' . $i . 'day'], $_POST['date_end' . $i . 'year']); - $result = $object->addline($product->description, $product->price, $_POST['qty' . $i], $product->tva_tx, $product->localtax1_tx, $product->localtax2_tx, $_POST['idprod' . $i], $_POST['remise_percent' . $i], $startday, $endday, 0, 0, '', $product->price_base_type, $product->price_ttc, $product->type, -1, 0, '', 0, 0, null, 0, '', 0, 100, '', $product->fk_unit); + $product->fetch($_POST['idprod'.$i]); + $startday = dol_mktime(12, 0, 0, $_POST['date_start'.$i.'month'], $_POST['date_start'.$i.'day'], $_POST['date_start'.$i.'year']); + $endday = dol_mktime(12, 0, 0, $_POST['date_end'.$i.'month'], $_POST['date_end'.$i.'day'], $_POST['date_end'.$i.'year']); + $result = $object->addline($product->description, $product->price, $_POST['qty'.$i], $product->tva_tx, $product->localtax1_tx, $product->localtax2_tx, $_POST['idprod'.$i], $_POST['remise_percent'.$i], $startday, $endday, 0, 0, '', $product->price_base_type, $product->price_ttc, $product->type, -1, 0, '', 0, 0, null, 0, '', 0, 100, '', $product->fk_unit); } } } @@ -1637,13 +1637,13 @@ if (empty($reshook)) $line->origin_id = $line->id; $line->fk_prev_id = $line->id; $line->fetch_optionals($line->id); - $line->situation_percent = $line->get_prev_progress($object->id); // get good progress including credit note + $line->situation_percent = $line->get_prev_progress($object->id); // get good progress including credit note // Si fk_remise_except defini on vérifie si la réduction à déjà été appliquée if ($line->fk_remise_except) { - $discount=new DiscountAbsolute($line->db); - $result=$discount->fetch($line->fk_remise_except); + $discount = new DiscountAbsolute($line->db); + $result = $discount->fetch($line->fk_remise_except); if ($result > 0) { // Check if discount not already affected to another invoice @@ -1694,7 +1694,7 @@ if (empty($reshook)) } // End of object creation, we show it - if ($id > 0 && ! $error) + if ($id > 0 && !$error) { $db->commit(); @@ -1705,19 +1705,19 @@ if (empty($reshook)) $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 (!empty($newlang)) { $outputlangs = new Translate("", $conf); $outputlangs->setDefaultLang($newlang); $outputlangs->load('products'); } - $model=$object->modelpdf; + $model = $object->modelpdf; $ret = $object->fetch($id); // Reload to get new records $result = $object->generateDocument($model, $outputlangs, $hidedetails, $hidedesc, $hideref); if ($result < 0) setEventMessages($object->error, $object->errors, 'errors'); } - header('Location: ' . $_SERVER["PHP_SELF"] . '?facid=' . $id); + header('Location: '.$_SERVER["PHP_SELF"].'?facid='.$id); exit(); } else @@ -1737,24 +1737,24 @@ if (empty($reshook)) $error = 0; // Set if we used free entry or predefined product - $predef=''; - $product_desc=(GETPOST('dp_desc', 'none')?GETPOST('dp_desc', 'none'):''); + $predef = ''; + $product_desc = (GETPOST('dp_desc', 'none') ?GETPOST('dp_desc', 'none') : ''); $price_ht = GETPOST('price_ht'); $price_ht_devise = GETPOST('multicurrency_price_ht'); $prod_entry_mode = GETPOST('prod_entry_mode', 'alpha'); if ($prod_entry_mode == 'free') { - $idprod=0; + $idprod = 0; $tva_tx = (GETPOST('tva_tx', 'alpha') ? GETPOST('tva_tx', 'alpha') : 0); } else { - $idprod=GETPOST('idprod', 'int'); + $idprod = GETPOST('idprod', 'int'); $tva_tx = ''; } - $qty = GETPOST('qty' . $predef); - $remise_percent = GETPOST('remise_percent' . $predef); + $qty = GETPOST('qty'.$predef); + $remise_percent = GETPOST('remise_percent'.$predef); // Extrafields $extralabelsline = $extrafields->fetch_name_optionals_label($object->table_element_line); @@ -1763,7 +1763,7 @@ if (empty($reshook)) if (is_array($extralabelsline)) { // Get extra fields foreach ($extralabelsline as $key => $value) { - unset($_POST["options_" . $key . $predef]); + unset($_POST["options_".$key.$predef]); } } @@ -1773,7 +1773,7 @@ if (empty($reshook)) } if (!$prod_entry_mode) { - if (GETPOST('type') < 0 && ! GETPOST('search_idprod')) + if (GETPOST('type') < 0 && !GETPOST('search_idprod')) { setEventMessages($langs->trans('ErrorChooseBetweenFreeEntryOrPredefinedProduct'), null, 'errors'); $error++; @@ -1827,7 +1827,7 @@ if (empty($reshook)) } } - if (! $error && ($qty >= 0) && (! empty($product_desc) || ! empty($idprod))) { + if (!$error && ($qty >= 0) && (!empty($product_desc) || !empty($idprod))) { $ret = $object->fetch($id); if ($ret < 0) { dol_print_error($db, $object->error); @@ -1836,8 +1836,8 @@ if (empty($reshook)) $ret = $object->fetch_thirdparty(); // 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')); + $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')); $price_base_type = (GETPOST('price_base_type', 'alpha') ? GETPOST('price_base_type', 'alpha') : 'HT'); // Define special_code for special lines @@ -1849,7 +1849,7 @@ if (empty($reshook)) // Ecrase $tva_tx par celui du produit // Ecrase $base_price_type par celui du produit // Replaces $fk_unit with the product's - if (! empty($idprod)) + if (!empty($idprod)) { $prod = new Product($db); $prod->fetch($idprod); @@ -1872,7 +1872,7 @@ if (empty($reshook)) $tmpprodvat = price2num(preg_replace('/\s*\(.*\)/', '', $prod->tva_tx)); // if price ht was forced (ie: from gui when calculated by margin rate and cost price). TODO Why this ? - if (! empty($price_ht)) + if (!empty($price_ht)) { $pu_ht = price2num($price_ht, 'MU'); $pu_ttc = price2num($pu_ht * (1 + ($tmpvat / 100)), 'MU'); @@ -1894,56 +1894,56 @@ if (empty($reshook)) $desc = ''; // 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)) { $outputlangs = $langs; $newlang = ''; if (empty($newlang) && GETPOST('lang_id', 'aZ09')) $newlang = GETPOST('lang_id', 'aZ09'); if (empty($newlang)) $newlang = $object->thirdparty->default_lang; - if (! empty($newlang)) { + if (!empty($newlang)) { $outputlangs = new Translate("", $conf); $outputlangs->setDefaultLang($newlang); $outputlangs->load('products'); } - $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; } - if (!empty($product_desc) && !empty($conf->global->MAIN_NO_CONCAT_DESCRIPTION)) $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)); // Add custom code and origin country into description - if (empty($conf->global->MAIN_PRODUCT_DISABLE_CUSTOMCOUNTRYCODE) && (! empty($prod->customcode) || ! empty($prod->country_code))) { + if (empty($conf->global->MAIN_PRODUCT_DISABLE_CUSTOMCOUNTRYCODE) && (!empty($prod->customcode) || !empty($prod->country_code))) { $tmptxt = '('; // 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)) { $outputlangs = $langs; $newlang = ''; if (empty($newlang) && GETPOST('lang_id', 'alpha')) $newlang = GETPOST('lang_id', 'alpha'); if (empty($newlang)) $newlang = $object->thirdparty->default_lang; - if (! empty($newlang)) { + if (!empty($newlang)) { $outputlangs = new Translate("", $conf); $outputlangs->setDefaultLang($newlang); $outputlangs->load('products'); } - if (! empty($prod->customcode)) - $tmptxt .= $outputlangs->transnoentitiesnoconv("CustomCode") . ': ' . $prod->customcode; - if (! empty($prod->customcode) && ! empty($prod->country_code)) + if (!empty($prod->customcode)) + $tmptxt .= $outputlangs->transnoentitiesnoconv("CustomCode").': '.$prod->customcode; + if (!empty($prod->customcode) && !empty($prod->country_code)) $tmptxt .= ' - '; - if (! empty($prod->country_code)) - $tmptxt .= $outputlangs->transnoentitiesnoconv("CountryOrigin") . ': ' . getCountry($prod->country_code, 0, $db, $outputlangs, 0); + if (!empty($prod->country_code)) + $tmptxt .= $outputlangs->transnoentitiesnoconv("CountryOrigin").': '.getCountry($prod->country_code, 0, $db, $outputlangs, 0); } else { - if (! empty($prod->customcode)) - $tmptxt .= $langs->transnoentitiesnoconv("CustomCode") . ': ' . $prod->customcode; - if (! empty($prod->customcode) && ! empty($prod->country_code)) + if (!empty($prod->customcode)) + $tmptxt .= $langs->transnoentitiesnoconv("CustomCode").': '.$prod->customcode; + if (!empty($prod->customcode) && !empty($prod->country_code)) $tmptxt .= ' - '; - if (! empty($prod->country_code)) - $tmptxt .= $langs->transnoentitiesnoconv("CountryOrigin") . ': ' . getCountry($prod->country_code, 0, $db, $langs, 0); + if (!empty($prod->country_code)) + $tmptxt .= $langs->transnoentitiesnoconv("CountryOrigin").': '.getCountry($prod->country_code, 0, $db, $langs, 0); } $tmptxt .= ')'; $desc = dol_concatdesc($desc, $tmptxt); @@ -1956,17 +1956,17 @@ if (empty($reshook)) $pu_ttc = price2num(GETPOST('price_ttc'), 'MU'); $tva_npr = (preg_match('/\*/', $tva_tx) ? 1 : 0); $tva_tx = str_replace('*', '', $tva_tx); - if (empty($tva_tx)) $tva_npr=0; + if (empty($tva_tx)) $tva_npr = 0; $label = (GETPOST('product_label') ? GETPOST('product_label') : ''); $desc = $product_desc; $type = GETPOST('type'); - $fk_unit= GETPOST('units', 'alpha'); + $fk_unit = GETPOST('units', 'alpha'); $pu_ht_devise = price2num($price_ht_devise, 'MU'); } // Margin - $fournprice = price2num(GETPOST('fournprice' . $predef) ? GETPOST('fournprice' . $predef) : ''); - $buyingprice = price2num(GETPOST('buying_price' . $predef) != '' ? GETPOST('buying_price' . $predef) : ''); // If buying_price is '0', we must keep this value + $fournprice = price2num(GETPOST('fournprice'.$predef) ? GETPOST('fournprice'.$predef) : ''); + $buyingprice = price2num(GETPOST('buying_price'.$predef) != '' ? GETPOST('buying_price'.$predef) : ''); // If buying_price is '0', we must keep this value // Local Taxes $localtax1_tx = get_localtax($tva_tx, 1, $object->thirdparty, $mysoc, $tva_npr); @@ -1976,7 +1976,7 @@ if (empty($reshook)) if ($tva_npr) $info_bits |= 0x01; - if ($usercanproductignorepricemin && (! empty($price_min) && (price2num($pu_ht) * (1 - price2num($remise_percent) / 100) < price2num($price_min)))) { + if ($usercanproductignorepricemin && (!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)); setEventMessages($mesg, null, 'errors'); } else { @@ -1992,12 +1992,12 @@ if (empty($reshook)) $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 (!empty($newlang)) { $outputlangs = new Translate("", $conf); $outputlangs->setDefaultLang($newlang); $outputlangs->load('products'); } - $model=$object->modelpdf; + $model = $object->modelpdf; $ret = $object->fetch($id); // Reload to get new records $result = $object->generateDocument($model, $outputlangs, $hidedetails, $hidedesc, $hideref); @@ -2048,9 +2048,9 @@ if (empty($reshook)) } } - elseif ($action == 'updateline' && $usercancreate && ! GETPOST('cancel', 'alpha')) + elseif ($action == 'updateline' && $usercancreate && !GETPOST('cancel', 'alpha')) { - if (! $object->fetch($id) > 0) dol_print_error($db); + if (!$object->fetch($id) > 0) dol_print_error($db); $object->fetch_thirdparty(); // Clean parameters @@ -2075,7 +2075,7 @@ if (empty($reshook)) // Add buying price $fournprice = price2num(GETPOST('fournprice') ? GETPOST('fournprice') : ''); - $buyingprice = price2num(GETPOST('buying_price') != '' ? GETPOST('buying_price') : ''); // If buying_price is '0', we muste keep this value + $buyingprice = price2num(GETPOST('buying_price') != '' ? GETPOST('buying_price') : ''); // If buying_price is '0', we muste keep this value // Extrafields $extralabelsline = $extrafields->fetch_name_optionals_label($object->table_element_line); @@ -2084,22 +2084,22 @@ if (empty($reshook)) if (is_array($extralabelsline)) { // Get extra fields foreach ($extralabelsline as $key => $value) { - unset($_POST["options_" . $key]); + unset($_POST["options_".$key]); } } // Define special_code for special lines - $special_code=GETPOST('special_code'); - if (! GETPOST('qty')) $special_code=3; + $special_code = GETPOST('special_code'); + if (!GETPOST('qty')) $special_code = 3; $line = new FactureLigne($db); $line->fetch(GETPOST('lineid')); $percent = $line->get_prev_progress($object->id); - if ($object->type == Facture::TYPE_CREDIT_NOTE && $object->situation_cycle_ref>0) + if ($object->type == Facture::TYPE_CREDIT_NOTE && $object->situation_cycle_ref > 0) { // in case of situation credit note - if(GETPOST('progress') >= 0 ) + if (GETPOST('progress') >= 0) { $mesg = $langs->trans("CantBeNullOrPositive"); setEventMessages($mesg, null, 'warnings'); @@ -2116,7 +2116,7 @@ if (empty($reshook)) } elseif (GETPOST('progress') < $percent) { - $mesg = '
' . $langs->trans("CantBeLessThanMinPercent") . '
'; + $mesg = '
'.$langs->trans("CantBeLessThanMinPercent").'
'; setEventMessages($mesg, null, 'warnings'); $error++; $result = -1; @@ -2124,7 +2124,7 @@ if (empty($reshook)) // Check minimum price $productid = GETPOST('productid', 'int'); - if (! empty($productid)) + if (!empty($productid)) { $product = new Product($db); $product->fetch($productid); @@ -2132,7 +2132,7 @@ 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') : ''); @@ -2174,7 +2174,7 @@ if (empty($reshook)) // Update line - if (! $error) { + if (!$error) { if (empty($usercancreatemargin)) { foreach ($object->lines as &$line) @@ -2202,7 +2202,7 @@ if (empty($reshook)) $newlang = GETPOST('lang_id', 'aZ09'); 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); $outputlangs->load('products'); @@ -2263,7 +2263,7 @@ if (empty($reshook)) { $percent = $line->get_prev_progress($object->id); if (floatval($all_progress) < floatval($percent)) { - $mesg = $langs->trans("Line") . ' ' . $i . ' '. $line->ref .' : ' . $langs->trans("CantBeLessThanMinPercent"); + $mesg = $langs->trans("Line").' '.$i.' '.$line->ref.' : '.$langs->trans("CantBeLessThanMinPercent"); setEventMessages($mesg, null, 'warnings'); $result = -1; } else @@ -2273,7 +2273,7 @@ if (empty($reshook)) } elseif ($action == 'updateline' && $usercancreate && $_POST['cancel'] == $langs->trans('Cancel')) { - header('Location: ' . $_SERVER["PHP_SELF"] . '?facid=' . $id); // Pour reaffichage de la fiche en cours d'edition + header('Location: '.$_SERVER["PHP_SELF"].'?facid='.$id); // Pour reaffichage de la fiche en cours d'edition exit(); } @@ -2292,7 +2292,7 @@ if (empty($reshook)) { $outingError = 0; $newCycle = $object->newCycle(); // we need to keep the "situation behavior" so we place it on a new situation cycle - if($newCycle > 1) + if ($newCycle > 1) { // Search credit notes $lastCycle = $object->situation_cycle_ref; @@ -2301,12 +2301,12 @@ if (empty($reshook)) if (count($object->tab_next_situation_invoice) > 0) { foreach ($object->tab_next_situation_invoice as $next_invoice) { - if($next_invoice->type == Facture::TYPE_CREDIT_NOTE + if ($next_invoice->type == Facture::TYPE_CREDIT_NOTE && $next_invoice->situation_counter == $object->situation_counter && $next_invoice->fk_facture_source == $object->id ) { - $linkedCreditNotesList[] = $next_invoice->id ; + $linkedCreditNotesList[] = $next_invoice->id; } } } @@ -2314,38 +2314,38 @@ if (empty($reshook)) $object->situation_cycle_ref = $newCycle; $object->situation_counter = 1; $object->situation_final = 0; - if($object->update($user) > 0) + if ($object->update($user) > 0) { $errors = 0; - if(count($linkedCreditNotesList) > 0) + if (count($linkedCreditNotesList) > 0) { // now, credit note must follow $sql = 'UPDATE '.MAIN_DB_PREFIX.'facture '; - $sql.= ' SET situation_cycle_ref='.$newCycle; - $sql.= ' , situation_final=0'; - $sql.= ' , situation_counter='.$object->situation_counter; - $sql.= ' WHERE rowid IN ('.implode(',', $linkedCreditNotesList).')'; + $sql .= ' SET situation_cycle_ref='.$newCycle; + $sql .= ' , situation_final=0'; + $sql .= ' , situation_counter='.$object->situation_counter; + $sql .= ' WHERE rowid IN ('.implode(',', $linkedCreditNotesList).')'; - $resql=$db->query($sql); + $resql = $db->query($sql); if (!$resql) $errors++; // Change each progression persent on each lines - foreach($object->lines as $line) + foreach ($object->lines as $line) { // no traitement for special product - if ($line->product_type == 9 ) continue; + if ($line->product_type == 9) continue; - if(!empty($object->tab_previous_situation_invoice)) + if (!empty($object->tab_previous_situation_invoice)) { // search the last invoice in cycle $lineIndex = count($object->tab_previous_situation_invoice) - 1; $searchPreviousInvoice = true; - while( $searchPreviousInvoice ) + while ($searchPreviousInvoice) { - if($object->tab_previous_situation_invoice[$lineIndex]->type == Facture::TYPE_SITUATION || $lineIndex < 1) + if ($object->tab_previous_situation_invoice[$lineIndex]->type == Facture::TYPE_SITUATION || $lineIndex < 1) { - $searchPreviousInvoice=false; // find, exit; + $searchPreviousInvoice = false; // find, exit; break; } else @@ -2356,9 +2356,9 @@ if (empty($reshook)) $maxPrevSituationPercent = 0; - foreach($object->tab_previous_situation_invoice[$lineIndex]->lines as $prevLine) + foreach ($object->tab_previous_situation_invoice[$lineIndex]->lines as $prevLine) { - if($prevLine->id == $line->fk_prev_id) + if ($prevLine->id == $line->fk_prev_id) { $maxPrevSituationPercent = max($maxPrevSituationPercent, $prevLine->situation_percent); } @@ -2367,7 +2367,7 @@ if (empty($reshook)) $line->situation_percent = $line->situation_percent - $maxPrevSituationPercent; - if($line->update()<0) $errors++; + if ($line->update() < 0) $errors++; } } } @@ -2395,7 +2395,7 @@ if (empty($reshook)) } // add lines from objectlinked - elseif($action == 'import_lines_from_object' + elseif ($action == 'import_lines_from_object' && $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)) @@ -2404,14 +2404,14 @@ if (empty($reshook)) $fromElementid = GETPOST('fromelementid'); $importLines = GETPOST('line_checkbox'); - if(!empty($importLines) && is_array($importLines) && !empty($fromElement) && ctype_alpha($fromElement) && !empty($fromElementid)) + if (!empty($importLines) && is_array($importLines) && !empty($fromElement) && ctype_alpha($fromElement) && !empty($fromElementid)) { - if($fromElement == 'commande') + 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'; @@ -2419,11 +2419,11 @@ if (empty($reshook)) $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($lineId); $desc = $originLine->desc; @@ -2439,15 +2439,15 @@ if (empty($reshook)) $ventil = 0; $info_bits = $originLine->info_bits; $fk_remise_except = $originLine->fk_remise_except; - $price_base_type='HT'; - $pu_ttc=0; + $price_base_type = 'HT'; + $pu_ttc = 0; $type = $originLine->product_type; - $rang=$nextRang++; + $rang = $nextRang++; $special_code = $originLine->special_code; $origin = $originLine->element; $origin_id = $originLine->id; - $fk_parent_line=0; - $fk_fournprice=$originLine->fk_fournprice; + $fk_parent_line = 0; + $fk_fournprice = $originLine->fk_fournprice; $pa_ht = $originLine->pa_ht; $label = $originLine->label; $array_options = $originLine->array_options; @@ -2458,18 +2458,18 @@ if (empty($reshook)) $res = $object->addline($desc, $pu_ht, $qty, $txtva, $txlocaltax1, $txlocaltax2, $fk_product, $remise_percent, $date_start, $date_end, $ventil, $info_bits, $fk_remise_except, $price_base_type, $pu_ttc, $type, $rang, $special_code, $origin, $origin_id, $fk_parent_line, $fk_fournprice, $pa_ht, $label, $array_options, $situation_percent, $fk_prev_id, $fk_unit, $pu_ht_devise); - if($res > 0){ + if ($res > 0) { $importCount++; - }else{ + } else { $error++; } } - else{ + else { $error++; } } - if($error) + if ($error) { setEventMessages($langs->trans('ErrorsOnXLines', $error), null, 'errors'); } @@ -2480,16 +2480,16 @@ if (empty($reshook)) include DOL_DOCUMENT_ROOT.'/core/actions_printing.inc.php'; // Actions to send emails - if (empty($id)) $id=$facid; - $trigger_name='BILL_SENTBYMAIL'; - $paramname='id'; - $autocopy='MAIN_MAIL_AUTOCOPY_INVOICE_TO'; - $trackid='inv'.$object->id; + if (empty($id)) $id = $facid; + $trigger_name = 'BILL_SENTBYMAIL'; + $paramname = 'id'; + $autocopy = 'MAIN_MAIL_AUTOCOPY_INVOICE_TO'; + $trackid = 'inv'.$object->id; include DOL_DOCUMENT_ROOT.'/core/actions_sendmails.inc.php'; // Actions to build doc $upload_dir = $conf->facture->multidir_output[$object->entity]; - $permissiontoadd=$usercancreate; + $permissiontoadd = $usercancreate; include DOL_DOCUMENT_ROOT.'/core/actions_builddoc.inc.php'; @@ -2500,7 +2500,7 @@ if (empty($reshook)) $ret = $extrafields->setOptionalsFromPost(null, $object, GETPOST('attribute', 'none')); if ($ret < 0) $error++; - if (! $error) + if (!$error) { // Actions on extra fields $result = $object->insertExtraFields('BILL_MODIFY'); @@ -2515,7 +2515,7 @@ if (empty($reshook)) $action = 'edit_extras'; } - if (! empty($conf->global->MAIN_DISABLE_CONTACTS_TAB) && $usercancreate) { + if (!empty($conf->global->MAIN_DISABLE_CONTACTS_TAB) && $usercancreate) { if ($action == 'addcontact') { $result = $object->fetch($id); @@ -2570,13 +2570,13 @@ $formother = new FormOther($db); $formfile = new FormFile($db); $formmargin = new FormMargin($db); $soc = new Societe($db); -$paymentstatic=new Paiement($db); +$paymentstatic = new Paiement($db); $bankaccountstatic = new Account($db); -if (! empty($conf->projet->enabled)) { $formproject = new FormProjets($db); } +if (!empty($conf->projet->enabled)) { $formproject = new FormProjets($db); } $now = dol_now(); -$title = $langs->trans('InvoiceCustomer') . " - " . $langs->trans('Card'); +$title = $langs->trans('InvoiceCustomer')." - ".$langs->trans('Card'); $helpurl = "EN:Customers_Invoices|FR:Factures_Clients|ES:Facturas_a_clientes"; llxHeader('', $title, $helpurl); @@ -2596,7 +2596,7 @@ if ($action == 'create') // Load objectsrc $remise_absolue = 0; - if (! empty($origin) && ! empty($originid)) + if (!empty($origin) && !empty($originid)) { // Parse element/subelement (ex: project_task) $element = $subelement = $origin; @@ -2620,7 +2620,7 @@ if ($action == 'create') } if (!$dateinvoice) { // Do not set 0 here (0 for a date is 1970) - $dateinvoice = (empty($dateinvoice)?(empty($conf->global->MAIN_AUTOFILL_DATE)?-1:''):$dateinvoice); + $dateinvoice = (empty($dateinvoice) ? (empty($conf->global->MAIN_AUTOFILL_DATE) ?-1 : '') : $dateinvoice); } } else { // For compatibility @@ -2638,7 +2638,7 @@ if ($action == 'create') $element = $subelement = 'expedition'; } - dol_include_once('/' . $element . '/class/' . $subelement . '.class.php'); + dol_include_once('/'.$element.'/class/'.$subelement.'.class.php'); $classname = ucfirst($subelement); $objectsrc = new $classname($db); @@ -2647,18 +2647,18 @@ if ($action == 'create') $objectsrc->fetch_lines(); $objectsrc->fetch_thirdparty(); - $projectid = (! empty($projectid) ? $projectid : $objectsrc->fk_project); - $ref_client = (! empty($objectsrc->ref_client) ? $objectsrc->ref_client : (! empty($objectsrc->ref_customer) ? $objectsrc->ref_customer:'')); - $ref_int = (! empty($objectsrc->ref_int) ? $objectsrc->ref_int : ''); + $projectid = (!empty($projectid) ? $projectid : $objectsrc->fk_project); + $ref_client = (!empty($objectsrc->ref_client) ? $objectsrc->ref_client : (!empty($objectsrc->ref_customer) ? $objectsrc->ref_customer : '')); + $ref_int = (!empty($objectsrc->ref_int) ? $objectsrc->ref_int : ''); // only if socid not filled else it's allready done upper if (empty($socid)) $soc = $objectsrc->thirdparty; - $dateinvoice = (empty($dateinvoice)?(empty($conf->global->MAIN_AUTOFILL_DATE)?-1:''):$dateinvoice); + $dateinvoice = (empty($dateinvoice) ? (empty($conf->global->MAIN_AUTOFILL_DATE) ?-1 : '') : $dateinvoice); if ($element == 'expedition') { - $ref_client = (! empty($objectsrc->ref_customer)?$objectsrc->ref_customer:''); + $ref_client = (!empty($objectsrc->ref_customer) ? $objectsrc->ref_customer : ''); $elem = $subelem = $objectsrc->origin; $expeoriginid = $objectsrc->origin_id; @@ -2668,23 +2668,23 @@ if ($action == 'create') $expesrc = new $classname($db); $expesrc->fetch($expeoriginid); - $cond_reglement_id = (! empty($expesrc->cond_reglement_id)?$expesrc->cond_reglement_id:(! empty($soc->cond_reglement_id)?$soc->cond_reglement_id:1)); - $mode_reglement_id = (! empty($expesrc->mode_reglement_id)?$expesrc->mode_reglement_id:(! empty($soc->mode_reglement_id)?$soc->mode_reglement_id:0)); - $fk_account = (! empty($expesrc->fk_account)?$expesrc->fk_account:(! empty($soc->fk_account)?$soc->fk_account:0)); - $remise_percent = (! empty($expesrc->remise_percent)?$expesrc->remise_percent:(! empty($soc->remise_percent)?$soc->remise_percent:0)); - $remise_absolue = (! empty($expesrc->remise_absolue)?$expesrc->remise_absolue:(! empty($soc->remise_absolue)?$soc->remise_absolue:0)); + $cond_reglement_id = (!empty($expesrc->cond_reglement_id) ? $expesrc->cond_reglement_id : (!empty($soc->cond_reglement_id) ? $soc->cond_reglement_id : 1)); + $mode_reglement_id = (!empty($expesrc->mode_reglement_id) ? $expesrc->mode_reglement_id : (!empty($soc->mode_reglement_id) ? $soc->mode_reglement_id : 0)); + $fk_account = (!empty($expesrc->fk_account) ? $expesrc->fk_account : (!empty($soc->fk_account) ? $soc->fk_account : 0)); + $remise_percent = (!empty($expesrc->remise_percent) ? $expesrc->remise_percent : (!empty($soc->remise_percent) ? $soc->remise_percent : 0)); + $remise_absolue = (!empty($expesrc->remise_absolue) ? $expesrc->remise_absolue : (!empty($soc->remise_absolue) ? $soc->remise_absolue : 0)); //Replicate extrafields $expesrc->fetch_optionals($expeoriginid); - $object->array_options=$expesrc->array_options; + $object->array_options = $expesrc->array_options; } else { - $cond_reglement_id = (! empty($objectsrc->cond_reglement_id)?$objectsrc->cond_reglement_id:(! empty($soc->cond_reglement_id)?$soc->cond_reglement_id:0)); - $mode_reglement_id = (! empty($objectsrc->mode_reglement_id)?$objectsrc->mode_reglement_id:(! empty($soc->mode_reglement_id)?$soc->mode_reglement_id:0)); - $fk_account = (! empty($objectsrc->fk_account)?$objectsrc->fk_account:(! empty($soc->fk_account)?$soc->fk_account:0)); - $remise_percent = (! empty($objectsrc->remise_percent)?$objectsrc->remise_percent:(! empty($soc->remise_percent)?$soc->remise_percent:0)); - $remise_absolue = (! empty($objectsrc->remise_absolue)?$objectsrc->remise_absolue:(! empty($soc->remise_absolue)?$soc->remise_absolue:0)); + $cond_reglement_id = (!empty($objectsrc->cond_reglement_id) ? $objectsrc->cond_reglement_id : (!empty($soc->cond_reglement_id) ? $soc->cond_reglement_id : 0)); + $mode_reglement_id = (!empty($objectsrc->mode_reglement_id) ? $objectsrc->mode_reglement_id : (!empty($soc->mode_reglement_id) ? $soc->mode_reglement_id : 0)); + $fk_account = (!empty($objectsrc->fk_account) ? $objectsrc->fk_account : (!empty($soc->fk_account) ? $soc->fk_account : 0)); + $remise_percent = (!empty($objectsrc->remise_percent) ? $objectsrc->remise_percent : (!empty($soc->remise_percent) ? $soc->remise_percent : 0)); + $remise_absolue = (!empty($objectsrc->remise_absolue) ? $objectsrc->remise_absolue : (!empty($soc->remise_absolue) ? $soc->remise_absolue : 0)); if (!empty($conf->multicurrency->enabled)) { @@ -2705,18 +2705,18 @@ if ($action == 'create') $fk_account = $soc->fk_account; $remise_percent = $soc->remise_percent; $remise_absolue = 0; - $dateinvoice = (empty($dateinvoice)?(empty($conf->global->MAIN_AUTOFILL_DATE)?-1:''):$dateinvoice); // Do not set 0 here (0 for a date is 1970) + $dateinvoice = (empty($dateinvoice) ? (empty($conf->global->MAIN_AUTOFILL_DATE) ?-1 : '') : $dateinvoice); // Do not set 0 here (0 for a date is 1970) if (!empty($conf->multicurrency->enabled) && !empty($soc->multicurrency_code)) $currency_code = $soc->multicurrency_code; } if (!empty($soc->id)) $absolute_discount = $soc->getAvailableDiscounts(); - $note_public = $object->getDefaultCreateValueFor('note_public', ((! empty($origin) && ! empty($originid) && is_object($objectsrc) && !empty($conf->global->FACTURE_REUSE_NOTES_ON_CREATE_FROM))?$objectsrc->note_public:null)); - $note_private = $object->getDefaultCreateValueFor('note_private', ((! empty($origin) && ! empty($originid) && is_object($objectsrc) && !empty($conf->global->FACTURE_REUSE_NOTES_ON_CREATE_FROM))?$objectsrc->note_private:null)); + $note_public = $object->getDefaultCreateValueFor('note_public', ((!empty($origin) && !empty($originid) && is_object($objectsrc) && !empty($conf->global->FACTURE_REUSE_NOTES_ON_CREATE_FROM)) ? $objectsrc->note_public : null)); + $note_private = $object->getDefaultCreateValueFor('note_private', ((!empty($origin) && !empty($originid) && is_object($objectsrc) && !empty($conf->global->FACTURE_REUSE_NOTES_ON_CREATE_FROM)) ? $objectsrc->note_private : null)); - if (! empty($conf->use_javascript_ajax)) + if (!empty($conf->use_javascript_ajax)) { - require_once DOL_DOCUMENT_ROOT . '/core/lib/ajax.lib.php'; + require_once DOL_DOCUMENT_ROOT.'/core/lib/ajax.lib.php'; print ajax_combobox('fac_replacement'); print ajax_combobox('fac_avoir'); print ajax_combobox('situations'); @@ -2725,35 +2725,35 @@ if ($action == 'create') if ($origin == 'contrat') { $langs->load("admin"); - $text=$langs->trans("ToCreateARecurringInvoice"); - $text.=' '.$langs->trans("ToCreateARecurringInvoiceGene", $langs->transnoentitiesnoconv("MenuFinancial"), $langs->transnoentitiesnoconv("BillsCustomers"), $langs->transnoentitiesnoconv("ListOfTemplates")); + $text = $langs->trans("ToCreateARecurringInvoice"); + $text .= ' '.$langs->trans("ToCreateARecurringInvoiceGene", $langs->transnoentitiesnoconv("MenuFinancial"), $langs->transnoentitiesnoconv("BillsCustomers"), $langs->transnoentitiesnoconv("ListOfTemplates")); if (empty($conf->global->INVOICE_DISABLE_AUTOMATIC_RECURRING_INVOICE)) { - $text.=' '.$langs->trans("ToCreateARecurringInvoiceGeneAuto", $langs->transnoentitiesnoconv('Module2300Name')); + $text .= ' '.$langs->trans("ToCreateARecurringInvoiceGeneAuto", $langs->transnoentitiesnoconv('Module2300Name')); } print info_admin($text, 0, 0, 0).'
'; } - print ''; - print ''; + print ''; + print ''; print ''; - if ($soc->id > 0) print '' . "\n"; + if ($soc->id > 0) print ''."\n"; print ''; - print ''; - print ''; - print ''; - print ''; - print ''; - if (!empty($currency_tx)) print ''; + print ''; + print ''; + print ''; + print ''; + print ''; + if (!empty($currency_tx)) print ''; dol_fiche_head(''); - print '
'; + print '
'; // Ref - print ''; + print ''; - $exampletemplateinvoice=new FactureRec($db); + $exampletemplateinvoice = new FactureRec($db); $invoice_predefined = new FactureRec($db); if (empty($origin) && empty($originid) && GETPOST('fac_rec', 'int') > 0) { @@ -2761,30 +2761,30 @@ if ($action == 'create') } // Thirdparty - if ($soc->id > 0 && (! GETPOST('fac_rec', 'int') || ! empty($invoice_predefined->frequency))) + if ($soc->id > 0 && (!GETPOST('fac_rec', 'int') || !empty($invoice_predefined->frequency))) { // If thirdparty known and not a predefined invoiced without a recurring rule - print ''; + print ''; print ''; - print '' . "\n"; + print ''."\n"; } else { - print ''; + print ''; print ''; - print '' . "\n"; + print ''."\n"; } // Overwrite some values if creation of invoice is from a predefined invoice @@ -2811,7 +2811,7 @@ if ($action == 'create') { $invoice_predefined->fetch(GETPOST('fac_rec', 'int')); - $dateinvoice = $invoice_predefined->date_when; // To use next gen date by default later + $dateinvoice = $invoice_predefined->date_when; // To use next gen date by default later if (empty($projectid)) $projectid = $invoice_predefined->fk_project; $cond_reglement_id = $invoice_predefined->cond_reglement_id; $mode_reglement_id = $invoice_predefined->mode_reglement_id; @@ -2819,12 +2819,12 @@ if ($action == 'create') $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'; - $sql .= ' WHERE r.fk_soc = ' . $invoice_predefined->socid; + $sql .= ' FROM '.MAIN_DB_PREFIX.'facture_rec as r'; + $sql .= ' WHERE r.fk_soc = '.$invoice_predefined->socid; $resql = $db->query($sql); if ($resql) @@ -2834,21 +2834,21 @@ if ($action == 'create') if ($num > 0) { - print '\n"; foreach ($this->lines as $line) @@ -4124,18 +4129,18 @@ abstract class CommonObject { if (empty($line->fk_parent_line)) { - $parameters = array('line'=>$line,'var'=>$var,'num'=>$num,'i'=>$i,'dateSelector'=>$dateSelector,'seller'=>$seller,'buyer'=>$buyer,'selected'=>$selected, 'table_element_line'=>$line->table_element); - $reshook = $hookmanager->executeHooks('printObjectLine', $parameters, $this, $action); // Note that $action and $object may have been modified by some hooks + $parameters = array('line'=>$line, 'num'=>$num, 'i'=>$i, 'dateSelector'=>$dateSelector, 'seller'=>$seller, 'buyer'=>$buyer, 'selected'=>$selected, 'table_element_line'=>$line->table_element); + $reshook = $hookmanager->executeHooks('printObjectLine', $parameters, $this, $action); // Note that $action and $object may have been modified by some hooks } else { - $parameters = array('line'=>$line,'var'=>$var,'num'=>$num,'i'=>$i,'dateSelector'=>$dateSelector,'seller'=>$seller,'buyer'=>$buyer,'selected'=>$selected, 'table_element_line'=>$line->table_element, 'fk_parent_line'=>$line->fk_parent_line); - $reshook = $hookmanager->executeHooks('printObjectSubLine', $parameters, $this, $action); // Note that $action and $object may have been modified by some hooks + $parameters = array('line'=>$line, 'num'=>$num, 'i'=>$i, 'dateSelector'=>$dateSelector, 'seller'=>$seller, 'buyer'=>$buyer, 'selected'=>$selected, 'table_element_line'=>$line->table_element, 'fk_parent_line'=>$line->fk_parent_line); + $reshook = $hookmanager->executeHooks('printObjectSubLine', $parameters, $this, $action); // Note that $action and $object may have been modified by some hooks } } if (empty($reshook)) { - $this->printObjectLine($action, $line, $var, $num, $i, $dateSelector, $seller, $buyer, $selected, $extrafields, $defaulttpldir); + $this->printObjectLine($action, $line, '', $num, $i, $dateSelector, $seller, $buyer, $selected, $extrafields, $defaulttpldir); } $i++; @@ -4147,36 +4152,36 @@ abstract class CommonObject * Return HTML content of a detail line * TODO Move this into an output class file (htmlline.class.php) * - * @param string $action GET/POST action - * @param CommonObjectLine $line Selected object line to output - * @param string $var Is it a an odd line (true) - * @param int $num Number of line (0) - * @param int $i I - * @param int $dateSelector 1=Show also date range input fields - * @param string $seller Object of seller third party - * @param string $buyer Object of buyer third party - * @param int $selected Object line selected - * @param Extrafields $extrafields Object of extrafields - * @param string $defaulttpldir Directory where to find the template + * @param string $action GET/POST action + * @param CommonObjectLine $line Selected object line to output + * @param string $var Is it a an odd line (true) + * @param int $num Number of line (0) + * @param int $i I + * @param int $dateSelector 1=Show also date range input fields + * @param string $seller Object of seller third party + * @param string $buyer Object of buyer third party + * @param int $selected Object line selected + * @param Extrafields $extrafields Object of extrafields + * @param string $defaulttpldir Directory where to find the template * @return void */ public function printObjectLine($action, $line, $var, $num, $i, $dateSelector, $seller, $buyer, $selected = 0, $extrafields = null, $defaulttpldir = '/core/tpl') { - global $conf,$langs,$user,$object,$hookmanager; - global $form,$bc,$bcdd; - global $object_rights, $disableedit, $disablemove, $disableremove; // TODO We should not use global var for this ! + global $conf, $langs, $user, $object, $hookmanager; + global $form; + global $object_rights, $disableedit, $disablemove, $disableremove; // TODO We should not use global var for this ! $object_rights = $this->getRights(); - $element=$this->element; + $element = $this->element; - $text=''; $description=''; $type=0; + $text = ''; $description = ''; $type = 0; // Show product and description - $type=(! empty($line->product_type)?$line->product_type:$line->fk_product_type); + $type = (!empty($line->product_type) ? $line->product_type : $line->fk_product_type); // Try to enhance type detection using date_start and date_end for free lines where type was not saved. - if (! empty($line->date_start)) $type=1; // deprecated - if (! empty($line->date_end)) $type=1; // deprecated + if (!empty($line->date_start)) $type = 1; // deprecated + if (!empty($line->date_end)) $type = 1; // deprecated // Ligne en mode visu if ($action != 'editline' || $selected != $line->id) @@ -4189,12 +4194,12 @@ abstract class CommonObject $product_static->ref = $line->ref; //can change ref in hook $product_static->label = $line->label; //can change label in hook - $text=$product_static->getNomUrl(1); + $text = $product_static->getNomUrl(1); // Define output language and label - if (! empty($conf->global->MAIN_MULTILANGS)) + if (!empty($conf->global->MAIN_MULTILANGS)) { - if (property_exists($this, 'socid') && ! is_object($this->thirdparty)) + if (property_exists($this, 'socid') && !is_object($this->thirdparty)) { dol_print_error('', 'Error: Method printObjectLine was called on an object and object->fetch_thirdparty was not done before'); return; @@ -4204,32 +4209,32 @@ abstract class CommonObject $prod->fetch($line->fk_product); $outputlangs = $langs; - $newlang=''; - if (empty($newlang) && GETPOST('lang_id', 'aZ09')) $newlang=GETPOST('lang_id', 'aZ09'); - if (! empty($conf->global->PRODUIT_TEXTS_IN_THIRDPARTY_LANGUAGE) && empty($newlang) && is_object($this->thirdparty)) $newlang=$this->thirdparty->default_lang; // To use language of customer - if (! empty($newlang)) + $newlang = ''; + if (empty($newlang) && GETPOST('lang_id', 'aZ09')) $newlang = GETPOST('lang_id', 'aZ09'); + if (!empty($conf->global->PRODUIT_TEXTS_IN_THIRDPARTY_LANGUAGE) && empty($newlang) && is_object($this->thirdparty)) $newlang = $this->thirdparty->default_lang; // To use language of customer + if (!empty($newlang)) { $outputlangs = new Translate("", $conf); $outputlangs->setDefaultLang($newlang); } - $label = (! empty($prod->multilangs[$outputlangs->defaultlang]["label"])) ? $prod->multilangs[$outputlangs->defaultlang]["label"] : $line->product_label; + $label = (!empty($prod->multilangs[$outputlangs->defaultlang]["label"])) ? $prod->multilangs[$outputlangs->defaultlang]["label"] : $line->product_label; } else { $label = $line->product_label; } - $text.= ' - '.(! empty($line->label)?$line->label:$label); - $description.=(! empty($conf->global->PRODUIT_DESC_IN_FORM)?'':dol_htmlentitiesbr($line->description)); // Description is what to show on popup. We shown nothing if already into desc. + $text .= ' - '.(!empty($line->label) ? $line->label : $label); + $description .= (!empty($conf->global->PRODUIT_DESC_IN_FORM) ? '' : dol_htmlentitiesbr($line->description)); // Description is what to show on popup. We shown nothing if already into desc. } - $line->pu_ttc = price2num($line->subprice * (1 + ($line->tva_tx/100)), 'MU'); + $line->pu_ttc = price2num($line->subprice * (1 + ($line->tva_tx / 100)), 'MU'); // Output template part (modules that overwrite templates must declare this into descriptor) // Use global variables + $dateSelector + $seller and $buyer - $dirtpls=array_merge($conf->modules_parts['tpl'], array($defaulttpldir)); - foreach($dirtpls as $module => $reldir) + $dirtpls = array_merge($conf->modules_parts['tpl'], array($defaulttpldir)); + foreach ($dirtpls as $module => $reldir) { if (!empty($module)) { @@ -4241,9 +4246,9 @@ abstract class CommonObject } if (empty($conf->file->strict_mode)) { - $res=@include $tpl; + $res = @include $tpl; } else { - $res=include $tpl; // for debug + $res = include $tpl; // for debug } if ($res) break; } @@ -4252,15 +4257,15 @@ abstract class CommonObject // Line in update mode if ($this->statut == 0 && $action == 'editline' && $selected == $line->id) { - $label = (! empty($line->label) ? $line->label : (($line->fk_product > 0) ? $line->product_label : '')); - $placeholder=' placeholder="'.$langs->trans("Label").'"'; + $label = (!empty($line->label) ? $line->label : (($line->fk_product > 0) ? $line->product_label : '')); + $placeholder = ' placeholder="'.$langs->trans("Label").'"'; - $line->pu_ttc = price2num($line->subprice * (1 + ($line->tva_tx/100)), 'MU'); + $line->pu_ttc = price2num($line->subprice * (1 + ($line->tva_tx / 100)), 'MU'); // Output template part (modules that overwrite templates must declare this into descriptor) // Use global variables + $dateSelector + $seller and $buyer - $dirtpls=array_merge($conf->modules_parts['tpl'], array($defaulttpldir)); - foreach($dirtpls as $module => $reldir) + $dirtpls = array_merge($conf->modules_parts['tpl'], array($defaulttpldir)); + foreach ($dirtpls as $module => $reldir) { if (!empty($module)) { @@ -4272,9 +4277,9 @@ abstract class CommonObject } if (empty($conf->file->strict_mode)) { - $res=@include $tpl; + $res = @include $tpl; } else { - $res=include $tpl; // for debug + $res = include $tpl; // for debug } if ($res) break; } @@ -4306,32 +4311,31 @@ abstract class CommonObject print ''; if (!empty($conf->multicurrency->enabled)) print ''; print ''; - if($conf->global->PRODUCT_USE_UNITS) + if ($conf->global->PRODUCT_USE_UNITS) { print ''; } print ''; print ''; print ''; - $var = true; - $i = 0; + $i = 0; - if (! empty($this->lines)) + if (!empty($this->lines)) { foreach ($this->lines as $line) { - if (is_object($hookmanager) && (($line->product_type == 9 && ! empty($line->special_code)) || ! empty($line->fk_parent_line))) + if (is_object($hookmanager) && (($line->product_type == 9 && !empty($line->special_code)) || !empty($line->fk_parent_line))) { if (empty($line->fk_parent_line)) { - $parameters=array('line'=>$line,'var'=>$var,'i'=>$i); - $action=''; - $hookmanager->executeHooks('printOriginObjectLine', $parameters, $this, $action); // Note that $action and $object may have been modified by some hooks + $parameters = array('line'=>$line, 'i'=>$i); + $action = ''; + $hookmanager->executeHooks('printOriginObjectLine', $parameters, $this, $action); // Note that $action and $object may have been modified by some hooks } } else { - $this->printOriginLine($line, $var, $restrictlist, '/core/tpl', $selectedLines); + $this->printOriginLine($line, '', $restrictlist, '/core/tpl', $selectedLines); } $i++; @@ -4359,35 +4363,35 @@ abstract class CommonObject //var_dump($line); if (!empty($line->date_start)) { - $date_start=$line->date_start; + $date_start = $line->date_start; } else { - $date_start=$line->date_debut_prevue; - if ($line->date_debut_reel) $date_start=$line->date_debut_reel; + $date_start = $line->date_debut_prevue; + if ($line->date_debut_reel) $date_start = $line->date_debut_reel; } if (!empty($line->date_end)) { - $date_end=$line->date_end; + $date_end = $line->date_end; } else { - $date_end=$line->date_fin_prevue; - if ($line->date_fin_reel) $date_end=$line->date_fin_reel; + $date_end = $line->date_fin_prevue; + if ($line->date_fin_reel) $date_end = $line->date_fin_reel; } $this->tpl['id'] = $line->id; $this->tpl['label'] = ''; - if (! empty($line->fk_parent_line)) $this->tpl['label'].= img_picto('', 'rightarrow'); + if (!empty($line->fk_parent_line)) $this->tpl['label'] .= img_picto('', 'rightarrow'); if (($line->info_bits & 2) == 2) // TODO Not sure this is used for source object { - $discount=new DiscountAbsolute($this->db); + $discount = new DiscountAbsolute($this->db); $discount->fk_soc = $this->socid; - $this->tpl['label'].= $discount->getNomUrl(0, 'discount'); + $this->tpl['label'] .= $discount->getNomUrl(0, 'discount'); } - elseif (! empty($line->fk_product)) + elseif (!empty($line->fk_product)) { $productstatic = new Product($this->db); $productstatic->id = $line->fk_product; @@ -4398,53 +4402,53 @@ abstract class CommonObject $productstatic = $line->product; } - $this->tpl['label'].= $productstatic->getNomUrl(1); - $this->tpl['label'].= ' - '.(! empty($line->label)?$line->label:$line->product_label); + $this->tpl['label'] .= $productstatic->getNomUrl(1); + $this->tpl['label'] .= ' - '.(!empty($line->label) ? $line->label : $line->product_label); // Dates if ($line->product_type == 1 && ($date_start || $date_end)) { - $this->tpl['label'].= get_date_range($date_start, $date_end); + $this->tpl['label'] .= get_date_range($date_start, $date_end); } } else { - $this->tpl['label'].= ($line->product_type == -1 ? ' ' : ($line->product_type == 1 ? img_object($langs->trans(''), 'service') : img_object($langs->trans(''), 'product'))); + $this->tpl['label'] .= ($line->product_type == -1 ? ' ' : ($line->product_type == 1 ? img_object($langs->trans(''), 'service') : img_object($langs->trans(''), 'product'))); if (!empty($line->desc)) { - $this->tpl['label'].=$line->desc; - }else { - $this->tpl['label'].= ($line->label ? ' '.$line->label : ''); + $this->tpl['label'] .= $line->desc; + } else { + $this->tpl['label'] .= ($line->label ? ' '.$line->label : ''); } // Dates if ($line->product_type == 1 && ($date_start || $date_end)) { - $this->tpl['label'].= get_date_range($date_start, $date_end); + $this->tpl['label'] .= get_date_range($date_start, $date_end); } } - if (! empty($line->desc)) + if (!empty($line->desc)) { if ($line->desc == '(CREDIT_NOTE)') // TODO Not sure this is used for source object { - $discount=new DiscountAbsolute($this->db); + $discount = new DiscountAbsolute($this->db); $discount->fetch($line->fk_remise_except); $this->tpl['description'] = $langs->transnoentities("DiscountFromCreditNote", $discount->getNomUrl(0)); } elseif ($line->desc == '(DEPOSIT)') // TODO Not sure this is used for source object { - $discount=new DiscountAbsolute($this->db); + $discount = new DiscountAbsolute($this->db); $discount->fetch($line->fk_remise_except); $this->tpl['description'] = $langs->transnoentities("DiscountFromDeposit", $discount->getNomUrl(0)); } elseif ($line->desc == '(EXCESS RECEIVED)') { - $discount=new DiscountAbsolute($this->db); + $discount = new DiscountAbsolute($this->db); $discount->fetch($line->fk_remise_except); $this->tpl['description'] = $langs->transnoentities("DiscountFromExcessReceived", $discount->getNomUrl(0)); } elseif ($line->desc == '(EXCESS PAID)') { - $discount=new DiscountAbsolute($this->db); + $discount = new DiscountAbsolute($this->db); $discount->fetch($line->fk_remise_except); $this->tpl['description'] = $langs->transnoentities("DiscountFromExcessPaid", $discount->getNomUrl(0)); } @@ -4461,7 +4465,7 @@ abstract class CommonObject // VAT Rate $this->tpl['vat_rate'] = vatrate($line->tva_tx, true); $this->tpl['vat_rate'] .= (($line->info_bits & 1) == 1) ? '*' : ''; - if (! empty($line->vat_src_code) && ! preg_match('/\(/', $this->tpl['vat_rate'])) $this->tpl['vat_rate'].=' ('.$line->vat_src_code.')'; + if (!empty($line->vat_src_code) && !preg_match('/\(/', $this->tpl['vat_rate'])) $this->tpl['vat_rate'] .= ' ('.$line->vat_src_code.')'; $this->tpl['price'] = price($line->subprice); $this->tpl['multicurrency_price'] = price($line->multicurrency_subprice); @@ -4470,13 +4474,13 @@ abstract class CommonObject $this->tpl['remise_percent'] = (($line->info_bits & 2) != 2) ? vatrate($line->remise_percent, true) : ' '; // Is the line strike or not - $this->tpl['strike']=0; - if ($restrictlist == 'services' && $line->product_type != Product::TYPE_SERVICE) $this->tpl['strike']=1; + $this->tpl['strike'] = 0; + if ($restrictlist == 'services' && $line->product_type != Product::TYPE_SERVICE) $this->tpl['strike'] = 1; // Output template part (modules that overwrite templates must declare this into descriptor) // Use global variables + $dateSelector + $seller and $buyer - $dirtpls=array_merge($conf->modules_parts['tpl'], array($defaulttpldir)); - foreach($dirtpls as $module => $reldir) + $dirtpls = array_merge($conf->modules_parts['tpl'], array($defaulttpldir)); + foreach ($dirtpls as $module => $reldir) { if (!empty($module)) { @@ -4488,9 +4492,9 @@ abstract class CommonObject } if (empty($conf->file->strict_mode)) { - $res=@include $tpl; + $res = @include $tpl; } else { - $res=include $tpl; // for debug + $res = include $tpl; // for debug } if ($res) break; } @@ -4514,20 +4518,20 @@ abstract class CommonObject $this->db->begin(); $sql = "INSERT INTO ".MAIN_DB_PREFIX."element_resources ("; - $sql.= "resource_id"; - $sql.= ", resource_type"; - $sql.= ", element_id"; - $sql.= ", element_type"; - $sql.= ", busy"; - $sql.= ", mandatory"; - $sql.= ") VALUES ("; - $sql.= $resource_id; - $sql.= ", '".$this->db->escape($resource_type)."'"; - $sql.= ", '".$this->db->escape($this->id)."'"; - $sql.= ", '".$this->db->escape($this->element)."'"; - $sql.= ", '".$this->db->escape($busy)."'"; - $sql.= ", '".$this->db->escape($mandatory)."'"; - $sql.= ")"; + $sql .= "resource_id"; + $sql .= ", resource_type"; + $sql .= ", element_id"; + $sql .= ", element_type"; + $sql .= ", busy"; + $sql .= ", mandatory"; + $sql .= ") VALUES ("; + $sql .= $resource_id; + $sql .= ", '".$this->db->escape($resource_type)."'"; + $sql .= ", '".$this->db->escape($this->id)."'"; + $sql .= ", '".$this->db->escape($this->element)."'"; + $sql .= ", '".$this->db->escape($busy)."'"; + $sql .= ", '".$this->db->escape($mandatory)."'"; + $sql .= ")"; dol_syslog(get_class($this)."::add_element_resource", LOG_DEBUG); if ($this->db->query($sql)) @@ -4537,7 +4541,7 @@ abstract class CommonObject } else { - $this->error=$this->db->lasterror(); + $this->error = $this->db->lasterror(); $this->db->rollback(); return 0; } @@ -4560,22 +4564,22 @@ abstract class CommonObject $this->db->begin(); $sql = "DELETE FROM ".MAIN_DB_PREFIX."element_resources"; - $sql.= " WHERE rowid=".$rowid; + $sql .= " WHERE rowid=".$rowid; dol_syslog(get_class($this)."::delete_resource", LOG_DEBUG); - $resql=$this->db->query($sql); - if (! $resql) + $resql = $this->db->query($sql); + if (!$resql) { - $this->error=$this->db->lasterror(); + $this->error = $this->db->lasterror(); $this->db->rollback(); return -1; } else { - if (! $notrigger) + if (!$notrigger) { - $result=$this->call_trigger(strtoupper($element).'_DELETE_RESOURCE', $user); + $result = $this->call_trigger(strtoupper($element).'_DELETE_RESOURCE', $user); if ($result < 0) { $this->db->rollback(); return -1; } } $this->db->commit(); @@ -4594,8 +4598,8 @@ abstract class CommonObject // Force a copy of this->lines, otherwise it will point to same object. if (isset($this->lines) && is_array($this->lines)) { - $nboflines=count($this->lines); - for($i=0; $i < $nboflines; $i++) + $nboflines = count($this->lines); + for ($i = 0; $i < $nboflines; $i++) { $this->lines[$i] = clone $this->lines[$i]; } @@ -4619,48 +4623,48 @@ abstract class CommonObject { global $conf, $langs, $user, $hookmanager, $action; - $srctemplatepath=''; + $srctemplatepath = ''; - $parameters = array('modelspath'=>$modelspath,'modele'=>$modele,'outputlangs'=>$outputlangs,'hidedetails'=>$hidedetails,'hidedesc'=>$hidedesc,'hideref'=>$hideref, 'moreparams'=>$moreparams); + $parameters = array('modelspath'=>$modelspath, 'modele'=>$modele, 'outputlangs'=>$outputlangs, 'hidedetails'=>$hidedetails, 'hidedesc'=>$hidedesc, 'hideref'=>$hideref, 'moreparams'=>$moreparams); $reshook = $hookmanager->executeHooks('commonGenerateDocument', $parameters, $this, $action); // Note that $action and $object may have been modified by some hooks if (empty($reshook)) { - dol_syslog("commonGenerateDocument modele=".$modele." outputlangs->defaultlang=".(is_object($outputlangs)?$outputlangs->defaultlang:'null')); + dol_syslog("commonGenerateDocument modele=".$modele." outputlangs->defaultlang=".(is_object($outputlangs) ? $outputlangs->defaultlang : 'null')); // Increase limit for PDF build - $err=error_reporting(); + $err = error_reporting(); error_reporting(0); @set_time_limit(120); error_reporting($err); // If selected model is a filename template (then $modele="modelname" or "modelname:filename") - $tmp=explode(':', $modele, 2); - if (! empty($tmp[1])) + $tmp = explode(':', $modele, 2); + if (!empty($tmp[1])) { - $modele=$tmp[0]; - $srctemplatepath=$tmp[1]; + $modele = $tmp[0]; + $srctemplatepath = $tmp[1]; } // Search template files - $file=''; - $classname=''; - $filefound=0; - $dirmodels=array('/'); - if (is_array($conf->modules_parts['models'])) $dirmodels=array_merge($dirmodels, $conf->modules_parts['models']); - foreach($dirmodels as $reldir) + $file = ''; + $classname = ''; + $filefound = 0; + $dirmodels = array('/'); + if (is_array($conf->modules_parts['models'])) $dirmodels = array_merge($dirmodels, $conf->modules_parts['models']); + foreach ($dirmodels as $reldir) { - foreach(array('doc','pdf') as $prefix) + foreach (array('doc', 'pdf') as $prefix) { - if (in_array(get_class($this), array('Adherent'))) $file = $prefix."_".$modele.".class.php"; // Member module use prefix_module.class.php + if (in_array(get_class($this), array('Adherent'))) $file = $prefix."_".$modele.".class.php"; // Member module use prefix_module.class.php else $file = $prefix."_".$modele.".modules.php"; // On verifie l'emplacement du modele - $file=dol_buildpath($reldir.$modelspath.$file, 0); + $file = dol_buildpath($reldir.$modelspath.$file, 0); if (file_exists($file)) { - $filefound=1; - $classname=$prefix.'_'.$modele; + $filefound = 1; + $classname = $prefix.'_'.$modele; break; } } @@ -4670,7 +4674,7 @@ abstract class CommonObject // If generator was found if ($filefound) { - global $db; // Required to solve a conception default making an include of code using $db instead of $this->db just after. + global $db; // Required to solve a conception default making an include of code using $db instead of $this->db just after. require_once $file; @@ -4679,32 +4683,32 @@ abstract class CommonObject // If generator is ODT, we must have srctemplatepath defined, if not we set it. if ($obj->type == 'odt' && empty($srctemplatepath)) { - $varfortemplatedir=$obj->scandir; - if ($varfortemplatedir && ! empty($conf->global->$varfortemplatedir)) + $varfortemplatedir = $obj->scandir; + if ($varfortemplatedir && !empty($conf->global->$varfortemplatedir)) { - $dirtoscan=$conf->global->$varfortemplatedir; + $dirtoscan = $conf->global->$varfortemplatedir; - $listoffiles=array(); + $listoffiles = array(); // Now we add first model found in directories scanned - $listofdir=explode(',', $dirtoscan); - foreach($listofdir as $key => $tmpdir) + $listofdir = explode(',', $dirtoscan); + foreach ($listofdir as $key => $tmpdir) { - $tmpdir=trim($tmpdir); - $tmpdir=preg_replace('/DOL_DATA_ROOT/', DOL_DATA_ROOT, $tmpdir); - if (! $tmpdir) { unset($listofdir[$key]); continue; } + $tmpdir = trim($tmpdir); + $tmpdir = preg_replace('/DOL_DATA_ROOT/', DOL_DATA_ROOT, $tmpdir); + if (!$tmpdir) { unset($listofdir[$key]); continue; } if (is_dir($tmpdir)) { - $tmpfiles=dol_dir_list($tmpdir, 'files', 0, '\.od(s|t)$', '', 'name', SORT_ASC, 0); - if (count($tmpfiles)) $listoffiles=array_merge($listoffiles, $tmpfiles); + $tmpfiles = dol_dir_list($tmpdir, 'files', 0, '\.od(s|t)$', '', 'name', SORT_ASC, 0); + if (count($tmpfiles)) $listoffiles = array_merge($listoffiles, $tmpfiles); } } if (count($listoffiles)) { - foreach($listoffiles as $record) + foreach ($listoffiles as $record) { - $srctemplatepath=$record['fullname']; + $srctemplatepath = $record['fullname']; break; } } @@ -4712,27 +4716,27 @@ abstract class CommonObject if (empty($srctemplatepath)) { - $this->error='ErrorGenerationAskedForOdtTemplateWithSrcFileNotDefined'; + $this->error = 'ErrorGenerationAskedForOdtTemplateWithSrcFileNotDefined'; return -1; } } - if ($obj->type == 'odt' && ! empty($srctemplatepath)) + if ($obj->type == 'odt' && !empty($srctemplatepath)) { - if (! dol_is_file($srctemplatepath)) + if (!dol_is_file($srctemplatepath)) { - $this->error='ErrorGenerationAskedForOdtTemplateWithSrcFileNotFound'; + $this->error = 'ErrorGenerationAskedForOdtTemplateWithSrcFileNotFound'; return -1; } } // We save charset_output to restore it because write_file can change it if needed for // output format that does not support UTF8. - $sav_charset_output=$outputlangs->charset_output; + $sav_charset_output = $outputlangs->charset_output; if (in_array(get_class($this), array('Adherent'))) { - $arrayofrecords = array(); // The write_file of templates of adherent class need this var + $arrayofrecords = array(); // The write_file of templates of adherent class need this var $resultwritefile = $obj->write_file($this, $outputlangs, $srctemplatepath, 'member', 1, $moreparams); } else @@ -4743,46 +4747,46 @@ abstract class CommonObject if ($resultwritefile > 0) { - $outputlangs->charset_output=$sav_charset_output; + $outputlangs->charset_output = $sav_charset_output; // We delete old preview require_once DOL_DOCUMENT_ROOT.'/core/lib/files.lib.php'; dol_delete_preview($this); // Index file in database - if (! empty($obj->result['fullpath'])) + if (!empty($obj->result['fullpath'])) { $destfull = $obj->result['fullpath']; $upload_dir = dirname($destfull); $destfile = basename($destfull); $rel_dir = preg_replace('/^'.preg_quote(DOL_DATA_ROOT, '/').'/', '', $upload_dir); - if (! preg_match('/[\\/]temp[\\/]|[\\/]thumbs|\.meta$/', $rel_dir)) // If not a tmp dir + if (!preg_match('/[\\/]temp[\\/]|[\\/]thumbs|\.meta$/', $rel_dir)) // If not a tmp dir { $filename = basename($destfile); $rel_dir = preg_replace('/[\\/]$/', '', $rel_dir); $rel_dir = preg_replace('/^[\\/]/', '', $rel_dir); include_once DOL_DOCUMENT_ROOT.'/ecm/class/ecmfiles.class.php'; - $ecmfile=new EcmFiles($this->db); - $result = $ecmfile->fetch(0, '', ($rel_dir?$rel_dir.'/':'').$filename); + $ecmfile = new EcmFiles($this->db); + $result = $ecmfile->fetch(0, '', ($rel_dir ? $rel_dir.'/' : '').$filename); // Set the public "share" key $setsharekey = false; if ($this->element == 'propal') { - $useonlinesignature = $conf->global->MAIN_FEATURES_LEVEL; // Replace this with 1 when feature to make online signature is ok - if ($useonlinesignature) $setsharekey=true; - if (! empty($conf->global->PROPOSAL_ALLOW_EXTERNAL_DOWNLOAD)) $setsharekey=true; + $useonlinesignature = $conf->global->MAIN_FEATURES_LEVEL; // Replace this with 1 when feature to make online signature is ok + if ($useonlinesignature) $setsharekey = true; + if (!empty($conf->global->PROPOSAL_ALLOW_EXTERNAL_DOWNLOAD)) $setsharekey = true; } - if ($this->element == 'commande' && ! empty($conf->global->ORDER_ALLOW_EXTERNAL_DOWNLOAD)) { - $setsharekey=true; + if ($this->element == 'commande' && !empty($conf->global->ORDER_ALLOW_EXTERNAL_DOWNLOAD)) { + $setsharekey = true; } - if ($this->element == 'facture' && ! empty($conf->global->INVOICE_ALLOW_EXTERNAL_DOWNLOAD)) { - $setsharekey=true; + if ($this->element == 'facture' && !empty($conf->global->INVOICE_ALLOW_EXTERNAL_DOWNLOAD)) { + $setsharekey = true; } - if ($this->element == 'bank_account' && ! empty($conf->global->BANK_ACCOUNT_ALLOW_EXTERNAL_DOWNLOAD)) { - $setsharekey=true; + if ($this->element == 'bank_account' && !empty($conf->global->BANK_ACCOUNT_ALLOW_EXTERNAL_DOWNLOAD)) { + $setsharekey = true; } if ($setsharekey) { @@ -4795,11 +4799,11 @@ abstract class CommonObject if ($result > 0) { - $ecmfile->label = md5_file(dol_osencode($destfull)); // hash of file content + $ecmfile->label = md5_file(dol_osencode($destfull)); // hash of file content $ecmfile->fullpath_orig = ''; $ecmfile->gen_or_uploaded = 'generated'; - $ecmfile->description = ''; // indexed content - $ecmfile->keyword = ''; // keyword content + $ecmfile->description = ''; // indexed content + $ecmfile->keyword = ''; // keyword content $result = $ecmfile->update($user); if ($result < 0) { setEventMessages($ecmfile->error, $ecmfile->errors, 'warnings'); @@ -4810,11 +4814,11 @@ abstract class CommonObject $ecmfile->entity = $conf->entity; $ecmfile->filepath = $rel_dir; $ecmfile->filename = $filename; - $ecmfile->label = md5_file(dol_osencode($destfull)); // hash of file content + $ecmfile->label = md5_file(dol_osencode($destfull)); // hash of file content $ecmfile->fullpath_orig = ''; $ecmfile->gen_or_uploaded = 'generated'; - $ecmfile->description = ''; // indexed content - $ecmfile->keyword = ''; // keyword content + $ecmfile->description = ''; // indexed content + $ecmfile->keyword = ''; // keyword content $ecmfile->src_object_type = $this->table_element; $ecmfile->src_object_id = $this->id; @@ -4830,15 +4834,15 @@ abstract class CommonObject //var_dump($obj->update_main_doc_field);exit; // Update the last_main_doc field into main object (if documenent generator has property ->update_main_doc_field set) - $update_main_doc_field=0; - if (! empty($obj->update_main_doc_field)) $update_main_doc_field=1; - if ($update_main_doc_field && ! empty($this->table_element)) + $update_main_doc_field = 0; + if (!empty($obj->update_main_doc_field)) $update_main_doc_field = 1; + if ($update_main_doc_field && !empty($this->table_element)) { $sql = 'UPDATE '.MAIN_DB_PREFIX.$this->table_element." SET last_main_doc = '".$this->db->escape($ecmfile->filepath.'/'.$ecmfile->filename)."'"; - $sql.= ' WHERE rowid = '.$this->id; + $sql .= ' WHERE rowid = '.$this->id; $resql = $this->db->query($sql); - if (! $resql) { + if (!$resql) { dol_print_error($this->db); } else { $this->last_main_doc = $ecmfile->filepath.'/'.$ecmfile->filename; @@ -4858,14 +4862,14 @@ abstract class CommonObject } else { - $outputlangs->charset_output=$sav_charset_output; + $outputlangs->charset_output = $sav_charset_output; dol_print_error($this->db, "Error generating document for ".__CLASS__.". Error: ".$obj->error, $obj->errors); return -1; } } else { - $this->error=$langs->trans("Error")." ".$langs->trans("ErrorFileDoesNotExists", $file); + $this->error = $langs->trans("Error")." ".$langs->trans("ErrorFileDoesNotExists", $file); dol_print_error('', $this->error); return -1; } @@ -4884,9 +4888,9 @@ abstract class CommonObject { global $maxwidthsmall, $maxheightsmall, $maxwidthmini, $maxheightmini, $quality; - require_once DOL_DOCUMENT_ROOT .'/core/lib/images.lib.php'; // This define also $maxwidthsmall, $quality, ... + require_once DOL_DOCUMENT_ROOT.'/core/lib/images.lib.php'; // This define also $maxwidthsmall, $quality, ... - $file_osencoded=dol_osencode($file); + $file_osencoded = dol_osencode($file); if (file_exists($file_osencoded)) { // Create small thumbs for company (Ratio is near 16/9) @@ -4925,16 +4929,16 @@ abstract class CommonObject if (isset($alternatevalue)) return $alternatevalue; - $newelement=$this->element; - if ($newelement == 'facture') $newelement='invoice'; - if ($newelement == 'commande') $newelement='order'; + $newelement = $this->element; + if ($newelement == 'facture') $newelement = 'invoice'; + if ($newelement == 'commande') $newelement = 'order'; if (empty($newelement)) { dol_syslog("Ask a default value using common method getDefaultCreateValueForField on an object with no property ->element defined. Return empty string.", LOG_WARNING); return ''; } - $keyforfieldname=strtoupper($newelement.'_DEFAULT_'.$fieldname); + $keyforfieldname = strtoupper($newelement.'_DEFAULT_'.$fieldname); //var_dump($keyforfieldname); if (isset($conf->global->$keyforfieldname)) return $conf->global->$keyforfieldname; @@ -4959,21 +4963,26 @@ abstract class CommonObject public function call_trigger($trigger_name, $user) { // phpcs:enable - global $langs,$conf; + global $langs, $conf; - include_once DOL_DOCUMENT_ROOT . '/core/class/interfaces.class.php'; - $interface=new Interfaces($this->db); - $result=$interface->run_triggers($trigger_name, $this, $user, $langs, $conf); + if (!is_object($langs)) { // If lang was not defined, we set it. It is required by run_triggers. + include_once DOL_DOCUMENT_ROOT.'/core/class/translate.class.php'; + $langs = new Translate('', $conf); + } + + include_once DOL_DOCUMENT_ROOT.'/core/class/interfaces.class.php'; + $interface = new Interfaces($this->db); + $result = $interface->run_triggers($trigger_name, $this, $user, $langs, $conf); if ($result < 0) { if (!empty($this->errors)) { - $this->errors=array_unique(array_merge($this->errors, $interface->errors)); // We use array_unique because when a trigger call another trigger on same object, this->errors is added twice. + $this->errors = array_unique(array_merge($this->errors, $interface->errors)); // We use array_unique because when a trigger call another trigger on same object, this->errors is added twice. } else { - $this->errors=$interface->errors; + $this->errors = $interface->errors; } } return $result; @@ -4997,19 +5006,19 @@ abstract class CommonObject // phpcs:enable global $extrafields; - if (empty($rowid)) $rowid=$this->id; + if (empty($rowid)) $rowid = $this->id; // To avoid SQL errors. Probably not the better solution though if (!$this->table_element) { return 0; } - $this->array_options=array(); + $this->array_options = array(); - if (! is_array($optionsArray)) + if (!is_array($optionsArray)) { // If $extrafields is not a known object, we initialize it. Best practice is to have $extrafields defined into card.php or list.php page. - if (! isset($extrafields) || ! is_object($extrafields)) + if (!isset($extrafields) || !is_object($extrafields)) { require_once DOL_DOCUMENT_ROOT.'/core/class/extrafields.class.php'; $extrafields = new ExtraFields($this->db); @@ -5020,7 +5029,7 @@ abstract class CommonObject { $extrafields->fetch_name_optionals_label($this->table_element); } - $optionsArray = (! empty($extrafields->attributes[$this->table_element]['label'])?$extrafields->attributes[$this->table_element]['label']:null); + $optionsArray = (!empty($extrafields->attributes[$this->table_element]['label']) ? $extrafields->attributes[$this->table_element]['label'] : null); } else { @@ -5039,18 +5048,18 @@ abstract class CommonObject { if (empty($extrafields->attributes[$this->table_element]['type'][$name]) || $extrafields->attributes[$this->table_element]['type'][$name] != 'separate') { - $sql.= ", ".$name; + $sql .= ", ".$name; } } - $sql.= " FROM ".MAIN_DB_PREFIX.$table_element."_extrafields"; - $sql.= " WHERE fk_object = ".$rowid; + $sql .= " FROM ".MAIN_DB_PREFIX.$table_element."_extrafields"; + $sql .= " WHERE fk_object = ".$rowid; //dol_syslog(get_class($this)."::fetch_optionals get extrafields data for ".$this->table_element, LOG_DEBUG); // Too verbose - $resql=$this->db->query($sql); + $resql = $this->db->query($sql); if ($resql) { $this->array_options = array(); - $numrows=$this->db->num_rows($resql); + $numrows = $this->db->num_rows($resql); if ($numrows) { $tab = $this->db->fetch_array($resql); @@ -5058,17 +5067,17 @@ abstract class CommonObject foreach ($tab as $key => $value) { // Test fetch_array ! is_int($key) because fetch_array result is a mix table with Key as alpha and Key as int (depend db engine) - if ($key != 'rowid' && $key != 'tms' && $key != 'fk_member' && ! is_int($key)) + if ($key != 'rowid' && $key != 'tms' && $key != 'fk_member' && !is_int($key)) { // we can add this attribute to object - if (! empty($extrafields) && in_array($extrafields->attributes[$this->table_element]['type'][$key], array('date','datetime'))) + if (!empty($extrafields) && in_array($extrafields->attributes[$this->table_element]['type'][$key], array('date', 'datetime'))) { //var_dump($extrafields->attributes[$this->table_element]['type'][$key]); - $this->array_options["options_".$key]=$this->db->jdate($value); + $this->array_options["options_".$key] = $this->db->jdate($value); } else { - $this->array_options["options_".$key]=$value; + $this->array_options["options_".$key] = $value; } //var_dump('key '.$key.' '.$value.' type='.$extrafields->attributes[$this->table_element]['type'][$key].' '.$this->array_options["options_".$key]); @@ -5077,7 +5086,7 @@ abstract class CommonObject // If field is a computed field, value must become result of compute foreach ($tab as $key => $value) { - if (! empty($extrafields) && !empty($extrafields->attributes[$this->table_element]['computed'][$key])) + if (!empty($extrafields) && !empty($extrafields->attributes[$this->table_element]['computed'][$key])) { $this->array_options["options_".$key] = dol_eval($extrafields->attributes[$this->table_element]['computed'][$key], 1, 0); } @@ -5112,10 +5121,10 @@ abstract class CommonObject $sql_del = "DELETE FROM ".MAIN_DB_PREFIX.$table_element."_extrafields WHERE fk_object = ".$this->id; dol_syslog(get_class($this)."::deleteExtraFields delete", LOG_DEBUG); - $resql=$this->db->query($sql_del); - if (! $resql) + $resql = $this->db->query($sql_del); + if (!$resql) { - $this->error=$this->db->lasterror(); + $this->error = $this->db->lasterror(); $this->db->rollback(); return -1; } @@ -5138,24 +5147,24 @@ abstract class CommonObject */ public function insertExtraFields($trigger = '', $userused = null) { - global $conf,$langs,$user; + global $conf, $langs, $user; - if (empty($userused)) $userused=$user; + if (empty($userused)) $userused = $user; - $error=0; + $error = 0; - if (! empty($conf->global->MAIN_EXTRAFIELDS_DISABLED)) return 0; // For avoid conflicts if trigger used + if (!empty($conf->global->MAIN_EXTRAFIELDS_DISABLED)) return 0; // For avoid conflicts if trigger used - if (! empty($this->array_options)) + if (!empty($this->array_options)) { // Check parameters $langs->load('admin'); require_once DOL_DOCUMENT_ROOT.'/core/class/extrafields.class.php'; $extrafields = new ExtraFields($this->db); - $target_extrafields=$extrafields->fetch_name_optionals_label($this->table_element); + $target_extrafields = $extrafields->fetch_name_optionals_label($this->table_element); //Eliminate copied source object extra_fields that do not exist in target object - $new_array_options=array(); + $new_array_options = array(); foreach ($this->array_options as $key => $value) { if (in_array(substr($key, 8), array_keys($target_extrafields))) // We remove the 'options_' from $key for test $new_array_options[$key] = $value; @@ -5163,9 +5172,9 @@ abstract class CommonObject $new_array_options['options_'.$key] = $value; } - foreach($new_array_options as $key => $value) + foreach ($new_array_options as $key => $value) { - $attributeKey = substr($key, 8); // Remove 'options_' prefix + $attributeKey = substr($key, 8); // Remove 'options_' prefix $attributeType = $extrafields->attributes[$this->table_element]['type'][$attributeKey]; $attributeLabel = $extrafields->attributes[$this->table_element]['label'][$attributeKey]; $attributeParam = $extrafields->attributes[$this->table_element]['param'][$attributeKey]; @@ -5175,13 +5184,13 @@ abstract class CommonObject if ($attributeRequired) { - $mandatorypb=false; - if ($attributeType == 'link' && $this->array_options[$key] == '-1') $mandatorypb=true; - if ($this->array_options[$key] === '') $mandatorypb=true; + $mandatorypb = false; + if ($attributeType == 'link' && $this->array_options[$key] == '-1') $mandatorypb = true; + if ($this->array_options[$key] === '') $mandatorypb = true; if ($mandatorypb) { dol_syslog("Mandatory extra field ".$key." is empty"); - $this->errors[]=$langs->trans('ErrorFieldRequired', $attributeLabel); + $this->errors[] = $langs->trans('ErrorFieldRequired', $attributeLabel); return -1; } } @@ -5207,25 +5216,25 @@ abstract class CommonObject switch ($attributeType) { case 'int': - if (!is_numeric($value) && $value!='') + if (!is_numeric($value) && $value != '') { - $this->errors[]=$langs->trans("ExtraFieldHasWrongValue", $attributeLabel); + $this->errors[] = $langs->trans("ExtraFieldHasWrongValue", $attributeLabel); return -1; } - elseif ($value=='') + elseif ($value == '') { $new_array_options[$key] = null; } break; case 'double': $value = price2num($value); - if (!is_numeric($value) && $value!='') + if (!is_numeric($value) && $value != '') { dol_syslog($langs->trans("ExtraFieldHasWrongValue")." sur ".$attributeLabel."(".$value."is not '".$attributeType."')", LOG_DEBUG); - $this->errors[]=$langs->trans("ExtraFieldHasWrongValue", $attributeLabel); + $this->errors[] = $langs->trans("ExtraFieldHasWrongValue", $attributeLabel); return -1; } - elseif ($value=='') + elseif ($value == '') { $new_array_options[$key] = null; } @@ -5239,12 +5248,12 @@ abstract class CommonObject } break;*/ case 'password': - $algo=''; + $algo = ''; if ($this->array_options[$key] != '' && is_array($extrafields->attributes[$this->table_element]['param'][$attributeKey]['options'])) { // If there is an encryption choice, we use it to crypt data before insert $tmparrays = array_keys($extrafields->attributes[$this->table_element]['param'][$attributeKey]['options']); - $algo=reset($tmparrays); + $algo = reset($tmparrays); if ($algo != '') { //global $action; // $action may be 'create', 'update', 'update_extras'... @@ -5255,7 +5264,7 @@ abstract class CommonObject //var_dump($this->oldcopy->array_options[$key]); var_dump($this->array_options[$key]); if ($this->array_options[$key] == $this->oldcopy->array_options[$key]) // If old value crypted in database is same than submited new value, it means we don't change it, so we don't update. { - $new_array_options[$key] = $this->array_options[$key]; // Value is kept + $new_array_options[$key] = $this->array_options[$key]; // Value is kept } else { @@ -5266,7 +5275,7 @@ abstract class CommonObject } else { - $new_array_options[$key] = $this->array_options[$key]; // Value is kept + $new_array_options[$key] = $this->array_options[$key]; // Value is kept } } } @@ -5281,13 +5290,13 @@ abstract class CommonObject case 'date': case 'datetime': // If data is a string instead of a timestamp, we convert it - if (! is_int($this->array_options[$key])) { + if (!is_int($this->array_options[$key])) { $this->array_options[$key] = strtotime($this->array_options[$key]); } $new_array_options[$key] = $this->db->idate($this->array_options[$key]); break; case 'link': - $param_list=array_keys($attributeParam['options']); + $param_list = array_keys($attributeParam['options']); // 0 : ObjectName // 1 : classPath $InfoFieldList = explode(":", $param_list[0]); @@ -5296,18 +5305,18 @@ abstract class CommonObject { if ($value == '-1') // -1 is key for no defined in combo list of objects { - $new_array_options[$key]=''; + $new_array_options[$key] = ''; } elseif ($value) { $object = new $InfoFieldList[0]($this->db); - if (is_numeric($value)) $res=$object->fetch($value); - else $res=$object->fetch('', $value); + if (is_numeric($value)) $res = $object->fetch($value); + else $res = $object->fetch('', $value); - if ($res > 0) $new_array_options[$key]=$object->id; + if ($res > 0) $new_array_options[$key] = $object->id; else { - $this->error="Id/Ref '".$value."' for object '".$object->element."' not found"; + $this->error = "Id/Ref '".$value."' for object '".$object->element."' not found"; $this->db->rollback(); return -1; } @@ -5332,70 +5341,70 @@ abstract class CommonObject $this->db->query($sql_del); $sql = "INSERT INTO ".MAIN_DB_PREFIX.$table_element."_extrafields (fk_object"; - foreach($new_array_options as $key => $value) + foreach ($new_array_options as $key => $value) { - $attributeKey = substr($key, 8); // Remove 'options_' prefix + $attributeKey = substr($key, 8); // Remove 'options_' prefix // Add field of attribut if ($extrafields->attributes[$this->table_element]['type'][$attributeKey] != 'separate') // Only for other type than separator - $sql.=",".$attributeKey; + $sql .= ",".$attributeKey; } // We must insert a default value for fields for other entities that are mandatory to avoid not null error if (is_array($extrafields->attributes[$this->table_element]['mandatoryfieldsofotherentities'])) { - foreach($extrafields->attributes[$this->table_element]['mandatoryfieldsofotherentities'] as $tmpkey => $tmpval) + foreach ($extrafields->attributes[$this->table_element]['mandatoryfieldsofotherentities'] as $tmpkey => $tmpval) { - if (! isset($extrafields->attributes[$this->table_element]['type'][$tmpkey])) // If field not already added previously + if (!isset($extrafields->attributes[$this->table_element]['type'][$tmpkey])) // If field not already added previously { - $sql.=",".$tmpkey; + $sql .= ",".$tmpkey; } } } $sql .= ") VALUES (".$this->id; - foreach($new_array_options as $key => $value) + foreach ($new_array_options as $key => $value) { - $attributeKey = substr($key, 8); // Remove 'options_' prefix + $attributeKey = substr($key, 8); // Remove 'options_' prefix // Add field of attribute if ($extrafields->attributes[$this->table_element]['type'][$attributeKey] != 'separate') // Only for other type than separator) { if ($new_array_options[$key] != '') { - $sql.=",'".$this->db->escape($new_array_options[$key])."'"; + $sql .= ",'".$this->db->escape($new_array_options[$key])."'"; } else { - $sql.=",null"; + $sql .= ",null"; } } } // We must insert a default value for fields for other entities that are mandatory to avoid not null error if (is_array($extrafields->attributes[$this->table_element]['mandatoryfieldsofotherentities'])) { - foreach($extrafields->attributes[$this->table_element]['mandatoryfieldsofotherentities'] as $tmpkey => $tmpval) + foreach ($extrafields->attributes[$this->table_element]['mandatoryfieldsofotherentities'] as $tmpkey => $tmpval) { - if (! isset($extrafields->attributes[$this->table_element]['type'][$tmpkey])) // If field not already added previously + if (!isset($extrafields->attributes[$this->table_element]['type'][$tmpkey])) // If field not already added previously { - if (in_array($tmpval, array('int', 'double'))) $sql.=", 0"; - else $sql.=", ''"; + if (in_array($tmpval, array('int', 'double'))) $sql .= ", 0"; + else $sql .= ", ''"; } } } - $sql.=")"; + $sql .= ")"; $resql = $this->db->query($sql); - if (! $resql) + if (!$resql) { - $this->error=$this->db->lasterror(); + $this->error = $this->db->lasterror(); $error++; } - if (! $error && $trigger) + if (!$error && $trigger) { // Call trigger - $this->context=array('extrafieldaddupdate'=>1); - $result=$this->call_trigger($trigger, $userused); + $this->context = array('extrafieldaddupdate'=>1); + $result = $this->call_trigger($trigger, $userused); if ($result < 0) $error++; // End call trigger } @@ -5426,23 +5435,23 @@ abstract class CommonObject */ public function updateExtraField($key, $trigger = null, $userused = null) { - global $conf,$langs,$user; + global $conf, $langs, $user; - if (empty($userused)) $userused=$user; + if (empty($userused)) $userused = $user; - $error=0; + $error = 0; - if (! empty($conf->global->MAIN_EXTRAFIELDS_DISABLED)) return 0; // For avoid conflicts if trigger used + if (!empty($conf->global->MAIN_EXTRAFIELDS_DISABLED)) return 0; // For avoid conflicts if trigger used - if (! empty($this->array_options) && isset($this->array_options["options_".$key])) + if (!empty($this->array_options) && isset($this->array_options["options_".$key])) { // Check parameters $langs->load('admin'); require_once DOL_DOCUMENT_ROOT.'/core/class/extrafields.class.php'; $extrafields = new ExtraFields($this->db); - $target_extrafields=$extrafields->fetch_name_optionals_label($this->table_element); + $target_extrafields = $extrafields->fetch_name_optionals_label($this->table_element); - $value=$this->array_options["options_".$key]; + $value = $this->array_options["options_".$key]; $attributeType = $extrafields->attributes[$this->table_element]['type'][$key]; $attributeLabel = $extrafields->attributes[$this->table_element]['label'][$key]; @@ -5455,25 +5464,25 @@ abstract class CommonObject switch ($attributeType) { case 'int': - if (!is_numeric($value) && $value!='') + if (!is_numeric($value) && $value != '') { - $this->errors[]=$langs->trans("ExtraFieldHasWrongValue", $attributeLabel); + $this->errors[] = $langs->trans("ExtraFieldHasWrongValue", $attributeLabel); return -1; } - elseif ($value=='') + elseif ($value == '') { $this->array_options["options_".$key] = null; } break; case 'double': $value = price2num($value); - if (!is_numeric($value) && $value!='') + if (!is_numeric($value) && $value != '') { dol_syslog($langs->trans("ExtraFieldHasWrongValue")." sur ".$attributeLabel."(".$value."is not '".$attributeType."')", LOG_DEBUG); - $this->errors[]=$langs->trans("ExtraFieldHasWrongValue", $attributeLabel); + $this->errors[] = $langs->trans("ExtraFieldHasWrongValue", $attributeLabel); return -1; } - elseif ($value=='') + elseif ($value == '') { $this->array_options["options_".$key] = null; } @@ -5490,13 +5499,13 @@ abstract class CommonObject $this->array_options["options_".$key] = price2num($this->array_options["options_".$key]); break; case 'date': - $this->array_options["options_".$key]=$this->db->idate($this->array_options["options_".$key]); + $this->array_options["options_".$key] = $this->db->idate($this->array_options["options_".$key]); break; case 'datetime': - $this->array_options["options_".$key]=$this->db->idate($this->array_options["options_".$key]); + $this->array_options["options_".$key] = $this->db->idate($this->array_options["options_".$key]); break; case 'link': - $param_list=array_keys($attributeParam['options']); + $param_list = array_keys($attributeParam['options']); // 0 : ObjectName // 1 : classPath $InfoFieldList = explode(":", $param_list[0]); @@ -5505,7 +5514,7 @@ abstract class CommonObject { $object = new $InfoFieldList[0]($this->db); $object->fetch(0, $value); - $this->array_options["options_".$key]=$object->id; + $this->array_options["options_".$key] = $object->id; } break; } @@ -5514,24 +5523,24 @@ abstract class CommonObject $sql = "UPDATE ".MAIN_DB_PREFIX.$this->table_element."_extrafields SET ".$key."='".$this->db->escape($this->array_options["options_".$key])."'"; $sql .= " WHERE fk_object = ".$this->id; $resql = $this->db->query($sql); - if (! $resql) + if (!$resql) { $error++; - $this->error=$this->db->lasterror(); + $this->error = $this->db->lasterror(); } - if (! $error && $trigger) + if (!$error && $trigger) { // Call trigger - $this->context=array('extrafieldupdate'=>1); - $result=$this->call_trigger($trigger, $userused); + $this->context = array('extrafieldupdate'=>1); + $result = $this->call_trigger($trigger, $userused); if ($result < 0) $error++; // End call trigger } if ($error) { - dol_syslog(get_class($this) . "::".__METHOD__ . $this->error, LOG_ERR); + dol_syslog(get_class($this)."::".__METHOD__.$this->error, LOG_ERR); $this->db->rollback(); return -1; } @@ -5560,73 +5569,71 @@ abstract class CommonObject */ public function showInputField($val, $key, $value, $moreparam = '', $keysuffix = '', $keyprefix = '', $morecss = 0) { - global $conf,$langs,$form; + global $conf, $langs, $form; - if (! is_object($form)) + if (!is_object($form)) { require_once DOL_DOCUMENT_ROOT.'/core/class/html.form.class.php'; - $form=new Form($this->db); + $form = new Form($this->db); } - $val=$this->fields[$key]; + $val = $this->fields[$key]; - $out=''; - $type=''; + $out = ''; + $type = ''; $param = array(); - $param['options']=array(); - $reg=array(); + $param['options'] = array(); + $reg = array(); $size = $this->fields[$key]['size']; // Because we work on extrafields - if (preg_match('/^(integer|link):(.*):(.*):(.*):(.*)/i', $val['type'], $reg)){ - $param['options']=array($reg[2].':'.$reg[3].':'.$reg[4].':'.$reg[5] => 'N'); - $type ='link'; - } elseif (preg_match('/^(integer|link):(.*):(.*):(.*)/i', $val['type'], $reg)){ - $param['options']=array($reg[2].':'.$reg[3].':'.$reg[4] => 'N'); - $type ='link'; - } elseif (preg_match('/^(integer|link):(.*):(.*)/i', $val['type'], $reg)){ - $param['options']=array($reg[2].':'.$reg[3] => 'N'); - $type ='link'; - } elseif(preg_match('/^sellist:(.*):(.*):(.*):(.*)/i', $val['type'], $reg)) { - $param['options']=array($reg[1].':'.$reg[2].':'.$reg[3].':'.$reg[4] => 'N'); - $type ='sellist'; - } elseif(preg_match('/varchar\((\d+)\)/', $val['type'], $reg)) { - $param['options']=array(); - $type ='varchar'; - $size=$reg[1]; - } elseif(preg_match('/varchar/', $val['type'])) { - $param['options']=array(); - $type ='varchar'; - } elseif(is_array($this->fields[$key]['arrayofkeyval'])) { - $param['options']=$this->fields[$key]['arrayofkeyval']; - $type ='select'; + if (preg_match('/^(integer|link):(.*):(.*):(.*):(.*)/i', $val['type'], $reg)) { + $param['options'] = array($reg[2].':'.$reg[3].':'.$reg[4].':'.$reg[5] => 'N'); + $type = 'link'; + } elseif (preg_match('/^(integer|link):(.*):(.*):(.*)/i', $val['type'], $reg)) { + $param['options'] = array($reg[2].':'.$reg[3].':'.$reg[4] => 'N'); + $type = 'link'; + } elseif (preg_match('/^(integer|link):(.*):(.*)/i', $val['type'], $reg)) { + $param['options'] = array($reg[2].':'.$reg[3] => 'N'); + $type = 'link'; + } elseif (preg_match('/^sellist:(.*):(.*):(.*):(.*)/i', $val['type'], $reg)) { + $param['options'] = array($reg[1].':'.$reg[2].':'.$reg[3].':'.$reg[4] => 'N'); + $type = 'sellist'; + } elseif (preg_match('/varchar\((\d+)\)/', $val['type'], $reg)) { + $param['options'] = array(); + $type = 'varchar'; + $size = $reg[1]; + } elseif (preg_match('/varchar/', $val['type'])) { + $param['options'] = array(); + $type = 'varchar'; + } elseif (is_array($this->fields[$key]['arrayofkeyval'])) { + $param['options'] = $this->fields[$key]['arrayofkeyval']; + $type = 'select'; } else { - $param['options']=array(); - $type =$this->fields[$key]['type']; + $param['options'] = array(); + $type = $this->fields[$key]['type']; } - $label=$this->fields[$key]['label']; + $label = $this->fields[$key]['label']; //$elementtype=$this->fields[$key]['elementtype']; // Seems not used - $default=$this->fields[$key]['default']; - $computed=$this->fields[$key]['computed']; - $unique=$this->fields[$key]['unique']; - $required=$this->fields[$key]['required']; + $default = $this->fields[$key]['default']; + $computed = $this->fields[$key]['computed']; + $unique = $this->fields[$key]['unique']; + $required = $this->fields[$key]['required']; - $langfile=$this->fields[$key]['langfile']; - $list=$this->fields[$key]['list']; - $hidden=(in_array(abs($this->fields[$key]['visible']), array(0,2)) ? 1 : 0); + $langfile = $this->fields[$key]['langfile']; + $list = $this->fields[$key]['list']; + $hidden = (in_array(abs($this->fields[$key]['visible']), array(0, 2)) ? 1 : 0); $objectid = $this->id; - if ($computed) { - if (! preg_match('/^search_/', $keyprefix)) return ''.$langs->trans("AutomaticallyCalculated").''; + if (!preg_match('/^search_/', $keyprefix)) return ''.$langs->trans("AutomaticallyCalculated").''; else return ''; } - // Set value of $morecss. For this, we use in priority showsize from parameters, then $val['css'] then autodefine - if (empty($morecss) && ! empty($val['css'])) + if (empty($morecss) && !empty($val['css'])) { $morecss = $val['css']; } @@ -5640,15 +5647,15 @@ abstract class CommonObject { $morecss = 'minwidth200imp'; } - elseif (in_array($type, array('int','integer','price')) || preg_match('/^double(\([0-9],[0-9]\)){0,1}/', $type)) + elseif (in_array($type, array('int', 'integer', 'price')) || preg_match('/^double(\([0-9],[0-9]\)){0,1}/', $type)) { $morecss = 'maxwidth75'; } elseif ($type == 'url') { - $morecss='minwidth400'; + $morecss = 'minwidth400'; } elseif ($type == 'boolean') { - $morecss=''; + $morecss = ''; } else { @@ -5667,10 +5674,10 @@ abstract class CommonObject } } - if (in_array($type, array('date','datetime'))) + if (in_array($type, array('date', 'datetime'))) { - $tmp=explode(',', $size); - $newsize=$tmp[0]; + $tmp = explode(',', $size); + $newsize = $tmp[0]; $showtime = in_array($type, array('datetime')) ? 1 : 0; @@ -5680,193 +5687,197 @@ abstract class CommonObject // TODO Must also support $moreparam $out = $form->selectDate($value, $keyprefix.$key.$keysuffix, $showtime, $showtime, $required, '', 1, (($keyprefix != 'search_' && $keyprefix != 'search_options_') ? 1 : 0), 0, 1); } - elseif (in_array($type, array('int','integer'))) + elseif (in_array($type, array('duration'))) { - $tmp=explode(',', $size); - $newsize=$tmp[0]; - $out=''; + $out=$form->select_duration($keyprefix.$key.$keysuffix, $value, 0, 'text', 0, 1); + } + elseif (in_array($type, array('int', 'integer'))) + { + $tmp = explode(',', $size); + $newsize = $tmp[0]; + $out = ''; } elseif (in_array($type, array('real'))) { - $out=''; + $out = ''; } elseif (preg_match('/varchar/', $type)) { - $out=''; + $out = ''; } elseif (in_array($type, array('mail', 'phone', 'url'))) { - $out=''; + $out = ''; } elseif ($type == 'text') { - if (! preg_match('/search_/', $keyprefix)) // If keyprefix is search_ or search_options_, we must just use a simple text field + if (!preg_match('/search_/', $keyprefix)) // If keyprefix is search_ or search_options_, we must just use a simple text field { require_once DOL_DOCUMENT_ROOT.'/core/class/doleditor.class.php'; - $doleditor=new DolEditor($keyprefix.$key.$keysuffix, $value, '', 200, 'dolibarr_notes', 'In', false, false, false, ROWS_5, '90%'); - $out=$doleditor->Create(1); + $doleditor = new DolEditor($keyprefix.$key.$keysuffix, $value, '', 200, 'dolibarr_notes', 'In', false, false, false, ROWS_5, '90%'); + $out = $doleditor->Create(1); } else { - $out=''; + $out = ''; } } elseif ($type == 'html') { - if (! preg_match('/search_/', $keyprefix)) // If keyprefix is search_ or search_options_, we must just use a simple text field + if (!preg_match('/search_/', $keyprefix)) // If keyprefix is search_ or search_options_, we must just use a simple text field { require_once DOL_DOCUMENT_ROOT.'/core/class/doleditor.class.php'; - $doleditor=new DolEditor($keyprefix.$key.$keysuffix, $value, '', 200, 'dolibarr_notes', 'In', false, false, ! empty($conf->fckeditor->enabled) && $conf->global->FCKEDITOR_ENABLE_SOCIETE, ROWS_5, '90%'); - $out=$doleditor->Create(1); + $doleditor = new DolEditor($keyprefix.$key.$keysuffix, $value, '', 200, 'dolibarr_notes', 'In', false, false, !empty($conf->fckeditor->enabled) && $conf->global->FCKEDITOR_ENABLE_SOCIETE, ROWS_5, '90%'); + $out = $doleditor->Create(1); } else { - $out=''; + $out = ''; } } elseif ($type == 'boolean') { - $checked=''; + $checked = ''; if (!empty($value)) { - $checked=' checked value="1" '; + $checked = ' checked value="1" '; } else { - $checked=' value="1" '; + $checked = ' value="1" '; } - $out=''; + $out = ''; } elseif ($type == 'price') { if (!empty($value)) { // $value in memory is a php numeric, we format it into user number format. - $value=price($value); + $value = price($value); } - $out=' '.$langs->getCurrencySymbol($conf->currency); + $out = ' '.$langs->getCurrencySymbol($conf->currency); } elseif (preg_match('/^double(\([0-9],[0-9]\)){0,1}/', $type)) { if (!empty($value)) { // $value in memory is a php numeric, we format it into user number format. - $value=price($value); + $value = price($value); } - $out=' '; + $out = ' '; } elseif ($type == 'select') { $out = ''; - if (! empty($conf->use_javascript_ajax) && ! empty($conf->global->MAIN_EXTRAFIELDS_USE_SELECT2)) + if (!empty($conf->use_javascript_ajax) && !empty($conf->global->MAIN_EXTRAFIELDS_USE_SELECT2)) { - include_once DOL_DOCUMENT_ROOT . '/core/lib/ajax.lib.php'; - $out.= ajax_combobox($keyprefix.$key.$keysuffix, array(), 0); + include_once DOL_DOCUMENT_ROOT.'/core/lib/ajax.lib.php'; + $out .= ajax_combobox($keyprefix.$key.$keysuffix, array(), 0); } - $out.=''; + if ((!isset($this->fields[$key]['default'])) || ($this->fields[$key]['notnull'] != 1))$out .= ''; foreach ($param['options'] as $key => $val) { if ((string) $key == '') continue; list($val, $parent) = explode('|', $val); - $out.=''; + $out .= ''; $num = $this->db->num_rows($resql); $i = 0; while ($i < $num) { - $labeltoshow=''; + $labeltoshow = ''; $obj = $this->db->fetch_object($resql); // Several field into label (eq table:code|libelle:rowid) @@ -5877,44 +5888,44 @@ abstract class CommonObject $notrans = true; foreach ($fields_label as $field_toshow) { - $labeltoshow.= $obj->$field_toshow.' '; + $labeltoshow .= $obj->$field_toshow.' '; } } else { - $labeltoshow=$obj->{$InfoFieldList[1]}; + $labeltoshow = $obj->{$InfoFieldList[1]}; } - $labeltoshow=dol_trunc($labeltoshow, 45); + $labeltoshow = dol_trunc($labeltoshow, 45); if ($value == $obj->rowid) { foreach ($fields_label as $field_toshow) { - $translabel=$langs->trans($obj->$field_toshow); - if ($translabel!=$obj->$field_toshow) { - $labeltoshow=dol_trunc($translabel, 18).' '; - }else { - $labeltoshow=dol_trunc($obj->$field_toshow, 18).' '; + $translabel = $langs->trans($obj->$field_toshow); + if ($translabel != $obj->$field_toshow) { + $labeltoshow = dol_trunc($translabel, 18).' '; + } else { + $labeltoshow = dol_trunc($obj->$field_toshow, 18).' '; } } - $out.=''; + $out .= ''; } else { - if (! $notrans) + if (!$notrans) { - $translabel=$langs->trans($obj->{$InfoFieldList[1]}); - if ($translabel!=$obj->{$InfoFieldList[1]}) { - $labeltoshow=dol_trunc($translabel, 18); + $translabel = $langs->trans($obj->{$InfoFieldList[1]}); + if ($translabel != $obj->{$InfoFieldList[1]}) { + $labeltoshow = dol_trunc($translabel, 18); } else { - $labeltoshow=dol_trunc($obj->{$InfoFieldList[1]}, 18); + $labeltoshow = dol_trunc($obj->{$InfoFieldList[1]}, 18); } } - if (empty($labeltoshow)) $labeltoshow='(not defined)'; - if ($value==$obj->rowid) + if (empty($labeltoshow)) $labeltoshow = '(not defined)'; + if ($value == $obj->rowid) { - $out.=''; + $out .= ''; } if (!empty($InfoFieldList[3]) && $parentField) @@ -5922,10 +5933,10 @@ abstract class CommonObject $parent = $parentName.':'.$obj->{$parentField}; } - $out.=''; + $out .= ''; } $i++; @@ -5936,23 +5947,23 @@ abstract class CommonObject print 'Error in request '.$sql.' '.$this->db->lasterror().'. Check setup of extra parameters.
'; } } - $out.=''; + $out .= ''; } elseif ($type == 'checkbox') { - $value_arr=explode(',', $value); - $out=$form->multiselectarray($keyprefix.$key.$keysuffix, (empty($param['options'])?null:$param['options']), $value_arr, '', 0, '', 0, '100%'); + $value_arr = explode(',', $value); + $out = $form->multiselectarray($keyprefix.$key.$keysuffix, (empty($param['options']) ?null:$param['options']), $value_arr, '', 0, '', 0, '100%'); } elseif ($type == 'radio') { - $out=''; + $out = ''; foreach ($param['options'] as $keyopt => $val) { - $out.=''.$val.'
'; + $out .= ''.$val.'
'; } } elseif ($type == 'chkbxlst') @@ -5967,24 +5978,24 @@ abstract class CommonObject if (is_array($param['options'])) { $param_list = array_keys($param['options']); $InfoFieldList = explode(":", $param_list[0]); - $parentName=''; - $parentField=''; + $parentName = ''; + $parentField = ''; // 0 : tableName // 1 : label field name // 2 : key fields name (if differ of rowid) // 3 : key field parent (for dependent lists) // 4 : where clause filter on column or table extrafield, syntax field='value' or extra.field=value - $keyList = (empty($InfoFieldList[2]) ? 'rowid' : $InfoFieldList[2] . ' as rowid'); + $keyList = (empty($InfoFieldList[2]) ? 'rowid' : $InfoFieldList[2].' as rowid'); - if (count($InfoFieldList) > 3 && ! empty($InfoFieldList[3])) { - list ( $parentName, $parentField ) = explode('|', $InfoFieldList[3]); - $keyList .= ', ' . $parentField; + if (count($InfoFieldList) > 3 && !empty($InfoFieldList[3])) { + list ($parentName, $parentField) = explode('|', $InfoFieldList[3]); + $keyList .= ', '.$parentField; } - if (count($InfoFieldList) > 4 && ! empty($InfoFieldList[4])) { + if (count($InfoFieldList) > 4 && !empty($InfoFieldList[4])) { if (strpos($InfoFieldList[4], 'extra.') !== false) { - $keyList = 'main.' . $InfoFieldList[2] . ' as rowid'; + $keyList = 'main.'.$InfoFieldList[2].' as rowid'; } else { - $keyList = $InfoFieldList[2] . ' as rowid'; + $keyList = $InfoFieldList[2].' as rowid'; } } @@ -5995,49 +6006,49 @@ abstract class CommonObject } $sqlwhere = ''; - $sql = 'SELECT ' . $keyList; - $sql .= ' FROM ' . MAIN_DB_PREFIX . $InfoFieldList[0]; - if (! empty($InfoFieldList[4])) { + $sql = 'SELECT '.$keyList; + $sql .= ' FROM '.MAIN_DB_PREFIX.$InfoFieldList[0]; + if (!empty($InfoFieldList[4])) { // can use SELECT request - if (strpos($InfoFieldList[4], '$SEL$')!==false) { - $InfoFieldList[4]=str_replace('$SEL$', 'SELECT', $InfoFieldList[4]); + if (strpos($InfoFieldList[4], '$SEL$') !== false) { + $InfoFieldList[4] = str_replace('$SEL$', 'SELECT', $InfoFieldList[4]); } // current object id can be use into filter - if (strpos($InfoFieldList[4], '$ID$')!==false && !empty($objectid)) { - $InfoFieldList[4]=str_replace('$ID$', $objectid, $InfoFieldList[4]); + if (strpos($InfoFieldList[4], '$ID$') !== false && !empty($objectid)) { + $InfoFieldList[4] = str_replace('$ID$', $objectid, $InfoFieldList[4]); } else { - $InfoFieldList[4]=str_replace('$ID$', '0', $InfoFieldList[4]); + $InfoFieldList[4] = str_replace('$ID$', '0', $InfoFieldList[4]); } // We have to join on extrafield table if (strpos($InfoFieldList[4], 'extra') !== false) { - $sql .= ' as main, ' . MAIN_DB_PREFIX . $InfoFieldList[0] . '_extrafields as extra'; - $sqlwhere .= ' WHERE extra.fk_object=main.' . $InfoFieldList[2] . ' AND ' . $InfoFieldList[4]; + $sql .= ' as main, '.MAIN_DB_PREFIX.$InfoFieldList[0].'_extrafields as extra'; + $sqlwhere .= ' WHERE extra.fk_object=main.'.$InfoFieldList[2].' AND '.$InfoFieldList[4]; } else { - $sqlwhere .= ' WHERE ' . $InfoFieldList[4]; + $sqlwhere .= ' WHERE '.$InfoFieldList[4]; } } else { $sqlwhere .= ' WHERE 1=1'; } // Some tables may have field, some other not. For the moment we disable it. - if (in_array($InfoFieldList[0], array ('tablewithentity'))) + if (in_array($InfoFieldList[0], array('tablewithentity'))) { - $sqlwhere .= ' AND entity = ' . $conf->entity; + $sqlwhere .= ' AND entity = '.$conf->entity; } // $sql.=preg_replace('/^ AND /','',$sqlwhere); // print $sql; $sql .= $sqlwhere; - dol_syslog(get_class($this) . '::showInputField type=chkbxlst', LOG_DEBUG); + dol_syslog(get_class($this).'::showInputField type=chkbxlst', LOG_DEBUG); $resql = $this->db->query($sql); if ($resql) { $num = $this->db->num_rows($resql); $i = 0; - $data=array(); + $data = array(); - while ( $i < $num ) { + while ($i < $num) { $labeltoshow = ''; $obj = $this->db->fetch_object($resql); @@ -6047,7 +6058,7 @@ abstract class CommonObject if (is_array($fields_label)) { $notrans = true; foreach ($fields_label as $field_toshow) { - $labeltoshow .= $obj->$field_toshow . ' '; + $labeltoshow .= $obj->$field_toshow.' '; } } else { $labeltoshow = $obj->{$InfoFieldList[1]}; @@ -6058,15 +6069,15 @@ abstract class CommonObject foreach ($fields_label as $field_toshow) { $translabel = $langs->trans($obj->$field_toshow); if ($translabel != $obj->$field_toshow) { - $labeltoshow = dol_trunc($translabel, 18) . ' '; + $labeltoshow = dol_trunc($translabel, 18).' '; } else { - $labeltoshow = dol_trunc($obj->$field_toshow, 18) . ' '; + $labeltoshow = dol_trunc($obj->$field_toshow, 18).' '; } } - $data[$obj->rowid]=$labeltoshow; + $data[$obj->rowid] = $labeltoshow; } else { - if (! $notrans) { + if (!$notrans) { $translabel = $langs->trans($obj->{$InfoFieldList[1]}); if ($translabel != $obj->{$InfoFieldList[1]}) { $labeltoshow = dol_trunc($translabel, 18); @@ -6079,77 +6090,77 @@ abstract class CommonObject } if (is_array($value_arr) && in_array($obj->rowid, $value_arr)) { - $data[$obj->rowid]=$labeltoshow; + $data[$obj->rowid] = $labeltoshow; } - if (! empty($InfoFieldList[3]) && $parentField) { - $parent = $parentName . ':' . $obj->{$parentField}; + if (!empty($InfoFieldList[3]) && $parentField) { + $parent = $parentName.':'.$obj->{$parentField}; } - $data[$obj->rowid]=$labeltoshow; + $data[$obj->rowid] = $labeltoshow; } - $i ++; + $i++; } $this->db->free($resql); - $out=$form->multiselectarray($keyprefix.$key.$keysuffix, $data, $value_arr, '', 0, '', 0, '100%'); + $out = $form->multiselectarray($keyprefix.$key.$keysuffix, $data, $value_arr, '', 0, '', 0, '100%'); } else { - print 'Error in request ' . $sql . ' ' . $this->db->lasterror() . '. Check setup of extra parameters.
'; + print 'Error in request '.$sql.' '.$this->db->lasterror().'. Check setup of extra parameters.
'; } } } elseif ($type == 'link') { - $param_list=array_keys($param['options']); // $param_list='ObjectName:classPath[:AddCreateButtonOrNot[:Filter]]' + $param_list = array_keys($param['options']); // $param_list='ObjectName:classPath[:AddCreateButtonOrNot[:Filter]]' $param_list_array = explode(':', $param_list[0]); - $showempty=(($required && $default != '')?0:1); + $showempty = (($required && $default != '') ? 0 : 1); - $out=$form->selectForForms($param_list[0], $keyprefix.$key.$keysuffix, $value, $showempty, '', '', $morecss, '', 0, empty($val['disabled'])?0:1); + $out = $form->selectForForms($param_list[0], $keyprefix.$key.$keysuffix, $value, $showempty, '', '', $morecss, '', 0, empty($val['disabled']) ? 0 : 1); - if (! empty($param_list_array[2])) // If we set to add a create button + if (!empty($param_list_array[2])) // If we set to add a create button { - if (! GETPOSTISSET('backtopage') && empty($val['disabled'])) // To avoid to open several infinitely the 'Create Object' button and to avoid to have button if field is protected by a "disabled". + if (!GETPOSTISSET('backtopage') && empty($val['disabled'])) // To avoid to open several infinitely the 'Create Object' button and to avoid to have button if field is protected by a "disabled". { - list($class,$classfile)=explode(':', $param_list[0]); - if (file_exists(dol_buildpath(dirname(dirname($classfile)).'/card.php'))) $url_path=dol_buildpath(dirname(dirname($classfile)).'/card.php', 1); - else $url_path=dol_buildpath(dirname(dirname($classfile)).'/'.strtolower($class).'_card.php', 1); + list($class, $classfile) = explode(':', $param_list[0]); + if (file_exists(dol_buildpath(dirname(dirname($classfile)).'/card.php'))) $url_path = dol_buildpath(dirname(dirname($classfile)).'/card.php', 1); + else $url_path = dol_buildpath(dirname(dirname($classfile)).'/'.strtolower($class).'_card.php', 1); $paramforthenewlink = ''; - $paramforthenewlink .= (GETPOSTISSET('action')?'&action='.GETPOST('action', 'aZ09'):''); - $paramforthenewlink .= (GETPOSTISSET('id')?'&id='.GETPOST('id', 'int'):''); + $paramforthenewlink .= (GETPOSTISSET('action') ? '&action='.GETPOST('action', 'aZ09') : ''); + $paramforthenewlink .= (GETPOSTISSET('id') ? '&id='.GETPOST('id', 'int') : ''); $paramforthenewlink .= '&fk_'.strtolower($class).'=--IDFORBACKTOPAGE--'; // TODO Add Javascript code to add input fields already filled into $paramforthenewlink so we won't loose them when going back to main page - $out.=''; + $out .= ''; } } } elseif ($type == 'password') { // If prefix is 'search_', field is used as a filter, we use a common text field. - $out=''; + $out = ''; } elseif ($type == 'array') { $newval = $val; $newval['type'] = 'varchar(256)'; - $out=''; + $out = ''; $inputs = array(); - if(! empty($value)) { - foreach($value as $option) { - $out.= ' '; - $out.= $this->showInputField($newval, $keyprefix.$key.$keysuffix.'[]', $option, $moreparam, '', '', $morecss).'
'; + if (!empty($value)) { + foreach ($value as $option) { + $out .= ' '; + $out .= $this->showInputField($newval, $keyprefix.$key.$keysuffix.'[]', $option, $moreparam, '', '', $morecss).'
'; } } - $out.= ''; + $out .= ''; $newInput = ' '; - $newInput.= $this->showInputField($newval, $keyprefix.$key.$keysuffix.'[]', '', $moreparam, '', '', $morecss).'
'; + $newInput .= $this->showInputField($newval, $keyprefix.$key.$keysuffix.'[]', '', $moreparam, '', '', $morecss).'
'; - if(! empty($conf->use_javascript_ajax)) { - $out.= ' + if (!empty($conf->use_javascript_ajax)) { + $out .= ' '."\n"; + $this->stringtoshow .= 'plotWithOptions_'.$tag.'();'."\n"; + $this->stringtoshow .= '});'."\n"; + $this->stringtoshow .= ''."\n"; } @@ -1138,8 +1138,8 @@ class DolGraph if ($shownographyet) { - $s= '
'; - $s.='
'.$langs->trans("NotEnoughDataYet").'
'; + $s = '
'; + $s .= '
'.$langs->trans("NotEnoughDataYet").'
'; return $s; } @@ -1161,11 +1161,11 @@ class DolGraph if ($direction == 'width') { if (empty($conf->dol_optimize_smallscreen)) return ($defaultsize ? $defaultsize : '500'); - else return (empty($_SESSION['dol_screen_width']) ? '280' : ($_SESSION['dol_screen_width']-40)); + else return (empty($_SESSION['dol_screen_width']) ? '280' : ($_SESSION['dol_screen_width'] - 40)); } if ($direction == 'height') { - return (empty($conf->dol_optimize_smallscreen)?($defaultsize?$defaultsize:'200'):'160'); + return (empty($conf->dol_optimize_smallscreen) ? ($defaultsize ? $defaultsize : '200') : '160'); } return 0; } diff --git a/htdocs/core/class/emailsenderprofile.class.php b/htdocs/core/class/emailsenderprofile.class.php index c4af5773885..b65d72332e0 100644 --- a/htdocs/core/class/emailsenderprofile.class.php +++ b/htdocs/core/class/emailsenderprofile.class.php @@ -82,8 +82,8 @@ class EmailSenderProfile extends CommonObject 'email' => array('type'=>'varchar(255)', 'label'=>'Email', 'visible'=>1, 'enabled'=>1, 'position'=>40, 'notnull'=>-1), //'fk_user_creat' => array('type'=>'integer', 'label'=>'UserAuthor', 'visible'=>-1, 'enabled'=>1, 'position'=>500, 'notnull'=>1,), //'fk_user_modif' => array('type'=>'integer', 'label'=>'UserModif', 'visible'=>-1, 'enabled'=>1, 'position'=>500, 'notnull'=>-1,), - 'signature' => array('type'=>'text', 'label'=>'Signature', 'visible'=>-1, 'enabled'=>1, 'position'=>1000, 'notnull'=>-1, 'index'=>1,), - 'position' => array('type'=>'integer', 'label'=>'Position', 'visible'=>-1, 'enabled'=>1, 'position'=>1000, 'notnull'=>-1, 'index'=>1,), + 'signature' => array('type'=>'text', 'label'=>'Signature', 'visible'=>-1, 'enabled'=>1, 'position'=>400, 'notnull'=>-1, 'index'=>1,), + 'position' => array('type'=>'integer', 'label'=>'Position', 'visible'=>1, 'enabled'=>1, 'position'=>405, 'notnull'=>-1, 'index'=>1,), 'date_creation' => array('type'=>'datetime', 'label'=>'DateCreation', 'visible'=>-1, 'enabled'=>1, 'position'=>500, 'notnull'=>1,), 'tms' => array('type'=>'timestamp', 'label'=>'DateModification', 'visible'=>-1, 'enabled'=>1, 'position'=>500, 'notnull'=>1,), 'active' => array('type'=>'integer', 'label'=>'Status', 'visible'=>1, 'enabled'=>1, 'position'=>1000, 'notnull'=>-1, 'index'=>1), diff --git a/htdocs/core/class/extrafields.class.php b/htdocs/core/class/extrafields.class.php index 439bc1e030f..889a38efddb 100644 --- a/htdocs/core/class/extrafields.class.php +++ b/htdocs/core/class/extrafields.class.php @@ -140,7 +140,7 @@ class ExtraFields /** * @var string Error code (or message) */ - public $error=''; + public $error = ''; /** * @var string[] Array of Error code (or message) @@ -153,7 +153,7 @@ class ExtraFields public $errno; - public static $type2label=array( + public static $type2label = array( 'varchar'=>'String', 'text'=>'TextLong', 'html'=>'HtmlText', @@ -280,67 +280,67 @@ class ExtraFields */ private function create($attrname, $type = 'varchar', $length = 255, $elementtype = 'member', $unique = 0, $required = 0, $default_value = '', $param = '', $perms = '', $list = '0', $computed = '', $help = '') { - if ($elementtype == 'thirdparty') $elementtype='societe'; - if ($elementtype == 'contact') $elementtype='socpeople'; + if ($elementtype == 'thirdparty') $elementtype = 'societe'; + if ($elementtype == 'contact') $elementtype = 'socpeople'; - $table=$elementtype.'_extrafields'; - if ($elementtype == 'categorie') $table='categories_extrafields'; + $table = $elementtype.'_extrafields'; + if ($elementtype == 'categorie') $table = 'categories_extrafields'; - if (! empty($attrname) && preg_match("/^\w[a-zA-Z0-9_]*$/", $attrname) && ! is_numeric($attrname)) + if (!empty($attrname) && preg_match("/^\w[a-zA-Z0-9_]*$/", $attrname) && !is_numeric($attrname)) { - if ($type=='boolean') { - $typedb='int'; - $lengthdb='1'; - } elseif($type=='price') { - $typedb='double'; - $lengthdb='24,8'; - } elseif($type=='phone') { - $typedb='varchar'; - $lengthdb='20'; - } elseif($type=='mail') { - $typedb='varchar'; - $lengthdb='128'; - } elseif($type=='url') { - $typedb='varchar'; - $lengthdb='255'; - } elseif (($type=='select') || ($type=='sellist') || ($type=='radio') ||($type=='checkbox') ||($type=='chkbxlst')){ - $typedb='varchar'; - $lengthdb='255'; - } elseif ($type=='link') { - $typedb='int'; - $lengthdb='11'; - } elseif ($type=='html') { - $typedb='text'; - $lengthdb=$length; - } elseif($type=='password') { - $typedb='varchar'; - $lengthdb='128'; + if ($type == 'boolean') { + $typedb = 'int'; + $lengthdb = '1'; + } elseif ($type == 'price') { + $typedb = 'double'; + $lengthdb = '24,8'; + } elseif ($type == 'phone') { + $typedb = 'varchar'; + $lengthdb = '20'; + } elseif ($type == 'mail') { + $typedb = 'varchar'; + $lengthdb = '128'; + } elseif ($type == 'url') { + $typedb = 'varchar'; + $lengthdb = '255'; + } elseif (($type == 'select') || ($type == 'sellist') || ($type == 'radio') || ($type == 'checkbox') || ($type == 'chkbxlst')) { + $typedb = 'varchar'; + $lengthdb = '255'; + } elseif ($type == 'link') { + $typedb = 'int'; + $lengthdb = '11'; + } elseif ($type == 'html') { + $typedb = 'text'; + $lengthdb = $length; + } elseif ($type == 'password') { + $typedb = 'varchar'; + $lengthdb = '128'; } else { - $typedb=$type; - $lengthdb=$length; - if ($type == 'varchar' && empty($lengthdb)) $lengthdb='255'; + $typedb = $type; + $lengthdb = $length; + if ($type == 'varchar' && empty($lengthdb)) $lengthdb = '255'; } $field_desc = array( 'type'=>$typedb, 'value'=>$lengthdb, - 'null'=>($required?'NOT NULL':'NULL'), + 'null'=>($required ? 'NOT NULL' : 'NULL'), 'default' => $default_value ); - $result=$this->db->DDLAddField(MAIN_DB_PREFIX.$table, $attrname, $field_desc); + $result = $this->db->DDLAddField(MAIN_DB_PREFIX.$table, $attrname, $field_desc); if ($result > 0) { if ($unique) { - $sql="ALTER TABLE ".MAIN_DB_PREFIX.$table." ADD UNIQUE INDEX uk_".$table."_".$attrname." (".$attrname.")"; - $resql=$this->db->query($sql, 1, 'dml'); + $sql = "ALTER TABLE ".MAIN_DB_PREFIX.$table." ADD UNIQUE INDEX uk_".$table."_".$attrname." (".$attrname.")"; + $resql = $this->db->query($sql, 1, 'dml'); } return 1; } else { - $this->error=$this->db->lasterror(); - $this->errno=$this->db->lasterrno(); + $this->error = $this->db->lasterror(); + $this->errno = $this->db->lasterrno(); return -1; } } @@ -378,19 +378,19 @@ class ExtraFields private function create_label($attrname, $label = '', $type = '', $pos = 0, $size = 0, $elementtype = 'member', $unique = 0, $required = 0, $param = '', $alwayseditable = 0, $perms = '', $list = '-1', $help = '', $default = '', $computed = '', $entity = '', $langfile = '', $enabled = '1', $totalizable = 0) { // phpcs:enable - global $conf,$user; + global $conf, $user; - if ($elementtype == 'thirdparty') $elementtype='societe'; - if ($elementtype == 'contact') $elementtype='socpeople'; + if ($elementtype == 'thirdparty') $elementtype = 'societe'; + if ($elementtype == 'contact') $elementtype = 'socpeople'; // Clean parameters - if (empty($pos)) $pos=0; - if (empty($list)) $list='0'; - if (empty($required)) $required=0; - if (empty($unique)) $unique=0; - if (empty($alwayseditable)) $alwayseditable=0; + if (empty($pos)) $pos = 0; + if (empty($list)) $list = '0'; + if (empty($required)) $required = 0; + if (empty($unique)) $unique = 0; + if (empty($alwayseditable)) $alwayseditable = 0; - if (! empty($attrname) && preg_match("/^\w[a-zA-Z0-9-_]*$/", $attrname) && ! is_numeric($attrname)) + if (!empty($attrname) && preg_match("/^\w[a-zA-Z0-9-_]*$/", $attrname) && !is_numeric($attrname)) { if (is_array($param) && count($param) > 0) { @@ -460,8 +460,8 @@ class ExtraFields } else { - $this->error=$this->db->lasterror(); - $this->errno=$this->db->lasterrno(); + $this->error = $this->db->lasterror(); + $this->errno = $this->db->lasterrno(); return -1; } } @@ -476,30 +476,30 @@ class ExtraFields */ public function delete($attrname, $elementtype = 'member') { - if ($elementtype == 'thirdparty') $elementtype='societe'; - if ($elementtype == 'contact') $elementtype='socpeople'; + if ($elementtype == 'thirdparty') $elementtype = 'societe'; + if ($elementtype == 'contact') $elementtype = 'socpeople'; - $table=$elementtype.'_extrafields'; - if ($elementtype == 'categorie') $table='categories_extrafields'; + $table = $elementtype.'_extrafields'; + if ($elementtype == 'categorie') $table = 'categories_extrafields'; - $error=0; + $error = 0; - if (! empty($attrname) && preg_match("/^\w[a-zA-Z0-9-_]*$/", $attrname)) + if (!empty($attrname) && preg_match("/^\w[a-zA-Z0-9-_]*$/", $attrname)) { - $result=$this->delete_label($attrname, $elementtype); + $result = $this->delete_label($attrname, $elementtype); if ($result < 0) { - $this->error=$this->db->lasterror(); - $this->errors[]=$this->db->lasterror(); + $this->error = $this->db->lasterror(); + $this->errors[] = $this->db->lasterror(); $error++; } - if (! $error) + if (!$error) { $sql = "SELECT COUNT(rowid) as nb"; - $sql.= " FROM ".MAIN_DB_PREFIX."extrafields"; - $sql.= " WHERE elementtype = '".$elementtype."'"; - $sql.= " AND name = '".$attrname."'"; + $sql .= " FROM ".MAIN_DB_PREFIX."extrafields"; + $sql .= " WHERE elementtype = '".$elementtype."'"; + $sql .= " AND name = '".$attrname."'"; //$sql.= " AND entity IN (0,".$conf->entity.")"; Do not test on entity here. We want to see if there is still on field remaning in other entities before deleting field in table $resql = $this->db->query($sql); if ($resql) @@ -507,11 +507,11 @@ class ExtraFields $obj = $this->db->fetch_object($resql); if ($obj->nb <= 0) { - $result=$this->db->DDLDropField(MAIN_DB_PREFIX.$table, $attrname); // This also drop the unique key + $result = $this->db->DDLDropField(MAIN_DB_PREFIX.$table, $attrname); // This also drop the unique key if ($result < 0) { - $this->error=$this->db->lasterror(); - $this->errors[]=$this->db->lasterror(); + $this->error = $this->db->lasterror(); + $this->errors[] = $this->db->lasterror(); $error++; } } @@ -539,18 +539,18 @@ class ExtraFields // phpcs:enable global $conf; - if ($elementtype == 'thirdparty') $elementtype='societe'; - if ($elementtype == 'contact') $elementtype='socpeople'; + if ($elementtype == 'thirdparty') $elementtype = 'societe'; + if ($elementtype == 'contact') $elementtype = 'socpeople'; if (isset($attrname) && $attrname != '' && preg_match("/^\w[a-zA-Z0-9-_]*$/", $attrname)) { $sql = "DELETE FROM ".MAIN_DB_PREFIX."extrafields"; - $sql.= " WHERE name = '".$attrname."'"; - $sql.= " AND entity IN (0,".$conf->entity.')'; - $sql.= " AND elementtype = '".$elementtype."'"; + $sql .= " WHERE name = '".$attrname."'"; + $sql .= " AND entity IN (0,".$conf->entity.')'; + $sql .= " AND elementtype = '".$elementtype."'"; dol_syslog(get_class($this)."::delete_label", LOG_DEBUG); - $resql=$this->db->query($sql); + $resql = $this->db->query($sql); if ($resql) { return 1; @@ -593,80 +593,80 @@ class ExtraFields */ public function update($attrname, $label, $type, $length, $elementtype, $unique = 0, $required = 0, $pos = 0, $param = '', $alwayseditable = 0, $perms = '', $list = '', $help = '', $default = '', $computed = '', $entity = '', $langfile = '', $enabled = '1', $totalizable = 0) { - if ($elementtype == 'thirdparty') $elementtype='societe'; - if ($elementtype == 'contact') $elementtype='socpeople'; + if ($elementtype == 'thirdparty') $elementtype = 'societe'; + if ($elementtype == 'contact') $elementtype = 'socpeople'; - $table=$elementtype.'_extrafields'; - if ($elementtype == 'categorie') $table='categories_extrafields'; + $table = $elementtype.'_extrafields'; + if ($elementtype == 'categorie') $table = 'categories_extrafields'; if (isset($attrname) && $attrname != '' && preg_match("/^\w[a-zA-Z0-9-_]*$/", $attrname)) { - if ($type=='boolean') { - $typedb='int'; - $lengthdb='1'; - } elseif($type=='price') { - $typedb='double'; - $lengthdb='24,8'; - } elseif($type=='phone') { - $typedb='varchar'; - $lengthdb='20'; - } elseif($type=='mail') { - $typedb='varchar'; - $lengthdb='128'; - } elseif($type=='url') { - $typedb='varchar'; - $lengthdb='255'; - } elseif (($type=='select') || ($type=='sellist') || ($type=='radio') || ($type=='checkbox') || ($type=='chkbxlst')) { - $typedb='varchar'; - $lengthdb='255'; + if ($type == 'boolean') { + $typedb = 'int'; + $lengthdb = '1'; + } elseif ($type == 'price') { + $typedb = 'double'; + $lengthdb = '24,8'; + } elseif ($type == 'phone') { + $typedb = 'varchar'; + $lengthdb = '20'; + } elseif ($type == 'mail') { + $typedb = 'varchar'; + $lengthdb = '128'; + } elseif ($type == 'url') { + $typedb = 'varchar'; + $lengthdb = '255'; + } elseif (($type == 'select') || ($type == 'sellist') || ($type == 'radio') || ($type == 'checkbox') || ($type == 'chkbxlst')) { + $typedb = 'varchar'; + $lengthdb = '255'; } elseif ($type == 'html') { - $typedb='text'; - } elseif ($type=='link') { - $typedb='int'; - $lengthdb='11'; - } elseif($type=='password') { - $typedb='varchar'; - $lengthdb='50'; + $typedb = 'text'; + } elseif ($type == 'link') { + $typedb = 'int'; + $lengthdb = '11'; + } elseif ($type == 'password') { + $typedb = 'varchar'; + $lengthdb = '50'; } else { - $typedb=$type; - $lengthdb=$length; + $typedb = $type; + $lengthdb = $length; } - $field_desc = array('type'=>$typedb, 'value'=>$lengthdb, 'null'=>($required?'NOT NULL':'NULL'), 'default'=>$default); + $field_desc = array('type'=>$typedb, 'value'=>$lengthdb, 'null'=>($required ? 'NOT NULL' : 'NULL'), 'default'=>$default); if ($type != 'separate') // No table update when separate type { - $result=$this->db->DDLUpdateField(MAIN_DB_PREFIX.$table, $attrname, $field_desc); + $result = $this->db->DDLUpdateField(MAIN_DB_PREFIX.$table, $attrname, $field_desc); } if ($result > 0 || $type == 'separate') { if ($label) { - $result=$this->update_label($attrname, $label, $type, $length, $elementtype, $unique, $required, $pos, $param, $alwayseditable, $perms, $list, $help, $default, $computed, $entity, $langfile, $enabled, $totalizable); + $result = $this->update_label($attrname, $label, $type, $length, $elementtype, $unique, $required, $pos, $param, $alwayseditable, $perms, $list, $help, $default, $computed, $entity, $langfile, $enabled, $totalizable); } if ($result > 0) { - $sql=''; + $sql = ''; if ($unique) { - $sql="ALTER TABLE ".MAIN_DB_PREFIX.$table." ADD UNIQUE INDEX uk_".$table."_".$attrname." (".$attrname.")"; + $sql = "ALTER TABLE ".MAIN_DB_PREFIX.$table." ADD UNIQUE INDEX uk_".$table."_".$attrname." (".$attrname.")"; } else { - $sql="ALTER TABLE ".MAIN_DB_PREFIX.$table." DROP INDEX uk_".$table."_".$attrname; + $sql = "ALTER TABLE ".MAIN_DB_PREFIX.$table." DROP INDEX uk_".$table."_".$attrname; } dol_syslog(get_class($this).'::update', LOG_DEBUG); - $resql=$this->db->query($sql, 1, 'dml'); + $resql = $this->db->query($sql, 1, 'dml'); return 1; } else { - $this->error=$this->db->lasterror(); + $this->error = $this->db->lasterror(); return -1; } } else { - $this->error=$this->db->lasterror(); + $this->error = $this->db->lasterror(); return -1; } } @@ -708,17 +708,17 @@ class ExtraFields dol_syslog(get_class($this)."::update_label ".$attrname.", ".$label.", ".$type.", ".$size.", ".$elementtype.", ".$unique.", ".$required.", ".$pos.", ".$alwayseditable.", ".$perms.", ".$list.", ".$default.", ".$computed.", ".$entity.", ".$langfile.", ".$enabled.", ".$totalizable); // Clean parameters - if ($elementtype == 'thirdparty') $elementtype='societe'; - if ($elementtype == 'contact') $elementtype='socpeople'; + if ($elementtype == 'thirdparty') $elementtype = 'societe'; + if ($elementtype == 'contact') $elementtype = 'socpeople'; - if (empty($pos)) $pos=0; - if (empty($list)) $list='0'; + if (empty($pos)) $pos = 0; + if (empty($list)) $list = '0'; if (empty($totalizable)) { $totalizable = 0; } - if (empty($required)) $required=0; - if (empty($unique)) $unique=0; - if (empty($alwayseditable)) $alwayseditable=0; + if (empty($required)) $required = 0; + if (empty($unique)) $unique = 0; + if (empty($alwayseditable)) $alwayseditable = 0; if (isset($attrname) && $attrname != '' && preg_match("/^\w[a-zA-Z0-9-_]*$/", $attrname)) { @@ -734,76 +734,76 @@ class ExtraFields } else { - $params=''; + $params = ''; } if ($entity === '' || $entity != '0') { // We dont want on all entities, we delete all and current $sql_del = "DELETE FROM ".MAIN_DB_PREFIX."extrafields"; - $sql_del.= " WHERE name = '".$attrname."'"; - $sql_del.= " AND entity IN (0, ".($entity===''?$conf->entity:$entity).")"; - $sql_del.= " AND elementtype = '".$elementtype."'"; + $sql_del .= " WHERE name = '".$attrname."'"; + $sql_del .= " AND entity IN (0, ".($entity === '' ? $conf->entity : $entity).")"; + $sql_del .= " AND elementtype = '".$elementtype."'"; } else { // We want on all entities ($entities = '0'), we delete on all only (we keep setup specific to each entity) $sql_del = "DELETE FROM ".MAIN_DB_PREFIX."extrafields"; - $sql_del.= " WHERE name = '".$attrname."'"; - $sql_del.= " AND entity = 0"; - $sql_del.= " AND elementtype = '".$elementtype."'"; + $sql_del .= " WHERE name = '".$attrname."'"; + $sql_del .= " AND entity = 0"; + $sql_del .= " AND elementtype = '".$elementtype."'"; } - $resql1=$this->db->query($sql_del); + $resql1 = $this->db->query($sql_del); $sql = "INSERT INTO ".MAIN_DB_PREFIX."extrafields("; - $sql.= " name,"; // This is code - $sql.= " entity,"; - $sql.= " label,"; - $sql.= " type,"; - $sql.= " size,"; - $sql.= " elementtype,"; - $sql.= " fieldunique,"; - $sql.= " fieldrequired,"; - $sql.= " perms,"; - $sql.= " langs,"; - $sql.= " pos,"; - $sql.= " alwayseditable,"; - $sql.= " param,"; - $sql.= " list,"; - $sql.= " totalizable,"; - $sql.= " fielddefault,"; - $sql.= " fieldcomputed,"; - $sql.= " fk_user_author,"; - $sql.= " fk_user_modif,"; - $sql.= " datec,"; - $sql.= " enabled,"; - $sql.= " help"; - $sql.= ") VALUES ("; - $sql.= "'".$attrname."',"; - $sql.= " ".($entity===''?$conf->entity:$entity).","; - $sql.= " '".$this->db->escape($label)."',"; - $sql.= " '".$this->db->escape($type)."',"; - $sql.= " '".$this->db->escape($size)."',"; - $sql.= " '".$this->db->escape($elementtype)."',"; - $sql.= " ".$unique.","; - $sql.= " ".$required.","; - $sql.= " ".($perms?"'".$this->db->escape($perms)."'":"null").","; - $sql.= " ".($langfile?"'".$this->db->escape($langfile)."'":"null").","; - $sql.= " ".$pos.","; - $sql.= " '".$this->db->escape($alwayseditable)."',"; - $sql.= " '".$this->db->escape($params)."',"; - $sql.= " '".$this->db->escape($list)."', "; - $sql.= " ".$totalizable.","; - $sql.= " ".(($default!='')?"'".$this->db->escape($default)."'":"null").","; - $sql.= " ".($computed?"'".$this->db->escape($computed)."'":"null").","; - $sql .= " " . $user->id . ","; - $sql .= " " . $user->id . ","; - $sql .= "'" . $this->db->idate(dol_now()) . "',"; - $sql .= "'" . $this->db->escape($enabled). "',"; - $sql.= " ".($help?"'".$this->db->escape($help)."'":"null"); - $sql.= ")"; + $sql .= " name,"; // This is code + $sql .= " entity,"; + $sql .= " label,"; + $sql .= " type,"; + $sql .= " size,"; + $sql .= " elementtype,"; + $sql .= " fieldunique,"; + $sql .= " fieldrequired,"; + $sql .= " perms,"; + $sql .= " langs,"; + $sql .= " pos,"; + $sql .= " alwayseditable,"; + $sql .= " param,"; + $sql .= " list,"; + $sql .= " totalizable,"; + $sql .= " fielddefault,"; + $sql .= " fieldcomputed,"; + $sql .= " fk_user_author,"; + $sql .= " fk_user_modif,"; + $sql .= " datec,"; + $sql .= " enabled,"; + $sql .= " help"; + $sql .= ") VALUES ("; + $sql .= "'".$attrname."',"; + $sql .= " ".($entity === '' ? $conf->entity : $entity).","; + $sql .= " '".$this->db->escape($label)."',"; + $sql .= " '".$this->db->escape($type)."',"; + $sql .= " '".$this->db->escape($size)."',"; + $sql .= " '".$this->db->escape($elementtype)."',"; + $sql .= " ".$unique.","; + $sql .= " ".$required.","; + $sql .= " ".($perms ? "'".$this->db->escape($perms)."'" : "null").","; + $sql .= " ".($langfile ? "'".$this->db->escape($langfile)."'" : "null").","; + $sql .= " ".$pos.","; + $sql .= " '".$this->db->escape($alwayseditable)."',"; + $sql .= " '".$this->db->escape($params)."',"; + $sql .= " '".$this->db->escape($list)."', "; + $sql .= " ".$totalizable.","; + $sql .= " ".(($default != '') ? "'".$this->db->escape($default)."'" : "null").","; + $sql .= " ".($computed ? "'".$this->db->escape($computed)."'" : "null").","; + $sql .= " ".$user->id.","; + $sql .= " ".$user->id.","; + $sql .= "'".$this->db->idate(dol_now())."',"; + $sql .= "'".$this->db->escape($enabled)."',"; + $sql .= " ".($help ? "'".$this->db->escape($help)."'" : "null"); + $sql .= ")"; - $resql2=$this->db->query($sql); + $resql2 = $this->db->query($sql); if ($resql1 && $resql2) { @@ -839,11 +839,11 @@ class ExtraFields if (empty($elementtype)) return array(); - if ($elementtype == 'thirdparty') $elementtype='societe'; - if ($elementtype == 'contact') $elementtype='socpeople'; - if ($elementtype == 'order_supplier') $elementtype='commande_fournisseur'; + if ($elementtype == 'thirdparty') $elementtype = 'societe'; + if ($elementtype == 'contact') $elementtype = 'socpeople'; + if ($elementtype == 'order_supplier') $elementtype = 'commande_fournisseur'; - $array_name_label=array(); + $array_name_label = array(); // To avoid conflicts with external modules. TODO Remove this. if (empty($forceload) && !empty($conf->global->MAIN_EXTRAFIELDS_DISABLED)) return $array_name_label; @@ -853,7 +853,8 @@ class ExtraFields // if (empty($forceload) && ! empty($this->attributes[$tab->elementtype]['loaded'])) return $array_name_label; // Set array of label of entity - // TODO Remove completely loading of label. This should be done by presentation. + // Remove completely loading of label. This should be done by presentation. + /* $labelmulticompany=array(); if (!empty($conf->multicompany->enabled)) { @@ -866,18 +867,16 @@ class ExtraFields $labelmulticompany[$obj->rowid]=$obj->label; } } - } - - // We should not have several time this log. If we have, there is some optimization to do by calling a simple $object->fetch_optionals() that include cache management. - dol_syslog("fetch_name_optionals_label elementtype=".$elementtype); + }*/ + // We should not have several time this request. If we have, there is some optimization to do by calling a simple $extrafields->fetch_optionals() in top of code and not into subcode $sql = "SELECT rowid,name,label,type,size,elementtype,fieldunique,fieldrequired,param,pos,alwayseditable,perms,langs,list,totalizable,fielddefault,fieldcomputed,entity,enabled,help"; - $sql.= " FROM ".MAIN_DB_PREFIX."extrafields"; + $sql .= " FROM ".MAIN_DB_PREFIX."extrafields"; //$sql.= " WHERE entity IN (0,".$conf->entity.")"; // Filter is done later - if ($elementtype) $sql.= " WHERE elementtype = '".$elementtype."'"; // Filed with object->table_element - $sql.= " ORDER BY pos"; + if ($elementtype) $sql .= " WHERE elementtype = '".$elementtype."'"; // Filed with object->table_element + $sql .= " ORDER BY pos"; - $resql=$this->db->query($sql); + $resql = $this->db->query($sql); if ($resql) { if ($this->db->num_rows($resql)) @@ -889,7 +888,7 @@ class ExtraFields // This field is not in current entity. We discard but before we save it into the array of mandatory fields if it is a mandatory field without default value if ($tab->fieldrequired && is_null($tab->fielddefault)) { - $this->attributes[$tab->elementtype]['mandatoryfieldsofotherentities'][$tab->name]=$tab->type; + $this->attributes[$tab->elementtype]['mandatoryfieldsofotherentities'][$tab->name] = $tab->type; } continue; } @@ -917,7 +916,6 @@ class ExtraFields $this->attribute_list[$tab->name]=$tab->list; $this->attribute_totalizable[$tab->name]=$tab->totalizable; $this->attribute_entityid[$tab->name]=$tab->entity; - $this->attribute_entitylabel[$tab->name]=(empty($labelmulticompany[$tab->entity])?'Entity'.$tab->entity:$labelmulticompany[$tab->entity]); // New usage $this->attributes[$tab->elementtype]['type'][$tab->name]=$tab->type; @@ -936,7 +934,6 @@ class ExtraFields $this->attributes[$tab->elementtype]['list'][$tab->name]=$tab->list; $this->attributes[$tab->elementtype]['totalizable'][$tab->name]=$tab->totalizable; $this->attributes[$tab->elementtype]['entityid'][$tab->name]=$tab->entity; - $this->attributes[$tab->elementtype]['entitylabel'][$tab->name]=(empty($labelmulticompany[$tab->entity])?'Entity'.$tab->entity:$labelmulticompany[$tab->entity]); $this->attributes[$tab->elementtype]['enabled'][$tab->name]=$tab->enabled; $this->attributes[$tab->elementtype]['help'][$tab->name]=$tab->help; @@ -972,58 +969,58 @@ class ExtraFields */ public function showInputField($key, $value, $moreparam = '', $keysuffix = '', $keyprefix = '', $morecss = '', $objectid = 0, $extrafieldsobjectkey = '', $mode = 0) { - global $conf,$langs,$form; + global $conf, $langs, $form; - if (! is_object($form)) + if (!is_object($form)) { require_once DOL_DOCUMENT_ROOT.'/core/class/html.form.class.php'; - $form=new Form($this->db); + $form = new Form($this->db); } - $out=''; + $out = ''; - if (! preg_match('/options_$/', $keyprefix)) // Because we work on extrafields, we add 'options_' to prefix if not already added + if (!preg_match('/options_$/', $keyprefix)) // Because we work on extrafields, we add 'options_' to prefix if not already added { $keyprefix = $keyprefix.'options_'; } - if (! empty($extrafieldsobjectkey)) + if (!empty($extrafieldsobjectkey)) { - $label=$this->attributes[$extrafieldsobjectkey]['label'][$key]; - $type=$this->attributes[$extrafieldsobjectkey]['type'][$key]; - $size=$this->attributes[$extrafieldsobjectkey]['size'][$key]; - $default=$this->attributes[$extrafieldsobjectkey]['default'][$key]; - $computed=$this->attributes[$extrafieldsobjectkey]['computed'][$key]; - $unique=$this->attributes[$extrafieldsobjectkey]['unique'][$key]; - $required=$this->attributes[$extrafieldsobjectkey]['required'][$key]; - $param=$this->attributes[$extrafieldsobjectkey]['param'][$key]; - $perms=dol_eval($this->attributes[$extrafieldsobjectkey]['perms'][$key], 1); - $langfile=$this->attributes[$extrafieldsobjectkey]['langfile'][$key]; - $list=dol_eval($this->attributes[$extrafieldsobjectkey]['list'][$key], 1); - $totalizable=$this->attributes[$extrafieldsobjectkey]['totalizable'][$key]; - $help=$this->attributes[$extrafieldsobjectkey]['help'][$key]; - $hidden=(empty($list) ? 1 : 0); // If empty, we are sure it is hidden, otherwise we show. If it depends on mode (view/create/edit form or list, this must be filtered by caller) + $label = $this->attributes[$extrafieldsobjectkey]['label'][$key]; + $type = $this->attributes[$extrafieldsobjectkey]['type'][$key]; + $size = $this->attributes[$extrafieldsobjectkey]['size'][$key]; + $default = $this->attributes[$extrafieldsobjectkey]['default'][$key]; + $computed = $this->attributes[$extrafieldsobjectkey]['computed'][$key]; + $unique = $this->attributes[$extrafieldsobjectkey]['unique'][$key]; + $required = $this->attributes[$extrafieldsobjectkey]['required'][$key]; + $param = $this->attributes[$extrafieldsobjectkey]['param'][$key]; + $perms = dol_eval($this->attributes[$extrafieldsobjectkey]['perms'][$key], 1); + $langfile = $this->attributes[$extrafieldsobjectkey]['langfile'][$key]; + $list = dol_eval($this->attributes[$extrafieldsobjectkey]['list'][$key], 1); + $totalizable = $this->attributes[$extrafieldsobjectkey]['totalizable'][$key]; + $help = $this->attributes[$extrafieldsobjectkey]['help'][$key]; + $hidden = (empty($list) ? 1 : 0); // If empty, we are sure it is hidden, otherwise we show. If it depends on mode (view/create/edit form or list, this must be filtered by caller) } else // Old usage { - $label=$this->attribute_label[$key]; - $type =$this->attribute_type[$key]; - $size =$this->attribute_size[$key]; - $elementtype=$this->attribute_elementtype[$key]; // Seems not used - $default=$this->attribute_default[$key]; - $computed=$this->attribute_computed[$key]; - $unique=$this->attribute_unique[$key]; - $required=$this->attribute_required[$key]; - $param=$this->attribute_param[$key]; - $langfile=$this->attribute_langfile[$key]; - $list=$this->attribute_list[$key]; - $totalizable=$this->attribute_totalizable[$key]; - $hidden=(empty($list) ? 1 : 0); // If empty, we are sure it is hidden, otherwise we show. If it depends on mode (view/create/edit form or list, this must be filtered by caller) + $label = $this->attribute_label[$key]; + $type = $this->attribute_type[$key]; + $size = $this->attribute_size[$key]; + $elementtype = $this->attribute_elementtype[$key]; // Seems not used + $default = $this->attribute_default[$key]; + $computed = $this->attribute_computed[$key]; + $unique = $this->attribute_unique[$key]; + $required = $this->attribute_required[$key]; + $param = $this->attribute_param[$key]; + $langfile = $this->attribute_langfile[$key]; + $list = $this->attribute_list[$key]; + $totalizable = $this->attribute_totalizable[$key]; + $hidden = (empty($list) ? 1 : 0); // If empty, we are sure it is hidden, otherwise we show. If it depends on mode (view/create/edit form or list, this must be filtered by caller) } if ($computed) { - if (! preg_match('/^search_/', $keyprefix)) return ''.$langs->trans("AutomaticallyCalculated").''; + if (!preg_match('/^search_/', $keyprefix)) return ''.$langs->trans("AutomaticallyCalculated").''; else return ''; } @@ -1037,21 +1034,21 @@ class ExtraFields { $morecss = 'minwidth200imp'; } - elseif (in_array($type, array('int','integer','double','price'))) + elseif (in_array($type, array('int', 'integer', 'double', 'price'))) { $morecss = 'maxwidth75'; } elseif ($type == 'password') { - $morecss='maxwidth100'; + $morecss = 'maxwidth100'; } elseif ($type == 'url') { - $morecss='minwidth400'; + $morecss = 'minwidth400'; } elseif ($type == 'boolean') { - $morecss=''; + $morecss = ''; } else { @@ -1070,10 +1067,10 @@ class ExtraFields } } - if (in_array($type, array('date','datetime'))) + if (in_array($type, array('date', 'datetime'))) { - $tmp=explode(',', $size); - $newsize=$tmp[0]; + $tmp = explode(',', $size); + $newsize = $tmp[0]; $showtime = in_array($type, array('datetime')) ? 1 : 0; @@ -1083,118 +1080,118 @@ class ExtraFields // TODO Must also support $moreparam $out = $form->selectDate($value, $keyprefix.$key.$keysuffix, $showtime, $showtime, $required, '', 1, (($keyprefix != 'search_' && $keyprefix != 'search_options_') ? 1 : 0), 0, 1); } - elseif (in_array($type, array('int','integer'))) + elseif (in_array($type, array('int', 'integer'))) { - $tmp=explode(',', $size); - $newsize=$tmp[0]; - $out=''; + $tmp = explode(',', $size); + $newsize = $tmp[0]; + $out = ''; } elseif (preg_match('/varchar/', $type)) { - $out=''; + $out = ''; } elseif (in_array($type, array('mail', 'phone', 'url'))) { - $out=''; + $out = ''; } elseif ($type == 'text') { - if (! preg_match('/search_/', $keyprefix)) // If keyprefix is search_ or search_options_, we must just use a simple text field + if (!preg_match('/search_/', $keyprefix)) // If keyprefix is search_ or search_options_, we must just use a simple text field { require_once DOL_DOCUMENT_ROOT.'/core/class/doleditor.class.php'; - $doleditor=new DolEditor($keyprefix.$key.$keysuffix, $value, '', 200, 'dolibarr_notes', 'In', false, false, false, ROWS_5, '90%'); - $out=$doleditor->Create(1); + $doleditor = new DolEditor($keyprefix.$key.$keysuffix, $value, '', 200, 'dolibarr_notes', 'In', false, false, false, ROWS_5, '90%'); + $out = $doleditor->Create(1); } else { - $out=''; + $out = ''; } } elseif ($type == 'html') { - if (! preg_match('/search_/', $keyprefix)) // If keyprefix is search_ or search_options_, we must just use a simple text field + if (!preg_match('/search_/', $keyprefix)) // If keyprefix is search_ or search_options_, we must just use a simple text field { require_once DOL_DOCUMENT_ROOT.'/core/class/doleditor.class.php'; - $doleditor=new DolEditor($keyprefix.$key.$keysuffix, $value, '', 200, 'dolibarr_notes', 'In', false, false, ! empty($conf->fckeditor->enabled) && $conf->global->FCKEDITOR_ENABLE_SOCIETE, ROWS_5, '90%'); - $out=$doleditor->Create(1); + $doleditor = new DolEditor($keyprefix.$key.$keysuffix, $value, '', 200, 'dolibarr_notes', 'In', false, false, !empty($conf->fckeditor->enabled) && $conf->global->FCKEDITOR_ENABLE_SOCIETE, ROWS_5, '90%'); + $out = $doleditor->Create(1); } else { - $out=''; + $out = ''; } } elseif ($type == 'boolean') { if (empty($mode)) { - $checked=''; + $checked = ''; if (!empty($value)) { - $checked=' checked value="1" '; + $checked = ' checked value="1" '; } else { - $checked=' value="1" '; + $checked = ' value="1" '; } - $out=''; + $out = ''; } else { - $out.=$form->selectyesno($keyprefix.$key.$keysuffix, $value, 1, false, 1); + $out .= $form->selectyesno($keyprefix.$key.$keysuffix, $value, 1, false, 1); } } elseif ($type == 'price') { if (!empty($value)) { // $value in memory is a php numeric, we format it into user number format. - $value=price($value); + $value = price($value); } - $out=' '.$langs->getCurrencySymbol($conf->currency); + $out = ' '.$langs->getCurrencySymbol($conf->currency); } elseif ($type == 'double') { if (!empty($value)) { // $value in memory is a php numeric, we format it into user number format. - $value=price($value); + $value = price($value); } - $out=' '; + $out = ' '; } elseif ($type == 'select') { $out = ''; - if (! empty($conf->use_javascript_ajax) && ! empty($conf->global->MAIN_EXTRAFIELDS_USE_SELECT2)) + if (!empty($conf->use_javascript_ajax) && !empty($conf->global->MAIN_EXTRAFIELDS_USE_SELECT2)) { - include_once DOL_DOCUMENT_ROOT . '/core/lib/ajax.lib.php'; - $out.= ajax_combobox($keyprefix.$key.$keysuffix, array(), 0); + include_once DOL_DOCUMENT_ROOT.'/core/lib/ajax.lib.php'; + $out .= ajax_combobox($keyprefix.$key.$keysuffix, array(), 0); } - $out.=''; + $out .= ''; foreach ($param['options'] as $key => $val) { if ((string) $key == '') continue; list($val, $parent) = explode('|', $val); - $out.=''; + $out .= ''; } - $out.=''; + $out .= ''; } elseif ($type == 'sellist') { $out = ''; - if (! empty($conf->use_javascript_ajax) && ! empty($conf->global->MAIN_EXTRAFIELDS_USE_SELECT2)) + if (!empty($conf->use_javascript_ajax) && !empty($conf->global->MAIN_EXTRAFIELDS_USE_SELECT2)) { - include_once DOL_DOCUMENT_ROOT . '/core/lib/ajax.lib.php'; - $out.= ajax_combobox($keyprefix.$key.$keysuffix, array(), 0); + include_once DOL_DOCUMENT_ROOT.'/core/lib/ajax.lib.php'; + $out .= ajax_combobox($keyprefix.$key.$keysuffix, array(), 0); } - $out.=''; if (is_array($param['options'])) { - $param_list=array_keys($param['options']); + $param_list = array_keys($param['options']); $InfoFieldList = explode(":", $param_list[0]); - $parentName=''; - $parentField=''; + $parentName = ''; + $parentField = ''; // 0 : tableName // 1 : label field name // 2 : key fields name (if differ of rowid) @@ -1202,22 +1199,22 @@ class ExtraFields // 4 : where clause filter on column or table extrafield, syntax field='value' or extra.field=value // 5 : id category type // 6 : ids categories list separated by comma for category root - $keyList=(empty($InfoFieldList[2])?'rowid':$InfoFieldList[2].' as rowid'); + $keyList = (empty($InfoFieldList[2]) ? 'rowid' : $InfoFieldList[2].' as rowid'); - if (count($InfoFieldList) > 4 && ! empty($InfoFieldList[4])) + if (count($InfoFieldList) > 4 && !empty($InfoFieldList[4])) { if (strpos($InfoFieldList[4], 'extra.') !== false) { - $keyList='main.'.$InfoFieldList[2].' as rowid'; + $keyList = 'main.'.$InfoFieldList[2].' as rowid'; } else { - $keyList=$InfoFieldList[2].' as rowid'; + $keyList = $InfoFieldList[2].' as rowid'; } } - if (count($InfoFieldList) > 3 && ! empty($InfoFieldList[3])) + if (count($InfoFieldList) > 3 && !empty($InfoFieldList[3])) { list($parentName, $parentField) = explode('|', $InfoFieldList[3]); - $keyList.= ', '.$parentField; + $keyList .= ', '.$parentField; } $filter_categorie = false; @@ -1235,8 +1232,8 @@ class ExtraFields } $sqlwhere = ''; - $sql = 'SELECT ' . $keyList; - $sql .= ' FROM ' . MAIN_DB_PREFIX . $InfoFieldList[0]; + $sql = 'SELECT '.$keyList; + $sql .= ' FROM '.MAIN_DB_PREFIX.$InfoFieldList[0]; if (!empty($InfoFieldList[4])) { // can use curent entity filter if (strpos($InfoFieldList[4], '$ENTITY$') !== false) { @@ -1255,24 +1252,24 @@ class ExtraFields } //We have to join on extrafield table if (strpos($InfoFieldList[4], 'extra') !== false) { - $sql .= ' as main, ' . MAIN_DB_PREFIX . $InfoFieldList[0] . '_extrafields as extra'; - $sqlwhere .= ' WHERE extra.fk_object=main.' . $InfoFieldList[2] . ' AND ' . $InfoFieldList[4]; + $sql .= ' as main, '.MAIN_DB_PREFIX.$InfoFieldList[0].'_extrafields as extra'; + $sqlwhere .= ' WHERE extra.fk_object=main.'.$InfoFieldList[2].' AND '.$InfoFieldList[4]; } else { - $sqlwhere .= ' WHERE ' . $InfoFieldList[4]; + $sqlwhere .= ' WHERE '.$InfoFieldList[4]; } } else { $sqlwhere .= ' WHERE 1=1'; } // Some tables may have field, some other not. For the moment we disable it. if (in_array($InfoFieldList[0], array('tablewithentity'))) { - $sqlwhere .= ' AND entity = ' . $conf->entity; + $sqlwhere .= ' AND entity = '.$conf->entity; } $sql .= $sqlwhere; //print $sql; - $sql .= ' ORDER BY ' . implode(', ', $fields_label); + $sql .= ' ORDER BY '.implode(', ', $fields_label); - dol_syslog(get_class($this) . '::showInputField type=sellist', LOG_DEBUG); + dol_syslog(get_class($this).'::showInputField type=sellist', LOG_DEBUG); $resql = $this->db->query($sql); if ($resql) { $out .= ''; @@ -1288,7 +1285,7 @@ class ExtraFields if (is_array($fields_label) && count($fields_label) > 1) { $notrans = true; foreach ($fields_label as $field_toshow) { - $labeltoshow .= $obj->$field_toshow . ' '; + $labeltoshow .= $obj->$field_toshow.' '; } } else { $labeltoshow = $obj->{$InfoFieldList[1]}; @@ -1299,10 +1296,10 @@ class ExtraFields if (!$notrans) { foreach ($fields_label as $field_toshow) { $translabel = $langs->trans($obj->$field_toshow); - $labeltoshow = dol_trunc($translabel, 18) . ' '; + $labeltoshow = dol_trunc($translabel, 18).' '; } } - $out .= ''; + $out .= ''; } else { if (!$notrans) { $translabel = $langs->trans($obj->{$InfoFieldList[1]}); @@ -1311,48 +1308,48 @@ class ExtraFields if (empty($labeltoshow)) $labeltoshow = '(not defined)'; if (!empty($InfoFieldList[3]) && $parentField) { - $parent = $parentName . ':' . $obj->{$parentField}; + $parent = $parentName.':'.$obj->{$parentField}; } - $out .= ''; + $out .= (!empty($parent) ? ' parent="'.$parent.'"' : ''); + $out .= '>'.$labeltoshow.''; } $i++; } $this->db->free($resql); } else { - print 'Error in request ' . $sql . ' ' . $this->db->lasterror() . '. Check setup of extra parameters.
'; + print 'Error in request '.$sql.' '.$this->db->lasterror().'. Check setup of extra parameters.
'; } } else { $data = $form->select_all_categories(Categorie::$MAP_ID_TO_CODE[$InfoFieldList[5]], '', 'parent', 64, $InfoFieldList[6], 1, 1); $out .= ''; foreach ($data as $data_key => $data_value) { - $out .= ''; } } } - $out.=''; + $out .= ''; } elseif ($type == 'checkbox') { - $value_arr=explode(',', $value); - $out=$form->multiselectarray($keyprefix.$key.$keysuffix, (empty($param['options'])?null:$param['options']), $value_arr, '', 0, '', 0, '100%'); + $value_arr = explode(',', $value); + $out = $form->multiselectarray($keyprefix.$key.$keysuffix, (empty($param['options']) ?null:$param['options']), $value_arr, '', 0, '', 0, '100%'); } elseif ($type == 'radio') { - $out=''; + $out = ''; foreach ($param['options'] as $keyopt => $val) { - $out.=''.$val.'
'; + $out .= ''.$val.'
'; } } elseif ($type == 'chkbxlst') @@ -1367,8 +1364,8 @@ class ExtraFields if (is_array($param['options'])) { $param_list = array_keys($param['options']); $InfoFieldList = explode(":", $param_list[0]); - $parentName=''; - $parentField=''; + $parentName = ''; + $parentField = ''; // 0 : tableName // 1 : label field name // 2 : key fields name (if differ of rowid) @@ -1376,17 +1373,17 @@ class ExtraFields // 4 : where clause filter on column or table extrafield, syntax field='value' or extra.field=value // 5 : id category type // 6 : ids categories list separated by comma for category root - $keyList = (empty($InfoFieldList[2]) ? 'rowid' : $InfoFieldList[2] . ' as rowid'); + $keyList = (empty($InfoFieldList[2]) ? 'rowid' : $InfoFieldList[2].' as rowid'); - if (count($InfoFieldList) > 3 && ! empty($InfoFieldList[3])) { - list ( $parentName, $parentField ) = explode('|', $InfoFieldList[3]); - $keyList .= ', ' . $parentField; + if (count($InfoFieldList) > 3 && !empty($InfoFieldList[3])) { + list ($parentName, $parentField) = explode('|', $InfoFieldList[3]); + $keyList .= ', '.$parentField; } - if (count($InfoFieldList) > 4 && ! empty($InfoFieldList[4])) { + if (count($InfoFieldList) > 4 && !empty($InfoFieldList[4])) { if (strpos($InfoFieldList[4], 'extra.') !== false) { - $keyList = 'main.' . $InfoFieldList[2] . ' as rowid'; + $keyList = 'main.'.$InfoFieldList[2].' as rowid'; } else { - $keyList = $InfoFieldList[2] . ' as rowid'; + $keyList = $InfoFieldList[2].' as rowid'; } } @@ -1405,8 +1402,8 @@ class ExtraFields } $sqlwhere = ''; - $sql = 'SELECT ' . $keyList; - $sql .= ' FROM ' . MAIN_DB_PREFIX . $InfoFieldList[0]; + $sql = 'SELECT '.$keyList; + $sql .= ' FROM '.MAIN_DB_PREFIX.$InfoFieldList[0]; if (!empty($InfoFieldList[4])) { // can use SELECT request if (strpos($InfoFieldList[4], '$SEL$') !== false) { @@ -1429,11 +1426,11 @@ class ExtraFields // Init des compteurs $nbPregRepl = $nbPregSel = 0; // On retire toutes les parenthèses sans = avant - $InfoFieldList[4] = preg_replace('#([^=])(\([^)^(]*(' . $word . ')[^)^(]*\))#', '$1 $3 ', $InfoFieldList[4], -1, $nbPregRepl); + $InfoFieldList[4] = preg_replace('#([^=])(\([^)^(]*('.$word.')[^)^(]*\))#', '$1 $3 ', $InfoFieldList[4], -1, $nbPregRepl); // On retire les espaces autour des = et parenthèses $InfoFieldList[4] = preg_replace('# *(=|\(|\)) *#', '$1', $InfoFieldList[4]); // On retire toutes les parenthèses avec = avant - $InfoFieldList[4] = preg_replace('#\b[a-zA-Z0-9-\.-_]+\b=\([^)^(]*(' . $word . ')[^)^(]*\)#', '$1 ', $InfoFieldList[4], -1, $nbPregSel); + $InfoFieldList[4] = preg_replace('#\b[a-zA-Z0-9-\.-_]+\b=\([^)^(]*('.$word.')[^)^(]*\)#', '$1 ', $InfoFieldList[4], -1, $nbPregSel); // On retire les espaces autour des = et parenthèses $InfoFieldList[4] = preg_replace('# *(=|\(|\)) *#', '$1', $InfoFieldList[4]); @@ -1442,7 +1439,7 @@ class ExtraFields } // Si l'on a un AND ou un OR, avant ou après - preg_match('#(AND|OR|) *(' . $word . ') *(AND|OR|)#', $InfoFieldList[4], $matchCondition); + preg_match('#(AND|OR|) *('.$word.') *(AND|OR|)#', $InfoFieldList[4], $matchCondition); while (!empty($matchCondition[0])) { // If the two sides differ but are not empty if (!empty($matchCondition[1]) && !empty($matchCondition[3]) && $matchCondition[1] != $matchCondition[3]) { @@ -1451,7 +1448,7 @@ class ExtraFields } else { if (!empty($matchCondition[1])) { $boolCond = (($matchCondition[1] == "AND") ? ' AND TRUE ' : ' OR FALSE '); - $InfoFieldList[4] = str_replace($matchCondition[0], $boolCond . $matchCondition[3], $InfoFieldList[4]); + $InfoFieldList[4] = str_replace($matchCondition[0], $boolCond.$matchCondition[3], $InfoFieldList[4]); } elseif (!empty($matchCondition[3])) { $boolCond = (($matchCondition[3] == "AND") ? ' TRUE AND ' : ' FALSE OR'); $InfoFieldList[4] = str_replace($matchCondition[0], $boolCond, $InfoFieldList[4]); @@ -1461,7 +1458,7 @@ class ExtraFields } // Si l'on a un AND ou un OR, avant ou après - preg_match('#(AND|OR|) *(' . $word . ') *(AND|OR|)#', $InfoFieldList[4], $matchCondition); + preg_match('#(AND|OR|) *('.$word.') *(AND|OR|)#', $InfoFieldList[4], $matchCondition); } } else { $InfoFieldList[4] = str_replace('$ID$', '0', $InfoFieldList[4]); @@ -1469,23 +1466,23 @@ class ExtraFields // We have to join on extrafield table if (strpos($InfoFieldList[4], 'extra') !== false) { - $sql .= ' as main, ' . MAIN_DB_PREFIX . $InfoFieldList[0] . '_extrafields as extra'; - $sqlwhere .= ' WHERE extra.fk_object=main.' . $InfoFieldList[2] . ' AND ' . $InfoFieldList[4]; + $sql .= ' as main, '.MAIN_DB_PREFIX.$InfoFieldList[0].'_extrafields as extra'; + $sqlwhere .= ' WHERE extra.fk_object=main.'.$InfoFieldList[2].' AND '.$InfoFieldList[4]; } else { - $sqlwhere .= ' WHERE ' . $InfoFieldList[4]; + $sqlwhere .= ' WHERE '.$InfoFieldList[4]; } } else { $sqlwhere .= ' WHERE 1=1'; } // Some tables may have field, some other not. For the moment we disable it. if (in_array($InfoFieldList[0], array('tablewithentity'))) { - $sqlwhere .= ' AND entity = ' . $conf->entity; + $sqlwhere .= ' AND entity = '.$conf->entity; } // $sql.=preg_replace('/^ AND /','',$sqlwhere); // print $sql; $sql .= $sqlwhere; - dol_syslog(get_class($this) . '::showInputField type=chkbxlst', LOG_DEBUG); + dol_syslog(get_class($this).'::showInputField type=chkbxlst', LOG_DEBUG); $resql = $this->db->query($sql); if ($resql) { $num = $this->db->num_rows($resql); @@ -1503,7 +1500,7 @@ class ExtraFields if (is_array($fields_label)) { $notrans = true; foreach ($fields_label as $field_toshow) { - $labeltoshow .= $obj->$field_toshow . ' '; + $labeltoshow .= $obj->$field_toshow.' '; } } else { $labeltoshow = $obj->{$InfoFieldList[1]}; @@ -1514,9 +1511,9 @@ class ExtraFields foreach ($fields_label as $field_toshow) { $translabel = $langs->trans($obj->$field_toshow); if ($translabel != $obj->$field_toshow) { - $labeltoshow = dol_trunc($translabel, 18) . ' '; + $labeltoshow = dol_trunc($translabel, 18).' '; } else { - $labeltoshow = dol_trunc($obj->$field_toshow, 18) . ' '; + $labeltoshow = dol_trunc($obj->$field_toshow, 18).' '; } } @@ -1538,7 +1535,7 @@ class ExtraFields } if (!empty($InfoFieldList[3]) && $parentField) { - $parent = $parentName . ':' . $obj->{$parentField}; + $parent = $parentName.':'.$obj->{$parentField}; } $data[$obj->rowid] = $labeltoshow; @@ -1656,70 +1653,70 @@ class ExtraFields //$value=price($value); $sizeparts = explode(",", $size); $number_decimals = $sizeparts[1]; - $value=price($value, 0, $langs, 0, 0, $number_decimals, ''); + $value = price($value, 0, $langs, 0, 0, $number_decimals, ''); } } elseif ($type == 'boolean') { - $checked=''; + $checked = ''; if (!empty($value)) { - $checked=' checked '; + $checked = ' checked '; } - $value=''; + $value = ''; } elseif ($type == 'mail') { - $value=dol_print_email($value, 0, 0, 0, 64, 1, 1); + $value = dol_print_email($value, 0, 0, 0, 64, 1, 1); } elseif ($type == 'url') { - $value=dol_print_url($value, '_blank', 32, 1); + $value = dol_print_url($value, '_blank', 32, 1); } elseif ($type == 'phone') { - $value=dol_print_phone($value, '', 0, 0, '', ' ', 'phone'); + $value = dol_print_phone($value, '', 0, 0, '', ' ', 'phone'); } elseif ($type == 'price') { - $value=price($value, 0, $langs, 0, 0, -1, $conf->currency); + $value = price($value, 0, $langs, 0, 0, -1, $conf->currency); } elseif ($type == 'select') { - if ($langfile && $param['options'][$value]) $value=$langs->trans($param['options'][$value]); - else $value=$param['options'][$value]; + if ($langfile && $param['options'][$value]) $value = $langs->trans($param['options'][$value]); + else $value = $param['options'][$value]; } elseif ($type == 'sellist') { - $param_list=array_keys($param['options']); + $param_list = array_keys($param['options']); $InfoFieldList = explode(":", $param_list[0]); - $selectkey="rowid"; - $keyList='rowid'; + $selectkey = "rowid"; + $keyList = 'rowid'; - if (count($InfoFieldList)>=3) + if (count($InfoFieldList) >= 3) { $selectkey = $InfoFieldList[2]; - $keyList=$InfoFieldList[2].' as rowid'; + $keyList = $InfoFieldList[2].' as rowid'; } $fields_label = explode('|', $InfoFieldList[1]); - if(is_array($fields_label)) { - $keyList .=', '; + if (is_array($fields_label)) { + $keyList .= ', '; $keyList .= implode(', ', $fields_label); } $sql = 'SELECT '.$keyList; - $sql.= ' FROM '.MAIN_DB_PREFIX .$InfoFieldList[0]; - if (strpos($InfoFieldList[4], 'extra')!==false) + $sql .= ' FROM '.MAIN_DB_PREFIX.$InfoFieldList[0]; + if (strpos($InfoFieldList[4], 'extra') !== false) { - $sql.= ' as main'; + $sql .= ' as main'; } - if ($selectkey=='rowid' && empty($value)) { - $sql.= " WHERE ".$selectkey."=0"; - } elseif ($selectkey=='rowid') { - $sql.= " WHERE ".$selectkey."=".$this->db->escape($value); - }else { - $sql.= " WHERE ".$selectkey."='".$this->db->escape($value)."'"; + if ($selectkey == 'rowid' && empty($value)) { + $sql .= " WHERE ".$selectkey."=0"; + } elseif ($selectkey == 'rowid') { + $sql .= " WHERE ".$selectkey."=".$this->db->escape($value); + } else { + $sql .= " WHERE ".$selectkey."='".$this->db->escape($value)."'"; } //$sql.= ' AND entity = '.$conf->entity; @@ -1728,38 +1725,38 @@ class ExtraFields $resql = $this->db->query($sql); if ($resql) { - $value=''; // value was used, so now we reste it to use it to build final output + $value = ''; // value was used, so now we reste it to use it to build final output $obj = $this->db->fetch_object($resql); // Several field into label (eq table:code|libelle:rowid) $fields_label = explode('|', $InfoFieldList[1]); - if(is_array($fields_label) && count($fields_label)>1) + if (is_array($fields_label) && count($fields_label) > 1) { foreach ($fields_label as $field_toshow) { - $translabel=''; + $translabel = ''; if (!empty($obj->$field_toshow)) { - $translabel=$langs->trans($obj->$field_toshow); + $translabel = $langs->trans($obj->$field_toshow); } - if ($translabel!=$field_toshow) { - $value.=dol_trunc($translabel, 18).' '; - }else { - $value.=$obj->$field_toshow.' '; + if ($translabel != $field_toshow) { + $value .= dol_trunc($translabel, 18).' '; + } else { + $value .= $obj->$field_toshow.' '; } } } else { - $translabel=''; + $translabel = ''; if (!empty($obj->{$InfoFieldList[1]})) { - $translabel=$langs->trans($obj->{$InfoFieldList[1]}); + $translabel = $langs->trans($obj->{$InfoFieldList[1]}); } - if ($translabel!=$obj->{$InfoFieldList[1]}) { - $value=dol_trunc($translabel, 18); - }else { - $value=$obj->{$InfoFieldList[1]}; + if ($translabel != $obj->{$InfoFieldList[1]}) { + $value = dol_trunc($translabel, 18); + } else { + $value = $obj->{$InfoFieldList[1]}; } } } @@ -1767,20 +1764,20 @@ class ExtraFields } elseif ($type == 'radio') { - $value=$param['options'][$value]; + $value = $param['options'][$value]; } elseif ($type == 'checkbox') { - $value_arr=explode(',', $value); - $value=''; - $toprint=array(); + $value_arr = explode(',', $value); + $value = ''; + $toprint = array(); if (is_array($value_arr)) { foreach ($value_arr as $keyval=>$valueval) { - $toprint[]='
  • '.$param['options'][$valueval].'
  • '; + $toprint[] = '
  • '.$param['options'][$valueval].'
  • '; } } - $value='
      '.implode(' ', $toprint).'
    '; + $value = '
      '.implode(' ', $toprint).'
    '; } elseif ($type == 'chkbxlst') { @@ -1794,7 +1791,7 @@ class ExtraFields if (count($InfoFieldList) >= 3) { $selectkey = $InfoFieldList[2]; - $keyList = $InfoFieldList[2] . ' as rowid'; + $keyList = $InfoFieldList[2].' as rowid'; } $fields_label = explode('|', $InfoFieldList[1]); @@ -1823,53 +1820,53 @@ class ExtraFields if (is_array($fields_label) && count($fields_label) > 1) { foreach ($fields_label as $field_toshow) { $translabel = ''; - if (! empty($obj->$field_toshow)) { + if (!empty($obj->$field_toshow)) { $translabel = $langs->trans($obj->$field_toshow); } if ($translabel != $field_toshow) { - $toprint[]='
  • '.dol_trunc($translabel, 18).'
  • '; + $toprint[] = '
  • '.dol_trunc($translabel, 18).'
  • '; } else { - $toprint[]='
  • '.$obj->$field_toshow.'
  • '; + $toprint[] = '
  • '.$obj->$field_toshow.'
  • '; } } } else { $translabel = ''; - if (! empty($obj->{$InfoFieldList[1]})) { + if (!empty($obj->{$InfoFieldList[1]})) { $translabel = $langs->trans($obj->{$InfoFieldList[1]}); } if ($translabel != $obj->{$InfoFieldList[1]}) { - $toprint[]='
  • '.dol_trunc($translabel, 18).'
  • '; + $toprint[] = '
  • '.dol_trunc($translabel, 18).'
  • '; } else { - $toprint[]='
  • '.$obj->{$InfoFieldList[1]}.'
  • '; + $toprint[] = '
  • '.$obj->{$InfoFieldList[1]}.'
  • '; } } } } - $value='
      '.implode(' ', $toprint).'
    '; + $value = '
      '.implode(' ', $toprint).'
    '; } else { - dol_syslog(get_class($this) . '::showOutputField error ' . $this->db->lasterror(), LOG_WARNING); + dol_syslog(get_class($this).'::showOutputField error '.$this->db->lasterror(), LOG_WARNING); } } elseif ($type == 'link') { - $out=''; + $out = ''; // Only if something to display (perf) if ($value) // If we have -1 here, pb is into insert, not into ouptut (fix insert instead of changing code here to compensate) { - $param_list=array_keys($param['options']); // $param_list='ObjectName:classPath' + $param_list = array_keys($param['options']); // $param_list='ObjectName:classPath' $InfoFieldList = explode(":", $param_list[0]); - $classname=$InfoFieldList[0]; - $classpath=$InfoFieldList[1]; - if (! empty($classpath)) + $classname = $InfoFieldList[0]; + $classpath = $InfoFieldList[1]; + if (!empty($classpath)) { dol_include_once($InfoFieldList[1]); if ($classname && class_exists($classname)) { $object = new $classname($this->db); $object->fetch($value); - $value=$object->getNomUrl(3); + $value = $object->getNomUrl(3); } } else @@ -1881,24 +1878,24 @@ class ExtraFields } elseif ($type == 'text') { - $value=dol_htmlentitiesbr($value); + $value = dol_htmlentitiesbr($value); } elseif ($type == 'html') { - $value=dol_htmlentitiesbr($value); + $value = dol_htmlentitiesbr($value); } elseif ($type == 'password') { - $value=dol_trunc(preg_replace('/./i', '*', $value), 8, 'right', 'UTF-8', 1); + $value = dol_trunc(preg_replace('/./i', '*', $value), 8, 'right', 'UTF-8', 1); } else { - $showsize=round($size); - if ($showsize > 48) $showsize=48; + $showsize = round($size); + if ($showsize > 48) $showsize = 48; } //print $type.'-'.$size; - $out=$value; + $out = $value; return $out; } @@ -1912,44 +1909,44 @@ class ExtraFields */ public function getAlignFlag($key, $extrafieldsobjectkey = '') { - global $conf,$langs; + global $conf, $langs; - if (! empty($extrafieldsobjectkey)) $type=$this->attributes[$extrafieldsobjectkey]['type'][$key]; - else $type=$this->attribute_type[$key]; + if (!empty($extrafieldsobjectkey)) $type = $this->attributes[$extrafieldsobjectkey]['type'][$key]; + else $type = $this->attribute_type[$key]; - $align=''; + $align = ''; if ($type == 'date') { - $align="center"; + $align = "center"; } elseif ($type == 'datetime') { - $align="center"; + $align = "center"; } elseif ($type == 'int') { - $align="right"; + $align = "right"; } elseif ($type == 'double') { - $align="right"; + $align = "right"; } elseif ($type == 'boolean') { - $align="center"; + $align = "center"; } elseif ($type == 'radio') { - $align="center"; + $align = "center"; } elseif ($type == 'checkbox') { - $align="center"; + $align = "center"; } elseif ($type == 'price') { - $align="right"; + $align = "right"; } return $align; @@ -1960,15 +1957,16 @@ class ExtraFields * * @param string $key Key of attribute * @param string $object Object + * @param int $colspan Value of colspan to use (it must includes the first column with title) * @return string HTML code with line for separator */ - public function showSeparator($key, $object) + public function showSeparator($key, $object, $colspan = 2) { global $langs; - $out = ''; + $out = ''; $extrafield_param = $this->attributes[$object->table_element]['param'][$key]; if (!empty($extrafield_param) && is_array($extrafield_param)) { @@ -1985,19 +1983,19 @@ class ExtraFields $out .= ''; - $out.=$this->select_dolusers('', $htmlname, $show_empty, $exclude, $disabled, $include, $enableonly, $force_entity, $maxlength, $showstatus, $morefilter); - $out.=' '; - $out.='
    '; + $out .= ''; + $out .= ''; + $out .= $this->select_dolusers('', $htmlname, $show_empty, $exclude, $disabled, $include, $enableonly, $force_entity, $maxlength, $showstatus, $morefilter); + $out .= ' '; + $out .= '
    '; } - $assignedtouser=array(); + $assignedtouser = array(); if (!empty($_SESSION['assignedtouser'])) { - $assignedtouser=json_decode($_SESSION['assignedtouser'], true); + $assignedtouser = json_decode($_SESSION['assignedtouser'], true); } - $nbassignetouser=count($assignedtouser); + $nbassignetouser = count($assignedtouser); - if ($nbassignetouser && $action != 'view') $out.='
    '; - if ($nbassignetouser) $out.='
      '; - $i=0; $ownerid=0; - foreach($assignedtouser as $key => $value) + if ($nbassignetouser && $action != 'view') $out .= '
      '; + if ($nbassignetouser) $out .= '
        '; + $i = 0; $ownerid = 0; + foreach ($assignedtouser as $key => $value) { if ($value['id'] == $ownerid) continue; - $out.='
      • '; + $out .= '
      • '; $userstatic->fetch($value['id']); - $out.= $userstatic->getNomUrl(-1); - if ($i == 0) { $ownerid = $value['id']; $out.=' ('.$langs->trans("Owner").')'; } + $out .= $userstatic->getNomUrl(-1); + if ($i == 0) { $ownerid = $value['id']; $out .= ' ('.$langs->trans("Owner").')'; } if ($nbassignetouser > 1 && $action != 'view') { - $out.=' '; + $out .= ' '; } // Show my availability if ($showproperties) { if ($ownerid == $value['id'] && is_array($listofuserid) && count($listofuserid) && in_array($ownerid, array_keys($listofuserid))) { - $out.='
        '; - $out.=' - '.$langs->trans("Availability").': '.$langs->trans("Busy"); - $out.='
        '; + $out .= '
        '; + $out .= ' - '.$langs->trans("Availability").': '.$langs->trans("Busy"); + $out .= '
        '; } } //$out.=' '.($value['mandatory']?$langs->trans("Mandatory"):$langs->trans("Optional")); //$out.=' '.($value['transparency']?$langs->trans("Busy"):$langs->trans("NotBusy")); - $out.='
      • '; + $out .= ''; $i++; } - if ($nbassignetouser) $out.='
      '; + if ($nbassignetouser) $out .= '
    '; //$out.=''; return $out; @@ -1897,31 +1897,31 @@ class Form public function select_produits($selected = '', $htmlname = 'productid', $filtertype = '', $limit = 20, $price_level = 0, $status = 1, $finished = 2, $selected_input_value = '', $hidelabel = 0, $ajaxoptions = array(), $socid = 0, $showempty = '1', $forcecombo = 0, $morecss = '', $hidepriceinlabel = 0, $warehouseStatus = '', $selected_combinations = array()) { // phpcs:enable - global $langs,$conf; + global $langs, $conf; // check parameters - $price_level = (! empty($price_level) ? $price_level : 0); - if (is_null($ajaxoptions)) $ajaxoptions=array(); + $price_level = (!empty($price_level) ? $price_level : 0); + if (is_null($ajaxoptions)) $ajaxoptions = array(); - if(strval($filtertype) === '' && (!empty($conf->product->enabled) || !empty($conf->service->enabled))){ - if(!empty($conf->product->enabled) && empty($conf->service->enabled)){ + if (strval($filtertype) === '' && (!empty($conf->product->enabled) || !empty($conf->service->enabled))) { + if (!empty($conf->product->enabled) && empty($conf->service->enabled)) { $filtertype = '0'; } - elseif(empty($conf->product->enabled) && !empty($conf->service->enabled)){ + elseif (empty($conf->product->enabled) && !empty($conf->service->enabled)) { $filtertype = '1'; } } - if (! empty($conf->use_javascript_ajax) && ! empty($conf->global->PRODUIT_USE_SEARCH_TO_SELECT)) + if (!empty($conf->use_javascript_ajax) && !empty($conf->global->PRODUIT_USE_SEARCH_TO_SELECT)) { - $placeholder=''; + $placeholder = ''; if ($selected && empty($selected_input_value)) { require_once DOL_DOCUMENT_ROOT.'/product/class/product.class.php'; $producttmpselect = new Product($this->db); $producttmpselect->fetch($selected); - $selected_input_value=$producttmpselect->ref; + $selected_input_value = $producttmpselect->ref; unset($producttmpselect); } // handle case where product or service module is disabled + no filter specified @@ -1935,10 +1935,10 @@ class Form } } // mode=1 means customers products - $urloption='htmlname='.$htmlname.'&outjson=1&price_level='.$price_level.'&type='.$filtertype.'&mode=1&status='.$status.'&finished='.$finished.'&hidepriceinlabel='.$hidepriceinlabel.'&warehousestatus='.$warehouseStatus; + $urloption = 'htmlname='.$htmlname.'&outjson=1&price_level='.$price_level.'&type='.$filtertype.'&mode=1&status='.$status.'&finished='.$finished.'&hidepriceinlabel='.$hidepriceinlabel.'&warehousestatus='.$warehouseStatus; //Price by customer - if (! empty($conf->global->PRODUIT_CUSTOMER_PRICES) && !empty($socid)) { - $urloption.='&socid='.$socid; + if (!empty($conf->global->PRODUIT_CUSTOMER_PRICES) && !empty($socid)) { + $urloption .= '&socid='.$socid; } print ajax_autocompleter($selected, $htmlname, DOL_URL_ROOT.'/product/ajax/products.php', $urloption, $conf->global->PRODUIT_USE_SEARCH_TO_SELECT, 0, $ajaxoptions); @@ -2017,7 +2017,7 @@ class Form } if (empty($hidelabel)) print $langs->trans("RefOrLabel").' : '; elseif ($hidelabel > 1) { - $placeholder=' placeholder="'.$langs->trans("RefOrLabel").'"'; + $placeholder = ' placeholder="'.$langs->trans("RefOrLabel").'"'; if ($hidelabel == 2) { print img_picto($langs->trans("Search"), 'search'); } @@ -2060,10 +2060,10 @@ class Form public function select_produits_list($selected = '', $htmlname = 'productid', $filtertype = '', $limit = 20, $price_level = 0, $filterkey = '', $status = 1, $finished = 2, $outputmode = 0, $socid = 0, $showempty = '1', $forcecombo = 0, $morecss = '', $hidepriceinlabel = 0, $warehouseStatus = '') { // phpcs:enable - global $langs,$conf,$user,$db; + global $langs, $conf, $user, $db; - $out=''; - $outarray=array(); + $out = ''; + $outarray = array(); // Units if ($conf->global->PRODUCT_USE_UNITS) { @@ -2071,7 +2071,7 @@ class Form } $warehouseStatusArray = array(); - if (! empty($warehouseStatus)) + if (!empty($warehouseStatus)) { require_once DOL_DOCUMENT_ROOT.'/product/stock/class/entrepot.class.php'; if (preg_match('/warehouseclosed/', $warehouseStatus)) @@ -2091,7 +2091,7 @@ class Form $selectFields = " p.rowid, p.label, p.ref, p.description, p.barcode, p.fk_product_type, p.price, p.price_ttc, p.price_base_type, p.tva_tx, p.duration, p.fk_price_expression"; if (count($warehouseStatusArray)) { - $selectFieldsGrouped = ", sum(".$db->ifsql("e.statut IS NULL", "0", "ps.reel").") as stock"; // e.statut is null if there is no record in stock + $selectFieldsGrouped = ", sum(".$db->ifsql("e.statut IS NULL", "0", "ps.reel").") as stock"; // e.statut is null if there is no record in stock } else { @@ -2099,12 +2099,12 @@ class Form } $sql = "SELECT "; - $sql.= $selectFields . $selectFieldsGrouped; + $sql .= $selectFields.$selectFieldsGrouped; - if (! empty($conf->global->PRODUCT_SORT_BY_CATEGORY)) + if (!empty($conf->global->PRODUCT_SORT_BY_CATEGORY)) { //Product category - $sql.= ", (SELECT ".MAIN_DB_PREFIX."categorie_product.fk_categorie + $sql .= ", (SELECT ".MAIN_DB_PREFIX."categorie_product.fk_categorie FROM ".MAIN_DB_PREFIX."categorie_product WHERE ".MAIN_DB_PREFIX."categorie_product.fk_product=p.rowid LIMIT 1 @@ -2112,70 +2112,70 @@ class Form } //Price by customer - if (! empty($conf->global->PRODUIT_CUSTOMER_PRICES) && !empty($socid)) + if (!empty($conf->global->PRODUIT_CUSTOMER_PRICES) && !empty($socid)) { - $sql.=', pcp.rowid as idprodcustprice, pcp.price as custprice, pcp.price_ttc as custprice_ttc,'; - $sql.=' pcp.price_base_type as custprice_base_type, pcp.tva_tx as custtva_tx'; - $selectFields.= ", idprodcustprice, custprice, custprice_ttc, custprice_base_type, custtva_tx"; + $sql .= ', pcp.rowid as idprodcustprice, pcp.price as custprice, pcp.price_ttc as custprice_ttc,'; + $sql .= ' pcp.price_base_type as custprice_base_type, pcp.tva_tx as custtva_tx'; + $selectFields .= ", idprodcustprice, custprice, custprice_ttc, custprice_base_type, custtva_tx"; } // Units - if (! empty($conf->global->PRODUCT_USE_UNITS)) { + if (!empty($conf->global->PRODUCT_USE_UNITS)) { $sql .= ", u.label as unit_long, u.short_label as unit_short, p.weight, p.weight_units, p.length, p.length_units, p.width, p.width_units, p.height, p.height_units, p.surface, p.surface_units, p.volume, p.volume_units"; $selectFields .= ', unit_long, unit_short, p.weight, p.weight_units, p.length, p.length_units, p.width, p.width_units, p.height, p.height_units, p.surface, p.surface_units, p.volume, p.volume_units'; } // Multilang : we add translation - if (! empty($conf->global->MAIN_MULTILANGS)) + if (!empty($conf->global->MAIN_MULTILANGS)) { - $sql.= ", pl.label as label_translated"; - $selectFields.= ", label_translated"; + $sql .= ", pl.label as label_translated"; + $selectFields .= ", label_translated"; } // Price by quantity - if (! empty($conf->global->PRODUIT_CUSTOMER_PRICES_BY_QTY) || !empty($conf->global->PRODUIT_CUSTOMER_PRICES_BY_QTY_MULTIPRICES)) + if (!empty($conf->global->PRODUIT_CUSTOMER_PRICES_BY_QTY) || !empty($conf->global->PRODUIT_CUSTOMER_PRICES_BY_QTY_MULTIPRICES)) { - $sql.= ", (SELECT pp.rowid FROM ".MAIN_DB_PREFIX."product_price as pp WHERE pp.fk_product = p.rowid"; - if ($price_level >= 1 && !empty($conf->global->PRODUIT_CUSTOMER_PRICES_BY_QTY_MULTIPRICES)) $sql.= " AND price_level=".$price_level; - $sql.= " ORDER BY date_price"; - $sql.= " DESC LIMIT 1) as price_rowid"; - $sql.= ", (SELECT pp.price_by_qty FROM ".MAIN_DB_PREFIX."product_price as pp WHERE pp.fk_product = p.rowid"; // price_by_qty is 1 if some prices by qty exists in subtable - if ($price_level >= 1 && !empty($conf->global->PRODUIT_CUSTOMER_PRICES_BY_QTY_MULTIPRICES)) $sql.= " AND price_level=".$price_level; - $sql.= " ORDER BY date_price"; - $sql.= " DESC LIMIT 1) as price_by_qty"; - $selectFields.= ", price_rowid, price_by_qty"; + $sql .= ", (SELECT pp.rowid FROM ".MAIN_DB_PREFIX."product_price as pp WHERE pp.fk_product = p.rowid"; + if ($price_level >= 1 && !empty($conf->global->PRODUIT_CUSTOMER_PRICES_BY_QTY_MULTIPRICES)) $sql .= " AND price_level=".$price_level; + $sql .= " ORDER BY date_price"; + $sql .= " DESC LIMIT 1) as price_rowid"; + $sql .= ", (SELECT pp.price_by_qty FROM ".MAIN_DB_PREFIX."product_price as pp WHERE pp.fk_product = p.rowid"; // price_by_qty is 1 if some prices by qty exists in subtable + if ($price_level >= 1 && !empty($conf->global->PRODUIT_CUSTOMER_PRICES_BY_QTY_MULTIPRICES)) $sql .= " AND price_level=".$price_level; + $sql .= " ORDER BY date_price"; + $sql .= " DESC LIMIT 1) as price_by_qty"; + $selectFields .= ", price_rowid, price_by_qty"; } - $sql.= " FROM ".MAIN_DB_PREFIX."product as p"; + $sql .= " FROM ".MAIN_DB_PREFIX."product as p"; if (count($warehouseStatusArray)) { - $sql.= " LEFT JOIN ".MAIN_DB_PREFIX."product_stock as ps on ps.fk_product = p.rowid"; - $sql.= " LEFT JOIN ".MAIN_DB_PREFIX."entrepot as e on ps.fk_entrepot = e.rowid AND e.entity IN (".getEntity('stock').")"; - $sql.= ' AND e.statut IN ('.$this->db->escape(implode(',', $warehouseStatusArray)).')'; // Return line if product is inside the selected stock. If not, an empty line will be returned so we will count 0. + $sql .= " LEFT JOIN ".MAIN_DB_PREFIX."product_stock as ps on ps.fk_product = p.rowid"; + $sql .= " LEFT JOIN ".MAIN_DB_PREFIX."entrepot as e on ps.fk_entrepot = e.rowid AND e.entity IN (".getEntity('stock').")"; + $sql .= ' AND e.statut IN ('.$this->db->escape(implode(',', $warehouseStatusArray)).')'; // Return line if product is inside the selected stock. If not, an empty line will be returned so we will count 0. } // include search in supplier ref - if(!empty($conf->global->MAIN_SEARCH_PRODUCT_BY_FOURN_REF)) + if (!empty($conf->global->MAIN_SEARCH_PRODUCT_BY_FOURN_REF)) { - $sql.= " LEFT JOIN ".MAIN_DB_PREFIX."product_fournisseur_price as pfp ON p.rowid = pfp.fk_product"; + $sql .= " LEFT JOIN ".MAIN_DB_PREFIX."product_fournisseur_price as pfp ON p.rowid = pfp.fk_product"; } //Price by customer - if (! empty($conf->global->PRODUIT_CUSTOMER_PRICES) && !empty($socid)) { - $sql.=" LEFT JOIN ".MAIN_DB_PREFIX."product_customer_price as pcp ON pcp.fk_soc=".$socid." AND pcp.fk_product=p.rowid"; + if (!empty($conf->global->PRODUIT_CUSTOMER_PRICES) && !empty($socid)) { + $sql .= " LEFT JOIN ".MAIN_DB_PREFIX."product_customer_price as pcp ON pcp.fk_soc=".$socid." AND pcp.fk_product=p.rowid"; } // Units - if (! empty($conf->global->PRODUCT_USE_UNITS)) { - $sql .= " LEFT JOIN " . MAIN_DB_PREFIX . "c_units u ON u.rowid = p.fk_unit"; + if (!empty($conf->global->PRODUCT_USE_UNITS)) { + $sql .= " LEFT JOIN ".MAIN_DB_PREFIX."c_units u ON u.rowid = p.fk_unit"; } // Multilang : we add translation - if (! empty($conf->global->MAIN_MULTILANGS)) + if (!empty($conf->global->MAIN_MULTILANGS)) { - $sql.= " LEFT JOIN ".MAIN_DB_PREFIX."product_lang as pl ON pl.fk_product = p.rowid AND pl.lang='". $langs->getDefaultLang() ."'"; + $sql .= " LEFT JOIN ".MAIN_DB_PREFIX."product_lang as pl ON pl.fk_product = p.rowid AND pl.lang='".$langs->getDefaultLang()."'"; } if (!empty($conf->global->PRODUIT_ATTRIBUTES_HIDECHILD)) { $sql .= " LEFT JOIN ".MAIN_DB_PREFIX."product_attribute_combination pac ON pac.fk_product_child = p.rowid"; } - $sql.= ' WHERE p.entity IN ('.getEntity('product').')'; + $sql .= ' WHERE p.entity IN ('.getEntity('product').')'; if (!empty($conf->global->PRODUIT_ATTRIBUTES_HIDECHILD)) { $sql .= " AND pac.rowid IS NULL"; @@ -2183,103 +2183,103 @@ class Form if ($finished == 0) { - $sql.= " AND p.finished = ".$finished; + $sql .= " AND p.finished = ".$finished; } elseif ($finished == 1) { - $sql.= " AND p.finished = ".$finished; - if ($status >= 0) $sql.= " AND p.tosell = ".$status; + $sql .= " AND p.finished = ".$finished; + if ($status >= 0) $sql .= " AND p.tosell = ".$status; } elseif ($status >= 0) { - $sql.= " AND p.tosell = ".$status; + $sql .= " AND p.tosell = ".$status; } // Filter by product type - if (strval($filtertype) != '') $sql.= " AND p.fk_product_type = ".$filtertype; + if (strval($filtertype) != '') $sql .= " AND p.fk_product_type = ".$filtertype; elseif (empty($conf->product->enabled)) { // when product module is disabled, show services only - $sql.= " AND p.fk_product_type = 1"; + $sql .= " AND p.fk_product_type = 1"; } elseif (empty($conf->service->enabled)) { // when service module is disabled, show products only - $sql.= " AND p.fk_product_type = 0"; + $sql .= " AND p.fk_product_type = 0"; } // Add criteria on ref/label if ($filterkey != '') { - $sql.=' AND ('; - $prefix=empty($conf->global->PRODUCT_DONOTSEARCH_ANYWHERE)?'%':''; // Can use index if PRODUCT_DONOTSEARCH_ANYWHERE is on + $sql .= ' AND ('; + $prefix = empty($conf->global->PRODUCT_DONOTSEARCH_ANYWHERE) ? '%' : ''; // Can use index if PRODUCT_DONOTSEARCH_ANYWHERE is on // For natural search $scrit = explode(' ', $filterkey); - $i=0; - if (count($scrit) > 1) $sql.="("; + $i = 0; + if (count($scrit) > 1) $sql .= "("; foreach ($scrit as $crit) { - if ($i > 0) $sql.=" AND "; - $sql.="(p.ref LIKE '".$db->escape($prefix.$crit)."%' OR p.label LIKE '".$db->escape($prefix.$crit)."%'"; - if (! empty($conf->global->MAIN_MULTILANGS)) $sql.=" OR pl.label LIKE '".$db->escape($prefix.$crit)."%'"; + if ($i > 0) $sql .= " AND "; + $sql .= "(p.ref LIKE '".$db->escape($prefix.$crit)."%' OR p.label LIKE '".$db->escape($prefix.$crit)."%'"; + if (!empty($conf->global->MAIN_MULTILANGS)) $sql .= " OR pl.label LIKE '".$db->escape($prefix.$crit)."%'"; if (!empty($conf->global->PRODUCT_AJAX_SEARCH_ON_DESCRIPTION)) { - $sql.=" OR p.description LIKE '".$db->escape($prefix.$crit)."%'"; - if (! empty($conf->global->MAIN_MULTILANGS)) $sql.=" OR pl.description LIKE '".$db->escape($prefix.$crit)."%'"; + $sql .= " OR p.description LIKE '".$db->escape($prefix.$crit)."%'"; + if (!empty($conf->global->MAIN_MULTILANGS)) $sql .= " OR pl.description LIKE '".$db->escape($prefix.$crit)."%'"; } - if (! empty($conf->global->MAIN_SEARCH_PRODUCT_BY_FOURN_REF)) $sql.=" OR pfp.ref_fourn LIKE '".$db->escape($prefix.$crit)."%'"; - $sql.=")"; + if (!empty($conf->global->MAIN_SEARCH_PRODUCT_BY_FOURN_REF)) $sql .= " OR pfp.ref_fourn LIKE '".$db->escape($prefix.$crit)."%'"; + $sql .= ")"; $i++; } - if (count($scrit) > 1) $sql.=")"; - if (! empty($conf->barcode->enabled)) $sql.= " OR p.barcode LIKE '".$db->escape($prefix.$filterkey)."%'"; - $sql.=')'; + if (count($scrit) > 1) $sql .= ")"; + if (!empty($conf->barcode->enabled)) $sql .= " OR p.barcode LIKE '".$db->escape($prefix.$filterkey)."%'"; + $sql .= ')'; } if (count($warehouseStatusArray)) { - $sql.= ' GROUP BY'.$selectFields; + $sql .= ' GROUP BY'.$selectFields; } //Sort by category - if(! empty($conf->global->PRODUCT_SORT_BY_CATEGORY)) + if (!empty($conf->global->PRODUCT_SORT_BY_CATEGORY)) { $sql .= " ORDER BY categorie_product_id "; //ASC OR DESC order - ($conf->global->PRODUCT_SORT_BY_CATEGORY == 1) ? $sql .="ASC" : $sql .="DESC"; + ($conf->global->PRODUCT_SORT_BY_CATEGORY == 1) ? $sql .= "ASC" : $sql .= "DESC"; } else { - $sql.= $db->order("p.ref"); + $sql .= $db->order("p.ref"); } - $sql.= $db->plimit($limit, 0); + $sql .= $db->plimit($limit, 0); // Build output string dol_syslog(get_class($this)."::select_produits_list search product", LOG_DEBUG); - $result=$this->db->query($sql); + $result = $this->db->query($sql); if ($result) { require_once DOL_DOCUMENT_ROOT.'/product/class/product.class.php'; require_once DOL_DOCUMENT_ROOT.'/product/dynamic_price/class/price_parser.class.php'; $num = $this->db->num_rows($result); - $events=null; + $events = null; - if (! $forcecombo) + if (!$forcecombo) { - include_once DOL_DOCUMENT_ROOT . '/core/lib/ajax.lib.php'; + include_once DOL_DOCUMENT_ROOT.'/core/lib/ajax.lib.php'; $out .= ajax_combobox($htmlname, $events, $conf->global->PRODUIT_USE_SEARCH_TO_SELECT); } - $out.=''; - $textifempty=''; + $textifempty = ''; // Do not use textifempty = ' ' or ' ' here, or search on key will search on ' key'. //if (! empty($conf->use_javascript_ajax) || $forcecombo) $textifempty=''; - if (! empty($conf->global->PRODUIT_USE_SEARCH_TO_SELECT)) + if (!empty($conf->global->PRODUIT_USE_SEARCH_TO_SELECT)) { - if ($showempty && ! is_numeric($showempty)) $textifempty=$langs->trans($showempty); - else $textifempty.=$langs->trans("All"); + if ($showempty && !is_numeric($showempty)) $textifempty = $langs->trans($showempty); + else $textifempty .= $langs->trans("All"); } else { - if ($showempty && ! is_numeric($showempty)) $textifempty=$langs->trans($showempty); + if ($showempty && !is_numeric($showempty)) $textifempty = $langs->trans($showempty); } - if ($showempty) $out.=''; + if ($showempty) $out .= ''; $i = 0; while ($num && $i < $num) @@ -2291,9 +2291,9 @@ class Form if ((!empty($conf->global->PRODUIT_CUSTOMER_PRICES_BY_QTY) || !empty($conf->global->PRODUIT_CUSTOMER_PRICES_BY_QTY_MULTIPRICES)) && !empty($objp->price_by_qty) && $objp->price_by_qty == 1) { // Price by quantity will return many prices for the same product $sql = "SELECT rowid, quantity, price, unitprice, remise_percent, remise, price_base_type"; - $sql.= " FROM ".MAIN_DB_PREFIX."product_price_by_qty"; - $sql.= " WHERE fk_product_price=".$objp->price_rowid; - $sql.= " ORDER BY quantity ASC"; + $sql .= " FROM ".MAIN_DB_PREFIX."product_price_by_qty"; + $sql .= " WHERE fk_product_price=".$objp->price_rowid; + $sql .= " ORDER BY quantity ASC"; dol_syslog(get_class($this)."::select_produits_list search price by qty", LOG_DEBUG); $result2 = $this->db->query($sql); @@ -2323,7 +2323,7 @@ class Form // Add new entry // "key" value of json key array is used by jQuery automatically as selected value // "label" value of json key array is used by jQuery automatically as text for combo box - $out.=$opt; + $out .= $opt; array_push($outarray, $optJson); } } @@ -2347,14 +2347,14 @@ class Form // Add new entry // "key" value of json key array is used by jQuery automatically as selected value // "label" value of json key array is used by jQuery automatically as text for combo box - $out.=$opt; + $out .= $opt; array_push($outarray, $optJson); } $i++; } - $out.=''; + $out .= ''; $this->db->free($result); @@ -2384,59 +2384,59 @@ class Form { global $langs, $conf, $user, $db; - $outkey=''; - $outval=''; - $outref=''; - $outlabel=''; - $outdesc=''; - $outbarcode=''; - $outtype=''; - $outprice_ht=''; - $outprice_ttc=''; - $outpricebasetype=''; - $outtva_tx=''; - $outqty=1; - $outdiscount=0; + $outkey = ''; + $outval = ''; + $outref = ''; + $outlabel = ''; + $outdesc = ''; + $outbarcode = ''; + $outtype = ''; + $outprice_ht = ''; + $outprice_ttc = ''; + $outpricebasetype = ''; + $outtva_tx = ''; + $outqty = 1; + $outdiscount = 0; - $maxlengtharticle=(empty($conf->global->PRODUCT_MAX_LENGTH_COMBO)?48:$conf->global->PRODUCT_MAX_LENGTH_COMBO); + $maxlengtharticle = (empty($conf->global->PRODUCT_MAX_LENGTH_COMBO) ? 48 : $conf->global->PRODUCT_MAX_LENGTH_COMBO); - $label=$objp->label; - if (! empty($objp->label_translated)) $label=$objp->label_translated; - if (! empty($filterkey) && $filterkey != '') $label=preg_replace('/('.preg_quote($filterkey).')/i', '$1', $label, 1); + $label = $objp->label; + if (!empty($objp->label_translated)) $label = $objp->label_translated; + if (!empty($filterkey) && $filterkey != '') $label = preg_replace('/('.preg_quote($filterkey).')/i', '$1', $label, 1); - $outkey=$objp->rowid; - $outref=$objp->ref; - $outlabel=$objp->label; - $outdesc=$objp->description; - $outbarcode=$objp->barcode; + $outkey = $objp->rowid; + $outref = $objp->ref; + $outlabel = $objp->label; + $outdesc = $objp->description; + $outbarcode = $objp->barcode; - $outtype=$objp->fk_product_type; - $outdurationvalue=$outtype == Product::TYPE_SERVICE?substr($objp->duration, 0, dol_strlen($objp->duration)-1):''; - $outdurationunit=$outtype == Product::TYPE_SERVICE?substr($objp->duration, -1):''; + $outtype = $objp->fk_product_type; + $outdurationvalue = $outtype == Product::TYPE_SERVICE ?substr($objp->duration, 0, dol_strlen($objp->duration) - 1) : ''; + $outdurationunit = $outtype == Product::TYPE_SERVICE ?substr($objp->duration, -1) : ''; // Units $outvalUnits = ''; - if (! empty($conf->global->PRODUCT_USE_UNITS)) { + if (!empty($conf->global->PRODUCT_USE_UNITS)) { if (!empty($objp->unit_short)) { - $outvalUnits .= ' - ' . $objp->unit_short; + $outvalUnits .= ' - '.$objp->unit_short; } } - if (! empty($conf->global->PRODUCT_SHOW_DIMENSIONS_IN_COMBO)) { - if (!empty($objp->weight) && $objp->weight_units!==null) { + if (!empty($conf->global->PRODUCT_SHOW_DIMENSIONS_IN_COMBO)) { + if (!empty($objp->weight) && $objp->weight_units !== null) { $unitToShow = showDimensionInBestUnit($objp->weight, $objp->weight_units, 'weight', $langs); - $outvalUnits .= ' - ' . $unitToShow; + $outvalUnits .= ' - '.$unitToShow; } - if ((!empty($objp->length) || !empty($objp->width) || !empty($objp->height)) && $objp->length_units!==null) { - $unitToShow = $objp->length . ' x ' . $objp->width . ' x ' . $objp->height . ' ' . measuringUnitString(0, 'size', $objp->length_units); - $outvalUnits .= ' - ' . $unitToShow; + if ((!empty($objp->length) || !empty($objp->width) || !empty($objp->height)) && $objp->length_units !== null) { + $unitToShow = $objp->length.' x '.$objp->width.' x '.$objp->height.' '.measuringUnitString(0, 'size', $objp->length_units); + $outvalUnits .= ' - '.$unitToShow; } - if (!empty($objp->surface) && $objp->surface_units!==null) { + if (!empty($objp->surface) && $objp->surface_units !== null) { $unitToShow = showDimensionInBestUnit($objp->surface, $objp->surface_units, 'surface', $langs); - $outvalUnits .= ' - ' . $unitToShow; + $outvalUnits .= ' - '.$unitToShow; } - if (!empty($objp->volume) && $objp->volume_units!==null) { + if (!empty($objp->volume) && $objp->volume_units !== null) { $unitToShow = showDimensionInBestUnit($objp->volume, $objp->volume_units, 'volume', $langs); - $outvalUnits .= ' - ' . $unitToShow; + $outvalUnits .= ' - '.$unitToShow; } } if ($outdurationvalue && $outdurationunit) { @@ -2448,50 +2448,50 @@ class Form 'y' => $langs->trans('Year') ); if (isset($da[$outdurationunit])) { - $outvalUnits .= ' - ' . $outdurationvalue . ' ' . $langs->transnoentities($da[$outdurationunit].($outdurationvalue > 1 ? 's' : '')); + $outvalUnits .= ' - '.$outdurationvalue.' '.$langs->transnoentities($da[$outdurationunit].($outdurationvalue > 1 ? 's' : '')); } } $opt = '\n"; + $opt .= "\n"; $optJson = array('key'=>$outkey, 'value'=>$outref, 'label'=>$outval, 'label2'=>$outlabel, 'desc'=>$outdesc, 'type'=>$outtype, 'price_ht'=>price2num($outprice_ht), 'price_ttc'=>price2num($outprice_ttc), 'pricebasetype'=>$outpricebasetype, 'tva_tx'=>$outtva_tx, 'qty'=>$outqty, 'discount'=>$outdiscount, 'duration_value'=>$outdurationvalue, 'duration_unit'=>$outdurationunit); } @@ -2663,25 +2663,25 @@ class Form public function select_produits_fournisseurs($socid, $selected = '', $htmlname = 'productid', $filtertype = '', $filtre = '', $ajaxoptions = array(), $hidelabel = 0, $alsoproductwithnosupplierprice = 0, $morecss = '') { // phpcs:enable - global $langs,$conf; + global $langs, $conf; global $price_level, $status, $finished; - $selected_input_value=''; - if (! empty($conf->use_javascript_ajax) && ! empty($conf->global->PRODUIT_USE_SEARCH_TO_SELECT)) + $selected_input_value = ''; + if (!empty($conf->use_javascript_ajax) && !empty($conf->global->PRODUIT_USE_SEARCH_TO_SELECT)) { if ($selected > 0) { require_once DOL_DOCUMENT_ROOT.'/product/class/product.class.php'; $producttmpselect = new Product($this->db); $producttmpselect->fetch($selected); - $selected_input_value=$producttmpselect->ref; + $selected_input_value = $producttmpselect->ref; unset($producttmpselect); } // mode=2 means suppliers products - $urloption=($socid > 0?'socid='.$socid.'&':'').'htmlname='.$htmlname.'&outjson=1&price_level='.$price_level.'&type='.$filtertype.'&mode=2&status='.$status.'&finished='.$finished.'&alsoproductwithnosupplierprice='.$alsoproductwithnosupplierprice; + $urloption = ($socid > 0 ? 'socid='.$socid.'&' : '').'htmlname='.$htmlname.'&outjson=1&price_level='.$price_level.'&type='.$filtertype.'&mode=2&status='.$status.'&finished='.$finished.'&alsoproductwithnosupplierprice='.$alsoproductwithnosupplierprice; print ajax_autocompleter($selected, $htmlname, DOL_URL_ROOT.'/product/ajax/products.php', $urloption, $conf->global->PRODUIT_USE_SEARCH_TO_SELECT, 0, $ajaxoptions); - print ($hidelabel?'':$langs->trans("RefOrLabel").' : ').''; + print ($hidelabel ? '' : $langs->trans("RefOrLabel").' : ').''; } else { @@ -2709,10 +2709,10 @@ class Form public function select_produits_fournisseurs_list($socid, $selected = '', $htmlname = 'productid', $filtertype = '', $filtre = '', $filterkey = '', $statut = -1, $outputmode = 0, $limit = 100, $alsoproductwithnosupplierprice = 0, $morecss = '') { // phpcs:enable - global $langs,$conf,$db; + global $langs, $conf, $db; - $out=''; - $outarray=array(); + $out = ''; + $outarray = array(); $langs->load('stocks'); // Units @@ -2721,55 +2721,55 @@ class Form } $sql = "SELECT p.rowid, p.label, p.ref, p.price, p.duration, p.fk_product_type,"; - $sql.= " pfp.ref_fourn, pfp.rowid as idprodfournprice, pfp.price as fprice, pfp.quantity, pfp.remise_percent, pfp.remise, pfp.unitprice,"; - $sql.= " pfp.fk_supplier_price_expression, pfp.fk_product, pfp.tva_tx, pfp.fk_soc, s.nom as name,"; - $sql.= " pfp.supplier_reputation"; + $sql .= " pfp.ref_fourn, pfp.rowid as idprodfournprice, pfp.price as fprice, pfp.quantity, pfp.remise_percent, pfp.remise, pfp.unitprice,"; + $sql .= " pfp.fk_supplier_price_expression, pfp.fk_product, pfp.tva_tx, pfp.fk_soc, s.nom as name,"; + $sql .= " pfp.supplier_reputation"; // Units if ($conf->global->PRODUCT_USE_UNITS) { $sql .= ", u.label as unit_long, u.short_label as unit_short, p.weight, p.weight_units, p.length, p.length_units, p.width, p.width_units, p.height, p.height_units, p.surface, p.surface_units, p.volume, p.volume_units"; } - if (! empty($conf->barcode->enabled)) $sql.= " ,pfp.barcode"; - $sql.= " FROM ".MAIN_DB_PREFIX."product as p"; - $sql.= " LEFT JOIN ".MAIN_DB_PREFIX."product_fournisseur_price as pfp ON p.rowid = pfp.fk_product"; - if ($socid) $sql.= " AND pfp.fk_soc = ".$socid; - $sql.= " LEFT JOIN ".MAIN_DB_PREFIX."societe as s ON pfp.fk_soc = s.rowid"; + if (!empty($conf->barcode->enabled)) $sql .= " ,pfp.barcode"; + $sql .= " FROM ".MAIN_DB_PREFIX."product as p"; + $sql .= " LEFT JOIN ".MAIN_DB_PREFIX."product_fournisseur_price as pfp ON p.rowid = pfp.fk_product"; + if ($socid) $sql .= " AND pfp.fk_soc = ".$socid; + $sql .= " LEFT JOIN ".MAIN_DB_PREFIX."societe as s ON pfp.fk_soc = s.rowid"; // Units if ($conf->global->PRODUCT_USE_UNITS) { - $sql .= " LEFT JOIN " . MAIN_DB_PREFIX . "c_units u ON u.rowid = p.fk_unit"; + $sql .= " LEFT JOIN ".MAIN_DB_PREFIX."c_units u ON u.rowid = p.fk_unit"; } - $sql.= " WHERE p.entity IN (".getEntity('product').")"; - $sql.= " AND p.tobuy = 1"; - if (strval($filtertype) != '') $sql.=" AND p.fk_product_type=".$this->db->escape($filtertype); - if (! empty($filtre)) $sql.=" ".$filtre; + $sql .= " WHERE p.entity IN (".getEntity('product').")"; + $sql .= " AND p.tobuy = 1"; + if (strval($filtertype) != '') $sql .= " AND p.fk_product_type=".$this->db->escape($filtertype); + if (!empty($filtre)) $sql .= " ".$filtre; // Add criteria on ref/label if ($filterkey != '') { - $sql.=' AND ('; - $prefix=empty($conf->global->PRODUCT_DONOTSEARCH_ANYWHERE)?'%':''; // Can use index if PRODUCT_DONOTSEARCH_ANYWHERE is on + $sql .= ' AND ('; + $prefix = empty($conf->global->PRODUCT_DONOTSEARCH_ANYWHERE) ? '%' : ''; // Can use index if PRODUCT_DONOTSEARCH_ANYWHERE is on // For natural search $scrit = explode(' ', $filterkey); - $i=0; - if (count($scrit) > 1) $sql.="("; + $i = 0; + if (count($scrit) > 1) $sql .= "("; foreach ($scrit as $crit) { - if ($i > 0) $sql.=" AND "; - $sql.="(pfp.ref_fourn LIKE '".$this->db->escape($prefix.$crit)."%' OR p.ref LIKE '".$this->db->escape($prefix.$crit)."%' OR p.label LIKE '".$this->db->escape($prefix.$crit)."%')"; + if ($i > 0) $sql .= " AND "; + $sql .= "(pfp.ref_fourn LIKE '".$this->db->escape($prefix.$crit)."%' OR p.ref LIKE '".$this->db->escape($prefix.$crit)."%' OR p.label LIKE '".$this->db->escape($prefix.$crit)."%')"; $i++; } - if (count($scrit) > 1) $sql.=")"; - if (! empty($conf->barcode->enabled)){ - $sql.= " OR p.barcode LIKE '".$this->db->escape($prefix.$filterkey)."%'"; - $sql.= " OR pfp.barcode LIKE '".$this->db->escape($prefix.$filterkey)."%'"; + if (count($scrit) > 1) $sql .= ")"; + if (!empty($conf->barcode->enabled)) { + $sql .= " OR p.barcode LIKE '".$this->db->escape($prefix.$filterkey)."%'"; + $sql .= " OR pfp.barcode LIKE '".$this->db->escape($prefix.$filterkey)."%'"; } - $sql.=')'; + $sql .= ')'; } - $sql.= " ORDER BY pfp.ref_fourn DESC, pfp.quantity ASC"; - $sql.= $db->plimit($limit, 0); + $sql .= " ORDER BY pfp.ref_fourn DESC, pfp.quantity ASC"; + $sql .= $db->plimit($limit, 0); // Build output string dol_syslog(get_class($this)."::select_produits_fournisseurs_list", LOG_DEBUG); - $result=$this->db->query($sql); + $result = $this->db->query($sql); if ($result) { require_once DOL_DOCUMENT_ROOT.'/product/dynamic_price/class/price_parser.class.php'; @@ -2777,47 +2777,47 @@ class Form $num = $this->db->num_rows($result); //$out.=''; - if (! $selected) $out.=''; - else $out.=''; + $out .= ''; + $out .= ''; $this->db->free($result); - include_once DOL_DOCUMENT_ROOT . '/core/lib/ajax.lib.php'; - $out.=ajax_combobox($htmlname); + include_once DOL_DOCUMENT_ROOT.'/core/lib/ajax.lib.php'; + $out .= ajax_combobox($htmlname); if (empty($outputmode)) return $out; return $outarray; @@ -2997,24 +2997,24 @@ class Form public function select_product_fourn_price($productid, $htmlname = 'productfournpriceid', $selected_supplier = '') { // phpcs:enable - global $langs,$conf; + global $langs, $conf; $langs->load('stocks'); $sql = "SELECT p.rowid, p.label, p.ref, p.price, p.duration, pfp.fk_soc,"; - $sql.= " pfp.ref_fourn, pfp.rowid as idprodfournprice, pfp.price as fprice, pfp.remise_percent, pfp.quantity, pfp.unitprice,"; - $sql.= " pfp.fk_supplier_price_expression, pfp.fk_product, pfp.tva_tx, s.nom as name"; - $sql.= " FROM ".MAIN_DB_PREFIX."product as p"; - $sql.= " LEFT JOIN ".MAIN_DB_PREFIX."product_fournisseur_price as pfp ON p.rowid = pfp.fk_product"; - $sql.= " LEFT JOIN ".MAIN_DB_PREFIX."societe as s ON pfp.fk_soc = s.rowid"; - $sql.= " WHERE pfp.entity IN (".getEntity('productsupplierprice').")"; - $sql.= " AND p.tobuy = 1"; - $sql.= " AND s.fournisseur = 1"; - $sql.= " AND p.rowid = ".$productid; - $sql.= " ORDER BY s.nom, pfp.ref_fourn DESC"; + $sql .= " pfp.ref_fourn, pfp.rowid as idprodfournprice, pfp.price as fprice, pfp.remise_percent, pfp.quantity, pfp.unitprice,"; + $sql .= " pfp.fk_supplier_price_expression, pfp.fk_product, pfp.tva_tx, s.nom as name"; + $sql .= " FROM ".MAIN_DB_PREFIX."product as p"; + $sql .= " LEFT JOIN ".MAIN_DB_PREFIX."product_fournisseur_price as pfp ON p.rowid = pfp.fk_product"; + $sql .= " LEFT JOIN ".MAIN_DB_PREFIX."societe as s ON pfp.fk_soc = s.rowid"; + $sql .= " WHERE pfp.entity IN (".getEntity('productsupplierprice').")"; + $sql .= " AND p.tobuy = 1"; + $sql .= " AND s.fournisseur = 1"; + $sql .= " AND p.rowid = ".$productid; + $sql .= " ORDER BY s.nom, pfp.ref_fourn DESC"; dol_syslog(get_class($this)."::select_product_fourn_price", LOG_DEBUG); - $result=$this->db->query($sql); + $result = $this->db->query($sql); if ($result) { @@ -3022,14 +3022,14 @@ class Form $form = ''; + $form .= ''; $this->db->free($result); return $form; } @@ -3113,12 +3113,12 @@ class Form // phpcs:enable // looking for users $sql = "SELECT a.rowid, a.label"; - $sql .= " FROM ".MAIN_DB_PREFIX ."societe_address as a"; + $sql .= " FROM ".MAIN_DB_PREFIX."societe_address as a"; $sql .= " WHERE a.fk_soc = ".$socid; $sql .= " ORDER BY a.label ASC"; dol_syslog(get_class($this)."::select_address", LOG_DEBUG); - $resql=$this->db->query($sql); + $resql = $this->db->query($sql); if ($resql) { print ''; if ($addempty) print ''; - foreach($this->cache_availability as $id => $arrayavailability) + foreach ($this->cache_availability as $id => $arrayavailability) { if ($selected == $id) { @@ -3296,34 +3296,34 @@ class Form global $langs; $num = count($this->cache_demand_reason); - if ($num > 0) return 0; // Cache already loaded + if ($num > 0) return 0; // Cache already loaded $sql = "SELECT rowid, code, label"; - $sql.= " FROM ".MAIN_DB_PREFIX.'c_input_reason'; - $sql.= " WHERE active > 0"; + $sql .= " FROM ".MAIN_DB_PREFIX.'c_input_reason'; + $sql .= " WHERE active > 0"; $resql = $this->db->query($sql); if ($resql) { $num = $this->db->num_rows($resql); $i = 0; - $tmparray=array(); + $tmparray = array(); while ($i < $num) { $obj = $this->db->fetch_object($resql); // Si traduction existe, on l'utilise, sinon on prend le libelle par defaut - $label=($obj->label!='-'?$obj->label:''); + $label = ($obj->label != '-' ? $obj->label : ''); if ($langs->trans("DemandReasonType".$obj->code) != ("DemandReasonType".$obj->code)) $label = $langs->trans("DemandReasonType".$obj->code); // So translation key DemandReasonTypeSRC_XXX will work - if ($langs->trans($obj->code) != $obj->code) $label=$langs->trans($obj->code); // So translation key SRC_XXX will work + if ($langs->trans($obj->code) != $obj->code) $label = $langs->trans($obj->code); // So translation key SRC_XXX will work - $tmparray[$obj->rowid]['id'] =$obj->rowid; - $tmparray[$obj->rowid]['code'] =$obj->code; - $tmparray[$obj->rowid]['label']=$label; + $tmparray[$obj->rowid]['id'] = $obj->rowid; + $tmparray[$obj->rowid]['code'] = $obj->code; + $tmparray[$obj->rowid]['label'] = $label; $i++; } - $this->cache_demand_reason=dol_sort_array($tmparray, 'label', 'asc', 0, 0, 1); + $this->cache_demand_reason = dol_sort_array($tmparray, 'label', 'asc', 0, 0, 1); unset($tmparray); return $num; @@ -3347,15 +3347,15 @@ class Form */ public function selectInputReason($selected = '', $htmlname = 'demandreasonid', $exclude = '', $addempty = 0) { - global $langs,$user; + global $langs, $user; $this->loadCacheInputReason(); print ''; + print ''; + print ''; - if ($user->admin && ! $noadmininfo) print info_admin($langs->trans("YouCanChangeValuesForThisListFromDictionarySetup"), 1); + if ($user->admin && !$noadmininfo) print info_admin($langs->trans("YouCanChangeValuesForThisListFromDictionarySetup"), 1); } @@ -3546,26 +3546,26 @@ class Form { global $langs; - $return=''; + $return = ''; - $return.= ''; $options = array( 'HT'=>$langs->trans("HT"), 'TTC'=>$langs->trans("TTC") ); - foreach($options as $id => $value) + foreach ($options as $id => $value) { if ($selected == $id) { - $return.= ''; + $return .= ''; } - $return.= ''; + $return .= ''; return $return; } @@ -3588,10 +3588,10 @@ class Form $langs->load("deliveries"); $sql = "SELECT rowid, code, libelle as label"; - $sql.= " FROM ".MAIN_DB_PREFIX."c_shipment_mode"; - $sql.= " WHERE active > 0"; - if ($filtre) $sql.=" AND ".$filtre; - $sql.= " ORDER BY libelle ASC"; + $sql .= " FROM ".MAIN_DB_PREFIX."c_shipment_mode"; + $sql .= " WHERE active > 0"; + if ($filtre) $sql .= " AND ".$filtre; + $sql .= " ORDER BY libelle ASC"; dol_syslog(get_class($this)."::selectShippingMode", LOG_DEBUG); $result = $this->db->query($sql); @@ -3599,7 +3599,7 @@ class Form $num = $this->db->num_rows($result); $i = 0; if ($num) { - print ''; if ($useempty == 1 || ($useempty == 2 && $num > 1)) { print ''; } @@ -3648,7 +3648,7 @@ class Form print ''; } else { if ($selected) { - $code=$langs->getLabelFromKey($db, $selected, 'c_shipment_mode', 'rowid', 'code'); + $code = $langs->getLabelFromKey($db, $selected, 'c_shipment_mode', 'rowid', 'code'); print $langs->trans("SendingMethod".strtoupper($code)); } else { print " "; @@ -3672,15 +3672,15 @@ class Form $opt = ''; $sql = 'SELECT rowid, ref, situation_cycle_ref, situation_counter, situation_final, fk_soc'; - $sql.= ' FROM ' . MAIN_DB_PREFIX . 'facture'; - $sql.= ' WHERE entity IN ('.getEntity('invoice').')'; - $sql.= ' AND situation_counter>=1'; - $sql.= ' ORDER by situation_cycle_ref, situation_counter desc'; + $sql .= ' FROM '.MAIN_DB_PREFIX.'facture'; + $sql .= ' WHERE entity IN ('.getEntity('invoice').')'; + $sql .= ' AND situation_counter>=1'; + $sql .= ' ORDER by situation_cycle_ref, situation_counter desc'; $resql = $this->db->query($sql); if ($resql && $this->db->num_rows($resql) > 0) { // Last seen cycle $ref = 0; - while ($obj = $this->db->fetch_object($resql)){ + while ($obj = $this->db->fetch_object($resql)) { //Same company ? if ($socid == $obj->fk_soc) { //Same cycle ? @@ -3692,9 +3692,9 @@ class Form //Not prov? if (substr($obj->ref, 1, 4) != 'PROV') { if ($selected == $obj->rowid) { - $opt .= ''; + $opt .= ''; } else { - $opt .= ''; + $opt .= ''; } } } @@ -3704,11 +3704,11 @@ class Form } else { - dol_syslog("Error sql=" . $sql . ", error=" . $this->error, LOG_ERR); + dol_syslog("Error sql=".$sql.", error=".$this->error, LOG_ERR); } if ($opt == '') { - $opt = ''; + $opt = ''; } return $opt; } @@ -3727,34 +3727,34 @@ class Form $langs->load('products'); - $return= ''; $sql = 'SELECT rowid, label, code from '.MAIN_DB_PREFIX.'c_units'; - $sql.= ' WHERE active > 0'; + $sql .= ' WHERE active > 0'; $resql = $this->db->query($sql); - if($resql && $this->db->num_rows($resql) > 0) + if ($resql && $this->db->num_rows($resql) > 0) { if ($showempty) $return .= ''; - while($res = $this->db->fetch_object($resql)) + while ($res = $this->db->fetch_object($resql)) { $unitLabel = $res->label; - if (! empty($langs->tab_translate['unit'.$res->code])) // check if Translation is available before + if (!empty($langs->tab_translate['unit'.$res->code])) // check if Translation is available before { - $unitLabel = $langs->trans('unit'.$res->code)!=$res->label?$langs->trans('unit'.$res->code):$res->label; + $unitLabel = $langs->trans('unit'.$res->code) != $res->label ? $langs->trans('unit'.$res->code) : $res->label; } if ($selected == $res->rowid) { - $return.=''; + $return .= ''; } else { - $return.=''; + $return .= ''; } } - $return.=''; + $return .= ''; } return $return; } @@ -3796,7 +3796,7 @@ class Form $i = 0; if ($num) { - print ''; if ($useempty == 1 || ($useempty == 2 && $num > 1)) { print ''; @@ -3868,7 +3868,7 @@ class Form $i = 0; if ($num) { - print ''; if ($useempty == 1 || ($useempty == 2 && $num > 1)) { print ''; @@ -3926,8 +3926,8 @@ class Form $langs->load('banks'); if ($selected) { - require_once DOL_DOCUMENT_ROOT .'/compta/bank/class/account.class.php'; - $bankstatic=new Account($this->db); + require_once DOL_DOCUMENT_ROOT.'/compta/bank/class/account.class.php'; + $bankstatic = new Account($this->db); $result = $bankstatic->fetch($selected); if ($result) print $bankstatic->getNomUrl(1); } else { @@ -3965,17 +3965,17 @@ class Form // For backward compatibility if (is_numeric($type)) { - dol_syslog(__METHOD__ . ': using numeric value for parameter type is deprecated. Use string code instead.', LOG_WARNING); + dol_syslog(__METHOD__.': using numeric value for parameter type is deprecated. Use string code instead.', LOG_WARNING); } if ($type === Categorie::TYPE_BANK_LINE) { // TODO Move this into common category feature - $categids=array(); + $categids = array(); $sql = "SELECT c.label, c.rowid"; - $sql.= " FROM ".MAIN_DB_PREFIX."bank_categ as c"; - $sql.= " WHERE entity = ".$conf->entity; - $sql.= " ORDER BY c.label"; + $sql .= " FROM ".MAIN_DB_PREFIX."bank_categ as c"; + $sql .= " WHERE entity = ".$conf->entity; + $sql .= " ORDER BY c.label"; $result = $this->db->query($sql); if ($result) { @@ -3984,7 +3984,7 @@ class Form while ($i < $num) { $objp = $this->db->fetch_object($result); - if ($objp) $cate_arbo[$objp->rowid]=array('id'=>$objp->rowid, 'fulllabel'=>$objp->label); + if ($objp) $cate_arbo[$objp->rowid] = array('id'=>$objp->rowid, 'fulllabel'=>$objp->label); $i++; } $this->db->free($result); @@ -3998,14 +3998,14 @@ class Form } $output = ''; - $output.= "\n"; + $output .= ''; + $output .= "\n"; if ($outputmode) return $outarray; return $output; @@ -4048,7 +4048,7 @@ class Form public function form_confirm($page, $title, $question, $action, $formquestion = '', $selectedchoice = "", $useajax = 0, $height = 170, $width = 500) { // phpcs:enable - dol_syslog(__METHOD__ . ': using form_confirm is deprecated. Use formconfim instead.', LOG_WARNING); + dol_syslog(__METHOD__.': using form_confirm is deprecated. Use formconfim instead.', LOG_WARNING); print $this->formconfirm($page, $title, $question, $action, $formquestion, $selectedchoice, $useajax, $height, $width); } @@ -4078,17 +4078,17 @@ class Form */ public function formconfirm($page, $title, $question, $action, $formquestion = '', $selectedchoice = '', $useajax = 0, $height = 0, $width = 500, $disableformtag = 0) { - global $langs,$conf; + global $langs, $conf; global $useglobalvars; - $more=''; - $formconfirm=''; - $inputok=array(); - $inputko=array(); + $more = ''; + $formconfirm = ''; + $inputok = array(); + $inputko = array(); // Clean parameters - $newselectedchoice=empty($selectedchoice)?"no":$selectedchoice; - if ($conf->browser->layout == 'phone') $width='95%'; + $newselectedchoice = empty($selectedchoice) ? "no" : $selectedchoice; + if ($conf->browser->layout == 'phone') $width = '95%'; // Set height automatically if not defined if (empty($height)) { @@ -4098,79 +4098,79 @@ class Form } } - if (is_array($formquestion) && ! empty($formquestion)) + if (is_array($formquestion) && !empty($formquestion)) { // First add hidden fields and value foreach ($formquestion as $key => $input) { - if (is_array($input) && ! empty($input)) + if (is_array($input) && !empty($input)) { if ($input['type'] == 'hidden') { - $more.=''."\n"; + $more .= ''."\n"; } } } // Now add questions - $more.='
    '."\n"; - if (! empty($formquestion['text'])) $more.='
    '."\n"; + $more .= '
    '."\n"; + if (!empty($formquestion['text'])) $more .= '
    '."\n"; foreach ($formquestion as $key => $input) { - if (is_array($input) && ! empty($input)) + if (is_array($input) && !empty($input)) { - $size=(! empty($input['size'])?' size="'.$input['size'].'"':''); - $moreattr=(! empty($input['moreattr'])?' '.$input['moreattr']:''); - $morecss=(! empty($input['morecss'])?' '.$input['morecss']:''); + $size = (!empty($input['size']) ? ' size="'.$input['size'].'"' : ''); + $moreattr = (!empty($input['moreattr']) ? ' '.$input['moreattr'] : ''); + $morecss = (!empty($input['morecss']) ? ' '.$input['morecss'] : ''); if ($input['type'] == 'text') { - $more.='
    '.$input['label'].'
    '."\n"; + $more .= '
    '.$input['label'].'
    '."\n"; } elseif ($input['type'] == 'password') { - $more.='
    '.$input['label'].'
    '."\n"; + $more .= '
    '.$input['label'].'
    '."\n"; } elseif ($input['type'] == 'select') { - $more.='
    '; - if (! empty($input['label'])) $more.=$input['label'].'
    '; - $more.=$this->selectarray($input['name'], $input['values'], $input['default'], 1, 0, 0, $moreattr, 0, 0, 0, '', $morecss); - $more.='
    '."\n"; + $more .= '
    '; + if (!empty($input['label'])) $more .= $input['label'].'
    '; + $more .= $this->selectarray($input['name'], $input['values'], $input['default'], 1, 0, 0, $moreattr, 0, 0, 0, '', $morecss); + $more .= '
    '."\n"; } elseif ($input['type'] == 'checkbox') { - $more.='
    '; - $more.='
    '.$input['label'].'
    '; - $more.=''.$input['label'].'
    '; + $more .= ' $selval) + $i = 0; + foreach ($input['values'] as $selkey => $selval) { - $more.='
    '; - if ($i==0) $more.='
    '.$input['label'].'
    '; - else $more.='
     
    '; - $more.='
    '.$input['label'].'
    '; + else $more .= '
     
    '; + $more .= '
    '.$input['label'].'
    '; - $more.='
    '; - $more.=$this->selectDate($input['value'], $input['name'], 0, 0, 0, '', 1, 0); - $more.='
    '."\n"; + $more .= '
    '.$input['label'].'
    '; + $more .= '
    '; + $more .= $this->selectDate($input['value'], $input['name'], 0, 0, 0, '', 1, 0); + $more .= '
    '."\n"; $formquestion[] = array('name'=>$input['name'].'day'); $formquestion[] = array('name'=>$input['name'].'month'); $formquestion[] = array('name'=>$input['name'].'year'); @@ -4179,43 +4179,43 @@ class Form } elseif ($input['type'] == 'other') { - $more.='
    '; - if (! empty($input['label'])) $more.=$input['label'].'
    '; - $more.=$input['value']; - $more.='
    '."\n"; + $more .= '
    '; + if (!empty($input['label'])) $more .= $input['label'].'
    '; + $more .= $input['value']; + $more .= '
    '."\n"; } elseif ($input['type'] == 'onecolumn') { - $more.='
    '; - $more.=$input['value']; - $more.='
    '."\n"; + $more .= '
    '; + $more .= $input['value']; + $more .= '
    '."\n"; } } } - $more.='
    '."\n"; + $more .= '
    '."\n"; } // JQUI method dialog is broken with jmobile, we use standard HTML. // Note: When using dol_use_jmobile or no js, you must also check code for button use a GET url with action=xxx and check that you also output the confirm code when action=xxx // See page product/card.php for example - if (! empty($conf->dol_use_jmobile)) $useajax=0; - if (empty($conf->use_javascript_ajax)) $useajax=0; + if (!empty($conf->dol_use_jmobile)) $useajax = 0; + if (empty($conf->use_javascript_ajax)) $useajax = 0; if ($useajax) { - $autoOpen=true; - $dialogconfirm='dialog-confirm'; - $button=''; - if (! is_numeric($useajax)) + $autoOpen = true; + $dialogconfirm = 'dialog-confirm'; + $button = ''; + if (!is_numeric($useajax)) { - $button=$useajax; - $useajax=1; - $autoOpen=false; - $dialogconfirm.='-'.$button; + $button = $useajax; + $useajax = 1; + $autoOpen = false; + $dialogconfirm .= '-'.$button; } - $pageyes=$page.(preg_match('/\?/', $page)?'&':'?').'action='.$action.'&confirm=yes'; - $pageno=($useajax == 2 ? $page.(preg_match('/\?/', $page)?'&':'?').'confirm=no':''); + $pageyes = $page.(preg_match('/\?/', $page) ? '&' : '?').'action='.$action.'&confirm=yes'; + $pageno = ($useajax == 2 ? $page.(preg_match('/\?/', $page) ? '&' : '?').'confirm=no' : ''); // Add input fields into list of fields to read during submit (inputok and inputko) if (is_array($formquestion)) { @@ -4227,28 +4227,28 @@ class Form } } // Show JQuery confirm box. Note that global var $useglobalvars is used inside this template - $formconfirm.= ''."\n"; - $formconfirm.= "\n\n"; - $formconfirm.= ''; - $formconfirm.= "\n"; + $formconfirm .= "\n"; } else { - $formconfirm.= "\n\n"; + $formconfirm .= "\n\n"; - if (empty($disableformtag)) $formconfirm.= ''."\n"; + if (empty($disableformtag)) $formconfirm .= ''."\n"; - $formconfirm.= ''."\n"; - $formconfirm.= ''."\n"; + $formconfirm .= ''."\n"; + $formconfirm .= ''."\n"; - $formconfirm.= '
    ' . $langs->trans('Ref') . '' . $langs->trans('Draft') . '
    '.$langs->trans('Ref').''.$langs->trans('Draft').'
    ' . $langs->trans('Customer') . '
    '.$langs->trans('Customer').''; print $soc->getNomUrl(1); - print ''; + print ''; // Outstanding Bill $arrayoutstandingbills = $soc->getOutstandingBills(); $outstandingBills = $arrayoutstandingbills['opened']; - print ' (' . $langs->trans('CurrentOutstandingBill') . ': '; + print ' ('.$langs->trans('CurrentOutstandingBill').': '; print price($outstandingBills, '', $langs, 0, 0, -1, $conf->currency); if ($soc->outstanding_limit != '') { if ($outstandingBills > $soc->outstanding_limit) print img_warning($langs->trans("OutstandingBillReached")); - print ' / ' . price($soc->outstanding_limit, '', $langs, 0, 0, -1, $conf->currency); + print ' / '.price($soc->outstanding_limit, '', $langs, 0, 0, -1, $conf->currency); } print ')'; print '
    ' . $langs->trans('Customer') . '
    '.$langs->trans('Customer').''; print $form->select_company($soc->id, 'socid', '((s.client = 1 OR s.client = 3) AND s.status=1)', 'SelectThirdParty', 0, 0, null, 0, 'minwidth300'); // Option to reload page to retrieve customer informations. Note, this clear other input @@ -2801,9 +2801,9 @@ if ($action == 'create') }); '; } - if (! GETPOST('fac_rec', 'int')) print ' '.$langs->trans("AddThirdParty").''; + if (!GETPOST('fac_rec', 'int')) print ' '.$langs->trans("AddThirdParty").''; print '
    ' . $langs->trans('CreateFromRepeatableInvoice') . ''; + print '
    '.$langs->trans('CreateFromRepeatableInvoice').''; //print ''; - print ''; // We may want to change the template to use print ''; while ($i < $num) { $objp = $db->fetch_object($resql); - print ''; - $i ++; + print '>'.$objp->title.' ('.price($objp->total_ttc).' '.$langs->trans("TTC").')'; + $i++; } print ''; // Option to reload page to retrieve customer informations. Note, this clear other input @@ -2874,25 +2874,25 @@ if ($action == 'create') } } - print '
    ' . $langs->trans('Type') . ''; + print '
    '.$langs->trans('Type').''; - print '
    ' . "\n"; + print '
    '."\n"; // Standard invoice print '
    '; - $tmp=' '; + $tmp = ' '; $tmp = $tmp.''; $desc = $form->textwithpicto($tmp, $langs->transnoentities("InvoiceStandardDesc"), 1, 'help', '', 0, 3); print $desc; print '
    '; - if ((empty($origin)) || ((($origin == 'propal') || ($origin == 'commande')) && (! empty($originid)))) + if ((empty($origin)) || ((($origin == 'propal') || ($origin == 'commande')) && (!empty($originid)))) { // Deposit if (empty($conf->global->INVOICE_DISABLE_DEPOSIT)) { print '
    '; - $tmp=' '; + $tmp = ' '; print ''; - $text = ''; + $text = ''; $text .= ''; $desc = $form->textwithpicto($text, $langs->transnoentities("InvoiceReplacementDesc"), 1, 'help', '', 0, 3); @@ -3003,29 +3003,29 @@ if ($action == 'create') } else { - if (! empty($conf->global->INVOICE_USE_SITUATION)) + if (!empty($conf->global->INVOICE_USE_SITUATION)) { print '
    '; - $tmp=' '; - $text = ' '; - $text.= '('.$langs->trans("YouMustCreateInvoiceFromThird").') '; + $tmp = ' '; + $text = ' '; + $text .= '('.$langs->trans("YouMustCreateInvoiceFromThird").') '; $desc = $form->textwithpicto($text, $langs->transnoentities("InvoiceFirstSituationDesc"), 1, 'help', '', 0, 3); print $desc; print '
    '; print '
    '; - $tmp=' '; - $text = ' '; - $text.= '('.$langs->trans("YouMustCreateInvoiceFromThird").') '; + $tmp = ' '; + $text = ' '; + $text .= '('.$langs->trans("YouMustCreateInvoiceFromThird").') '; $desc = $form->textwithpicto($text, $langs->transnoentities("InvoiceFirstSituationDesc"), 1, 'help', '', 0, 3); print $desc; print '
    '; } print '
    '; - $tmp=' '; - $text = ' '; - $text.= '('.$langs->trans("YouMustCreateInvoiceFromThird").') '; + $tmp = ' '; + $text = ' '; + $text .= '('.$langs->trans("YouMustCreateInvoiceFromThird").') '; $desc = $form->textwithpicto($text, $langs->transnoentities("InvoiceReplacementDesc"), 1, 'help', '', 0, 3); print $desc; print '
    '; @@ -3040,7 +3040,7 @@ if ($action == 'create') if (empty($conf->global->INVOICE_DISABLE_CREDIT_NOTE)) { // Show link for credit note - $facids=$facturestatic->list_qualified_avoir_invoices($soc->id); + $facids = $facturestatic->list_qualified_avoir_invoices($soc->id); if ($facids < 0) { dol_print_error($db, $facturestatic); @@ -3056,19 +3056,19 @@ if ($action == 'create') $newinvoice_static->type = $valarray ['type']; $newinvoice_static->paye = $valarray ['paye']; - $optionsav .= ''; } print '
    '; - $tmp='global->INVOICE_CREDIT_NOTE_STANDALONE)) || $invoice_predefined->id > 0) $tmp.=' disabled'; - $tmp.= '> '; + $tmp = 'global->INVOICE_CREDIT_NOTE_STANDALONE)) || $invoice_predefined->id > 0) $tmp .= ' disabled'; + $tmp .= '> '; // Show credit note options only if we checked credit note print ''; - $text = ' '; + $text = ' '; // $text.=''; $text .= ''; $desc = $form->textwithpicto($text, $langs->transnoentities("InvoiceAvoirDesc"), 1, 'help', '', 0, 3); print $desc; print '
    '; - print '    0 ? 'checked':'').' /> "; - print '
        0 ? 'checked':'').' /> "; + print '    0 ? 'checked' : '').' /> "; + print '
        0 ? 'checked' : '').' /> "; print '
    '; print '
    '; @@ -3111,20 +3111,20 @@ if ($action == 'create') else { print '
    '; - if (empty($conf->global->INVOICE_CREDIT_NOTE_STANDALONE)) $tmp=' '; - else $tmp=' '; - $text = ' '; - $text.= '('.$langs->trans("YouMustCreateInvoiceFromThird").') '; + if (empty($conf->global->INVOICE_CREDIT_NOTE_STANDALONE)) $tmp = ' '; + else $tmp = ' '; + $text = ' '; + $text .= '('.$langs->trans("YouMustCreateInvoiceFromThird").') '; $desc = $form->textwithpicto($text, $langs->transnoentities("InvoiceAvoirDesc"), 1, 'help', '', 0, 3); print $desc; - print '
    ' . "\n"; + print '
    '."\n"; } } // Template invoice print '
    '; - $tmp=' '; - $text = ' '; + $tmp = ' '; + $text = ' '; //$text.= '('.$langs->trans("YouMustCreateStandardInvoiceFirst").') '; $desc = $form->textwithpicto($text, $langs->transnoentities("YouMustCreateStandardInvoiceFirstDesc"), 1, 'help', '', 0, 3); print $desc; @@ -3133,16 +3133,16 @@ if ($action == 'create') print '
    '; - if(!empty($conf->global->INVOICE_USE_DEFAULT_DOCUMENT)) // Hidden conf + if (!empty($conf->global->INVOICE_USE_DEFAULT_DOCUMENT)) // Hidden conf { // Add auto select default document model - $listtType=array(Facture::TYPE_STANDARD,Facture::TYPE_REPLACEMENT,Facture::TYPE_CREDIT_NOTE,Facture::TYPE_DEPOSIT,Facture::TYPE_SITUATION); - $jsListType=''; + $listtType = array(Facture::TYPE_STANDARD, Facture::TYPE_REPLACEMENT, Facture::TYPE_CREDIT_NOTE, Facture::TYPE_DEPOSIT, Facture::TYPE_SITUATION); + $jsListType = ''; foreach ($listtType as $type) { $thisTypeConfName = 'FACTURE_ADDON_PDF_'.$type; - $curent = !empty($conf->global->{$thisTypeConfName})?$conf->global->{$thisTypeConfName}:$conf->global->FACTURE_ADDON_PDF; - $jsListType.=(!empty($jsListType)?',':'').'"'.$type.'":"'.$curent.'"'; + $curent = !empty($conf->global->{$thisTypeConfName}) ? $conf->global->{$thisTypeConfName}:$conf->global->FACTURE_ADDON_PDF; + $jsListType .= (!empty($jsListType) ? ',' : '').'"'.$type.'":"'.$curent.'"'; } print ''; // set cookie by js - $boxcontent.=''; + $boxcontent .= ''; $this->info_box_contents[0][] = array( 'tr'=>'class="nohover showiffilter'.$this->boxcode.' hideobject"', 'td' => 'class="nohover"', @@ -144,43 +144,43 @@ class box_task extends ModeleBoxes $sql = "SELECT pt.rowid, pt.ref, pt.fk_projet, pt.fk_task_parent, pt.datec, pt.dateo, pt.datee, pt.datev, pt.label, pt.description, pt.duration_effective, pt.planned_workload, pt.progress"; - $sql.= ", p.rowid project_id, p.ref project_ref, p.title project_title"; + $sql .= ", p.rowid project_id, p.ref project_ref, p.title project_title"; - $sql.= " FROM ".MAIN_DB_PREFIX."projet_task as pt"; - $sql.= " JOIN ".MAIN_DB_PREFIX."projet as p ON (pt.fk_projet = p.rowid)"; + $sql .= " FROM ".MAIN_DB_PREFIX."projet_task as pt"; + $sql .= " JOIN ".MAIN_DB_PREFIX."projet as p ON (pt.fk_projet = p.rowid)"; - if($filterValue === 'im_task_contact') { - $sql .= " JOIN " . MAIN_DB_PREFIX . "element_contact as ec ON (ec.element_id = pt.rowid AND ec.fk_socpeople = '" . $user->id . "' )"; - $sql .= " JOIN " . MAIN_DB_PREFIX . "c_type_contact as tc ON (ec.fk_c_type_contact = tc.rowid AND tc.element = 'project_task' AND tc.source = 'internal' )"; + if ($filterValue === 'im_task_contact') { + $sql .= " JOIN ".MAIN_DB_PREFIX."element_contact as ec ON (ec.element_id = pt.rowid AND ec.fk_socpeople = '".$user->id."' )"; + $sql .= " JOIN ".MAIN_DB_PREFIX."c_type_contact as tc ON (ec.fk_c_type_contact = tc.rowid AND tc.element = 'project_task' AND tc.source = 'internal' )"; } - elseif($filterValue === 'im_project_contact') { - $sql .= " JOIN " . MAIN_DB_PREFIX . "element_contact as ec ON (ec.element_id = p.rowid AND ec.fk_socpeople = '" . $user->id . "' )"; - $sql .= " JOIN " . MAIN_DB_PREFIX . "c_type_contact as tc ON (ec.fk_c_type_contact = tc.rowid AND tc.element = 'project' AND tc.source = 'internal' )"; + elseif ($filterValue === 'im_project_contact') { + $sql .= " JOIN ".MAIN_DB_PREFIX."element_contact as ec ON (ec.element_id = p.rowid AND ec.fk_socpeople = '".$user->id."' )"; + $sql .= " JOIN ".MAIN_DB_PREFIX."c_type_contact as tc ON (ec.fk_c_type_contact = tc.rowid AND tc.element = 'project' AND tc.source = 'internal' )"; } - $sql.= " WHERE "; - $sql.= " pt.entity = ".$conf->entity; - $sql.= " AND p.fk_statut = ".Project::STATUS_VALIDATED; - $sql.= " AND (pt.progress < 100 OR pt.progress IS NULL ) "; // 100% is done and not displayed - $sql.= " AND p.usage_task = 1 "; + $sql .= " WHERE "; + $sql .= " pt.entity = ".$conf->entity; + $sql .= " AND p.fk_statut = ".Project::STATUS_VALIDATED; + $sql .= " AND (pt.progress < 100 OR pt.progress IS NULL ) "; // 100% is done and not displayed + $sql .= " AND p.usage_task = 1 "; - $sql.= " ORDER BY pt.datee ASC, pt.dateo ASC"; - $sql.= $this->db->plimit($max, 0); + $sql .= " ORDER BY pt.datee ASC, pt.dateo ASC"; + $sql .= $this->db->plimit($max, 0); $result = $this->db->query($sql); $i = 1; if ($result) { $num = $this->db->num_rows($result); while ($objp = $this->db->fetch_object($result)) { - $taskstatic->id=$objp->rowid; - $taskstatic->ref=$objp->ref; - $taskstatic->label=$objp->label; + $taskstatic->id = $objp->rowid; + $taskstatic->ref = $objp->ref; + $taskstatic->label = $objp->label; $taskstatic->progress = $objp->progress; $taskstatic->fk_statut = $objp->fk_statut; $taskstatic->date_end = $objp->datee; - $taskstatic->planned_workload= $objp->planned_workload; - $taskstatic->duration_effective= $objp->duration_effective; + $taskstatic->planned_workload = $objp->planned_workload; + $taskstatic->duration_effective = $objp->duration_effective; $projectstatic->id = $objp->project_id; $projectstatic->ref = $objp->project_ref; diff --git a/htdocs/core/class/CMailFile.class.php b/htdocs/core/class/CMailFile.class.php index 5f8c630e46a..335c1b50111 100644 --- a/htdocs/core/class/CMailFile.class.php +++ b/htdocs/core/class/CMailFile.class.php @@ -41,13 +41,13 @@ class CMailFile public $sendmode; public $sendsetup; - public $subject; // Topic: Subject of email - public $addr_from; // From: Label and EMail of sender (must include '<>'). For example '' or 'John Doe ' or ''). Note that with gmail smtps, value here is forced by google to account (but not the reply-to). + public $subject; // Topic: Subject of email + public $addr_from; // From: Label and EMail of sender (must include '<>'). For example '' or 'John Doe ' or ''). Note that with gmail smtps, value here is forced by google to account (but not the reply-to). // Sender: Who send the email ("Sender" has sent emails on behalf of "From"). // Use it when the "From" is an email of a domain that is a SPF protected domain, and sending smtp server is not this domain. In such case, add Sender field with an email of the protected domain. // Return-Path: Email where to send bounds. - public $reply_to; // Reply-To: Email where to send replies from mailer software (mailer use From if reply-to not defined, Gmail use gmail account if reply-to not defined) - public $errors_to; // Errors-To: Email where to send errors. + public $reply_to; // Reply-To: Email where to send replies from mailer software (mailer use From if reply-to not defined, Gmail use gmail account if reply-to not defined) + public $errors_to; // Errors-To: Email where to send errors. public $addr_to; public $addr_cc; public $addr_bcc; @@ -64,10 +64,10 @@ class CMailFile /** * @var string Error code (or message) */ - public $error=''; + public $error = ''; - public $smtps; // Contains SMTPs object (if this method is used) - public $phpmailer; // Contains PHPMailer object (if this method is used) + public $smtps; // Contains SMTPs object (if this method is used) + public $phpmailer; // Contains PHPMailer object (if this method is used) /** * @var string CSS @@ -78,6 +78,7 @@ class CMailFile //! Defined background directly in body tag public $bodyCSS; + public $msgid; public $headers; public $message; /** @@ -96,9 +97,9 @@ class CMailFile // Image public $html; public $image_boundary; - public $atleastoneimage=0; // at least one image file with file=xxx.ext into content (TODO Debug this. How can this case be tested. Remove if not used). - public $html_images=array(); - public $images_encoded=array(); + public $atleastoneimage = 0; // at least one image file with file=xxx.ext into content (TODO Debug this. How can this case be tested. Remove if not used). + public $html_images = array(); + public $images_encoded = array(); public $image_types = array( 'gif' => 'image/gif', 'jpg' => 'image/jpeg', @@ -162,28 +163,28 @@ class CMailFile { $this->sendmode = $conf->global->MAIN_MAIL_SENDMODE_EMAILING; } - if (empty($this->sendmode)) $this->sendmode=$conf->global->MAIN_MAIL_SENDMODE; - if (empty($this->sendmode)) $this->sendmode='mail'; + if (empty($this->sendmode)) $this->sendmode = $conf->global->MAIN_MAIL_SENDMODE; + if (empty($this->sendmode)) $this->sendmode = 'mail'; // We define end of line (RFC 821). - $this->eol="\r\n"; + $this->eol = "\r\n"; // We define end of line for header fields (RFC 822bis section 2.3 says header must contains \r\n). - $this->eol2="\r\n"; - if (! empty($conf->global->MAIN_FIX_FOR_BUGGED_MTA)) + $this->eol2 = "\r\n"; + if (!empty($conf->global->MAIN_FIX_FOR_BUGGED_MTA)) { - $this->eol="\n"; - $this->eol2="\n"; + $this->eol = "\n"; + $this->eol2 = "\n"; $moreinheader = str_replace("\r\n", "\n", $moreinheader); } // On defini mixed_boundary - $this->mixed_boundary = "multipart_x." . time() . ".x_boundary"; + $this->mixed_boundary = "multipart_x.".time().".x_boundary"; // On defini related_boundary - $this->related_boundary = 'mul_'.dol_hash(uniqid("dolibarr2"), 3); // Force md5 hash (does not contains special chars) + $this->related_boundary = 'mul_'.dol_hash(uniqid("dolibarr2"), 3); // Force md5 hash (does not contains special chars) // On defini alternative_boundary - $this->alternative_boundary = 'mul_'.dol_hash(uniqid("dolibarr3"), 3); // Force md5 hash (does not contains special chars) + $this->alternative_boundary = 'mul_'.dol_hash(uniqid("dolibarr3"), 3); // Force md5 hash (does not contains special chars) dol_syslog("CMailFile::CMailfile: sendmode=".$this->sendmode." charset=".$conf->file->character_set_client." from=$from, to=$to, addr_cc=$addr_cc, addr_bcc=$addr_bcc, errors_to=$errors_to, trackid=$trackid sendcontext=$sendcontext", LOG_DEBUG); dol_syslog("CMailFile::CMailfile: subject=".$subject.", deliveryreceipt=".$deliveryreceipt.", msgishtml=".$msgishtml, LOG_DEBUG); @@ -191,13 +192,13 @@ class CMailFile if (empty($subject)) { dol_syslog("CMailFile::CMailfile: Try to send an email with empty subject"); - $this->error='ErrorSubjectIsRequired'; + $this->error = 'ErrorSubjectIsRequired'; return; } if (empty($msg)) { dol_syslog("CMailFile::CMailfile: Try to send an email with empty body"); - $msg='.'; // Avoid empty message (with empty message conten show a multipart structure) + $msg = '.'; // Avoid empty message (with empty message conten show a multipart structure) } // Detect if message is HTML (use fast method) @@ -214,21 +215,21 @@ class CMailFile global $dolibarr_main_url_root; // Define $urlwithroot - $urlwithouturlroot=preg_replace('/'.preg_quote(DOL_URL_ROOT, '/').'$/i', '', trim($dolibarr_main_url_root)); - $urlwithroot=$urlwithouturlroot.DOL_URL_ROOT; // This is to use external domain name found into config file + $urlwithouturlroot = preg_replace('/'.preg_quote(DOL_URL_ROOT, '/').'$/i', '', trim($dolibarr_main_url_root)); + $urlwithroot = $urlwithouturlroot.DOL_URL_ROOT; // This is to use external domain name found into config file //$urlwithroot=DOL_MAIN_URL_ROOT; // This is to use same domain name than current // Replace relative /viewimage to absolute path $msg = preg_replace('/src="'.preg_quote(DOL_URL_ROOT, '/').'\/viewimage\.php/ims', 'src="'.$urlwithroot.'/viewimage.php', $msg, -1, $nbrep); - if (! empty($conf->global->MAIN_MAIL_FORCE_CONTENT_TYPE_TO_HTML)) $this->msgishtml=1; // To force to send everything with content type html. + if (!empty($conf->global->MAIN_MAIL_FORCE_CONTENT_TYPE_TO_HTML)) $this->msgishtml = 1; // To force to send everything with content type html. // Detect images if ($this->msgishtml) { $this->html = $msg; - if (! empty($conf->global->MAIN_MAIL_ADD_INLINE_IMAGES_IF_IN_MEDIAS)) + if (!empty($conf->global->MAIN_MAIL_ADD_INLINE_IMAGES_IF_IN_MEDIAS)) { $findimg = $this->findHtmlImages($dolibarr_main_data_root.'/medias'); } @@ -240,7 +241,7 @@ class CMailFile { if ($this->html_images[$i]) { - $this->atleastoneimage=1; + $this->atleastoneimage = 1; dol_syslog("CMailFile::CMailfile: html_images[$i]['name']=".$this->html_images[$i]['name'], LOG_DEBUG); } } @@ -254,16 +255,17 @@ class CMailFile { if ($filename_list[$i]) { - $this->atleastonefile=1; + $this->atleastonefile = 1; dol_syslog("CMailFile::CMailfile: filename_list[$i]=".$filename_list[$i].", mimetype_list[$i]=".$mimetype_list[$i]." mimefilename_list[$i]=".$mimefilename_list[$i], LOG_DEBUG); } } } // Add autocopy to (Note: Adding bcc for specific modules are also done from pages) - if (! empty($conf->global->MAIN_MAIL_AUTOCOPY_TO)) $addr_bcc.=($addr_bcc?', ':'').$conf->global->MAIN_MAIL_AUTOCOPY_TO; + if (!empty($conf->global->MAIN_MAIL_AUTOCOPY_TO)) $addr_bcc .= ($addr_bcc ? ', ' : '').$conf->global->MAIN_MAIL_AUTOCOPY_TO; - // Action according to choosed sending method + // We set all data according to choosed sending method. + // We also set a value for ->msgid if ($this->sendmode == 'mail') { // Use mail php function (default PHP method) @@ -274,19 +276,19 @@ class CMailFile $text_body = ""; $files_encoded = ""; - // Define smtp_headers + // Define smtp_headers (this also set ->msgid) $smtp_headers = $this->write_smtpheaders(); - if (! empty($moreinheader)) $smtp_headers.=$moreinheader; // $moreinheader contains the \r\n + if (!empty($moreinheader)) $smtp_headers .= $moreinheader; // $moreinheader contains the \r\n // Define mime_headers $mime_headers = $this->write_mimeheaders($filename_list, $mimefilename_list); - if (! empty($this->html)) + if (!empty($this->html)) { if (!empty($css)) { $this->css = $css; - $this->buildCSS(); // Build a css style (mode = all) into this->styleCSS and this->bodyCSS + $this->buildCSS(); // Build a css style (mode = all) into this->styleCSS and this->bodyCSS } $msg = $this->html; @@ -302,15 +304,15 @@ class CMailFile } // We now define $this->headers and $this->message - $this->headers = $smtp_headers . $mime_headers; + $this->headers = $smtp_headers.$mime_headers; // On nettoie le header pour qu'il ne se termine pas par un retour chariot. // This avoid also empty lines at end that can be interpreted as mail injection by email servers. $this->headers = preg_replace("/([\r\n]+)$/i", "", $this->headers); //$this->message = $this->eol.'This is a message with multiple parts in MIME format.'.$this->eol; $this->message = 'This is a message with multiple parts in MIME format.'.$this->eol; - $this->message.= $text_body . $files_encoded; - $this->message.= "--" . $this->mixed_boundary . "--" . $this->eol; + $this->message .= $text_body.$files_encoded; + $this->message .= "--".$this->mixed_boundary."--".$this->eol; } elseif ($this->sendmode == 'smtps') { @@ -327,9 +329,9 @@ class CMailFile $smtps->setTrackId($trackid); $smtps->setReplyTo($this->getValidAddress($replyto, 0, 1)); - if (! empty($moreinheader)) $smtps->setMoreInHeader($moreinheader); + if (!empty($moreinheader)) $smtps->setMoreInHeader($moreinheader); - if (! empty($this->html)) + if (!empty($this->html)) { if (!empty($css)) { @@ -355,7 +357,7 @@ class CMailFile { foreach ($filename_list as $i => $val) { - $content=file_get_contents($filename_list[$i]); + $content = file_get_contents($filename_list[$i]); $smtps->setAttachment($content, $mimefilename_list[$i], $mimetype_list[$i]); } } @@ -365,7 +367,10 @@ class CMailFile $smtps->setErrorsTo($errors_to); $smtps->setDeliveryReceipt($deliveryreceipt); - $this->smtps=$smtps; + $host=dol_getprefix('email'); + $this->msgid = time() . '.SMTPs-dolibarr-'.$trackid.'@' . $host; + + $this->smtps = $smtps; } elseif ($this->sendmode == 'swiftmailer') { @@ -385,8 +390,9 @@ class CMailFile //$this->message = new Swift_SignedMessage(); // Adding a trackid header to a message $headers = $this->message->getHeaders(); - $headers->addTextHeader('X-Dolibarr-TRACKID', $trackid . '@' . $host); - $headerID = time() . '.swiftmailer-dolibarr-' . $trackid . '@' . $host; + $headers->addTextHeader('X-Dolibarr-TRACKID', $trackid.'@'.$host); + $this->msgid = time().'.swiftmailer-dolibarr-'.$trackid.'@'.$host; + $headerID = $this->msgid; $msgid = $headers->get('Message-ID'); $msgid->setId($headerID); $headers->addIdHeader('References', $headerID); @@ -396,12 +402,12 @@ class CMailFile try { $result = $this->message->setSubject($subject); } catch (Exception $e) { - $this->errors[] = $e->getMessage(); + $this->errors[] = $e->getMessage(); } // Set the From address with an associative array //$this->message->setFrom(array('john@doe.com' => 'John Doe')); - if (! empty($from)) { + if (!empty($from)) { try { $result = $this->message->setFrom($this->getArrayAddress($from)); } catch (Exception $e) { @@ -410,7 +416,7 @@ class CMailFile } // Set the To addresses with an associative array - if (! empty($to)) { + if (!empty($to)) { try { $result = $this->message->setTo($this->getArrayAddress($to)); } catch (Exception $e) { @@ -418,7 +424,7 @@ class CMailFile } } - if (! empty($replyto)) { + if (!empty($replyto)) { try { $result = $this->message->SetReplyTo($this->getArrayAddress($replyto)); } catch (Exception $e) { @@ -429,10 +435,10 @@ class CMailFile try { $result = $this->message->setCharSet($conf->file->character_set_client); } catch (Exception $e) { - $this->errors[] = $e->getMessage(); + $this->errors[] = $e->getMessage(); } - if (! empty($this->html)) { + if (!empty($this->html)) { if (!empty($css)) { $this->css = $css; $this->buildCSS(); @@ -474,8 +480,8 @@ class CMailFile } } - if (! empty($addr_cc)) $this->message->setCc($this->getArrayAddress($addr_cc)); - if (! empty($addr_bcc)) $this->message->setBcc($this->getArrayAddress($addr_bcc)); + if (!empty($addr_cc)) $this->message->setCc($this->getArrayAddress($addr_cc)); + if (!empty($addr_bcc)) $this->message->setBcc($this->getArrayAddress($addr_bcc)); //if (! empty($errors_to)) $this->message->setErrorsTo($this->getArrayAddress($errors_to); if (isset($deliveryreceipt) && $deliveryreceipt == 1) $this->message->setReadReceiptTo($this->getArrayAddress($from)); } @@ -495,25 +501,25 @@ class CMailFile */ public function sendfile() { - global $conf,$db,$langs; + global $conf, $db, $langs; - $errorlevel=error_reporting(); + $errorlevel = error_reporting(); //error_reporting($errorlevel ^ E_WARNING); // Desactive warnings - $res=false; + $res = false; if (empty($conf->global->MAIN_DISABLE_ALL_MAILS) || !empty($conf->global->MAIN_MAIL_FORCE_SENDTO)) { - require_once DOL_DOCUMENT_ROOT . '/core/class/hookmanager.class.php'; + require_once DOL_DOCUMENT_ROOT.'/core/class/hookmanager.class.php'; $hookmanager = new HookManager($db); $hookmanager->initHooks(array('mail')); - $parameters=array(); $action=''; + $parameters = array(); $action = ''; $reshook = $hookmanager->executeHooks('sendMail', $parameters, $this, $action); // Note that $action and $object may have been modified by some hooks if ($reshook < 0) { - $this->error = "Error in hook maildao sendMail " . $reshook; - dol_syslog("CMailFile::sendfile: mail end error=" . $this->error, LOG_ERR); + $this->error = "Error in hook maildao sendMail ".$reshook; + dol_syslog("CMailFile::sendfile: mail end error=".$this->error, LOG_ERR); return $reshook; } @@ -523,23 +529,23 @@ class CMailFile } $sendingmode = $this->sendmode; - if ($this->context == 'emailing' && ! empty($conf->global->MAILING_NO_USING_PHPMAIL) && $sendingmode == 'mail') + if ($this->context == 'emailing' && !empty($conf->global->MAILING_NO_USING_PHPMAIL) && $sendingmode == 'mail') { // List of sending methods - $listofmethods=array(); - $listofmethods['mail']='PHP mail function'; + $listofmethods = array(); + $listofmethods['mail'] = 'PHP mail function'; //$listofmethods['simplemail']='Simplemail class'; - $listofmethods['smtps']='SMTP/SMTPS socket library'; + $listofmethods['smtps'] = 'SMTP/SMTPS socket library'; // EMailing feature may be a spam problem, so when you host several users/instance, having this option may force each user to use their own SMTP agent. // You ensure that every user is using its own SMTP server when using the mass emailing module. - $linktoadminemailbefore=''; - $linktoadminemailend=''; + $linktoadminemailbefore = ''; + $linktoadminemailend = ''; $this->error = $langs->trans("MailSendSetupIs", $listofmethods[$sendingmode]); $this->errors[] = $langs->trans("MailSendSetupIs", $listofmethods[$sendingmode]); $this->error .= '
    '.$langs->trans("MailSendSetupIs2", $linktoadminemailbefore, $linktoadminemailend, $langs->transnoentitiesnoconv("MAIN_MAIL_SENDMODE"), $listofmethods['smtps']); $this->errors[] = $langs->trans("MailSendSetupIs2", $linktoadminemailbefore, $linktoadminemailend, $langs->transnoentitiesnoconv("MAIN_MAIL_SENDMODE"), $listofmethods['smtps']); - if (! empty($conf->global->MAILING_SMTP_SETUP_EMAILS_FOR_QUESTIONS)) + if (!empty($conf->global->MAILING_SMTP_SETUP_EMAILS_FOR_QUESTIONS)) { $this->error .= '
    '.$langs->trans("MailSendSetupIs3", $conf->global->MAILING_SMTP_SETUP_EMAILS_FOR_QUESTIONS); $this->errors[] = $langs->trans("MailSendSetupIs3", $conf->global->MAILING_SMTP_SETUP_EMAILS_FOR_QUESTIONS); @@ -548,52 +554,52 @@ class CMailFile } // Check number of recipient is lower or equal than MAIL_MAX_NB_OF_RECIPIENTS_IN_SAME_EMAIL - if (empty($conf->global->MAIL_MAX_NB_OF_RECIPIENTS_TO_IN_SAME_EMAIL)) $conf->global->MAIL_MAX_NB_OF_RECIPIENTS_TO_IN_SAME_EMAIL=10; + if (empty($conf->global->MAIL_MAX_NB_OF_RECIPIENTS_TO_IN_SAME_EMAIL)) $conf->global->MAIL_MAX_NB_OF_RECIPIENTS_TO_IN_SAME_EMAIL = 10; $tmparray1 = explode(',', $this->addr_to); if (count($tmparray1) > $conf->global->MAIL_MAX_NB_OF_RECIPIENTS_TO_IN_SAME_EMAIL) { $this->error = 'Too much recipients in to:'; - dol_syslog("CMailFile::sendfile: mail end error=" . $this->error, LOG_WARNING); + dol_syslog("CMailFile::sendfile: mail end error=".$this->error, LOG_WARNING); return false; } - if (empty($conf->global->MAIL_MAX_NB_OF_RECIPIENTS_CC_IN_SAME_EMAIL)) $conf->global->MAIL_MAX_NB_OF_RECIPIENTS_CC_IN_SAME_EMAIL=10; + if (empty($conf->global->MAIL_MAX_NB_OF_RECIPIENTS_CC_IN_SAME_EMAIL)) $conf->global->MAIL_MAX_NB_OF_RECIPIENTS_CC_IN_SAME_EMAIL = 10; $tmparray2 = explode(',', $this->addr_cc); if (count($tmparray2) > $conf->global->MAIL_MAX_NB_OF_RECIPIENTS_CC_IN_SAME_EMAIL) { $this->error = 'Too much recipients in cc:'; - dol_syslog("CMailFile::sendfile: mail end error=" . $this->error, LOG_WARNING); + dol_syslog("CMailFile::sendfile: mail end error=".$this->error, LOG_WARNING); return false; } - if (empty($conf->global->MAIL_MAX_NB_OF_RECIPIENTS_BCC_IN_SAME_EMAIL)) $conf->global->MAIL_MAX_NB_OF_RECIPIENTS_BCC_IN_SAME_EMAIL=10; + if (empty($conf->global->MAIL_MAX_NB_OF_RECIPIENTS_BCC_IN_SAME_EMAIL)) $conf->global->MAIL_MAX_NB_OF_RECIPIENTS_BCC_IN_SAME_EMAIL = 10; $tmparray3 = explode(',', $this->addr_bcc); if (count($tmparray3) > $conf->global->MAIL_MAX_NB_OF_RECIPIENTS_BCC_IN_SAME_EMAIL) { $this->error = 'Too much recipients in bcc:'; - dol_syslog("CMailFile::sendfile: mail end error=" . $this->error, LOG_WARNING); + dol_syslog("CMailFile::sendfile: mail end error=".$this->error, LOG_WARNING); return false; } - if (empty($conf->global->MAIL_MAX_NB_OF_RECIPIENTS_IN_SAME_EMAIL)) $conf->global->MAIL_MAX_NB_OF_RECIPIENTS_IN_SAME_EMAIL=10; - if ((count($tmparray1)+count($tmparray2)+count($tmparray3)) > $conf->global->MAIL_MAX_NB_OF_RECIPIENTS_IN_SAME_EMAIL) + if (empty($conf->global->MAIL_MAX_NB_OF_RECIPIENTS_IN_SAME_EMAIL)) $conf->global->MAIL_MAX_NB_OF_RECIPIENTS_IN_SAME_EMAIL = 10; + if ((count($tmparray1) + count($tmparray2) + count($tmparray3)) > $conf->global->MAIL_MAX_NB_OF_RECIPIENTS_IN_SAME_EMAIL) { $this->error = 'Too much recipients in to:, cc:, bcc:'; - dol_syslog("CMailFile::sendfile: mail end error=" . $this->error, LOG_WARNING); + dol_syslog("CMailFile::sendfile: mail end error=".$this->error, LOG_WARNING); return false; } - $keyforsmtpserver='MAIN_MAIL_SMTP_SERVER'; - $keyforsmtpport ='MAIN_MAIL_SMTP_PORT'; - $keyforsmtpid ='MAIN_MAIL_SMTPS_ID'; - $keyforsmtppw ='MAIN_MAIL_SMTPS_PW'; - $keyfortls ='MAIN_MAIL_EMAIL_TLS'; - $keyforstarttls ='MAIN_MAIL_EMAIL_STARTTLS'; + $keyforsmtpserver = 'MAIN_MAIL_SMTP_SERVER'; + $keyforsmtpport = 'MAIN_MAIL_SMTP_PORT'; + $keyforsmtpid = 'MAIN_MAIL_SMTPS_ID'; + $keyforsmtppw = 'MAIN_MAIL_SMTPS_PW'; + $keyfortls = 'MAIN_MAIL_EMAIL_TLS'; + $keyforstarttls = 'MAIN_MAIL_EMAIL_STARTTLS'; if ($this->sendcontext == 'emailing' && !empty($conf->global->MAIN_MAIL_SENDMODE_EMAILING) && $conf->global->MAIN_MAIL_SENDMODE_EMAILING != 'default') { - $keyforsmtpserver='MAIN_MAIL_SMTP_SERVER_EMAILING'; - $keyforsmtpport ='MAIN_MAIL_SMTP_PORT_EMAILING'; - $keyforsmtpid ='MAIN_MAIL_SMTPS_ID_EMAILING'; - $keyforsmtppw ='MAIN_MAIL_SMTPS_PW_EMAILING'; - $keyfortls ='MAIN_MAIL_EMAIL_TLS_EMAILING'; - $keyforstarttls ='MAIN_MAIL_EMAIL_STARTTLS_EMAILING'; + $keyforsmtpserver = 'MAIN_MAIL_SMTP_SERVER_EMAILING'; + $keyforsmtpport = 'MAIN_MAIL_SMTP_PORT_EMAILING'; + $keyforsmtpid = 'MAIN_MAIL_SMTPS_ID_EMAILING'; + $keyforsmtppw = 'MAIN_MAIL_SMTPS_PW_EMAILING'; + $keyfortls = 'MAIN_MAIL_EMAIL_TLS_EMAILING'; + $keyforstarttls = 'MAIN_MAIL_EMAIL_STARTTLS_EMAILING'; } if (!empty($conf->global->MAIN_MAIL_FORCE_SENDTO)) @@ -620,64 +626,64 @@ class CMailFile } // Force parameters - if (! empty($conf->global->$keyforsmtpserver)) ini_set('SMTP', $conf->global->$keyforsmtpserver); - if (! empty($conf->global->$keyforsmtpport)) ini_set('smtp_port', $conf->global->$keyforsmtpport); + if (!empty($conf->global->$keyforsmtpserver)) ini_set('SMTP', $conf->global->$keyforsmtpserver); + if (!empty($conf->global->$keyforsmtpport)) ini_set('smtp_port', $conf->global->$keyforsmtpport); - $res=true; - if ($res && ! $this->subject) + $res = true; + if ($res && !$this->subject) { - $this->error="Failed to send mail with php mail to HOST=".ini_get('SMTP').", PORT=".ini_get('smtp_port')."
    Subject is empty"; + $this->error = "Failed to send mail with php mail to HOST=".ini_get('SMTP').", PORT=".ini_get('smtp_port')."
    Subject is empty"; dol_syslog("CMailFile::sendfile: mail end error=".$this->error, LOG_ERR); - $res=false; + $res = false; } - $dest=$this->getValidAddress($this->addr_to, 2); - if ($res && ! $dest) + $dest = $this->getValidAddress($this->addr_to, 2); + if ($res && !$dest) { - $this->error="Failed to send mail with php mail to HOST=".ini_get('SMTP').", PORT=".ini_get('smtp_port')."
    Recipient address '$dest' invalid"; + $this->error = "Failed to send mail with php mail to HOST=".ini_get('SMTP').", PORT=".ini_get('smtp_port')."
    Recipient address '$dest' invalid"; dol_syslog("CMailFile::sendfile: mail end error=".$this->error, LOG_ERR); - $res=false; + $res = false; } if ($res) { - $additionnalparam = ''; // By default - if (! empty($conf->global->MAIN_MAIL_ALLOW_SENDMAIL_F)) + $additionnalparam = ''; // By default + if (!empty($conf->global->MAIN_MAIL_ALLOW_SENDMAIL_F)) { // le "Return-Path" (retour des messages bounced) dans les header ne fonctionne pas avec tous les MTA // Le forcage de la valeur grace à l'option -f de sendmail est donc possible si la constante MAIN_MAIL_ALLOW_SENDMAIL_F est definie. // Having this variable defined may create problems with some sendmail (option -f refused) // Having this variable not defined may create problems with some other sendmail (option -f required) - $additionnalparam .= ($additionnalparam?' ':'').(! empty($conf->global->MAIN_MAIL_ERRORS_TO) ? '-f' . $this->getValidAddress($conf->global->MAIN_MAIL_ERRORS_TO, 2) : ($this->addr_from != '' ? '-f' . $this->getValidAddress($this->addr_from, 2) : '') ); + $additionnalparam .= ($additionnalparam ? ' ' : '').(!empty($conf->global->MAIN_MAIL_ERRORS_TO) ? '-f'.$this->getValidAddress($conf->global->MAIN_MAIL_ERRORS_TO, 2) : ($this->addr_from != '' ? '-f'.$this->getValidAddress($this->addr_from, 2) : '')); } - if (! empty($conf->global->MAIN_MAIL_SENDMAIL_FORCE_BA)) // To force usage of -ba option. This option tells sendmail to read From: or Sender: to setup sender + if (!empty($conf->global->MAIN_MAIL_SENDMAIL_FORCE_BA)) // To force usage of -ba option. This option tells sendmail to read From: or Sender: to setup sender { - $additionnalparam .= ($additionnalparam?' ':'').'-ba'; + $additionnalparam .= ($additionnalparam ? ' ' : '').'-ba'; } - if (! empty($conf->global->MAIN_MAIL_SENDMAIL_FORCE_ADDPARAM)) $additionnalparam .= ($additionnalparam?' ':'').'-U '.$additionnalparam; // Use -U to add additionnal params + if (!empty($conf->global->MAIN_MAIL_SENDMAIL_FORCE_ADDPARAM)) $additionnalparam .= ($additionnalparam ? ' ' : '').'-U '.$additionnalparam; // Use -U to add additionnal params dol_syslog("CMailFile::sendfile: mail start HOST=".ini_get('SMTP').", PORT=".ini_get('smtp_port').", additionnal_parameters=".$additionnalparam, LOG_DEBUG); - $this->message=stripslashes($this->message); + $this->message = stripslashes($this->message); - if (! empty($conf->global->MAIN_MAIL_DEBUG)) $this->dump_mail(); + if (!empty($conf->global->MAIN_MAIL_DEBUG)) $this->dump_mail(); - if (! empty($additionnalparam)) $res = mail($dest, $this->encodetorfc2822($this->subject), $this->message, $this->headers, $additionnalparam); + if (!empty($additionnalparam)) $res = mail($dest, $this->encodetorfc2822($this->subject), $this->message, $this->headers, $additionnalparam); else $res = mail($dest, $this->encodetorfc2822($this->subject), $this->message, $this->headers); - if (! $res) + if (!$res) { $langs->load("errors"); - $this->error="Failed to send mail with php mail"; - $linuxlike=1; - if (preg_match('/^win/i', PHP_OS)) $linuxlike=0; - if (preg_match('/^mac/i', PHP_OS)) $linuxlike=0; - if (! $linuxlike) + $this->error = "Failed to send mail with php mail"; + $linuxlike = 1; + if (preg_match('/^win/i', PHP_OS)) $linuxlike = 0; + if (preg_match('/^mac/i', PHP_OS)) $linuxlike = 0; + if (!$linuxlike) { - $this->error.=" to HOST=".ini_get('SMTP').", PORT=".ini_get('smtp_port'); // This values are value used only for non linuxlike systems + $this->error .= " to HOST=".ini_get('SMTP').", PORT=".ini_get('smtp_port'); // This values are value used only for non linuxlike systems } - $this->error.=".
    "; - $this->error.=$langs->trans("ErrorPhpMailDelivery"); + $this->error .= ".
    "; + $this->error .= $langs->trans("ErrorPhpMailDelivery"); dol_syslog("CMailFile::sendfile: mail end error=".$this->error, LOG_ERR); } else @@ -692,86 +698,86 @@ class CMailFile } // Restore parameters - if (! empty($conf->global->$keyforsmtpserver)) ini_restore('SMTP'); - if (! empty($conf->global->$keyforsmtpport)) ini_restore('smtp_port'); + if (!empty($conf->global->$keyforsmtpserver)) ini_restore('SMTP'); + if (!empty($conf->global->$keyforsmtpport)) ini_restore('smtp_port'); } elseif ($this->sendmode == 'smtps') { - if (! is_object($this->smtps)) + if (!is_object($this->smtps)) { - $this->error="Failed to send mail with smtps lib to HOST=".$server.", PORT=".$conf->global->$keyforsmtpport."
    Constructor of object CMailFile was not initialized without errors."; + $this->error = "Failed to send mail with smtps lib to HOST=".$server.", PORT=".$conf->global->$keyforsmtpport."
    Constructor of object CMailFile was not initialized without errors."; dol_syslog("CMailFile::sendfile: mail end error=".$this->error, LOG_ERR); return false; } // Use SMTPS library // ------------------------------------------ - $this->smtps->setTransportType(0); // Only this method is coded in SMTPs library + $this->smtps->setTransportType(0); // Only this method is coded in SMTPs library // Clean parameters - if (empty($conf->global->$keyforsmtpserver)) $conf->global->$keyforsmtpserver=ini_get('SMTP'); - if (empty($conf->global->$keyforsmtpport)) $conf->global->$keyforsmtpport=ini_get('smtp_port'); + if (empty($conf->global->$keyforsmtpserver)) $conf->global->$keyforsmtpserver = ini_get('SMTP'); + if (empty($conf->global->$keyforsmtpport)) $conf->global->$keyforsmtpport = ini_get('smtp_port'); // If we use SSL/TLS - $server=$conf->global->$keyforsmtpserver; - $secure=''; - if (! empty($conf->global->$keyfortls) && function_exists('openssl_open')) $secure='ssl'; - if (! empty($conf->global->$keyforstarttls) && function_exists('openssl_open')) $secure='tls'; - $server=($secure?$secure.'://':'').$server; + $server = $conf->global->$keyforsmtpserver; + $secure = ''; + if (!empty($conf->global->$keyfortls) && function_exists('openssl_open')) $secure = 'ssl'; + if (!empty($conf->global->$keyforstarttls) && function_exists('openssl_open')) $secure = 'tls'; + $server = ($secure ? $secure.'://' : '').$server; - $port=$conf->global->$keyforsmtpport; + $port = $conf->global->$keyforsmtpport; $this->smtps->setHost($server); $this->smtps->setPort($port); // 25, 465...; - $loginid=''; $loginpass=''; - if (! empty($conf->global->$keyforsmtpid)) + $loginid = ''; $loginpass = ''; + if (!empty($conf->global->$keyforsmtpid)) { $loginid = $conf->global->$keyforsmtpid; $this->smtps->setID($loginid); } - if (! empty($conf->global->$keyforsmtppw)) + if (!empty($conf->global->$keyforsmtppw)) { $loginpass = $conf->global->$keyforsmtppw; $this->smtps->setPW($loginpass); } - $res=true; - $from=$this->smtps->getFrom('org'); - if ($res && ! $from) + $res = true; + $from = $this->smtps->getFrom('org'); + if ($res && !$from) { - $this->error="Failed to send mail with smtps lib to HOST=".$server.", PORT=".$conf->global->$keyforsmtpport."
    Sender address '$from' invalid"; + $this->error = "Failed to send mail with smtps lib to HOST=".$server.", PORT=".$conf->global->$keyforsmtpport."
    Sender address '$from' invalid"; dol_syslog("CMailFile::sendfile: mail end error=".$this->error, LOG_ERR); - $res=false; + $res = false; } - $dest=$this->smtps->getTo(); - if ($res && ! $dest) + $dest = $this->smtps->getTo(); + if ($res && !$dest) { - $this->error="Failed to send mail with smtps lib to HOST=".$server.", PORT=".$conf->global->$keyforsmtpport."
    Recipient address '$dest' invalid"; + $this->error = "Failed to send mail with smtps lib to HOST=".$server.", PORT=".$conf->global->$keyforsmtpport."
    Recipient address '$dest' invalid"; dol_syslog("CMailFile::sendfile: mail end error=".$this->error, LOG_ERR); - $res=false; + $res = false; } if ($res) { - if (! empty($conf->global->MAIN_MAIL_DEBUG)) $this->smtps->setDebug(true); + if (!empty($conf->global->MAIN_MAIL_DEBUG)) $this->smtps->setDebug(true); - $result=$this->smtps->sendMsg(); + $result = $this->smtps->sendMsg(); //print $result; - if (! empty($conf->global->MAIN_MAIL_DEBUG)) $this->dump_mail(); + if (!empty($conf->global->MAIN_MAIL_DEBUG)) $this->dump_mail(); - $result=$this->smtps->getErrors(); + $result = $this->smtps->getErrors(); if (empty($this->error) && empty($result)) { dol_syslog("CMailFile::sendfile: mail end success", LOG_DEBUG); - $res=true; + $res = true; } else { - if (empty($this->error)) $this->error=$result; + if (empty($this->error)) $this->error = $result; dol_syslog("CMailFile::sendfile: mail end error=".$this->error, LOG_ERR); - $res=false; + $res = false; } } } @@ -782,19 +788,19 @@ class CMailFile require_once DOL_DOCUMENT_ROOT.'/includes/swiftmailer/lib/swift_required.php'; // Clean parameters - if (empty($conf->global->$keyforsmtpserver)) $conf->global->$keyforsmtpserver=ini_get('SMTP'); - if (empty($conf->global->$keyforsmtpport)) $conf->global->$keyforsmtpport=ini_get('smtp_port'); + if (empty($conf->global->$keyforsmtpserver)) $conf->global->$keyforsmtpserver = ini_get('SMTP'); + if (empty($conf->global->$keyforsmtpport)) $conf->global->$keyforsmtpport = ini_get('smtp_port'); // If we use SSL/TLS $server = $conf->global->$keyforsmtpserver; $secure = ''; - if (! empty($conf->global->$keyfortls) && function_exists('openssl_open')) $secure='ssl'; - if (! empty($conf->global->$keyforstarttls) && function_exists('openssl_open')) $secure='tls'; + if (!empty($conf->global->$keyfortls) && function_exists('openssl_open')) $secure = 'ssl'; + if (!empty($conf->global->$keyforstarttls) && function_exists('openssl_open')) $secure = 'tls'; $this->transport = new Swift_SmtpTransport($server, $conf->global->$keyforsmtpport, $secure); - if (! empty($conf->global->$keyforsmtpid)) $this->transport->setUsername($conf->global->$keyforsmtpid); - if (! empty($conf->global->$keyforsmtppw)) $this->transport->setPassword($conf->global->$keyforsmtppw); + if (!empty($conf->global->$keyforsmtpid)) $this->transport->setUsername($conf->global->$keyforsmtpid); + if (!empty($conf->global->$keyforsmtppw)) $this->transport->setPassword($conf->global->$keyforsmtppw); //$smtps->_msgReplyTo = 'reply@web.com'; // Create the Mailer using your created Transport @@ -809,7 +815,7 @@ class CMailFile $this->message->attachSigner($signer->ignoreHeader('Return-Path')); } - if (! empty($conf->global->MAIN_MAIL_DEBUG)) { + if (!empty($conf->global->MAIN_MAIL_DEBUG)) { // To use the ArrayLogger $this->logger = new Swift_Plugins_Loggers_ArrayLogger(); // Or to use the Echo Logger @@ -820,14 +826,14 @@ class CMailFile try { $result = $this->mailer->send($this->message); } catch (Exception $e) { - $this->error = $e->getMessage(); + $this->error = $e->getMessage(); } - if (! empty($conf->global->MAIN_MAIL_DEBUG)) $this->dump_mail(); + if (!empty($conf->global->MAIN_MAIL_DEBUG)) $this->dump_mail(); $res = true; - if (! empty($this->error) || ! $result) { + if (!empty($this->error) || !$result) { dol_syslog("CMailFile::sendfile: mail end error=".$this->error, LOG_ERR); - $res=false; + $res = false; } else { @@ -842,23 +848,23 @@ class CMailFile return 'Bad value for sendmode'; } - $parameters=array(); $action=''; + $parameters = array(); $action = ''; $reshook = $hookmanager->executeHooks('sendMailAfter', $parameters, $this, $action); // Note that $action and $object may have been modified by some hooks if ($reshook < 0) { - $this->error = "Error in hook maildao sendMailAfter " . $reshook; - dol_syslog("CMailFile::sendfile: mail end error=" . $this->error, LOG_ERR); + $this->error = "Error in hook maildao sendMailAfter ".$reshook; + dol_syslog("CMailFile::sendfile: mail end error=".$this->error, LOG_ERR); return $reshook; } } else { - $this->error='No mail sent. Feature is disabled by option MAIN_DISABLE_ALL_MAILS'; + $this->error = 'No mail sent. Feature is disabled by option MAIN_DISABLE_ALL_MAILS'; dol_syslog("CMailFile::sendfile: ".$this->error, LOG_WARNING); } - error_reporting($errorlevel); // Reactive niveau erreur origine + error_reporting($errorlevel); // Reactive niveau erreur origine return $res; } @@ -885,17 +891,17 @@ class CMailFile private function _encode_file($sourcefile) { // phpcs:enable - $newsourcefile=dol_osencode($sourcefile); + $newsourcefile = dol_osencode($sourcefile); if (is_readable($newsourcefile)) { - $contents = file_get_contents($newsourcefile); // Need PHP 4.3 - $encoded = chunk_split(base64_encode($contents), 76, $this->eol); // 76 max is defined into http://tools.ietf.org/html/rfc2047 + $contents = file_get_contents($newsourcefile); // Need PHP 4.3 + $encoded = chunk_split(base64_encode($contents), 76, $this->eol); // 76 max is defined into http://tools.ietf.org/html/rfc2047 return $encoded; } else { - $this->error="Error: Can't read file '".$sourcefile."' into _encode_file"; + $this->error = "Error: Can't read file '".$sourcefile."' into _encode_file"; dol_syslog("CMailFile::encode_file: ".$this->error, LOG_ERR); return -1; } @@ -913,30 +919,30 @@ class CMailFile public function dump_mail() { // phpcs:enable - global $conf,$dolibarr_main_data_root; + global $conf, $dolibarr_main_data_root; if (@is_writeable($dolibarr_main_data_root)) // Avoid fatal error on fopen with open_basedir { - $outputfile=$dolibarr_main_data_root."/dolibarr_mail.log"; + $outputfile = $dolibarr_main_data_root."/dolibarr_mail.log"; $fp = fopen($outputfile, "w"); if ($this->sendmode == 'mail') { fputs($fp, $this->headers); - fputs($fp, $this->eol); // This eol is added by the mail function, so we add it in log + fputs($fp, $this->eol); // This eol is added by the mail function, so we add it in log fputs($fp, $this->message); } elseif ($this->sendmode == 'smtps') { - fputs($fp, $this->smtps->log); // this->smtps->log is filled only if MAIN_MAIL_DEBUG was set to on + fputs($fp, $this->smtps->log); // this->smtps->log is filled only if MAIN_MAIL_DEBUG was set to on } elseif ($this->sendmode == 'swiftmailer') { - fputs($fp, $this->logger->dump()); // this->logger is filled only if MAIN_MAIL_DEBUG was set to on + fputs($fp, $this->logger->dump()); // this->logger is filled only if MAIN_MAIL_DEBUG was set to on } fclose($fp); - if (! empty($conf->global->MAIN_UMASK)) + if (!empty($conf->global->MAIN_UMASK)) @chmod($outputfile, octdec($conf->global->MAIN_UMASK)); } } @@ -953,12 +959,12 @@ class CMailFile if (!preg_match('/^[\s\t]*styleCSS)) $out.= $this->styleCSS; - $out.= "bodyCSS)) $out.= $this->bodyCSS; - $out.= ">"; - $out.= $msg; - $out.= ""; + if (!empty($this->styleCSS)) $out .= $this->styleCSS; + $out .= "bodyCSS)) $out .= $this->bodyCSS; + $out .= ">"; + $out .= $msg; + $out .= ""; } else { @@ -975,24 +981,24 @@ class CMailFile */ public function buildCSS() { - if (! empty($this->css)) + if (!empty($this->css)) { // Style CSS $this->styleCSS = ''; + $this->styleCSS .= '}'; + $this->styleCSS .= ''; } } @@ -1013,48 +1019,50 @@ class CMailFile // Sender //$out.= "Sender: ".getValidAddress($this->addr_from,2)).$this->eol2; - $out.= "From: ".$this->getValidAddress($this->addr_from, 3, 1).$this->eol2; - if (! empty($conf->global->MAIN_MAIL_SENDMAIL_FORCE_BA)) + $out .= "From: ".$this->getValidAddress($this->addr_from, 3, 1).$this->eol2; + if (!empty($conf->global->MAIN_MAIL_SENDMAIL_FORCE_BA)) { - $out.= "To: ".$this->getValidAddress($this->addr_to, 0, 1).$this->eol2; + $out .= "To: ".$this->getValidAddress($this->addr_to, 0, 1).$this->eol2; } // Return-Path is important because it is used by SPF. Some MTA does not read Return-Path from header but from command line. See option MAIN_MAIL_ALLOW_SENDMAIL_F for that. - $out.= "Return-Path: ".$this->getValidAddress($this->addr_from, 0, 1).$this->eol2; - if (isset($this->reply_to) && $this->reply_to) $out.= "Reply-To: ".$this->getValidAddress($this->reply_to, 2).$this->eol2; - if (isset($this->errors_to) && $this->errors_to) $out.= "Errors-To: ".$this->getValidAddress($this->errors_to, 2).$this->eol2; + $out .= "Return-Path: ".$this->getValidAddress($this->addr_from, 0, 1).$this->eol2; + if (isset($this->reply_to) && $this->reply_to) $out .= "Reply-To: ".$this->getValidAddress($this->reply_to, 2).$this->eol2; + if (isset($this->errors_to) && $this->errors_to) $out .= "Errors-To: ".$this->getValidAddress($this->errors_to, 2).$this->eol2; // Receiver - if (isset($this->addr_cc) && $this->addr_cc) $out.= "Cc: ".$this->getValidAddress($this->addr_cc, 2).$this->eol2; - if (isset($this->addr_bcc) && $this->addr_bcc) $out.= "Bcc: ".$this->getValidAddress($this->addr_bcc, 2).$this->eol2; // TODO Question: bcc must not be into header, only into SMTP command "RCPT TO". Does php mail support this ? + if (isset($this->addr_cc) && $this->addr_cc) $out .= "Cc: ".$this->getValidAddress($this->addr_cc, 2).$this->eol2; + if (isset($this->addr_bcc) && $this->addr_bcc) $out .= "Bcc: ".$this->getValidAddress($this->addr_bcc, 2).$this->eol2; // TODO Question: bcc must not be into header, only into SMTP command "RCPT TO". Does php mail support this ? // Delivery receipt - if (isset($this->deliveryreceipt) && $this->deliveryreceipt == 1) $out.= "Disposition-Notification-To: ".$this->getValidAddress($this->addr_from, 2).$this->eol2; + if (isset($this->deliveryreceipt) && $this->deliveryreceipt == 1) $out .= "Disposition-Notification-To: ".$this->getValidAddress($this->addr_from, 2).$this->eol2; //$out.= "X-Priority: 3".$this->eol2; - $out.= 'Date: ' . date("r") . $this->eol2; + $out .= 'Date: '.date("r").$this->eol2; $trackid = $this->trackid; if ($trackid) { // References is kept in response and Message-ID is returned into In-Reply-To: - $out.= 'Message-ID: <' . time() . '.phpmail-dolibarr-'. $trackid . '@' . $host . ">" . $this->eol2; // Uppercase seems replaced by phpmail - $out.= 'References: <' . time() . '.phpmail-dolibarr-'. $trackid . '@' . $host . ">" . $this->eol2; - $out.= 'X-Dolibarr-TRACKID: ' . $trackid . '@' . $host. $this->eol2; + $this->msgid = time().'.phpmail-dolibarr-'.$trackid.'@'.$host; + $out .= 'Message-ID: <'.$this->msgid.">".$this->eol2; // Uppercase seems replaced by phpmail + $out .= 'References: <'.$this->msgid.">".$this->eol2; + $out .= 'X-Dolibarr-TRACKID: '.$trackid.'@'.$host.$this->eol2; } else { - $out.= 'Message-ID: <' . time() . '.phpmail@' . $host . ">" . $this->eol2; + $this->msgid = time().'.phpmail@'.$host; + $out .= 'Message-ID: <'.$this->msgid.">".$this->eol2; } - if (! empty($_SERVER['REMOTE_ADDR'])) $out.= "X-RemoteAddr: " . $_SERVER['REMOTE_ADDR']. $this->eol2; - $out.= "X-Mailer: Dolibarr version " . DOL_VERSION ." (using php mail)".$this->eol2; - $out.= "Mime-Version: 1.0".$this->eol2; + if (!empty($_SERVER['REMOTE_ADDR'])) $out .= "X-RemoteAddr: ".$_SERVER['REMOTE_ADDR'].$this->eol2; + $out .= "X-Mailer: Dolibarr version ".DOL_VERSION." (using php mail)".$this->eol2; + $out .= "Mime-Version: 1.0".$this->eol2; //$out.= "From: ".$this->getValidAddress($this->addr_from,3,1).$this->eol; - $out.= "Content-Type: multipart/mixed;".$this->eol2." boundary=\"".$this->mixed_boundary."\"".$this->eol2; - $out.= "Content-Transfer-Encoding: 8bit".$this->eol2; // TODO Seems to be ignored. Header is 7bit once received. + $out .= "Content-Type: multipart/mixed;".$this->eol2." boundary=\"".$this->mixed_boundary."\"".$this->eol2; + $out .= "Content-Transfer-Encoding: 8bit".$this->eol2; // TODO Seems to be ignored. Header is 7bit once received. dol_syslog("CMailFile::write_smtpheaders smtp_header=\n".$out); return $out; @@ -1072,18 +1080,18 @@ class CMailFile public function write_mimeheaders($filename_list, $mimefilename_list) { // phpcs:enable - $mimedone=0; + $mimedone = 0; $out = ""; if (is_array($filename_list)) { - $filename_list_size=count($filename_list); - for($i=0;$i < $filename_list_size;$i++) + $filename_list_size = count($filename_list); + for ($i = 0; $i < $filename_list_size; $i++) { if ($filename_list[$i]) { if ($mimefilename_list[$i]) $filename_list[$i] = $mimefilename_list[$i]; - $out.= "X-attachments: $filename_list[$i]".$this->eol2; + $out .= "X-attachments: $filename_list[$i]".$this->eol2; } } } @@ -1104,31 +1112,31 @@ class CMailFile // phpcs:enable global $conf; - $out=''; + $out = ''; - $out.= "--" . $this->mixed_boundary . $this->eol; + $out .= "--".$this->mixed_boundary.$this->eol; if ($this->atleastoneimage) { - $out.= "Content-Type: multipart/alternative;".$this->eol." boundary=\"".$this->alternative_boundary."\"".$this->eol; - $out.= $this->eol; - $out.= "--" . $this->alternative_boundary . $this->eol; + $out .= "Content-Type: multipart/alternative;".$this->eol." boundary=\"".$this->alternative_boundary."\"".$this->eol; + $out .= $this->eol; + $out .= "--".$this->alternative_boundary.$this->eol; } // Make RFC821 Compliant, replace bare linefeeds - $strContent = preg_replace("/(?global->MAIN_FIX_FOR_BUGGED_MTA)) + $strContent = preg_replace("/(?global->MAIN_FIX_FOR_BUGGED_MTA)) { - $strContent = preg_replace("/\r\n/si", "\n", $strContent); // PCRE modifier /s means new lines are common chars + $strContent = preg_replace("/\r\n/si", "\n", $strContent); // PCRE modifier /s means new lines are common chars } $strContentAltText = ''; if ($this->msgishtml) { - // Similar code to forge a text from html is also in CMailFile.class.php + // Similar code to forge a text from html is also in smtps.class.php $strContentAltText = preg_replace("/]*>/", " ", $strContent); $strContentAltText = html_entity_decode(strip_tags($strContentAltText)); - $strContentAltText = rtrim(wordwrap($strContentAltText, 75, empty($conf->global->MAIN_FIX_FOR_BUGGED_MTA)?"\r\n":"\n")); + $strContentAltText = trim(wordwrap($strContentAltText, 75, empty($conf->global->MAIN_FIX_FOR_BUGGED_MTA) ? "\r\n" : "\n")); // Check if html header already in message, if not complete the message $strContent = $this->checkIfHTML($strContent); @@ -1137,57 +1145,57 @@ class CMailFile // Make RFC2045 Compliant, split lines //$strContent = rtrim(chunk_split($strContent)); // Function chunck_split seems ko if not used on a base64 content // TODO Encode main content into base64 and use the chunk_split, or quoted-printable - $strContent = rtrim(wordwrap($strContent, 75, empty($conf->global->MAIN_FIX_FOR_BUGGED_MTA)?"\r\n":"\n")); // TODO Using this method creates unexpected line break on text/plain content. + $strContent = rtrim(wordwrap($strContent, 75, empty($conf->global->MAIN_FIX_FOR_BUGGED_MTA) ? "\r\n" : "\n")); // TODO Using this method creates unexpected line break on text/plain content. if ($this->msgishtml) { if ($this->atleastoneimage) { - $out.= "Content-Type: text/plain; charset=".$conf->file->character_set_client.$this->eol; + $out .= "Content-Type: text/plain; charset=".$conf->file->character_set_client.$this->eol; //$out.= "Content-Transfer-Encoding: 7bit".$this->eol; - $out.= $this->eol.($strContentAltText?$strContentAltText:strip_tags($strContent)).$this->eol; // Add plain text message - $out.= "--" . $this->alternative_boundary . $this->eol; - $out.= "Content-Type: multipart/related;".$this->eol." boundary=\"".$this->related_boundary."\"".$this->eol; - $out.= $this->eol; - $out.= "--" . $this->related_boundary . $this->eol; + $out .= $this->eol.($strContentAltText ? $strContentAltText : strip_tags($strContent)).$this->eol; // Add plain text message + $out .= "--".$this->alternative_boundary.$this->eol; + $out .= "Content-Type: multipart/related;".$this->eol." boundary=\"".$this->related_boundary."\"".$this->eol; + $out .= $this->eol; + $out .= "--".$this->related_boundary.$this->eol; } - if (! $this->atleastoneimage && $strContentAltText && ! empty($conf->global->MAIN_MAIL_USE_MULTI_PART)) // Add plain text message part before html part + if (!$this->atleastoneimage && $strContentAltText && !empty($conf->global->MAIN_MAIL_USE_MULTI_PART)) // Add plain text message part before html part { - $out.= "Content-Type: multipart/alternative;".$this->eol." boundary=\"".$this->alternative_boundary."\"".$this->eol; - $out.= $this->eol; - $out.= "--" . $this->alternative_boundary . $this->eol; - $out.= "Content-Type: text/plain; charset=".$conf->file->character_set_client.$this->eol; + $out .= "Content-Type: multipart/alternative;".$this->eol." boundary=\"".$this->alternative_boundary."\"".$this->eol; + $out .= $this->eol; + $out .= "--".$this->alternative_boundary.$this->eol; + $out .= "Content-Type: text/plain; charset=".$conf->file->character_set_client.$this->eol; //$out.= "Content-Transfer-Encoding: 7bit".$this->eol; - $out.= $this->eol.$strContentAltText.$this->eol; - $out.= "--" . $this->alternative_boundary . $this->eol; + $out .= $this->eol.$strContentAltText.$this->eol; + $out .= "--".$this->alternative_boundary.$this->eol; } - $out.= "Content-Type: text/html; charset=".$conf->file->character_set_client.$this->eol; + $out .= "Content-Type: text/html; charset=".$conf->file->character_set_client.$this->eol; //$out.= "Content-Transfer-Encoding: 7bit".$this->eol; // TODO Use base64 - $out.= $this->eol.$strContent.$this->eol; + $out .= $this->eol.$strContent.$this->eol; - if (! $this->atleastoneimage && $strContentAltText && ! empty($conf->global->MAIN_MAIL_USE_MULTI_PART)) // Add plain text message part after html part + if (!$this->atleastoneimage && $strContentAltText && !empty($conf->global->MAIN_MAIL_USE_MULTI_PART)) // Add plain text message part after html part { - $out.= "--" . $this->alternative_boundary . "--". $this->eol; + $out .= "--".$this->alternative_boundary."--".$this->eol; } } else { - $out.= "Content-Type: text/plain; charset=".$conf->file->character_set_client.$this->eol; + $out .= "Content-Type: text/plain; charset=".$conf->file->character_set_client.$this->eol; //$out.= "Content-Transfer-Encoding: 7bit".$this->eol; - $out.= $this->eol.$strContent.$this->eol; + $out .= $this->eol.$strContent.$this->eol; } - $out.= $this->eol; + $out .= $this->eol; // Encode images if ($this->atleastoneimage) { $out .= $this->write_images($this->images_encoded); // always end related and end alternative after inline images - $out .= "--" . $this->related_boundary . "--" . $this->eol; - $out .= $this->eol . "--" . $this->alternative_boundary . "--" . $this->eol; + $out .= "--".$this->related_boundary."--".$this->eol; + $out .= $this->eol."--".$this->alternative_boundary."--".$this->eol; $out .= $this->eol; } @@ -1208,8 +1216,8 @@ class CMailFile // phpcs:enable $out = ''; - $filename_list_size=count($filename_list); - for($i=0;$i < $filename_list_size;$i++) + $filename_list_size = count($filename_list); + for ($i = 0; $i < $filename_list_size; $i++) { if ($filename_list[$i]) { @@ -1218,18 +1226,18 @@ class CMailFile if ($encoded >= 0) { if ($mimefilename_list[$i]) $filename_list[$i] = $mimefilename_list[$i]; - if (! $mimetype_list[$i]) { + if (!$mimetype_list[$i]) { $mimetype_list[$i] = "application/octet-stream"; } - $out.= "--" . $this->mixed_boundary . $this->eol; - $out.= "Content-Disposition: attachment; filename=\"".$filename_list[$i]."\"".$this->eol; - $out.= "Content-Type: " . $mimetype_list[$i] . "; name=\"".$filename_list[$i]."\"".$this->eol; - $out.= "Content-Transfer-Encoding: base64".$this->eol; - $out.= "Content-Description: ".$filename_list[$i].$this->eol; - $out.= $this->eol; - $out.= $encoded; - $out.= $this->eol; + $out .= "--".$this->mixed_boundary.$this->eol; + $out .= "Content-Disposition: attachment; filename=\"".$filename_list[$i]."\"".$this->eol; + $out .= "Content-Type: ".$mimetype_list[$i]."; name=\"".$filename_list[$i]."\"".$this->eol; + $out .= "Content-Transfer-Encoding: base64".$this->eol; + $out .= "Content-Description: ".$filename_list[$i].$this->eol; + $out .= $this->eol; + $out .= $encoded; + $out .= $this->eol; //$out.= $this->eol; } else @@ -1261,14 +1269,14 @@ class CMailFile { dol_syslog("CMailFile::write_images: ".$img["name"]); - $out.= "--" . $this->related_boundary . $this->eol; // always related for an inline image - $out.= "Content-Type: " . $img["content_type"] . "; name=\"".$img["name"]."\"".$this->eol; - $out.= "Content-Transfer-Encoding: base64".$this->eol; - $out.= "Content-Disposition: inline; filename=\"".$img["name"]."\"".$this->eol; - $out.= "Content-ID: <".$img["cid"].">".$this->eol; - $out.= $this->eol; - $out.= $img["image_encoded"]; - $out.= $this->eol; + $out .= "--".$this->related_boundary.$this->eol; // always related for an inline image + $out .= "Content-Type: ".$img["content_type"]."; name=\"".$img["name"]."\"".$this->eol; + $out .= "Content-Transfer-Encoding: base64".$this->eol; + $out .= "Content-Disposition: inline; filename=\"".$img["name"]."\"".$this->eol; + $out .= "Content-ID: <".$img["cid"].">".$this->eol; + $out .= $this->eol; + $out .= $img["image_encoded"]; + $out .= $this->eol; } } @@ -1289,39 +1297,39 @@ class CMailFile // phpcs:enable global $conf; - $_retVal=0; - $timeout=5; // Timeout in seconds + $_retVal = 0; + $timeout = 5; // Timeout in seconds if (function_exists('fsockopen')) { - $keyforsmtpserver='MAIN_MAIL_SMTP_SERVER'; - $keyforsmtpport ='MAIN_MAIL_SMTP_PORT'; - $keyforsmtpid ='MAIN_MAIL_SMTPS_ID'; - $keyforsmtppw ='MAIN_MAIL_SMTPS_PW'; - $keyfortls ='MAIN_MAIL_EMAIL_TLS'; - $keyforstarttls ='MAIN_MAIL_EMAIL_STARTTLS'; + $keyforsmtpserver = 'MAIN_MAIL_SMTP_SERVER'; + $keyforsmtpport = 'MAIN_MAIL_SMTP_PORT'; + $keyforsmtpid = 'MAIN_MAIL_SMTPS_ID'; + $keyforsmtppw = 'MAIN_MAIL_SMTPS_PW'; + $keyfortls = 'MAIN_MAIL_EMAIL_TLS'; + $keyforstarttls = 'MAIN_MAIL_EMAIL_STARTTLS'; if ($this->sendcontext == 'emailing' && !empty($conf->global->MAIN_MAIL_SENDMODE_EMAILING) && $conf->global->MAIN_MAIL_SENDMODE_EMAILING != 'default') { - $keyforsmtpserver='MAIN_MAIL_SMTP_SERVER_EMAILING'; - $keyforsmtpport ='MAIN_MAIL_SMTP_PORT_EMAILING'; - $keyforsmtpid ='MAIN_MAIL_SMTPS_ID_EMAILING'; - $keyforsmtppw ='MAIN_MAIL_SMTPS_PW_EMAILING'; - $keyfortls ='MAIN_MAIL_EMAIL_TLS_EMAILING'; - $keyforstarttls ='MAIN_MAIL_EMAIL_STARTTLS_EMAILING'; + $keyforsmtpserver = 'MAIN_MAIL_SMTP_SERVER_EMAILING'; + $keyforsmtpport = 'MAIN_MAIL_SMTP_PORT_EMAILING'; + $keyforsmtpid = 'MAIN_MAIL_SMTPS_ID_EMAILING'; + $keyforsmtppw = 'MAIN_MAIL_SMTPS_PW_EMAILING'; + $keyfortls = 'MAIN_MAIL_EMAIL_TLS_EMAILING'; + $keyforstarttls = 'MAIN_MAIL_EMAIL_STARTTLS_EMAILING'; } // If we use SSL/TLS - if (! empty($conf->global->$keyfortls) && function_exists('openssl_open')) $host='ssl://'.$host; + if (!empty($conf->global->$keyfortls) && function_exists('openssl_open')) $host = 'ssl://'.$host; // tls smtp start with no encryption //if (! empty($conf->global->MAIN_MAIL_EMAIL_STARTTLS) && function_exists('openssl_open')) $host='tls://'.$host; dol_syslog("Try socket connection to host=".$host." port=".$port); //See if we can connect to the SMTP server if ($socket = @fsockopen( - $host, // Host to test, IP or domain. Add ssl:// for SSL/TLS. - $port, // which Port number to use - $errno, // actual system level error - $errstr, // and any text that goes with the error + $host, // Host to test, IP or domain. Add ssl:// for SSL/TLS. + $port, // which Port number to use + $errno, // actual system level error + $errstr, // and any text that goes with the error $timeout // timeout for reading/writing data over the socket )) { // Windows still does not have support for this timeout function @@ -1334,7 +1342,7 @@ class CMailFile } else { - $this->error = utf8_check('Error '.$errno.' - '.$errstr)?'Error '.$errno.' - '.$errstr:utf8_encode('Error '.$errno.' - '.$errstr); + $this->error = utf8_check('Error '.$errno.' - '.$errstr) ? 'Error '.$errno.' - '.$errstr : utf8_encode('Error '.$errno.' - '.$errstr); } } return $_retVal; @@ -1352,21 +1360,21 @@ class CMailFile public function server_parse($socket, $response) { // phpcs:enable - $_retVal = true; // Indicates if Object was created or not + $_retVal = true; // Indicates if Object was created or not $server_response = ''; while (substr($server_response, 3, 1) != ' ') { - if (! ($server_response = fgets($socket, 256)) ) + if (!($server_response = fgets($socket, 256))) { - $this->error="Couldn't get mail server response codes"; + $this->error = "Couldn't get mail server response codes"; return false; } } - if( !( substr($server_response, 0, 3) == $response ) ) + if (!(substr($server_response, 0, 3) == $response)) { - $this->error="Ran into problems sending Mail.\r\nResponse: $server_response"; + $this->error = "Ran into problems sending Mail.\r\nResponse: $server_response"; $_retVal = false; } @@ -1385,11 +1393,11 @@ class CMailFile $extensions = array_keys($this->image_types); $matches = array(); - preg_match_all('/(?:"|\')([^"\']+\.('.implode('|', $extensions).'))(?:"|\')/Ui', $this->html, $matches); // If "xxx.ext" or 'xxx.ext' found + preg_match_all('/(?:"|\')([^"\']+\.('.implode('|', $extensions).'))(?:"|\')/Ui', $this->html, $matches); // If "xxx.ext" or 'xxx.ext' found - if (! empty($matches)) + if (!empty($matches)) { - $i=0; + $i = 0; foreach ($matches[1] as $full) { if (preg_match('/file=([A-Za-z0-9_\-\/]+[\.]?[A-Za-z0-9]+)?$/i', $full, $regs)) // If xxx is 'file=aaa' @@ -1410,12 +1418,12 @@ class CMailFile // Content type if (preg_match('/^.+\.(\w{3,4})$/', $img, $reg)) { - $ext=strtolower($reg[1]); + $ext = strtolower($reg[1]); $this->html_images[$i]["content_type"] = $this->image_types[$ext]; } // cid - $this->html_images[$i]["cid"] = dol_hash(uniqid(time()), 3); // Force md5 hash (does not contains special chars) + $this->html_images[$i]["cid"] = dol_hash(uniqid(time()), 3); // Force md5 hash (does not contains special chars) $this->html = preg_replace("/src=\"$src\"|src='$src'/i", "src=\"cid:".$this->html_images[$i]["cid"]."\"", $this->html); } $i++; @@ -1426,7 +1434,7 @@ class CMailFile { $inline = array(); - $i=0; + $i = 0; foreach ($this->html_images as $img) { @@ -1485,13 +1493,13 @@ class CMailFile { global $conf; - $ret=''; + $ret = ''; - $arrayaddress=explode(',', $address); + $arrayaddress = explode(',', $address); // Boucle sur chaque composant de l'adresse - $i=0; - foreach($arrayaddress as $val) + $i = 0; + foreach ($arrayaddress as $val) { if (preg_match('/^(.*)<(.*)>$/i', trim($val), $regs)) { @@ -1508,36 +1516,36 @@ class CMailFile { $i++; - $newemail=''; + $newemail = ''; if ($format == 5) { - $newemail = $name?$name:$email; + $newemail = $name ? $name : $email; $newemail = ''.$newemail.''; } if ($format == 4) { - $newemail = $name?$name:$email; + $newemail = $name ? $name : $email; } if ($format == 2) { - $newemail=$email; + $newemail = $email; } if ($format == 1 || $format == 3) { - $newemail='<'.$email.'>'; + $newemail = '<'.$email.'>'; } if ($format == 0 || $format == 3) { - if (! empty($conf->global->MAIN_MAIL_NO_FULL_EMAIL)) $newemail='<'.$email.'>'; - elseif (! $name) $newemail='<'.$email.'>'; - else $newemail=($format==3?'"':'').($encode?self::encodetorfc2822($name):$name).($format==3?'"':'').' <'.$email.'>'; + if (!empty($conf->global->MAIN_MAIL_NO_FULL_EMAIL)) $newemail = '<'.$email.'>'; + elseif (!$name) $newemail = '<'.$email.'>'; + else $newemail = ($format == 3 ? '"' : '').($encode ?self::encodetorfc2822($name) : $name).($format == 3 ? '"' : '').' <'.$email.'>'; } - $ret=($ret ? $ret.',' : '').$newemail; + $ret = ($ret ? $ret.',' : '').$newemail; // Stop if we have too much records if ($maxnumberofemail && $i >= $maxnumberofemail) { - if (count($arrayaddress) > $maxnumberofemail) $ret.='...'; + if (count($arrayaddress) > $maxnumberofemail) $ret .= '...'; break; } } @@ -1556,12 +1564,12 @@ class CMailFile { global $conf; - $ret=array(); + $ret = array(); - $arrayaddress=explode(',', $address); + $arrayaddress = explode(',', $address); // Boucle sur chaque composant de l'adresse - foreach($arrayaddress as $val) + foreach ($arrayaddress as $val) { if (preg_match('/^(.*)<(.*)>$/i', trim($val), $regs)) { @@ -1574,7 +1582,7 @@ class CMailFile $email = trim($val); } - $ret[$email]=empty($conf->global->MAIN_MAIL_NO_FULL_EMAIL)?$name:null; + $ret[$email] = empty($conf->global->MAIN_MAIL_NO_FULL_EMAIL) ? $name : null; } return $ret; diff --git a/htdocs/core/class/ccountry.class.php b/htdocs/core/class/ccountry.class.php index 0934d85b3e7..e117f99488a 100644 --- a/htdocs/core/class/ccountry.class.php +++ b/htdocs/core/class/ccountry.class.php @@ -40,15 +40,15 @@ class Ccountry // extends CommonObject /** * @var string Error code (or message) */ - public $error=''; + public $error = ''; /** * @var string[] Error codes (or messages) */ public $errors = array(); - public $element='ccountry'; //!< Id that identify managed objects - public $table_element='c_country'; //!< Name of table without prefix where object is stored + public $element = 'ccountry'; //!< Id that identify managed objects + public $table_element = 'c_country'; //!< Name of table without prefix where object is stored /** * @var int ID @@ -65,7 +65,7 @@ class Ccountry // extends CommonObject public $active; - public $fields=array( + public $fields = array( 'label' => array('type'=>'varchar(250)', 'label'=>'Label', 'enabled'=>1, 'visible'=>1, 'position'=>15, 'notnull'=>-1, 'showoncombobox'=>'1') ); @@ -91,43 +91,43 @@ class Ccountry // extends CommonObject public function create($user, $notrigger = 0) { global $conf, $langs; - $error=0; + $error = 0; // Clean parameters - if (isset($this->code)) $this->code=trim($this->code); - if (isset($this->code_iso)) $this->code_iso=trim($this->code_iso); - if (isset($this->label)) $this->label=trim($this->label); - if (isset($this->active)) $this->active=trim($this->active); + if (isset($this->code)) $this->code = trim($this->code); + if (isset($this->code_iso)) $this->code_iso = trim($this->code_iso); + if (isset($this->label)) $this->label = trim($this->label); + if (isset($this->active)) $this->active = trim($this->active); // Check parameters // Put here code to add control on parameters values // Insert request $sql = "INSERT INTO ".MAIN_DB_PREFIX."c_country("; - $sql.= "rowid,"; - $sql.= "code,"; - $sql.= "code_iso,"; - $sql.= "label,"; - $sql.= "active"; - $sql.= ") VALUES ("; - $sql.= " ".(! isset($this->rowid)?'NULL':"'".$this->db->escape($this->rowid)."'").","; - $sql.= " ".(! isset($this->code)?'NULL':"'".$this->db->escape($this->code)."'").","; - $sql.= " ".(! isset($this->code_iso)?'NULL':"'".$this->db->escape($this->code_iso)."'").","; - $sql.= " ".(! isset($this->label)?'NULL':"'".$this->db->escape($this->label)."'").","; - $sql.= " ".(! isset($this->active)?'NULL':"'".$this->db->escape($this->active)."'").""; - $sql.= ")"; + $sql .= "rowid,"; + $sql .= "code,"; + $sql .= "code_iso,"; + $sql .= "label,"; + $sql .= "active"; + $sql .= ") VALUES ("; + $sql .= " ".(!isset($this->rowid) ? 'NULL' : "'".$this->db->escape($this->rowid)."'").","; + $sql .= " ".(!isset($this->code) ? 'NULL' : "'".$this->db->escape($this->code)."'").","; + $sql .= " ".(!isset($this->code_iso) ? 'NULL' : "'".$this->db->escape($this->code_iso)."'").","; + $sql .= " ".(!isset($this->label) ? 'NULL' : "'".$this->db->escape($this->label)."'").","; + $sql .= " ".(!isset($this->active) ? 'NULL' : "'".$this->db->escape($this->active)."'").""; + $sql .= ")"; $this->db->begin(); dol_syslog(get_class($this)."::create", LOG_DEBUG); - $resql=$this->db->query($sql); - if (! $resql) { $error++; $this->errors[]="Error ".$this->db->lasterror(); } + $resql = $this->db->query($sql); + if (!$resql) { $error++; $this->errors[] = "Error ".$this->db->lasterror(); } - if (! $error) + if (!$error) { $this->id = $this->db->last_insert_id(MAIN_DB_PREFIX."c_country"); - if (! $notrigger) + if (!$notrigger) { // Uncomment this and change MYOBJECT to your own tag if you // want this action call a trigger. @@ -144,13 +144,13 @@ class Ccountry // extends CommonObject // Commit or rollback if ($error) { - foreach($this->errors as $errmsg) + foreach ($this->errors as $errmsg) { dol_syslog(get_class($this)."::create ".$errmsg, LOG_ERR); - $this->error.=($this->error?', '.$errmsg:$errmsg); + $this->error .= ($this->error ? ', '.$errmsg : $errmsg); } $this->db->rollback(); - return -1*$error; + return -1 * $error; } else { @@ -205,7 +205,7 @@ class Ccountry // extends CommonObject } else { - $this->error="Error ".$this->db->lasterror(); + $this->error = "Error ".$this->db->lasterror(); return -1; } } @@ -221,13 +221,13 @@ class Ccountry // extends CommonObject public function update($user = null, $notrigger = 0) { global $conf, $langs; - $error=0; + $error = 0; // Clean parameters - if (isset($this->code)) $this->code=trim($this->code); - if (isset($this->code_iso)) $this->code_iso=trim($this->code_iso); - if (isset($this->label)) $this->label=trim($this->label); - if (isset($this->active)) $this->active=trim($this->active); + if (isset($this->code)) $this->code = trim($this->code); + if (isset($this->code_iso)) $this->code_iso = trim($this->code_iso); + if (isset($this->label)) $this->label = trim($this->label); + if (isset($this->active)) $this->active = trim($this->active); // Check parameters @@ -235,21 +235,21 @@ class Ccountry // extends CommonObject // Update request $sql = "UPDATE ".MAIN_DB_PREFIX."c_country SET"; - $sql.= " code=".(isset($this->code)?"'".$this->db->escape($this->code)."'":"null").","; - $sql.= " code_iso=".(isset($this->code_iso)?"'".$this->db->escape($this->code_iso)."'":"null").","; - $sql.= " label=".(isset($this->label)?"'".$this->db->escape($this->label)."'":"null").","; - $sql.= " active=".(isset($this->active)?$this->active:"null").""; - $sql.= " WHERE rowid=".$this->id; + $sql .= " code=".(isset($this->code) ? "'".$this->db->escape($this->code)."'" : "null").","; + $sql .= " code_iso=".(isset($this->code_iso) ? "'".$this->db->escape($this->code_iso)."'" : "null").","; + $sql .= " label=".(isset($this->label) ? "'".$this->db->escape($this->label)."'" : "null").","; + $sql .= " active=".(isset($this->active) ? $this->active : "null").""; + $sql .= " WHERE rowid=".$this->id; $this->db->begin(); dol_syslog(get_class($this)."::update", LOG_DEBUG); $resql = $this->db->query($sql); - if (! $resql) { $error++; $this->errors[]="Error ".$this->db->lasterror(); } + if (!$resql) { $error++; $this->errors[] = "Error ".$this->db->lasterror(); } - if (! $error) + if (!$error) { - if (! $notrigger) + if (!$notrigger) { // Uncomment this and change MYOBJECT to your own tag if you // want this action call a trigger. @@ -266,13 +266,13 @@ class Ccountry // extends CommonObject // Commit or rollback if ($error) { - foreach($this->errors as $errmsg) + foreach ($this->errors as $errmsg) { dol_syslog(get_class($this)."::update ".$errmsg, LOG_ERR); - $this->error.=($this->error?', '.$errmsg:$errmsg); + $this->error .= ($this->error ? ', '.$errmsg : $errmsg); } $this->db->rollback(); - return -1*$error; + return -1 * $error; } else { @@ -292,20 +292,20 @@ class Ccountry // extends CommonObject public function delete($user, $notrigger = 0) { global $conf, $langs; - $error=0; + $error = 0; $sql = "DELETE FROM ".MAIN_DB_PREFIX."c_country"; - $sql.= " WHERE rowid=".$this->id; + $sql .= " WHERE rowid=".$this->id; $this->db->begin(); 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) { - if (! $notrigger) + if (!$notrigger) { // Uncomment this and change MYOBJECT to your own tag if you // want this action call a trigger. @@ -322,13 +322,13 @@ class Ccountry // extends CommonObject // Commit or rollback if ($error) { - 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); + $this->error .= ($this->error ? ', '.$errmsg : $errmsg); } $this->db->rollback(); - return -1*$error; + return -1 * $error; } else { diff --git a/htdocs/core/class/commondocgenerator.class.php b/htdocs/core/class/commondocgenerator.class.php index 6a9bc0c9f29..6012e33fb96 100644 --- a/htdocs/core/class/commondocgenerator.class.php +++ b/htdocs/core/class/commondocgenerator.class.php @@ -37,7 +37,7 @@ abstract class CommonDocGenerator /** * @var string Error code (or message) */ - public $error=''; + public $error = ''; /** * @var string[] Array of error strings @@ -74,7 +74,7 @@ abstract class CommonDocGenerator // phpcs:enable global $conf; - $logotouse=$conf->user->dir_output.'/'.get_exdir($user->id, 2, 0, 1, $user, 'user').'/'.$user->photo; + $logotouse = $conf->user->dir_output.'/'.get_exdir($user->id, 2, 0, 1, $user, 'user').'/'.$user->photo; return array( 'myuser_lastname'=>$user->lastname, @@ -112,20 +112,20 @@ abstract class CommonDocGenerator // phpcs:enable global $conf; - if (empty($mysoc->forme_juridique) && ! empty($mysoc->forme_juridique_code)) + if (empty($mysoc->forme_juridique) && !empty($mysoc->forme_juridique_code)) { - $mysoc->forme_juridique=getFormeJuridiqueLabel($mysoc->forme_juridique_code); + $mysoc->forme_juridique = getFormeJuridiqueLabel($mysoc->forme_juridique_code); } - if (empty($mysoc->country) && ! empty($mysoc->country_code)) + if (empty($mysoc->country) && !empty($mysoc->country_code)) { - $mysoc->country=$outputlangs->transnoentitiesnoconv("Country".$mysoc->country_code); + $mysoc->country = $outputlangs->transnoentitiesnoconv("Country".$mysoc->country_code); } - if (empty($mysoc->state) && ! empty($mysoc->state_code)) + if (empty($mysoc->state) && !empty($mysoc->state_code)) { - $mysoc->state=getState($mysoc->state_code, 0); + $mysoc->state = getState($mysoc->state_code, 0); } - $logotouse=$conf->mycompany->dir_output.'/logos/thumbs/'.$mysoc->logo_small; + $logotouse = $conf->mycompany->dir_output.'/logos/thumbs/'.$mysoc->logo_small; return array( 'mycompany_logo'=>$logotouse, @@ -172,13 +172,13 @@ abstract class CommonDocGenerator // phpcs:enable global $conf; - if (empty($object->country) && ! empty($object->country_code)) + if (empty($object->country) && !empty($object->country_code)) { - $object->country=$outputlangs->transnoentitiesnoconv("Country".$object->country_code); + $object->country = $outputlangs->transnoentitiesnoconv("Country".$object->country_code); } - if (empty($object->state) && ! empty($object->state_code)) + if (empty($object->state) && !empty($object->state_code)) { - $object->state=getState($object->state_code, 0); + $object->state = getState($object->state_code, 0); } $array_thirdparty = array( @@ -326,7 +326,7 @@ abstract class CommonDocGenerator // phpcs:enable global $conf; - $now=dol_now('gmt'); // gmt + $now = dol_now('gmt'); // gmt $array_other = array( // Date in default language 'current_date'=>dol_print_date($now, 'day', 'tzuser'), @@ -341,7 +341,7 @@ abstract class CommonDocGenerator ); - foreach($conf->global as $key => $val) + foreach ($conf->global as $key => $val) { if (preg_match('/(_pass|password|secret|_key|key$)/i', $key)) $newval = '*****forbidden*****'; else $newval = $val; @@ -366,12 +366,12 @@ abstract class CommonDocGenerator // phpcs:enable global $conf; - $sumpayed=$sumdeposit=$sumcreditnote=''; - $already_payed_all=0; - $remain_to_pay=0; + $sumpayed = $sumdeposit = $sumcreditnote = ''; + $already_payed_all = 0; + $remain_to_pay = 0; if ($object->element == 'facture') { - $invoice_source=new Facture($this->db); + $invoice_source = new Facture($this->db); if ($object->fk_facture_source > 0) { $invoice_source->fetch($object->fk_facture_source); @@ -379,44 +379,44 @@ abstract class CommonDocGenerator $sumpayed = $object->getSommePaiement(); $sumdeposit = $object->getSumDepositsUsed(); $sumcreditnote = $object->getSumCreditNotesUsed(); - $already_payed_all=$sumpayed + $sumdeposit + $sumcreditnote; - $remain_to_pay=$sumpayed - $sumdeposit - $sumcreditnote; + $already_payed_all = $sumpayed + $sumdeposit + $sumcreditnote; + $remain_to_pay = $sumpayed - $sumdeposit - $sumcreditnote; } $date = ($object->element == 'contrat' ? $object->date_contrat : $object->date); - $resarray=array( + $resarray = array( $array_key.'_id'=>$object->id, $array_key.'_ref'=>$object->ref, $array_key.'_ref_ext'=>$object->ref_ext, - $array_key.'_ref_customer'=>(! empty($object->ref_client) ? $object->ref_client : (empty($object->ref_customer) ? '' : $object->ref_customer)), - $array_key.'_ref_supplier'=>(! empty($object->ref_fournisseur) ? $object->ref_fournisseur : (empty($object->ref_supplier) ? '' : $object->ref_supplier)), + $array_key.'_ref_customer'=>(!empty($object->ref_client) ? $object->ref_client : (empty($object->ref_customer) ? '' : $object->ref_customer)), + $array_key.'_ref_supplier'=>(!empty($object->ref_fournisseur) ? $object->ref_fournisseur : (empty($object->ref_supplier) ? '' : $object->ref_supplier)), $array_key.'_source_invoice_ref'=>$invoice_source->ref, // Dates $array_key.'_hour'=>dol_print_date($date, 'hour'), $array_key.'_date'=>dol_print_date($date, 'day'), $array_key.'_date_rfc'=>dol_print_date($date, 'dayrfc'), - $array_key.'_date_limit'=>(! empty($object->date_lim_reglement)?dol_print_date($object->date_lim_reglement, 'day'):''), - $array_key.'_date_end'=>(! empty($object->fin_validite)?dol_print_date($object->fin_validite, 'day'):''), + $array_key.'_date_limit'=>(!empty($object->date_lim_reglement) ?dol_print_date($object->date_lim_reglement, 'day') : ''), + $array_key.'_date_end'=>(!empty($object->fin_validite) ?dol_print_date($object->fin_validite, 'day') : ''), $array_key.'_date_creation'=>dol_print_date($object->date_creation, 'day'), - $array_key.'_date_modification'=>(! empty($object->date_modification)?dol_print_date($object->date_modification, 'day'):''), - $array_key.'_date_validation'=>(! empty($object->date_validation)?dol_print_date($object->date_validation, 'dayhour'):''), - $array_key.'_date_delivery_planed'=>(! empty($object->date_livraison)?dol_print_date($object->date_livraison, 'day'):''), - $array_key.'_date_close'=>(! empty($object->date_cloture)?dol_print_date($object->date_cloture, 'dayhour'):''), + $array_key.'_date_modification'=>(!empty($object->date_modification) ?dol_print_date($object->date_modification, 'day') : ''), + $array_key.'_date_validation'=>(!empty($object->date_validation) ?dol_print_date($object->date_validation, 'dayhour') : ''), + $array_key.'_date_delivery_planed'=>(!empty($object->date_livraison) ?dol_print_date($object->date_livraison, 'day') : ''), + $array_key.'_date_close'=>(!empty($object->date_cloture) ?dol_print_date($object->date_cloture, 'dayhour') : ''), $array_key.'_payment_mode_code'=>$object->mode_reglement_code, - $array_key.'_payment_mode'=>($outputlangs->transnoentitiesnoconv('PaymentType'.$object->mode_reglement_code)!='PaymentType'.$object->mode_reglement_code?$outputlangs->transnoentitiesnoconv('PaymentType'.$object->mode_reglement_code):$object->mode_reglement), + $array_key.'_payment_mode'=>($outputlangs->transnoentitiesnoconv('PaymentType'.$object->mode_reglement_code) != 'PaymentType'.$object->mode_reglement_code ? $outputlangs->transnoentitiesnoconv('PaymentType'.$object->mode_reglement_code) : $object->mode_reglement), $array_key.'_payment_term_code'=>$object->cond_reglement_code, - $array_key.'_payment_term'=>($outputlangs->transnoentitiesnoconv('PaymentCondition'.$object->cond_reglement_code)!='PaymentCondition'.$object->cond_reglement_code?$outputlangs->transnoentitiesnoconv('PaymentCondition'.$object->cond_reglement_code):($object->cond_reglement_doc?$object->cond_reglement_doc:$object->cond_reglement)), + $array_key.'_payment_term'=>($outputlangs->transnoentitiesnoconv('PaymentCondition'.$object->cond_reglement_code) != 'PaymentCondition'.$object->cond_reglement_code ? $outputlangs->transnoentitiesnoconv('PaymentCondition'.$object->cond_reglement_code) : ($object->cond_reglement_doc ? $object->cond_reglement_doc : $object->cond_reglement)), $array_key.'_total_ht_locale'=>price($object->total_ht, 0, $outputlangs), - $array_key.'_total_vat_locale'=>(! empty($object->total_vat)?price($object->total_vat, 0, $outputlangs):price($object->total_tva, 0, $outputlangs)), + $array_key.'_total_vat_locale'=>(!empty($object->total_vat) ?price($object->total_vat, 0, $outputlangs) : price($object->total_tva, 0, $outputlangs)), $array_key.'_total_localtax1_locale'=>price($object->total_localtax1, 0, $outputlangs), $array_key.'_total_localtax2_locale'=>price($object->total_localtax2, 0, $outputlangs), $array_key.'_total_ttc_locale'=>price($object->total_ttc, 0, $outputlangs), $array_key.'_total_ht'=>price2num($object->total_ht), - $array_key.'_total_vat'=>(! empty($object->total_vat)?price2num($object->total_vat):price2num($object->total_tva)), + $array_key.'_total_vat'=>(!empty($object->total_vat) ?price2num($object->total_vat) : price2num($object->total_tva)), $array_key.'_total_localtax1'=>price2num($object->total_localtax1), $array_key.'_total_localtax2'=>price2num($object->total_localtax2), $array_key.'_total_ttc'=>price2num($object->total_ttc), @@ -432,7 +432,7 @@ abstract class CommonDocGenerator $array_key.'_note_private'=>$object->note, $array_key.'_note_public'=>$object->note_public, - $array_key.'_note'=>$object->note_public, // For backward compatibility + $array_key.'_note'=>$object->note_public, // For backward compatibility // Payments $array_key.'_already_payed_locale'=>price($sumpayed, 0, $outputlangs), @@ -459,9 +459,9 @@ abstract class CommonDocGenerator } // Fetch project information if there is a project assigned to this object - if ($object->element != "project" && ! empty($object->fk_project) && $object->fk_project > 0) + if ($object->element != "project" && !empty($object->fk_project) && $object->fk_project > 0) { - if (! is_object($object->project)) + if (!is_object($object->project)) { $object->fetch_projet(); } @@ -497,23 +497,23 @@ abstract class CommonDocGenerator $resarray['object_total_up'] = $totalUp; $resarray['object_total_up_locale'] = price($resarray['object_total_up'], 0, $outputlangs); if (method_exists($object, 'getTotalDiscount')) { - $totalDiscount=$object->getTotalDiscount(); + $totalDiscount = $object->getTotalDiscount(); } else { - $totalDiscount=0; + $totalDiscount = 0; } if (!empty($totalUp) && !empty($totalDiscount)) { $resarray['object_total_discount'] = round(100 / $totalUp * $totalDiscount, 2); $resarray['object_total_discount_locale'] = price($resarray['object_total_discount'], 0, $outputlangs); } else { - $resarray['object_total_discount']=''; - $resarray['object_total_discount_locale']=''; + $resarray['object_total_discount'] = ''; + $resarray['object_total_discount_locale'] = ''; } } // Retrieve extrafields if (is_array($object->array_options) && count($object->array_options)) { - $extrafieldkey=$object->element; + $extrafieldkey = $object->element; require_once DOL_DOCUMENT_ROOT.'/core/class/extrafields.class.php'; $extrafields = new ExtraFields($this->db); @@ -539,7 +539,7 @@ abstract class CommonDocGenerator // phpcs:enable global $conf; - $resarray= array( + $resarray = array( 'line_fulldesc'=>doc_getlinedesc($line, $outputlangs), 'line_product_ref'=>$line->product_ref, 'line_product_ref_fourn'=>$line->ref_fourn, // for supplier doc lines @@ -554,7 +554,7 @@ abstract class CommonDocGenerator 'line_total_up'=>price2num($line->subprice * $line->qty), 'line_total_up_locale'=>price($line->subprice * $line->qty, 0, $outputlangs), 'line_qty'=>$line->qty, - 'line_discount_percent'=>($line->remise_percent?$line->remise_percent.'%':''), + 'line_discount_percent'=>($line->remise_percent ? $line->remise_percent.'%' : ''), 'line_price_ht'=>price2num($line->total_ht), 'line_price_ttc'=>price2num($line->total_ttc), 'line_price_vat'=>price2num($line->total_tva), @@ -625,7 +625,7 @@ abstract class CommonDocGenerator { $tmpproduct = new Product($this->db); $result = $tmpproduct->fetch($line->fk_product); - foreach($tmpproduct->array_options as $key=>$label) + foreach ($tmpproduct->array_options as $key=>$label) $resarray["line_product_".$key] = $label; } @@ -647,9 +647,9 @@ abstract class CommonDocGenerator global $conf; dol_include_once('/core/lib/product.lib.php'); $object->list_delivery_methods($object->shipping_method_id); - $calculatedVolume=($object->trueWidth * $object->trueHeight * $object->trueDepth); + $calculatedVolume = ($object->trueWidth * $object->trueHeight * $object->trueDepth); - $array_shipment=array( + $array_shipment = array( $array_key.'_id'=>$object->id, $array_key.'_ref'=>$object->ref, $array_key.'_ref_ext'=>$object->ref_ext, @@ -676,8 +676,8 @@ abstract class CommonDocGenerator // Add vat by rates foreach ($object->lines as $line) { - if (empty($array_shipment[$array_key.'_total_vat_'.$line->tva_tx])) $array_shipment[$array_key.'_total_vat_'.$line->tva_tx]=0; - $array_shipment[$array_key.'_total_vat_'.$line->tva_tx]+=$line->total_tva; + if (empty($array_shipment[$array_key.'_total_vat_'.$line->tva_tx])) $array_shipment[$array_key.'_total_vat_'.$line->tva_tx] = 0; + $array_shipment[$array_key.'_total_vat_'.$line->tva_tx] += $line->total_tva; } // Retrieve extrafields @@ -758,7 +758,7 @@ abstract class CommonDocGenerator // phpcs:enable $array_other = array(); if (!empty($object)) { - foreach($object as $key => $value) { + foreach ($object as $key => $value) { if (!empty($value)) { if (!is_array($value) && !is_object($value)) { $array_other['object_'.$key] = $value; @@ -862,7 +862,7 @@ abstract class CommonDocGenerator } } - $array_to_fill=array_merge($array_to_fill, array($array_key.'_options_'.$key => $object->array_options['options_'.$key])); + $array_to_fill = array_merge($array_to_fill, array($array_key.'_options_'.$key => $object->array_options['options_'.$key])); } return $array_to_fill; @@ -883,10 +883,10 @@ abstract class CommonDocGenerator */ public function printRect($pdf, $x, $y, $l, $h, $hidetop = 0, $hidebottom = 0) { - if (empty($hidetop) || $hidetop==-1) $pdf->line($x, $y, $x+$l, $y); - $pdf->line($x+$l, $y, $x+$l, $y+$h); - if (empty($hidebottom)) $pdf->line($x+$l, $y+$h, $x, $y+$h); - $pdf->line($x, $y+$h, $x, $y); + if (empty($hidetop) || $hidetop == -1) $pdf->line($x, $y, $x + $l, $y); + $pdf->line($x + $l, $y, $x + $l, $y + $h); + if (empty($hidebottom)) $pdf->line($x + $l, $y + $h, $x, $y + $h); + $pdf->line($x, $y + $h, $x, $y); } @@ -899,8 +899,8 @@ abstract class CommonDocGenerator */ public function columnSort($a, $b) { - if(empty($a['rank'])){ $a['rank'] = 0; } - if(empty($b['rank'])){ $b['rank'] = 0; } + if (empty($a['rank'])) { $a['rank'] = 0; } + if (empty($b['rank'])) { $b['rank'] = 0; } if ($a['rank'] == $b['rank']) { return 0; } @@ -956,25 +956,25 @@ abstract class CommonDocGenerator foreach ($this->cols as $colKey =>& $colDef) { // setting empty conf with default - if(!empty($colDef['title'])){ + if (!empty($colDef['title'])) { $colDef['title'] = array_replace($this->defaultTitlesFieldsStyle, $colDef['title']); } - else{ + else { $colDef['title'] = $this->defaultTitlesFieldsStyle; } // setting empty conf with default - if(!empty($colDef['content'])){ + if (!empty($colDef['content'])) { $colDef['content'] = array_replace($this->defaultContentsFieldsStyle, $colDef['content']); } - else{ + else { $colDef['content'] = $this->defaultContentsFieldsStyle; } - if($this->getColumnStatus($colKey)) + if ($this->getColumnStatus($colKey)) { // In case of flexible column - if(empty($colDef['width'])){ + if (empty($colDef['width'])) { $colDef['width'] = abs(($arrayWidth - $totalDefinedColWidth)) / $countFlexCol; } @@ -1020,7 +1020,7 @@ abstract class CommonDocGenerator */ public function getColumnRank($colKey) { - if(!isset($this->cols[$colKey]['rank'])) return -1; + if (!isset($this->cols[$colKey]['rank'])) return -1; return $this->cols[$colKey]['rank']; } @@ -1039,22 +1039,22 @@ abstract class CommonDocGenerator $rank = -1; // try to get rank from target column - if(!empty($targetCol)){ + if (!empty($targetCol)) { $rank = $this->getColumnRank($targetCol); - if($rank>=0 && $insertAfterTarget){ $rank++; } + if ($rank >= 0 && $insertAfterTarget) { $rank++; } } // get rank from new column definition - if($rank<0 && !empty($defArray['rank'])){ + if ($rank < 0 && !empty($defArray['rank'])) { $rank = $defArray['rank']; } // error: no rank - if($rank<0){ return -1; } + if ($rank < 0) { return -1; } foreach ($this->cols as $colKey =>& $colDef) { - if( $rank <= $colDef['rank']) + if ($rank <= $colDef['rank']) { $colDef['rank'] = $colDef['rank'] + 1; } @@ -1080,16 +1080,16 @@ abstract class CommonDocGenerator { global $hookmanager; - $parameters=array( + $parameters = array( 'curY' => &$curY, 'columnText' => $columnText, 'colKey' => $colKey ); - $reshook=$hookmanager->executeHooks('printStdColumnContent', $parameters, $this); // Note that $action and $object may have been modified by hook + $reshook = $hookmanager->executeHooks('printStdColumnContent', $parameters, $this); // Note that $action and $object may have been modified by hook if ($reshook < 0) setEventMessages($hookmanager->error, $hookmanager->errors, 'errors'); if (!$reshook) { - if(empty($columnText)) return; + if (empty($columnText)) return; $pdf->SetXY($this->getColumnContentXStart($colKey), $curY); // Set curent position $colDef = $this->cols[$colKey]; $pdf->writeHTMLCell($this->getColumnContentWidth($colKey), 2, $this->getColumnContentXStart($colKey), $curY, $columnText, 0, 0, 0, true, $colDef['content']['align']); @@ -1105,7 +1105,7 @@ abstract class CommonDocGenerator */ public function getColumnStatus($colKey) { - if( !empty($this->cols[$colKey]['status'])){ + if (!empty($this->cols[$colKey]['status'])) { return true; } else return false; @@ -1135,7 +1135,7 @@ abstract class CommonDocGenerator 'hidetop' => $hidetop ); - $reshook = $hookmanager->executeHooks('pdfTabTitles', $parameters, $this); // Note that $object may have been modified by hook + $reshook = $hookmanager->executeHooks('pdfTabTitles', $parameters, $this); // Note that $object may have been modified by hook if ($reshook < 0) { setEventMessages($hookmanager->error, $hookmanager->errors, 'errors'); } elseif (empty($reshook)) { diff --git a/htdocs/core/class/commonobject.class.php b/htdocs/core/class/commonobject.class.php index 913a87dd7f9..1ce1eca120f 100644 --- a/htdocs/core/class/commonobject.class.php +++ b/htdocs/core/class/commonobject.class.php @@ -60,7 +60,7 @@ abstract class CommonObject /** * @var string[] Array of error strings */ - public $errors=array(); + public $errors = array(); /** * @var string ID to identify managed object @@ -75,7 +75,7 @@ abstract class CommonObject /** * @var int Name of subtable line */ - public $table_element_line=''; + public $table_element_line = ''; /** * @var string Key value used to track if data is coming from import wizard @@ -85,7 +85,7 @@ abstract class CommonObject /** * @var mixed Contains data to manage extrafields */ - public $array_options=array(); + public $array_options = array(); /** * @var int[][] Array of linked objects ids. Loaded by ->fetchObjectLinked @@ -114,7 +114,7 @@ abstract class CommonObject /** * @var array Can be used to pass information when only object is provided to method */ - public $context=array(); + public $context = array(); /** * @var string Contains canvas name if record is an alternative canvas record @@ -380,7 +380,7 @@ abstract class CommonObject * @var mixed Contains comments * @see fetchComments() */ - public $comments=array(); + public $comments = array(); /** * @var int @@ -426,9 +426,15 @@ abstract class CommonObject */ public $date_creation; + /** + * @var integer|string $date_validation; + */ + public $date_validation; // Date validation - public $date_validation; // Date validation - public $date_modification; // Date last change (tms field) + /** + * @var integer|string $date_modification; + */ + public $date_modification; // Date last change (tms field) public $next_prev_filter; @@ -448,27 +454,27 @@ abstract class CommonObject */ public static function isExistingObject($element, $id, $ref = '', $ref_ext = '') { - global $db,$conf; + global $db, $conf; $sql = "SELECT rowid, ref, ref_ext"; - $sql.= " FROM ".MAIN_DB_PREFIX.$element; - $sql.= " WHERE entity IN (".getEntity($element).")" ; + $sql .= " FROM ".MAIN_DB_PREFIX.$element; + $sql .= " WHERE entity IN (".getEntity($element).")"; - if ($id > 0) $sql.= " AND rowid = ".$db->escape($id); - elseif ($ref) $sql.= " AND ref = '".$db->escape($ref)."'"; - elseif ($ref_ext) $sql.= " AND ref_ext = '".$db->escape($ref_ext)."'"; + if ($id > 0) $sql .= " AND rowid = ".$db->escape($id); + elseif ($ref) $sql .= " AND ref = '".$db->escape($ref)."'"; + elseif ($ref_ext) $sql .= " AND ref_ext = '".$db->escape($ref_ext)."'"; else { - $error='ErrorWrongParameters'; + $error = 'ErrorWrongParameters'; dol_print_error(get_class()."::isExistingObject ".$error, LOG_ERR); return -1; } - if ($ref || $ref_ext) $sql.= " AND entity = ".$conf->entity; + if ($ref || $ref_ext) $sql .= " AND entity = ".$conf->entity; dol_syslog(get_class()."::isExistingObject", LOG_DEBUG); $resql = $db->query($sql); if ($resql) { - $num=$db->num_rows($resql); + $num = $db->num_rows($resql); if ($num > 0) return 1; else return 0; } @@ -482,7 +488,7 @@ abstract class CommonObject */ public function errorsToString() { - return $this->error.(is_array($this->errors)?(($this->error!=''?', ':'').join(', ', $this->errors)):''); + return $this->error.(is_array($this->errors) ? (($this->error != '' ? ', ' : '').join(', ', $this->errors)) : ''); } /** @@ -495,14 +501,14 @@ abstract class CommonObject { global $hookmanager; - $parameters=array('objref'=>$objref); - $action=''; + $parameters = array('objref'=>$objref); + $action = ''; $reshook = $hookmanager->executeHooks('getFormatedCustomerRef', $parameters, $this, $action); // Note that $action and $object may have been modified by some hooks if ($reshook > 0) { return $hookmanager->resArray['objref']; } - return $objref.(isset($hookmanager->resArray['objref'])?$hookmanager->resArray['objref']:''); + return $objref.(isset($hookmanager->resArray['objref']) ? $hookmanager->resArray['objref'] : ''); } /** @@ -515,14 +521,14 @@ abstract class CommonObject { global $hookmanager; - $parameters=array('objref'=>$objref); - $action=''; + $parameters = array('objref'=>$objref); + $action = ''; $reshook = $hookmanager->executeHooks('getFormatedSupplierRef', $parameters, $this, $action); // Note that $action and $object may have been modified by some hooks if ($reshook > 0) { return $hookmanager->resArray['objref']; } - return $objref.(isset($hookmanager->resArray['objref'])?$hookmanager->resArray['objref']:''); + return $objref.(isset($hookmanager->resArray['objref']) ? $hookmanager->resArray['objref'] : ''); } /** @@ -537,18 +543,18 @@ abstract class CommonObject public function getFullName($langs, $option = 0, $nameorder = -1, $maxlen = 0) { //print "lastname=".$this->lastname." name=".$this->name." nom=".$this->nom."
    \n"; - $lastname=$this->lastname; - $firstname=$this->firstname; - if (empty($lastname)) $lastname=(isset($this->lastname)?$this->lastname:(isset($this->name)?$this->name:(isset($this->nom)?$this->nom:(isset($this->societe)?$this->societe:(isset($this->company)?$this->company:''))))); + $lastname = $this->lastname; + $firstname = $this->firstname; + if (empty($lastname)) $lastname = (isset($this->lastname) ? $this->lastname : (isset($this->name) ? $this->name : (isset($this->nom) ? $this->nom : (isset($this->societe) ? $this->societe : (isset($this->company) ? $this->company : ''))))); - $ret=''; + $ret = ''; if ($option && $this->civility_id) { - if ($langs->transnoentitiesnoconv("Civility".$this->civility_id)!="Civility".$this->civility_id) $ret.=$langs->transnoentitiesnoconv("Civility".$this->civility_id).' '; - else $ret.=$this->civility_id.' '; + if ($langs->transnoentitiesnoconv("Civility".$this->civility_id) != "Civility".$this->civility_id) $ret .= $langs->transnoentitiesnoconv("Civility".$this->civility_id).' '; + else $ret .= $this->civility_id.' '; } - $ret.=dolGetFirstLastname($firstname, $lastname, $nameorder); + $ret .= dolGetFirstLastname($firstname, $lastname, $nameorder); return dol_trunc($ret, $maxlen); } @@ -565,20 +571,20 @@ abstract class CommonObject { if ($withcountry && $this->country_id && (empty($this->country_code) || empty($this->country))) { - require_once DOL_DOCUMENT_ROOT .'/core/lib/company.lib.php'; - $tmparray=getCountry($this->country_id, 'all'); - $this->country_code=$tmparray['code']; - $this->country =$tmparray['label']; + require_once DOL_DOCUMENT_ROOT.'/core/lib/company.lib.php'; + $tmparray = getCountry($this->country_id, 'all'); + $this->country_code = $tmparray['code']; + $this->country = $tmparray['label']; } if ($withregion && $this->state_id && (empty($this->state_code) || empty($this->state) || empty($this->region) || empty($this->region_cpde))) { - require_once DOL_DOCUMENT_ROOT .'/core/lib/company.lib.php'; - $tmparray=getState($this->state_id, 'all', 0, 1); - $this->state_code =$tmparray['code']; - $this->state =$tmparray['label']; - $this->region_code =$tmparray['region_code']; - $this->region =$tmparray['region']; + require_once DOL_DOCUMENT_ROOT.'/core/lib/company.lib.php'; + $tmparray = getState($this->state_id, 'all', 0, 1); + $this->state_code = $tmparray['code']; + $this->state = $tmparray['label']; + $this->region_code = $tmparray['region_code']; + $this->region = $tmparray['region']; } return dol_format_address($this, $withcountry, $sep); @@ -596,123 +602,123 @@ abstract class CommonObject { global $conf, $langs; - $countriesusingstate=array('AU','US','IN','GB','ES','UK','TR'); // See also option MAIN_FORCE_STATE_INTO_ADDRESS + $countriesusingstate = array('AU', 'US', 'IN', 'GB', 'ES', 'UK', 'TR'); // See also option MAIN_FORCE_STATE_INTO_ADDRESS - $contactid=0; - $thirdpartyid=0; + $contactid = 0; + $thirdpartyid = 0; if ($this->element == 'societe') { - $thirdpartyid=$this->id; + $thirdpartyid = $this->id; } if ($this->element == 'contact') { - $contactid=$this->id; - $thirdpartyid=$object->fk_soc; + $contactid = $this->id; + $thirdpartyid = $object->fk_soc; } if ($this->element == 'user') { - $contactid=$this->contact_id; - $thirdpartyid=$object->fk_soc; + $contactid = $this->contact_id; + $thirdpartyid = $object->fk_soc; } - $out=''; + $out = ''; - $outdone=0; + $outdone = 0; $coords = $this->getFullAddress(1, ', ', $conf->global->MAIN_SHOW_REGION_IN_STATE_SELECT); if ($coords) { - if (! empty($conf->use_javascript_ajax)) + if (!empty($conf->use_javascript_ajax)) { $namecoords = ''; - if ( $this->element == 'contact' && ! empty($conf->global->MAIN_SHOW_COMPANY_NAME_IN_BANNER_ADDRESS)) + if ($this->element == 'contact' && !empty($conf->global->MAIN_SHOW_COMPANY_NAME_IN_BANNER_ADDRESS)) { - $namecoords.= $object->name.'
    '; + $namecoords .= $object->name.'
    '; } - $namecoords.= $this->getFullName($langs, 1).'
    '.$coords; + $namecoords .= $this->getFullName($langs, 1).'
    '.$coords; // hideonsmatphone because copyToClipboard call jquery dialog that does not work with jmobile - $out.=''; - $out.=img_picto($langs->trans("Address"), 'object_address.png'); - $out.=' '; + $out .= ''; + $out .= img_picto($langs->trans("Address"), 'object_address.png'); + $out .= ' '; } - $out.=dol_print_address($coords, 'address_'.$htmlkey.'_'.$this->id, $this->element, $this->id, 1, ', '); $outdone++; + $out .= dol_print_address($coords, 'address_'.$htmlkey.'_'.$this->id, $this->element, $this->id, 1, ', '); $outdone++; $outdone++; } - if (! in_array($this->country_code, $countriesusingstate) && empty($conf->global->MAIN_FORCE_STATE_INTO_ADDRESS) // If MAIN_FORCE_STATE_INTO_ADDRESS is on, state is already returned previously with getFullAddress + if (!in_array($this->country_code, $countriesusingstate) && empty($conf->global->MAIN_FORCE_STATE_INTO_ADDRESS) // If MAIN_FORCE_STATE_INTO_ADDRESS is on, state is already returned previously with getFullAddress && empty($conf->global->SOCIETE_DISABLE_STATE) && $this->state) { if (!empty($conf->global->MAIN_SHOW_REGION_IN_STATE_SELECT) && $conf->global->MAIN_SHOW_REGION_IN_STATE_SELECT == 1 && $this->region) { - $out.=($outdone?' - ':'').$this->region.' - '.$this->state; + $out .= ($outdone ? ' - ' : '').$this->region.' - '.$this->state; } else { - $out.=($outdone?' - ':'').$this->state; + $out .= ($outdone ? ' - ' : '').$this->state; } $outdone++; } - if (! empty($this->phone) || ! empty($this->phone_pro) || ! empty($this->phone_mobile) || ! empty($this->phone_perso) || ! empty($this->fax) || ! empty($this->office_phone) || ! empty($this->user_mobile) || ! empty($this->office_fax)) $out.=($outdone?'
    ':''); - if (! empty($this->phone) && empty($this->phone_pro)) { // For objects that store pro phone into ->phone - $out.=dol_print_phone($this->phone, $this->country_code, $contactid, $thirdpartyid, 'AC_TEL', ' ', 'phone', $langs->trans("PhonePro")); $outdone++; + if (!empty($this->phone) || !empty($this->phone_pro) || !empty($this->phone_mobile) || !empty($this->phone_perso) || !empty($this->fax) || !empty($this->office_phone) || !empty($this->user_mobile) || !empty($this->office_fax)) $out .= ($outdone ? '
    ' : ''); + if (!empty($this->phone) && empty($this->phone_pro)) { // For objects that store pro phone into ->phone + $out .= dol_print_phone($this->phone, $this->country_code, $contactid, $thirdpartyid, 'AC_TEL', ' ', 'phone', $langs->trans("PhonePro")); $outdone++; } - if (! empty($this->phone_pro)) { - $out.=dol_print_phone($this->phone_pro, $this->country_code, $contactid, $thirdpartyid, 'AC_TEL', ' ', 'phone', $langs->trans("PhonePro")); $outdone++; + if (!empty($this->phone_pro)) { + $out .= dol_print_phone($this->phone_pro, $this->country_code, $contactid, $thirdpartyid, 'AC_TEL', ' ', 'phone', $langs->trans("PhonePro")); $outdone++; } - if (! empty($this->phone_mobile)) { - $out.=dol_print_phone($this->phone_mobile, $this->country_code, $contactid, $thirdpartyid, 'AC_TEL', ' ', 'mobile', $langs->trans("PhoneMobile")); $outdone++; + if (!empty($this->phone_mobile)) { + $out .= dol_print_phone($this->phone_mobile, $this->country_code, $contactid, $thirdpartyid, 'AC_TEL', ' ', 'mobile', $langs->trans("PhoneMobile")); $outdone++; } - if (! empty($this->phone_perso)) { - $out.=dol_print_phone($this->phone_perso, $this->country_code, $contactid, $thirdpartyid, 'AC_TEL', ' ', 'phone', $langs->trans("PhonePerso")); $outdone++; + if (!empty($this->phone_perso)) { + $out .= dol_print_phone($this->phone_perso, $this->country_code, $contactid, $thirdpartyid, 'AC_TEL', ' ', 'phone', $langs->trans("PhonePerso")); $outdone++; } - if (! empty($this->office_phone)) { - $out.=dol_print_phone($this->office_phone, $this->country_code, $contactid, $thirdpartyid, 'AC_TEL', ' ', 'phone', $langs->trans("PhonePro")); $outdone++; + if (!empty($this->office_phone)) { + $out .= dol_print_phone($this->office_phone, $this->country_code, $contactid, $thirdpartyid, 'AC_TEL', ' ', 'phone', $langs->trans("PhonePro")); $outdone++; } - if (! empty($this->user_mobile)) { - $out.=dol_print_phone($this->user_mobile, $this->country_code, $contactid, $thirdpartyid, 'AC_TEL', ' ', 'mobile', $langs->trans("PhoneMobile")); $outdone++; + if (!empty($this->user_mobile)) { + $out .= dol_print_phone($this->user_mobile, $this->country_code, $contactid, $thirdpartyid, 'AC_TEL', ' ', 'mobile', $langs->trans("PhoneMobile")); $outdone++; } - if (! empty($this->fax)) { - $out.=dol_print_phone($this->fax, $this->country_code, $contactid, $thirdpartyid, 'AC_FAX', ' ', 'fax', $langs->trans("Fax")); $outdone++; + if (!empty($this->fax)) { + $out .= dol_print_phone($this->fax, $this->country_code, $contactid, $thirdpartyid, 'AC_FAX', ' ', 'fax', $langs->trans("Fax")); $outdone++; } - if (! empty($this->office_fax)) { - $out.=dol_print_phone($this->office_fax, $this->country_code, $contactid, $thirdpartyid, 'AC_FAX', ' ', 'fax', $langs->trans("Fax")); $outdone++; + if (!empty($this->office_fax)) { + $out .= dol_print_phone($this->office_fax, $this->country_code, $contactid, $thirdpartyid, 'AC_FAX', ' ', 'fax', $langs->trans("Fax")); $outdone++; } - $out.='
    '; - $outdone=0; - if (! empty($this->email)) + $out .= '
    '; + $outdone = 0; + if (!empty($this->email)) { - $out.=dol_print_email($this->email, $this->id, $object->id, 'AC_EMAIL', 0, 0, 1); + $out .= dol_print_email($this->email, $this->id, $object->id, 'AC_EMAIL', 0, 0, 1); $outdone++; } - if (! empty($this->url)) + if (!empty($this->url)) { //$out.=dol_print_url($this->url,'_goout',0,1);//steve changed to blank - $out.=dol_print_url($this->url, '_blank', 0, 1); + $out .= dol_print_url($this->url, '_blank', 0, 1); $outdone++; } - $out.='
    '; - if (! empty($conf->socialnetworks->enabled)) + $out .= '
    '; + if (!empty($conf->socialnetworks->enabled)) { - if (is_array($this->socialnetworks) && count($this->socialnetworks)>0) { + if (is_array($this->socialnetworks) && count($this->socialnetworks) > 0) { foreach ($this->socialnetworks as $key => $value) { - $out.=dol_print_socialnetworks($value, $this->id, $object->id, $key); + $out .= dol_print_socialnetworks($value, $this->id, $object->id, $key); $outdone++; } } else { - if ($this->skype) $out.=dol_print_socialnetworks($this->skype, $this->id, $object->id, 'skype'); + if ($this->skype) $out .= dol_print_socialnetworks($this->skype, $this->id, $object->id, 'skype'); $outdone++; - if ($this->jabberid) $out.=dol_print_socialnetworks($this->jabberid, $this->id, $object->id, 'jabber'); + if ($this->jabberid) $out .= dol_print_socialnetworks($this->jabberid, $this->id, $object->id, 'jabber'); $outdone++; - if ($this->twitter) $out.=dol_print_socialnetworks($this->twitter, $this->id, $object->id, 'twitter'); + if ($this->twitter) $out .= dol_print_socialnetworks($this->twitter, $this->id, $object->id, 'twitter'); $outdone++; - if ($this->facebook) $out.=dol_print_socialnetworks($this->facebook, $this->id, $object->id, 'facebook'); + if ($this->facebook) $out .= dol_print_socialnetworks($this->facebook, $this->id, $object->id, 'facebook'); $outdone++; - if ($this->linkedin) $out.=dol_print_socialnetworks($this->linkedin, $this->id, $object->id, 'linkedin'); + if ($this->linkedin) $out .= dol_print_socialnetworks($this->linkedin, $this->id, $object->id, 'linkedin'); $outdone++; } } - $out.='
    '; + $out .= '
    '; - $out.=''; + $out .= ''; return $out; } @@ -731,11 +737,11 @@ abstract class CommonObject if (empty($this->last_main_doc)) { - return ''; // No way to known which document name to use + return ''; // No way to known which document name to use } include_once DOL_DOCUMENT_ROOT.'/ecm/class/ecmfiles.class.php'; - $ecmfile=new EcmFiles($this->db); + $ecmfile = new EcmFiles($this->db); $result = $ecmfile->fetch(0, '', $this->last_main_doc); if ($result < 0) { @@ -782,29 +788,29 @@ abstract class CommonObject else return ''; } // Define $urlwithroot - $urlwithouturlroot=preg_replace('/'.preg_quote(DOL_URL_ROOT, '/').'$/i', '', trim($dolibarr_main_url_root)); + $urlwithouturlroot = preg_replace('/'.preg_quote(DOL_URL_ROOT, '/').'$/i', '', trim($dolibarr_main_url_root)); // This is to use external domain name found into config file //if (DOL_URL_ROOT && ! preg_match('/\/$/', $urlwithouturlroot) && ! preg_match('/^\//', DOL_URL_ROOT)) $urlwithroot=$urlwithouturlroot.'/'.DOL_URL_ROOT; //else - $urlwithroot=$urlwithouturlroot.DOL_URL_ROOT; + $urlwithroot = $urlwithouturlroot.DOL_URL_ROOT; //$urlwithroot=DOL_MAIN_URL_ROOT; // This is to use same domain name than current - $forcedownload=0; + $forcedownload = 0; - $paramlink=''; + $paramlink = ''; //if (! empty($modulepart)) $paramlink.=($paramlink?'&':'').'modulepart='.$modulepart; // For sharing with hash (so public files), modulepart is not required. //if (! empty($ecmfile->entity)) $paramlink.='&entity='.$ecmfile->entity; // For sharing with hash (so public files), entity is not required. //$paramlink.=($paramlink?'&':'').'file='.urlencode($filepath); // No need of name of file for public link, we will use the hash - if (! empty($ecmfile->share)) $paramlink.=($paramlink?'&':'').'hashp='.$ecmfile->share; // Hash for public share - if ($forcedownload) $paramlink.=($paramlink?'&':'').'attachment=1'; + if (!empty($ecmfile->share)) $paramlink .= ($paramlink ? '&' : '').'hashp='.$ecmfile->share; // Hash for public share + if ($forcedownload) $paramlink .= ($paramlink ? '&' : '').'attachment=1'; if ($relativelink) { - $linktoreturn='document.php'.($paramlink?'?'.$paramlink:''); + $linktoreturn = 'document.php'.($paramlink ? '?'.$paramlink : ''); } else { - $linktoreturn=$urlwithroot.'/document.php'.($paramlink?'?'.$paramlink:''); + $linktoreturn = $urlwithroot.'/document.php'.($paramlink ? '?'.$paramlink : ''); } // Here $ecmfile->share is defined @@ -825,7 +831,7 @@ abstract class CommonObject public function add_contact($fk_socpeople, $type_contact, $source = 'external', $notrigger = 0) { // phpcs:enable - global $user,$langs; + global $user, $langs; dol_syslog(get_class($this)."::add_contact $fk_socpeople, $type_contact, $source, $notrigger"); @@ -834,43 +840,43 @@ abstract class CommonObject if ($fk_socpeople <= 0) { $langs->load("errors"); - $this->error=$langs->trans("ErrorWrongValueForParameterX", "1"); + $this->error = $langs->trans("ErrorWrongValueForParameterX", "1"); dol_syslog(get_class($this)."::add_contact ".$this->error, LOG_ERR); return -1; } - if (! $type_contact) + if (!$type_contact) { $langs->load("errors"); - $this->error=$langs->trans("ErrorWrongValueForParameterX", "2"); + $this->error = $langs->trans("ErrorWrongValueForParameterX", "2"); dol_syslog(get_class($this)."::add_contact ".$this->error, LOG_ERR); return -2; } - $id_type_contact=0; + $id_type_contact = 0; if (is_numeric($type_contact)) { - $id_type_contact=$type_contact; + $id_type_contact = $type_contact; } else { // We look for id type_contact $sql = "SELECT tc.rowid"; - $sql.= " FROM ".MAIN_DB_PREFIX."c_type_contact as tc"; - $sql.= " WHERE tc.element='".$this->db->escape($this->element)."'"; - $sql.= " AND tc.source='".$this->db->escape($source)."'"; - $sql.= " AND tc.code='".$this->db->escape($type_contact)."' AND tc.active=1"; + $sql .= " FROM ".MAIN_DB_PREFIX."c_type_contact as tc"; + $sql .= " WHERE tc.element='".$this->db->escape($this->element)."'"; + $sql .= " AND tc.source='".$this->db->escape($source)."'"; + $sql .= " AND tc.code='".$this->db->escape($type_contact)."' AND tc.active=1"; //print $sql; - $resql=$this->db->query($sql); + $resql = $this->db->query($sql); if ($resql) { $obj = $this->db->fetch_object($resql); - if ($obj) $id_type_contact=$obj->rowid; + if ($obj) $id_type_contact = $obj->rowid; } } if ($id_type_contact == 0) { - $this->error='CODE_NOT_VALID_FOR_THIS_ELEMENT'; + $this->error = 'CODE_NOT_VALID_FOR_THIS_ELEMENT'; dol_syslog("CODE_NOT_VALID_FOR_THIS_ELEMENT: Code type of contact '".$type_contact."' does not exists or is not active for element ".$this->element.", we can ignore it"); return -3; } @@ -878,34 +884,34 @@ abstract class CommonObject $datecreate = dol_now(); // Socpeople must have already been added by some trigger, then we have to check it to avoid DB_ERROR_RECORD_ALREADY_EXISTS error - $TListeContacts=$this->liste_contact(-1, $source); - $already_added=false; - if (is_array($TListeContacts) && ! empty($TListeContacts)) { - foreach($TListeContacts as $array_contact) { + $TListeContacts = $this->liste_contact(-1, $source); + $already_added = false; + if (is_array($TListeContacts) && !empty($TListeContacts)) { + foreach ($TListeContacts as $array_contact) { if ($array_contact['status'] == 4 && $array_contact['id'] == $fk_socpeople && $array_contact['fk_c_type_contact'] == $id_type_contact) { - $already_added=true; + $already_added = true; break; } } } - if(!$already_added) { + if (!$already_added) { $this->db->begin(); // Insert into database $sql = "INSERT INTO ".MAIN_DB_PREFIX."element_contact"; - $sql.= " (element_id, fk_socpeople, datecreate, statut, fk_c_type_contact) "; - $sql.= " VALUES (".$this->id.", ".$fk_socpeople." , " ; - $sql.= "'".$this->db->idate($datecreate)."'"; - $sql.= ", 4, ". $id_type_contact; - $sql.= ")"; + $sql .= " (element_id, fk_socpeople, datecreate, statut, fk_c_type_contact) "; + $sql .= " VALUES (".$this->id.", ".$fk_socpeople." , "; + $sql .= "'".$this->db->idate($datecreate)."'"; + $sql .= ", 4, ".$id_type_contact; + $sql .= ")"; - $resql=$this->db->query($sql); + $resql = $this->db->query($sql); if ($resql) { - if (! $notrigger) + if (!$notrigger) { - $result=$this->call_trigger(strtoupper($this->element).'_ADD_CONTACT', $user); + $result = $this->call_trigger(strtoupper($this->element).'_ADD_CONTACT', $user); if ($result < 0) { $this->db->rollback(); @@ -920,14 +926,14 @@ abstract class CommonObject { if ($this->db->errno() == 'DB_ERROR_RECORD_ALREADY_EXISTS') { - $this->error=$this->db->errno(); + $this->error = $this->db->errno(); $this->db->rollback(); echo 'err rollback'; return -2; } else { - $this->error=$this->db->error(); + $this->error = $this->db->error(); $this->db->rollback(); return -1; } @@ -947,11 +953,11 @@ abstract class CommonObject { // phpcs:enable $contacts = $objFrom->liste_contact(-1, $source); - foreach($contacts as $contact) + foreach ($contacts as $contact) { if ($this->add_contact($contact['id'], $contact['fk_c_type_contact'], $contact['source']) < 0) { - $this->error=$this->db->lasterror(); + $this->error = $this->db->lasterror(); return -1; } } @@ -973,18 +979,18 @@ abstract class CommonObject // phpcs:enable // Insert into database $sql = "UPDATE ".MAIN_DB_PREFIX."element_contact set"; - $sql.= " statut = ".$statut; - if ($type_contact_id) $sql.= ", fk_c_type_contact = '".$type_contact_id ."'"; - if ($fk_socpeople) $sql.= ", fk_socpeople = '".$fk_socpeople ."'"; - $sql.= " where rowid = ".$rowid; - $resql=$this->db->query($sql); + $sql .= " statut = ".$statut; + if ($type_contact_id) $sql .= ", fk_c_type_contact = '".$type_contact_id."'"; + if ($fk_socpeople) $sql .= ", fk_socpeople = '".$fk_socpeople."'"; + $sql .= " where rowid = ".$rowid; + $resql = $this->db->query($sql); if ($resql) { return 0; } else { - $this->error=$this->db->lasterror(); + $this->error = $this->db->lasterror(); return -1; } } @@ -1006,14 +1012,14 @@ abstract class CommonObject $this->db->begin(); $sql = "DELETE FROM ".MAIN_DB_PREFIX."element_contact"; - $sql.= " WHERE rowid =".$rowid; + $sql .= " WHERE rowid =".$rowid; dol_syslog(get_class($this)."::delete_contact", LOG_DEBUG); if ($this->db->query($sql)) { - if (! $notrigger) + if (!$notrigger) { - $result=$this->call_trigger(strtoupper($this->element).'_DELETE_CONTACT', $user); + $result = $this->call_trigger(strtoupper($this->element).'_DELETE_CONTACT', $user); if ($result < 0) { $this->db->rollback(); return -1; } } @@ -1022,7 +1028,7 @@ abstract class CommonObject } else { - $this->error=$this->db->lasterror(); + $this->error = $this->db->lasterror(); $this->db->rollback(); return -1; } @@ -1042,16 +1048,16 @@ abstract class CommonObject $temp = array(); $typeContact = $this->liste_type_contact($source, '', 0, 0, $code); - foreach($typeContact as $key => $value) + foreach ($typeContact as $key => $value) { array_push($temp, $key); } $listId = implode(",", $temp); $sql = "DELETE FROM ".MAIN_DB_PREFIX."element_contact"; - $sql.= " WHERE element_id = ".$this->id; + $sql .= " WHERE element_id = ".$this->id; if ($listId) - $sql.= " AND fk_c_type_contact IN (".$listId.")"; + $sql .= " AND fk_c_type_contact IN (".$listId.")"; dol_syslog(get_class($this)."::delete_linked_contact", LOG_DEBUG); if ($this->db->query($sql)) @@ -1060,7 +1066,7 @@ abstract class CommonObject } else { - $this->error=$this->db->lasterror(); + $this->error = $this->db->lasterror(); return -1; } } @@ -1080,49 +1086,49 @@ abstract class CommonObject // phpcs:enable global $langs; - $tab=array(); + $tab = array(); - $sql = "SELECT ec.rowid, ec.statut as statuslink, ec.fk_socpeople as id, ec.fk_c_type_contact"; // This field contains id of llx_socpeople or id of llx_user - if ($source == 'internal') $sql.=", '-1' as socid, t.statut as statuscontact, t.login, t.photo"; - if ($source == 'external' || $source == 'thirdparty') $sql.=", t.fk_soc as socid, t.statut as statuscontact"; - $sql.= ", t.civility as civility, t.lastname as lastname, t.firstname, t.email"; - $sql.= ", tc.source, tc.element, tc.code, tc.libelle"; - $sql.= " FROM ".MAIN_DB_PREFIX."c_type_contact tc"; - $sql.= ", ".MAIN_DB_PREFIX."element_contact ec"; - if ($source == 'internal') $sql.=" LEFT JOIN ".MAIN_DB_PREFIX."user t on ec.fk_socpeople = t.rowid"; - if ($source == 'external'|| $source == 'thirdparty') $sql.=" LEFT JOIN ".MAIN_DB_PREFIX."socpeople t on ec.fk_socpeople = t.rowid"; - $sql.= " WHERE ec.element_id =".$this->id; - $sql.= " AND ec.fk_c_type_contact=tc.rowid"; - $sql.= " AND tc.element='".$this->db->escape($this->element)."'"; - if ($code) $sql.= " AND tc.code = '".$this->db->escape($code)."'"; - if ($source == 'internal') $sql.= " AND tc.source = 'internal'"; - if ($source == 'external' || $source == 'thirdparty') $sql.= " AND tc.source = 'external'"; - $sql.= " AND tc.active=1"; - if ($status >= 0) $sql.= " AND ec.statut = ".$status; - $sql.=" ORDER BY t.lastname ASC"; + $sql = "SELECT ec.rowid, ec.statut as statuslink, ec.fk_socpeople as id, ec.fk_c_type_contact"; // This field contains id of llx_socpeople or id of llx_user + if ($source == 'internal') $sql .= ", '-1' as socid, t.statut as statuscontact, t.login, t.photo"; + if ($source == 'external' || $source == 'thirdparty') $sql .= ", t.fk_soc as socid, t.statut as statuscontact"; + $sql .= ", t.civility as civility, t.lastname as lastname, t.firstname, t.email"; + $sql .= ", tc.source, tc.element, tc.code, tc.libelle"; + $sql .= " FROM ".MAIN_DB_PREFIX."c_type_contact tc"; + $sql .= ", ".MAIN_DB_PREFIX."element_contact ec"; + if ($source == 'internal') $sql .= " LEFT JOIN ".MAIN_DB_PREFIX."user t on ec.fk_socpeople = t.rowid"; + if ($source == 'external' || $source == 'thirdparty') $sql .= " LEFT JOIN ".MAIN_DB_PREFIX."socpeople t on ec.fk_socpeople = t.rowid"; + $sql .= " WHERE ec.element_id =".$this->id; + $sql .= " AND ec.fk_c_type_contact=tc.rowid"; + $sql .= " AND tc.element='".$this->db->escape($this->element)."'"; + if ($code) $sql .= " AND tc.code = '".$this->db->escape($code)."'"; + if ($source == 'internal') $sql .= " AND tc.source = 'internal'"; + if ($source == 'external' || $source == 'thirdparty') $sql .= " AND tc.source = 'external'"; + $sql .= " AND tc.active=1"; + if ($status >= 0) $sql .= " AND ec.statut = ".$status; + $sql .= " ORDER BY t.lastname ASC"; dol_syslog(get_class($this)."::liste_contact", LOG_DEBUG); - $resql=$this->db->query($sql); + $resql = $this->db->query($sql); if ($resql) { - $num=$this->db->num_rows($resql); - $i=0; + $num = $this->db->num_rows($resql); + $i = 0; while ($i < $num) { $obj = $this->db->fetch_object($resql); - if (! $list) + if (!$list) { - $transkey="TypeContact_".$obj->element."_".$obj->source."_".$obj->code; - $libelle_type=($langs->trans($transkey)!=$transkey ? $langs->trans($transkey) : $obj->libelle); - $tab[$i]=array('source'=>$obj->source,'socid'=>$obj->socid,'id'=>$obj->id, - 'nom'=>$obj->lastname, // For backward compatibility + $transkey = "TypeContact_".$obj->element."_".$obj->source."_".$obj->code; + $libelle_type = ($langs->trans($transkey) != $transkey ? $langs->trans($transkey) : $obj->libelle); + $tab[$i] = array('source'=>$obj->source, 'socid'=>$obj->socid, 'id'=>$obj->id, + 'nom'=>$obj->lastname, // For backward compatibility 'civility'=>$obj->civility, 'lastname'=>$obj->lastname, 'firstname'=>$obj->firstname, 'email'=>$obj->email, 'login'=>$obj->login, 'photo'=>$obj->photo, 'statuscontact'=>$obj->statuscontact, 'rowid'=>$obj->rowid, 'code'=>$obj->code, 'libelle'=>$libelle_type, 'status'=>$obj->statuslink, 'fk_c_type_contact'=>$obj->fk_c_type_contact); } else { - $tab[$i]=$obj->id; + $tab[$i] = $obj->id; } $i++; @@ -1132,7 +1138,7 @@ abstract class CommonObject } else { - $this->error=$this->db->lasterror(); + $this->error = $this->db->lasterror(); dol_print_error($this->db); return -1; } @@ -1148,16 +1154,16 @@ abstract class CommonObject public function swapContactStatus($rowid) { $sql = "SELECT ec.datecreate, ec.statut, ec.fk_socpeople, ec.fk_c_type_contact,"; - $sql.= " tc.code, tc.libelle"; + $sql .= " tc.code, tc.libelle"; //$sql.= ", s.fk_soc"; - $sql.= " FROM (".MAIN_DB_PREFIX."element_contact as ec, ".MAIN_DB_PREFIX."c_type_contact as tc)"; + $sql .= " FROM (".MAIN_DB_PREFIX."element_contact as ec, ".MAIN_DB_PREFIX."c_type_contact as tc)"; //$sql.= " LEFT JOIN ".MAIN_DB_PREFIX."socpeople as s ON ec.fk_socpeople=s.rowid"; // Si contact de type external, alors il est lie a une societe - $sql.= " WHERE ec.rowid =".$rowid; - $sql.= " AND ec.fk_c_type_contact=tc.rowid"; - $sql.= " AND tc.element = '".$this->db->escape($this->element)."'"; + $sql .= " WHERE ec.rowid =".$rowid; + $sql .= " AND ec.fk_c_type_contact=tc.rowid"; + $sql .= " AND tc.element = '".$this->db->escape($this->element)."'"; dol_syslog(get_class($this)."::swapContactStatus", LOG_DEBUG); - $resql=$this->db->query($sql); + $resql = $this->db->query($sql); if ($resql) { $obj = $this->db->fetch_object($resql); @@ -1168,7 +1174,7 @@ abstract class CommonObject } else { - $this->error=$this->db->error(); + $this->error = $this->db->error(); dol_print_error($this->db); return -1; } @@ -1190,39 +1196,39 @@ abstract class CommonObject // phpcs:enable global $langs; - if (empty($order)) $order='position'; - if ($order == 'position') $order.=',code'; + if (empty($order)) $order = 'position'; + if ($order == 'position') $order .= ',code'; $tab = array(); $sql = "SELECT DISTINCT tc.rowid, tc.code, tc.libelle, tc.position"; - $sql.= " FROM ".MAIN_DB_PREFIX."c_type_contact as tc"; - $sql.= " WHERE tc.element='".$this->db->escape($this->element)."'"; - if ($activeonly == 1) $sql.= " AND tc.active=1"; // only the active types - if (! empty($source) && $source != 'all') $sql.= " AND tc.source='".$this->db->escape($source)."'"; - if (! empty($code)) $sql.= " AND tc.code='".$this->db->escape($code)."'"; - $sql.= $this->db->order($order, 'ASC'); + $sql .= " FROM ".MAIN_DB_PREFIX."c_type_contact as tc"; + $sql .= " WHERE tc.element='".$this->db->escape($this->element)."'"; + if ($activeonly == 1) $sql .= " AND tc.active=1"; // only the active types + if (!empty($source) && $source != 'all') $sql .= " AND tc.source='".$this->db->escape($source)."'"; + if (!empty($code)) $sql .= " AND tc.code='".$this->db->escape($code)."'"; + $sql .= $this->db->order($order, 'ASC'); //print "sql=".$sql; - $resql=$this->db->query($sql); + $resql = $this->db->query($sql); if ($resql) { - $num=$this->db->num_rows($resql); - $i=0; + $num = $this->db->num_rows($resql); + $i = 0; while ($i < $num) { $obj = $this->db->fetch_object($resql); - $transkey="TypeContact_".$this->element."_".$source."_".$obj->code; - $libelle_type=($langs->trans($transkey)!=$transkey ? $langs->trans($transkey) : $obj->libelle); - if (empty($option)) $tab[$obj->rowid]=$libelle_type; - else $tab[$obj->code]=$libelle_type; + $transkey = "TypeContact_".$this->element."_".$source."_".$obj->code; + $libelle_type = ($langs->trans($transkey) != $transkey ? $langs->trans($transkey) : $obj->libelle); + if (empty($option)) $tab[$obj->rowid] = $libelle_type; + else $tab[$obj->code] = $libelle_type; $i++; } return $tab; } else { - $this->error=$this->db->lasterror(); + $this->error = $this->db->lasterror(); //dol_print_error($this->db); return null; } @@ -1247,51 +1253,51 @@ abstract class CommonObject $tab = array(); $sql = "SELECT DISTINCT tc.rowid, tc.code, tc.libelle, tc.position, tc.element"; - $sql.= " FROM ".MAIN_DB_PREFIX."c_type_contact as tc"; + $sql .= " FROM ".MAIN_DB_PREFIX."c_type_contact as tc"; - $sqlWhere=array(); + $sqlWhere = array(); if (!empty($element)) - $sqlWhere[]=" tc.element='".$this->db->escape($element)."'"; + $sqlWhere[] = " tc.element='".$this->db->escape($element)."'"; if ($activeonly == 1) - $sqlWhere[]=" tc.active=1"; // only the active types + $sqlWhere[] = " tc.active=1"; // only the active types - if (! empty($source) && $source != 'all') - $sqlWhere[]=" tc.source='".$this->db->escape($source)."'"; + if (!empty($source) && $source != 'all') + $sqlWhere[] = " tc.source='".$this->db->escape($source)."'"; - if (! empty($code)) - $sqlWhere[]=" tc.code='".$this->db->escape($code)."'"; + if (!empty($code)) + $sqlWhere[] = " tc.code='".$this->db->escape($code)."'"; - if (count($sqlWhere)>0) { - $sql .= " WHERE ". implode(' AND ', $sqlWhere); + if (count($sqlWhere) > 0) { + $sql .= " WHERE ".implode(' AND ', $sqlWhere); } - $sql.= $this->db->order('tc.element, tc.position', 'ASC'); + $sql .= $this->db->order('tc.element, tc.position', 'ASC'); dol_syslog(get_class($this)."::".__METHOD__, LOG_DEBUG); - $resql=$this->db->query($sql); + $resql = $this->db->query($sql); if ($resql) { $num = $this->db->num_rows($resql); if ($num > 0) { while ($obj = $this->db->fetch_object($resql)) { - if (strpos($obj->element, 'project')!==false) { - $element='projet'; - } elseif($obj->element=='contrat') { - $element='contract'; - } elseif(strpos($obj->element, 'supplier')!==false && $obj->element!='supplier_proposal') { - $element='fournisseur'; - } elseif(strpos($obj->element, 'supplier')!==false && $obj->element!='supplier_proposal') { - $element='fournisseur'; + if (strpos($obj->element, 'project') !== false) { + $element = 'projet'; + } elseif ($obj->element == 'contrat') { + $element = 'contract'; + } elseif (strpos($obj->element, 'supplier') !== false && $obj->element != 'supplier_proposal') { + $element = 'fournisseur'; + } elseif (strpos($obj->element, 'supplier') !== false && $obj->element != 'supplier_proposal') { + $element = 'fournisseur'; } else { - $element=$obj->element; + $element = $obj->element; } if ($conf->{$element}->enabled) { - $libelle_element = $langs->trans('ContactDefault_' . $obj->element); - $transkey = "TypeContact_" . $this->element . "_" . $source . "_" . $obj->code; + $libelle_element = $langs->trans('ContactDefault_'.$obj->element); + $transkey = "TypeContact_".$this->element."_".$source."_".$obj->code; $libelle_type = ($langs->trans($transkey) != $transkey ? $langs->trans($transkey) : $obj->libelle); if (empty($option)) - $tab[$obj->rowid] = $libelle_element . ' - ' . $libelle_type; - else $tab[$obj->rowid] = $libelle_element . ' - ' . $libelle_type; + $tab[$obj->rowid] = $libelle_element.' - '.$libelle_type; + else $tab[$obj->rowid] = $libelle_element.' - '.$libelle_type; } } } @@ -1299,7 +1305,7 @@ abstract class CommonObject } else { - $this->error=$this->db->lasterror(); + $this->error = $this->db->lasterror(); return null; } } @@ -1319,49 +1325,49 @@ abstract class CommonObject { global $conf; - $result=array(); - $i=0; + $result = array(); + $i = 0; //cas particulier pour les expeditions - if ($this->element=='shipping' && $this->origin_id != 0) { - $id=$this->origin_id; - $element='commande'; - } elseif ($this->element=='reception' && $this->origin_id != 0) { - $id=$this->origin_id; - $element='order_supplier'; + if ($this->element == 'shipping' && $this->origin_id != 0) { + $id = $this->origin_id; + $element = 'commande'; + } elseif ($this->element == 'reception' && $this->origin_id != 0) { + $id = $this->origin_id; + $element = 'order_supplier'; } else { - $id=$this->id; - $element=$this->element; + $id = $this->id; + $element = $this->element; } $sql = "SELECT ec.fk_socpeople"; - $sql.= " FROM ".MAIN_DB_PREFIX."element_contact as ec,"; - if ($source == 'internal') $sql.= " ".MAIN_DB_PREFIX."user as c,"; - if ($source == 'external') $sql.= " ".MAIN_DB_PREFIX."socpeople as c,"; - $sql.= " ".MAIN_DB_PREFIX."c_type_contact as tc"; - $sql.= " WHERE ec.element_id = ".$id; - $sql.= " AND ec.fk_socpeople = c.rowid"; - if ($source == 'internal') $sql.= " AND c.entity IN (".getEntity('user').")"; - if ($source == 'external') $sql.= " AND c.entity IN (".getEntity('societe').")"; - $sql.= " AND ec.fk_c_type_contact = tc.rowid"; - $sql.= " AND tc.element = '".$element."'"; - $sql.= " AND tc.source = '".$source."'"; - if ($code) $sql.= " AND tc.code = '".$code."'"; - $sql.= " AND tc.active = 1"; - if ($status) $sql.= " AND ec.statut = ".$status; + $sql .= " FROM ".MAIN_DB_PREFIX."element_contact as ec,"; + if ($source == 'internal') $sql .= " ".MAIN_DB_PREFIX."user as c,"; + if ($source == 'external') $sql .= " ".MAIN_DB_PREFIX."socpeople as c,"; + $sql .= " ".MAIN_DB_PREFIX."c_type_contact as tc"; + $sql .= " WHERE ec.element_id = ".$id; + $sql .= " AND ec.fk_socpeople = c.rowid"; + if ($source == 'internal') $sql .= " AND c.entity IN (".getEntity('user').")"; + if ($source == 'external') $sql .= " AND c.entity IN (".getEntity('societe').")"; + $sql .= " AND ec.fk_c_type_contact = tc.rowid"; + $sql .= " AND tc.element = '".$element."'"; + $sql .= " AND tc.source = '".$source."'"; + if ($code) $sql .= " AND tc.code = '".$code."'"; + $sql .= " AND tc.active = 1"; + if ($status) $sql .= " AND ec.statut = ".$status; dol_syslog(get_class($this)."::getIdContact", LOG_DEBUG); - $resql=$this->db->query($sql); + $resql = $this->db->query($sql); if ($resql) { while ($obj = $this->db->fetch_object($resql)) { - $result[$i]=$obj->fk_socpeople; + $result[$i] = $obj->fk_socpeople; $i++; } } else { - $this->error=$this->db->error(); + $this->error = $this->db->error(); return null; } @@ -1378,13 +1384,13 @@ abstract class CommonObject public function fetch_contact($contactid = null) { // phpcs:enable - if (empty($contactid)) $contactid=$this->contactid; + if (empty($contactid)) $contactid = $this->contactid; if (empty($contactid)) return 0; require_once DOL_DOCUMENT_ROOT.'/contact/class/contact.class.php'; $contact = new Contact($this->db); - $result=$contact->fetch($contactid); + $result = $contact->fetch($contactid); $this->contact = $contact; return $result; } @@ -1404,7 +1410,7 @@ abstract class CommonObject if (empty($this->socid) && empty($this->fk_soc) && empty($this->fk_thirdparty) && empty($force_thirdparty_id)) return 0; - require_once DOL_DOCUMENT_ROOT . '/societe/class/societe.class.php'; + require_once DOL_DOCUMENT_ROOT.'/societe/class/societe.class.php'; $idtofetch = isset($this->socid) ? $this->socid : (isset($this->fk_soc) ? $this->fk_soc : $this->fk_thirdparty); if ($force_thirdparty_id) @@ -1467,7 +1473,7 @@ abstract class CommonObject dol_syslog(get_class($this).'::fetch_barcode this->element='.$this->element.' this->barcode_type='.$this->barcode_type); - $idtype=$this->barcode_type; + $idtype = $this->barcode_type; if (empty($idtype) && $idtype != '0') // If type of barcode no set, we try to guess. If set to '0' it means we forced to have type remain not defined { if ($this->element == 'product') $idtype = $conf->global->PRODUIT_DEFAULT_BARCODE_TYPE; @@ -1480,8 +1486,8 @@ abstract class CommonObject if (empty($this->barcode_type) || empty($this->barcode_type_code) || empty($this->barcode_type_label) || empty($this->barcode_type_coder)) // If data not already loaded { $sql = "SELECT rowid, code, libelle as label, coder"; - $sql.= " FROM ".MAIN_DB_PREFIX."c_barcode_type"; - $sql.= " WHERE rowid = ".$idtype; + $sql .= " FROM ".MAIN_DB_PREFIX."c_barcode_type"; + $sql .= " WHERE rowid = ".$idtype; dol_syslog(get_class($this).'::fetch_barcode', LOG_DEBUG); $resql = $this->db->query($sql); if ($resql) @@ -1514,13 +1520,13 @@ abstract class CommonObject // phpcs:enable include_once DOL_DOCUMENT_ROOT.'/projet/class/project.class.php'; - if (empty($this->fk_project) && ! empty($this->fk_projet)) $this->fk_project = $this->fk_projet; // For backward compatibility + if (empty($this->fk_project) && !empty($this->fk_projet)) $this->fk_project = $this->fk_projet; // For backward compatibility if (empty($this->fk_project)) return 0; $project = new Project($this->db); $result = $project->fetch($this->fk_project); - $this->projet = $project; // deprecated + $this->projet = $project; // deprecated $this->project = $project; return $result; } @@ -1556,7 +1562,7 @@ abstract class CommonObject { // phpcs:enable $user = new User($this->db); - $result=$user->fetch($userid); + $result = $user->fetch($userid); $this->user = $user; return $result; } @@ -1594,14 +1600,14 @@ abstract class CommonObject { global $conf; - $result=false; + $result = false; $sql = "SELECT rowid FROM ".MAIN_DB_PREFIX.$table; - $sql.= " WHERE ".$field." = '".$key."'"; - if (! empty($element)) { - $sql.= " AND entity IN (".getEntity($element).")"; + $sql .= " WHERE ".$field." = '".$key."'"; + if (!empty($element)) { + $sql .= " AND entity IN (".getEntity($element).")"; } else { - $sql.= " AND entity = ".$conf->entity; + $sql .= " AND entity = ".$conf->entity; } dol_syslog(get_class($this).'::fetchObjectFrom', LOG_DEBUG); @@ -1628,10 +1634,10 @@ abstract class CommonObject */ public function getValueFrom($table, $id, $field) { - $result=false; + $result = false; if (!empty($id) && !empty($field) && !empty($table)) { $sql = "SELECT ".$field." FROM ".MAIN_DB_PREFIX.$table; - $sql.= " WHERE rowid = ".$id; + $sql .= " WHERE rowid = ".$id; dol_syslog(get_class($this).'::getValueFrom', LOG_DEBUG); $resql = $this->db->query($sql); @@ -1662,34 +1668,34 @@ abstract class CommonObject */ public function setValueFrom($field, $value, $table = '', $id = null, $format = '', $id_field = '', $fuser = null, $trigkey = '', $fk_user_field = 'fk_user_modif') { - global $user,$langs,$conf; + global $user, $langs, $conf; - if (empty($table)) $table=$this->table_element; - if (empty($id)) $id=$this->id; - if (empty($format)) $format='text'; - if (empty($id_field)) $id_field='rowid'; + if (empty($table)) $table = $this->table_element; + if (empty($id)) $id = $this->id; + if (empty($format)) $format = 'text'; + if (empty($id_field)) $id_field = 'rowid'; - $error=0; + $error = 0; $this->db->begin(); // Special case - if ($table == 'product' && $field == 'note_private') $field='note'; + if ($table == 'product' && $field == 'note_private') $field = 'note'; if (in_array($table, array('actioncomm', 'adherent', 'advtargetemailing', 'cronjob', 'establishment'))) $fk_user_field = 'fk_user_mod'; $sql = "UPDATE ".MAIN_DB_PREFIX.$table." SET "; - if ($format == 'text') $sql.= $field." = '".$this->db->escape($value)."'"; - elseif ($format == 'int') $sql.= $field." = ".$this->db->escape($value); - elseif ($format == 'date') $sql.= $field." = ".($value ? "'".$this->db->idate($value)."'" : "null"); + if ($format == 'text') $sql .= $field." = '".$this->db->escape($value)."'"; + elseif ($format == 'int') $sql .= $field." = ".$this->db->escape($value); + elseif ($format == 'date') $sql .= $field." = ".($value ? "'".$this->db->idate($value)."'" : "null"); if ($fk_user_field) { - if (! empty($fuser) && is_object($fuser)) $sql.=", ".$fk_user_field." = ".$fuser->id; - elseif (empty($fuser) || $fuser != 'none') $sql.=", ".$fk_user_field." = ".$user->id; + if (!empty($fuser) && is_object($fuser)) $sql .= ", ".$fk_user_field." = ".$fuser->id; + elseif (empty($fuser) || $fuser != 'none') $sql .= ", ".$fk_user_field." = ".$user->id; } - $sql.= " WHERE ".$id_field." = ".$id; + $sql .= " WHERE ".$id_field." = ".$id; dol_syslog(get_class($this)."::".__FUNCTION__."", LOG_DEBUG); $resql = $this->db->query($sql); @@ -1706,11 +1712,11 @@ abstract class CommonObject { $result = $this->fetchCommon($id); } - if ($result >= 0) $result=$this->call_trigger($trigkey, (! empty($fuser) && is_object($fuser)) ? $fuser : $user); // This may set this->errors + if ($result >= 0) $result = $this->call_trigger($trigkey, (!empty($fuser) && is_object($fuser)) ? $fuser : $user); // This may set this->errors if ($result < 0) $error++; } - if (! $error) + if (!$error) { if (property_exists($this, $field)) $this->$field = $value; $this->db->commit(); @@ -1724,7 +1730,7 @@ abstract class CommonObject } else { - $this->error=$this->db->lasterror(); + $this->error = $this->db->lasterror(); $this->db->rollback(); return -1; } @@ -1744,7 +1750,7 @@ abstract class CommonObject // phpcs:enable global $conf, $user; - if (! $this->table_element) + if (!$this->table_element) { dol_print_error('', get_class($this)."::load_previous_next_ref was called on objet with property table_element not defined"); return -1; @@ -1761,45 +1767,45 @@ abstract class CommonObject if ($this->element == 'societe') $alias = 'te'; $sql = "SELECT MAX(te.".$fieldid.")"; - $sql.= " FROM ".(empty($nodbprefix)?MAIN_DB_PREFIX:'').$this->table_element." as te"; - if ($this->element == 'user' && ! empty($conf->global->MULTICOMPANY_TRANSVERSE_MODE)) { - $sql.= ",".MAIN_DB_PREFIX."usergroup_user as ug"; + $sql .= " FROM ".(empty($nodbprefix) ?MAIN_DB_PREFIX:'').$this->table_element." as te"; + if ($this->element == 'user' && !empty($conf->global->MULTICOMPANY_TRANSVERSE_MODE)) { + $sql .= ",".MAIN_DB_PREFIX."usergroup_user as ug"; } - if (isset($this->ismultientitymanaged) && $this->ismultientitymanaged == 2) $sql.= ", ".MAIN_DB_PREFIX."societe as s"; // If we need to link to societe to limit select to entity - elseif ($this->restrictiononfksoc == 1 && $this->element != 'societe' && !$user->rights->societe->client->voir && !$socid) $sql.= ", ".MAIN_DB_PREFIX."societe as s"; // If we need to link to societe to limit select to socid - elseif ($this->restrictiononfksoc == 2 && $this->element != 'societe' && !$user->rights->societe->client->voir && !$socid) $sql.= " LEFT JOIN ".MAIN_DB_PREFIX."societe as s ON te.fk_soc = s.rowid"; // If we need to link to societe to limit select to socid - if ($this->restrictiononfksoc && !$user->rights->societe->client->voir && !$socid) $sql.= " LEFT JOIN ".MAIN_DB_PREFIX."societe_commerciaux as sc ON ".$alias.".rowid = sc.fk_soc"; - $sql.= " WHERE te.".$fieldid." < '".$this->db->escape($this->ref)."'"; // ->ref must always be defined (set to id if field does not exists) - if ($this->restrictiononfksoc == 1 && !$user->rights->societe->client->voir && !$socid) $sql.= " AND sc.fk_user = " .$user->id; - if ($this->restrictiononfksoc == 2 && !$user->rights->societe->client->voir && !$socid) $sql.= " AND (sc.fk_user = " .$user->id.' OR te.fk_soc IS NULL)'; - if (! empty($filter)) + if (isset($this->ismultientitymanaged) && $this->ismultientitymanaged == 2) $sql .= ", ".MAIN_DB_PREFIX."societe as s"; // If we need to link to societe to limit select to entity + elseif ($this->restrictiononfksoc == 1 && $this->element != 'societe' && !$user->rights->societe->client->voir && !$socid) $sql .= ", ".MAIN_DB_PREFIX."societe as s"; // If we need to link to societe to limit select to socid + elseif ($this->restrictiononfksoc == 2 && $this->element != 'societe' && !$user->rights->societe->client->voir && !$socid) $sql .= " LEFT JOIN ".MAIN_DB_PREFIX."societe as s ON te.fk_soc = s.rowid"; // If we need to link to societe to limit select to socid + if ($this->restrictiononfksoc && !$user->rights->societe->client->voir && !$socid) $sql .= " LEFT JOIN ".MAIN_DB_PREFIX."societe_commerciaux as sc ON ".$alias.".rowid = sc.fk_soc"; + $sql .= " WHERE te.".$fieldid." < '".$this->db->escape($this->ref)."'"; // ->ref must always be defined (set to id if field does not exists) + if ($this->restrictiononfksoc == 1 && !$user->rights->societe->client->voir && !$socid) $sql .= " AND sc.fk_user = ".$user->id; + if ($this->restrictiononfksoc == 2 && !$user->rights->societe->client->voir && !$socid) $sql .= " AND (sc.fk_user = ".$user->id.' OR te.fk_soc IS NULL)'; + if (!empty($filter)) { - if (! preg_match('/^\s*AND/i', $filter)) $sql.=" AND "; // For backward compatibility - $sql.=$filter; + if (!preg_match('/^\s*AND/i', $filter)) $sql .= " AND "; // For backward compatibility + $sql .= $filter; } - if (isset($this->ismultientitymanaged) && $this->ismultientitymanaged == 2) $sql.= ' AND te.fk_soc = s.rowid'; // If we need to link to societe to limit select to entity - elseif ($this->restrictiononfksoc == 1 && $this->element != 'societe' && !$user->rights->societe->client->voir && !$socid) $sql.= ' AND te.fk_soc = s.rowid'; // If we need to link to societe to limit select to socid + if (isset($this->ismultientitymanaged) && $this->ismultientitymanaged == 2) $sql .= ' AND te.fk_soc = s.rowid'; // If we need to link to societe to limit select to entity + elseif ($this->restrictiononfksoc == 1 && $this->element != 'societe' && !$user->rights->societe->client->voir && !$socid) $sql .= ' AND te.fk_soc = s.rowid'; // If we need to link to societe to limit select to socid if (isset($this->ismultientitymanaged) && $this->ismultientitymanaged == 1) { - if ($this->element == 'user' && ! empty($conf->global->MULTICOMPANY_TRANSVERSE_MODE)) { - if (! empty($user->admin) && empty($user->entity) && $conf->entity == 1) { - $sql.= " AND te.entity IS NOT NULL"; // Show all users + if ($this->element == 'user' && !empty($conf->global->MULTICOMPANY_TRANSVERSE_MODE)) { + if (!empty($user->admin) && empty($user->entity) && $conf->entity == 1) { + $sql .= " AND te.entity IS NOT NULL"; // Show all users } else { - $sql.= " AND ug.fk_user = te.rowid"; - $sql.= " AND ug.entity IN (".getEntity($this->element).")"; + $sql .= " AND ug.fk_user = te.rowid"; + $sql .= " AND ug.entity IN (".getEntity($this->element).")"; } } else { - $sql.= ' AND te.entity IN ('.getEntity($this->element).')'; + $sql .= ' AND te.entity IN ('.getEntity($this->element).')'; } } - if ($this->restrictiononfksoc == 1 && $socid && $this->element != 'societe') $sql.= ' AND te.fk_soc = ' . $socid; - if ($this->restrictiononfksoc == 2 && $socid && $this->element != 'societe') $sql.= ' AND (te.fk_soc = ' . $socid.' OR te.fk_soc IS NULL)'; - if ($this->restrictiononfksoc && $socid && $this->element == 'societe') $sql.= ' AND te.rowid = ' . $socid; + if ($this->restrictiononfksoc == 1 && $socid && $this->element != 'societe') $sql .= ' AND te.fk_soc = '.$socid; + if ($this->restrictiononfksoc == 2 && $socid && $this->element != 'societe') $sql .= ' AND (te.fk_soc = '.$socid.' OR te.fk_soc IS NULL)'; + if ($this->restrictiononfksoc && $socid && $this->element == 'societe') $sql .= ' AND te.rowid = '.$socid; //print 'socid='.$socid.' restrictiononfksoc='.$this->restrictiononfksoc.' ismultientitymanaged = '.$this->ismultientitymanaged.' filter = '.$filter.' -> '.$sql."
    "; $result = $this->db->query($sql); - if (! $result) + if (!$result) { - $this->error=$this->db->lasterror(); + $this->error = $this->db->lasterror(); return -1; } $row = $this->db->fetch_row($result); @@ -1807,46 +1813,46 @@ abstract class CommonObject $sql = "SELECT MIN(te.".$fieldid.")"; - $sql.= " FROM ".(empty($nodbprefix)?MAIN_DB_PREFIX:'').$this->table_element." as te"; - if ($this->element == 'user' && ! empty($conf->global->MULTICOMPANY_TRANSVERSE_MODE)) { - $sql.= ",".MAIN_DB_PREFIX."usergroup_user as ug"; + $sql .= " FROM ".(empty($nodbprefix) ?MAIN_DB_PREFIX:'').$this->table_element." as te"; + if ($this->element == 'user' && !empty($conf->global->MULTICOMPANY_TRANSVERSE_MODE)) { + $sql .= ",".MAIN_DB_PREFIX."usergroup_user as ug"; } - if (isset($this->ismultientitymanaged) && $this->ismultientitymanaged == 2) $sql.= ", ".MAIN_DB_PREFIX."societe as s"; // If we need to link to societe to limit select to entity - elseif ($this->restrictiononfksoc == 1 && $this->element != 'societe' && !$user->rights->societe->client->voir && !$socid) $sql.= ", ".MAIN_DB_PREFIX."societe as s"; // If we need to link to societe to limit select to socid - elseif ($this->restrictiononfksoc == 2 && $this->element != 'societe' && !$user->rights->societe->client->voir && !$socid) $sql.= " LEFT JOIN ".MAIN_DB_PREFIX."societe as s ON te.fk_soc = s.rowid"; // If we need to link to societe to limit select to socid - if ($this->restrictiononfksoc && !$user->rights->societe->client->voir && !$socid) $sql.= " LEFT JOIN ".MAIN_DB_PREFIX."societe_commerciaux as sc ON ".$alias.".rowid = sc.fk_soc"; - $sql.= " WHERE te.".$fieldid." > '".$this->db->escape($this->ref)."'"; // ->ref must always be defined (set to id if field does not exists) - if ($this->restrictiononfksoc == 1 && !$user->rights->societe->client->voir && !$socid) $sql.= " AND sc.fk_user = " .$user->id; - if ($this->restrictiononfksoc == 2 && !$user->rights->societe->client->voir && !$socid) $sql.= " AND (sc.fk_user = " .$user->id.' OR te.fk_soc IS NULL)'; - if (! empty($filter)) + if (isset($this->ismultientitymanaged) && $this->ismultientitymanaged == 2) $sql .= ", ".MAIN_DB_PREFIX."societe as s"; // If we need to link to societe to limit select to entity + elseif ($this->restrictiononfksoc == 1 && $this->element != 'societe' && !$user->rights->societe->client->voir && !$socid) $sql .= ", ".MAIN_DB_PREFIX."societe as s"; // If we need to link to societe to limit select to socid + elseif ($this->restrictiononfksoc == 2 && $this->element != 'societe' && !$user->rights->societe->client->voir && !$socid) $sql .= " LEFT JOIN ".MAIN_DB_PREFIX."societe as s ON te.fk_soc = s.rowid"; // If we need to link to societe to limit select to socid + if ($this->restrictiononfksoc && !$user->rights->societe->client->voir && !$socid) $sql .= " LEFT JOIN ".MAIN_DB_PREFIX."societe_commerciaux as sc ON ".$alias.".rowid = sc.fk_soc"; + $sql .= " WHERE te.".$fieldid." > '".$this->db->escape($this->ref)."'"; // ->ref must always be defined (set to id if field does not exists) + if ($this->restrictiononfksoc == 1 && !$user->rights->societe->client->voir && !$socid) $sql .= " AND sc.fk_user = ".$user->id; + if ($this->restrictiononfksoc == 2 && !$user->rights->societe->client->voir && !$socid) $sql .= " AND (sc.fk_user = ".$user->id.' OR te.fk_soc IS NULL)'; + if (!empty($filter)) { - if (! preg_match('/^\s*AND/i', $filter)) $sql.=" AND "; // For backward compatibility - $sql.=$filter; + if (!preg_match('/^\s*AND/i', $filter)) $sql .= " AND "; // For backward compatibility + $sql .= $filter; } - if (isset($this->ismultientitymanaged) && $this->ismultientitymanaged == 2) $sql.= ' AND te.fk_soc = s.rowid'; // If we need to link to societe to limit select to entity - elseif ($this->restrictiononfksoc == 1 && $this->element != 'societe' && !$user->rights->societe->client->voir && !$socid) $sql.= ' AND te.fk_soc = s.rowid'; // If we need to link to societe to limit select to socid + if (isset($this->ismultientitymanaged) && $this->ismultientitymanaged == 2) $sql .= ' AND te.fk_soc = s.rowid'; // If we need to link to societe to limit select to entity + elseif ($this->restrictiononfksoc == 1 && $this->element != 'societe' && !$user->rights->societe->client->voir && !$socid) $sql .= ' AND te.fk_soc = s.rowid'; // If we need to link to societe to limit select to socid if (isset($this->ismultientitymanaged) && $this->ismultientitymanaged == 1) { - if ($this->element == 'user' && ! empty($conf->global->MULTICOMPANY_TRANSVERSE_MODE)) { - if (! empty($user->admin) && empty($user->entity) && $conf->entity == 1) { - $sql.= " AND te.entity IS NOT NULL"; // Show all users + if ($this->element == 'user' && !empty($conf->global->MULTICOMPANY_TRANSVERSE_MODE)) { + if (!empty($user->admin) && empty($user->entity) && $conf->entity == 1) { + $sql .= " AND te.entity IS NOT NULL"; // Show all users } else { - $sql.= " AND ug.fk_user = te.rowid"; - $sql.= " AND ug.entity IN (".getEntity($this->element).")"; + $sql .= " AND ug.fk_user = te.rowid"; + $sql .= " AND ug.entity IN (".getEntity($this->element).")"; } } else { - $sql.= ' AND te.entity IN ('.getEntity($this->element).')'; + $sql .= ' AND te.entity IN ('.getEntity($this->element).')'; } } - if ($this->restrictiononfksoc == 1 && $socid && $this->element != 'societe') $sql.= ' AND te.fk_soc = ' . $socid; - if ($this->restrictiononfksoc == 2 && $socid && $this->element != 'societe') $sql.= ' AND (te.fk_soc = ' . $socid.' OR te.fk_soc IS NULL)'; - if ($this->restrictiononfksoc && $socid && $this->element == 'societe') $sql.= ' AND te.rowid = ' . $socid; + if ($this->restrictiononfksoc == 1 && $socid && $this->element != 'societe') $sql .= ' AND te.fk_soc = '.$socid; + if ($this->restrictiononfksoc == 2 && $socid && $this->element != 'societe') $sql .= ' AND (te.fk_soc = '.$socid.' OR te.fk_soc IS NULL)'; + if ($this->restrictiononfksoc && $socid && $this->element == 'societe') $sql .= ' AND te.rowid = '.$socid; //print 'socid='.$socid.' restrictiononfksoc='.$this->restrictiononfksoc.' ismultientitymanaged = '.$this->ismultientitymanaged.' filter = '.$filter.' -> '.$sql."
    "; // Rem: Bug in some mysql version: SELECT MIN(rowid) FROM llx_socpeople WHERE rowid > 1 when one row in database with rowid=1, returns 1 instead of null $result = $this->db->query($sql); - if (! $result) + if (!$result) { - $this->error=$this->db->lasterror(); + $this->error = $this->db->lasterror(); return -2; } $row = $this->db->fetch_row($result); @@ -1867,7 +1873,7 @@ abstract class CommonObject { $contactAlreadySelected = array(); $tab = $this->liste_contact(-1, $source); - $num=count($tab); + $num = count($tab); $i = 0; while ($i < $num) { @@ -1887,30 +1893,30 @@ abstract class CommonObject */ public function setProject($projectid) { - if (! $this->table_element) + if (!$this->table_element) { dol_syslog(get_class($this)."::setProject was called on objet with property table_element not defined", LOG_ERR); return -1; } $sql = 'UPDATE '.MAIN_DB_PREFIX.$this->table_element; - if (! empty($this->fields['fk_project'])) // Common case + if (!empty($this->fields['fk_project'])) // Common case { - if ($projectid) $sql.= ' SET fk_project = '.$projectid; - else $sql.= ' SET fk_project = NULL'; - $sql.= ' WHERE rowid = '.$this->id; + if ($projectid) $sql .= ' SET fk_project = '.$projectid; + else $sql .= ' SET fk_project = NULL'; + $sql .= ' WHERE rowid = '.$this->id; } elseif ($this->table_element == 'actioncomm') // Special case for actioncomm { - if ($projectid) $sql.= ' SET fk_project = '.$projectid; - else $sql.= ' SET fk_project = NULL'; - $sql.= ' WHERE id = '.$this->id; + if ($projectid) $sql .= ' SET fk_project = '.$projectid; + else $sql .= ' SET fk_project = NULL'; + $sql .= ' WHERE id = '.$this->id; } else // Special case for old architecture objects { - if ($projectid) $sql.= ' SET fk_projet = '.$projectid; - else $sql.= ' SET fk_projet = NULL'; - $sql.= ' WHERE rowid = '.$this->id; + if ($projectid) $sql .= ' SET fk_projet = '.$projectid; + else $sql .= ' SET fk_projet = NULL'; + $sql .= ' WHERE rowid = '.$this->id; } dol_syslog(get_class($this)."::setProject", LOG_DEBUG); @@ -1956,14 +1962,14 @@ abstract class CommonObject else { dol_syslog(get_class($this).'::setPaymentMethods Erreur '.$sql.' - '.$this->db->error()); - $this->error=$this->db->error(); + $this->error = $this->db->error(); return -1; } } else { dol_syslog(get_class($this).'::setPaymentMethods, status of the object is incompatible'); - $this->error='Status of the object is incompatible '.$this->statut; + $this->error = 'Status of the object is incompatible '.$this->statut; return -2; } } @@ -1997,14 +2003,14 @@ abstract class CommonObject else { dol_syslog(get_class($this).'::setMulticurrencyCode Erreur '.$sql.' - '.$this->db->error()); - $this->error=$this->db->error(); + $this->error = $this->db->error(); return -1; } } else { dol_syslog(get_class($this).'::setMulticurrencyCode, status of the object is incompatible'); - $this->error='Status of the object is incompatible '.$this->statut; + $this->error = 'Status of the object is incompatible '.$this->statut; return -2; } } @@ -2037,12 +2043,12 @@ abstract class CommonObject foreach ($this->lines as &$line) { // Amounts in company currency will be recalculated - if($mode == 1) { + if ($mode == 1) { $line->subprice = 0; } // Amounts in foreign currency will be recalculated - if($mode == 2) { + if ($mode == 2) { $line->multicurrency_subprice = 0; } @@ -2050,14 +2056,14 @@ abstract class CommonObject case 'propal': $this->updateline( $line->id, $line->subprice, $line->qty, $line->remise_percent, $line->tva_tx, $line->localtax1_tx, $line->localtax2_tx, - ($line->description?$line->description:$line->desc), 'HT', $line->info_bits, $line->special_code, $line->fk_parent_line, + ($line->description ? $line->description : $line->desc), 'HT', $line->info_bits, $line->special_code, $line->fk_parent_line, $line->skip_update_total, $line->fk_fournprice, $line->pa_ht, $line->label, $line->product_type, $line->date_start, $line->date_end, $line->array_options, $line->fk_unit, $line->multicurrency_subprice ); break; case 'commande': $this->updateline( - $line->id, ($line->description?$line->description:$line->desc), $line->subprice, $line->qty, $line->remise_percent, + $line->id, ($line->description ? $line->description : $line->desc), $line->subprice, $line->qty, $line->remise_percent, $line->tva_tx, $line->localtax1_tx, $line->localtax2_tx, 'HT', $line->info_bits, $line->date_start, $line->date_end, $line->product_type, $line->fk_parent_line, $line->skip_update_total, $line->fk_fournprice, $line->pa_ht, $line->label, $line->special_code, $line->array_options, $line->fk_unit, $line->multicurrency_subprice @@ -2065,7 +2071,7 @@ abstract class CommonObject break; case 'facture': $this->updateline( - $line->id, ($line->description?$line->description:$line->desc), $line->subprice, $line->qty, $line->remise_percent, + $line->id, ($line->description ? $line->description : $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, $line->skip_update_total, $line->fk_fournprice, $line->pa_ht, $line->label, $line->special_code, $line->array_options, $line->situation_percent, $line->fk_unit, $line->multicurrency_subprice @@ -2074,21 +2080,21 @@ abstract class CommonObject case 'supplier_proposal': $this->updateline( $line->id, $line->subprice, $line->qty, $line->remise_percent, $line->tva_tx, $line->localtax1_tx, $line->localtax2_tx, - ($line->description?$line->description:$line->desc), 'HT', $line->info_bits, $line->special_code, $line->fk_parent_line, + ($line->description ? $line->description : $line->desc), 'HT', $line->info_bits, $line->special_code, $line->fk_parent_line, $line->skip_update_total, $line->fk_fournprice, $line->pa_ht, $line->label, $line->product_type, $line->array_options, $line->ref_fourn, $line->multicurrency_subprice ); break; case 'order_supplier': $this->updateline( - $line->id, ($line->description?$line->description:$line->desc), $line->subprice, $line->qty, $line->remise_percent, + $line->id, ($line->description ? $line->description : $line->desc), $line->subprice, $line->qty, $line->remise_percent, $line->tva_tx, $line->localtax1_tx, $line->localtax2_tx, 'HT', $line->info_bits, $line->product_type, false, $line->date_start, $line->date_end, $line->array_options, $line->fk_unit, $line->multicurrency_subprice ); break; case 'invoice_supplier': $this->updateline( - $line->id, ($line->description?$line->description:$line->desc), $line->subprice, $line->tva_tx, $line->localtax1_tx, + $line->id, ($line->description ? $line->description : $line->desc), $line->subprice, $line->tva_tx, $line->localtax1_tx, $line->localtax2_tx, $line->qty, 0, 'HT', $line->info_bits, $line->product_type, $line->remise_percent, false, $line->date_start, $line->date_end, $line->array_options, $line->fk_unit, $line->multicurrency_subprice ); @@ -2105,14 +2111,14 @@ abstract class CommonObject else { dol_syslog(get_class($this).'::setMulticurrencyRate Erreur '.$sql.' - '.$this->db->error()); - $this->error=$this->db->error(); + $this->error = $this->db->error(); return -1; } } else { dol_syslog(get_class($this).'::setMulticurrencyRate, status of the object is incompatible'); - $this->error='Status of the object is incompatible '.$this->statut; + $this->error = 'Status of the object is incompatible '.$this->statut; return -2; } } @@ -2142,20 +2148,20 @@ abstract class CommonObject $this->cond_reglement_id = $id; // for supplier if (get_class($this) == 'Fournisseur') $this->cond_reglement_supplier_id = $id; - $this->cond_reglement = $id; // for compatibility + $this->cond_reglement = $id; // for compatibility return 1; } else { dol_syslog(get_class($this).'::setPaymentTerms Erreur '.$sql.' - '.$this->db->error()); - $this->error=$this->db->error(); + $this->error = $this->db->error(); return -1; } } else { dol_syslog(get_class($this).'::setPaymentTerms, status of the object is incompatible'); - $this->error='Status of the object is incompatible '.$this->statut; + $this->error = 'Status of the object is incompatible '.$this->statut; return -2; } } @@ -2186,14 +2192,14 @@ abstract class CommonObject else { dol_syslog(get_class($this).'::setRetainedWarrantyPaymentTerms Erreur '.$sql.' - '.$this->db->error()); - $this->error=$this->db->error(); + $this->error = $this->db->error(); return -1; } } else { dol_syslog(get_class($this).'::setRetainedWarrantyPaymentTerms, status of the object is incompatible'); - $this->error='Status of the object is incompatible '.$this->statut; + $this->error = 'Status of the object is incompatible '.$this->statut; return -2; } } @@ -2211,7 +2217,7 @@ abstract class CommonObject if ($this->element == 'delivery' || $this->element == 'shipping') $fieldname = 'fk_address'; $sql = "UPDATE ".MAIN_DB_PREFIX.$this->table_element." SET ".$fieldname." = ".$id; - $sql.= " WHERE rowid = ".$this->id." AND fk_statut = 0"; + $sql .= " WHERE rowid = ".$this->id." AND fk_statut = 0"; if ($this->db->query($sql)) { @@ -2220,7 +2226,7 @@ abstract class CommonObject } else { - $this->error=$this->db->error(); + $this->error = $this->db->error(); dol_syslog(get_class($this).'::setDeliveryAddress Erreur '.$sql.' - '.$this->error); return -1; } @@ -2240,25 +2246,25 @@ abstract class CommonObject { global $user; - if (empty($userused)) $userused=$user; + if (empty($userused)) $userused = $user; $error = 0; - if (! $this->table_element) { + if (!$this->table_element) { dol_syslog(get_class($this)."::setShippingMethod was called on objet with property table_element not defined", LOG_ERR); return -1; } $this->db->begin(); - if ($shipping_method_id<0) $shipping_method_id='NULL'; + if ($shipping_method_id < 0) $shipping_method_id = 'NULL'; dol_syslog(get_class($this).'::setShippingMethod('.$shipping_method_id.')'); $sql = "UPDATE ".MAIN_DB_PREFIX.$this->table_element; - $sql.= " SET fk_shipping_method = ".$shipping_method_id; - $sql.= " WHERE rowid=".$this->id; + $sql .= " SET fk_shipping_method = ".$shipping_method_id; + $sql .= " WHERE rowid=".$this->id; $resql = $this->db->query($sql); - if (! $resql) { + if (!$resql) { dol_syslog(get_class($this).'::setShippingMethod Error ', LOG_DEBUG); $this->error = $this->db->lasterror(); $error++; @@ -2266,8 +2272,8 @@ abstract class CommonObject if (!$notrigger) { // Call trigger - $this->context=array('shippingmethodupdate'=>1); - $result = $this->call_trigger(strtoupper(get_class($this)) . '_MODIFY', $userused); + $this->context = array('shippingmethodupdate'=>1); + $result = $this->call_trigger(strtoupper(get_class($this)).'_MODIFY', $userused); if ($result < 0) $error++; // End call trigger } @@ -2277,7 +2283,7 @@ abstract class CommonObject $this->db->rollback(); return -1; } else { - $this->shipping_method_id = ($shipping_method_id=='NULL')?null:$shipping_method_id; + $this->shipping_method_id = ($shipping_method_id == 'NULL') ?null:$shipping_method_id; $this->db->commit(); return 1; } @@ -2292,23 +2298,23 @@ abstract class CommonObject */ public function setWarehouse($warehouse_id) { - if (! $this->table_element) { + if (!$this->table_element) { dol_syslog(get_class($this)."::setWarehouse was called on objet with property table_element not defined", LOG_ERR); return -1; } - if ($warehouse_id<0) $warehouse_id='NULL'; + if ($warehouse_id < 0) $warehouse_id = 'NULL'; dol_syslog(get_class($this).'::setWarehouse('.$warehouse_id.')'); $sql = "UPDATE ".MAIN_DB_PREFIX.$this->table_element; - $sql.= " SET fk_warehouse = ".$warehouse_id; - $sql.= " WHERE rowid=".$this->id; + $sql .= " SET fk_warehouse = ".$warehouse_id; + $sql .= " WHERE rowid=".$this->id; if ($this->db->query($sql)) { - $this->warehouse_id = ($warehouse_id=='NULL')?null:$warehouse_id; + $this->warehouse_id = ($warehouse_id == 'NULL') ?null:$warehouse_id; return 1; } else { dol_syslog(get_class($this).'::setWarehouse Error ', LOG_DEBUG); - $this->error=$this->db->error(); + $this->error = $this->db->error(); return 0; } } @@ -2323,25 +2329,25 @@ abstract class CommonObject */ public function setDocModel($user, $modelpdf) { - if (! $this->table_element) + if (!$this->table_element) { dol_syslog(get_class($this)."::setDocModel was called on objet with property table_element not defined", LOG_ERR); return -1; } - $newmodelpdf=dol_trunc($modelpdf, 255); + $newmodelpdf = dol_trunc($modelpdf, 255); $sql = "UPDATE ".MAIN_DB_PREFIX.$this->table_element; - $sql.= " SET model_pdf = '".$this->db->escape($newmodelpdf)."'"; - $sql.= " WHERE rowid = ".$this->id; + $sql .= " SET model_pdf = '".$this->db->escape($newmodelpdf)."'"; + $sql .= " WHERE rowid = ".$this->id; // if ($this->element == 'facture') $sql.= " AND fk_statut < 2"; // if ($this->element == 'propal') $sql.= " AND fk_statut = 0"; dol_syslog(get_class($this)."::setDocModel", LOG_DEBUG); - $resql=$this->db->query($sql); + $resql = $this->db->query($sql); if ($resql) { - $this->modelpdf=$modelpdf; + $this->modelpdf = $modelpdf; return 1; } else @@ -2364,25 +2370,25 @@ abstract class CommonObject { global $user; - if (empty($userused)) $userused=$user; + if (empty($userused)) $userused = $user; $error = 0; - if (! $this->table_element) { + if (!$this->table_element) { dol_syslog(get_class($this)."::setBankAccount was called on objet with property table_element not defined", LOG_ERR); return -1; } $this->db->begin(); - if ($fk_account<0) $fk_account='NULL'; + if ($fk_account < 0) $fk_account = 'NULL'; dol_syslog(get_class($this).'::setBankAccount('.$fk_account.')'); $sql = "UPDATE ".MAIN_DB_PREFIX.$this->table_element; - $sql.= " SET fk_account = ".$fk_account; - $sql.= " WHERE rowid=".$this->id; + $sql .= " SET fk_account = ".$fk_account; + $sql .= " WHERE rowid=".$this->id; $resql = $this->db->query($sql); - if (! $resql) + if (!$resql) { dol_syslog(get_class($this).'::setBankAccount Error '.$sql.' - '.$this->db->error()); $this->error = $this->db->lasterror(); @@ -2393,8 +2399,8 @@ abstract class CommonObject if (!$notrigger) { // Call trigger - $this->context=array('bankaccountupdate'=>1); - $result = $this->call_trigger(strtoupper(get_class($this)) . '_MODIFY', $userused); + $this->context = array('bankaccountupdate'=>1); + $result = $this->call_trigger(strtoupper(get_class($this)).'_MODIFY', $userused); if ($result < 0) $error++; // End call trigger } @@ -2406,7 +2412,7 @@ abstract class CommonObject } else { - $this->fk_account = ($fk_account=='NULL')?null:$fk_account; + $this->fk_account = ($fk_account == 'NULL') ?null:$fk_account; $this->db->commit(); return 1; } @@ -2428,23 +2434,23 @@ abstract class CommonObject public function line_order($renum = false, $rowidorder = 'ASC', $fk_parent_line = true) { // phpcs:enable - if (! $this->table_element_line) + if (!$this->table_element_line) { dol_syslog(get_class($this)."::line_order was called on objet with property table_element_line not defined", LOG_ERR); return -1; } - if (! $this->fk_element) + if (!$this->fk_element) { dol_syslog(get_class($this)."::line_order was called on objet with property fk_element not defined", LOG_ERR); return -1; } // Count number of lines to reorder (according to choice $renum) - $nl=0; + $nl = 0; $sql = 'SELECT count(rowid) FROM '.MAIN_DB_PREFIX.$this->table_element_line; - $sql.= ' WHERE '.$this->fk_element.'='.$this->id; - if (! $renum) $sql.= ' AND rang = 0'; - if ($renum) $sql.= ' AND rang <> 0'; + $sql .= ' WHERE '.$this->fk_element.'='.$this->id; + if (!$renum) $sql .= ' AND rang = 0'; + if ($renum) $sql .= ' AND rang <> 0'; dol_syslog(get_class($this)."::line_order", LOG_DEBUG); $resql = $this->db->query($sql); @@ -2458,28 +2464,28 @@ abstract class CommonObject { // The goal of this part is to reorder all lines, with all children lines sharing the same // counter that parents. - $rows=array(); + $rows = array(); // We first search all lines that are parent lines (for multilevel details lines) $sql = 'SELECT rowid FROM '.MAIN_DB_PREFIX.$this->table_element_line; - $sql.= ' WHERE '.$this->fk_element.' = '.$this->id; - if ($fk_parent_line) $sql.= ' AND fk_parent_line IS NULL'; - $sql.= ' ORDER BY rang ASC, rowid '.$rowidorder; + $sql .= ' WHERE '.$this->fk_element.' = '.$this->id; + if ($fk_parent_line) $sql .= ' AND fk_parent_line IS NULL'; + $sql .= ' ORDER BY rang ASC, rowid '.$rowidorder; dol_syslog(get_class($this)."::line_order search all parent lines", LOG_DEBUG); $resql = $this->db->query($sql); if ($resql) { - $i=0; + $i = 0; $num = $this->db->num_rows($resql); while ($i < $num) { $row = $this->db->fetch_row($resql); - $rows[] = $row[0]; // Add parent line into array rows + $rows[] = $row[0]; // Add parent line into array rows $childrens = $this->getChildrenOfLine($row[0]); - if (! empty($childrens)) + if (!empty($childrens)) { - foreach($childrens as $child) + foreach ($childrens as $child) { array_push($rows, $child); } @@ -2488,11 +2494,11 @@ abstract class CommonObject } // Now we set a new number for each lines (parent and children with children included into parent tree) - if (! empty($rows)) + if (!empty($rows)) { - foreach($rows as $key => $row) + foreach ($rows as $key => $row) { - $this->updateRangOfLine($row, ($key+1)); + $this->updateRangOfLine($row, ($key + 1)); } } } @@ -2512,18 +2518,18 @@ abstract class CommonObject */ public function getChildrenOfLine($id) { - $rows=array(); + $rows = array(); $sql = 'SELECT rowid FROM '.MAIN_DB_PREFIX.$this->table_element_line; - $sql.= ' WHERE '.$this->fk_element.' = '.$this->id; - $sql.= ' AND fk_parent_line = '.$id; - $sql.= ' ORDER BY rang ASC'; + $sql .= ' WHERE '.$this->fk_element.' = '.$this->id; + $sql .= ' AND fk_parent_line = '.$id; + $sql .= ' ORDER BY rang ASC'; dol_syslog(get_class($this)."::getChildrenOfLine search children lines for line ".$id."", LOG_DEBUG); $resql = $this->db->query($sql); if ($resql) { - $i=0; + $i = 0; $num = $this->db->num_rows($resql); while ($i < $num) { @@ -2588,14 +2594,14 @@ abstract class CommonObject */ public function updateRangOfLine($rowid, $rang) { - $fieldposition = 'rang'; // @TODO Rename 'rang' into 'position' + $fieldposition = 'rang'; // @TODO Rename 'rang' into 'position' if (in_array($this->table_element_line, array('bom_bomline', 'ecm_files', 'emailcollector_emailcollectoraction'))) $fieldposition = 'position'; $sql = 'UPDATE '.MAIN_DB_PREFIX.$this->table_element_line.' SET '.$fieldposition.' = '.$rang; - $sql.= ' WHERE rowid = '.$rowid; + $sql .= ' WHERE rowid = '.$rowid; dol_syslog(get_class($this)."::updateRangOfLine", LOG_DEBUG); - if (! $this->db->query($sql)) + if (!$this->db->query($sql)) { dol_print_error($this->db); } @@ -2612,9 +2618,9 @@ abstract class CommonObject { // phpcs:enable $num = count($rows); - for ($i = 0 ; $i < $num ; $i++) + for ($i = 0; $i < $num; $i++) { - $this->updateRangOfLine($rows[$i], ($i+1)); + $this->updateRangOfLine($rows[$i], ($i + 1)); } } @@ -2632,14 +2638,14 @@ abstract class CommonObject $fieldposition = 'rang'; if (in_array($this->table_element_line, array('ecm_files', 'emailcollector_emailcollectoraction'))) $fieldposition = 'position'; - $sql = 'UPDATE '.MAIN_DB_PREFIX.$this->table_element_line.' SET '.$fieldposition.' = '.$rang ; - $sql.= ' WHERE '.$this->fk_element.' = '.$this->id; - $sql.= ' AND rang = '.($rang - 1); - if ($this->db->query($sql) ) + $sql = 'UPDATE '.MAIN_DB_PREFIX.$this->table_element_line.' SET '.$fieldposition.' = '.$rang; + $sql .= ' WHERE '.$this->fk_element.' = '.$this->id; + $sql .= ' AND rang = '.($rang - 1); + if ($this->db->query($sql)) { $sql = 'UPDATE '.MAIN_DB_PREFIX.$this->table_element_line.' SET '.$fieldposition.' = '.($rang - 1); - $sql.= ' WHERE rowid = '.$rowid; - if (! $this->db->query($sql) ) + $sql .= ' WHERE rowid = '.$rowid; + if (!$this->db->query($sql)) { dol_print_error($this->db); } @@ -2667,13 +2673,13 @@ abstract class CommonObject if (in_array($this->table_element_line, array('ecm_files', 'emailcollector_emailcollectoraction'))) $fieldposition = 'position'; $sql = 'UPDATE '.MAIN_DB_PREFIX.$this->table_element_line.' SET '.$fieldposition.' = '.$rang; - $sql.= ' WHERE '.$this->fk_element.' = '.$this->id; - $sql.= ' AND rang = '.($rang+1); - if ($this->db->query($sql) ) + $sql .= ' WHERE '.$this->fk_element.' = '.$this->id; + $sql .= ' AND rang = '.($rang + 1); + if ($this->db->query($sql)) { - $sql = 'UPDATE '.MAIN_DB_PREFIX.$this->table_element_line.' SET '.$fieldposition.' = '.($rang+1); - $sql.= ' WHERE rowid = '.$rowid; - if (! $this->db->query($sql) ) + $sql = 'UPDATE '.MAIN_DB_PREFIX.$this->table_element_line.' SET '.$fieldposition.' = '.($rang + 1); + $sql .= ' WHERE rowid = '.$rowid; + if (!$this->db->query($sql)) { dol_print_error($this->db); } @@ -2694,7 +2700,7 @@ abstract class CommonObject public function getRangOfLine($rowid) { $sql = 'SELECT rang FROM '.MAIN_DB_PREFIX.$this->table_element_line; - $sql.= ' WHERE rowid ='.$rowid; + $sql .= ' WHERE rowid ='.$rowid; dol_syslog(get_class($this)."::getRangOfLine", LOG_DEBUG); $resql = $this->db->query($sql); @@ -2714,8 +2720,8 @@ abstract class CommonObject public function getIdOfLine($rang) { $sql = 'SELECT rowid FROM '.MAIN_DB_PREFIX.$this->table_element_line; - $sql.= ' WHERE '.$this->fk_element.' = '.$this->id; - $sql.= ' AND rang = '.$rang; + $sql .= ' WHERE '.$this->fk_element.' = '.$this->id; + $sql .= ' AND rang = '.$rang; $resql = $this->db->query($sql); if ($resql) { @@ -2738,15 +2744,15 @@ abstract class CommonObject if ($fk_parent_line) { $sql = 'SELECT max(rang) FROM '.MAIN_DB_PREFIX.$this->table_element_line; - $sql.= ' WHERE '.$this->fk_element.' = '.$this->id; - $sql.= ' AND fk_parent_line = '.$fk_parent_line; + $sql .= ' WHERE '.$this->fk_element.' = '.$this->id; + $sql .= ' AND fk_parent_line = '.$fk_parent_line; dol_syslog(get_class($this)."::line_max", LOG_DEBUG); $resql = $this->db->query($sql); if ($resql) { $row = $this->db->fetch_row($resql); - if (! empty($row[0])) + if (!empty($row[0])) { return $row[0]; } @@ -2760,7 +2766,7 @@ abstract class CommonObject else { $sql = 'SELECT max(rang) FROM '.MAIN_DB_PREFIX.$this->table_element_line; - $sql.= ' WHERE '.$this->fk_element.' = '.$this->id; + $sql .= ' WHERE '.$this->fk_element.' = '.$this->id; dol_syslog(get_class($this)."::line_max", LOG_DEBUG); $resql = $this->db->query($sql); @@ -2782,15 +2788,15 @@ abstract class CommonObject public function update_ref_ext($ref_ext) { // phpcs:enable - if (! $this->table_element) + if (!$this->table_element) { dol_syslog(get_class($this)."::update_ref_ext was called on objet with property table_element not defined", LOG_ERR); return -1; } $sql = 'UPDATE '.MAIN_DB_PREFIX.$this->table_element; - $sql.= " SET ref_ext = '".$this->db->escape($ref_ext)."'"; - $sql.= " WHERE ".(isset($this->table_rowid)?$this->table_rowid:'rowid')." = ". $this->id; + $sql .= " SET ref_ext = '".$this->db->escape($ref_ext)."'"; + $sql .= " WHERE ".(isset($this->table_rowid) ? $this->table_rowid : 'rowid')." = ".$this->id; dol_syslog(get_class($this)."::update_ref_ext", LOG_DEBUG); if ($this->db->query($sql)) @@ -2800,7 +2806,7 @@ abstract class CommonObject } else { - $this->error=$this->db->error(); + $this->error = $this->db->error(); return -1; } } @@ -2818,26 +2824,26 @@ abstract class CommonObject // phpcs:enable global $user; - if (! $this->table_element) + if (!$this->table_element) { - $this->error='update_note was called on objet with property table_element not defined'; + $this->error = 'update_note was called on objet with property table_element not defined'; dol_syslog(get_class($this)."::update_note was called on objet with property table_element not defined", LOG_ERR); return -1; } - if (! in_array($suffix, array('','_public','_private'))) + if (!in_array($suffix, array('', '_public', '_private'))) { - $this->error='update_note Parameter suffix must be empty, \'_private\' or \'_public\''; + $this->error = 'update_note Parameter suffix must be empty, \'_private\' or \'_public\''; dol_syslog(get_class($this)."::update_note Parameter suffix must be empty, '_private' or '_public'", LOG_ERR); return -2; } // Special cas //var_dump($this->table_element);exit; - if ($this->table_element == 'product') $suffix=''; + if ($this->table_element == 'product') $suffix = ''; $sql = 'UPDATE '.MAIN_DB_PREFIX.$this->table_element; - $sql.= " SET note".$suffix." = ".(!empty($note)?("'".$this->db->escape($note)."'"):"NULL"); - $sql.= " ,".(in_array($this->table_element, array('actioncomm', 'adherent', 'advtargetemailing', 'cronjob', 'establishment'))?"fk_user_mod":"fk_user_modif")." = ".$user->id; - $sql.= " WHERE rowid =". $this->id; + $sql .= " SET note".$suffix." = ".(!empty($note) ? ("'".$this->db->escape($note)."'") : "NULL"); + $sql .= " ,".(in_array($this->table_element, array('actioncomm', 'adherent', 'advtargetemailing', 'cronjob', 'establishment')) ? "fk_user_mod" : "fk_user_modif")." = ".$user->id; + $sql .= " WHERE rowid =".$this->id; dol_syslog(get_class($this)."::update_note", LOG_DEBUG); if ($this->db->query($sql)) @@ -2846,14 +2852,14 @@ abstract class CommonObject elseif ($suffix == '_private') $this->note_private = $note; else { - $this->note = $note; // deprecated + $this->note = $note; // deprecated $this->note_private = $note; } return 1; } else { - $this->error=$this->db->lasterror(); + $this->error = $this->db->lasterror(); return -1; } } @@ -2904,8 +2910,8 @@ abstract class CommonObject elseif ($this->element == 'supplier_proposal') $MODULE = "MODULE_DISALLOW_UPDATE_PRICE_SUPPLIER_PROPOSAL"; - if (! empty($MODULE)) { - if (! empty($conf->global->$MODULE)) { + if (!empty($MODULE)) { + if (!empty($conf->global->$MODULE)) { $modsactivated = explode(',', $conf->global->$MODULE); foreach ($modsactivated as $mod) { if ($conf->$mod->enabled) @@ -2916,44 +2922,44 @@ abstract class CommonObject include_once DOL_DOCUMENT_ROOT.'/core/lib/price.lib.php'; - if ($roundingadjust == '-1') $roundingadjust='auto'; // For backward compatibility + if ($roundingadjust == '-1') $roundingadjust = 'auto'; // For backward compatibility - $forcedroundingmode=$roundingadjust; - if ($forcedroundingmode == 'auto' && isset($conf->global->MAIN_ROUNDOFTOTAL_NOT_TOTALOFROUND)) $forcedroundingmode=$conf->global->MAIN_ROUNDOFTOTAL_NOT_TOTALOFROUND; - elseif ($forcedroundingmode == 'auto') $forcedroundingmode='0'; + $forcedroundingmode = $roundingadjust; + if ($forcedroundingmode == 'auto' && isset($conf->global->MAIN_ROUNDOFTOTAL_NOT_TOTALOFROUND)) $forcedroundingmode = $conf->global->MAIN_ROUNDOFTOTAL_NOT_TOTALOFROUND; + elseif ($forcedroundingmode == 'auto') $forcedroundingmode = '0'; - $error=0; + $error = 0; $multicurrency_tx = !empty($this->multicurrency_tx) ? $this->multicurrency_tx : 1; // Define constants to find lines to sum - $fieldtva='total_tva'; - $fieldlocaltax1='total_localtax1'; - $fieldlocaltax2='total_localtax2'; - $fieldup='subprice'; + $fieldtva = 'total_tva'; + $fieldlocaltax1 = 'total_localtax1'; + $fieldlocaltax2 = 'total_localtax2'; + $fieldup = 'subprice'; if ($this->element == 'facture_fourn' || $this->element == 'invoice_supplier') { - $fieldtva='tva'; - $fieldup='pu_ht'; + $fieldtva = 'tva'; + $fieldup = 'pu_ht'; } if ($this->element == 'expensereport') { - $fieldup='value_unit'; + $fieldup = 'value_unit'; } $sql = 'SELECT rowid, qty, '.$fieldup.' as up, remise_percent, total_ht, '.$fieldtva.' as total_tva, total_ttc, '.$fieldlocaltax1.' as total_localtax1, '.$fieldlocaltax2.' as total_localtax2,'; - $sql.= ' tva_tx as vatrate, localtax1_tx, localtax2_tx, localtax1_type, localtax2_type, info_bits, product_type'; - if ($this->table_element_line == 'facturedet') $sql.= ', situation_percent'; - $sql.= ', multicurrency_total_ht, multicurrency_total_tva, multicurrency_total_ttc'; - $sql.= ' FROM '.MAIN_DB_PREFIX.$this->table_element_line; - $sql.= ' WHERE '.$this->fk_element.' = '.$this->id; + $sql .= ' tva_tx as vatrate, localtax1_tx, localtax2_tx, localtax1_type, localtax2_type, info_bits, product_type'; + if ($this->table_element_line == 'facturedet') $sql .= ', situation_percent'; + $sql .= ', multicurrency_total_ht, multicurrency_total_tva, multicurrency_total_ttc'; + $sql .= ' FROM '.MAIN_DB_PREFIX.$this->table_element_line; + $sql .= ' WHERE '.$this->fk_element.' = '.$this->id; if ($exclspec) { - $product_field='product_type'; - if ($this->table_element_line == 'contratdet') $product_field=''; // contratdet table has no product_type field - if ($product_field) $sql.= ' AND '.$product_field.' <> 9'; + $product_field = 'product_type'; + if ($this->table_element_line == 'contratdet') $product_field = ''; // contratdet table has no product_type field + if ($product_field) $sql .= ' AND '.$product_field.' <> 9'; } - $sql.= ' ORDER by rowid'; // We want to be sure to always use same order of line to not change lines differently when option MAIN_ROUNDOFTOTAL_NOT_TOTALOFROUND is used + $sql .= ' ORDER by rowid'; // We want to be sure to always use same order of line to not change lines differently when option MAIN_ROUNDOFTOTAL_NOT_TOTALOFROUND is used dol_syslog(get_class($this)."::update_price", LOG_DEBUG); $resql = $this->db->query($sql); @@ -2967,7 +2973,7 @@ abstract class CommonObject $total_ht_by_vats = array(); $total_tva_by_vats = array(); $total_ttc_by_vats = array(); - $this->multicurrency_total_ht = 0; + $this->multicurrency_total_ht = 0; $this->multicurrency_total_tva = 0; $this->multicurrency_total_ttc = 0; @@ -2978,54 +2984,54 @@ abstract class CommonObject $obj = $this->db->fetch_object($resql); // Note: There is no check on detail line and no check on total, if $forcedroundingmode = 'none' - $parameters=array('fk_element' => $obj->rowid); + $parameters = array('fk_element' => $obj->rowid); $reshook = $hookmanager->executeHooks('changeRoundingMode', $parameters, $this, $action); // Note that $action and $object may have been modified by some hooks if (empty($reshook) && $forcedroundingmode == '0') // Check if data on line are consistent. This may solve lines that were not consistent because set with $forcedroundingmode='auto' { - $localtax_array=array($obj->localtax1_type,$obj->localtax1_tx,$obj->localtax2_type,$obj->localtax2_tx); - $tmpcal=calcul_price_total($obj->qty, $obj->up, $obj->remise_percent, $obj->vatrate, $obj->localtax1_tx, $obj->localtax2_tx, 0, 'HT', $obj->info_bits, $obj->product_type, $seller, $localtax_array, (isset($obj->situation_percent) ? $obj->situation_percent : 100), $multicurrency_tx); - $diff=price2num($tmpcal[1] - $obj->total_tva, 'MT', 1); + $localtax_array = array($obj->localtax1_type, $obj->localtax1_tx, $obj->localtax2_type, $obj->localtax2_tx); + $tmpcal = calcul_price_total($obj->qty, $obj->up, $obj->remise_percent, $obj->vatrate, $obj->localtax1_tx, $obj->localtax2_tx, 0, 'HT', $obj->info_bits, $obj->product_type, $seller, $localtax_array, (isset($obj->situation_percent) ? $obj->situation_percent : 100), $multicurrency_tx); + $diff = price2num($tmpcal[1] - $obj->total_tva, 'MT', 1); if ($diff) { - $sqlfix="UPDATE ".MAIN_DB_PREFIX.$this->table_element_line." SET ".$fieldtva." = ".$tmpcal[1].", total_ttc = ".$tmpcal[2]." WHERE rowid = ".$obj->rowid; + $sqlfix = "UPDATE ".MAIN_DB_PREFIX.$this->table_element_line." SET ".$fieldtva." = ".$tmpcal[1].", total_ttc = ".$tmpcal[2]." WHERE rowid = ".$obj->rowid; dol_syslog('We found unconsistent data into detailed line (difference of '.$diff.') for line rowid = '.$obj->rowid." (total vat of line calculated=".$tmpcal[1].", database=".$obj->total_tva."). We fix the total_vat and total_ttc of line by running sqlfix = ".$sqlfix); - $resqlfix=$this->db->query($sqlfix); - if (! $resqlfix) dol_print_error($this->db, 'Failed to update line'); + $resqlfix = $this->db->query($sqlfix); + if (!$resqlfix) dol_print_error($this->db, 'Failed to update line'); $obj->total_tva = $tmpcal[1]; $obj->total_ttc = $tmpcal[2]; // } } - $this->total_ht += $obj->total_ht; // The field visible at end of line detail + $this->total_ht += $obj->total_ht; // The field visible at end of line detail $this->total_tva += $obj->total_tva; $this->total_localtax1 += $obj->total_localtax1; $this->total_localtax2 += $obj->total_localtax2; $this->total_ttc += $obj->total_ttc; - $this->multicurrency_total_ht += $obj->multicurrency_total_ht; // The field visible at end of line detail + $this->multicurrency_total_ht += $obj->multicurrency_total_ht; // The field visible at end of line detail $this->multicurrency_total_tva += $obj->multicurrency_total_tva; $this->multicurrency_total_ttc += $obj->multicurrency_total_ttc; - if (! isset($total_ht_by_vats[$obj->vatrate])) $total_ht_by_vats[$obj->vatrate]=0; - if (! isset($total_tva_by_vats[$obj->vatrate])) $total_tva_by_vats[$obj->vatrate]=0; - if (! isset($total_ttc_by_vats[$obj->vatrate])) $total_ttc_by_vats[$obj->vatrate]=0; + if (!isset($total_ht_by_vats[$obj->vatrate])) $total_ht_by_vats[$obj->vatrate] = 0; + if (!isset($total_tva_by_vats[$obj->vatrate])) $total_tva_by_vats[$obj->vatrate] = 0; + if (!isset($total_ttc_by_vats[$obj->vatrate])) $total_ttc_by_vats[$obj->vatrate] = 0; $total_ht_by_vats[$obj->vatrate] += $obj->total_ht; $total_tva_by_vats[$obj->vatrate] += $obj->total_tva; $total_ttc_by_vats[$obj->vatrate] += $obj->total_ttc; if ($forcedroundingmode == '1') // Check if we need adjustement onto line for vat. TODO This works on the company currency but not on multicurrency { - $tmpvat=price2num($total_ht_by_vats[$obj->vatrate] * $obj->vatrate / 100, 'MT', 1); - $diff=price2num($total_tva_by_vats[$obj->vatrate]-$tmpvat, 'MT', 1); + $tmpvat = price2num($total_ht_by_vats[$obj->vatrate] * $obj->vatrate / 100, 'MT', 1); + $diff = price2num($total_tva_by_vats[$obj->vatrate] - $tmpvat, 'MT', 1); //print 'Line '.$i.' rowid='.$obj->rowid.' vat_rate='.$obj->vatrate.' total_ht='.$obj->total_ht.' total_tva='.$obj->total_tva.' total_ttc='.$obj->total_ttc.' total_ht_by_vats='.$total_ht_by_vats[$obj->vatrate].' total_tva_by_vats='.$total_tva_by_vats[$obj->vatrate].' (new calculation = '.$tmpvat.') total_ttc_by_vats='.$total_ttc_by_vats[$obj->vatrate].($diff?" => DIFF":"")."
    \n"; if ($diff) { if (abs($diff) > 0.1) { dol_syslog('A rounding difference was detected into TOTAL but is too high to be corrected', LOG_WARNING); exit; } - $sqlfix="UPDATE ".MAIN_DB_PREFIX.$this->table_element_line." SET ".$fieldtva." = ".($obj->total_tva - $diff).", total_ttc = ".($obj->total_ttc - $diff)." WHERE rowid = ".$obj->rowid; + $sqlfix = "UPDATE ".MAIN_DB_PREFIX.$this->table_element_line." SET ".$fieldtva." = ".($obj->total_tva - $diff).", total_ttc = ".($obj->total_ttc - $diff)." WHERE rowid = ".$obj->rowid; dol_syslog('We found a difference of '.$diff.' for line rowid = '.$obj->rowid.". We fix the total_vat and total_ttc of line by running sqlfix = ".$sqlfix); - $resqlfix=$this->db->query($sqlfix); - if (! $resqlfix) dol_print_error($this->db, 'Failed to update line'); + $resqlfix = $this->db->query($sqlfix); + if (!$resqlfix) dol_print_error($this->db, 'Failed to update line'); $this->total_tva -= $diff; $this->total_ttc -= $diff; $total_tva_by_vats[$obj->vatrate] -= $diff; @@ -3037,11 +3043,11 @@ abstract class CommonObject } // Add revenue stamp to total - $this->total_ttc += isset($this->revenuestamp)?$this->revenuestamp:0; - $this->multicurrency_total_ttc += isset($this->revenuestamp)?($this->revenuestamp * $multicurrency_tx):0; + $this->total_ttc += isset($this->revenuestamp) ? $this->revenuestamp : 0; + $this->multicurrency_total_ttc += isset($this->revenuestamp) ? ($this->revenuestamp * $multicurrency_tx) : 0; // Situations totals - if ($this->situation_cycle_ref && $this->situation_counter > 1 && method_exists($this, 'get_prev_sits') && $this->type != $this::TYPE_CREDIT_NOTE ) + if ($this->situation_cycle_ref && $this->situation_counter > 1 && method_exists($this, 'get_prev_sits') && $this->type != $this::TYPE_CREDIT_NOTE) { $prev_sits = $this->get_prev_sits(); @@ -3060,17 +3066,17 @@ abstract class CommonObject $this->db->free($resql); // Now update global field total_ht, total_ttc and tva - $fieldht='total_ht'; - $fieldtva='tva'; - $fieldlocaltax1='localtax1'; - $fieldlocaltax2='localtax2'; - $fieldttc='total_ttc'; + $fieldht = 'total_ht'; + $fieldtva = 'tva'; + $fieldlocaltax1 = 'localtax1'; + $fieldlocaltax2 = 'localtax2'; + $fieldttc = 'total_ttc'; // Specific code for backward compatibility with old field names - if ($this->element == 'facture' || $this->element == 'facturerec') $fieldht='total'; - if ($this->element == 'facture_fourn' || $this->element == 'invoice_supplier') $fieldtva='total_tva'; - if ($this->element == 'propal') $fieldttc='total'; - if ($this->element == 'expensereport') $fieldtva='total_tva'; - if ($this->element == 'supplier_proposal') $fieldttc='total'; + if ($this->element == 'facture' || $this->element == 'facturerec') $fieldht = 'total'; + if ($this->element == 'facture_fourn' || $this->element == 'invoice_supplier') $fieldtva = 'total_tva'; + if ($this->element == 'propal') $fieldttc = 'total'; + if ($this->element == 'expensereport') $fieldtva = 'total_tva'; + if ($this->element == 'supplier_proposal') $fieldttc = 'total'; if (empty($nodatabaseupdate)) { @@ -3087,16 +3093,16 @@ abstract class CommonObject dol_syslog(get_class($this)."::update_price", LOG_DEBUG); - $resql=$this->db->query($sql); - if (! $resql) + $resql = $this->db->query($sql); + if (!$resql) { $error++; - $this->error=$this->db->lasterror(); - $this->errors[]=$this->db->lasterror(); + $this->error = $this->db->lasterror(); + $this->errors[] = $this->db->lasterror(); } } - if (! $error) + if (!$error) { return 1; } @@ -3124,27 +3130,27 @@ abstract class CommonObject public function add_object_linked($origin = null, $origin_id = null) { // phpcs:enable - $origin = (! empty($origin) ? $origin : $this->origin); - $origin_id = (! empty($origin_id) ? $origin_id : $this->origin_id); + $origin = (!empty($origin) ? $origin : $this->origin); + $origin_id = (!empty($origin_id) ? $origin_id : $this->origin_id); // Special case - if ($origin == 'order') $origin='commande'; - if ($origin == 'invoice') $origin='facture'; - if ($origin == 'invoice_template') $origin='facturerec'; - if ($origin == 'supplierorder') $origin='order_supplier'; + if ($origin == 'order') $origin = 'commande'; + if ($origin == 'invoice') $origin = 'facture'; + if ($origin == 'invoice_template') $origin = 'facturerec'; + if ($origin == 'supplierorder') $origin = 'order_supplier'; $this->db->begin(); $sql = "INSERT INTO ".MAIN_DB_PREFIX."element_element ("; - $sql.= "fk_source"; - $sql.= ", sourcetype"; - $sql.= ", fk_target"; - $sql.= ", targettype"; - $sql.= ") VALUES ("; - $sql.= $origin_id; - $sql.= ", '".$this->db->escape($origin)."'"; - $sql.= ", ".$this->id; - $sql.= ", '".$this->db->escape($this->element)."'"; - $sql.= ")"; + $sql .= "fk_source"; + $sql .= ", sourcetype"; + $sql .= ", fk_target"; + $sql .= ", targettype"; + $sql .= ") VALUES ("; + $sql .= $origin_id; + $sql .= ", '".$this->db->escape($origin)."'"; + $sql .= ", ".$this->id; + $sql .= ", '".$this->db->escape($this->element)."'"; + $sql .= ")"; dol_syslog(get_class($this)."::add_object_linked", LOG_DEBUG); if ($this->db->query($sql)) @@ -3154,7 +3160,7 @@ abstract class CommonObject } else { - $this->error=$this->db->lasterror(); + $this->error = $this->db->lasterror(); $this->db->rollback(); return 0; } @@ -3186,29 +3192,29 @@ abstract class CommonObject { global $conf; - $this->linkedObjectsIds=array(); - $this->linkedObjects=array(); + $this->linkedObjectsIds = array(); + $this->linkedObjects = array(); - $justsource=false; - $justtarget=false; - $withtargettype=false; - $withsourcetype=false; + $justsource = false; + $justtarget = false; + $withtargettype = false; + $withsourcetype = false; - if (! empty($sourceid) && ! empty($sourcetype) && empty($targetid)) + if (!empty($sourceid) && !empty($sourcetype) && empty($targetid)) { - $justsource=true; // the source (id and type) is a search criteria - if (! empty($targettype)) $withtargettype=true; + $justsource = true; // the source (id and type) is a search criteria + if (!empty($targettype)) $withtargettype = true; } - if (! empty($targetid) && ! empty($targettype) && empty($sourceid)) + if (!empty($targetid) && !empty($targettype) && empty($sourceid)) { - $justtarget=true; // the target (id and type) is a search criteria - if (! empty($sourcetype)) $withsourcetype=true; + $justtarget = true; // the target (id and type) is a search criteria + if (!empty($sourcetype)) $withsourcetype = true; } - $sourceid = (! empty($sourceid) ? $sourceid : $this->id); - $targetid = (! empty($targetid) ? $targetid : $this->id); - $sourcetype = (! empty($sourcetype) ? $sourcetype : $this->element); - $targettype = (! empty($targettype) ? $targettype : $this->element); + $sourceid = (!empty($sourceid) ? $sourceid : $this->id); + $targetid = (!empty($targetid) ? $targetid : $this->id); + $sourcetype = (!empty($sourcetype) ? $sourcetype : $this->element); + $targettype = (!empty($targettype) ? $targettype : $this->element); /*if (empty($sourceid) && empty($targetid)) { @@ -3218,25 +3224,25 @@ abstract class CommonObject // Links between objects are stored in table element_element $sql = 'SELECT rowid, fk_source, sourcetype, fk_target, targettype'; - $sql.= ' FROM '.MAIN_DB_PREFIX.'element_element'; - $sql.= " WHERE "; + $sql .= ' FROM '.MAIN_DB_PREFIX.'element_element'; + $sql .= " WHERE "; if ($justsource || $justtarget) { if ($justsource) { - $sql.= "fk_source = ".$sourceid." AND sourcetype = '".$sourcetype."'"; - if ($withtargettype) $sql.= " AND targettype = '".$targettype."'"; + $sql .= "fk_source = ".$sourceid." AND sourcetype = '".$sourcetype."'"; + if ($withtargettype) $sql .= " AND targettype = '".$targettype."'"; } elseif ($justtarget) { - $sql.= "fk_target = ".$targetid." AND targettype = '".$targettype."'"; - if ($withsourcetype) $sql.= " AND sourcetype = '".$sourcetype."'"; + $sql .= "fk_target = ".$targetid." AND targettype = '".$targettype."'"; + if ($withsourcetype) $sql .= " AND sourcetype = '".$sourcetype."'"; } } else { - $sql.= "(fk_source = ".$sourceid." AND sourcetype = '".$sourcetype."')"; - $sql.= " ".$clause." (fk_target = ".$targetid." AND targettype = '".$targettype."')"; + $sql .= "(fk_source = ".$sourceid." AND sourcetype = '".$sourcetype."')"; + $sql .= " ".$clause." (fk_target = ".$targetid." AND targettype = '".$targettype."')"; } $sql .= ' ORDER BY '.$orderby; @@ -3253,31 +3259,31 @@ abstract class CommonObject { if ($justsource) { - $this->linkedObjectsIds[$obj->targettype][$obj->rowid]=$obj->fk_target; + $this->linkedObjectsIds[$obj->targettype][$obj->rowid] = $obj->fk_target; } elseif ($justtarget) { - $this->linkedObjectsIds[$obj->sourcetype][$obj->rowid]=$obj->fk_source; + $this->linkedObjectsIds[$obj->sourcetype][$obj->rowid] = $obj->fk_source; } } else { if ($obj->fk_source == $sourceid && $obj->sourcetype == $sourcetype) { - $this->linkedObjectsIds[$obj->targettype][$obj->rowid]=$obj->fk_target; + $this->linkedObjectsIds[$obj->targettype][$obj->rowid] = $obj->fk_target; } if ($obj->fk_target == $targetid && $obj->targettype == $targettype) { - $this->linkedObjectsIds[$obj->sourcetype][$obj->rowid]=$obj->fk_source; + $this->linkedObjectsIds[$obj->sourcetype][$obj->rowid] = $obj->fk_source; } } $i++; } - if (! empty($this->linkedObjectsIds)) + if (!empty($this->linkedObjectsIds)) { $tmparray = $this->linkedObjectsIds; - foreach($tmparray as $objecttype => $objectids) // $objecttype is a module name ('facture', 'mymodule', ...) or a module name with a suffix ('project_task', 'mymodule_myobj', ...) + foreach ($tmparray as $objecttype => $objectids) // $objecttype is a module name ('facture', 'mymodule', ...) or a module name with a suffix ('project_task', 'mymodule_myobj', ...) { // Parse element/subelement (ex: project_task, cabinetmed_consultation, ...) $module = $element = $subelement = $objecttype; @@ -3290,31 +3296,31 @@ abstract class CommonObject $classpath = $element.'/class'; // To work with non standard classpath or module name - if ($objecttype == 'facture') { + if ($objecttype == 'facture') { $classpath = 'compta/facture/class'; } - elseif ($objecttype == 'facturerec') { + elseif ($objecttype == 'facturerec') { $classpath = 'compta/facture/class'; $module = 'facture'; } - elseif ($objecttype == 'propal') { + elseif ($objecttype == 'propal') { $classpath = 'comm/propal/class'; } - elseif ($objecttype == 'supplier_proposal') { + elseif ($objecttype == 'supplier_proposal') { $classpath = 'supplier_proposal/class'; } - elseif ($objecttype == 'shipping') { + elseif ($objecttype == 'shipping') { $classpath = 'expedition/class'; $subelement = 'expedition'; $module = 'expedition_bon'; } - elseif ($objecttype == 'delivery') { + elseif ($objecttype == 'delivery') { $classpath = 'livraison/class'; $subelement = 'livraison'; $module = 'livraison_bon'; } - elseif ($objecttype == 'invoice_supplier' || $objecttype == 'order_supplier') { + elseif ($objecttype == 'invoice_supplier' || $objecttype == 'order_supplier') { $classpath = 'fourn/class'; $module = 'fournisseur'; } - elseif ($objecttype == 'fichinter') { + elseif ($objecttype == 'fichinter') { $classpath = 'fichinter/class'; $subelement = 'fichinter'; $module = 'ficheinter'; } - elseif ($objecttype == 'subscription') { + elseif ($objecttype == 'subscription') { $classpath = 'adherents/class'; $module = 'adherent'; } @@ -3327,16 +3333,16 @@ abstract class CommonObject elseif ($objecttype == 'invoice_supplier') { $classfile = 'fournisseur.facture'; $classname = 'FactureFournisseur'; } - elseif ($objecttype == 'order_supplier') { + elseif ($objecttype == 'order_supplier') { $classfile = 'fournisseur.commande'; $classname = 'CommandeFournisseur'; } - elseif ($objecttype == 'supplier_proposal') { + elseif ($objecttype == 'supplier_proposal') { $classfile = 'supplier_proposal'; $classname = 'SupplierProposal'; } - elseif ($objecttype == 'facturerec') { + elseif ($objecttype == 'facturerec') { $classfile = 'facture-rec'; $classname = 'FactureRec'; } - elseif ($objecttype == 'subscription') { + elseif ($objecttype == 'subscription') { $classfile = 'subscription'; $classname = 'Subscription'; } @@ -3349,7 +3355,7 @@ abstract class CommonObject //print '/'.$classpath.'/'.$classfile.'.class.php '.class_exists($classname); if (class_exists($classname)) { - foreach($objectids as $i => $objectid) // $i is rowid into llx_element_element + foreach ($objectids as $i => $objectid) // $i is rowid into llx_element_element { $object = new $classname($this->db); $ret = $object->fetch($objectid); @@ -3388,26 +3394,26 @@ abstract class CommonObject */ public function updateObjectLinked($sourceid = null, $sourcetype = '', $targetid = null, $targettype = '') { - $updatesource=false; - $updatetarget=false; + $updatesource = false; + $updatetarget = false; - if (! empty($sourceid) && ! empty($sourcetype) && empty($targetid) && empty($targettype)) $updatesource=true; - elseif (empty($sourceid) && empty($sourcetype) && ! empty($targetid) && ! empty($targettype)) $updatetarget=true; + if (!empty($sourceid) && !empty($sourcetype) && empty($targetid) && empty($targettype)) $updatesource = true; + elseif (empty($sourceid) && empty($sourcetype) && !empty($targetid) && !empty($targettype)) $updatetarget = true; $sql = "UPDATE ".MAIN_DB_PREFIX."element_element SET "; if ($updatesource) { - $sql.= "fk_source = ".$sourceid; - $sql.= ", sourcetype = '".$this->db->escape($sourcetype)."'"; - $sql.= " WHERE fk_target = ".$this->id; - $sql.= " AND targettype = '".$this->db->escape($this->element)."'"; + $sql .= "fk_source = ".$sourceid; + $sql .= ", sourcetype = '".$this->db->escape($sourcetype)."'"; + $sql .= " WHERE fk_target = ".$this->id; + $sql .= " AND targettype = '".$this->db->escape($this->element)."'"; } elseif ($updatetarget) { - $sql.= "fk_target = ".$targetid; - $sql.= ", targettype = '".$this->db->escape($targettype)."'"; - $sql.= " WHERE fk_source = ".$this->id; - $sql.= " AND sourcetype = '".$this->db->escape($this->element)."'"; + $sql .= "fk_target = ".$targetid; + $sql .= ", targettype = '".$this->db->escape($targettype)."'"; + $sql .= " WHERE fk_source = ".$this->id; + $sql .= " AND sourcetype = '".$this->db->escape($this->element)."'"; } dol_syslog(get_class($this)."::updateObjectLinked", LOG_DEBUG); @@ -3417,7 +3423,7 @@ abstract class CommonObject } else { - $this->error=$this->db->lasterror(); + $this->error = $this->db->lasterror(); return -1; } } @@ -3435,40 +3441,40 @@ abstract class CommonObject */ public function deleteObjectLinked($sourceid = null, $sourcetype = '', $targetid = null, $targettype = '', $rowid = '') { - $deletesource=false; - $deletetarget=false; + $deletesource = false; + $deletetarget = false; - if (! empty($sourceid) && ! empty($sourcetype) && empty($targetid) && empty($targettype)) $deletesource=true; - elseif (empty($sourceid) && empty($sourcetype) && ! empty($targetid) && ! empty($targettype)) $deletetarget=true; + if (!empty($sourceid) && !empty($sourcetype) && empty($targetid) && empty($targettype)) $deletesource = true; + elseif (empty($sourceid) && empty($sourcetype) && !empty($targetid) && !empty($targettype)) $deletetarget = true; - $sourceid = (! empty($sourceid) ? $sourceid : $this->id); - $sourcetype = (! empty($sourcetype) ? $sourcetype : $this->element); - $targetid = (! empty($targetid) ? $targetid : $this->id); - $targettype = (! empty($targettype) ? $targettype : $this->element); + $sourceid = (!empty($sourceid) ? $sourceid : $this->id); + $sourcetype = (!empty($sourcetype) ? $sourcetype : $this->element); + $targetid = (!empty($targetid) ? $targetid : $this->id); + $targettype = (!empty($targettype) ? $targettype : $this->element); $sql = "DELETE FROM ".MAIN_DB_PREFIX."element_element"; - $sql.= " WHERE"; + $sql .= " WHERE"; if ($rowid > 0) { - $sql.=" rowid = ".$rowid; + $sql .= " rowid = ".$rowid; } else { if ($deletesource) { - $sql.= " fk_source = ".$sourceid." AND sourcetype = '".$this->db->escape($sourcetype)."'"; - $sql.= " AND fk_target = ".$this->id." AND targettype = '".$this->db->escape($this->element)."'"; + $sql .= " fk_source = ".$sourceid." AND sourcetype = '".$this->db->escape($sourcetype)."'"; + $sql .= " AND fk_target = ".$this->id." AND targettype = '".$this->db->escape($this->element)."'"; } elseif ($deletetarget) { - $sql.= " fk_target = ".$targetid." AND targettype = '".$this->db->escape($targettype)."'"; - $sql.= " AND fk_source = ".$this->id." AND sourcetype = '".$this->db->escape($this->element)."'"; + $sql .= " fk_target = ".$targetid." AND targettype = '".$this->db->escape($targettype)."'"; + $sql .= " AND fk_source = ".$this->id." AND sourcetype = '".$this->db->escape($this->element)."'"; } else { - $sql.= " (fk_source = ".$this->id." AND sourcetype = '".$this->db->escape($this->element)."')"; - $sql.= " OR"; - $sql.= " (fk_target = ".$this->id." AND targettype = '".$this->db->escape($this->element)."')"; + $sql .= " (fk_source = ".$this->id." AND sourcetype = '".$this->db->escape($this->element)."')"; + $sql .= " OR"; + $sql .= " (fk_target = ".$this->id." AND targettype = '".$this->db->escape($this->element)."')"; } } @@ -3479,8 +3485,8 @@ abstract class CommonObject } else { - $this->error=$this->db->lasterror(); - $this->errors[]=$this->error; + $this->error = $this->db->lasterror(); + $this->errors[] = $this->error; return -1; } } @@ -3496,28 +3502,28 @@ abstract class CommonObject */ public function setStatut($status, $elementId = null, $elementType = '', $trigkey = '') { - global $user,$langs,$conf; + global $user, $langs, $conf; - $savElementId=$elementId; // To be used later to know if we were using the method using the id of this or not. + $savElementId = $elementId; // To be used later to know if we were using the method using the id of this or not. - $elementId = (!empty($elementId)?$elementId:$this->id); - $elementTable = (!empty($elementType)?$elementType:$this->table_element); + $elementId = (!empty($elementId) ? $elementId : $this->id); + $elementTable = (!empty($elementType) ? $elementType : $this->table_element); $this->db->begin(); - $fieldstatus="fk_statut"; - if ($elementTable == 'facture_rec') $fieldstatus="suspended"; - if ($elementTable == 'mailing') $fieldstatus="statut"; - if ($elementTable == 'cronjob') $fieldstatus="status"; - if ($elementTable == 'user') $fieldstatus="statut"; - if ($elementTable == 'expensereport') $fieldstatus="fk_statut"; - if ($elementTable == 'commande_fournisseur_dispatch') $fieldstatus="status"; + $fieldstatus = "fk_statut"; + if ($elementTable == 'facture_rec') $fieldstatus = "suspended"; + if ($elementTable == 'mailing') $fieldstatus = "statut"; + if ($elementTable == 'cronjob') $fieldstatus = "status"; + if ($elementTable == 'user') $fieldstatus = "statut"; + if ($elementTable == 'expensereport') $fieldstatus = "fk_statut"; + if ($elementTable == 'commande_fournisseur_dispatch') $fieldstatus = "status"; $sql = "UPDATE ".MAIN_DB_PREFIX.$elementTable; - $sql.= " SET ".$fieldstatus." = ".$status; + $sql .= " SET ".$fieldstatus." = ".$status; // If status = 1 = validated, update also fk_user_valid - if ($status == 1 && $elementTable == 'expensereport') $sql.=", fk_user_valid = ".$user->id; - $sql.= " WHERE rowid=".$elementId; + if ($status == 1 && $elementTable == 'expensereport') $sql .= ", fk_user_valid = ".$user->id; + $sql .= " WHERE rowid=".$elementId; dol_syslog(get_class($this)."::setStatut", LOG_DEBUG); if ($this->db->query($sql)) @@ -3527,27 +3533,27 @@ abstract class CommonObject // Try autoset of trigkey if (empty($trigkey)) { - if ($this->element == 'supplier_proposal' && $status == 2) $trigkey='SUPPLIER_PROPOSAL_SIGN'; // 2 = SupplierProposal::STATUS_SIGNED. Can't use constant into this generic class - if ($this->element == 'supplier_proposal' && $status == 3) $trigkey='SUPPLIER_PROPOSAL_REFUSE'; // 3 = SupplierProposal::STATUS_REFUSED. Can't use constant into this generic class - if ($this->element == 'supplier_proposal' && $status == 4) $trigkey='SUPPLIER_PROPOSAL_CLOSE'; // 4 = SupplierProposal::STATUS_CLOSED. Can't use constant into this generic class - if ($this->element == 'fichinter' && $status == 3) $trigkey='FICHINTER_CLASSIFY_DONE'; - if ($this->element == 'fichinter' && $status == 2) $trigkey='FICHINTER_CLASSIFY_BILLED'; - if ($this->element == 'fichinter' && $status == 1) $trigkey='FICHINTER_CLASSIFY_UNBILLED'; + if ($this->element == 'supplier_proposal' && $status == 2) $trigkey = 'SUPPLIER_PROPOSAL_SIGN'; // 2 = SupplierProposal::STATUS_SIGNED. Can't use constant into this generic class + if ($this->element == 'supplier_proposal' && $status == 3) $trigkey = 'SUPPLIER_PROPOSAL_REFUSE'; // 3 = SupplierProposal::STATUS_REFUSED. Can't use constant into this generic class + if ($this->element == 'supplier_proposal' && $status == 4) $trigkey = 'SUPPLIER_PROPOSAL_CLOSE'; // 4 = SupplierProposal::STATUS_CLOSED. Can't use constant into this generic class + if ($this->element == 'fichinter' && $status == 3) $trigkey = 'FICHINTER_CLASSIFY_DONE'; + if ($this->element == 'fichinter' && $status == 2) $trigkey = 'FICHINTER_CLASSIFY_BILLED'; + if ($this->element == 'fichinter' && $status == 1) $trigkey = 'FICHINTER_CLASSIFY_UNBILLED'; } if ($trigkey) { // Appel des triggers - include_once DOL_DOCUMENT_ROOT . '/core/class/interfaces.class.php'; - $interface=new Interfaces($this->db); - $result=$interface->run_triggers($trigkey, $this, $user, $langs, $conf); + include_once DOL_DOCUMENT_ROOT.'/core/class/interfaces.class.php'; + $interface = new Interfaces($this->db); + $result = $interface->run_triggers($trigkey, $this, $user, $langs, $conf); if ($result < 0) { - $error++; $this->errors=$interface->errors; + $error++; $this->errors = $interface->errors; } // Fin appel triggers } - if (! $error) + if (!$error) { $this->db->commit(); @@ -3568,7 +3574,7 @@ abstract class CommonObject } else { - $this->error=$this->db->lasterror(); + $this->error = $this->db->lasterror(); $this->db->rollback(); return -1; } @@ -3587,16 +3593,16 @@ abstract class CommonObject global $conf; if (empty($id) && empty($ref)) return 0; - if (! empty($conf->global->MAIN_DISABLE_CANVAS)) return 0; // To increase speed. Not enabled by default. + if (!empty($conf->global->MAIN_DISABLE_CANVAS)) return 0; // To increase speed. Not enabled by default. // Clean parameters $ref = trim($ref); $sql = "SELECT rowid, canvas"; - $sql.= " FROM ".MAIN_DB_PREFIX.$this->table_element; - $sql.= " WHERE entity IN (".getEntity($this->element).")"; - if (! empty($id)) $sql.= " AND rowid = ".$id; - if (! empty($ref)) $sql.= " AND ref = '".$this->db->escape($ref)."'"; + $sql .= " FROM ".MAIN_DB_PREFIX.$this->table_element; + $sql .= " WHERE entity IN (".getEntity($this->element).")"; + if (!empty($id)) $sql .= " AND rowid = ".$id; + if (!empty($ref)) $sql .= " AND ref = '".$this->db->escape($ref)."'"; $resql = $this->db->query($sql); if ($resql) @@ -3604,7 +3610,7 @@ abstract class CommonObject $obj = $this->db->fetch_object($resql); if ($obj) { - $this->canvas = $obj->canvas; + $this->canvas = $obj->canvas; return 1; } else return 0; @@ -3626,7 +3632,7 @@ abstract class CommonObject public function getSpecialCode($lineid) { $sql = 'SELECT special_code FROM '.MAIN_DB_PREFIX.$this->table_element_line; - $sql.= ' WHERE rowid = '.$lineid; + $sql .= ' WHERE rowid = '.$lineid; $resql = $this->db->query($sql); if ($resql) { @@ -3646,10 +3652,10 @@ abstract class CommonObject { global $langs; - if (empty($id)) $id=$this->id; + if (empty($id)) $id = $this->id; // Check parameters - if (! isset($this->childtables) || ! is_array($this->childtables) || count($this->childtables) == 0) + if (!isset($this->childtables) || !is_array($this->childtables) || count($this->childtables) == 0) { dol_print_error('Called isObjectUsed on a class with property this->childtables not defined'); return -1; @@ -3657,24 +3663,24 @@ abstract class CommonObject $arraytoscan = $this->childtables; // For backward compatibility, we check if array is old format array('table1', 'table2', ...) - $tmparray=array_keys($this->childtables); + $tmparray = array_keys($this->childtables); if (is_numeric($tmparray[0])) { $arraytoscan = array_flip($this->childtables); } // Test if child exists - $haschild=0; - foreach($arraytoscan as $table => $elementname) + $haschild = 0; + foreach ($arraytoscan as $table => $elementname) { //print $id.'-'.$table.'-'.$elementname.'
    '; // Check if third party can be deleted $sql = "SELECT COUNT(*) as nb from ".MAIN_DB_PREFIX.$table; - $sql.= " WHERE ".$this->fk_element." = ".$id; - $resql=$this->db->query($sql); + $sql .= " WHERE ".$this->fk_element." = ".$id; + $resql = $this->db->query($sql); if ($resql) { - $obj=$this->db->fetch_object($resql); + $obj = $this->db->fetch_object($resql); if ($obj->nb > 0) { $langs->load("errors"); @@ -3682,24 +3688,24 @@ abstract class CommonObject $haschild += $obj->nb; if (is_numeric($elementname)) // old usage { - $this->errors[]=$langs->trans("ErrorRecordHasAtLeastOneChildOfType", $table); + $this->errors[] = $langs->trans("ErrorRecordHasAtLeastOneChildOfType", $table); } else // new usage: $elementname=Translation key { - $this->errors[]=$langs->trans("ErrorRecordHasAtLeastOneChildOfType", $langs->transnoentitiesnoconv($elementname)); + $this->errors[] = $langs->trans("ErrorRecordHasAtLeastOneChildOfType", $langs->transnoentitiesnoconv($elementname)); } - break; // We found at least one, we stop here + break; // We found at least one, we stop here } } else { - $this->errors[]=$this->db->lasterror(); + $this->errors[] = $this->db->lasterror(); return -1; } } if ($haschild > 0) { - $this->errors[]="ErrorRecordHasChildren"; + $this->errors[] = "ErrorRecordHasChildren"; return $haschild; } else return 0; @@ -3713,16 +3719,16 @@ abstract class CommonObject */ public function hasProductsOrServices($predefined = -1) { - $nb=0; + $nb = 0; - foreach($this->lines as $key => $val) + foreach ($this->lines as $key => $val) { - $qualified=0; - if ($predefined == -1) $qualified=1; - if ($predefined == 1 && $val->fk_product > 0) $qualified=1; - if ($predefined == 0 && $val->fk_product <= 0) $qualified=1; - if ($predefined == 2 && $val->fk_product > 0 && $val->product_type==0) $qualified=1; - if ($predefined == 3 && $val->fk_product > 0 && $val->product_type==1) $qualified=1; + $qualified = 0; + if ($predefined == -1) $qualified = 1; + if ($predefined == 1 && $val->fk_product > 0) $qualified = 1; + if ($predefined == 0 && $val->fk_product <= 0) $qualified = 1; + if ($predefined == 2 && $val->fk_product > 0 && $val->product_type == 0) $qualified = 1; + if ($predefined == 3 && $val->fk_product > 0 && $val->product_type == 1) $qualified = 1; if ($qualified) $nb++; } dol_syslog(get_class($this).'::hasProductsOrServices we found '.$nb.' qualified lines of products/servcies'); @@ -3736,24 +3742,24 @@ abstract class CommonObject */ public function getTotalDiscount() { - $total_discount=0.00; + $total_discount = 0.00; $sql = "SELECT subprice as pu_ht, qty, remise_percent, total_ht"; - $sql.= " FROM ".MAIN_DB_PREFIX.$this->table_element."det"; - $sql.= " WHERE ".$this->fk_element." = ".$this->id; + $sql .= " FROM ".MAIN_DB_PREFIX.$this->table_element."det"; + $sql .= " WHERE ".$this->fk_element." = ".$this->id; dol_syslog(get_class($this).'::getTotalDiscount', LOG_DEBUG); $resql = $this->db->query($sql); if ($resql) { - $num=$this->db->num_rows($resql); - $i=0; + $num = $this->db->num_rows($resql); + $i = 0; while ($i < $num) { $obj = $this->db->fetch_object($resql); $pu_ht = $obj->pu_ht; - $qty= $obj->qty; + $qty = $obj->qty; $total_ht = $obj->total_ht; $total_discount_line = floatval(price2num(($pu_ht * $qty) - $total_ht, 'MT')); @@ -3787,18 +3793,18 @@ abstract class CommonObject { if (isset($line->qty_asked)) { - if (empty($totalOrdered)) $totalOrdered=0; // Avoid warning because $totalOrdered is '' - $totalOrdered+=$line->qty_asked; // defined for shipment only + if (empty($totalOrdered)) $totalOrdered = 0; // Avoid warning because $totalOrdered is '' + $totalOrdered += $line->qty_asked; // defined for shipment only } if (isset($line->qty_shipped)) { - if (empty($totalToShip)) $totalToShip=0; // Avoid warning because $totalToShip is '' - $totalToShip+=$line->qty_shipped; // defined for shipment only + if (empty($totalToShip)) $totalToShip = 0; // Avoid warning because $totalToShip is '' + $totalToShip += $line->qty_shipped; // defined for shipment only } elseif ($line->element == 'commandefournisseurdispatch' && isset($line->qty)) { - if (empty($totalToShip)) $totalToShip=0; - $totalToShip+=$line->qty; // defined for reception only + if (empty($totalToShip)) $totalToShip = 0; + $totalToShip += $line->qty; // defined for reception only } // Define qty, weight, volume, weight_units, volume_units @@ -3811,27 +3817,27 @@ abstract class CommonObject } $weight = $line->weight ? $line->weight : 0; - ($weight==0 && !empty($line->product->weight))? $weight=$line->product->weight: 0; + ($weight == 0 && !empty($line->product->weight)) ? $weight = $line->product->weight : 0; $volume = $line->volume ? $line->volume : 0; - ($volume==0 && !empty($line->product->volume))? $volume=$line->product->volume: 0; + ($volume == 0 && !empty($line->product->volume)) ? $volume = $line->product->volume : 0; - $weight_units=$line->weight_units; - ($weight_units==0 && !empty($line->product->weight_units))? $weight_units=$line->product->weight_units: 0; - $volume_units=$line->volume_units; - ($volume_units==0 && !empty($line->product->volume_units))? $volume_units=$line->product->volume_units: 0; + $weight_units = $line->weight_units; + ($weight_units == 0 && !empty($line->product->weight_units)) ? $weight_units = $line->product->weight_units : 0; + $volume_units = $line->volume_units; + ($volume_units == 0 && !empty($line->product->volume_units)) ? $volume_units = $line->product->volume_units : 0; - $weightUnit=0; - $volumeUnit=0; - if (! empty($weight_units)) $weightUnit = $weight_units; - if (! empty($volume_units)) $volumeUnit = $volume_units; + $weightUnit = 0; + $volumeUnit = 0; + if (!empty($weight_units)) $weightUnit = $weight_units; + if (!empty($volume_units)) $volumeUnit = $volume_units; - if (empty($totalWeight)) $totalWeight=0; // Avoid warning because $totalWeight is '' - if (empty($totalVolume)) $totalVolume=0; // Avoid warning because $totalVolume is '' + if (empty($totalWeight)) $totalWeight = 0; // Avoid warning because $totalWeight is '' + if (empty($totalVolume)) $totalVolume = 0; // Avoid warning because $totalVolume is '' //var_dump($line->volume_units); if ($weight_units < 50) // < 50 means a standard unit (power of 10 of official unit), > 50 means an exotic unit (like inch) { - $trueWeightUnit=pow(10, $weightUnit); + $trueWeightUnit = pow(10, $weightUnit); $totalWeight += $weight * $qty * $trueWeightUnit; } else { @@ -3845,19 +3851,19 @@ abstract class CommonObject $totalWeight += $weight * $qty * $trueWeightUnit; } else { - $totalWeight += $weight * $qty; // This may be wrong if we mix different units + $totalWeight += $weight * $qty; // This may be wrong if we mix different units } } if ($volume_units < 50) // >50 means a standard unit (power of 10 of official unit), > 50 means an exotic unit (like inch) { //print $line->volume."x".$line->volume_units."x".($line->volume_units < 50)."x".$volumeUnit; - $trueVolumeUnit=pow(10, $volumeUnit); + $trueVolumeUnit = pow(10, $volumeUnit); //print $line->volume; $totalVolume += $volume * $qty * $trueVolumeUnit; } else { - $totalVolume += $volume * $qty; // This may be wrong if we mix different units + $totalVolume += $volume * $qty; // This may be wrong if we mix different units } } @@ -3874,17 +3880,17 @@ abstract class CommonObject { $this->db->begin(); - $extraparams = (! empty($this->extraparams) ? json_encode($this->extraparams) : null); + $extraparams = (!empty($this->extraparams) ? json_encode($this->extraparams) : null); $sql = "UPDATE ".MAIN_DB_PREFIX.$this->table_element; - $sql.= " SET extraparams = ".(! empty($extraparams) ? "'".$this->db->escape($extraparams)."'" : "null"); - $sql.= " WHERE rowid = ".$this->id; + $sql .= " SET extraparams = ".(!empty($extraparams) ? "'".$this->db->escape($extraparams)."'" : "null"); + $sql .= " WHERE rowid = ".$this->id; dol_syslog(get_class($this)."::setExtraParameters", LOG_DEBUG); $resql = $this->db->query($sql); - if (! $resql) + if (!$resql) { - $this->error=$this->db->lasterror(); + $this->error = $this->db->lasterror(); $this->db->rollback(); return -1; } @@ -3919,7 +3925,7 @@ abstract class CommonObject } } - $out .= (($res->code && $this->location_incoterms)?' - ':'').$this->location_incoterms; + $out .= (($res->code && $this->location_incoterms) ? ' - ' : '').$this->location_incoterms; return $out; } @@ -3965,11 +3971,11 @@ abstract class CommonObject if ($this->id && $this->table_element) { $sql = "UPDATE ".MAIN_DB_PREFIX.$this->table_element; - $sql.= " SET fk_incoterms = ".($id_incoterm > 0 ? $id_incoterm : "null"); - $sql.= ", location_incoterms = ".($id_incoterm > 0 ? "'".$this->db->escape($location)."'" : "null"); - $sql.= " WHERE rowid = " . $this->id; + $sql .= " SET fk_incoterms = ".($id_incoterm > 0 ? $id_incoterm : "null"); + $sql .= ", location_incoterms = ".($id_incoterm > 0 ? "'".$this->db->escape($location)."'" : "null"); + $sql .= " WHERE rowid = ".$this->id; dol_syslog(get_class($this).'::setIncoterms', LOG_DEBUG); - $resql=$this->db->query($sql); + $resql = $this->db->query($sql); if ($resql) { $this->fk_incoterms = $id_incoterm; @@ -4011,11 +4017,11 @@ abstract class CommonObject */ public function formAddObjectLine($dateSelector, $seller, $buyer, $defaulttpldir = '/core/tpl') { - global $conf,$user,$langs,$object,$hookmanager,$extrafields; - global $form,$bcnd,$var; + global $conf, $user, $langs, $object, $hookmanager, $extrafields; + global $form; // Line extrafield - if (! is_object($extrafields)) + if (!is_object($extrafields)) { require_once DOL_DOCUMENT_ROOT.'/core/class/extrafields.class.php'; $extrafields = new ExtraFields($this->db); @@ -4024,8 +4030,8 @@ abstract class CommonObject // Output template part (modules that overwrite templates must declare this into descriptor) // Use global variables + $dateSelector + $seller and $buyer - $dirtpls=array_merge($conf->modules_parts['tpl'], array($defaulttpldir)); - foreach($dirtpls as $module => $reldir) + $dirtpls = array_merge($conf->modules_parts['tpl'], array($defaulttpldir)); + foreach ($dirtpls as $module => $reldir) { if (!empty($module)) { @@ -4037,9 +4043,9 @@ abstract class CommonObject } if (empty($conf->file->strict_mode)) { - $res=@include $tpl; + $res = @include $tpl; } else { - $res=include $tpl; // for debug + $res = include $tpl; // for debug } if ($res) break; } @@ -4071,13 +4077,13 @@ abstract class CommonObject global $inputalsopricewithtax, $usemargins, $disableedit, $disablemove, $disableremove, $outputalsopricetotalwithtax; // Define usemargins - $usemargins=0; - if (! empty($conf->margin->enabled) && ! empty($this->element) && in_array($this->element, array('facture','facturerec','propal','commande'))) $usemargins=1; + $usemargins = 0; + if (!empty($conf->margin->enabled) && !empty($this->element) && in_array($this->element, array('facture', 'facturerec', 'propal', 'commande'))) $usemargins = 1; $num = count($this->lines); // Line extrafield - if (! is_object($extrafields)) + if (!is_object($extrafields)) { require_once DOL_DOCUMENT_ROOT.'/core/class/extrafields.class.php'; $extrafields = new ExtraFields($this->db); @@ -4090,8 +4096,8 @@ abstract class CommonObject { // Output template part (modules that overwrite templates must declare this into descriptor) // Use global variables + $dateSelector + $seller and $buyer - $dirtpls=array_merge($conf->modules_parts['tpl'], array($defaulttpldir)); - foreach($dirtpls as $module => $reldir) + $dirtpls = array_merge($conf->modules_parts['tpl'], array($defaulttpldir)); + foreach ($dirtpls as $module => $reldir) { if (!empty($module)) { @@ -4102,16 +4108,15 @@ abstract class CommonObject $tpl = DOL_DOCUMENT_ROOT.$reldir.'/objectline_title.tpl.php'; } if (empty($conf->file->strict_mode)) { - $res=@include $tpl; + $res = @include $tpl; } else { - $res=include $tpl; // for debug + $res = include $tpl; // for debug } if ($res) break; } } - $var = true; - $i = 0; + $i = 0; print "
    '.$langs->trans('PriceUHT').''.$langs->trans('PriceUHTCurrency').''.$langs->trans('Qty').''.$langs->trans('Unit').''.$langs->trans('ReductionShort').''.$form->showCheckAddButtons('checkforselect', 1).'
    '; - $out.= $langs->trans($this->attributes[$object->table_element]['label'][$key]); - $out.= '
    '; + $out .= $langs->trans($this->attributes[$object->table_element]['label'][$key]); + $out .= '
    '.$formquestion['text'].'
    '.$formquestion['text'].'
    '."\n"; + $formconfirm .= '
    '."\n"; // Line title - $formconfirm.= ''."\n"; + $formconfirm .= ''."\n"; // Line form fields if ($more) { - $formconfirm.=''."\n"; + $formconfirm .= ''."\n"; } // Line with question - $formconfirm.= ''; - $formconfirm.= ''; - $formconfirm.= ''; - $formconfirm.= ''; - $formconfirm.= ''."\n"; + $formconfirm .= ''; + $formconfirm .= ''; + $formconfirm .= ''; + $formconfirm .= ''; + $formconfirm .= ''."\n"; - $formconfirm.= '
    '.img_picto('', 'recent').' '.$title.'
    '.img_picto('', 'recent').' '.$title.'
    '."\n"; - $formconfirm.=$more; - $formconfirm.='
    '."\n"; + $formconfirm .= $more; + $formconfirm .= '
    '.$question.''; - $formconfirm.= $this->selectyesno("confirm", $newselectedchoice); - $formconfirm.= '
    '.$question.''; + $formconfirm .= $this->selectyesno("confirm", $newselectedchoice); + $formconfirm .= '
    '."\n"; + $formconfirm .= '
    '."\n"; - if (empty($disableformtag)) $formconfirm.= "\n"; - $formconfirm.= '
    '; + if (empty($disableformtag)) $formconfirm .= "\n"; + $formconfirm .= '
    '; - $formconfirm.= "\n"; + $formconfirm .= "\n"; } return $formconfirm; @@ -4372,20 +4372,20 @@ class Form require_once DOL_DOCUMENT_ROOT.'/core/lib/project.lib.php'; require_once DOL_DOCUMENT_ROOT.'/core/class/html.formprojet.class.php'; - $out=''; + $out = ''; - $formproject=new FormProjets($this->db); + $formproject = new FormProjets($this->db); $langs->load("project"); if ($htmlname != "none") { - $out.="\n"; - $out.='
    '; - $out.=''; - $out.=''; - $out.=$formproject->select_projects($socid, $selected, $htmlname, $maxlength, 0, 1, $discard_closed, $forcefocus, 0, 0, '', 1); - $out.=''; - $out.='
    '; + $out .= "\n"; + $out .= '
    '; + $out .= ''; + $out .= ''; + $out .= $formproject->select_projects($socid, $selected, $htmlname, $maxlength, 0, 1, $discard_closed, $forcefocus, 0, 0, '', 1); + $out .= ''; + $out .= '
    '; } else { @@ -4394,11 +4394,11 @@ class Form $projet = new Project($this->db); $projet->fetch($selected); //print ''.$projet->title.''; - $out.=$projet->getNomUrl(0, '', 1); + $out .= $projet->getNomUrl(0, '', 1); } else { - $out.=" "; + $out .= " "; } } @@ -4539,24 +4539,24 @@ class Form // phpcs:enable global $langs; - $ret=''; + $ret = ''; if ($htmlname != "none") { - $ret.='
    '; - $ret.=''; - $ret.=''; - $ret.=''; - $ret.=''; - $ret.=''; - $ret.='
    '; - $ret.=$this->selectDate($selected, $htmlname, $displayhour, $displaymin, 1, 'form'.$htmlname, 1, 0); - $ret.='
    '; + $ret .= '
    '; + $ret .= ''; + $ret .= ''; + $ret .= ''; + $ret .= ''; + $ret .= ''; + $ret .= '
    '; + $ret .= $this->selectDate($selected, $htmlname, $displayhour, $displaymin, 1, 'form'.$htmlname, 1, 0); + $ret .= '
    '; } else { - if ($displayhour) $ret.=dol_print_date($selected, 'dayhour'); - else $ret.=dol_print_date($selected, 'day'); + if ($displayhour) $ret .= dol_print_date($selected, 'dayhour'); + else $ret .= dol_print_date($selected, 'day'); } if (empty($nooutput)) print $ret; @@ -4593,8 +4593,8 @@ class Form { if ($selected) { - require_once DOL_DOCUMENT_ROOT .'/user/class/user.class.php'; - $theuser=new User($this->db); + require_once DOL_DOCUMENT_ROOT.'/user/class/user.class.php'; + $theuser = new User($this->db); $theuser->fetch($selected); print $theuser->getNomUrl(1); } else { @@ -4700,7 +4700,7 @@ class Form } else { - if (! empty($rate)) + if (!empty($rate)) { print price($rate, 1, $langs, 1, 0); if ($currency && $rate != 1) print '   ('.price($rate, 1, $langs, 1, 0).' '.$currency.' = 1 '.$conf->currency.')'; @@ -4732,33 +4732,33 @@ class Form public function form_remise_dispo($page, $selected, $htmlname, $socid, $amount, $filter = '', $maxvalue = 0, $more = '', $hidelist = 0, $discount_type = 0) { // phpcs:enable - global $conf,$langs; + global $conf, $langs; if ($htmlname != "none") { print '
    '; print ''; print ''; print '
    '; - if(! empty($discount_type)) { - if (! empty($conf->global->FACTURE_DEPOSITS_ARE_JUST_PAYMENTS)) + if (!empty($discount_type)) { + if (!empty($conf->global->FACTURE_DEPOSITS_ARE_JUST_PAYMENTS)) { - if (! $filter || $filter=="fk_invoice_supplier_source IS NULL") $translationKey = 'HasAbsoluteDiscountFromSupplier'; // If we want deposit to be substracted to payments only and not to total of final invoice + if (!$filter || $filter == "fk_invoice_supplier_source IS NULL") $translationKey = 'HasAbsoluteDiscountFromSupplier'; // If we want deposit to be substracted to payments only and not to total of final invoice else $translationKey = 'HasCreditNoteFromSupplier'; } else { - if (! $filter || $filter=="fk_invoice_supplier_source IS NULL OR (description LIKE '(DEPOSIT)%' AND description NOT LIKE '(EXCESS PAID)%')") $translationKey = 'HasAbsoluteDiscountFromSupplier'; + if (!$filter || $filter == "fk_invoice_supplier_source IS NULL OR (description LIKE '(DEPOSIT)%' AND description NOT LIKE '(EXCESS PAID)%')") $translationKey = 'HasAbsoluteDiscountFromSupplier'; else $translationKey = 'HasCreditNoteFromSupplier'; } } else { - if (! empty($conf->global->FACTURE_DEPOSITS_ARE_JUST_PAYMENTS)) + if (!empty($conf->global->FACTURE_DEPOSITS_ARE_JUST_PAYMENTS)) { - if (! $filter || $filter=="fk_facture_source IS NULL") $translationKey = 'CompanyHasAbsoluteDiscount'; // If we want deposit to be substracted to payments only and not to total of final invoice + if (!$filter || $filter == "fk_facture_source IS NULL") $translationKey = 'CompanyHasAbsoluteDiscount'; // If we want deposit to be substracted to payments only and not to total of final invoice else $translationKey = 'CompanyHasCreditNote'; } else { - if (! $filter || $filter=="fk_facture_source IS NULL OR (description LIKE '(DEPOSIT)%' AND description NOT LIKE '(EXCESS RECEIVED)%')") $translationKey = 'CompanyHasAbsoluteDiscount'; + if (!$filter || $filter == "fk_facture_source IS NULL OR (description LIKE '(DEPOSIT)%' AND description NOT LIKE '(EXCESS RECEIVED)%')") $translationKey = 'CompanyHasAbsoluteDiscount'; else $translationKey = 'CompanyHasCreditNote'; } } @@ -4769,19 +4769,19 @@ class Form { print '
    '; $newfilter = 'discount_type='.intval($discount_type); - if(! empty($discount_type)) { - $newfilter.= ' AND fk_invoice_supplier IS NULL AND fk_invoice_supplier_line IS NULL'; // Supplier discounts available + if (!empty($discount_type)) { + $newfilter .= ' AND fk_invoice_supplier IS NULL AND fk_invoice_supplier_line IS NULL'; // Supplier discounts available } else { - $newfilter.= ' AND fk_facture IS NULL AND fk_facture_line IS NULL'; // Customer discounts available + $newfilter .= ' AND fk_facture IS NULL AND fk_facture_line IS NULL'; // Customer discounts available } - if ($filter) $newfilter.=' AND ('.$filter.')'; - $nbqualifiedlines=$this->select_remises($selected, $htmlname, $newfilter, $socid, $maxvalue); + if ($filter) $newfilter .= ' AND ('.$filter.')'; + $nbqualifiedlines = $this->select_remises($selected, $htmlname, $newfilter, $socid, $maxvalue); if ($nbqualifiedlines > 0) { print '   '; @@ -4832,10 +4832,10 @@ class Form print ''; print ''; print ''; @@ -4846,8 +4846,8 @@ class Form { if ($selected) { - require_once DOL_DOCUMENT_ROOT .'/contact/class/contact.class.php'; - $contact=new Contact($this->db); + require_once DOL_DOCUMENT_ROOT.'/contact/class/contact.class.php'; + $contact = new Contact($this->db); $contact->fetch($selected); print $contact->getFullName($langs); } else { @@ -4879,25 +4879,25 @@ class Form $out = ''; if ($htmlname != "none") { - $out.=''; - $out.= ''; - $out.= ''; - $out.= $this->select_company($selected, $htmlname, $filter, $showempty, $showtype, $forcecombo, $events); - $out.= ''; - $out.= ''; + $out .= ''; + $out .= ''; + $out .= ''; + $out .= $this->select_company($selected, $htmlname, $filter, $showempty, $showtype, $forcecombo, $events); + $out .= ''; + $out .= ''; } else { if ($selected) { - require_once DOL_DOCUMENT_ROOT .'/societe/class/societe.class.php'; + require_once DOL_DOCUMENT_ROOT.'/societe/class/societe.class.php'; $soc = new Societe($this->db); $soc->fetch($selected); - $out.= $soc->getNomUrl($langs); + $out .= $soc->getNomUrl($langs); } else { - $out.= " "; + $out .= " "; } } @@ -4930,41 +4930,41 @@ class Form */ public function selectCurrency($selected = '', $htmlname = 'currency_id', $mode = 0) { - global $conf,$langs,$user; + global $conf, $langs, $user; $langs->loadCacheCurrencies(''); - $out=''; + $out = ''; - if ($selected=='euro' || $selected=='euros') $selected='EUR'; // Pour compatibilite + if ($selected == 'euro' || $selected == 'euros') $selected = 'EUR'; // Pour compatibilite - $out.= ''; foreach ($langs->cache_currencies as $code_iso => $currency) { if ($selected && $selected == $code_iso) { - $out.= ''; + $out .= ''; } - $out.= ''; - if ($user->admin) $out.= info_admin($langs->trans("YouCanChangeValuesForThisListFromDictionarySetup"), 1); + $out .= ''; + if ($user->admin) $out .= info_admin($langs->trans("YouCanChangeValuesForThisListFromDictionarySetup"), 1); // Make select dynamic - include_once DOL_DOCUMENT_ROOT . '/core/lib/ajax.lib.php'; + include_once DOL_DOCUMENT_ROOT.'/core/lib/ajax.lib.php'; $out .= ajax_combobox($htmlname); return $out; @@ -4980,25 +4980,25 @@ class Form */ public function selectMultiCurrency($selected = '', $htmlname = 'multicurrency_code', $useempty = 0) { - global $db,$conf,$langs,$user; + global $db, $conf, $langs, $user; - $langs->loadCacheCurrencies(''); // Load ->cache_currencies + $langs->loadCacheCurrencies(''); // Load ->cache_currencies $TCurrency = array(); $sql = 'SELECT code FROM '.MAIN_DB_PREFIX.'multicurrency'; - $sql.= " WHERE entity IN ('".getEntity('mutlicurrency')."')"; + $sql .= " WHERE entity IN ('".getEntity('mutlicurrency')."')"; $resql = $db->query($sql); if ($resql) { while ($obj = $db->fetch_object($resql)) $TCurrency[$obj->code] = $obj->code; } - $out=''; - $out.= ''; if ($useempty) $out .= ''; // If company current currency not in table, we add it into list. Should always be available. - if (! in_array($conf->currency, $TCurrency)) + if (!in_array($conf->currency, $TCurrency)) { $TCurrency[$conf->currency] = $conf->currency; } @@ -5008,20 +5008,20 @@ class Form { if (isset($TCurrency[$code_iso])) { - if (!empty($selected) && $selected == $code_iso) $out.= ''; + $out .= $currency['label']; + $out .= ' ('.$langs->getCurrencySymbol($code_iso).')'; + $out .= ''; } } } - $out.= ''; + $out .= ''; // Make select dynamic - include_once DOL_DOCUMENT_ROOT . '/core/lib/ajax.lib.php'; - $out.= ajax_combobox($htmlname); + include_once DOL_DOCUMENT_ROOT.'/core/lib/ajax.lib.php'; + $out .= ajax_combobox($htmlname); return $out; } @@ -5039,18 +5039,18 @@ class Form global $langs; $num = count($this->cache_vatrates); - if ($num > 0) return $num; // Cache already loaded + if ($num > 0) return $num; // Cache already loaded dol_syslog(__METHOD__, LOG_DEBUG); - $sql = "SELECT DISTINCT t.rowid, t.code, t.taux, t.localtax1, t.localtax1_type, t.localtax2, t.localtax2_type, t.recuperableonly"; - $sql.= " FROM ".MAIN_DB_PREFIX."c_tva as t, ".MAIN_DB_PREFIX."c_country as c"; - $sql.= " WHERE t.fk_pays = c.rowid"; - $sql.= " AND t.active > 0"; - $sql.= " AND c.code IN (".$country_code.")"; - $sql.= " ORDER BY t.code ASC, t.taux ASC, t.recuperableonly ASC"; + $sql = "SELECT DISTINCT t.rowid, t.code, t.taux, t.localtax1, t.localtax1_type, t.localtax2, t.localtax2_type, t.recuperableonly"; + $sql .= " FROM ".MAIN_DB_PREFIX."c_tva as t, ".MAIN_DB_PREFIX."c_country as c"; + $sql .= " WHERE t.fk_pays = c.rowid"; + $sql .= " AND t.active > 0"; + $sql .= " AND c.code IN (".$country_code.")"; + $sql .= " ORDER BY t.code ASC, t.taux ASC, t.recuperableonly ASC"; - $resql=$this->db->query($sql); + $resql = $this->db->query($sql); if ($resql) { $num = $this->db->num_rows($resql); @@ -5060,22 +5060,22 @@ class Form { $obj = $this->db->fetch_object($resql); $this->cache_vatrates[$i]['rowid'] = $obj->rowid; - $this->cache_vatrates[$i]['code'] = $obj->code; + $this->cache_vatrates[$i]['code'] = $obj->code; $this->cache_vatrates[$i]['txtva'] = $obj->taux; - $this->cache_vatrates[$i]['nprtva'] = $obj->recuperableonly; + $this->cache_vatrates[$i]['nprtva'] = $obj->recuperableonly; $this->cache_vatrates[$i]['localtax1'] = $obj->localtax1; $this->cache_vatrates[$i]['localtax1_type'] = $obj->localtax1_type; $this->cache_vatrates[$i]['localtax2'] = $obj->localtax2; $this->cache_vatrates[$i]['localtax2_type'] = $obj->localtax1_type; - $this->cache_vatrates[$i]['label'] = $obj->taux.'%'.($obj->code?' ('.$obj->code.')':''); // Label must contains only 0-9 , . % or * - $this->cache_vatrates[$i]['labelallrates'] = $obj->taux.'/'.($obj->localtax1?$obj->localtax1:'0').'/'.($obj->localtax2?$obj->localtax2:'0').($obj->code?' ('.$obj->code.')':''); // Must never be used as key, only label - $positiverates=''; - if ($obj->taux) $positiverates.=($positiverates?'/':'').$obj->taux; - if ($obj->localtax1) $positiverates.=($positiverates?'/':'').$obj->localtax1; - if ($obj->localtax2) $positiverates.=($positiverates?'/':'').$obj->localtax2; - if (empty($positiverates)) $positiverates='0'; - $this->cache_vatrates[$i]['labelpositiverates'] = $positiverates.($obj->code?' ('.$obj->code.')':''); // Must never be used as key, only label + $this->cache_vatrates[$i]['label'] = $obj->taux.'%'.($obj->code ? ' ('.$obj->code.')' : ''); // Label must contains only 0-9 , . % or * + $this->cache_vatrates[$i]['labelallrates'] = $obj->taux.'/'.($obj->localtax1 ? $obj->localtax1 : '0').'/'.($obj->localtax2 ? $obj->localtax2 : '0').($obj->code ? ' ('.$obj->code.')' : ''); // Must never be used as key, only label + $positiverates = ''; + if ($obj->taux) $positiverates .= ($positiverates ? '/' : '').$obj->taux; + if ($obj->localtax1) $positiverates .= ($positiverates ? '/' : '').$obj->localtax1; + if ($obj->localtax2) $positiverates .= ($positiverates ? '/' : '').$obj->localtax2; + if (empty($positiverates)) $positiverates = '0'; + $this->cache_vatrates[$i]['labelpositiverates'] = $positiverates.($obj->code ? ' ('.$obj->code.')' : ''); // Must never be used as key, only label } return $num; @@ -5118,34 +5118,34 @@ class Form public function load_tva($htmlname = 'tauxtva', $selectedrate = '', $societe_vendeuse = '', $societe_acheteuse = '', $idprod = 0, $info_bits = 0, $type = '', $options_only = false, $mode = 0) { // phpcs:enable - global $langs,$conf,$mysoc; + global $langs, $conf, $mysoc; $langs->load('errors'); - $return=''; + $return = ''; // Define defaultnpr, defaultttx and defaultcode - $defaultnpr=($info_bits & 0x01); - $defaultnpr=(preg_match('/\*/', $selectedrate) ? 1 : $defaultnpr); - $defaulttx=str_replace('*', '', $selectedrate); - $defaultcode=''; + $defaultnpr = ($info_bits & 0x01); + $defaultnpr = (preg_match('/\*/', $selectedrate) ? 1 : $defaultnpr); + $defaulttx = str_replace('*', '', $selectedrate); + $defaultcode = ''; if (preg_match('/\((.*)\)/', $defaulttx, $reg)) { - $defaultcode=$reg[1]; - $defaulttx=preg_replace('/\s*\(.*\)/', '', $defaulttx); + $defaultcode = $reg[1]; + $defaulttx = preg_replace('/\s*\(.*\)/', '', $defaulttx); } //var_dump($selectedrate.'-'.$defaulttx.'-'.$defaultnpr.'-'.$defaultcode); // Check parameters - if (is_object($societe_vendeuse) && ! $societe_vendeuse->country_code) + if (is_object($societe_vendeuse) && !$societe_vendeuse->country_code) { if ($societe_vendeuse->id == $mysoc->id) { - $return.= ''.$langs->trans("ErrorYourCountryIsNotDefined").''; + $return .= ''.$langs->trans("ErrorYourCountryIsNotDefined").''; } else { - $return.= ''.$langs->trans("ErrorSupplierCountryIsNotDefined").''; + $return .= ''.$langs->trans("ErrorSupplierCountryIsNotDefined").''; } return $return; } @@ -5158,82 +5158,82 @@ class Form // First we defined code_country to use to find list if (is_object($societe_vendeuse)) { - $code_country="'".$societe_vendeuse->country_code."'"; + $code_country = "'".$societe_vendeuse->country_code."'"; } else { - $code_country="'".$mysoc->country_code."'"; // Pour compatibilite ascendente + $code_country = "'".$mysoc->country_code."'"; // Pour compatibilite ascendente } - if (! empty($conf->global->SERVICE_ARE_ECOMMERCE_200238EC)) // If option to have vat for end customer for services is on + if (!empty($conf->global->SERVICE_ARE_ECOMMERCE_200238EC)) // If option to have vat for end customer for services is on { require_once DOL_DOCUMENT_ROOT.'/core/lib/company.lib.php'; - if (! isInEEC($societe_vendeuse) && (! is_object($societe_acheteuse) || (isInEEC($societe_acheteuse) && ! $societe_acheteuse->isACompany()))) + if (!isInEEC($societe_vendeuse) && (!is_object($societe_acheteuse) || (isInEEC($societe_acheteuse) && !$societe_acheteuse->isACompany()))) { // We also add the buyer if (is_numeric($type)) { if ($type == 1) // We know product is a service { - $code_country.=",'".$societe_acheteuse->country_code."'"; + $code_country .= ",'".$societe_acheteuse->country_code."'"; } } - elseif (! $idprod) // We don't know type of product + elseif (!$idprod) // We don't know type of product { - $code_country.=",'".$societe_acheteuse->country_code."'"; + $code_country .= ",'".$societe_acheteuse->country_code."'"; } else { - $prodstatic=new Product($this->db); + $prodstatic = new Product($this->db); $prodstatic->fetch($idprod); if ($prodstatic->type == Product::TYPE_SERVICE) // We know product is a service { - $code_country.=",'".$societe_acheteuse->country_code."'"; + $code_country .= ",'".$societe_acheteuse->country_code."'"; } } } } // Now we get list - $num = $this->load_cache_vatrates($code_country); // If no vat defined, return -1 with message into this->error + $num = $this->load_cache_vatrates($code_country); // If no vat defined, return -1 with message into this->error if ($num > 0) { // Definition du taux a pre-selectionner (si defaulttx non force et donc vaut -1 ou '') if ($defaulttx < 0 || dol_strlen($defaulttx) == 0) { - $tmpthirdparty=new Societe($this->db); - $defaulttx=get_default_tva($societe_vendeuse, (is_object($societe_acheteuse)?$societe_acheteuse:$tmpthirdparty), $idprod); - $defaultnpr=get_default_npr($societe_vendeuse, (is_object($societe_acheteuse)?$societe_acheteuse:$tmpthirdparty), $idprod); + $tmpthirdparty = new Societe($this->db); + $defaulttx = get_default_tva($societe_vendeuse, (is_object($societe_acheteuse) ? $societe_acheteuse : $tmpthirdparty), $idprod); + $defaultnpr = get_default_npr($societe_vendeuse, (is_object($societe_acheteuse) ? $societe_acheteuse : $tmpthirdparty), $idprod); if (preg_match('/\((.*)\)/', $defaulttx, $reg)) { - $defaultcode=$reg[1]; - $defaulttx=preg_replace('/\s*\(.*\)/', '', $defaulttx); + $defaultcode = $reg[1]; + $defaulttx = preg_replace('/\s*\(.*\)/', '', $defaulttx); } - if (empty($defaulttx)) $defaultnpr=0; + if (empty($defaulttx)) $defaultnpr = 0; } // Si taux par defaut n'a pu etre determine, on prend dernier de la liste. // Comme ils sont tries par ordre croissant, dernier = plus eleve = taux courant if ($defaulttx < 0 || dol_strlen($defaulttx) == 0) { - if (empty($conf->global->MAIN_VAT_DEFAULT_IF_AUTODETECT_FAILS)) $defaulttx = $this->cache_vatrates[$num-1]['txtva']; - else $defaulttx=($conf->global->MAIN_VAT_DEFAULT_IF_AUTODETECT_FAILS == 'none' ? '' : $conf->global->MAIN_VAT_DEFAULT_IF_AUTODETECT_FAILS); + if (empty($conf->global->MAIN_VAT_DEFAULT_IF_AUTODETECT_FAILS)) $defaulttx = $this->cache_vatrates[$num - 1]['txtva']; + else $defaulttx = ($conf->global->MAIN_VAT_DEFAULT_IF_AUTODETECT_FAILS == 'none' ? '' : $conf->global->MAIN_VAT_DEFAULT_IF_AUTODETECT_FAILS); } // Disabled if seller is not subject to VAT - $disabled=false; $title=''; + $disabled = false; $title = ''; if (is_object($societe_vendeuse) && $societe_vendeuse->id == $mysoc->id && $societe_vendeuse->tva_assuj == "0") { // Override/enable VAT for expense report regardless of global setting - needed if expense report used for business expenses if (empty($conf->global->OVERRIDE_VAT_FOR_EXPENSE_REPORT)) { - $title=' title="'.$langs->trans('VATIsNotUsed').'"'; - $disabled=true; + $title = ' title="'.$langs->trans('VATIsNotUsed').'"'; + $disabled = true; } } - if (! $options_only) $return.= ''; - $selectedfound=false; + $selectedfound = false; foreach ($this->cache_vatrates as $rate) { // Keep only 0 if seller is not subject to VAT @@ -5241,48 +5241,48 @@ class Form // Define key to use into select list $key = $rate['txtva']; - $key.= $rate['nprtva'] ? '*': ''; - if ($mode > 0 && $rate['code']) $key.=' ('.$rate['code'].')'; + $key .= $rate['nprtva'] ? '*' : ''; + if ($mode > 0 && $rate['code']) $key .= ' ('.$rate['code'].')'; if ($mode < 0) $key = $rate['rowid']; - $return.= ''; + $return .= ''; } - if (! $options_only) $return.= ''; + if (!$options_only) $return .= ''; } else { - $return.= $this->error; + $return .= $this->error; } $this->num = $num; @@ -5319,7 +5319,7 @@ class Form { // phpcs:enable $retstring = $this->selectDate($set_time, $prefix, $h, $m, $empty, $form_name, $d, $addnowlink, $disabled, $fullday, $addplusone, $adddateof); - if (! empty($nooutput)) { + if (!empty($nooutput)) { return $retstring; } print $retstring; @@ -5353,35 +5353,35 @@ class Form */ public function selectDate($set_time = '', $prefix = 're', $h = 0, $m = 0, $empty = 0, $form_name = "", $d = 1, $addnowlink = 0, $disabled = 0, $fullday = '', $addplusone = '', $adddateof = '', $openinghours = '', $stepminutes = 1, $labeladddateof = '') { - global $conf,$langs; + global $conf, $langs; - $retstring=''; + $retstring = ''; - if ($prefix=='') $prefix='re'; - if ($h == '') $h=0; - if ($m == '') $m=0; - $emptydate=0; - $emptyhours=0; - if ($stepminutes<=0 || $stepminutes>30) $stepminutes = 1; - if ($empty == 1) { $emptydate=1; $emptyhours=1; } - if ($empty == 2) { $emptydate=0; $emptyhours=1; } - $orig_set_time=$set_time; + if ($prefix == '') $prefix = 're'; + if ($h == '') $h = 0; + if ($m == '') $m = 0; + $emptydate = 0; + $emptyhours = 0; + if ($stepminutes <= 0 || $stepminutes > 30) $stepminutes = 1; + if ($empty == 1) { $emptydate = 1; $emptyhours = 1; } + if ($empty == 2) { $emptydate = 0; $emptyhours = 1; } + $orig_set_time = $set_time; if ($set_time === '' && $emptydate == 0) { include_once DOL_DOCUMENT_ROOT.'/core/lib/date.lib.php'; - $set_time = dol_now('tzuser')-(getServerTimeZoneInt('now')*3600); // set_time must be relative to PHP server timezone + $set_time = dol_now('tzuser') - (getServerTimeZoneInt('now') * 3600); // set_time must be relative to PHP server timezone } // Analysis of the pre-selection date if (preg_match('/^([0-9]+)\-([0-9]+)\-([0-9]+)\s?([0-9]+)?:?([0-9]+)?/', $set_time, $reg)) // deprecated usage { // Date format 'YYYY-MM-DD' or 'YYYY-MM-DD HH:MM:SS' - $syear = (! empty($reg[1])?$reg[1]:''); - $smonth = (! empty($reg[2])?$reg[2]:''); - $sday = (! empty($reg[3])?$reg[3]:''); - $shour = (! empty($reg[4])?$reg[4]:''); - $smin = (! empty($reg[5])?$reg[5]:''); + $syear = (!empty($reg[1]) ? $reg[1] : ''); + $smonth = (!empty($reg[2]) ? $reg[2] : ''); + $sday = (!empty($reg[3]) ? $reg[3] : ''); + $shour = (!empty($reg[4]) ? $reg[4] : ''); + $smin = (!empty($reg[5]) ? $reg[5] : ''); } elseif (strval($set_time) != '' && $set_time != -1) { @@ -5416,9 +5416,9 @@ class Form if ($m == 3) $smin = ''; // You can set MAIN_POPUP_CALENDAR to 'eldy' or 'jquery' - $usecalendar='combo'; - if (! empty($conf->use_javascript_ajax) && (empty($conf->global->MAIN_POPUP_CALENDAR) || $conf->global->MAIN_POPUP_CALENDAR != "none")) { - $usecalendar = ((empty($conf->global->MAIN_POPUP_CALENDAR) || $conf->global->MAIN_POPUP_CALENDAR == 'eldy')?'jquery':$conf->global->MAIN_POPUP_CALENDAR); + $usecalendar = 'combo'; + if (!empty($conf->use_javascript_ajax) && (empty($conf->global->MAIN_POPUP_CALENDAR) || $conf->global->MAIN_POPUP_CALENDAR != "none")) { + $usecalendar = ((empty($conf->global->MAIN_POPUP_CALENDAR) || $conf->global->MAIN_POPUP_CALENDAR == 'eldy') ? 'jquery' : $conf->global->MAIN_POPUP_CALENDAR); } if ($d) @@ -5426,50 +5426,50 @@ class Form // Show date with popup if ($usecalendar != 'combo') { - $formated_date=''; + $formated_date = ''; //print "e".$set_time." t ".$conf->format_date_short; if (strval($set_time) != '' && $set_time != -1) { //$formated_date=dol_print_date($set_time,$conf->format_date_short); - $formated_date=dol_print_date($set_time, $langs->trans("FormatDateShortInput")); // FormatDateShortInput for dol_print_date / FormatDateShortJavaInput that is same for javascript + $formated_date = dol_print_date($set_time, $langs->trans("FormatDateShortInput")); // FormatDateShortInput for dol_print_date / FormatDateShortJavaInput that is same for javascript } // Calendrier popup version eldy if ($usecalendar == "eldy") { // Zone de saisie manuelle de la date - $retstring.='trans("FormatDateShortJavaInput").'\'); "'; // FormatDateShortInput for dol_print_date / FormatDateShortJavaInput that is same for javascript - $retstring.='>'; + $retstring .= 'trans("FormatDateShortJavaInput").'\'); "'; // FormatDateShortInput for dol_print_date / FormatDateShortJavaInput that is same for javascript + $retstring .= '>'; // Icone calendrier - if (! $disabled) + if (!$disabled) { - $retstring.=''; + $retstring .= ''; } - else $retstring.=''; + else $retstring .= ''; - $retstring.=''."\n"; - $retstring.=''."\n"; - $retstring.=''."\n"; + $retstring .= ''."\n"; + $retstring .= ''."\n"; + $retstring .= ''."\n"; } elseif ($usecalendar == 'jquery') { - if (! $disabled) + if (!$disabled) { // Output javascript for datepicker - $retstring.=""; + $retstring .= ""; } // Zone de saisie manuelle de la date - $retstring.='
    '; - $retstring.='trans("FormatDateShortJavaInput").'\'); "'; // FormatDateShortInput for dol_print_date / FormatDateShortJavaInput that is same for javascript - $retstring.='>'; + $retstring .= '
    '; + $retstring .= 'trans("FormatDateShortJavaInput").'\'); "'; // FormatDateShortInput for dol_print_date / FormatDateShortJavaInput that is same for javascript + $retstring .= '>'; // Icone calendrier - if (! $disabled) + if (!$disabled) { /* Not required. Managed by option buttonImage of jquery $retstring.=img_object($langs->trans("SelectDate"),'calendarday','id="'.$prefix.'id" class="datecallink"'); @@ -5513,17 +5513,17 @@ class Form } else { - $retstring.=''; + $retstring .= ''; } - $retstring.='
    '; - $retstring.=''."\n"; - $retstring.=''."\n"; - $retstring.=''."\n"; + $retstring .= '
    '; + $retstring .= ''."\n"; + $retstring .= ''."\n"; + $retstring .= ''."\n"; } else { - $retstring.="Bad value of MAIN_POPUP_CALENDAR"; + $retstring .= "Bad value of MAIN_POPUP_CALENDAR"; } } // Show date with combo selects @@ -5531,55 +5531,55 @@ class Form { //$retstring.='
    '; // Day - $retstring.=''; + $retstring .= ''; if ($emptydate || $set_time == -1) { - $retstring.=''; + $retstring .= ''; } - for ($day = 1 ; $day <= 31; $day++) + for ($day = 1; $day <= 31; $day++) { - $retstring.=''; + $retstring .= ''; } - $retstring.=""; + $retstring .= ""; - $retstring.=''; + $retstring .= ''; if ($emptydate || $set_time == -1) { - $retstring.=''; + $retstring .= ''; } // Month - for ($month = 1 ; $month <= 12 ; $month++) + for ($month = 1; $month <= 12; $month++) { - $retstring.='"; + $retstring .= '"; } - $retstring.=""; + $retstring .= ""; // Year if ($emptydate || $set_time == -1) { - $retstring.=''; + $retstring .= ''; } else { - $retstring.=''; + $retstring .= ''; - for ($year = $syear - 10; $year < $syear + 10 ; $year++) + for ($year = $syear - 10; $year < $syear + 10; $year++) { - $retstring.=''; + $retstring .= ''; } - $retstring.="\n"; + $retstring .= "\n"; } //$retstring.='
    '; } } - if ($d && $h) $retstring.=($h==2?'
    ':' '); + if ($d && $h) $retstring .= ($h == 2 ? '
    ' : ' '); if ($h) { @@ -5589,33 +5589,33 @@ class Form $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.=''; + $retstring .= ''; + if ($emptyhours) $retstring .= ''; for ($hour = $hourstart; $hour < $hourend; $hour++) { - if (strlen($hour) < 2) $hour = "0" . $hour; - $retstring.=''; + if (strlen($hour) < 2) $hour = "0".$hour; + $retstring .= ''; } - $retstring.=''; - if ($m && empty($conf->dol_optimize_smallscreen)) $retstring.=":"; + $retstring .= ''; + if ($m && empty($conf->dol_optimize_smallscreen)) $retstring .= ":"; } if ($m) { // Show minutes - $retstring.=''; - if ($emptyhours) $retstring.=''; - for ($min = 0; $min < 60 ; $min+=$stepminutes) + $retstring .= ''; + if ($emptyhours) $retstring .= ''; + for ($min = 0; $min < 60; $min += $stepminutes) { - if (strlen($min) < 2) $min = "0" . $min; - $retstring.=''; + if (strlen($min) < 2) $min = "0".$min; + $retstring .= ''; } - $retstring.=''; + $retstring .= ''; - $retstring.=''; + $retstring .= ''; } // Add a "Now" link @@ -5623,10 +5623,10 @@ class Form { // Script which will be inserted in the onClick of the "Now" link $reset_scripts = ""; - if ($addnowlink==2) // local computer time + if ($addnowlink == 2) // local computer time { // pad add leading 0 on numbers - $reset_scripts.="Number.prototype.pad = function(size) { + $reset_scripts .= "Number.prototype.pad = function(size) { var s = String(this); while (s.length < (size || 2)) {s = '0' + s;} return s; @@ -5635,14 +5635,14 @@ class Form } // Generate the date part, depending on the use or not of the javascript calendar - if($addnowlink==1) // server time expressed in user time setup + if ($addnowlink == 1) // server time expressed in user time setup { $reset_scripts .= 'jQuery(\'#'.$prefix.'\').val(\''.dol_print_date(dol_now(), 'day', 'tzuser').'\');'; $reset_scripts .= 'jQuery(\'#'.$prefix.'day\').val(\''.dol_print_date(dol_now(), '%d', 'tzuser').'\');'; $reset_scripts .= 'jQuery(\'#'.$prefix.'month\').val(\''.dol_print_date(dol_now(), '%m', 'tzuser').'\');'; $reset_scripts .= 'jQuery(\'#'.$prefix.'year\').val(\''.dol_print_date(dol_now(), '%Y', 'tzuser').'\');'; } - elseif($addnowlink==2) + elseif ($addnowlink == 2) { $reset_scripts .= 'jQuery(\'#'.$prefix.'\').val(d.toLocaleDateString(\''.str_replace('_', '-', $langs->defaultlang).'\'));'; $reset_scripts .= 'jQuery(\'#'.$prefix.'day\').val(d.getDate().pad());'; @@ -5665,11 +5665,11 @@ class Form { 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(dol_now(), '%H', 'tzuser').'\');'; } - elseif($addnowlink==2) + elseif ($addnowlink == 2) { $reset_scripts .= 'jQuery(\'#'.$prefix.'hour\').val(d.getHours().pad());'; } @@ -5681,11 +5681,11 @@ class Form { 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(dol_now(), '%M', 'tzuser').'\');'; } - elseif($addnowlink==2) + elseif ($addnowlink == 2) { $reset_scripts .= 'jQuery(\'#'.$prefix.'min\').val(d.getMinutes().pad());'; } @@ -5694,9 +5694,9 @@ class Form // If reset_scripts is not empty, print the link with the reset_scripts in the onClick if ($reset_scripts && empty($conf->dol_optimize_smallscreen)) { - $retstring.=' '; + $retstring .= ' '; } } @@ -5749,14 +5749,14 @@ class Form /** * Function to show a form to select a duration on a page * - * @param string $prefix Prefix for input fields - * @param int $iSecond Default preselected duration (number of seconds or '') - * @param int $disabled Disable the combo box - * @param string $typehour If 'select' then input hour and input min is a combo, - * if 'text' input hour is in text and input min is a text, - * if 'textselect' input hour is in text and input min is a combo - * @param integer $minunderhours If 1, show minutes selection under the hours - * @param int $nooutput Do not output html string but return it + * @param string $prefix Prefix for input fields + * @param int $iSecond Default preselected duration (number of seconds or '') + * @param int $disabled Disable the combo box + * @param string $typehour If 'select' then input hour and input min is a combo, + * If 'text' input hour is in text and input min is a text, + * If 'textselect' input hour is in text and input min is a combo + * @param integer $minunderhours If 1, show minutes selection under the hours + * @param int $nooutput Do not output html string but return it * @return string|void */ public function select_duration($prefix, $iSecond = '', $disabled = 0, $typehour = 'select', $minunderhours = 0, $nooutput = 0) @@ -5764,9 +5764,9 @@ class Form // phpcs:enable global $langs; - $retstring=''; + $retstring = ''; - $hourSelected=0; $minSelected=0; + $hourSelected = 0; $minSelected = 0; // Hours if ($iSecond != '') @@ -5777,54 +5777,54 @@ class Form $minSelected = convertSecondToTime($iSecond, 'min'); } - if ($typehour=='select' ) + if ($typehour == 'select') { - $retstring.=''; for ($hour = 0; $hour < 25; $hour++) // For a duration, we allow 24 hours { - $retstring.='"; } - $retstring.=""; + $retstring .= ""; } - elseif ($typehour=='text' || $typehour=='textselect') + elseif ($typehour == 'text' || $typehour == 'textselect') { - $retstring.=''; + $retstring .= ''; } else return 'BadValueForParameterTypeHour'; - if ($typehour!='text') $retstring.=' '.$langs->trans('HourShort'); - else $retstring.=':'; + if ($typehour != 'text') $retstring .= ' '.$langs->trans('HourShort'); + else $retstring .= ':'; // Minutes - if ($minunderhours) $retstring.='
    '; - else $retstring.=' '; + if ($minunderhours) $retstring .= '
    '; + else $retstring .= ' '; - if ($typehour=='select' || $typehour=='textselect') + if ($typehour == 'select' || $typehour == 'textselect') { - $retstring.=''; + for ($min = 0; $min <= 55; $min = $min + 5) { - $retstring.=''; + $out .= ''; } else { - $out.= ''; + $out .= ''; } } else @@ -6072,18 +6083,18 @@ class Form } $i++; - if (($i % 10) == 0) $out.="\n"; + if (($i % 10) == 0) $out .= "\n"; } } - $out.= ''."\n"; + $out .= ''."\n"; } else { dol_print_error($this->db); } - $this->result=array('nbofelement'=>$num); + $this->result = array('nbofelement'=>$num); if ($outputmode) return $outarray; return $out; @@ -6122,31 +6133,31 @@ class Form //if (preg_match('/^multi/',$htmlname)) $jsbeautify = 1; $jsbeautify = 1; - if ($value_as_key) $array=array_combine($array, $array); + if ($value_as_key) $array = array_combine($array, $array); - $out=''; + $out = ''; // Add code for jquery to use multiselect if ($addjscombo && $jsbeautify) { - $minLengthToAutocomplete=0; - $tmpplugin=empty($conf->global->MAIN_USE_JQUERY_MULTISELECT)?(constant('REQUIRE_JQUERY_MULTISELECT')?constant('REQUIRE_JQUERY_MULTISELECT'):'select2'):$conf->global->MAIN_USE_JQUERY_MULTISELECT; + $minLengthToAutocomplete = 0; + $tmpplugin = empty($conf->global->MAIN_USE_JQUERY_MULTISELECT) ? (constant('REQUIRE_JQUERY_MULTISELECT') ?constant('REQUIRE_JQUERY_MULTISELECT') : 'select2') : $conf->global->MAIN_USE_JQUERY_MULTISELECT; // Enhance with select2 - include_once DOL_DOCUMENT_ROOT . '/core/lib/ajax.lib.php'; + include_once DOL_DOCUMENT_ROOT.'/core/lib/ajax.lib.php'; $out .= ajax_combobox($htmlname); } - $out.='"; + $out .= ""; return $out; } @@ -6240,16 +6251,16 @@ class Form global $delayedhtmlcontent; // TODO Use an internal dolibarr component instead of select2 - if (empty($conf->global->MAIN_USE_JQUERY_MULTISELECT) && ! defined('REQUIRE_JQUERY_MULTISELECT')) return ''; + if (empty($conf->global->MAIN_USE_JQUERY_MULTISELECT) && !defined('REQUIRE_JQUERY_MULTISELECT')) return ''; - $out=''; + $out = ''; - $tmpplugin='select2'; - $outdelayed="\n".' + $tmpplugin = 'select2'; + $outdelayed = "\n".' '; if ($acceptdelayedhtml) { - $delayedhtmlcontent.=$outdelayed; + $delayedhtmlcontent .= $outdelayed; } else { - $out.=$outdelayed; + $out .= $outdelayed; } return $out; } @@ -6342,13 +6353,13 @@ class Form global $delayedhtmlcontent; // TODO Use an internal dolibarr component instead of select2 - if (empty($conf->global->MAIN_USE_JQUERY_MULTISELECT) && ! defined('REQUIRE_JQUERY_MULTISELECT')) return ''; + if (empty($conf->global->MAIN_USE_JQUERY_MULTISELECT) && !defined('REQUIRE_JQUERY_MULTISELECT')) return ''; - $out=''; + $out = ''; $formattedarrayresult = array(); - foreach($array as $key => $value) { + foreach ($array as $key => $value) { $o = new stdClass(); $o->id = $key; $o->text = $value['text']; @@ -6356,13 +6367,13 @@ class Form $formattedarrayresult[] = $o; } - $tmpplugin='select2'; - $outdelayed="\n".' + $tmpplugin = 'select2'; + $outdelayed = "\n".' '; if ($acceptdelayedhtml) { - $delayedhtmlcontent.=$outdelayed; + $delayedhtmlcontent .= $outdelayed; } else { - $out.=$outdelayed; + $out .= $outdelayed; } return $out; } @@ -6466,36 +6477,36 @@ class Form } // Add code for jquery to use multiselect - if (! empty($conf->global->MAIN_USE_JQUERY_MULTISELECT) || defined('REQUIRE_JQUERY_MULTISELECT')) + if (!empty($conf->global->MAIN_USE_JQUERY_MULTISELECT) || defined('REQUIRE_JQUERY_MULTISELECT')) { - $out.="\n".' + $out .= "\n".' '; + $out .= ''; } // Try also magic suggest - $out .= ''."\n"; + if (is_array($array) && !empty($array)) { - if ($value_as_key) $array=array_combine($array, $array); + if ($value_as_key) $array = array_combine($array, $array); - if (! empty($array)) + if (!empty($array)) { foreach ($array as $key => $value) { - $out.= ''."\n"; + $out .= dol_htmlentitiesbr($newval); + $out .= ''."\n"; } } } - $out.= ''."\n"; + $out .= ''."\n"; return $out; } @@ -6566,44 +6577,44 @@ class Form */ public static function multiSelectArrayWithCheckbox($htmlname, &$array, $varpage) { - global $conf,$langs,$user; + global $conf, $langs, $user; - if (! empty($conf->global->MAIN_OPTIMIZEFORTEXTBROWSER)) return ''; + if (!empty($conf->global->MAIN_OPTIMIZEFORTEXTBROWSER)) return ''; - $tmpvar="MAIN_SELECTEDFIELDS_".$varpage; - if (! empty($user->conf->$tmpvar)) + $tmpvar = "MAIN_SELECTEDFIELDS_".$varpage; + if (!empty($user->conf->$tmpvar)) { - $tmparray=explode(',', $user->conf->$tmpvar); - foreach($array as $key => $val) + $tmparray = explode(',', $user->conf->$tmpvar); + foreach ($array as $key => $val) { //var_dump($key); //var_dump($tmparray); - if (in_array($key, $tmparray)) $array[$key]['checked']=1; - else $array[$key]['checked']=0; + if (in_array($key, $tmparray)) $array[$key]['checked'] = 1; + else $array[$key]['checked'] = 0; } } - $lis=''; - $listcheckedstring=''; + $lis = ''; + $listcheckedstring = ''; - foreach($array as $key => $val) + foreach ($array as $key => $val) { /* var_dump($val); var_dump(array_key_exists('enabled', $val)); var_dump(!$val['enabled']);*/ - if (array_key_exists('enabled', $val) && isset($val['enabled']) && ! $val['enabled']) + if (array_key_exists('enabled', $val) && isset($val['enabled']) && !$val['enabled']) { - unset($array[$key]); // We don't want this field + unset($array[$key]); // We don't want this field continue; } if ($val['label']) { - $lis.='
  • '; - $listcheckedstring.=(empty($val['checked'])?'':$key.','); + $lis .= '
  • '; + $listcheckedstring .= (empty($val['checked']) ? '' : $key.','); } } - $out =' + $out = '
    '; print ''; - $nboftypesoutput=0; + $nboftypesoutput = 0; - foreach($object->linkedObjects as $objecttype => $objects) + foreach ($object->linkedObjects as $objecttype => $objects) { $tplpath = $element = $subelement = $objecttype; // to display inport button on tpl - $showImportButton=false; - if(!empty($compatibleImportElementsList) && in_array($element, $compatibleImportElementsList)){ - $showImportButton=true; + $showImportButton = false; + if (!empty($compatibleImportElementsList) && in_array($element, $compatibleImportElementsList)) { + $showImportButton = true; } $regs = array(); @@ -6751,47 +6762,47 @@ class Form $subelement = $regs[2]; $tplpath = $element.'/'.$subelement; } - $tplname='linkedobjectblock'; + $tplname = 'linkedobjectblock'; // To work with non standard path - if ($objecttype == 'facture') { + if ($objecttype == 'facture') { $tplpath = 'compta/'.$element; - if (empty($conf->facture->enabled)) continue; // Do not show if module disabled + if (empty($conf->facture->enabled)) continue; // Do not show if module disabled } - elseif ($objecttype == 'facturerec') { + elseif ($objecttype == 'facturerec') { $tplpath = 'compta/facture'; $tplname = 'linkedobjectblockForRec'; - if (empty($conf->facture->enabled)) continue; // Do not show if module disabled + if (empty($conf->facture->enabled)) continue; // Do not show if module disabled } - elseif ($objecttype == 'propal') { + elseif ($objecttype == 'propal') { $tplpath = 'comm/'.$element; - if (empty($conf->propal->enabled)) continue; // Do not show if module disabled + if (empty($conf->propal->enabled)) continue; // Do not show if module disabled } - elseif ($objecttype == 'supplier_proposal') { - if (empty($conf->supplier_proposal->enabled)) continue; // Do not show if module disabled + elseif ($objecttype == 'supplier_proposal') { + if (empty($conf->supplier_proposal->enabled)) continue; // Do not show if module disabled } elseif ($objecttype == 'shipping' || $objecttype == 'shipment') { $tplpath = 'expedition'; - if (empty($conf->expedition->enabled)) continue; // Do not show if module disabled + if (empty($conf->expedition->enabled)) continue; // Do not show if module disabled } elseif ($objecttype == 'reception') { $tplpath = 'reception'; - if (empty($conf->reception->enabled)) continue; // Do not show if module disabled + if (empty($conf->reception->enabled)) continue; // Do not show if module disabled } - elseif ($objecttype == 'delivery') { + elseif ($objecttype == 'delivery') { $tplpath = 'livraison'; - if (empty($conf->expedition->enabled)) continue; // Do not show if module disabled + if (empty($conf->expedition->enabled)) continue; // Do not show if module disabled } elseif ($objecttype == 'invoice_supplier') { $tplpath = 'fourn/facture'; } - elseif ($objecttype == 'order_supplier') { + elseif ($objecttype == 'order_supplier') { $tplpath = 'fourn/commande'; } - elseif ($objecttype == 'expensereport') { + elseif ($objecttype == 'expensereport') { $tplpath = 'expensereport'; } - elseif ($objecttype == 'subscription') { + elseif ($objecttype == 'subscription') { $tplpath = 'adherents'; } @@ -6800,16 +6811,16 @@ class Form // Output template part (modules that overwrite templates must declare this into descriptor) - $dirtpls=array_merge($conf->modules_parts['tpl'], array('/'.$tplpath.'/tpl')); - foreach($dirtpls as $reldir) + $dirtpls = array_merge($conf->modules_parts['tpl'], array('/'.$tplpath.'/tpl')); + foreach ($dirtpls as $reldir) { if ($nboftypesoutput == ($nbofdifferenttypes - 1)) // No more type to show after { global $noMoreLinkedObjectBlockAfter; - $noMoreLinkedObjectBlockAfter=1; + $noMoreLinkedObjectBlockAfter = 1; } - $res=@include dol_buildpath($reldir.'/'.$tplname.'.tpl.php'); + $res = @include dol_buildpath($reldir.'/'.$tplname.'.tpl.php'); if ($res) { $nboftypesoutput++; @@ -6818,7 +6829,7 @@ class Form } } - if (! $nboftypesoutput) + if (!$nboftypesoutput) { print ''; } @@ -6827,7 +6838,7 @@ class Form if (!empty($compatibleImportElementsList)) { - $res=@include dol_buildpath('core/tpl/ajax/objectlinked_lineimport.tpl.php'); + $res = @include dol_buildpath('core/tpl/ajax/objectlinked_lineimport.tpl.php'); } @@ -6850,73 +6861,73 @@ class Form global $conf, $langs, $hookmanager; global $bc, $action; - $linktoelem=''; - $linktoelemlist=''; - $listofidcompanytoscan=''; + $linktoelem = ''; + $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) + $possiblelinks = array(); + 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)) + $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)) { include_once DOL_DOCUMENT_ROOT.'/projet/class/project.class.php'; - $tmpproject=new Project($this->db); + $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); } - $possiblelinks=array( + $possiblelinks = array( 'propal'=>array('enabled'=>$conf->propal->enabled, 'perms'=>1, 'label'=>'LinkToProposal', 'sql'=>"SELECT s.rowid as socid, s.nom as name, s.client, t.rowid, t.ref, t.ref_client, t.total_ht FROM ".MAIN_DB_PREFIX."societe as s, ".MAIN_DB_PREFIX."propal as t WHERE t.fk_soc = s.rowid AND t.fk_soc IN (".$listofidcompanytoscan.') AND t.entity IN ('.getEntity('propal').')'), 'order'=>array('enabled'=>$conf->commande->enabled, 'perms'=>1, 'label'=>'LinkToOrder', 'sql'=>"SELECT s.rowid as socid, s.nom as name, s.client, t.rowid, t.ref, t.ref_client, t.total_ht FROM ".MAIN_DB_PREFIX."societe as s, ".MAIN_DB_PREFIX."commande as t WHERE t.fk_soc = s.rowid AND t.fk_soc IN (".$listofidcompanytoscan.') AND t.entity IN ('.getEntity('commande').')'), 'invoice'=>array('enabled'=>$conf->facture->enabled, 'perms'=>1, 'label'=>'LinkToInvoice', 'sql'=>"SELECT s.rowid as socid, s.nom as name, s.client, t.rowid, t.ref, t.ref_client, t.total as total_ht FROM ".MAIN_DB_PREFIX."societe as s, ".MAIN_DB_PREFIX."facture as t WHERE t.fk_soc = s.rowid AND t.fk_soc IN (".$listofidcompanytoscan.') AND t.entity IN ('.getEntity('invoice').')'), 'invoice_template'=>array('enabled'=>$conf->facture->enabled, 'perms'=>1, 'label'=>'LinkToTemplateInvoice', 'sql'=>"SELECT s.rowid as socid, s.nom as name, s.client, t.rowid, t.titre as ref, t.total as total_ht FROM ".MAIN_DB_PREFIX."societe as s, ".MAIN_DB_PREFIX."facture_rec as t WHERE t.fk_soc = s.rowid AND t.fk_soc IN (".$listofidcompanytoscan.') AND t.entity IN ('.getEntity('invoice').')'), - 'contrat'=>array('enabled'=>$conf->contrat->enabled , 'perms'=>1, 'label'=>'LinkToContract', 'sql'=>"SELECT s.rowid as socid, s.nom as name, s.client, t.rowid, t.ref, t.ref_supplier, '' as total_ht FROM ".MAIN_DB_PREFIX."societe as s, ".MAIN_DB_PREFIX."contrat as t WHERE t.fk_soc = s.rowid AND t.fk_soc IN (".$listofidcompanytoscan.') AND t.entity IN ('.getEntity('contract').')'), + 'contrat'=>array('enabled'=>$conf->contrat->enabled, 'perms'=>1, 'label'=>'LinkToContract', 'sql'=>"SELECT s.rowid as socid, s.nom as name, s.client, t.rowid, t.ref, t.ref_supplier, '' as total_ht FROM ".MAIN_DB_PREFIX."societe as s, ".MAIN_DB_PREFIX."contrat as t WHERE t.fk_soc = s.rowid AND t.fk_soc IN (".$listofidcompanytoscan.') AND t.entity IN ('.getEntity('contract').')'), 'fichinter'=>array('enabled'=>$conf->ficheinter->enabled, 'perms'=>1, 'label'=>'LinkToIntervention', 'sql'=>"SELECT s.rowid as socid, s.nom as name, s.client, t.rowid, t.ref FROM ".MAIN_DB_PREFIX."societe as s, ".MAIN_DB_PREFIX."fichinter as t WHERE t.fk_soc = s.rowid AND t.fk_soc IN (".$listofidcompanytoscan.') AND t.entity IN ('.getEntity('intervention').')'), - 'supplier_proposal'=>array('enabled'=>$conf->supplier_proposal->enabled , 'perms'=>1, 'label'=>'LinkToSupplierProposal', 'sql'=>"SELECT s.rowid as socid, s.nom as name, s.client, t.rowid, t.ref, '' as ref_supplier, t.total_ht FROM ".MAIN_DB_PREFIX."societe as s, ".MAIN_DB_PREFIX."supplier_proposal as t WHERE t.fk_soc = s.rowid AND t.fk_soc IN (".$listofidcompanytoscan.') AND t.entity IN ('.getEntity('supplier_proposal').')'), - 'order_supplier'=>array('enabled'=>$conf->supplier_order->enabled , 'perms'=>1, 'label'=>'LinkToSupplierOrder', 'sql'=>"SELECT s.rowid as socid, s.nom as name, s.client, t.rowid, t.ref, t.ref_supplier, t.total_ht FROM ".MAIN_DB_PREFIX."societe as s, ".MAIN_DB_PREFIX."commande_fournisseur as t WHERE t.fk_soc = s.rowid AND t.fk_soc IN (".$listofidcompanytoscan.') AND t.entity IN ('.getEntity('commande_fournisseur').')'), - 'invoice_supplier'=>array('enabled'=>$conf->supplier_invoice->enabled , 'perms'=>1, 'label'=>'LinkToSupplierInvoice', 'sql'=>"SELECT s.rowid as socid, s.nom as name, s.client, t.rowid, t.ref, t.ref_supplier, t.total_ht FROM ".MAIN_DB_PREFIX."societe as s, ".MAIN_DB_PREFIX."facture_fourn as t WHERE t.fk_soc = s.rowid AND t.fk_soc IN (".$listofidcompanytoscan.') AND t.entity IN ('.getEntity('facture_fourn').')'), - 'ticket'=>array('enabled'=>$conf->ticket->enabled , 'perms'=>1, 'label'=>'LinkToTicket', 'sql'=>"SELECT s.rowid as socid, s.nom as name, s.client, t.rowid, t.ref, t.track_id, '0' as total_ht FROM ".MAIN_DB_PREFIX."societe as s, ".MAIN_DB_PREFIX."ticket as t WHERE t.fk_soc = s.rowid AND t.fk_soc IN (".$listofidcompanytoscan.') AND t.entity IN ('.getEntity('ticket').')') + 'supplier_proposal'=>array('enabled'=>$conf->supplier_proposal->enabled, 'perms'=>1, 'label'=>'LinkToSupplierProposal', 'sql'=>"SELECT s.rowid as socid, s.nom as name, s.client, t.rowid, t.ref, '' as ref_supplier, t.total_ht FROM ".MAIN_DB_PREFIX."societe as s, ".MAIN_DB_PREFIX."supplier_proposal as t WHERE t.fk_soc = s.rowid AND t.fk_soc IN (".$listofidcompanytoscan.') AND t.entity IN ('.getEntity('supplier_proposal').')'), + 'order_supplier'=>array('enabled'=>$conf->supplier_order->enabled, 'perms'=>1, 'label'=>'LinkToSupplierOrder', 'sql'=>"SELECT s.rowid as socid, s.nom as name, s.client, t.rowid, t.ref, t.ref_supplier, t.total_ht FROM ".MAIN_DB_PREFIX."societe as s, ".MAIN_DB_PREFIX."commande_fournisseur as t WHERE t.fk_soc = s.rowid AND t.fk_soc IN (".$listofidcompanytoscan.') AND t.entity IN ('.getEntity('commande_fournisseur').')'), + 'invoice_supplier'=>array('enabled'=>$conf->supplier_invoice->enabled, 'perms'=>1, 'label'=>'LinkToSupplierInvoice', 'sql'=>"SELECT s.rowid as socid, s.nom as name, s.client, t.rowid, t.ref, t.ref_supplier, t.total_ht FROM ".MAIN_DB_PREFIX."societe as s, ".MAIN_DB_PREFIX."facture_fourn as t WHERE t.fk_soc = s.rowid AND t.fk_soc IN (".$listofidcompanytoscan.') AND t.entity IN ('.getEntity('facture_fourn').')'), + 'ticket'=>array('enabled'=>$conf->ticket->enabled, 'perms'=>1, 'label'=>'LinkToTicket', 'sql'=>"SELECT s.rowid as socid, s.nom as name, s.client, t.rowid, t.ref, t.track_id, '0' as total_ht FROM ".MAIN_DB_PREFIX."societe as s, ".MAIN_DB_PREFIX."ticket as t WHERE t.fk_soc = s.rowid AND t.fk_soc IN (".$listofidcompanytoscan.') AND t.entity IN ('.getEntity('ticket').')') ); } // Can complete the possiblelink array $hookmanager->initHooks(array('commonobject')); - $parameters=array('listofidcompanytoscan' => $listofidcompanytoscan); + $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 + $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)) { - $possiblelinks=array_merge($possiblelinks, $hookmanager->resArray); + $possiblelinks = array_merge($possiblelinks, $hookmanager->resArray); } } elseif ($reshook > 0) { if (is_array($hookmanager->resArray) && count($hookmanager->resArray)) { - $possiblelinks=$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['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"').'>'; + print '
    use_javascript_ajax) ? '' : ' style="display:none"').'>'; $sql = $possiblelink['sql']; $resqllist = $this->db->query($sql); @@ -6934,10 +6945,10 @@ class Form print '
    '; - $num=$this->select_contacts($societe->id, $selected, $htmlname); - if ($num==0) + $num = $this->select_contacts($societe->id, $selected, $htmlname); + if ($num == 0) { - $addcontact = (! empty($conf->global->SOCIETE_ADDRESSES_MANAGEMENT) ? $langs->trans("AddContact") : $langs->trans("AddContactAddress")); + $addcontact = (!empty($conf->global->SOCIETE_ADDRESSES_MANAGEMENT) ? $langs->trans("AddContact") : $langs->trans("AddContactAddress")); print ''.$addcontact.''; } print '
    '.$langs->trans("None").'
    '; print ''; print ''; - print ''; - print ''; - print ''; - print ''; + print ''; + print ''; + print ''; + print ''; print ''; while ($i < $num) { @@ -6945,17 +6956,17 @@ class Form print ''; print ''; - print ''; - print ''; - print ''; - print ''; + print ''; + print ''; + print ''; + print ''; print ''; $i++; } print '
    ' . $langs->trans("Ref") . '' . $langs->trans("RefCustomer") . '' . $langs->trans("AmountHTShort") . '' . $langs->trans("Company") . ''.$langs->trans("Ref").''.$langs->trans("RefCustomer").''.$langs->trans("AmountHTShort").''.$langs->trans("Company").'
    '; - print ''; + print ''; print '' . $objp->ref . '' . $objp->ref_client . '' . price($objp->total_ht) . '' . $objp->name . ''.$objp->ref.''.$objp->ref_client.''.price($objp->total_ht).''.$objp->name.'
    '; - print '
         
    '; + print '
         
    '; print ''; $this->db->free($resqllist); @@ -6968,19 +6979,19 @@ class Form } //$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) { - $linktoelem=' + $linktoelem = ' '; - if (! $found) $out=''; + if (!$found) $out = ''; } else { @@ -1098,21 +1098,21 @@ class FormFile if ($disablecrop == -1) { - $disablecrop=1; - if (in_array($modulepart, array('bank','bom','expensereport','holiday','member','project','product','produit','service','societe','tax','ticket','user'))) $disablecrop=0; + $disablecrop = 1; + if (in_array($modulepart, array('bank', 'bom', 'expensereport', 'holiday', 'member', 'project', 'product', 'produit', 'service', 'societe', 'tax', 'ticket', 'user'))) $disablecrop = 0; } // Define relative path used to store the file if (empty($relativepath)) { - $relativepath=(! empty($object->ref)?dol_sanitizeFileName($object->ref):'').'/'; - if ($object->element == 'invoice_supplier') $relativepath=get_exdir($object->id, 2, 0, 0, $object, 'invoice_supplier').$relativepath; // TODO Call using a defined value for $relativepath - if ($object->element == 'project_task') $relativepath='Call_not_supported_._Call_function_using_a_defined_relative_path_.'; + $relativepath = (!empty($object->ref) ?dol_sanitizeFileName($object->ref) : '').'/'; + if ($object->element == 'invoice_supplier') $relativepath = get_exdir($object->id, 2, 0, 0, $object, 'invoice_supplier').$relativepath; // TODO Call using a defined value for $relativepath + if ($object->element == 'project_task') $relativepath = 'Call_not_supported_._Call_function_using_a_defined_relative_path_.'; } // For backward compatiblity, we detect file stored into an old path - if (! empty($conf->global->PRODUCT_USE_OLD_PATH_FOR_PHOTO) && $filearray[0]['level1name'] == 'photos') + if (!empty($conf->global->PRODUCT_USE_OLD_PATH_FOR_PHOTO) && $filearray[0]['level1name'] == 'photos') { - $relativepath=preg_replace('/^.*\/produit\//', '', $filearray[0]['path']).'/'; + $relativepath = preg_replace('/^.*\/produit\//', '', $filearray[0]['path']).'/'; } // Defined relative dir to DOL_DATA_ROOT $relativedir = ''; @@ -1123,13 +1123,13 @@ class FormFile } $hookmanager->initHooks(array('formfile')); - $parameters=array( + $parameters = array( 'filearray' => $filearray, 'modulepart'=> $modulepart, 'param' => $param, 'forcedownload' => $forcedownload, - 'relativepath' => $relativepath, // relative filename to module dir - 'relativedir' => $relativedir, // relative dirname to DOL_DATA_ROOT + 'relativepath' => $relativepath, // relative filename to module dir + 'relativedir' => $relativedir, // relative dirname to DOL_DATA_ROOT 'permtodelete' => $permonobject, 'useinecm' => $useinecm, 'textifempty' => $textifempty, @@ -1137,7 +1137,7 @@ class FormFile 'title' => $title, 'url' => $url ); - $reshook=$hookmanager->executeHooks('showFilesList', $parameters, $object); + $reshook = $hookmanager->executeHooks('showFilesList', $parameters, $object); if (isset($reshook) && $reshook != '') // null or '' for bypass { @@ -1145,34 +1145,34 @@ class FormFile } else { - if (! is_object($form)) + if (!is_object($form)) { - include_once DOL_DOCUMENT_ROOT.'/core/class/html.form.class.php'; // The compoent may be included into ajax page that does not include the Form class - $form=new Form($this->db); + include_once DOL_DOCUMENT_ROOT.'/core/class/html.form.class.php'; // The compoent may be included into ajax page that does not include the Form class + $form = new Form($this->db); } - if (! preg_match('/&id=/', $param) && isset($object->id)) $param.='&id='.$object->id; - $relativepathwihtoutslashend=preg_replace('/\/$/', '', $relativepath); - if ($relativepathwihtoutslashend) $param.= '&file='.urlencode($relativepathwihtoutslashend); + if (!preg_match('/&id=/', $param) && isset($object->id)) $param .= '&id='.$object->id; + $relativepathwihtoutslashend = preg_replace('/\/$/', '', $relativepath); + if ($relativepathwihtoutslashend) $param .= '&file='.urlencode($relativepathwihtoutslashend); if ($permtoeditline < 0) // Old behaviour for backward compatibility. New feature should call method with value 0 or 1 { - $permtoeditline=0; - if (in_array($modulepart, array('product','produit','service'))) + $permtoeditline = 0; + if (in_array($modulepart, array('product', 'produit', 'service'))) { - if ($user->rights->produit->creer && $object->type == Product::TYPE_PRODUCT) $permtoeditline=1; - if ($user->rights->service->creer && $object->type == Product::TYPE_SERVICE) $permtoeditline=1; + if ($user->rights->produit->creer && $object->type == Product::TYPE_PRODUCT) $permtoeditline = 1; + if ($user->rights->service->creer && $object->type == Product::TYPE_SERVICE) $permtoeditline = 1; } } if (empty($conf->global->MAIN_UPLOAD_DOC)) { - $permtoeditline=0; - $permonobject=0; + $permtoeditline = 0; + $permonobject = 0; } // Show list of existing files - if ((empty($useinecm) || $useinecm == 6) && $title != 'none') print load_fiche_titre($title?$title:$langs->trans("AttachedFiles")); - if (empty($url)) $url=$_SERVER["PHP_SELF"]; + if ((empty($useinecm) || $useinecm == 6) && $title != 'none') print load_fiche_titre($title ? $title : $langs->trans("AttachedFiles")); + if (empty($url)) $url = $_SERVER["PHP_SELF"]; print ''."\n"; if (GETPOST('action', 'aZ09') == 'editfile' && $permtoeditline) @@ -1187,7 +1187,7 @@ class FormFile print '
    '; print ''."\n"; - if (! empty($addfilterfields)) + if (!empty($addfilterfields)) { print ''; print ''; @@ -1196,7 +1196,7 @@ class FormFile if (empty($useinecm) || $useinecm == 4 || $useinecm == 5 || $useinecm == 6) print ''; print ''; print ''; - if (! $disablemove) print ''; + if (!$disablemove) print ''; print "\n"; } @@ -1205,10 +1205,10 @@ class FormFile print_liste_field_titre('Documents2', $url, "name", "", $param, '', $sortfield, $sortorder, 'left '); print_liste_field_titre('Size', $url, "size", "", $param, '', $sortfield, $sortorder, 'right '); print_liste_field_titre('Date', $url, "date", "", $param, '', $sortfield, $sortorder, 'center '); - if (empty($useinecm) || $useinecm == 4 || $useinecm == 5 || $useinecm == 6) print_liste_field_titre('', $url, "", "", $param, '', $sortfield, $sortorder, 'center '); // Preview + if (empty($useinecm) || $useinecm == 4 || $useinecm == 5 || $useinecm == 6) print_liste_field_titre('', $url, "", "", $param, '', $sortfield, $sortorder, 'center '); // Preview print_liste_field_titre(''); print_liste_field_titre(''); - if (! $disablemove) print_liste_field_titre(''); + if (!$disablemove) print_liste_field_titre(''); print "\n"; // Get list of files stored into database for same relative directory @@ -1219,29 +1219,29 @@ class FormFile //var_dump($sortfield.' - '.$sortorder); if ($sortfield && $sortorder) // If $sortfield is for example 'position_name', we will sort on the property 'position_name' (that is concat of position+name) { - $filearray=dol_sort_array($filearray, $sortfield, $sortorder); + $filearray = dol_sort_array($filearray, $sortfield, $sortorder); } } - $nboffiles=count($filearray); + $nboffiles = count($filearray); if ($nboffiles > 0) include_once DOL_DOCUMENT_ROOT.'/core/lib/images.lib.php'; - $i=0; $nboflines = 0; $lastrowid=0; - foreach($filearray as $key => $file) // filearray must be only files here + $i = 0; $nboflines = 0; $lastrowid = 0; + foreach ($filearray as $key => $file) // filearray must be only files here { if ($file['name'] != '.' && $file['name'] != '..' - && ! preg_match('/\.meta$/i', $file['name'])) + && !preg_match('/\.meta$/i', $file['name'])) { if ($filearray[$key]['rowid'] > 0) $lastrowid = $filearray[$key]['rowid']; - $filepath=$relativepath.$file['name']; + $filepath = $relativepath.$file['name']; - $editline=0; + $editline = 0; $nboflines++; print ''."\n"; // Do we have entry into database ? print ''."\n"; - print ''; + print ''; // File name print '\n"; @@ -1287,10 +1287,10 @@ class FormFile print ''; // Date - print ''; // 140px = width for date with PM format + print ''; // 140px = width for date with PM format // Preview - if (empty($useinecm) || $useinecm == 4 || $useinecm == 5|| $useinecm == 6) + if (empty($useinecm) || $useinecm == 4 || $useinecm == 5 || $useinecm == 6) { $fileinfo = pathinfo($file['name']); print ''; // Actions buttons - if (! $editline) + if (!$editline) { // Delete or view link // ($param must start with &) @@ -1370,10 +1370,10 @@ class FormFile } if (empty($useinecm) || $useinecm == 2 || $useinecm == 6) { - $newmodulepart=$modulepart; - if (in_array($modulepart, array('product','produit','service'))) $newmodulepart='produit|service'; + $newmodulepart = $modulepart; + if (in_array($modulepart, array('product', 'produit', 'service'))) $newmodulepart = 'produit|service'; - if (! $disablecrop && image_format_supported($file['name']) > 0) + if (!$disablecrop && image_format_supported($file['name']) > 0) { if ($permtoeditline) { @@ -1384,17 +1384,17 @@ class FormFile if ($permtoeditline) { - $paramsectiondir=(in_array($modulepart, array('medias','ecm'))?'§ion_dir='.urlencode($relativepath):''); - print ''.img_edit('default', 0, 'class="paddingrightonly"').''; + $paramsectiondir = (in_array($modulepart, array('medias', 'ecm')) ? '§ion_dir='.urlencode($relativepath) : ''); + print ''.img_edit('default', 0, 'class="paddingrightonly"').''; } } if ($permonobject) { - $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; - print ''.img_delete().''; + $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; + print ''.img_delete().''; } print ""; @@ -1405,13 +1405,13 @@ class FormFile if ($i > 0) { print 'id.'">'.img_up('default', 0, 'imgupforline').''; } - if ($i < $nboffiles-1) { + if ($i < $nboffiles - 1) { print 'id.'">'.img_down('default', 0, 'imgdownforline').''; } print ''; } else { - print 'browser->layout != 'phone' && empty($disablemove)) ?' class="linecolmove tdlineupdown center"':' class="linecolmove center"').'>'; + print 'browser->layout != 'phone' && empty($disablemove)) ? ' class="linecolmove tdlineupdown center"' : ' class="linecolmove center"').'>'; print ''; } } @@ -1432,8 +1432,8 @@ class FormFile } if ($nboffiles == 0) { - $colspan='6'; - if (empty($disablemove)) $colspan++; // 6 columns or 7 + $colspan = '6'; + if (empty($disablemove)) $colspan++; // 6 columns or 7 print ''; @@ -1610,16 +1610,14 @@ if ($action=='create') print ''; print ''; - print ''; - // Payment term - print ''; // Payment mode - print ''; // Planned delivery date @@ -1627,30 +1625,29 @@ if ($action=='create') print $langs->trans('DateDeliveryPlanned'); print ''; print ''; // 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 ''; } // Project - if (! empty($conf->projet->enabled)) + if (!empty($conf->projet->enabled)) { $formproject = new FormProjets($db); $langs->load('projects'); - print ''; } @@ -1659,17 +1656,17 @@ if ($action=='create') { print ''; print ''; - print ''; } // Multicurrency - if (! empty($conf->multicurrency->enabled)) + if (!empty($conf->multicurrency->enabled)) { print ''; print ''; - print ''; } @@ -1690,42 +1687,42 @@ if ($action=='create') //print ''; print ''; - if (! empty($origin) && ! empty($originid) && is_object($objectsrc)) { - print "\n"; + if (!empty($origin) && !empty($originid) && is_object($objectsrc)) { + print "\n"; print "\n"; - print '' . "\n"; - print '' . "\n"; - print '' . "\n"; - print ''; - print ''; + print ''."\n"; + print ''."\n"; + print ''."\n"; + print ''; + print ''; $newclassname = $classname; - print ''; - print ''; - print '"; + print ''; + print ''; + print '"; if ($mysoc->localtax1_assuj == "1" || $objectsrc->total_localtax1 != 0) // Localtax1 RE { - print '"; + print '"; } if ($mysoc->localtax2_assuj == "1" || $objectsrc->total_localtax2 != 0) // Localtax2 IRPF { - print '"; + print '"; } - print '"; + print '"; if (!empty($conf->multicurrency->enabled)) { - print ''; - print ''; - print ''; + print ''; + print ''; + print ''; } } // Other options - $parameters=array(); - $reshook=$hookmanager->executeHooks('formObjectOptions', $parameters, $object, $action); // Note that $action and $object may have been modified by hook + $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)) @@ -1741,13 +1738,13 @@ if ($action=='create') print '
    '; print ''; print '     '; - print ''; + print ''; print '
    '; print "\n"; // 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); @@ -1759,30 +1756,30 @@ if ($action=='create') print '
    '; @@ -1250,7 +1250,7 @@ class FormFile //print "XX".$file['name']; //$file['name'] must be utf8 print ''; print img_mime($file['name'], $file['name'].' ('.dol_print_size($file['size'], 0, 0).')', 'inline-block valignbottom paddingright'); @@ -1259,11 +1259,11 @@ class FormFile if (GETPOST('action', 'aZ09') == 'editfile' && $file['name'] == basename(GETPOST('urlfile', 'alpha'))) { print ''; - $section_dir=dirname(GETPOST('urlfile', 'alpha')); + $section_dir = dirname(GETPOST('urlfile', 'alpha')); print ''; print ''; print ''; - $editline=1; + $editline = 1; } else { @@ -1271,7 +1271,7 @@ class FormFile print ''; } // Preview link - if (! $editline) print $this->showPreview($file, $modulepart, $filepath, 0, '&entity='.(! empty($object->entity)?$object->entity:$conf->entity)); + if (!$editline) print $this->showPreview($file, $modulepart, $filepath, 0, '&entity='.(!empty($object->entity) ? $object->entity : $conf->entity)); print "'.dol_print_date($file['date'], "dayhour", "tzuser").''.dol_print_date($file['date'], "dayhour", "tzuser").''; @@ -1298,23 +1298,23 @@ class FormFile { if ($useinecm == 5 || $useinecm == 6) { - $smallfile=getImageFileNameForSize($file['name'], ''); // There is no thumb for ECM module and Media filemanager, so we use true image + $smallfile = getImageFileNameForSize($file['name'], ''); // There is no thumb for ECM module and Media filemanager, so we use true image } else { - $smallfile=getImageFileNameForSize($file['name'], '_small'); // For new thumbs using same ext (in lower case however) than original + $smallfile = getImageFileNameForSize($file['name'], '_small'); // For new thumbs using same ext (in lower case however) than original } - if (! dol_is_file($file['path'].'/'.$smallfile)) $smallfile=getImageFileNameForSize($file['name'], '_small', '.png'); // For backward compatibility of old thumbs that were created with filename in lower case and with .png extension + if (!dol_is_file($file['path'].'/'.$smallfile)) $smallfile = getImageFileNameForSize($file['name'], '_small', '.png'); // For backward compatibility of old thumbs that were created with filename in lower case and with .png extension //print $file['path'].'/'.$smallfile.'
    '; - $urlforhref=getAdvancedPreviewUrl($modulepart, $relativepath.$fileinfo['filename'].'.'.strtolower($fileinfo['extension']), 1, '&entity='.(!empty($object->entity)?$object->entity:$conf->entity)); + $urlforhref = getAdvancedPreviewUrl($modulepart, $relativepath.$fileinfo['filename'].'.'.strtolower($fileinfo['extension']), 1, '&entity='.(!empty($object->entity) ? $object->entity : $conf->entity)); if (empty($urlforhref)) { - $urlforhref=DOL_URL_ROOT.'/viewimage.php?modulepart='.$modulepart.'&entity='.(!empty($object->entity)?$object->entity:$conf->entity).'&file='.urlencode($relativepath.$fileinfo['filename'].'.'.strtolower($fileinfo['extension'])); + $urlforhref = DOL_URL_ROOT.'/viewimage.php?modulepart='.$modulepart.'&entity='.(!empty($object->entity) ? $object->entity : $conf->entity).'&file='.urlencode($relativepath.$fileinfo['filename'].'.'.strtolower($fileinfo['extension'])); print ''; } else { print ''; } - print ''; + print ''; print ''; } else print ' '; @@ -1328,24 +1328,24 @@ class FormFile if ($editline) { print $langs->trans("FileSharedViaALink").' '; - print ' '; + print ' '; } else { if ($file['share']) { // Define $urlwithroot - $urlwithouturlroot=preg_replace('/'.preg_quote(DOL_URL_ROOT, '/').'$/i', '', trim($dolibarr_main_url_root)); - $urlwithroot=$urlwithouturlroot.DOL_URL_ROOT; // This is to use external domain name found into config file + $urlwithouturlroot = preg_replace('/'.preg_quote(DOL_URL_ROOT, '/').'$/i', '', trim($dolibarr_main_url_root)); + $urlwithroot = $urlwithouturlroot.DOL_URL_ROOT; // This is to use external domain name found into config file //$urlwithroot=DOL_MAIN_URL_ROOT; // This is to use same domain name than current //print ''.$langs->trans("Hash").' : '.$file['share'].''; - $forcedownload=0; - $paramlink=''; - if (! empty($file['share'])) $paramlink.=($paramlink?'&':'').'hashp='.$file['share']; // Hash for public share - if ($forcedownload) $paramlink.=($paramlink?'&':'').'attachment=1'; + $forcedownload = 0; + $paramlink = ''; + if (!empty($file['share'])) $paramlink .= ($paramlink ? '&' : '').'hashp='.$file['share']; // Hash for public share + if ($forcedownload) $paramlink .= ($paramlink ? '&' : '').'attachment=1'; - $fulllink=$urlwithroot.'/document.php'.($paramlink?'?'.$paramlink:''); + $fulllink = $urlwithroot.'/document.php'.($paramlink ? '?'.$paramlink : ''); print img_picto($langs->trans("FileSharedViaALink"), 'globe').' '; print ''; @@ -1359,7 +1359,7 @@ class FormFile print '
    '; if (empty($textifempty)) print $langs->trans("NoFileFound"); else print $textifempty; @@ -1443,9 +1443,9 @@ class FormFile print ''; if ($nboflines > 1 && is_object($object)) { - if (! empty($conf->use_javascript_ajax) && $permtoeditline) { + if (!empty($conf->use_javascript_ajax) && $permtoeditline) { $table_element_line = 'ecm_files'; - include DOL_DOCUMENT_ROOT . '/core/tpl/ajaxrow.tpl.php'; + include DOL_DOCUMENT_ROOT.'/core/tpl/ajaxrow.tpl.php'; } } @@ -1491,9 +1491,9 @@ class FormFile // Show list of documents if (empty($useinecm) || $useinecm == 6) print load_fiche_titre($langs->trans("AttachedFiles")); - if (empty($url)) $url=$_SERVER["PHP_SELF"]; + if (empty($url)) $url = $_SERVER["PHP_SELF"]; - if (! empty($addfilterfields)) + if (!empty($addfilterfields)) { print '
    '; print ''; @@ -1503,7 +1503,7 @@ class FormFile print '
    '; print ''."\n"; - if (! empty($addfilterfields)) + if (!empty($addfilterfields)) { print ''; print ''; @@ -1512,15 +1512,15 @@ class FormFile print ''; // Action column print ''; print "\n"; } print ''; - $sortref="fullname"; - if ($modulepart == 'invoice_supplier') $sortref='level1name'; + $sortref = "fullname"; + if ($modulepart == 'invoice_supplier') $sortref = 'level1name'; print_liste_field_titre("Ref", $url, $sortref, "", $param, '', $sortfield, $sortorder); print_liste_field_titre("Documents2", $url, "name", "", $param, '', $sortfield, $sortorder); print_liste_field_titre("Size", $url, "size", "", $param, '', $sortfield, $sortorder, 'right '); @@ -1532,115 +1532,115 @@ class FormFile if ($modulepart == 'company') { include_once DOL_DOCUMENT_ROOT.'/societe/class/societe.class.php'; - $object_instance=new Societe($this->db); + $object_instance = new Societe($this->db); } elseif ($modulepart == 'invoice') { include_once DOL_DOCUMENT_ROOT.'/compta/facture/class/facture.class.php'; - $object_instance=new Facture($this->db); + $object_instance = new Facture($this->db); } elseif ($modulepart == 'invoice_supplier') { include_once DOL_DOCUMENT_ROOT.'/fourn/class/fournisseur.facture.class.php'; - $object_instance=new FactureFournisseur($this->db); + $object_instance = new FactureFournisseur($this->db); } elseif ($modulepart == 'propal') { include_once DOL_DOCUMENT_ROOT.'/comm/propal/class/propal.class.php'; - $object_instance=new Propal($this->db); + $object_instance = new Propal($this->db); } elseif ($modulepart == 'supplier_proposal') { include_once DOL_DOCUMENT_ROOT.'/supplier_proposal/class/supplier_proposal.class.php'; - $object_instance=new SupplierProposal($this->db); + $object_instance = new SupplierProposal($this->db); } elseif ($modulepart == 'order') { include_once DOL_DOCUMENT_ROOT.'/commande/class/commande.class.php'; - $object_instance=new Commande($this->db); + $object_instance = new Commande($this->db); } elseif ($modulepart == 'order_supplier') { include_once DOL_DOCUMENT_ROOT.'/fourn/class/fournisseur.commande.class.php'; - $object_instance=new CommandeFournisseur($this->db); + $object_instance = new CommandeFournisseur($this->db); } elseif ($modulepart == 'contract') { include_once DOL_DOCUMENT_ROOT.'/contrat/class/contrat.class.php'; - $object_instance=new Contrat($this->db); + $object_instance = new Contrat($this->db); } elseif ($modulepart == 'product') { include_once DOL_DOCUMENT_ROOT.'/product/class/product.class.php'; - $object_instance=new Product($this->db); + $object_instance = new Product($this->db); } elseif ($modulepart == 'tax') { include_once DOL_DOCUMENT_ROOT.'/compta/sociales/class/chargesociales.class.php'; - $object_instance=new ChargeSociales($this->db); + $object_instance = new ChargeSociales($this->db); } elseif ($modulepart == 'project') { include_once DOL_DOCUMENT_ROOT.'/projet/class/project.class.php'; - $object_instance=new Project($this->db); + $object_instance = new Project($this->db); } elseif ($modulepart == 'fichinter') { include_once DOL_DOCUMENT_ROOT.'/fichinter/class/fichinter.class.php'; - $object_instance=new Fichinter($this->db); + $object_instance = new Fichinter($this->db); } elseif ($modulepart == 'user') { include_once DOL_DOCUMENT_ROOT.'/user/class/user.class.php'; - $object_instance=new User($this->db); + $object_instance = new User($this->db); } elseif ($modulepart == 'expensereport') { include_once DOL_DOCUMENT_ROOT.'/expensereport/class/expensereport.class.php'; - $object_instance=new ExpenseReport($this->db); + $object_instance = new ExpenseReport($this->db); } elseif ($modulepart == 'holiday') { include_once DOL_DOCUMENT_ROOT.'/holiday/class/holiday.class.php'; - $object_instance=new Holiday($this->db); + $object_instance = new Holiday($this->db); } elseif ($modulepart == 'banque') { include_once DOL_DOCUMENT_ROOT.'/compta/bank/class/account.class.php'; - $object_instance=new Account($this->db); + $object_instance = new Account($this->db); } - foreach($filearray as $key => $file) + foreach ($filearray as $key => $file) { if (!is_dir($file['name']) && $file['name'] != '.' && $file['name'] != '..' && $file['name'] != 'CVS' - && ! preg_match('/\.meta$/i', $file['name'])) + && !preg_match('/\.meta$/i', $file['name'])) { // Define relative path used to store the file - $relativefile=preg_replace('/'.preg_quote($upload_dir.'/', '/').'/', '', $file['fullname']); + $relativefile = preg_replace('/'.preg_quote($upload_dir.'/', '/').'/', '', $file['fullname']); - $id=0; $ref=''; $label=''; + $id = 0; $ref = ''; $label = ''; // To show ref or specific information according to view to show (defined by $module) - if ($modulepart == 'company' || $modulepart == 'tax') { preg_match('/(\d+)\/[^\/]+$/', $relativefile, $reg); $id=(isset($reg[1])?$reg[1]:''); } - elseif ($modulepart == 'invoice_supplier') { preg_match('/([^\/]+)\/[^\/]+$/', $relativefile, $reg); $ref=(isset($reg[1])?$reg[1]:''); if (is_numeric($ref)) { $id=$ref; $ref=''; } } // $ref may be also id with old supplier invoices - elseif ($modulepart == 'user' || $modulepart == 'holiday') { preg_match('/(.*)\/[^\/]+$/', $relativefile, $reg); $id=(isset($reg[1])?$reg[1]:''); } + if ($modulepart == 'company' || $modulepart == 'tax') { preg_match('/(\d+)\/[^\/]+$/', $relativefile, $reg); $id = (isset($reg[1]) ? $reg[1] : ''); } + elseif ($modulepart == 'invoice_supplier') { preg_match('/([^\/]+)\/[^\/]+$/', $relativefile, $reg); $ref = (isset($reg[1]) ? $reg[1] : ''); if (is_numeric($ref)) { $id = $ref; $ref = ''; } } // $ref may be also id with old supplier invoices + elseif ($modulepart == 'user' || $modulepart == 'holiday') { preg_match('/(.*)\/[^\/]+$/', $relativefile, $reg); $id = (isset($reg[1]) ? $reg[1] : ''); } elseif (in_array($modulepart, array('invoice', 'propal', 'supplier_proposal', 'order', 'order_supplier', 'contract', 'product', 'project', 'fichinter', 'expensereport', 'banque'))) { - preg_match('/(.*)\/[^\/]+$/', $relativefile, $reg); $ref=(isset($reg[1])?$reg[1]:''); + preg_match('/(.*)\/[^\/]+$/', $relativefile, $reg); $ref = (isset($reg[1]) ? $reg[1] : ''); } else { //print 'Error: Value for modulepart = '.$modulepart.' is not yet implemented in function list_of_autoecmfiles'."\n"; } - if (! $id && ! $ref) continue; - $found=0; - if (! empty($this->cache_objects[$modulepart.'_'.$id.'_'.$ref])) + if (!$id && !$ref) continue; + $found = 0; + if (!empty($this->cache_objects[$modulepart.'_'.$id.'_'.$ref])) { - $found=1; + $found = 1; } else { @@ -1659,24 +1659,24 @@ class FormFile } if ($result > 0) { // Save object loaded into a cache - $found=1; $this->cache_objects[$modulepart.'_'.$id.'_'.$ref] = clone $object_instance; + $found = 1; $this->cache_objects[$modulepart.'_'.$id.'_'.$ref] = clone $object_instance; } - if ($result == 0) { $found=1; $this->cache_objects[$modulepart.'_'.$id.'_'.$ref]='notfound'; unset($filearray[$key]); } + if ($result == 0) { $found = 1; $this->cache_objects[$modulepart.'_'.$id.'_'.$ref] = 'notfound'; unset($filearray[$key]); } } - if (! $found > 0 || ! is_object($this->cache_objects[$modulepart.'_'.$id.'_'.$ref])) continue; // We do not show orphelins files + if (!$found > 0 || !is_object($this->cache_objects[$modulepart.'_'.$id.'_'.$ref])) continue; // We do not show orphelins files print ''."\n"; print ''; print '
    '; - $searchpicto=$form->showFilterButtons(); + $searchpicto = $form->showFilterButtons(); print $searchpicto; print '
    '; if ($found > 0 && is_object($this->cache_objects[$modulepart.'_'.$id.'_'.$ref])) print $this->cache_objects[$modulepart.'_'.$id.'_'.$ref]->getNomUrl(1, 'document'); - else print $langs->trans("ObjectDeleted", ($id?$id:$ref)); + else print $langs->trans("ObjectDeleted", ($id ? $id : $ref)); //$modulesubdir=dol_sanitizeFileName($ref); - $modulesubdir=dirname($relativefile); + $modulesubdir = dirname($relativefile); //$filedir=$conf->$modulepart->dir_output . '/' . dol_sanitizeFileName($obj->ref); - $filedir=$file['path']; + $filedir = $file['path']; //$urlsource=$_SERVER['PHP_SELF'].'?id='.$obj->rowid; //print $formfile->getDocumentsLink($modulepart, $filename, $filedir); @@ -1719,7 +1719,7 @@ class FormFile print "
    "; print '
    '; - if (! empty($addfilterfields)) print '
    '; + if (!empty($addfilterfields)) print ''; // Fin de zone } @@ -1745,7 +1745,7 @@ class FormFile $mul_upload_max_filesize = ($mul_upload_max_filesize == 'M' ? 1048576 : ($mul_upload_max_filesize == 'K' ? 1024 : ($mul_upload_max_filesize == 'G' ? 1073741824 : 1))); $upload_max_filesize = $mul_upload_max_filesize * (int) $upload_max_filesize; // Max file size - $max_file_size = (($post_max_size < $upload_max_filesize) ? $post_max_size : $upload_max_filesize); + $max_file_size = (($post_max_size < $upload_max_filesize) ? $post_max_size : $upload_max_filesize); // Include main include DOL_DOCUMENT_ROOT.'/core/tpl/ajax/fileupload_main.tpl.php'; @@ -1771,7 +1771,7 @@ class FormFile $langs->load("link"); - require_once DOL_DOCUMENT_ROOT . '/core/class/link.class.php'; + require_once DOL_DOCUMENT_ROOT.'/core/class/link.class.php'; $link = new Link($this->db); $links = array(); if ($sortfield == "name") { @@ -1782,14 +1782,14 @@ class FormFile $sortfield = null; } $res = $link->fetchAll($links, $object->element, $object->id, $sortfield, $sortorder); - $param .= (isset($object->id)?'&id=' . $object->id : ''); + $param .= (isset($object->id) ? '&id='.$object->id : ''); print ''."\n"; // Show list of associated links print load_fiche_titre($langs->trans("LinkedFiles")); - print '
    '; + print ''; print ''; print ''; @@ -1850,36 +1850,36 @@ class FormFile if ($action == 'update' && $selected === $link->id) { print ''; print ''; - print ''; + print ''; print ''; print ''; } else { print ''."\n"; print ''; - print ''; + print ''; print ''; 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); + $ret = $product->load_stats_propale($socid); if ($ret < 0) dol_print_error($db); $langs->load("propal"); 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); + $ret = $product->load_stats_proposal_supplier($socid); if ($ret < 0) dol_print_error($db); $langs->load("propal"); 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); + $ret = $product->load_stats_commande($socid); if ($ret < 0) dol_print_error($db); $langs->load("orders"); print ''; } // Supplier orders - if (! empty($conf->fournisseur->enabled) && $user->rights->fournisseur->commande->lire) + if (!empty($conf->fournisseur->enabled) && $user->rights->fournisseur->commande->lire) { $nblines++; - $ret=$product->load_stats_commande_fournisseur($socid); + $ret = $product->load_stats_commande_fournisseur($socid); if ($ret < 0) dol_print_error($db); $langs->load("orders"); 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); + $ret = $product->load_stats_facture($socid); if ($ret < 0) dol_print_error($db); $langs->load("bills"); print ''; } // Supplier invoices - if (! empty($conf->fournisseur->enabled) && $user->rights->fournisseur->facture->lire) + if (!empty($conf->fournisseur->enabled) && $user->rights->fournisseur->facture->lire) { $nblines++; - $ret=$product->load_stats_facture_fournisseur($socid); + $ret = $product->load_stats_facture_fournisseur($socid); if ($ret < 0) dol_print_error($db); $langs->load("bills"); print ''."\n"; - $projectstatic->id=$lines[$i]->fk_project; - $projectstatic->ref=$lines[$i]->projectref; - $projectstatic->public=$lines[$i]->public; - $projectstatic->title=$lines[$i]->projectlabel; - $projectstatic->usage_bill_time=$lines[$i]->usage_bill_time; + $projectstatic->id = $lines[$i]->fk_project; + $projectstatic->ref = $lines[$i]->projectref; + $projectstatic->public = $lines[$i]->public; + $projectstatic->title = $lines[$i]->projectlabel; + $projectstatic->usage_bill_time = $lines[$i]->usage_bill_time; - $taskstatic->id=$lines[$i]->id; - $taskstatic->ref=$lines[$i]->ref; - $taskstatic->label=($taskrole[$lines[$i]->id]?$langs->trans("YourRole").': '.$taskrole[$lines[$i]->id]:''); + $taskstatic->id = $lines[$i]->id; + $taskstatic->ref = $lines[$i]->ref; + $taskstatic->label = ($taskrole[$lines[$i]->id] ? $langs->trans("YourRole").': '.$taskrole[$lines[$i]->id] : ''); $taskstatic->projectstatus = $lines[$i]->projectstatus; $taskstatic->progress = $lines[$i]->progress; $taskstatic->fk_statut = $lines[$i]->status; $taskstatic->datee = $lines[$i]->date_end; - $taskstatic->planned_workload= $lines[$i]->planned_workload; - $taskstatic->duration_effective= $lines[$i]->duration; + $taskstatic->planned_workload = $lines[$i]->planned_workload; + $taskstatic->duration_effective = $lines[$i]->duration; if ($showproject) @@ -466,14 +466,14 @@ function projectLinesa(&$inc, $parent, &$lines, &$level, $var, $showproject, &$t // Project ref print ""; // Project status print '"; } @@ -494,12 +494,12 @@ function projectLinesa(&$inc, $parent, &$lines, &$level, $var, $showproject, &$t 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; + $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; // Planned Workload (in working hours) print '\n"; - if (! $showlineingray) $inc++; + if (!$showlineingray) $inc++; if ($level >= 0) // Call sublevels { @@ -662,7 +662,7 @@ function projectLinesa(&$inc, $parent, &$lines, &$level, $var, $showproject, &$t print convertSecondToTime($total_projectlinesa_planned, 'allhourmin'); print ''; print ''; @@ -680,13 +680,13 @@ function projectLinesa(&$inc, $parent, &$lines, &$level, $var, $showproject, &$t if ($totalCalculatedProgress > $totalAverageDeclaredProgress) { $progressBarClass = 'progress-bar-danger'; - $badgeClass.= 'badge-danger'; + $badgeClass .= 'badge-danger'; } elseif ($totalCalculatedProgress * $warningRatio >= $totalAverageDeclaredProgress) { // warning if close at 1% $progressBarClass = 'progress-bar-warning'; - $badgeClass.= 'badge-warning'; + $badgeClass .= 'badge-warning'; } else { $progressBarClass = 'progress-bar-success'; - $badgeClass.= 'badge-success'; + $badgeClass .= 'badge-success'; } } @@ -719,7 +719,7 @@ function projectLinesa(&$inc, $parent, &$lines, &$level, $var, $showproject, &$t print ''; } // Contacts of task - if (! empty($conf->global->PROJECT_SHOW_CONTACTS_IN_LIST)) + if (!empty($conf->global->PROJECT_SHOW_CONTACTS_IN_LIST)) { print ''; } @@ -753,43 +753,43 @@ function projectLinesPerAction(&$inc, $parent, $fuser, $lines, &$level, &$projec global $conf, $db, $user, $bc, $langs; global $form, $formother, $projectstatic, $taskstatic, $thirdpartystatic; - $lastprojectid=0; - $totalforeachline=array(); - $workloadforid=array(); - $lineswithoutlevel0=array(); + $lastprojectid = 0; + $totalforeachline = array(); + $workloadforid = array(); + $lineswithoutlevel0 = array(); - $numlines=count($lines); + $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++) + for ($i = 0; $i < $numlines; $i++) { - if ($lines[$i]->fk_task_parent) $lineswithoutlevel0[]=$lines[$i]; + if ($lines[$i]->fk_task_parent) $lineswithoutlevel0[] = $lines[$i]; } } if (empty($oldprojectforbreak)) { - $oldprojectforbreak = (empty($conf->global->PROJECT_TIMESHEET_DISABLEBREAK_ON_PROJECT)?0:-1); // 0 to start break , -1 no break + $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++) + 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) { - $lastprojectid=$lines[$i]->fk_project; + $lastprojectid = $lines[$i]->fk_project; if ($preselectedday) { $projectstatic->id = $lines[$i]->fk_project; @@ -800,25 +800,25 @@ function projectLinesPerAction(&$inc, $parent, $fuser, $lines, &$level, &$projec { 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; + $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; } } - $projectstatic->id=$lines[$i]->fk_project; - $projectstatic->ref=$lines[$i]->project_ref; - $projectstatic->title=$lines[$i]->project_label; - $projectstatic->public=$lines[$i]->public; + $projectstatic->id = $lines[$i]->fk_project; + $projectstatic->ref = $lines[$i]->project_ref; + $projectstatic->title = $lines[$i]->project_label; + $projectstatic->public = $lines[$i]->public; - $taskstatic->id=$lines[$i]->task_id; - $taskstatic->ref=($lines[$i]->task_ref?$lines[$i]->task_ref:$lines[$i]->task_id); - $taskstatic->label=$lines[$i]->task_label; - $taskstatic->date_start=$lines[$i]->date_start; - $taskstatic->date_end=$lines[$i]->date_end; + $taskstatic->id = $lines[$i]->task_id; + $taskstatic->ref = ($lines[$i]->task_ref ? $lines[$i]->task_ref : $lines[$i]->task_id); + $taskstatic->label = $lines[$i]->task_label; + $taskstatic->date_start = $lines[$i]->date_start; + $taskstatic->date_end = $lines[$i]->date_end; - $thirdpartystatic->id=$lines[$i]->socid; - $thirdpartystatic->name=$lines[$i]->thirdparty_name; - $thirdpartystatic->email=$lines[$i]->thirdparty_email; + $thirdpartystatic->id = $lines[$i]->socid; + $thirdpartystatic->name = $lines[$i]->thirdparty_name; + $thirdpartystatic->email = $lines[$i]->thirdparty_email; if (empty($oldprojectforbreak) || ($oldprojectforbreak != -1 && $oldprojectforbreak != $projectstatic->id)) { @@ -862,11 +862,11 @@ function projectLinesPerAction(&$inc, $parent, $fuser, $lines, &$level, &$projec // Ref print ''; - $disabledproject=1;$disabledtask=1; + $disabledproject = 1; $disabledtask = 1; //print "x".$lines[$i]->fk_project; //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; + $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])) { - $disabledtask=1; + $disabledtask = 1; } // Hour @@ -899,23 +899,23 @@ function projectLinesPerAction(&$inc, $parent, $fuser, $lines, &$level, &$projec print dol_print_date($lines[$i]->timespent_datehour, 'hour'); print ''; - $cssonholiday=''; - if (! $isavailable[$preselectedday]['morning'] && ! $isavailable[$preselectedday]['afternoon']) $cssonholiday.='onholidayallday '; - elseif (! $isavailable[$preselectedday]['morning']) $cssonholiday.='onholidaymorning '; - elseif (! $isavailable[$preselectedday]['afternoon']) $cssonholiday.='onholidayafternoon '; + $cssonholiday = ''; + if (!$isavailable[$preselectedday]['morning'] && !$isavailable[$preselectedday]['afternoon']) $cssonholiday .= 'onholidayallday '; + elseif (!$isavailable[$preselectedday]['morning']) $cssonholiday .= 'onholidaymorning '; + elseif (!$isavailable[$preselectedday]['afternoon']) $cssonholiday .= 'onholidayafternoon '; // Duration - print ''; - $filenamelinked=''; + $filenamelinked = ''; if ($line->fk_ecm_files > 0) { $result = $ecmfilesstatic->fetch($line->fk_ecm_files); @@ -2355,7 +2355,7 @@ else } } - $tredited='tredited'; + $tredited = 'tredited'; include DOL_DOCUMENT_ROOT.'/expensereport/tpl/expensereport_addfile.tpl.php'; include DOL_DOCUMENT_ROOT.'/expensereport/tpl/expensereport_linktofile.tpl.php'; @@ -2369,7 +2369,7 @@ else print ''; // Select project - if (! empty($conf->projet->enabled)) + if (!empty($conf->projet->enabled)) { print ''; // Unit price @@ -2441,8 +2441,8 @@ else && $user->rights->expensereport->creer) { $colspan = 11; - if (! empty($conf->global->MAIN_USE_EXPENSE_IK)) $colspan++; - if (! empty($conf->projet->enabled)) $colspan++; + if (!empty($conf->global->MAIN_USE_EXPENSE_IK)) $colspan++; + if (!empty($conf->projet->enabled)) $colspan++; if ($action != 'editline') $colspan++; $nbFiles = $nbLinks = 0; @@ -2452,10 +2452,10 @@ else 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/class/link.class.php'; - $upload_dir = $conf->expensereport->dir_output . "/" . dol_sanitizeFileName($object->ref); - $arrayoffiles=dol_dir_list($upload_dir, 'files', 0, '', '(\.meta|_preview.*\.png|'.preg_quote(dol_sanitizeFileName($object->ref.'.pdf'), '/').')$'); + $upload_dir = $conf->expensereport->dir_output."/".dol_sanitizeFileName($object->ref); + $arrayoffiles = dol_dir_list($upload_dir, 'files', 0, '', '(\.meta|_preview.*\.png|'.preg_quote(dol_sanitizeFileName($object->ref.'.pdf'), '/').')$'); $nbFiles = count($arrayoffiles); - $nbLinks=Link::count($db, $object->element, $object->id); + $nbLinks = Link::count($db, $object->element, $object->id); } // Add line with link to add new file or attach to an existing file @@ -2499,7 +2499,7 @@ else print ''; print ''; print ''; - if (! empty($conf->projet->enabled)) print ''; + if (!empty($conf->projet->enabled)) print ''; if (!empty($conf->global->MAIN_USE_EXPENSE_IK)) print ''; print ''; print ''; @@ -2520,18 +2520,18 @@ else // Select date print ''; // Select project - if (! empty($conf->projet->enabled)) + if (!empty($conf->projet->enabled)) { print ''; } - if (! empty($conf->global->MAIN_USE_EXPENSE_IK)) + if (!empty($conf->global->MAIN_USE_EXPENSE_IK)) { print ''; // Unit price net @@ -2568,7 +2568,7 @@ else // Quantity print ''; // Picture @@ -2634,7 +2634,7 @@ if ($action != 'create' && $action != 'edit') // Send if ($object->fk_statut > ExpenseReport::STATUS_DRAFT) { //if ((empty($conf->global->MAIN_USE_ADVANCED_PERMS) || $user->rights->expensereport->expensereport_advance->send)) { - print ''; + print ''; //} else // print ''; } @@ -2665,7 +2665,7 @@ if ($action != 'create' && $action != 'edit') * ET fk_user_author == user courant * Afficher : "Enregistrer" / "Modifier" / "Supprimer" */ - if($user->rights->expensereport->creer && $object->fk_statut == ExpenseReport::STATUS_REFUSED) + if ($user->rights->expensereport->creer && $object->fk_statut == ExpenseReport::STATUS_REFUSED) { if ($user->id == $object->fk_user_author || $user->id == $object->fk_user_valid) { @@ -2729,16 +2729,16 @@ if ($action != 'create' && $action != 'edit') } // If bank module is used - if ($user->rights->expensereport->to_paid && ! empty($conf->banque->enabled) && $object->fk_statut == ExpenseReport::STATUS_APPROVED) + if ($user->rights->expensereport->to_paid && !empty($conf->banque->enabled) && $object->fk_statut == ExpenseReport::STATUS_APPROVED) { // Pay if ($remaintopay == 0) { - print '
    ' . $langs->trans('DoPayment') . '
    '; + print '
    '.$langs->trans('DoPayment').'
    '; } else { - print ''; + print ''; } } @@ -2748,7 +2748,7 @@ if ($action != 'create' && $action != 'edit') //if ((round($remaintopay) == 0 || empty($conf->banque->enabled)) && $object->paid == 0) if ($object->paid == 0) { - print '"; + print '"; } } @@ -2773,7 +2773,7 @@ if ($action != 'create' && $action != 'edit') // Clone if ($user->rights->expensereport->creer) { - print ''; + print ''; } /* If draft, validated, cancel, and user can create, he can always delete its card before it is approved */ @@ -2782,7 +2782,7 @@ if ($action != 'create' && $action != 'edit') // Delete print ''; } - elseif($user->rights->expensereport->supprimer && $object->fk_statut != ExpenseReport::STATUS_CLOSED) + elseif ($user->rights->expensereport->supprimer && $object->fk_statut != ExpenseReport::STATUS_CLOSED) { // Delete print ''; @@ -2809,14 +2809,14 @@ 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; - $genallowed = $user->rights->expensereport->creer; - $delallowed = $user->rights->expensereport->creer; - $var = true; + $filename = dol_sanitizeFileName($object->ref); + $filedir = $conf->expensereport->dir_output."/".dol_sanitizeFileName($object->ref); + $urlsource = $_SERVER["PHP_SELF"]."?id=".$object->id; + $genallowed = $user->rights->expensereport->creer; + $delallowed = $user->rights->expensereport->creer; + $var = true; print $formfile->showdocuments('expensereport', $filename, $filedir, $urlsource, $genallowed, $delallowed); $somethingshown = $formfile->numoffiles; } @@ -2832,7 +2832,7 @@ if ($action != 'presend') print '
    '; // List of actions on element - include_once DOL_DOCUMENT_ROOT . '/core/class/html.formactions.class.php'; + include_once DOL_DOCUMENT_ROOT.'/core/class/html.formactions.class.php'; $formactions = new FormActions($db); $somethingshown = $formactions->showactions($object, 'expensereport', null); @@ -2840,8 +2840,8 @@ if ($action != 'presend') } // Presend form -$modelmail='expensereport'; -$defaulttopic='SendExpenseReportRef'; +$modelmail = 'expensereport'; +$defaulttopic = 'SendExpenseReportRef'; $diroutput = $conf->expensereport->dir_output; $trackid = 'exp'.$object->id; diff --git a/htdocs/expensereport/class/expensereport.class.php b/htdocs/expensereport/class/expensereport.class.php index 91c69b0f3b3..ad21603efce 100644 --- a/htdocs/expensereport/class/expensereport.class.php +++ b/htdocs/expensereport/class/expensereport.class.php @@ -1800,7 +1800,7 @@ class ExpenseReport extends CommonObject if ($result > 0) { $this->db->commit(); - return $this->line->rowid; + return $this->line->id; } else { @@ -2049,7 +2049,6 @@ class ExpenseReport extends CommonObject $this->line->fk_ecm_files = $fk_ecm_files; - $this->line->rowid = $rowid; $this->line->id = $rowid; // Select des infos sur le type fees @@ -2660,7 +2659,7 @@ class ExpenseReportLine $resql=$this->db->query($sql); if ($resql) { - $this->rowid=$this->db->last_insert_id(MAIN_DB_PREFIX.'expensereport_det'); + $this->id=$this->db->last_insert_id(MAIN_DB_PREFIX.'expensereport_det'); if (! $fromaddline) { diff --git a/htdocs/expensereport/document.php b/htdocs/expensereport/document.php index 1bf2c0db8da..48461eec8bf 100644 --- a/htdocs/expensereport/document.php +++ b/htdocs/expensereport/document.php @@ -35,7 +35,7 @@ require_once DOL_DOCUMENT_ROOT.'/core/lib/expensereport.lib.php'; require_once DOL_DOCUMENT_ROOT.'/expensereport/class/expensereport.class.php'; // Load translation files required by the page -$langs->loadLangs(array("other","trips","companies","interventions")); +$langs->loadLangs(array("other", "trips", "companies", "interventions")); $id = GETPOST('id', 'int'); $ref = GETPOST('ref', 'alpha'); @@ -55,15 +55,15 @@ if (empty($page) || $page == -1) { $page = 0; } // If $page is not defined, $offset = $conf->liste_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); $object->fetch($id, $ref); $upload_dir = $conf->expensereport->dir_output.'/'.dol_sanitizeFileName($object->ref); -$modulepart='trip'; +$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 @@ -73,7 +73,7 @@ $modulepart='trip'; * Actions */ -include DOL_DOCUMENT_ROOT . '/core/actions_linkedfiles.inc.php'; +include DOL_DOCUMENT_ROOT.'/core/actions_linkedfiles.inc.php'; /* @@ -82,33 +82,33 @@ include DOL_DOCUMENT_ROOT . '/core/actions_linkedfiles.inc.php'; $form = new Form($db); -$title=$langs->trans("ExpenseReport") . " - " . $langs->trans("Documents"); -$helpurl="EN:Module_Expense_Reports"; +$title = $langs->trans("ExpenseReport")." - ".$langs->trans("Documents"); +$helpurl = "EN:Module_Expense_Reports"; llxHeader("", $title, $helpurl); if ($object->id) { $object->fetch_thirdparty(); - $head=expensereport_prepare_head($object); + $head = expensereport_prepare_head($object); dol_fiche_head($head, 'documents', $langs->trans("ExpenseReport"), -1, 'trip'); - $linkback = ''.$langs->trans("BackToList").''; + $linkback = ''.$langs->trans("BackToList").''; - $morehtmlref='
    '; - $morehtmlref.='
    '; + $morehtmlref = '
    '; + $morehtmlref .= '
    '; dol_banner_tab($object, 'ref', $linkback, 1, 'ref', 'ref', $morehtmlref); // 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) + $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) { - $totalsize+=$file['size']; + $totalsize += $file['size']; } print '
    '; @@ -116,7 +116,7 @@ if ($object->id) print '
    '; - print ''; - print ''; + print ''; + print ''; print ''; - print $langs->trans('Link') . ': '; + print $langs->trans('Link').': '; print ''; - print $langs->trans('Label') . ': '; + print $langs->trans('Label').': '; print '' . dol_print_date(dol_now(), "dayhour", "tzuser") . ''.dol_print_date(dol_now(), "dayhour", "tzuser").''; - print ''; - print ''; + print ''; + print ''; print ''; print img_picto('', 'globe').' '; - print ''; + print ''; print dol_escape_htmltag($link->label); print ''; print '' . dol_print_date($link->datea, "dayhour", "tzuser") . ''.dol_print_date($link->datea, "dayhour", "tzuser").''; - print '' . img_edit() . ''; // id= is included into $param + print ''.img_edit().''; // id= is included into $param if ($permissiontodelete) { - print '   ' . img_delete() . ''; // id= is included into $param + print '   '.img_delete().''; // id= is included into $param } else { print ' '; } @@ -1915,21 +1915,21 @@ class FormFile { global $langs, $conf; - $out=''; - if ($conf->browser->layout != 'phone' && ! empty($conf->use_javascript_ajax)) + $out = ''; + if ($conf->browser->layout != 'phone' && !empty($conf->use_javascript_ajax)) { - $urladvancedpreview=getAdvancedPreviewUrl($modulepart, $relativepath, 1, $param); // Return if a file is qualified for preview. + $urladvancedpreview = getAdvancedPreviewUrl($modulepart, $relativepath, 1, $param); // Return if a file is qualified for preview. if (count($urladvancedpreview)) { - $out.= ''; + $out .= ''; //$out.= ''; if (empty($ruleforpicto)) { //$out.= img_picto($langs->trans('Preview').' '.$file['name'], 'detail'); - $out.=''; + $out .= ''; } - else $out.= img_mime($relativepath, $langs->trans('Preview').' '.$file['name']); - $out.= ''; + else $out .= img_mime($relativepath, $langs->trans('Preview').' '.$file['name']); + $out .= ''; } } return $out; diff --git a/htdocs/core/class/html.formother.class.php b/htdocs/core/class/html.formother.class.php index 69525c0f134..e5b3f8fbb6e 100644 --- a/htdocs/core/class/html.formother.class.php +++ b/htdocs/core/class/html.formother.class.php @@ -72,10 +72,10 @@ class FormOther { // phpcs:enable $sql = "SELECT rowid, label"; - $sql.= " FROM ".MAIN_DB_PREFIX."export_model"; - $sql.= " WHERE type = '".$type."'"; - if (!empty($fk_user)) $sql.=" AND fk_user IN (0, ".$fk_user.")"; // An export model - $sql.= " ORDER BY rowid"; + $sql .= " FROM ".MAIN_DB_PREFIX."export_model"; + $sql .= " WHERE type = '".$type."'"; + if (!empty($fk_user)) $sql .= " AND fk_user IN (0, ".$fk_user.")"; // An export model + $sql .= " ORDER BY rowid"; $result = $this->db->query($sql); if ($result) { @@ -124,9 +124,9 @@ class FormOther { // phpcs:enable $sql = "SELECT rowid, label"; - $sql.= " FROM ".MAIN_DB_PREFIX."import_model"; - $sql.= " WHERE type = '".$type."'"; - $sql.= " ORDER BY rowid"; + $sql .= " FROM ".MAIN_DB_PREFIX."import_model"; + $sql .= " WHERE type = '".$type."'"; + $sql .= " ORDER BY rowid"; $result = $this->db->query($sql); if ($result) { @@ -175,13 +175,13 @@ class FormOther global $langs; $sql = "SELECT e.rowid, e.code, e.label, e.price, e.organization,"; - $sql.= " c.label as country"; - $sql.= " FROM ".MAIN_DB_PREFIX."c_ecotaxe as e,".MAIN_DB_PREFIX."c_country as c"; - $sql.= " WHERE e.active = 1 AND e.fk_pays = c.rowid"; - $sql.= " ORDER BY country, e.organization ASC, e.code ASC"; + $sql .= " c.label as country"; + $sql .= " FROM ".MAIN_DB_PREFIX."c_ecotaxe as e,".MAIN_DB_PREFIX."c_country as c"; + $sql .= " WHERE e.active = 1 AND e.fk_pays = c.rowid"; + $sql .= " ORDER BY country, e.organization ASC, e.code ASC"; dol_syslog(get_class($this).'::select_ecotaxes', LOG_DEBUG); - $resql=$this->db->query($sql); + $resql = $this->db->query($sql); if ($resql) { print ''; + $out .= ''; + $out .= ''; return $out; } else @@ -294,24 +294,24 @@ class FormOther public function select_percent($selected = 0, $htmlname = 'percent', $disabled = 0, $increment = 5, $start = 0, $end = 100, $showempty = 0) { // phpcs:enable - $return = ''; + if ($showempty) $return .= ''; - for ($i = $start ; $i <= $end ; $i += $increment) + for ($i = $start; $i <= $end; $i += $increment) { if ($selected != '' && (int) $selected == $i) { - $return.= ''; + $return .= $i.' % '; + $return .= ''; } - $return.= ''; + $return .= ''; return $return; } @@ -338,7 +338,7 @@ class FormOther // For backward compatibility if (is_numeric($type)) { - dol_syslog(__METHOD__ . ': using numeric value for parameter type is deprecated. Use string code instead.', LOG_WARNING); + dol_syslog(__METHOD__.': using numeric value for parameter type is deprecated. Use string code instead.', LOG_WARNING); } // Load list of "categories" @@ -349,30 +349,30 @@ class FormOther // Enhance with select2 if ($conf->use_javascript_ajax) { - include_once DOL_DOCUMENT_ROOT . '/core/lib/ajax.lib.php'; + include_once DOL_DOCUMENT_ROOT.'/core/lib/ajax.lib.php'; $comboenhancement = ajax_combobox('select_categ_'.$htmlname); - $moreforfilter.=$comboenhancement; + $moreforfilter .= $comboenhancement; } // Print a select with each of them - $moreforfilter.=''; + if ($showempty) $moreforfilter .= ''; // Should use -1 to say nothing if (is_array($tab_categs)) { foreach ($tab_categs as $categ) { - $moreforfilter.=''; + $moreforfilter .= ''; } - $moreforfilter.=''; + $moreforfilter .= ''; return $moreforfilter; } @@ -382,15 +382,16 @@ class FormOther /** * Return select list for categories (to use in form search selectors) * - * @param string $selected Preselected value - * @param string $htmlname Name of combo list (example: 'search_sale') - * @param User $user Object user - * @param int $showstatus 0=show user status only if status is disabled, 1=always show user status into label, -1=never show user status - * @param int $showempty 1=show also an empty value - * @param string $morecss More CSS - * @return string Html combo list code + * @param string $selected Preselected value + * @param string $htmlname Name of combo list (example: 'search_sale') + * @param User $user Object user + * @param int $showstatus 0=show user status only if status is disabled, 1=always show user status into label, -1=never show user status + * @param int $showempty 1=show also an empty value + * @param string $morecss More CSS + * @param int $norepresentative Show also an entry "Not categorized" + * @return string Html combo list code */ - public function select_salesrepresentatives($selected, $htmlname, $user, $showstatus = 0, $showempty = 1, $morecss = '') + public function select_salesrepresentatives($selected, $htmlname, $user, $showstatus = 0, $showempty = 1, $morecss = '', $norepresentative = 0) { // phpcs:enable global $conf, $langs; @@ -498,6 +499,13 @@ class FormOther { dol_print_error($this->db); } + + if ($norepresentative) + { + $langs->load("companies"); + $out.=''; + } + $out.=''; return $out; @@ -525,14 +533,14 @@ class FormOther require_once DOL_DOCUMENT_ROOT.'/projet/class/task.class.php'; //print $modeproject.'-'.$modetask; - $task=new Task($this->db); - $tasksarray=$task->getTasksArray($modetask?$user:0, $modeproject?$user:0, $projectid, 0, $mode, '', $filteronprojstatus); + $task = new Task($this->db); + $tasksarray = $task->getTasksArray($modetask ? $user : 0, $modeproject ? $user : 0, $projectid, 0, $mode, '', $filteronprojstatus); if ($tasksarray) { - print ''; if ($useempty) print ''; - $j=0; - $level=0; + $j = 0; + $level = 0; $this->_pLineSelect($j, 0, $tasksarray, $level, $selectedtask, $projectid, $disablechildoftaskid); print ''; @@ -560,10 +568,10 @@ class FormOther { global $langs, $user, $conf; - $lastprojectid=0; + $lastprojectid = 0; - $numlines=count($lines); - for ($i = 0 ; $i < $numlines ; $i++) { + $numlines = count($lines); + for ($i = 0; $i < $numlines; $i++) { if ($lines[$i]->fk_parent == $parent) { $var = !$var; @@ -577,7 +585,7 @@ class FormOther if ($i > 0) print ''; print '\n"; - $lastprojectid=$lines[$i]->fk_project; + $lastprojectid = $lines[$i]->fk_project; $inc++; } } - $newdisablechildoftaskid=$disablechildoftaskid; + $newdisablechildoftaskid = $disablechildoftaskid; // Print task if (isset($lines[$i]->id)) // We use isset because $lines[$i]->id may be null if project has no task and are on root project (tasks may be caught by a left join). We enter here only if '0' or >0 { // Check if we must disable entry - $disabled=0; + $disabled = 0; if ($disablechildoftaskid && (($lines[$i]->id == $disablechildoftaskid || $lines[$i]->fk_parent == $disablechildoftaskid))) { $disabled++; - if ($lines[$i]->fk_parent == $disablechildoftaskid) $newdisablechildoftaskid=$lines[$i]->id; // If task is child of a disabled parent, we will propagate id to disable next child too + if ($lines[$i]->fk_parent == $disablechildoftaskid) $newdisablechildoftaskid = $lines[$i]->id; // If task is child of a disabled parent, we will propagate id to disable next child too } print ''; foreach ($arrayofcolors as $val) { - $out.= ''; @@ -945,39 +953,39 @@ class FormOther */ public function selectyear($selected = '', $htmlname = 'yearid', $useempty = 0, $min_year = 10, $max_year = 5, $offset = 0, $invert = 0, $option = '', $morecss = 'valignmiddle maxwidth75imp') { - $out=''; + $out = ''; - $currentyear = date("Y")+$offset; - $max_year = $currentyear+$max_year; - $min_year = $currentyear-$min_year; - if(empty($selected) && empty($useempty)) $selected = $currentyear; + $currentyear = date("Y") + $offset; + $max_year = $currentyear + $max_year; + $min_year = $currentyear - $min_year; + if (empty($selected) && empty($useempty)) $selected = $currentyear; - $out.= ''; + if ($useempty) { - $selected_html=''; + $selected_html = ''; if ($selected == '') $selected_html = ' selected'; - $out.= ''; + $out .= ''; } - if (! $invert) + if (!$invert) { for ($y = $max_year; $y >= $min_year; $y--) { - $selected_html=''; + $selected_html = ''; if ($selected > 0 && $y == $selected) $selected_html = ' selected'; - $out.= ''; + $out .= ''; } } else { for ($y = $min_year; $y <= $max_year; $y++) { - $selected_html=''; + $selected_html = ''; if ($selected > 0 && $y == $selected) $selected_html = ' selected'; - $out.= ''; + $out .= ''; } } - $out.= "\n"; + $out .= "\n"; return $out; } @@ -993,70 +1001,70 @@ class FormOther */ public static function getBoxesArea($user, $areacode) { - global $conf,$langs,$db; + global $conf, $langs, $db; include_once DOL_DOCUMENT_ROOT.'/core/class/infobox.class.php'; - $confuserzone='MAIN_BOXES_'.$areacode; + $confuserzone = 'MAIN_BOXES_'.$areacode; // $boxactivated will be array of boxes enabled into global setup // $boxidactivatedforuser will be array of boxes choosed by user - $selectboxlist=''; - $boxactivated=InfoBox::listBoxes($db, 'activated', $areacode, (empty($user->conf->$confuserzone)?null:$user), array(), 0); // Search boxes of common+user (or common only if user has no specific setup) + $selectboxlist = ''; + $boxactivated = InfoBox::listBoxes($db, 'activated', $areacode, (empty($user->conf->$confuserzone) ?null:$user), array(), 0); // Search boxes of common+user (or common only if user has no specific setup) - $boxidactivatedforuser=array(); - foreach($boxactivated as $box) + $boxidactivatedforuser = array(); + foreach ($boxactivated as $box) { - if (empty($user->conf->$confuserzone) || $box->fk_user == $user->id) $boxidactivatedforuser[$box->id]=$box->id; // We keep only boxes to show for user + if (empty($user->conf->$confuserzone) || $box->fk_user == $user->id) $boxidactivatedforuser[$box->id] = $box->id; // We keep only boxes to show for user } // Define selectboxlist - $arrayboxtoactivatelabel=array(); - if (! empty($user->conf->$confuserzone)) + $arrayboxtoactivatelabel = array(); + if (!empty($user->conf->$confuserzone)) { - $boxorder=''; - $langs->load("boxes"); // Load label of boxes - foreach($boxactivated as $box) + $boxorder = ''; + $langs->load("boxes"); // Load label of boxes + foreach ($boxactivated as $box) { - if (! empty($boxidactivatedforuser[$box->id])) continue; // Already visible for user - $label=$langs->transnoentitiesnoconv($box->boxlabel); + if (!empty($boxidactivatedforuser[$box->id])) continue; // Already visible for user + $label = $langs->transnoentitiesnoconv($box->boxlabel); //if (preg_match('/graph/',$box->class)) $label.=' ('.$langs->trans("Graph").')'; if (preg_match('/graph/', $box->class) && $conf->browser->layout != 'phone') { - $label=$label.' '; + $label = $label.' '; } - $arrayboxtoactivatelabel[$box->id]=$label; // We keep only boxes not shown for user, to show into combo list + $arrayboxtoactivatelabel[$box->id] = $label; // We keep only boxes not shown for user, to show into combo list } - foreach($boxidactivatedforuser as $boxid) + foreach ($boxidactivatedforuser as $boxid) { - if (empty($boxorder)) $boxorder.='A:'; - $boxorder.=$boxid.','; + if (empty($boxorder)) $boxorder .= 'A:'; + $boxorder .= $boxid.','; } //var_dump($boxidactivatedforuser); // Class Form must have been already loaded - $selectboxlist.=''."\n"; - $selectboxlist.=''; - $selectboxlist.=''; - $selectboxlist.=''; - $selectboxlist.=''; - $selectboxlist.=''; - $selectboxlist.=Form::selectarray('boxcombo', $arrayboxtoactivatelabel, -1, $langs->trans("ChooseBoxToAdd").'...', 0, 0, '', 0, 0, 0, 'ASC', 'maxwidth150onsmartphone', 0, 'hidden selected', 0, 1); - if (empty($conf->use_javascript_ajax)) $selectboxlist.=' '; - $selectboxlist.=''; - if (! empty($conf->use_javascript_ajax)) + $selectboxlist .= ''."\n"; + $selectboxlist .= '
    '; + $selectboxlist .= ''; + $selectboxlist .= ''; + $selectboxlist .= ''; + $selectboxlist .= ''; + $selectboxlist .= Form::selectarray('boxcombo', $arrayboxtoactivatelabel, -1, $langs->trans("ChooseBoxToAdd").'...', 0, 0, '', 0, 0, 0, 'ASC', 'maxwidth150onsmartphone', 0, 'hidden selected', 0, 1); + if (empty($conf->use_javascript_ajax)) $selectboxlist .= ' '; + $selectboxlist .= '
    '; + if (!empty($conf->use_javascript_ajax)) { - include_once DOL_DOCUMENT_ROOT . '/core/lib/ajax.lib.php'; - $selectboxlist.=ajax_combobox("boxcombo"); + include_once DOL_DOCUMENT_ROOT.'/core/lib/ajax.lib.php'; + $selectboxlist .= ajax_combobox("boxcombo"); } } // Javascript code for dynamic actions - if (! empty($conf->use_javascript_ajax)) + if (!empty($conf->use_javascript_ajax)) { - $selectboxlist.=''."\n"; + $selectboxlist .= ''."\n"; } // Define boxlista and boxlistb - $nbboxactivated=count($boxidactivatedforuser); + $nbboxactivated = count($boxidactivatedforuser); if ($nbboxactivated) { // Load translation files required by the page - $langs->loadLangs(array("boxes","projects")); + $langs->loadLangs(array("boxes", "projects")); - $emptybox=new ModeleBoxes($db); + $emptybox = new ModeleBoxes($db); - $boxlista.="\n\n"; + $boxlista .= "\n\n"; // Define $box_max_lines - $box_max_lines=5; - if (! empty($conf->global->MAIN_BOXES_MAXLINES)) $box_max_lines=$conf->global->MAIN_BOXES_MAXLINES; + $box_max_lines = 5; + if (!empty($conf->global->MAIN_BOXES_MAXLINES)) $box_max_lines = $conf->global->MAIN_BOXES_MAXLINES; - $ii=0; + $ii = 0; foreach ($boxactivated as $key => $box) { - if ((! empty($user->conf->$confuserzone) && $box->fk_user == 0) || (empty($user->conf->$confuserzone) && $box->fk_user != 0)) continue; - if (empty($box->box_order) && $ii < ($nbboxactivated / 2)) $box->box_order='A'.sprintf("%02d", ($ii+1)); // When box_order was not yet set to Axx or Bxx and is still 0 + if ((!empty($user->conf->$confuserzone) && $box->fk_user == 0) || (empty($user->conf->$confuserzone) && $box->fk_user != 0)) continue; + if (empty($box->box_order) && $ii < ($nbboxactivated / 2)) $box->box_order = 'A'.sprintf("%02d", ($ii + 1)); // When box_order was not yet set to Axx or Bxx and is still 0 if (preg_match('/^A/i', $box->box_order)) // column A { $ii++; @@ -1152,26 +1160,26 @@ class FormOther //print 'box_order '.$boxactivated[$ii]->box_order.'
    '; // Show box $box->loadBox($box_max_lines); - $boxlista.= $box->outputBox(); + $boxlista .= $box->outputBox(); } } if ($conf->browser->layout != 'phone') { - $emptybox->box_id='A'; - $emptybox->info_box_head=array(); - $emptybox->info_box_contents=array(); - $boxlista.= $emptybox->outputBox(array(), array()); + $emptybox->box_id = 'A'; + $emptybox->info_box_head = array(); + $emptybox->info_box_contents = array(); + $boxlista .= $emptybox->outputBox(array(), array()); } - $boxlista.= "\n"; + $boxlista .= "\n"; - $boxlistb.= "\n\n"; + $boxlistb .= "\n\n"; - $ii=0; + $ii = 0; foreach ($boxactivated as $key => $box) { - if ((! empty($user->conf->$confuserzone) && $box->fk_user == 0) || (empty($user->conf->$confuserzone) && $box->fk_user != 0)) continue; - if (empty($box->box_order) && $ii < ($nbboxactivated / 2)) $box->box_order='B'.sprintf("%02d", ($ii+1)); // When box_order was not yet set to Axx or Bxx and is still 0 + if ((!empty($user->conf->$confuserzone) && $box->fk_user == 0) || (empty($user->conf->$confuserzone) && $box->fk_user != 0)) continue; + if (empty($box->box_order) && $ii < ($nbboxactivated / 2)) $box->box_order = 'B'.sprintf("%02d", ($ii + 1)); // When box_order was not yet set to Axx or Bxx and is still 0 if (preg_match('/^B/i', $box->box_order)) // colonne B { $ii++; @@ -1179,22 +1187,22 @@ class FormOther //print 'box_order '.$boxactivated[$ii]->box_order.'
    '; // Show box $box->loadBox($box_max_lines); - $boxlistb.= $box->outputBox(); + $boxlistb .= $box->outputBox(); } } if ($conf->browser->layout != 'phone') { - $emptybox->box_id='B'; - $emptybox->info_box_head=array(); - $emptybox->info_box_contents=array(); - $boxlistb.= $emptybox->outputBox(array(), array()); + $emptybox->box_id = 'B'; + $emptybox->info_box_head = array(); + $emptybox->info_box_contents = array(); + $boxlistb .= $emptybox->outputBox(array(), array()); } - $boxlistb.= "\n"; + $boxlistb .= "\n"; } - return array('selectboxlist'=>count($boxactivated)?$selectboxlist:'', 'boxactivated'=>$boxactivated, 'boxlista'=>$boxlista, 'boxlistb'=>$boxlistb); + return array('selectboxlist'=>count($boxactivated) ? $selectboxlist : '', 'boxactivated'=>$boxactivated, 'boxlista'=>$boxlista, 'boxlistb'=>$boxlistb); } @@ -1219,8 +1227,8 @@ class FormOther $langs->load("admin"); $sql = "SELECT rowid, ".$keyfield.", ".$labelfield; - $sql.= " FROM ".MAIN_DB_PREFIX.$dictionarytable; - $sql.= " ORDER BY ".$labelfield; + $sql .= " FROM ".MAIN_DB_PREFIX.$dictionarytable; + $sql .= " ORDER BY ".$labelfield; dol_syslog(get_class($this)."::select_dictionary", LOG_DEBUG); $result = $this->db->query($sql); @@ -1230,7 +1238,7 @@ class FormOther $i = 0; if ($num) { - print ''; if ($useempty == 1 || ($useempty == 2 && $num > 1)) { print ''; @@ -1275,17 +1283,17 @@ class FormOther { global $langs; - $automatic="automatic"; $manual="manual"; + $automatic = "automatic"; $manual = "manual"; if ($option) { - $automatic="1"; - $manual="0"; + $automatic = "1"; + $manual = "0"; } $disabled = ($disabled ? ' disabled' : ''); $resultautomanual = ''; - print ''; + print '
    '; + print ''; + print ''; foreach ($this->param as $key => $value) { - print ''; + print ''; } - print ''; + print ''; print ''; if ($this->withref) { // Ref $defaultref = $ticketstat->getDefaultRef(); - print ''; + print ''; } // TITLE if ($this->withemail) { - print ''; } @@ -184,7 +184,7 @@ class FormTicket $subelement = $regs[2]; } - dol_include_once('/' . $element . '/class/' . $subelement . '.class.php'); + dol_include_once('/'.$element.'/class/'.$subelement.'.class.php'); $classname = ucfirst($subelement); $objectsrc = new $classname($this->db); $objectsrc->fetch(GETPOST('originid', 'int')); @@ -195,53 +195,53 @@ class FormTicket $objectsrc->fetch_thirdparty(); $newclassname = $classname; - print ''; + print ''; } // Type - print ''; // Severity - print ''; // Group - print ''; // Subject if ($this->withtitletopic) { - print ''; } else { if ($this->withthreadid > 0) { - $subject = $langs->trans('SubjectAnswerToTicket') . ' ' . $this->withthreadid . ' : ' . $this->topic_title . ''; + $subject = $langs->trans('SubjectAnswerToTicket').' '.$this->withthreadid.' : '.$this->topic_title.''; } - print ''; + print ''; print ''; } } // MESSAGE $msg = GETPOSTISSET('message') ? GETPOST('message', 'none') : ''; - print ''; - if (! empty($conf->use_javascript_ajax) && ! empty($conf->global->COMPANY_USE_SEARCH_TO_SELECT)) { + if (!empty($conf->use_javascript_ajax) && !empty($conf->global->COMPANY_USE_SEARCH_TO_SELECT)) { $htmlname = 'socid'; print ''; - print ''; - print ''; - print ''; + print ''; + print ''; + print ''; print ''; foreach ($this->param as $key => $value) { - print ''; + print ''; } // Get message template - $model_id=0; + $model_id = 0; if (array_key_exists('models_id', $this->param)) { - $model_id=$this->param["models_id"]; - $arraydefaultmessage=$formmail->getEMailTemplate($this->db, $this->param["models"], $user, $outputlangs, $model_id); + $model_id = $this->param["models_id"]; + $arraydefaultmessage = $formmail->getEMailTemplate($this->db, $this->param["models"], $user, $outputlangs, $model_id); } $result = $formmail->fetchAllEMailTemplate($this->param["models"], $user, $outputlangs); - if ($result<0) { + if ($result < 0) { setEventMessages($this->error, $this->errors, 'errors'); } - $modelmail_array=array(); + $modelmail_array = array(); foreach ($formmail->lines_model as $line) { - $modelmail_array[$line->id]=$line->label; + $modelmail_array[$line->id] = $line->label; } - print '
    ' . $langs->trans("Ref") . '
    '.$langs->trans("Ref").'
    '; - print ''; + print '
    '; + print ''; print '
    ' . $langs->trans($newclassname) . '' . $objectsrc->getNomUrl(1) . '
    '.$langs->trans($newclassname).''.$objectsrc->getNomUrl(1).'
    '; + print '
    '; $this->selectTypesTickets((GETPOST('type_code') ? GETPOST('type_code') : $this->type_code), 'type_code', '', '2'); print '
    '; + print '
    '; $this->selectSeveritiesTickets((GETPOST('severity_code') ? GETPOST('severity_code') : $this->severity_code), 'severity_code', '', '2'); print '
    '; + print '
    '; $this->selectGroupTickets((GETPOST('category_code') ? GETPOST('category_code') : $this->category_code), 'category_code', '', '2'); print '
    '; + print '
    '; // Réponse à un ticket : affichage du titre du thread en readonly if ($this->withtopicreadonly) { - print $langs->trans('SubjectAnswerToTicket') . ' ' . $this->topic_title; + print $langs->trans('SubjectAnswerToTicket').' '.$this->topic_title; print '
    '; + print '
    '; // If public form, display more information $toolbarname = 'dolibarr_notes'; if ($this->ispublic) { $toolbarname = 'dolibarr_details'; - print '
    ' . ($conf->global->TICKET_PUBLIC_TEXT_HELP_MESSAGE ? $conf->global->TICKET_PUBLIC_TEXT_HELP_MESSAGE : $langs->trans('TicketPublicPleaseBeAccuratelyDescribe')) . '
    '; + print '
    '.($conf->global->TICKET_PUBLIC_TEXT_HELP_MESSAGE ? $conf->global->TICKET_PUBLIC_TEXT_HELP_MESSAGE : $langs->trans('TicketPublicPleaseBeAccuratelyDescribe')).'
    '; } - include_once DOL_DOCUMENT_ROOT . '/core/class/doleditor.class.php'; + include_once DOL_DOCUMENT_ROOT.'/core/class/doleditor.class.php'; $uselocalbrowser = true; $doleditor = new DolEditor('message', $msg, '100%', 230, $toolbarname, 'In', true, $uselocalbrowser, $conf->global->FCKEDITOR_ENABLE_TICKET, ROWS_8, '90%'); $doleditor->Create(); @@ -249,7 +249,7 @@ class FormTicket // FK_USER_CREATE if ($this->withusercreate > 0 && $this->fk_user_create) { - print '
    ' . $langs->trans("CreatedBy") . ''; + print '
    '.$langs->trans("CreatedBy").''; $langs->load("users"); $fuser = new User($this->db); @@ -267,12 +267,12 @@ class FormTicket // altairis: force company and contact id for external user if (empty($user->socid)) { // Company - print '
    ' . $langs->trans("ThirdParty") . ''; + print '
    '.$langs->trans("ThirdParty").''; $events = array(); $events[] = array('method' => 'getContacts', 'url' => dol_buildpath('/core/ajax/contacts.php', 1), 'htmlname' => 'contactid', 'params' => array('add-customer-contact' => 'disabled')); print $form->select_company($this->withfromsocid, 'socid', '', 1, 1, '', $events, 0, 'minwidth200'); print '
    '; + print '
    '; // External users can't send message email if ($user->rights->ticket->write && !$user->socid) @@ -891,11 +891,11 @@ class FormTicket print ''; // Zone to select its email template - if (count($modelmail_array)>0) { + if (count($modelmail_array) > 0) { print ''; } - print ''; + print ''; $label_title = empty($conf->global->MAIN_APPLICATION_TITLE) ? $mysoc->name : $conf->global->MAIN_APPLICATION_TITLE; - print ''; // Destinataires - print ''; @@ -972,10 +972,10 @@ class FormTicket // External users can't send message email if ($user->rights->ticket->write && !$user->socid) { $mail_intro = GETPOST('mail_intro') ? GETPOST('mail_intro') : $conf->global->TICKET_MESSAGE_MAIL_INTRO; - print ''; - $out .= ''; + $out .= ''; $out .= '\n"; @@ -1075,10 +1075,10 @@ class FormTicket print '
    '; $checkbox_selected = (GETPOST('send_email') == "1" ? ' checked' : ''); print ' '; - print ''; + print ''; print '
    '; $checkbox_selected = (GETPOST('private_message', 'alpha') == "1" ? ' checked' : ''); print ' '; - print ''; + print ''; print ''; print $form->textwithpicto('', $langs->trans("TicketMessagePrivateHelp"), 1, 'help'); print '
    '; + print '
    '; //$toolbarname = 'dolibarr_details'; $toolbarname = 'dolibarr_notes'; - include_once DOL_DOCUMENT_ROOT . '/core/class/doleditor.class.php'; + include_once DOL_DOCUMENT_ROOT.'/core/class/doleditor.class.php'; $doleditor = new DolEditor('message', $defaultmessage, '100%', 200, $toolbarname, '', false, true, $conf->global->FCKEDITOR_ENABLE_SOCIETE, ROWS_5, 70); $doleditor->Create(); print ''; @@ -1025,10 +1025,10 @@ class FormTicket // External users can't send message email if ($user->rights->ticket->write && !$user->socid) { $mail_signature = GETPOST('mail_signature') ? GETPOST('mail_signature') : $conf->global->TICKET_MESSAGE_MAIL_SIGNATURE; - print '
    ' . $langs->trans("MailFile") . ''.$langs->trans("MailFile").''; // TODO Trick to have param removedfile containing nb of image to delete. But this does not works without javascript - $out .= '' . "\n"; + $out .= ''."\n"; $out .= '' . "\n"; + $out .= ''."\n"; if (count($listofpaths)) { foreach ($listofpaths as $key => $val) { - $out .= '
    '; - $out .= img_mime($listofnames[$key]) . ' ' . $listofnames[$key]; + $out .= '
    '; + $out .= img_mime($listofnames[$key]).' '.$listofnames[$key]; if (!$this->withfilereadonly) { - $out .= ' '; + $out .= ' '; } $out .= '
    '; } } else { - $out .= $langs->trans("NoAttachedFiles") . '
    '; + $out .= $langs->trans("NoAttachedFiles").'
    '; } if ($this->withfile == 2) { // Can add other files - $out .= ''; + $out .= ''; $out .= ' '; - $out .= ''; + $out .= ''; } $out .= "
    '; print '

    '; - print ''; + print ''; if ($this->withcancel) { print "     "; - print "trans("Cancel") . "\">"; + print "trans("Cancel")."\">"; } print "
    \n"; diff --git a/htdocs/core/class/html.formwebsite.class.php b/htdocs/core/class/html.formwebsite.class.php index 12ec3e7f5ad..6cd88175a67 100644 --- a/htdocs/core/class/html.formwebsite.class.php +++ b/htdocs/core/class/html.formwebsite.class.php @@ -56,19 +56,19 @@ class FormWebsite */ public function selectWebsite($selected = '', $htmlname = 'exportmodelid', $useempty = 0) { - $out=''; + $out = ''; $sql = "SELECT rowid, ref"; - $sql.= " FROM ".MAIN_DB_PREFIX."website"; - $sql.= " WHERE 1 = 1"; - $sql.= " ORDER BY rowid"; + $sql .= " FROM ".MAIN_DB_PREFIX."website"; + $sql .= " WHERE 1 = 1"; + $sql .= " ORDER BY rowid"; $result = $this->db->query($sql); if ($result) { - $out.=''; if ($useempty) { - $out.=''; + $out .= ''; } $num = $this->db->num_rows($result); @@ -78,17 +78,17 @@ class FormWebsite $obj = $this->db->fetch_object($result); if ($selected == $obj->rowid) { - $out.=''; + $out .= $obj->ref; + $out .= ''; $i++; } - $out.=""; + $out .= ""; } else { dol_print_error($this->db); @@ -114,9 +114,9 @@ class FormWebsite $langs->load("admin"); $sql = "SELECT rowid, code, label, entity"; - $sql.= " FROM ".MAIN_DB_PREFIX.'c_type_container'; - $sql.= " WHERE active = 1 AND entity IN (".getEntity('c_type_container').")"; - $sql.= " ORDER BY label"; + $sql .= " FROM ".MAIN_DB_PREFIX.'c_type_container'; + $sql .= " WHERE active = 1 AND entity IN (".getEntity('c_type_container').")"; + $sql .= " ORDER BY label"; dol_syslog(get_class($this)."::selectTypeOfContainer", LOG_DEBUG); $result = $this->db->query($sql); @@ -126,7 +126,7 @@ class FormWebsite $i = 0; if ($num) { - print ''; if ($useempty == 1 || ($useempty == 2 && $num > 1)) { print ''; @@ -179,8 +179,8 @@ class FormWebsite $listofsamples = dol_dir_list(DOL_DOCUMENT_ROOT.'/website/samples', 'files', 0, '^page-sample-.*\.html$'); $arrayofsamples = array(); - $arrayofsamples['empty']='EmptyPage'; // Always this one first - foreach($listofsamples as $sample) + $arrayofsamples['empty'] = 'EmptyPage'; // Always this one first + foreach ($listofsamples as $sample) { $reg = array(); if (preg_match('/^page-sample-(.*)\.html$/', $sample['name'], $reg)) @@ -193,14 +193,14 @@ class FormWebsite } $out = ''; - $out .= ''; if ($useempty == 1 || $useempty == 2) { $out .= ''; } - foreach($arrayofsamples as $key => $val) + foreach ($arrayofsamples as $key => $val) { if ($selected == $key) { @@ -228,60 +228,67 @@ class FormWebsite * @param int $pageid Preselected container ID * @param int $showempty Show empty record * @param string $action Action on page that use this select list + * @param string $morecss More CSS + * @param array $excludeids Exclude some ID in list * @return string HTML select component with list of type of containers */ - public function selectContainer($website, $htmlname = 'pageid', $pageid = 0, $showempty = 0, $action = '') + public function selectContainer($website, $htmlname = 'pageid', $pageid = 0, $showempty = 0, $action = '', $morecss = 'minwidth200', $excludeids = null) { global $langs; $atleastonepage = (is_array($website->lines) && count($website->lines) > 0); - $out=''; + $out = ''; if ($atleastonepage && $action != 'editsource') { - $out.=''; } else { - $out.=''; } - if ($showempty || ! $atleastonepage) $out.=''; + if ($showempty || !$atleastonepage) $out .= ''; if ($atleastonepage) { if (empty($pageid) && $action != 'createcontainer') // Page id is not defined, we try to take one { - $firstpageid=0;$homepageid=0; - foreach($website->lines as $key => $valpage) + $firstpageid = 0; $homepageid = 0; + foreach ($website->lines as $key => $valpage) { - if (empty($firstpageid)) $firstpageid=$valpage->id; - if ($website->fk_default_home && $key == $website->fk_default_home) $homepageid=$valpage->id; + if (empty($firstpageid)) $firstpageid = $valpage->id; + if ($website->fk_default_home && $key == $website->fk_default_home) $homepageid = $valpage->id; } - $pageid=$homepageid?$homepageid:$firstpageid; // We choose home page and if not defined yet, we take first page + $pageid = $homepageid ? $homepageid : $firstpageid; // We choose home page and if not defined yet, we take first page } - foreach($website->lines as $key => $valpage) + foreach ($website->lines as $key => $valpage) { - $out.=''; + if (is_array($excludeids) && count($excludeids) && in_array($valpage->id, $excludeids)) continue; + + $valueforoption = '['.$valpage->type_container.' '.sprintf("%03d", $valpage->id).'] '; + $valueforoption .= $valpage->pageurl.' - '.$valpage->title; + if ($website->fk_default_home && $key == $website->fk_default_home) $valueforoption .= ' ('.$langs->trans("HomePage").')'; + + $out .= ''; } } - $out.=''; + $out .= ''; if ($atleastonepage && $action != 'editsource') { - $out.=ajax_combobox($htmlname); + $out .= ajax_combobox($htmlname); } else { - $out.=''; - $out.=ajax_combobox($htmlname); + $out .= ''; + $out .= ajax_combobox($htmlname); } return $out; } diff --git a/htdocs/core/class/infobox.class.php b/htdocs/core/class/infobox.class.php index 4ff061933e9..de00ea85e6f 100644 --- a/htdocs/core/class/infobox.class.php +++ b/htdocs/core/class/infobox.class.php @@ -94,29 +94,29 @@ class InfoBox { global $conf; - $boxes=array(); + $boxes = array(); - $confuserzone='MAIN_BOXES_'.$zone; + $confuserzone = 'MAIN_BOXES_'.$zone; if ($mode == 'activated') // activated { $sql = "SELECT b.rowid, b.position, b.box_order, b.fk_user,"; - $sql.= " d.rowid as box_id, d.file, d.note, d.tms"; - $sql.= " FROM ".MAIN_DB_PREFIX."boxes as b, ".MAIN_DB_PREFIX."boxes_def as d"; - $sql.= " WHERE b.box_id = d.rowid"; - $sql.= " AND b.entity IN (0,".$conf->entity.")"; - if ($zone >= 0) $sql.= " AND b.position = ".$zone; - if (is_object($user)) $sql.= " AND b.fk_user IN (0,".$user->id.")"; - else $sql.= " AND b.fk_user = 0"; - $sql.= " ORDER BY b.box_order"; + $sql .= " d.rowid as box_id, d.file, d.note, d.tms"; + $sql .= " FROM ".MAIN_DB_PREFIX."boxes as b, ".MAIN_DB_PREFIX."boxes_def as d"; + $sql .= " WHERE b.box_id = d.rowid"; + $sql .= " AND b.entity IN (0,".$conf->entity.")"; + if ($zone >= 0) $sql .= " AND b.position = ".$zone; + if (is_object($user)) $sql .= " AND b.fk_user IN (0,".$user->id.")"; + else $sql .= " AND b.fk_user = 0"; + $sql .= " ORDER BY b.box_order"; } else // available { $sql = "SELECT d.rowid as box_id, d.file, d.note, d.tms"; - $sql.= " FROM ".MAIN_DB_PREFIX."boxes_def as d"; - $sql.= " WHERE d.entity IN (0,".$conf->entity.")"; + $sql .= " FROM ".MAIN_DB_PREFIX."boxes_def as d"; + $sql .= " WHERE d.entity IN (0,".$conf->entity.")"; } - dol_syslog(get_class()."::listBoxes get default box list for mode=".$mode." userid=".(is_object($user)?$user->id:'')."", LOG_DEBUG); + dol_syslog(get_class()."::listBoxes get default box list for mode=".$mode." userid=".(is_object($user) ? $user->id : '')."", LOG_DEBUG); $resql = $db->query($sql); if ($resql) { @@ -126,7 +126,7 @@ class InfoBox { $obj = $db->fetch_object($resql); - if (! in_array($obj->box_id, $excludelist)) + if (!in_array($obj->box_id, $excludelist)) { if (preg_match('/^([^@]+)@([^@]+)$/i', $obj->file, $regs)) { @@ -136,7 +136,7 @@ class InfoBox } else { - $boxname=preg_replace('/\.php$/i', '', $obj->file); + $boxname = preg_replace('/\.php$/i', '', $obj->file); $relsourcefile = "/core/boxes/".$boxname.".php"; } @@ -148,48 +148,48 @@ class InfoBox dol_include_once($relsourcefile); if (class_exists($boxname)) { - $box=new $boxname($db, $obj->note); // Constructor may set properties like box->enabled. obj->note is note into box def, not user params. + $box = new $boxname($db, $obj->note); // Constructor may set properties like box->enabled. obj->note is note into box def, not user params. //$box=new stdClass(); // box properties - $box->rowid = (empty($obj->rowid) ? '' : $obj->rowid); - $box->id = (empty($obj->box_id) ? '' : $obj->box_id); - $box->position = ($obj->position == '' ? '' : $obj->position); // '0' must stay '0' + $box->rowid = (empty($obj->rowid) ? '' : $obj->rowid); + $box->id = (empty($obj->box_id) ? '' : $obj->box_id); + $box->position = ($obj->position == '' ? '' : $obj->position); // '0' must stay '0' $box->box_order = (empty($obj->box_order) ? '' : $obj->box_order); - $box->fk_user = (empty($obj->fk_user) ? 0 : $obj->fk_user); - $box->sourcefile= $relsourcefile; + $box->fk_user = (empty($obj->fk_user) ? 0 : $obj->fk_user); + $box->sourcefile = $relsourcefile; $box->class = $boxname; - if ($mode == 'activated' && ! is_object($user)) // List of activated box was not yet personalized into database + if ($mode == 'activated' && !is_object($user)) // List of activated box was not yet personalized into database { if (is_numeric($box->box_order)) { - if ($box->box_order % 2 == 1) $box->box_order='A'.$box->box_order; - elseif ($box->box_order % 2 == 0) $box->box_order='B'.$box->box_order; + if ($box->box_order % 2 == 1) $box->box_order = 'A'.$box->box_order; + elseif ($box->box_order % 2 == 0) $box->box_order = 'B'.$box->box_order; } } // box_def properties - $box->box_id = (empty($obj->box_id) ? '' : $obj->box_id); - $box->note = (empty($obj->note) ? '' : $obj->note); + $box->box_id = (empty($obj->box_id) ? '' : $obj->box_id); + $box->note = (empty($obj->note) ? '' : $obj->note); // Filter on box->enabled (used for example by box_comptes) // Filter also on box->depends. Example: array("product|service") or array("contrat", "service") - $enabled=$box->enabled; + $enabled = $box->enabled; if (isset($box->depends) && count($box->depends) > 0) { - foreach($box->depends as $moduleelem) + foreach ($box->depends as $moduleelem) { - $arrayelem=explode('|', $moduleelem); - $tmpenabled=0; // $tmpenabled is used for the '|' test (OR) - foreach($arrayelem as $module) + $arrayelem = explode('|', $moduleelem); + $tmpenabled = 0; // $tmpenabled is used for the '|' test (OR) + foreach ($arrayelem as $module) { - $tmpmodule=preg_replace('/@[^@]+/', '', $module); - if (! empty($conf->$tmpmodule->enabled)) $tmpenabled=1; + $tmpmodule = preg_replace('/@[^@]+/', '', $module); + if (!empty($conf->$tmpmodule->enabled)) $tmpenabled = 1; //print $boxname.'-'.$module.'-module enabled='.(empty($conf->$tmpmodule->enabled)?0:1).'
    '; } if (empty($tmpenabled)) // We found at least one module required that is disabled { - $enabled=0; + $enabled = 0; break; } } @@ -197,7 +197,7 @@ class InfoBox //print '=>'.$boxname.'-enabled='.$enabled.'
    '; //print 'xx module='.$module.' enabled='.$enabled; - if ($enabled && ($includehidden || empty($box->hidden))) $boxes[]=$box; + if ($enabled && ($includehidden || empty($box->hidden))) $boxes[] = $box; else unset($box); } else @@ -231,66 +231,66 @@ class InfoBox { global $conf; - $error=0; + $error = 0; require_once DOL_DOCUMENT_ROOT.'/core/lib/functions2.lib.php'; dol_syslog(get_class()."::saveboxorder zone=".$zone." userid=".$userid); - if (! $userid || $userid == 0) return 0; + if (!$userid || $userid == 0) return 0; $user = new User($db); - $user->id=$userid; + $user->id = $userid; $db->begin(); // Save parameters to say user has a dedicated setup - $tab=array(); - $confuserzone='MAIN_BOXES_'.$zone; - $tab[$confuserzone]=1; + $tab = array(); + $confuserzone = 'MAIN_BOXES_'.$zone; + $tab[$confuserzone] = 1; if (dol_set_user_param($db, $conf, $user, $tab) < 0) { - $error=$db->lasterror(); + $error = $db->lasterror(); $db->rollback(); return -3; } // Delete all lines $sql = "DELETE FROM ".MAIN_DB_PREFIX."boxes"; - $sql.= " WHERE entity = ".$conf->entity; - $sql.= " AND fk_user = ".$userid; - $sql.= " AND position = ".$zone; + $sql .= " WHERE entity = ".$conf->entity; + $sql .= " AND fk_user = ".$userid; + $sql .= " AND position = ".$zone; dol_syslog(get_class()."::saveboxorder", LOG_DEBUG); $result = $db->query($sql); if ($result) { - $colonnes=explode('-', $boxorder); + $colonnes = explode('-', $boxorder); foreach ($colonnes as $collist) { - $part=explode(':', $collist); - $colonne=$part[0]; - $list=$part[1]; + $part = explode(':', $collist); + $colonne = $part[0]; + $list = $part[1]; dol_syslog(get_class()."::saveboxorder column=".$colonne.' list='.$list); - $i=0; - $listarray=explode(',', $list); + $i = 0; + $listarray = explode(',', $list); foreach ($listarray as $id) { if (is_numeric($id)) { //dol_syslog("aaaaa".count($listarray)); $i++; - $ii=sprintf('%02d', $i); + $ii = sprintf('%02d', $i); $sql = "INSERT INTO ".MAIN_DB_PREFIX."boxes"; - $sql.= "(box_id, position, box_order, fk_user, entity)"; - $sql.= " values ("; - $sql.= " ".$id.","; - $sql.= " ".$zone.","; - $sql.= " '".$colonne.$ii."',"; - $sql.= " ".$userid.","; - $sql.= " ".$conf->entity; - $sql.= ")"; + $sql .= "(box_id, position, box_order, fk_user, entity)"; + $sql .= " values ("; + $sql .= " ".$id.","; + $sql .= " ".$zone.","; + $sql .= " '".$colonne.$ii."',"; + $sql .= " ".$userid.","; + $sql .= " ".$conf->entity; + $sql .= ")"; dol_syslog(get_class()."::saveboxorder", LOG_DEBUG); $result = $db->query($sql); @@ -304,7 +304,7 @@ class InfoBox } if ($error) { - $error=$db->error(); + $error = $db->error(); $db->rollback(); return -2; } @@ -316,7 +316,7 @@ class InfoBox } else { - $error=$db->lasterror(); + $error = $db->lasterror(); $db->rollback(); dol_syslog(get_class()."::saveboxorder ".$error); return -1; diff --git a/htdocs/core/class/interfaces.class.php b/htdocs/core/class/interfaces.class.php index bdcfe6bbf75..304a7a248a3 100644 --- a/htdocs/core/class/interfaces.class.php +++ b/htdocs/core/class/interfaces.class.php @@ -36,7 +36,7 @@ class Interfaces */ public $db; - public $dir; // Directory with all core and external triggers files + public $dir; // Directory with all core and external triggers files /** * @var string[] Error codes (or messages) @@ -69,18 +69,18 @@ class Interfaces { // phpcs:enable // Check parameters - if (! is_object($object) || ! is_object($conf)) // Error + if (!is_object($object) || !is_object($conf)) // Error { - $this->error='function run_triggers called with wrong parameters action='.$action.' object='.is_object($object).' user='.is_object($user).' langs='.is_object($langs).' conf='.is_object($conf); + $this->error = 'function run_triggers called with wrong parameters action='.$action.' object='.is_object($object).' user='.is_object($user).' langs='.is_object($langs).' conf='.is_object($conf); dol_syslog(get_class($this).'::run_triggers '.$this->error, LOG_ERR); - $this->errors[]=$this->error; + $this->errors[] = $this->error; return -1; } - if (! is_object($langs)) // Warning + if (!is_object($langs)) // Warning { dol_syslog(get_class($this).'::run_triggers was called with wrong parameters action='.$action.' object='.is_object($object).' user='.is_object($user).' langs='.is_object($langs).' conf='.is_object($conf), LOG_WARNING); } - if (! is_object($user)) // Warning + if (!is_object($user)) // Warning { dol_syslog(get_class($this).'::run_triggers was called with wrong parameters action='.$action.' object='.is_object($object).' user='.is_object($user).' langs='.is_object($langs).' conf='.is_object($conf), LOG_WARNING); global $db; @@ -93,44 +93,44 @@ class Interfaces $files = array(); $modules = array(); $orders = array(); - $i=0; + $i = 0; - $dirtriggers=array_merge(array('/core/triggers'), $conf->modules_parts['triggers']); - foreach($dirtriggers as $reldir) + $dirtriggers = array_merge(array('/core/triggers'), $conf->modules_parts['triggers']); + foreach ($dirtriggers as $reldir) { - $dir=dol_buildpath($reldir, 0); - $newdir=dol_osencode($dir); + $dir = dol_buildpath($reldir, 0); + $newdir = dol_osencode($dir); //print "xx".$dir;exit; // Check if directory exists (we do not use dol_is_dir to avoir loading files.lib.php at each call) - if (! is_dir($newdir)) continue; + if (!is_dir($newdir)) continue; - $handle=opendir($newdir); + $handle = opendir($newdir); if (is_resource($handle)) { - while (($file = readdir($handle))!==false) + while (($file = readdir($handle)) !== false) { if (is_readable($newdir."/".$file) && preg_match('/^interface_([0-9]+)_([^_]+)_(.+)\.class\.php$/i', $file, $reg)) { - $part1=$reg[1]; - $part2=$reg[2]; - $part3=$reg[3]; + $part1 = $reg[1]; + $part2 = $reg[2]; + $part3 = $reg[3]; $nbfile++; // Check if trigger file is disabled by name if (preg_match('/NORUN$/i', $file)) continue; // Check if trigger file is for a particular module - $qualified=true; + $qualified = true; if (strtolower($reg[2]) != 'all') { - $module=preg_replace('/^mod/i', '', $reg[2]); - $constparam='MAIN_MODULE_'.strtoupper($module); - if (empty($conf->global->$constparam)) $qualified=false; + $module = preg_replace('/^mod/i', '', $reg[2]); + $constparam = 'MAIN_MODULE_'.strtoupper($module); + if (empty($conf->global->$constparam)) $qualified = false; } - if (! $qualified) + if (!$qualified) { //dol_syslog(get_class($this)."::run_triggers action=".$action." Triggers for file '".$file."' need module to be enabled", LOG_DEBUG); continue; @@ -150,7 +150,7 @@ class Interfaces include_once $newdir.'/'.$file; //print 'Done for '.$modName."\n"; } - catch(Exception $e) + catch (Exception $e) { dol_syslog('ko for '.$modName." ".$e->getMessage()."\n", LOG_ERR); } @@ -158,11 +158,13 @@ class Interfaces $modules[$i] = $modName; $files[$i] = $file; $fullpathfiles[$modName] = $newdir.'/'.$file; - $orders[$i] = $part1.'_'.$part2.'_'.$part3; // Set sort criteria value + $orders[$i] = $part1.'_'.$part2.'_'.$part3; // Set sort criteria value $i++; } } + + closedir($handle); } } @@ -177,17 +179,17 @@ class Interfaces $objMod = new $modName($this->db); if ($objMod) { - $result=0; + $result = 0; if (method_exists($objMod, 'runTrigger')) // New method to implement { //dol_syslog(get_class($this)."::run_triggers action=".$action." Launch runTrigger for file '".$files[$key]."'", LOG_DEBUG); - $result=$objMod->runTrigger($action, $object, $user, $langs, $conf); + $result = $objMod->runTrigger($action, $object, $user, $langs, $conf); } elseif (method_exists($objMod, 'run_trigger')) // Deprecated method { dol_syslog(get_class($this)."::run_triggers action=".$action." Launch old method run_trigger (rename your trigger into runTrigger) for file '".$files[$key]."'", LOG_WARNING); - $result=$objMod->run_trigger($action, $object, $user, $langs, $conf); + $result = $objMod->run_trigger($action, $object, $user, $langs, $conf); } else { @@ -211,8 +213,8 @@ class Interfaces //dol_syslog("Error in trigger ".$action." - Nb of error string returned = ".count($objMod->errors), LOG_ERR); $nbtotal++; $nbko++; - if (! empty($objMod->errors)) $this->errors=array_merge($this->errors, $objMod->errors); - elseif (! empty($objMod->error)) $this->errors[]=$objMod->error; + if (!empty($objMod->errors)) $this->errors = array_merge($this->errors, $objMod->errors); + elseif (!empty($objMod->error)) $this->errors[] = $objMod->error; //dol_syslog("Error in trigger ".$action." - Nb of error string returned = ".count($this->errors), LOG_ERR); } } @@ -253,32 +255,32 @@ class Interfaces $orders = array(); $i = 0; - $dirtriggers=array_merge(array('/core/triggers/'), $conf->modules_parts['triggers']); + $dirtriggers = array_merge(array('/core/triggers/'), $conf->modules_parts['triggers']); if (is_array($forcedirtriggers)) { - $dirtriggers=$forcedirtriggers; + $dirtriggers = $forcedirtriggers; } - foreach($dirtriggers as $reldir) + foreach ($dirtriggers as $reldir) { - $dir=dol_buildpath($reldir, 0); - $newdir=dol_osencode($dir); + $dir = dol_buildpath($reldir, 0); + $newdir = dol_osencode($dir); // Check if directory exists (we do not use dol_is_dir to avoid loading files.lib.php at each call) - if (! is_dir($newdir)) continue; + if (!is_dir($newdir)) continue; - $handle=opendir($newdir); + $handle = opendir($newdir); if (is_resource($handle)) { - while (($file = readdir($handle))!==false) + while (($file = readdir($handle)) !== false) { if (is_readable($newdir.'/'.$file) && preg_match('/^interface_([0-9]+)_([^_]+)_(.+)\.class\.php/', $file, $reg)) { if (preg_match('/\.back$/', $file)) continue; - $part1=$reg[1]; - $part2=$reg[2]; - $part3=$reg[3]; + $part1 = $reg[1]; + $part2 = $reg[2]; + $part3 = $reg[3]; $modName = 'Interface'.ucfirst($reg[3]); //print "file=$file"; print "modName=$modName"; exit; @@ -295,9 +297,9 @@ class Interfaces $files[$i] = $file; $fullpath[$i] = $dir.'/'.$file; $relpath[$i] = preg_replace('/^\//', '', $reldir).'/'.$file; - $iscoreorexternal[$i] = ($reldir == '/core/triggers/'?'internal':'external'); + $iscoreorexternal[$i] = ($reldir == '/core/triggers/' ? 'internal' : 'external'); $modules[$i] = $modName; - $orders[$i] = $part1.'_'.$part2.'_'.$part3; // Set sort criteria value + $orders[$i] = $part1.'_'.$part2.'_'.$part3; // Set sort criteria value $i++; } @@ -317,7 +319,7 @@ class Interfaces $modName = $modules[$key]; if (empty($modName)) continue; - if (! class_exists($modName)) + if (!class_exists($modName)) { print 'Error: A trigger file was found but its class "'.$modName.'" was not found.'."
    \n"; continue; @@ -326,24 +328,24 @@ class Interfaces $objMod = new $modName($db); // Define disabledbyname and disabledbymodule - $disabledbyname=0; - $disabledbymodule=1; - $module=''; + $disabledbyname = 0; + $disabledbymodule = 1; + $module = ''; // Check if trigger file is disabled by name - if (preg_match('/NORUN$/i', $files[$key])) $disabledbyname=1; + if (preg_match('/NORUN$/i', $files[$key])) $disabledbyname = 1; // Check if trigger file is for a particular module if (preg_match('/^interface_([0-9]+)_([^_]+)_(.+)\.class\.php/i', $files[$key], $reg)) { - $module=preg_replace('/^mod/i', '', $reg[2]); - $constparam='MAIN_MODULE_'.strtoupper($module); - if (strtolower($module) == 'all') $disabledbymodule=0; - elseif (empty($conf->global->$constparam)) $disabledbymodule=2; - $triggers[$j]['module']=strtolower($module); + $module = preg_replace('/^mod/i', '', $reg[2]); + $constparam = 'MAIN_MODULE_'.strtoupper($module); + if (strtolower($module) == 'all') $disabledbymodule = 0; + elseif (empty($conf->global->$constparam)) $disabledbymodule = 2; + $triggers[$j]['module'] = strtolower($module); } // We set info of modules - $triggers[$j]['picto'] = $objMod->picto?img_object('', $objMod->picto, 'class="valignmiddle pictomodule "'):img_object('', 'generic', 'class="valignmiddle pictomodule "'); + $triggers[$j]['picto'] = $objMod->picto ?img_object('', $objMod->picto, 'class="valignmiddle pictomodule "') : img_object('', 'generic', 'class="valignmiddle pictomodule "'); $triggers[$j]['file'] = $files[$key]; $triggers[$j]['fullpath'] = $fullpath[$key]; $triggers[$j]['relpath'] = $relpath[$key]; @@ -352,19 +354,19 @@ class Interfaces $triggers[$j]['status'] = img_picto($langs->trans("Active"), 'tick'); if ($disabledbyname > 0 || $disabledbymodule > 1) $triggers[$j]['status'] = ''; - $text =''.$langs->trans("Description").':
    '; - $text.=$objMod->getDesc().'
    '; - $text.='
    '.$langs->trans("Status").':
    '; + $text = ''.$langs->trans("Description").':
    '; + $text .= $objMod->getDesc().'
    '; + $text .= '
    '.$langs->trans("Status").':
    '; if ($disabledbyname == 1) { - $text.=$langs->trans("TriggerDisabledByName").'
    '; - if ($disabledbymodule == 2) $text.=$langs->trans("TriggerDisabledAsModuleDisabled", $module).'
    '; + $text .= $langs->trans("TriggerDisabledByName").'
    '; + if ($disabledbymodule == 2) $text .= $langs->trans("TriggerDisabledAsModuleDisabled", $module).'
    '; } else { - if ($disabledbymodule == 0) $text.=$langs->trans("TriggerAlwaysActive").'
    '; - if ($disabledbymodule == 1) $text.=$langs->trans("TriggerActiveAsModuleActive", $module).'
    '; - if ($disabledbymodule == 2) $text.=$langs->trans("TriggerDisabledAsModuleDisabled", $module).'
    '; + if ($disabledbymodule == 0) $text .= $langs->trans("TriggerAlwaysActive").'
    '; + if ($disabledbymodule == 1) $text .= $langs->trans("TriggerActiveAsModuleActive", $module).'
    '; + if ($disabledbymodule == 2) $text .= $langs->trans("TriggerDisabledAsModuleDisabled", $module).'
    '; } $triggers[$j]['info'] = $text; diff --git a/htdocs/core/class/link.class.php b/htdocs/core/class/link.class.php index cdc5b283c44..1a844f86f2b 100644 --- a/htdocs/core/class/link.class.php +++ b/htdocs/core/class/link.class.php @@ -74,9 +74,9 @@ class Link extends CommonObject */ public function create($user = '') { - global $langs,$conf; + global $langs, $conf; - $error=0; + $error = 0; $langs->load("errors"); // Clean parameters if (empty($this->label)) { @@ -99,34 +99,34 @@ class Link extends CommonObject $sql = "INSERT INTO ".MAIN_DB_PREFIX."links (entity, datea, url, label, objecttype, objectid)"; $sql .= " VALUES ('".$conf->entity."', '".$this->db->idate($this->datea)."'"; - $sql .= ", '" . $this->db->escape($this->url) . "'"; - $sql .= ", '" . $this->db->escape($this->label) . "'"; - $sql .= ", '" . $this->db->escape($this->objecttype) . "'"; - $sql .= ", " . $this->objectid . ")"; + $sql .= ", '".$this->db->escape($this->url)."'"; + $sql .= ", '".$this->db->escape($this->label)."'"; + $sql .= ", '".$this->db->escape($this->objecttype)."'"; + $sql .= ", ".$this->objectid.")"; dol_syslog(get_class($this)."::create", LOG_DEBUG); $result = $this->db->query($sql); if ($result) { - $this->id = $this->db->last_insert_id(MAIN_DB_PREFIX . "links"); + $this->id = $this->db->last_insert_id(MAIN_DB_PREFIX."links"); if ($this->id > 0) { // Call trigger - $result=$this->call_trigger('LINK_CREATE', $user); + $result = $this->call_trigger('LINK_CREATE', $user); if ($result < 0) $error++; // End call triggers } else { $error++; } - if (! $error) + if (!$error) { - dol_syslog(get_class($this)."::Create success id=" . $this->id); + dol_syslog(get_class($this)."::Create success id=".$this->id); $this->db->commit(); return $this->id; } else { - dol_syslog(get_class($this)."::Create echec update " . $this->error, LOG_ERR); + dol_syslog(get_class($this)."::Create echec update ".$this->error, LOG_ERR); $this->db->rollback(); return -3; } @@ -135,13 +135,13 @@ class Link extends CommonObject { if ($this->db->errno() == 'DB_ERROR_RECORD_ALREADY_EXISTS') { - $this->error=$langs->trans("ErrorCompanyNameAlreadyExists", $this->name); - $result=-1; + $this->error = $langs->trans("ErrorCompanyNameAlreadyExists", $this->name); + $result = -1; } else { - $this->error=$this->db->lasterror(); - $result=-2; + $this->error = $this->db->lasterror(); + $result = -2; } $this->db->rollback(); return $result; @@ -157,13 +157,13 @@ class Link extends CommonObject */ public function update($user = '', $call_trigger = 1) { - global $langs,$conf; + global $langs, $conf; require_once DOL_DOCUMENT_ROOT.'/core/lib/functions2.lib.php'; $langs->load("errors"); - $error=0; + $error = 0; - dol_syslog(get_class($this)."::Update id = " . $this->id . " call_trigger = " . $call_trigger); + dol_syslog(get_class($this)."::Update id = ".$this->id." call_trigger = ".$call_trigger); // Check parameters if (empty($this->url)) @@ -180,30 +180,30 @@ class Link extends CommonObject $this->db->begin(); - $sql = "UPDATE " . MAIN_DB_PREFIX . "links SET "; - $sql .= "entity = '" . $conf->entity ."'"; - $sql .= ", datea = '" . $this->db->idate(dol_now()) . "'"; - $sql .= ", url = '" . $this->db->escape($this->url) . "'"; - $sql .= ", label = '" . $this->db->escape($this->label) . "'"; - $sql .= ", objecttype = '" . $this->db->escape($this->objecttype) . "'"; - $sql .= ", objectid = " . $this->objectid; - $sql .= " WHERE rowid = " . $this->id; + $sql = "UPDATE ".MAIN_DB_PREFIX."links SET "; + $sql .= "entity = '".$conf->entity."'"; + $sql .= ", datea = '".$this->db->idate(dol_now())."'"; + $sql .= ", url = '".$this->db->escape($this->url)."'"; + $sql .= ", label = '".$this->db->escape($this->label)."'"; + $sql .= ", objecttype = '".$this->db->escape($this->objecttype)."'"; + $sql .= ", objectid = ".$this->objectid; + $sql .= " WHERE rowid = ".$this->id; - dol_syslog(get_class($this)."::update sql = " .$sql); + dol_syslog(get_class($this)."::update sql = ".$sql); $resql = $this->db->query($sql); if ($resql) { if ($call_trigger) { // Call trigger - $result=$this->call_trigger('LINK_MODIFY', $user); + $result = $this->call_trigger('LINK_MODIFY', $user); if ($result < 0) $error++; // End call triggers } - if (! $error) + if (!$error) { - dol_syslog(get_class($this) . "::Update success"); + dol_syslog(get_class($this)."::Update success"); $this->db->commit(); return 1; } else { @@ -218,12 +218,12 @@ class Link extends CommonObject { // Doublon $this->error = $langs->trans("ErrorDuplicateField"); - $result = -1; + $result = -1; } else { - $this->error = $langs->trans("Error sql = " . $sql); - $result = -2; + $this->error = $langs->trans("Error sql = ".$sql); + $result = -2; } $this->db->rollback(); return $result; @@ -244,14 +244,14 @@ class Link extends CommonObject { global $conf; - $sql = "SELECT rowid, entity, datea, url, label, objecttype, objectid FROM " . MAIN_DB_PREFIX . "links"; - $sql .= " WHERE objecttype = '" . $objecttype . "' AND objectid = " . $objectid; - if ($conf->entity != 0) $sql .= " AND entity = " . $conf->entity; + $sql = "SELECT rowid, entity, datea, url, label, objecttype, objectid FROM ".MAIN_DB_PREFIX."links"; + $sql .= " WHERE objecttype = '".$objecttype."' AND objectid = ".$objectid; + if ($conf->entity != 0) $sql .= " AND entity = ".$conf->entity; if ($sortfield) { if (empty($sortorder)) { $sortorder = "ASC"; } - $sql .= " ORDER BY " . $sortfield . " " . $sortorder; + $sql .= " ORDER BY ".$sortfield." ".$sortorder; } dol_syslog(get_class($this)."::fetchAll", LOG_DEBUG); @@ -259,7 +259,7 @@ class Link extends CommonObject if ($resql) { $num = $this->db->num_rows($resql); - dol_syslog(get_class($this)."::fetchAll " . $num . "records", LOG_DEBUG); + dol_syslog(get_class($this)."::fetchAll ".$num."records", LOG_DEBUG); if ($num > 0) { while ($obj = $this->db->fetch_object($resql)) @@ -295,9 +295,9 @@ class Link extends CommonObject { global $conf; - $sql = "SELECT COUNT(rowid) as nb FROM " . MAIN_DB_PREFIX . "links"; - $sql .= " WHERE objecttype = '" . $objecttype . "' AND objectid = " . $objectid; - if ($conf->entity != 0) $sql .= " AND entity = " . $conf->entity; + $sql = "SELECT COUNT(rowid) as nb FROM ".MAIN_DB_PREFIX."links"; + $sql .= " WHERE objecttype = '".$objecttype."' AND objectid = ".$objectid; + if ($conf->entity != 0) $sql .= " AND entity = ".$conf->entity; $resql = $db->query($sql); if ($resql) @@ -322,15 +322,15 @@ class Link extends CommonObject $rowid = $this->id; } - $sql = "SELECT rowid, entity, datea, url, label, objecttype, objectid FROM " . MAIN_DB_PREFIX . "links"; - $sql .= " WHERE rowid = " . $rowid; - if($conf->entity != 0) $sql .= " AND entity = " . $conf->entity; + $sql = "SELECT rowid, entity, datea, url, label, objecttype, objectid FROM ".MAIN_DB_PREFIX."links"; + $sql .= " WHERE rowid = ".$rowid; + if ($conf->entity != 0) $sql .= " AND entity = ".$conf->entity; dol_syslog(get_class($this)."::fetch", LOG_DEBUG); $resql = $this->db->query($sql); if ($resql) { - if($this->db->num_rows($resql) > 0) + if ($this->db->num_rows($resql) > 0) { $obj = $this->db->fetch_object($resql); @@ -348,7 +348,7 @@ class Link extends CommonObject return 0; } } else { - $this->error=$this->db->lasterror(); + $this->error = $this->db->lasterror(); return -1; } } @@ -367,7 +367,7 @@ class Link extends CommonObject $this->db->begin(); // Call trigger - $result=$this->call_trigger('LINK_DELETE', $user); + $result = $this->call_trigger('LINK_DELETE', $user); if ($result < 0) { $this->db->rollback(); @@ -376,17 +376,17 @@ class Link extends CommonObject // End call triggers // Remove link - $sql = "DELETE FROM " . MAIN_DB_PREFIX . "links"; - $sql.= " WHERE rowid = " . $this->id; + $sql = "DELETE FROM ".MAIN_DB_PREFIX."links"; + $sql .= " WHERE rowid = ".$this->id; dol_syslog(get_class($this)."::delete", LOG_DEBUG); - if (! $this->db->query($sql)) + if (!$this->db->query($sql)) { $error++; $this->error = $this->db->lasterror(); } - if (! $error) { + if (!$error) { $this->db->commit(); return 1; diff --git a/htdocs/core/class/menu.class.php b/htdocs/core/class/menu.class.php index f0ee1378647..cc60cba1abd 100644 --- a/htdocs/core/class/menu.class.php +++ b/htdocs/core/class/menu.class.php @@ -93,7 +93,7 @@ class Menu $array_start = array_slice($this->liste, 0, ($idafter+1)); $array_new = array(0=>array('url'=>$url,'titre'=>$titre,'level'=>$level,'enabled'=>$enabled,'target'=>$target,'mainmenu'=>$mainmenu,'leftmenu'=>$leftmenu,'position'=>$position, 'id'=>$id, 'idsel'=>$idsel, 'classname'=>$classname, 'prefix'=>$prefix)); $array_end = array_slice($this->liste, ($idafter+1)); - $this->liste=array_merge($array_start, $array_new, $array_end); + $this->liste = array_merge($array_start, $array_new, $array_end); } // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps @@ -105,7 +105,7 @@ class Menu public function remove_last() { // phpcs:enable - if (count($this->liste) > 1) { + if (count($this->liste) > 1) { array_pop($this->liste); } } diff --git a/htdocs/core/class/menubase.class.php b/htdocs/core/class/menubase.class.php index 5a63ad0efd6..06e2e99397f 100644 --- a/htdocs/core/class/menubase.class.php +++ b/htdocs/core/class/menubase.class.php @@ -1,7 +1,7 @@ * Copyright (C) 2009-2012 Regis Houssin - * Copyright (C) 2018 Frédéric France + * Copyright (C) 2018-2019 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 @@ -45,17 +45,32 @@ class Menubase public $errors = array(); /** - * @var int ID - */ - public $id; + * @var int ID + */ + public $id; + /** + * @var string Menu handler + */ public $menu_handler; + + /** + * @var string Module name if record is added by a module + */ public $module; + + /** + * @var string Menu top or left + */ public $type; + + /** + * @var string Name family/module for top menu (home, companies, ...) + */ public $mainmenu; /** - * @var int ID + * @var int 0 or Id of mother menu line, or -1 if we use fk_mainmenu and fk_leftmenu */ public $fk_menu; @@ -70,23 +85,71 @@ class Menubase public $fk_leftmenu; /** - * @var int position + * @var int Sort order of entry */ public $position; + + /** + * @var string Relative (or absolute) url to go + */ public $url; + + /** + * @var string Target of Url link + */ public $target; + + /** + * @var string Key for menu translation + * @deprecated + * @see title + */ public $titre; + + /** + * @var string Key for menu translation + */ + public $title; + + /** + * @var string Lang file to load for translation + */ public $langs; + + /** + * @var string Not used + * @deprecated + */ public $level; - public $leftmenu; //menu_handler=trim($this->menu_handler); - $this->module=trim($this->module); - $this->type=trim($this->type); - $this->mainmenu=trim($this->mainmenu); - $this->leftmenu=trim($this->leftmenu); - $this->fk_menu = (int) $this->fk_menu; // If -1, fk_mainmenu and fk_leftmenu must be defined - $this->fk_mainmenu=trim($this->fk_mainmenu); - $this->fk_leftmenu=trim($this->fk_leftmenu); + $this->menu_handler = trim($this->menu_handler); + $this->module = trim($this->module); + $this->type = trim($this->type); + $this->mainmenu = trim($this->mainmenu); + $this->leftmenu = trim($this->leftmenu); + $this->fk_menu = (int) $this->fk_menu; // If -1, fk_mainmenu and fk_leftmenu must be defined + $this->fk_mainmenu = trim($this->fk_mainmenu); + $this->fk_leftmenu = trim($this->fk_leftmenu); $this->position = (int) $this->position; - $this->url=trim($this->url); - $this->target=trim($this->target); - $this->titre=trim($this->titre); - $this->langs=trim($this->langs); - $this->perms=trim($this->perms); - $this->enabled=trim($this->enabled); - $this->user=trim($this->user); - if (empty($this->position)) $this->position=0; - if (! $this->level) $this->level=0; + $this->url = trim($this->url); + $this->target = trim($this->target); + $this->titre = trim($this->titre); + $this->langs = trim($this->langs); + $this->perms = trim($this->perms); + $this->enabled = trim($this->enabled); + $this->user = (int) $this->user; + if (empty($this->position)) $this->position = 0; + if (!$this->level) $this->level = 0; // Check parameters if (empty($this->menu_handler)) return -1; @@ -138,32 +201,32 @@ class Menubase if (in_array($this->db->type, array('pgsql'))) { $sql = "SELECT MAX(rowid) as maxrowid FROM ".MAIN_DB_PREFIX."menu"; - $resqlrowid=$this->db->query($sql); + $resqlrowid = $this->db->query($sql); if ($resqlrowid) { - $obj=$this->db->fetch_object($resqlrowid); - $maxrowid=$obj->maxrowid; + $obj = $this->db->fetch_object($resqlrowid); + $maxrowid = $obj->maxrowid; // Max rowid can be empty if there is no record yet - if(empty($maxrowid)) $maxrowid=1; + if (empty($maxrowid)) $maxrowid = 1; $sql = "SELECT setval('".MAIN_DB_PREFIX."menu_rowid_seq', ".($maxrowid).")"; //print $sql; exit; - $resqlrowidset=$this->db->query($sql); - if (! $resqlrowidset) dol_print_error($this->db); + $resqlrowidset = $this->db->query($sql); + if (!$resqlrowidset) dol_print_error($this->db); } else dol_print_error($this->db); } // Check that entry does not exists yet on key menu_handler-fk_menu-position-url-entity, to avoid errors with postgresql $sql = "SELECT count(*)"; - $sql.= " FROM ".MAIN_DB_PREFIX."menu"; - $sql.= " WHERE menu_handler = '".$this->db->escape($this->menu_handler)."'"; - $sql.= " AND fk_menu = ".((int) $this->fk_menu); - $sql.= " AND position = ".((int) $this->position); - $sql.= " AND url = '".$this->db->escape($this->url)."'"; - $sql.= " AND entity = ".$conf->entity; + $sql .= " FROM ".MAIN_DB_PREFIX."menu"; + $sql .= " WHERE menu_handler = '".$this->db->escape($this->menu_handler)."'"; + $sql .= " AND fk_menu = ".((int) $this->fk_menu); + $sql .= " AND position = ".((int) $this->position); + $sql .= " AND url = '".$this->db->escape($this->url)."'"; + $sql .= " AND entity = ".$conf->entity; - $result=$this->db->query($sql); + $result = $this->db->query($sql); if ($result) { $row = $this->db->fetch_row($result); @@ -172,45 +235,45 @@ class Menubase { // Insert request $sql = "INSERT INTO ".MAIN_DB_PREFIX."menu("; - $sql.= "menu_handler,"; - $sql.= "entity,"; - $sql.= "module,"; - $sql.= "type,"; - $sql.= "mainmenu,"; - $sql.= "leftmenu,"; - $sql.= "fk_menu,"; - $sql.= "fk_mainmenu,"; - $sql.= "fk_leftmenu,"; - $sql.= "position,"; - $sql.= "url,"; - $sql.= "target,"; - $sql.= "titre,"; - $sql.= "langs,"; - $sql.= "perms,"; - $sql.= "enabled,"; - $sql.= "usertype"; - $sql.= ") VALUES ("; - $sql.= " '".$this->db->escape($this->menu_handler)."',"; - $sql.= " '".$this->db->escape($conf->entity)."',"; - $sql.= " '".$this->db->escape($this->module)."',"; - $sql.= " '".$this->db->escape($this->type)."',"; - $sql.= " ".($this->mainmenu?"'".$this->db->escape($this->mainmenu)."'":"''").","; // Can't be null - $sql.= " ".($this->leftmenu?"'".$this->db->escape($this->leftmenu)."'":"null").","; - $sql.= " ".((int) $this->fk_menu).","; - $sql.= " ".($this->fk_mainmenu?"'".$this->db->escape($this->fk_mainmenu)."'":"null").","; - $sql.= " ".($this->fk_leftmenu?"'".$this->db->escape($this->fk_leftmenu)."'":"null").","; - $sql.= " ".((int) $this->position).","; - $sql.= " '".$this->db->escape($this->url)."',"; - $sql.= " '".$this->db->escape($this->target)."',"; - $sql.= " '".$this->db->escape($this->titre)."',"; - $sql.= " '".$this->db->escape($this->langs)."',"; - $sql.= " '".$this->db->escape($this->perms)."',"; - $sql.= " '".$this->db->escape($this->enabled)."',"; - $sql.= " '".$this->db->escape($this->user)."'"; - $sql.= ")"; + $sql .= "menu_handler,"; + $sql .= "entity,"; + $sql .= "module,"; + $sql .= "type,"; + $sql .= "mainmenu,"; + $sql .= "leftmenu,"; + $sql .= "fk_menu,"; + $sql .= "fk_mainmenu,"; + $sql .= "fk_leftmenu,"; + $sql .= "position,"; + $sql .= "url,"; + $sql .= "target,"; + $sql .= "titre,"; + $sql .= "langs,"; + $sql .= "perms,"; + $sql .= "enabled,"; + $sql .= "usertype"; + $sql .= ") VALUES ("; + $sql .= " '".$this->db->escape($this->menu_handler)."',"; + $sql .= " '".$this->db->escape($conf->entity)."',"; + $sql .= " '".$this->db->escape($this->module)."',"; + $sql .= " '".$this->db->escape($this->type)."',"; + $sql .= " ".($this->mainmenu ? "'".$this->db->escape($this->mainmenu)."'" : "''").","; // Can't be null + $sql .= " ".($this->leftmenu ? "'".$this->db->escape($this->leftmenu)."'" : "null").","; + $sql .= " ".((int) $this->fk_menu).","; + $sql .= " ".($this->fk_mainmenu ? "'".$this->db->escape($this->fk_mainmenu)."'" : "null").","; + $sql .= " ".($this->fk_leftmenu ? "'".$this->db->escape($this->fk_leftmenu)."'" : "null").","; + $sql .= " ".((int) $this->position).","; + $sql .= " '".$this->db->escape($this->url)."',"; + $sql .= " '".$this->db->escape($this->target)."',"; + $sql .= " '".$this->db->escape($this->titre)."',"; + $sql .= " '".$this->db->escape($this->langs)."',"; + $sql .= " '".$this->db->escape($this->perms)."',"; + $sql .= " '".$this->db->escape($this->enabled)."',"; + $sql .= " '".$this->db->escape($this->user)."'"; + $sql .= ")"; dol_syslog(get_class($this)."::create", LOG_DEBUG); - $resql=$this->db->query($sql); + $resql = $this->db->query($sql); if ($resql) { $this->id = $this->db->last_insert_id(MAIN_DB_PREFIX."menu"); @@ -220,7 +283,7 @@ class Menubase } else { - $this->error="Error ".$this->db->lasterror(); + $this->error = "Error ".$this->db->lasterror(); return -1; } } @@ -246,55 +309,55 @@ class Menubase */ public function update($user = null, $notrigger = 0) { - global $conf, $langs; + //global $conf, $langs; // Clean parameters - $this->rowid=trim($this->rowid); - $this->menu_handler=trim($this->menu_handler); - $this->module=trim($this->module); - $this->type=trim($this->type); - $this->mainmenu=trim($this->mainmenu); - $this->leftmenu=trim($this->leftmenu); + $this->rowid = trim($this->rowid); + $this->menu_handler = trim($this->menu_handler); + $this->module = trim($this->module); + $this->type = trim($this->type); + $this->mainmenu = trim($this->mainmenu); + $this->leftmenu = trim($this->leftmenu); $this->fk_menu = (int) $this->fk_menu; - $this->fk_mainmenu=trim($this->fk_mainmenu); - $this->fk_leftmenu=trim($this->fk_leftmenu); + $this->fk_mainmenu = trim($this->fk_mainmenu); + $this->fk_leftmenu = trim($this->fk_leftmenu); $this->position = (int) $this->position; - $this->url=trim($this->url); - $this->target=trim($this->target); - $this->titre=trim($this->titre); - $this->langs=trim($this->langs); - $this->perms=trim($this->perms); - $this->enabled=trim($this->enabled); - $this->user=trim($this->user); + $this->url = trim($this->url); + $this->target = trim($this->target); + $this->titre = trim($this->titre); + $this->langs = trim($this->langs); + $this->perms = trim($this->perms); + $this->enabled = trim($this->enabled); + $this->user = (int) $this->user; // Check parameters // Put here code to add control on parameters values // Update request $sql = "UPDATE ".MAIN_DB_PREFIX."menu SET"; - $sql.= " menu_handler='".$this->db->escape($this->menu_handler)."',"; - $sql.= " module='".$this->db->escape($this->module)."',"; - $sql.= " type='".$this->db->escape($this->type)."',"; - $sql.= " mainmenu='".$this->db->escape($this->mainmenu)."',"; - $sql.= " leftmenu='".$this->db->escape($this->leftmenu)."',"; - $sql.= " fk_menu=".$this->fk_menu.","; - $sql.= " fk_mainmenu=".($this->fk_mainmenu?"'".$this->db->escape($this->fk_mainmenu)."'":"null").","; - $sql.= " fk_leftmenu=".($this->fk_leftmenu?"'".$this->db->escape($this->fk_leftmenu)."'":"null").","; - $sql.= " position=".($this->position > 0 ? $this->position : 0).","; - $sql.= " url='".$this->db->escape($this->url)."',"; - $sql.= " target='".$this->db->escape($this->target)."',"; - $sql.= " titre='".$this->db->escape($this->titre)."',"; - $sql.= " langs='".$this->db->escape($this->langs)."',"; - $sql.= " perms='".$this->db->escape($this->perms)."',"; - $sql.= " enabled='".$this->db->escape($this->enabled)."',"; - $sql.= " usertype='".$this->db->escape($this->user)."'"; - $sql.= " WHERE rowid=".$this->id; + $sql .= " menu_handler='".$this->db->escape($this->menu_handler)."',"; + $sql .= " module='".$this->db->escape($this->module)."',"; + $sql .= " type='".$this->db->escape($this->type)."',"; + $sql .= " mainmenu='".$this->db->escape($this->mainmenu)."',"; + $sql .= " leftmenu='".$this->db->escape($this->leftmenu)."',"; + $sql .= " fk_menu=".$this->fk_menu.","; + $sql .= " fk_mainmenu=".($this->fk_mainmenu ? "'".$this->db->escape($this->fk_mainmenu)."'" : "null").","; + $sql .= " fk_leftmenu=".($this->fk_leftmenu ? "'".$this->db->escape($this->fk_leftmenu)."'" : "null").","; + $sql .= " position=".($this->position > 0 ? $this->position : 0).","; + $sql .= " url='".$this->db->escape($this->url)."',"; + $sql .= " target='".$this->db->escape($this->target)."',"; + $sql .= " titre='".$this->db->escape($this->titre)."',"; + $sql .= " langs='".$this->db->escape($this->langs)."',"; + $sql .= " perms='".$this->db->escape($this->perms)."',"; + $sql .= " enabled='".$this->db->escape($this->enabled)."',"; + $sql .= " usertype='".$this->db->escape($this->user)."'"; + $sql .= " WHERE rowid=".$this->id; dol_syslog(get_class($this)."::update", LOG_DEBUG); $resql = $this->db->query($sql); - if (! $resql) + if (!$resql) { - $this->error="Error ".$this->db->lasterror(); + $this->error = "Error ".$this->db->lasterror(); return -1; } @@ -311,40 +374,40 @@ class Menubase */ public function fetch($id, $user = null) { - global $langs; + //global $langs; $sql = "SELECT"; - $sql.= " t.rowid,"; - $sql.= " t.menu_handler,"; - $sql.= " t.entity,"; - $sql.= " t.module,"; - $sql.= " t.type,"; - $sql.= " t.mainmenu,"; - $sql.= " t.leftmenu,"; - $sql.= " t.fk_menu,"; - $sql.= " t.fk_mainmenu,"; - $sql.= " t.fk_leftmenu,"; - $sql.= " t.position,"; - $sql.= " t.url,"; - $sql.= " t.target,"; - $sql.= " t.titre,"; - $sql.= " t.langs,"; - $sql.= " t.perms,"; - $sql.= " t.enabled,"; - $sql.= " t.usertype as user,"; - $sql.= " t.tms"; - $sql.= " FROM ".MAIN_DB_PREFIX."menu as t"; - $sql.= " WHERE t.rowid = ".$id; + $sql .= " t.rowid,"; + $sql .= " t.menu_handler,"; + $sql .= " t.entity,"; + $sql .= " t.module,"; + $sql .= " t.type,"; + $sql .= " t.mainmenu,"; + $sql .= " t.leftmenu,"; + $sql .= " t.fk_menu,"; + $sql .= " t.fk_mainmenu,"; + $sql .= " t.fk_leftmenu,"; + $sql .= " t.position,"; + $sql .= " t.url,"; + $sql .= " t.target,"; + $sql .= " t.titre,"; + $sql .= " t.langs,"; + $sql .= " t.perms,"; + $sql .= " t.enabled,"; + $sql .= " t.usertype as user,"; + $sql .= " t.tms"; + $sql .= " FROM ".MAIN_DB_PREFIX."menu as t"; + $sql .= " WHERE t.rowid = ".$id; dol_syslog(get_class($this)."::fetch", LOG_DEBUG); - $resql=$this->db->query($sql); + $resql = $this->db->query($sql); if ($resql) { if ($this->db->num_rows($resql)) { $obj = $this->db->fetch_object($resql); - $this->id = $obj->rowid; + $this->id = $obj->rowid; $this->menu_handler = $obj->menu_handler; $this->entity = $obj->entity; @@ -371,7 +434,7 @@ class Menubase } else { - $this->error="Error ".$this->db->lasterror(); + $this->error = "Error ".$this->db->lasterror(); return -1; } } @@ -385,16 +448,16 @@ class Menubase */ public function delete($user) { - global $conf, $langs; + //global $conf, $langs; $sql = "DELETE FROM ".MAIN_DB_PREFIX."menu"; - $sql.= " WHERE rowid=".$this->id; + $sql .= " WHERE rowid=".$this->id; dol_syslog(get_class($this)."::delete", LOG_DEBUG); $resql = $this->db->query($sql); - if (! $resql) + if (!$resql) { - $this->error="Error ".$this->db->lasterror(); + $this->error = "Error ".$this->db->lasterror(); return -1; } @@ -411,25 +474,25 @@ class Menubase */ public function initAsSpecimen() { - $this->id=0; + $this->id = 0; - $this->menu_handler='all'; - $this->module='specimen'; - $this->type='top'; - $this->mainmenu=''; - $this->fk_menu='0'; - $this->position=''; - $this->url='http://dummy'; - $this->target=''; - $this->titre='Specimen menu'; // deprecated - $this->title='Specimen menu'; - $this->langs=''; - $this->level=''; - $this->leftmenu=''; - $this->perms=''; - $this->enabled=''; - $this->user=''; - $this->tms=''; + $this->menu_handler = 'all'; + $this->module = 'specimen'; + $this->type = 'top'; + $this->mainmenu = ''; + $this->fk_menu = '0'; + $this->position = ''; + $this->url = 'http://dummy'; + $this->target = ''; + $this->titre = 'Specimen menu'; // deprecated + $this->title = 'Specimen menu'; + $this->langs = ''; + $this->level = ''; + $this->leftmenu = ''; + $this->perms = ''; + $this->enabled = ''; + $this->user = ''; + $this->tms = ''; } @@ -445,16 +508,16 @@ class Menubase */ public function menuTopCharger($mymainmenu, $myleftmenu, $type_user, $menu_handler, &$tabMenu) { - global $langs, $user, $conf; // To export to dol_eval function - global $mainmenu,$leftmenu; // To export to dol_eval function + global $langs, $user, $conf; // To export to dol_eval function + global $mainmenu, $leftmenu; // To export to dol_eval function - $mainmenu=$mymainmenu; // To export to dol_eval function - $leftmenu=$myleftmenu; // To export to dol_eval function + $mainmenu = $mymainmenu; // To export to dol_eval function + $leftmenu = $myleftmenu; // To export to dol_eval function - $newTabMenu=array(); - foreach($tabMenu as $val) + $newTabMenu = array(); + foreach ($tabMenu as $val) { - if ($val['type']=='top') $newTabMenu[]=$val; + if ($val['type'] == 'top') $newTabMenu[] = $val; } return $newTabMenu; @@ -474,20 +537,20 @@ class Menubase */ public function menuLeftCharger($newmenu, $mymainmenu, $myleftmenu, $type_user, $menu_handler, &$tabMenu) { - global $langs, $user, $conf; // To export to dol_eval function - global $mainmenu,$leftmenu; // To export to dol_eval function + global $langs, $user, $conf; // To export to dol_eval function + global $mainmenu, $leftmenu; // To export to dol_eval function - $mainmenu=$mymainmenu; // To export to dol_eval function - $leftmenu=$myleftmenu; // To export to dol_eval function + $mainmenu = $mymainmenu; // To export to dol_eval function + $leftmenu = $myleftmenu; // To export to dol_eval function // Detect what is top mainmenu id - $menutopid=''; - foreach($tabMenu as $key => $val) + $menutopid = ''; + foreach ($tabMenu as $key => $val) { // Define menutopid of mainmenu if (empty($menutopid) && $val['type'] == 'top' && $val['mainmenu'] == $mainmenu) { - $menutopid=$val['rowid']; + $menutopid = $val['rowid']; break; } } @@ -499,7 +562,7 @@ class Menubase $this->recur($tabMenu, $menutopid, 1); // Now complete $this->newmenu->list when fk_menu value is -1 (left menu added by modules with no top menu) - foreach($tabMenu as $key => $val) + foreach ($tabMenu as $key => $val) { //var_dump($tabMenu); if ($val['fk_menu'] == -1 && $val['fk_mainmenu'] == $mainmenu) // We found a menu entry not linked to parent with good mainmenu @@ -515,16 +578,16 @@ class Menubase else { // Search first menu with this couple (mainmenu,leftmenu)=(fk_mainmenu,fk_leftmenu) - $searchlastsub=0;$lastid=0;$nextid=0;$found=0; - foreach($this->newmenu->liste as $keyparent => $valparent) + $searchlastsub = 0; $lastid = 0; $nextid = 0; $found = 0; + foreach ($this->newmenu->liste as $keyparent => $valparent) { //var_dump($valparent); if ($searchlastsub) // If we started to search for last submenu { - if ($valparent['level'] >= $searchlastsub) $lastid=$keyparent; + if ($valparent['level'] >= $searchlastsub) $lastid = $keyparent; if ($valparent['level'] < $searchlastsub) { - $nextid=$keyparent; + $nextid = $keyparent; break; } } @@ -532,9 +595,9 @@ class Menubase { //print "We found parent: keyparent='.$keyparent.' - level=".$valparent['level'].' - '.join(',',$valparent).'
    '; // Now we look to find last subelement of this parent (we add at end) - $searchlastsub=($valparent['level']+1); - $lastid=$keyparent; - $found=1; + $searchlastsub = ($valparent['level'] + 1); + $lastid = $keyparent; + $found = 1; } } //print 'We must insert menu entry between entry '.$lastid.' and '.$nextid.'
    '; @@ -566,22 +629,19 @@ class Menubase global $langs, $user, $conf; // To export to dol_eval function global $mainmenu, $leftmenu; // To export to dol_eval function - $menutopid=0; - $mainmenu=$mymainmenu; // To export to dol_eval function - $leftmenu=$myleftmenu; // To export to dol_eval function + $mainmenu = $mymainmenu; // To export to dol_eval function + $leftmenu = $myleftmenu; // To export to dol_eval function $sql = "SELECT m.rowid, m.type, m.module, m.fk_menu, m.fk_mainmenu, m.fk_leftmenu, m.url, m.titre, m.langs, m.perms, m.enabled, m.target, m.mainmenu, m.leftmenu, m.position"; - $sql.= " FROM ".MAIN_DB_PREFIX."menu as m"; - $sql.= " WHERE m.entity IN (0,".$conf->entity.")"; - $sql.= " AND m.menu_handler IN ('".$menu_handler."','all')"; - if ($type_user == 0) $sql.= " AND m.usertype IN (0,2)"; - if ($type_user == 1) $sql.= " AND m.usertype IN (1,2)"; - $sql.= " ORDER BY m.position, m.rowid"; + $sql .= " FROM ".MAIN_DB_PREFIX."menu as m"; + $sql .= " WHERE m.entity IN (0,".$conf->entity.")"; + $sql .= " AND m.menu_handler IN ('".$menu_handler."','all')"; + if ($type_user == 0) $sql .= " AND m.usertype IN (0,2)"; + if ($type_user == 1) $sql .= " AND m.usertype IN (1,2)"; + $sql .= " ORDER BY m.position, m.rowid"; //print $sql; - //$tmp1=microtime(true); - //print '>>> 1 0
    '; - dol_syslog(get_class($this)."::menuLoad mymainmenu=".$mymainmenu." myleftmenu=".$myleftmenu." type_user=".$type_user." menu_handler=".$menu_handler." tabMenu size=".count($tabMenu)."", LOG_DEBUG); + //dol_syslog(get_class($this)."::menuLoad mymainmenu=".$mymainmenu." myleftmenu=".$myleftmenu." type_user=".$type_user." menu_handler=".$menu_handler." tabMenu size=".count($tabMenu)."", LOG_DEBUG); $resql = $this->db->query($sql); if ($resql) { @@ -598,8 +658,8 @@ class Menubase $perms = true; if ($menu['perms']) { - $tmpcond=$menu['perms']; - if ($leftmenu == 'all') $tmpcond=preg_replace('/\$leftmenu\s*==\s*["\'a-zA-Z_]+/', '1==1', $tmpcond); // Force part of condition to true + $tmpcond = $menu['perms']; + if ($leftmenu == 'all') $tmpcond = preg_replace('/\$leftmenu\s*==\s*["\'a-zA-Z_]+/', '1==1', $tmpcond); // Force part of condition to true $perms = verifCond($tmpcond); //print "verifCond rowid=".$menu['rowid']." ".$tmpcond.":".$perms."
    \n"; } @@ -608,19 +668,19 @@ class Menubase $enabled = true; if ($menu['enabled']) { - $tmpcond=$menu['enabled']; - if ($leftmenu == 'all') $tmpcond=preg_replace('/\$leftmenu\s*==\s*["\'a-zA-Z_]+/', '1==1', $tmpcond); // Force part of condition to true + $tmpcond = $menu['enabled']; + if ($leftmenu == 'all') $tmpcond = preg_replace('/\$leftmenu\s*==\s*["\'a-zA-Z_]+/', '1==1', $tmpcond); // Force part of condition to true $enabled = verifCond($tmpcond); } // Define $title if ($enabled) { - $title = $langs->trans($menu['titre']); // If $menu['titre'] start with $, a dol_eval is done. + $title = $langs->trans($menu['titre']); // If $menu['titre'] start with $, a dol_eval is done. //var_dump($title.'-'.$menu['titre']); if ($title == $menu['titre']) // Translation not found { - if (! empty($menu['langs'])) // If there is a dedicated translation file + if (!empty($menu['langs'])) // If there is a dedicated translation file { //print 'Load file '.$menu['langs'].'
    '; $langs->load($menu['langs']); @@ -655,10 +715,10 @@ class Menubase $tabMenu[$b]['module'] = $menu['module']; $tabMenu[$b]['fk_menu'] = $menu['fk_menu']; $tabMenu[$b]['url'] = $menu['url']; - if (! preg_match("/^(http:\/\/|https:\/\/)/i", $tabMenu[$b]['url'])) + if (!preg_match("/^(http:\/\/|https:\/\/)/i", $tabMenu[$b]['url'])) { - if (preg_match('/\?/', $tabMenu[$b]['url'])) $tabMenu[$b]['url'].='&idmenu='.$menu['rowid']; - else $tabMenu[$b]['url'].='?idmenu='.$menu['rowid']; + if (preg_match('/\?/', $tabMenu[$b]['url'])) $tabMenu[$b]['url'] .= '&idmenu='.$menu['rowid']; + else $tabMenu[$b]['url'] .= '?idmenu='.$menu['rowid']; } $tabMenu[$b]['titre'] = $title; $tabMenu[$b]['target'] = $menu['target']; @@ -707,10 +767,10 @@ class Menubase for ($x = 0; $x < $num; $x++) { //si un element a pour pere : $pere - if ( (($tab[$x]['fk_menu'] >= 0 && $tab[$x]['fk_menu'] == $pere)) && $tab[$x]['enabled']) + if ((($tab[$x]['fk_menu'] >= 0 && $tab[$x]['fk_menu'] == $pere)) && $tab[$x]['enabled']) { - $this->newmenu->add($tab[$x]['url'], $tab[$x]['titre'], ($level-1), $tab[$x]['perms'], $tab[$x]['target'], $tab[$x]['mainmenu'], $tab[$x]['leftmenu']); - $this->recur($tab, $tab[$x]['rowid'], ($level+1)); + $this->newmenu->add($tab[$x]['url'], $tab[$x]['titre'], ($level - 1), $tab[$x]['perms'], $tab[$x]['target'], $tab[$x]['mainmenu'], $tab[$x]['leftmenu']); + $this->recur($tab, $tab[$x]['rowid'], ($level + 1)); } } } diff --git a/htdocs/core/class/smtps.class.php b/htdocs/core/class/smtps.class.php index d950f92b3c2..9eebf9091b2 100644 --- a/htdocs/core/class/smtps.class.php +++ b/htdocs/core/class/smtps.class.php @@ -1304,13 +1304,6 @@ class SMTPs $_header .= 'Bcc: ' . $this->getBCC() . "\r\n"; */ - $host=$this->getHost(); - $usetls = preg_match('@tls://@i', $host); - - $host=preg_replace('@tcp://@i', '', $host); // Remove prefix - $host=preg_replace('@ssl://@i', '', $host); // Remove prefix - $host=preg_replace('@tls://@i', '', $host); // Remove prefix - $host=dol_getprefix('email'); //NOTE: Message-ID should probably contain the username of the user who sent the msg @@ -1385,7 +1378,7 @@ class SMTPs // Similar code to forge a text from html is also in CMailFile.class.php $strContentAltText = preg_replace("/]*>/", " ", $strContent); $strContentAltText = html_entity_decode(strip_tags($strContentAltText)); - $strContentAltText = rtrim(wordwrap($strContentAltText, 75, "\r\n")); + $strContentAltText = trim(wordwrap($strContentAltText, 75, "\r\n")); } // Make RFC2045 Compliant diff --git a/htdocs/core/db/DoliDB.class.php b/htdocs/core/db/DoliDB.class.php index eb13095aaf0..29d77c089c0 100644 --- a/htdocs/core/db/DoliDB.class.php +++ b/htdocs/core/db/DoliDB.class.php @@ -29,7 +29,7 @@ require_once DOL_DOCUMENT_ROOT .'/core/db/Database.interface.php'; */ abstract class DoliDB implements Database { - /** @var resource Database handler */ + /** @var bool|resource Database handler */ public $db; /** @var string Database type */ public $type; diff --git a/htdocs/core/db/mysqli.class.php b/htdocs/core/db/mysqli.class.php index 902c3049cc4..a6f35a69fb9 100644 --- a/htdocs/core/db/mysqli.class.php +++ b/htdocs/core/db/mysqli.class.php @@ -40,7 +40,7 @@ class DoliDBMysqli extends DoliDB const LABEL='MySQL or MariaDB'; //! Version min database const VERSIONMIN='5.0.3'; - /** @var mysqli_result Resultset of last query */ + /** @var bool|mysqli_result Resultset of last query */ private $_results; /** @@ -187,12 +187,12 @@ class DoliDBMysqli extends DoliDB /** * Connect to server * - * @param string $host database server host - * @param string $login login - * @param string $passwd password - * @param string $name name of database (not used for mysql, used for pgsql) - * @param integer $port Port of database server - * @return mysqli Database access object + * @param string $host Database server host + * @param string $login Login + * @param string $passwd Password + * @param string $name Name of database (not used for mysql, used for pgsql) + * @param integer $port Port of database server + * @return mysqli Database access object * @see close() */ public function connect($host, $login, $passwd, $name, $port = 0) diff --git a/htdocs/core/db/pgsql.class.php b/htdocs/core/db/pgsql.class.php index 2388b60c7e1..28821f31725 100644 --- a/htdocs/core/db/pgsql.class.php +++ b/htdocs/core/db/pgsql.class.php @@ -401,7 +401,7 @@ class DoliDBPgsql extends DoliDB * @param string $passwd Password * @param string $name Name of database (not used for mysql, used for pgsql) * @param integer $port Port of database server - * @return false|resource Database access handler + * @return bool|resource Database access handler * @see close() */ public function connect($host, $login, $passwd, $name, $port = 0) diff --git a/htdocs/core/lib/admin.lib.php b/htdocs/core/lib/admin.lib.php index 1d3f7eb65c3..a38a9c4289c 100644 --- a/htdocs/core/lib/admin.lib.php +++ b/htdocs/core/lib/admin.lib.php @@ -1427,7 +1427,7 @@ function form_constantes($tableau, $strictw3c = 0, $helptext = '') print ''; } - print ''; + print '
    '; print ''; print ''; print '
    '.$langs->trans("Description").''; diff --git a/htdocs/core/lib/agenda.lib.php b/htdocs/core/lib/agenda.lib.php index ad17cd259bd..ed228294bf5 100644 --- a/htdocs/core/lib/agenda.lib.php +++ b/htdocs/core/lib/agenda.lib.php @@ -238,7 +238,7 @@ function show_array_actions_to_do($max = 5) $num = $db->num_rows($resql); print '
    '; - print ''; + print '
    '; print ''; print ''; print ''; @@ -336,7 +336,7 @@ function show_array_last_actions_done($max = 5) $num = $db->num_rows($resql); print '
    '; - print '
    '.$langs->trans("LastActionsToDo", $max).''.$langs->trans("FullList").'
    '; + print '
    '; print ''; print ''; print ''; diff --git a/htdocs/core/lib/bank.lib.php b/htdocs/core/lib/bank.lib.php index c4849d59adc..fb9c607eb72 100644 --- a/htdocs/core/lib/bank.lib.php +++ b/htdocs/core/lib/bank.lib.php @@ -3,6 +3,7 @@ * Copyright (C) 2012 Regis Houssin * Copyright (C) 2015 Alexandre Spangaro * Copyright (C) 2016 Juanjo Menent + * Copyright (C) 2019 Nicolas ZABOURI * * 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 @@ -37,42 +38,42 @@ function bank_prepare_head(Account $object) $h = 0; $head = array(); - $head[$h][0] = DOL_URL_ROOT . '/compta/bank/card.php?id=' . $object->id; + $head[$h][0] = DOL_URL_ROOT.'/compta/bank/card.php?id='.$object->id; $head[$h][1] = $langs->trans("Card"); $head[$h][2] = 'bankname'; $h++; - $head[$h][0] = DOL_URL_ROOT . "/compta/bank/bankentries_list.php?id=" . $object->id; + $head[$h][0] = DOL_URL_ROOT."/compta/bank/bankentries_list.php?id=".$object->id; $head[$h][1] = $langs->trans("BankTransactions"); $head[$h][2] = 'journal'; $h++; // if ($conf->global->MAIN_FEATURES_LEVEL >= 1) // { - $head[$h][0] = DOL_URL_ROOT . "/compta/bank/treso.php?account=" . $object->id; + $head[$h][0] = DOL_URL_ROOT."/compta/bank/treso.php?account=".$object->id; $head[$h][1] = $langs->trans("PlannedTransactions"); $head[$h][2] = 'cash'; $h++; // } - $head[$h][0] = DOL_URL_ROOT . "/compta/bank/annuel.php?account=" . $object->id; + $head[$h][0] = DOL_URL_ROOT."/compta/bank/annuel.php?account=".$object->id; $head[$h][1] = $langs->trans("IOMonthlyReporting"); $head[$h][2] = 'annual'; $h++; - $head[$h][0] = DOL_URL_ROOT . "/compta/bank/graph.php?account=" . $object->id; + $head[$h][0] = DOL_URL_ROOT."/compta/bank/graph.php?account=".$object->id; $head[$h][1] = $langs->trans("Graph"); $head[$h][2] = 'graph'; $h++; if ($object->courant != Account::TYPE_CASH) { - $nbReceipts=0; + $nbReceipts = 0; // List of all standing receipts $sql = "SELECT COUNT(DISTINCT(b.num_releve)) as nb"; - $sql.= " FROM ".MAIN_DB_PREFIX."bank as b"; - $sql.= " WHERE b.fk_account = ".$object->id; + $sql .= " FROM ".MAIN_DB_PREFIX."bank as b"; + $sql .= " WHERE b.fk_account = ".$object->id; $resql = $db->query($sql); if ($resql) @@ -84,7 +85,7 @@ function bank_prepare_head(Account $object) $head[$h][0] = DOL_URL_ROOT."/compta/bank/releve.php?account=".$object->id; $head[$h][1] = $langs->trans("AccountStatements"); - if (($nbReceipts) > 0) $head[$h][1].= ''.($nbReceipts).''; + if (($nbReceipts) > 0) $head[$h][1] .= ''.($nbReceipts).''; $head[$h][2] = 'statement'; $h++; } @@ -92,12 +93,12 @@ function bank_prepare_head(Account $object) // Attached files require_once DOL_DOCUMENT_ROOT.'/core/lib/files.lib.php'; require_once DOL_DOCUMENT_ROOT.'/core/class/link.class.php'; - $upload_dir = $conf->bank->dir_output . "/" . dol_sanitizeFileName($object->ref); + $upload_dir = $conf->bank->dir_output."/".dol_sanitizeFileName($object->ref); $nbFiles = count(dol_dir_list($upload_dir, 'files', 0, '', '(\.meta|_preview.*\.png)$')); - $nbLinks=Link::count($db, $object->element, $object->id); - $head[$h][0] = DOL_URL_ROOT . "/compta/bank/document.php?account=" . $object->id; + $nbLinks = Link::count($db, $object->element, $object->id); + $head[$h][0] = DOL_URL_ROOT."/compta/bank/document.php?account=".$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++; @@ -128,12 +129,12 @@ function bank_admin_prepare_head($object) $h = 0; $head = array(); - $head[$h][0] = DOL_URL_ROOT . '/admin/bank.php'; + $head[$h][0] = DOL_URL_ROOT.'/admin/bank.php'; $head[$h][1] = $langs->trans("Miscellaneous"); $head[$h][2] = 'general'; $h++; - $head[$h][0] = DOL_URL_ROOT . '/admin/chequereceipts.php'; + $head[$h][0] = DOL_URL_ROOT.'/admin/chequereceipts.php'; $head[$h][1] = $langs->trans("CheckReceiptShort"); $head[$h][2] = 'checkreceipts'; $h++; @@ -152,9 +153,50 @@ function bank_admin_prepare_head($object) complete_head_from_modules($conf, $langs, $object, $head, $h, 'bank_admin', 'remove'); + return $head; } + +/** + * Prepare array with list of tabs + * + * @param Object $object Object related to tabs + * @param Object $num val to account statement + * @return array Array of tabs to shoc + */ +function account_statement_prepare_head($object, $num) +{ + global $langs, $conf, $user, $db; + $h = 0; + $head = array(); + + $head[$h][0] = DOL_URL_ROOT.'/compta/bank/releve.php?account='.$object->id.'&num='.$num; + $head[$h][1] = $langs->trans("AccountStatements"); + $head[$h][2] = 'statement'; + $h++; + + // Attached files + require_once DOL_DOCUMENT_ROOT.'/core/lib/files.lib.php'; + require_once DOL_DOCUMENT_ROOT.'/core/class/link.class.php'; + $upload_dir = $conf->bank->dir_output."/".$object->id.'/'.dol_sanitizeFileName($num); + $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."/compta/bank/account_statement_document.php?account=".$object->id."&num=".$num; + $head[$h][1] = $langs->trans("Documents"); + if (($nbFiles + $nbLinks) > 0) $head[$h][1] .= ' '.($nbFiles + $nbLinks).''; + $head[$h][2] = 'document'; + $h++; + + complete_head_from_modules($conf, $langs, $object, $head, $h, 'account_statement'); + + complete_head_from_modules($conf, $langs, $object, $head, $h, 'account_statement', 'remove'); + + return $head; +} + + /** * Prepare array with list of tabs * @@ -181,12 +223,12 @@ function various_payment_prepare_head($object) require_once DOL_DOCUMENT_ROOT.'/core/lib/files.lib.php'; require_once DOL_DOCUMENT_ROOT.'/core/class/link.class.php'; - $upload_dir = $conf->bank->dir_output . "/" . dol_sanitizeFileName($object->ref); + $upload_dir = $conf->bank->dir_output."/".dol_sanitizeFileName($object->ref); $nbFiles = count(dol_dir_list($upload_dir, 'files', 0, '', '(\.meta|_preview.*\.png)$')); - $nbLinks=Link::count($db, $object->element, $object->id); + $nbLinks = Link::count($db, $object->element, $object->id); $head[$h][0] = DOL_URL_ROOT.'/compta/bank/various_payment/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++; @@ -251,12 +293,12 @@ function checkBanForAccount($account) if (empty($account->cle)) $account->cle = $account->cle_rib; - dol_syslog("bank.lib::checkBanForAccount account->code_banque=" . $account->code_banque . " account->code_guichet=" . $account->code_guichet . " account->number=" . $account->number . " account->cle=" . $account->cle . " account->iban=" . $account->iban . " country_code=" . $country_code, LOG_DEBUG); + dol_syslog("bank.lib::checkBanForAccount account->code_banque=".$account->code_banque." account->code_guichet=".$account->code_guichet." account->number=".$account->number." account->cle=".$account->cle." account->iban=".$account->iban." country_code=".$country_code, LOG_DEBUG); if ($country_code == 'FR') { // France rules $coef = array(62, 34, 3); // Concatenation des differents codes. - $rib = strtolower(trim($account->code_banque) . trim($account->code_guichet) . trim($account->number) . trim($account->cle)); + $rib = strtolower(trim($account->code_banque).trim($account->code_guichet).trim($account->number).trim($account->cle)); // On remplace les eventuelles lettres par des chiffres. //$rib = strtr($rib, "abcdefghijklmnopqrstuvwxyz","12345678912345678912345678"); //Ne marche pas $rib = strtr($rib, "abcdefghijklmnopqrstuvwxyz", "12345678912345678923456789"); @@ -280,7 +322,7 @@ function checkBanForAccount($account) if ($country_code == 'ES') { // Spanish rules $CCC = strtolower(trim($account->number)); - $rib = strtolower(trim($account->code_banque) . trim($account->code_guichet)); + $rib = strtolower(trim($account->code_banque).trim($account->code_guichet)); $cle_rib = strtolower(checkES($rib, $CCC)); if ($cle_rib == strtolower($account->cle)) { return true; @@ -322,7 +364,7 @@ function checkES($IentOfi, $InumCta) return $keycontrol; } - $ccc = $IentOfi . $InumCta; + $ccc = $IentOfi.$InumCta; $numbers = "1234567890"; $i = 0; @@ -354,7 +396,7 @@ function checkES($IentOfi, $InumCta) $sum = 0; for ($i = 0; $i < 11; $i++) { - $sum += $values[$i] * (int) substr($InumCta, $i, 1);//int to cast result of substr to a number + $sum += $values[$i] * (int) substr($InumCta, $i, 1); //int to cast result of substr to a number } $key = 11 - $sum % 11; diff --git a/htdocs/core/lib/company.lib.php b/htdocs/core/lib/company.lib.php index d87f59eefa2..734810eb5e4 100644 --- a/htdocs/core/lib/company.lib.php +++ b/htdocs/core/lib/company.lib.php @@ -55,7 +55,7 @@ function societe_prepare_head(Societe $object) if (empty($conf->global->MAIN_DISABLE_CONTACTS_TAB)) { //$nbContact = count($object->liste_contact(-1,'internal')) + count($object->liste_contact(-1,'external')); - $nbContact = 0; // TODO + $nbContact = 0; // TODO $sql = "SELECT COUNT(p.rowid) as nb"; $sql .= " FROM ".MAIN_DB_PREFIX."socpeople as p"; @@ -69,7 +69,7 @@ function societe_prepare_head(Societe $object) $head[$h][0] = DOL_URL_ROOT.'/societe/contact.php?socid='.$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++; } @@ -79,22 +79,22 @@ function societe_prepare_head(Societe $object) $head[$h][0] = DOL_URL_ROOT.'/societe/societecontact.php?socid='.$object->id; $nbContact = count($object->liste_contact(-1, 'internal')) + count($object->liste_contact(-1, 'external')); $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 ($object->client==1 || $object->client==2 || $object->client==3) + if ($object->client == 1 || $object->client == 2 || $object->client == 3) { $head[$h][0] = DOL_URL_ROOT.'/comm/card.php?socid='.$object->id; $head[$h][1] = ''; - if (empty($conf->global->SOCIETE_DISABLE_PROSPECTS) && ($object->client==2 || $object->client==3)) $head[$h][1] .= $langs->trans("Prospect"); - if (empty($conf->global->SOCIETE_DISABLE_PROSPECTS) && empty($conf->global->SOCIETE_DISABLE_CUSTOMERS) && $object->client==3) $head[$h][1] .= ' | '; - if (empty($conf->global->SOCIETE_DISABLE_CUSTOMERS) && ($object->client==1 || $object->client==3)) $head[$h][1] .= $langs->trans("Customer"); + if (empty($conf->global->SOCIETE_DISABLE_PROSPECTS) && ($object->client == 2 || $object->client == 3)) $head[$h][1] .= $langs->trans("Prospect"); + if (empty($conf->global->SOCIETE_DISABLE_PROSPECTS) && empty($conf->global->SOCIETE_DISABLE_CUSTOMERS) && $object->client == 3) $head[$h][1] .= ' | '; + if (empty($conf->global->SOCIETE_DISABLE_CUSTOMERS) && ($object->client == 1 || $object->client == 3)) $head[$h][1] .= $langs->trans("Customer"); $head[$h][2] = 'customer'; $h++; - if (! empty($conf->global->PRODUIT_CUSTOMER_PRICES)) + if (!empty($conf->global->PRODUIT_CUSTOMER_PRICES)) { $langs->load("products"); // price @@ -104,7 +104,7 @@ function societe_prepare_head(Societe $object) $h++; } } - if (! empty($conf->fournisseur->enabled) && $object->fournisseur && ! empty($user->rights->fournisseur->lire)) + if (!empty($conf->fournisseur->enabled) && $object->fournisseur && !empty($user->rights->fournisseur->lire)) { $head[$h][0] = DOL_URL_ROOT.'/fourn/card.php?socid='.$object->id; $head[$h][1] = $langs->trans("Supplier"); @@ -112,16 +112,16 @@ function societe_prepare_head(Societe $object) $h++; } - if (! empty($conf->projet->enabled) && (!empty($user->rights->projet->lire) )) + if (!empty($conf->projet->enabled) && (!empty($user->rights->projet->lire))) { $head[$h][0] = DOL_URL_ROOT.'/societe/project.php?socid='.$object->id; $head[$h][1] = $langs->trans("Projects"); $nbNote = 0; $sql = "SELECT COUNT(n.rowid) as nb"; - $sql.= " FROM ".MAIN_DB_PREFIX."projet as n"; - $sql.= " WHERE fk_soc = ".$object->id; - $sql.= " AND entity IN (".getEntity('project').")"; - $resql=$db->query($sql); + $sql .= " FROM ".MAIN_DB_PREFIX."projet as n"; + $sql .= " WHERE fk_soc = ".$object->id; + $sql .= " AND entity IN (".getEntity('project').")"; + $resql = $db->query($sql); if ($resql) { $num = $db->num_rows($resql); @@ -129,20 +129,20 @@ function societe_prepare_head(Societe $object) while ($i < $num) { $obj = $db->fetch_object($resql); - $nbNote=$obj->nb; + $nbNote = $obj->nb; $i++; } } else { dol_print_error($db); } - if ($nbNote > 0) $head[$h][1].= ''.$nbNote.''; + if ($nbNote > 0) $head[$h][1] .= ''.$nbNote.''; $head[$h][2] = 'project'; $h++; } // Tab to link resources - if (! empty($conf->resource->enabled) && ! empty($conf->global->RESOURCE_ON_THIRDPARTIES)) + if (!empty($conf->resource->enabled) && !empty($conf->global->RESOURCE_ON_THIRDPARTIES)) { $head[$h][0] = DOL_URL_ROOT.'/resource/element_resource.php?element=societe&element_id='.$object->id; $head[$h][1] = $langs->trans("Resources"); @@ -150,10 +150,10 @@ function societe_prepare_head(Societe $object) $h++; } - if (! empty($conf->global->ACCOUNTING_ENABLE_LETTERING)) + if (!empty($conf->global->ACCOUNTING_ENABLE_LETTERING)) { // Tab to accountancy - if (! empty($conf->accounting->enabled) && $object->client>0) + if (!empty($conf->accounting->enabled) && $object->client > 0) { $head[$h][0] = DOL_URL_ROOT.'/accountancy/bookkeeping/thirdparty_lettering_customer.php?socid='.$object->id; $head[$h][1] = $langs->trans("TabLetteringCustomer"); @@ -162,7 +162,7 @@ function societe_prepare_head(Societe $object) } // Tab to accountancy - if (! empty($conf->accounting->enabled) && $object->fournisseur>0) + if (!empty($conf->accounting->enabled) && $object->fournisseur > 0) { $head[$h][0] = DOL_URL_ROOT.'/accountancy/bookkeeping/thirdparty_lettering_supplier.php?socid='.$object->id; $head[$h][1] = $langs->trans("TabLetteringSupplier"); @@ -172,7 +172,7 @@ function societe_prepare_head(Societe $object) } // Related items - if ((! empty($conf->commande->enabled) || ! empty($conf->propal->enabled) || ! empty($conf->facture->enabled) || ! empty($conf->ficheinter->enabled) || ! empty($conf->fournisseur->enabled)) + if ((!empty($conf->commande->enabled) || !empty($conf->propal->enabled) || !empty($conf->facture->enabled) || !empty($conf->ficheinter->enabled) || !empty($conf->fournisseur->enabled)) && empty($conf->global->THIRPARTIES_DISABLE_RELATED_OBJECT_TAB)) { $head[$h][0] = DOL_URL_ROOT.'/societe/consumption.php?socid='.$object->id; @@ -184,31 +184,31 @@ function societe_prepare_head(Societe $object) // Bank accounts if (empty($conf->global->SOCIETE_DISABLE_BANKACCOUNT)) { - $nbBankAccount=0; - $foundonexternalonlinesystem=0; + $nbBankAccount = 0; + $foundonexternalonlinesystem = 0; $langs->load("banks"); //$title = $langs->trans("BankAccounts"); $title = $langs->trans("PaymentInformation"); - if (! empty($conf->stripe->enabled)) + if (!empty($conf->stripe->enabled)) { //$langs->load("stripe"); //$title = $langs->trans("BankAccountsAndGateways"); $servicestatus = 0; - if (! empty($conf->global->STRIPE_LIVE) && ! GETPOST('forcesandbox', 'alpha')) $servicestatus = 1; + if (!empty($conf->global->STRIPE_LIVE) && !GETPOST('forcesandbox', 'alpha')) $servicestatus = 1; include_once DOL_DOCUMENT_ROOT.'/societe/class/societeaccount.class.php'; $societeaccount = new SocieteAccount($db); - $stripecu = $societeaccount->getCustomerAccount($object->id, 'stripe', $servicestatus); // Get thirdparty cu_... + $stripecu = $societeaccount->getCustomerAccount($object->id, 'stripe', $servicestatus); // Get thirdparty cu_... if ($stripecu) $foundonexternalonlinesystem++; } $sql = "SELECT COUNT(n.rowid) as nb"; - $sql.= " FROM ".MAIN_DB_PREFIX."societe_rib as n"; - $sql.= " WHERE fk_soc = ".$object->id; - $resql=$db->query($sql); + $sql .= " FROM ".MAIN_DB_PREFIX."societe_rib as n"; + $sql .= " WHERE fk_soc = ".$object->id; + $resql = $db->query($sql); if ($resql) { $num = $db->num_rows($resql); @@ -216,7 +216,7 @@ function societe_prepare_head(Societe $object) while ($i < $num) { $obj = $db->fetch_object($resql); - $nbBankAccount=$obj->nb; + $nbBankAccount = $obj->nb; $i++; } } @@ -226,23 +226,23 @@ function societe_prepare_head(Societe $object) //if (! empty($conf->stripe->enabled) && $nbBankAccount > 0) $nbBankAccount = '...'; // No way to know exact number - $head[$h][0] = DOL_URL_ROOT .'/societe/paymentmodes.php?socid='.$object->id; + $head[$h][0] = DOL_URL_ROOT.'/societe/paymentmodes.php?socid='.$object->id; $head[$h][1] = $title; - if ($foundonexternalonlinesystem) $head[$h][1].= ' ...'; - elseif ($nbBankAccount > 0) $head[$h][1].= ''.$nbBankAccount.''; + if ($foundonexternalonlinesystem) $head[$h][1] .= ' ...'; + elseif ($nbBankAccount > 0) $head[$h][1] .= ''.$nbBankAccount.''; $head[$h][2] = 'rib'; $h++; } - if (! empty($conf->website->enabled) && (! empty($conf->global->WEBSITE_USE_WEBSITE_ACCOUNTS)) && (!empty($user->rights->societe->lire))) + if (!empty($conf->website->enabled) && (!empty($conf->global->WEBSITE_USE_WEBSITE_ACCOUNTS)) && (!empty($user->rights->societe->lire))) { $head[$h][0] = DOL_URL_ROOT.'/societe/website.php?id='.$object->id; $head[$h][1] = $langs->trans("WebSiteAccounts"); $nbNote = 0; $sql = "SELECT COUNT(n.rowid) as nb"; - $sql.= " FROM ".MAIN_DB_PREFIX."societe_account as n"; - $sql.= " WHERE fk_soc = ".$object->id.' AND fk_website > 0'; - $resql=$db->query($sql); + $sql .= " FROM ".MAIN_DB_PREFIX."societe_account as n"; + $sql .= " WHERE fk_soc = ".$object->id.' AND fk_website > 0'; + $resql = $db->query($sql); if ($resql) { $num = $db->num_rows($resql); @@ -250,14 +250,14 @@ function societe_prepare_head(Societe $object) while ($i < $num) { $obj = $db->fetch_object($resql); - $nbNote=$obj->nb; + $nbNote = $obj->nb; $i++; } } else { dol_print_error($db); } - if ($nbNote > 0) $head[$h][1].= ''.$nbNote.''; + if ($nbNote > 0) $head[$h][1] .= ''.$nbNote.''; $head[$h][2] = 'website'; $h++; } @@ -271,13 +271,13 @@ function societe_prepare_head(Societe $object) if ($user->socid == 0) { // Notifications - if (! empty($conf->notification->enabled)) + if (!empty($conf->notification->enabled)) { $nbNote = 0; $sql = "SELECT COUNT(n.rowid) as nb"; - $sql.= " FROM ".MAIN_DB_PREFIX."notify_def as n"; - $sql.= " WHERE fk_soc = ".$object->id; - $resql=$db->query($sql); + $sql .= " FROM ".MAIN_DB_PREFIX."notify_def as n"; + $sql .= " WHERE fk_soc = ".$object->id; + $resql = $db->query($sql); if ($resql) { $num = $db->num_rows($resql); @@ -285,7 +285,7 @@ function societe_prepare_head(Societe $object) while ($i < $num) { $obj = $db->fetch_object($resql); - $nbNote=$obj->nb; + $nbNote = $obj->nb; $i++; } } @@ -295,41 +295,41 @@ function societe_prepare_head(Societe $object) $head[$h][0] = DOL_URL_ROOT.'/societe/notify/card.php?socid='.$object->id; $head[$h][1] = $langs->trans("Notifications"); - if ($nbNote > 0) $head[$h][1].= ''.$nbNote.''; + if ($nbNote > 0) $head[$h][1] .= ''.$nbNote.''; $head[$h][2] = 'notify'; $h++; } // Notes $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.'/societe/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++; // Attached files require_once DOL_DOCUMENT_ROOT.'/core/lib/files.lib.php'; require_once DOL_DOCUMENT_ROOT.'/core/class/link.class.php'; - $upload_dir = $conf->societe->multidir_output[$object->entity] . "/" . $object->id ; + $upload_dir = $conf->societe->multidir_output[$object->entity]."/".$object->id; $nbFiles = count(dol_dir_list($upload_dir, 'files', 0, '', '(\.meta|_preview.*\.png)$')); - $nbLinks=Link::count($db, $object->element, $object->id); + $nbLinks = Link::count($db, $object->element, $object->id); $head[$h][0] = DOL_URL_ROOT.'/societe/document.php?socid='.$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++; } $head[$h][0] = DOL_URL_ROOT.'/societe/agenda.php?socid='.$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) )) + $head[$h][1] .= $langs->trans("Events"); + 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"); + $head[$h][1] .= '/'; + $head[$h][1] .= $langs->trans("Agenda"); } $head[$h][2] = 'agenda'; $h++; @@ -430,46 +430,46 @@ function societe_admin_prepare_head() */ function getCountry($searchkey, $withcode = '', $dbtouse = 0, $outputlangs = '', $entconv = 1, $searchlabel = '') { - global $db,$langs; + global $db, $langs; - $result=''; + $result = ''; // Check parameters if (empty($searchkey) && empty($searchlabel)) { - if ($withcode === 'all') return array('id'=>'','code'=>'','label'=>''); + if ($withcode === 'all') return array('id'=>'', 'code'=>'', 'label'=>''); else return ''; } - if (! is_object($dbtouse)) $dbtouse=$db; - if (! is_object($outputlangs)) $outputlangs=$langs; + if (!is_object($dbtouse)) $dbtouse = $db; + if (!is_object($outputlangs)) $outputlangs = $langs; $sql = "SELECT rowid, code, label FROM ".MAIN_DB_PREFIX."c_country"; - if (is_numeric($searchkey)) $sql.= " WHERE rowid=".$searchkey; - elseif (! empty($searchkey)) $sql.= " WHERE code='".$db->escape($searchkey)."'"; - else $sql.= " WHERE label='".$db->escape($searchlabel)."'"; + if (is_numeric($searchkey)) $sql .= " WHERE rowid=".$searchkey; + elseif (!empty($searchkey)) $sql .= " WHERE code='".$db->escape($searchkey)."'"; + else $sql .= " WHERE label='".$db->escape($searchlabel)."'"; - $resql=$dbtouse->query($sql); + $resql = $dbtouse->query($sql); if ($resql) { $obj = $dbtouse->fetch_object($resql); if ($obj) { - $label=((! empty($obj->label) && $obj->label!='-')?$obj->label:''); + $label = ((!empty($obj->label) && $obj->label != '-') ? $obj->label : ''); if (is_object($outputlangs)) { $outputlangs->load("dict"); - if ($entconv) $label=($obj->code && ($outputlangs->trans("Country".$obj->code)!="Country".$obj->code))?$outputlangs->trans("Country".$obj->code):$label; - else $label=($obj->code && ($outputlangs->transnoentitiesnoconv("Country".$obj->code)!="Country".$obj->code))?$outputlangs->transnoentitiesnoconv("Country".$obj->code):$label; + if ($entconv) $label = ($obj->code && ($outputlangs->trans("Country".$obj->code) != "Country".$obj->code)) ? $outputlangs->trans("Country".$obj->code) : $label; + else $label = ($obj->code && ($outputlangs->transnoentitiesnoconv("Country".$obj->code) != "Country".$obj->code)) ? $outputlangs->transnoentitiesnoconv("Country".$obj->code) : $label; } - if ($withcode == 1) $result=$label?"$obj->code - $label":"$obj->code"; - elseif ($withcode == 2) $result=$obj->code; - elseif ($withcode == 3) $result=$obj->rowid; - elseif ($withcode === 'all') $result=array('id'=>$obj->rowid,'code'=>$obj->code,'label'=>$label); - else $result=$label; + if ($withcode == 1) $result = $label ? "$obj->code - $label" : "$obj->code"; + elseif ($withcode == 2) $result = $obj->code; + elseif ($withcode == 3) $result = $obj->rowid; + elseif ($withcode === 'all') $result = array('id'=>$obj->rowid, 'code'=>$obj->code, 'label'=>$label); + else $result = $label; } else { - $result='NotDefined'; + $result = 'NotDefined'; } $dbtouse->free($resql); return $result; @@ -495,58 +495,58 @@ function getCountry($searchkey, $withcode = '', $dbtouse = 0, $outputlangs = '', */ function getState($id, $withcode = '', $dbtouse = 0, $withregion = 0, $outputlangs = '', $entconv = 1) { - global $db,$langs; + global $db, $langs; - if (! is_object($dbtouse)) $dbtouse=$db; + if (!is_object($dbtouse)) $dbtouse = $db; $sql = "SELECT d.rowid as id, d.code_departement as code, d.nom as name, d.active, c.label as country, c.code as country_code, r.code_region as region_code, r.nom as region_name FROM"; - $sql .= " ".MAIN_DB_PREFIX ."c_departements as d, ".MAIN_DB_PREFIX."c_regions as r,".MAIN_DB_PREFIX."c_country as c"; + $sql .= " ".MAIN_DB_PREFIX."c_departements as d, ".MAIN_DB_PREFIX."c_regions as r,".MAIN_DB_PREFIX."c_country as c"; $sql .= " WHERE d.fk_region=r.code_region and r.fk_pays=c.rowid and d.rowid=".$id; $sql .= " AND d.active = 1 AND r.active = 1 AND c.active = 1"; $sql .= " ORDER BY c.code, d.code_departement"; dol_syslog("Company.lib::getState", LOG_DEBUG); - $resql=$dbtouse->query($sql); + $resql = $dbtouse->query($sql); if ($resql) { $obj = $dbtouse->fetch_object($resql); if ($obj) { - $label=((! empty($obj->name) && $obj->name!='-')?$obj->name:''); + $label = ((!empty($obj->name) && $obj->name != '-') ? $obj->name : ''); if (is_object($outputlangs)) { $outputlangs->load("dict"); - if ($entconv) $label=($obj->code && ($outputlangs->trans("State".$obj->code)!="State".$obj->code))?$outputlangs->trans("State".$obj->code):$label; - else $label=($obj->code && ($outputlangs->transnoentitiesnoconv("State".$obj->code)!="State".$obj->code))?$outputlangs->transnoentitiesnoconv("State".$obj->code):$label; + if ($entconv) $label = ($obj->code && ($outputlangs->trans("State".$obj->code) != "State".$obj->code)) ? $outputlangs->trans("State".$obj->code) : $label; + else $label = ($obj->code && ($outputlangs->transnoentitiesnoconv("State".$obj->code) != "State".$obj->code)) ? $outputlangs->transnoentitiesnoconv("State".$obj->code) : $label; } if ($withcode == 1) { if ($withregion == 1) { - return $label = $obj->region_name . ' - ' . $obj->code . ' - ' . ($langs->trans($obj->code)!=$obj->code?$langs->trans($obj->code):($obj->name!='-'?$obj->name:'')); + return $label = $obj->region_name.' - '.$obj->code.' - '.($langs->trans($obj->code) != $obj->code ? $langs->trans($obj->code) : ($obj->name != '-' ? $obj->name : '')); } else { - return $label = $obj->code . ' - ' . ($langs->trans($obj->code)!=$obj->code?$langs->trans($obj->code):($obj->name!='-'?$obj->name:'')); + return $label = $obj->code.' - '.($langs->trans($obj->code) != $obj->code ? $langs->trans($obj->code) : ($obj->name != '-' ? $obj->name : '')); } } elseif ($withcode == 2) { if ($withregion == 1) { - return $label = $obj->region_name . ' - ' . ($langs->trans($obj->code)!=$obj->code?$langs->trans($obj->code):($obj->name!='-'?$obj->name:'')); + return $label = $obj->region_name.' - '.($langs->trans($obj->code) != $obj->code ? $langs->trans($obj->code) : ($obj->name != '-' ? $obj->name : '')); } else { - return $label = ($langs->trans($obj->code)!=$obj->code?$langs->trans($obj->code):($obj->name!='-'?$obj->name:'')); + return $label = ($langs->trans($obj->code) != $obj->code ? $langs->trans($obj->code) : ($obj->name != '-' ? $obj->name : '')); } } elseif ($withcode === 'all') { if ($withregion == 1) { - return array('id'=>$obj->id,'code'=>$obj->code,'label'=>$label,'region_code'=>$obj->region_code,'region'=>$obj->region_name); + return array('id'=>$obj->id, 'code'=>$obj->code, 'label'=>$label, 'region_code'=>$obj->region_code, 'region'=>$obj->region_name); } else { - return array('id'=>$obj->id,'code'=>$obj->code,'label'=>$label); + return array('id'=>$obj->id, 'code'=>$obj->code, 'label'=>$label); } } else { if ($withregion == 1) { - return $label = $obj->region_name . ' - ' . $label; + return $label = $obj->region_name.' - '.$label; } else { return $label; @@ -571,23 +571,23 @@ function getState($id, $withcode = '', $dbtouse = 0, $withregion = 0, $outputlan */ function currency_name($code_iso, $withcode = '', $outputlangs = null) { - global $langs,$db; + global $langs, $db; - if (empty($outputlangs)) $outputlangs=$langs; + if (empty($outputlangs)) $outputlangs = $langs; $outputlangs->load("dict"); // If there is a translation, we can send immediatly the label - if ($outputlangs->trans("Currency".$code_iso)!="Currency".$code_iso) + if ($outputlangs->trans("Currency".$code_iso) != "Currency".$code_iso) { - return ($withcode?$code_iso.' - ':'').$outputlangs->trans("Currency".$code_iso); + return ($withcode ? $code_iso.' - ' : '').$outputlangs->trans("Currency".$code_iso); } // If no translation, we read table to get label by default $sql = "SELECT label FROM ".MAIN_DB_PREFIX."c_currencies"; - $sql.= " WHERE code_iso='".$code_iso."'"; + $sql .= " WHERE code_iso='".$code_iso."'"; - $resql=$db->query($sql); + $resql = $db->query($sql); if ($resql) { $num = $db->num_rows($resql); @@ -595,8 +595,8 @@ function currency_name($code_iso, $withcode = '', $outputlangs = null) if ($num) { $obj = $db->fetch_object($resql); - $label=($obj->label!='-'?$obj->label:''); - if ($withcode) return ($label==$code_iso)?"$code_iso":"$code_iso - $label"; + $label = ($obj->label != '-' ? $obj->label : ''); + if ($withcode) return ($label == $code_iso) ? "$code_iso" : "$code_iso - $label"; else return $label; } else @@ -615,15 +615,15 @@ function currency_name($code_iso, $withcode = '', $outputlangs = null) */ function getFormeJuridiqueLabel($code) { - global $db,$langs; + global $db, $langs; - if (! $code) return ''; + if (!$code) return ''; $sql = "SELECT libelle FROM ".MAIN_DB_PREFIX."c_forme_juridique"; - $sql.= " WHERE code='$code'"; + $sql .= " WHERE code='$code'"; dol_syslog("Company.lib::getFormeJuridiqueLabel", LOG_DEBUG); - $resql=$db->query($sql); + $resql = $db->query($sql); if ($resql) { $num = $db->num_rows($resql); @@ -631,7 +631,7 @@ function getFormeJuridiqueLabel($code) if ($num) { $obj = $db->fetch_object($resql); - $label=($obj->libelle!='-' ? $obj->libelle : ''); + $label = ($obj->libelle != '-' ? $obj->libelle : ''); return $label; } else @@ -654,43 +654,43 @@ function getCountriesInEEC() // List of all country codes that are in europe for european vat rules // List found on http://ec.europa.eu/taxation_customs/common/faq/faq_1179_en.htm#9 - $country_code_in_EEC=array( - 'AT', // Austria - 'BE', // Belgium - 'BG', // Bulgaria - 'CY', // Cyprus - 'CZ', // Czech republic - 'DE', // Germany - 'DK', // Danemark - 'EE', // Estonia - 'ES', // Spain - 'FI', // Finland - 'FR', // France - 'GB', // United Kingdom - 'GR', // Greece - 'HR', // Croatia - 'NL', // Holland - 'HU', // Hungary - 'IE', // Ireland - 'IM', // Isle of Man - Included in UK - 'IT', // Italy - 'LT', // Lithuania - 'LU', // Luxembourg - 'LV', // Latvia - 'MC', // Monaco - Included in France - 'MT', // Malta + $country_code_in_EEC = array( + 'AT', // Austria + 'BE', // Belgium + 'BG', // Bulgaria + 'CY', // Cyprus + 'CZ', // Czech republic + 'DE', // Germany + 'DK', // Danemark + 'EE', // Estonia + 'ES', // Spain + 'FI', // Finland + 'FR', // France + 'GB', // United Kingdom + 'GR', // Greece + 'HR', // Croatia + 'NL', // Holland + 'HU', // Hungary + 'IE', // Ireland + 'IM', // Isle of Man - Included in UK + 'IT', // Italy + 'LT', // Lithuania + 'LU', // Luxembourg + 'LV', // Latvia + 'MC', // Monaco - Included in France + 'MT', // Malta //'NO', // Norway - 'PL', // Poland - 'PT', // Portugal - 'RO', // Romania - 'SE', // Sweden - 'SK', // Slovakia - 'SI', // Slovenia - 'UK', // United Kingdom + 'PL', // Poland + 'PT', // Portugal + 'RO', // Romania + 'SE', // Sweden + 'SK', // Slovakia + 'SI', // Slovenia + 'UK', // United Kingdom //'CH', // Switzerland - No. Swizerland in not in EEC ); - if (! empty($conf->global->MAIN_COUNTRIES_IN_EEC)) + if (!empty($conf->global->MAIN_COUNTRIES_IN_EEC)) { // For example MAIN_COUNTRIES_IN_EEC = 'AT,BE,BG,CY,CZ,DE,DK,EE,ES,FI,FR,GB,GR,HR,NL,HU,IE,IM,IT,LT,LU,LV,MC,MT,PL,PT,RO,SE,SK,SI,UK' $country_code_in_EEC = explode(',', $conf->global->MAIN_COUNTRIES_IN_EEC); @@ -732,16 +732,16 @@ function show_projects($conf, $langs, $db, $object, $backtopage = '', $nocreatel { global $user; - $i = -1 ; + $i = -1; - if (! empty($conf->projet->enabled) && $user->rights->projet->lire) + if (!empty($conf->projet->enabled) && $user->rights->projet->lire) { $langs->load("projects"); - $newcardbutton=''; - if (! empty($conf->projet->enabled) && $user->rights->projet->creer && empty($nocreatelink)) + $newcardbutton = ''; + if (!empty($conf->projet->enabled) && $user->rights->projet->creer && empty($nocreatelink)) { - $newcardbutton.= dolGetButtonTitle($langs->trans('AddProject'), '', 'fa fa-plus-circle', DOL_URL_ROOT.'/projet/card.php?socid='.$object->id.'&action=create&backtopage='.urlencode($backtopage)); + $newcardbutton .= dolGetButtonTitle($langs->trans('AddProject'), '', 'fa fa-plus-circle', DOL_URL_ROOT.'/projet/card.php?socid='.$object->id.'&action=create&backtopage='.urlencode($backtopage)); } print "\n"; @@ -757,7 +757,7 @@ function show_projects($conf, $langs, $db, $object, $backtopage = '', $nocreatel $sql .= " AND p.entity IN (".getEntity('project').")"; $sql .= " ORDER BY p.dateo DESC"; - $result=$db->query($sql); + $result = $db->query($sql); if ($result) { $num = $db->num_rows($result); @@ -779,7 +779,7 @@ function show_projects($conf, $langs, $db, $object, $backtopage = '', $nocreatel $projecttmp = new Project($db); - $i=0; + $i = 0; while ($i < $num) { @@ -794,7 +794,7 @@ function show_projects($conf, $langs, $db, $object, $backtopage = '', $nocreatel print ''; // Ref - print ''; + print ''; // Label print ''; // Date start @@ -856,7 +856,7 @@ function show_projects($conf, $langs, $db, $object, $backtopage = '', $nocreatel */ function show_contacts($conf, $langs, $db, $object, $backtopage = '') { - global $user,$conf,$extrafields,$hookmanager; + global $user, $conf, $extrafields, $hookmanager; global $contextpage; require_once DOL_DOCUMENT_ROOT.'/core/class/html.formcompany.class.php'; @@ -869,12 +869,12 @@ function show_contacts($conf, $langs, $db, $object, $backtopage = '') $page = GETPOST('page', 'int'); $search_status = GETPOST("search_status", 'int'); - if ($search_status=='') $search_status=1; // always display active customer first + if ($search_status == '') $search_status = 1; // always display active customer first $search_name = GETPOST("search_name", 'alpha'); $search_address = GETPOST("search_address", 'alpha'); $search_poste = GETPOST("search_poste", 'alpha'); - $search_roles = GETPOST("search_roles", 'array'); + $search_roles = GETPOST("search_roles", 'array'); $socialnetworks = getArrayOfSocialNetworks(); @@ -902,10 +902,10 @@ function show_contacts($conf, $langs, $db, $object, $backtopage = '') } } - if (! $sortorder) $sortorder="ASC"; - if (! $sortfield) $sortfield="t.lastname"; + if (!$sortorder) $sortorder = "ASC"; + if (!$sortfield) $sortfield = "t.lastname"; - if (! empty($conf->clicktodial->enabled)) + if (!empty($conf->clicktodial->enabled)) { $user->fetch_clicktodial(); // lecture des infos de clicktodial du user } @@ -915,17 +915,17 @@ function show_contacts($conf, $langs, $db, $object, $backtopage = '') $extrafields->fetch_name_optionals_label($contactstatic->table_element); - $contactstatic->fields=array( - 'name' =>array('type'=>'varchar(128)', 'label'=>'Name', 'enabled'=>1, 'visible'=>1, 'notnull'=>1, 'showoncombobox'=>1, 'index'=>1, 'position'=>10, 'searchall'=>1), - 'poste' =>array('type'=>'varchar(128)', 'label'=>'PostOrFunction', 'enabled'=>1, 'visible'=>1, 'notnull'=>1, 'showoncombobox'=>1, 'index'=>1, 'position'=>20), - 'address' =>array('type'=>'varchar(128)', 'label'=>'Address', 'enabled'=>1, 'visible'=>1, 'notnull'=>1, 'showoncombobox'=>1, 'index'=>1, 'position'=>30), - 'role' =>array('type'=>'checkbox', 'label'=>'Role', 'enabled'=>1, 'visible'=>1, 'notnull'=>1, 'showoncombobox'=>1, 'index'=>1, 'position'=>40), - 'statut' =>array('type'=>'integer', 'label'=>'Status', 'enabled'=>1, 'visible'=>1, 'notnull'=>1, 'default'=>0, 'index'=>1, 'position'=>50, 'arrayofkeyval'=>array(0=>$contactstatic->LibStatut(0, 1), 1=>$contactstatic->LibStatut(1, 1))), + $contactstatic->fields = array( + 'name' =>array('type'=>'varchar(128)', 'label'=>'Name', 'enabled'=>1, 'visible'=>1, 'notnull'=>1, 'showoncombobox'=>1, 'index'=>1, 'position'=>10, 'searchall'=>1), + 'poste' =>array('type'=>'varchar(128)', 'label'=>'PostOrFunction', 'enabled'=>1, 'visible'=>1, 'notnull'=>1, 'showoncombobox'=>1, 'index'=>1, 'position'=>20), + 'address' =>array('type'=>'varchar(128)', 'label'=>'Address', 'enabled'=>1, 'visible'=>1, 'notnull'=>1, 'showoncombobox'=>1, 'index'=>1, 'position'=>30), + 'role' =>array('type'=>'checkbox', 'label'=>'Role', 'enabled'=>1, 'visible'=>1, 'notnull'=>1, 'showoncombobox'=>1, 'index'=>1, 'position'=>40), + 'statut' =>array('type'=>'integer', 'label'=>'Status', 'enabled'=>1, 'visible'=>1, 'notnull'=>1, 'default'=>0, 'index'=>1, 'position'=>50, 'arrayofkeyval'=>array(0=>$contactstatic->LibStatut(0, 1), 1=>$contactstatic->LibStatut(1, 1))), ); // Definition of fields for list - $arrayfields=array( - 't.rowid'=>array('label'=>"TechnicalID", 'checked'=>($conf->global->MAIN_SHOW_TECHNICAL_ID?1:0), 'enabled'=>($conf->global->MAIN_SHOW_TECHNICAL_ID?1:0), 'position'=>1), + $arrayfields = array( + 't.rowid'=>array('label'=>"TechnicalID", 'checked'=>($conf->global->MAIN_SHOW_TECHNICAL_ID ? 1 : 0), 'enabled'=>($conf->global->MAIN_SHOW_TECHNICAL_ID ? 1 : 0), 'position'=>1), 't.name'=>array('label'=>"Name", 'checked'=>1, 'position'=>10), 't.poste'=>array('label'=>"PostOrFunction", 'checked'=>1, 'position'=>20), 't.address'=>array('label'=>(empty($conf->dol_optimize_smallscreen) ? $langs->trans("Address").' / '.$langs->trans("Phone").' / '.$langs->trans("Email") : $langs->trans("Address")), 'checked'=>1, 'position'=>30), @@ -935,59 +935,59 @@ function show_contacts($conf, $langs, $db, $object, $backtopage = '') // Extra fields if (is_array($extrafields->attributes[$contactstatic->table_element]['label']) && count($extrafields->attributes[$contactstatic->table_element]['label'])) { - foreach($extrafields->attributes[$contactstatic->table_element]['label'] as $key => $val) + foreach ($extrafields->attributes[$contactstatic->table_element]['label'] as $key => $val) { - if (! empty($extrafields->attributes[$contactstatic->table_element]['list'][$key])) { - $arrayfields["ef.".$key]=array( + if (!empty($extrafields->attributes[$contactstatic->table_element]['list'][$key])) { + $arrayfields["ef.".$key] = array( 'label'=>$extrafields->attributes[$contactstatic->table_element]['label'][$key], - 'checked'=>(($extrafields->attributes[$contactstatic->table_element]['list'][$key]<0)?0:1), - 'position'=>1000+$extrafields->attributes[$contactstatic->table_element]['pos'][$key], - 'enabled'=>(abs($extrafields->attributes[$contactstatic->table_element]['list'][$key])!=3 && $extrafields->attributes[$contactstatic->table_element]['perms'][$key])); + 'checked'=>(($extrafields->attributes[$contactstatic->table_element]['list'][$key] < 0) ? 0 : 1), + 'position'=>1000 + $extrafields->attributes[$contactstatic->table_element]['pos'][$key], + 'enabled'=>(abs($extrafields->attributes[$contactstatic->table_element]['list'][$key]) != 3 && $extrafields->attributes[$contactstatic->table_element]['perms'][$key])); } } } // Initialize array of search criterias - $search=array(); - foreach($arrayfields as $key => $val) + $search = array(); + foreach ($arrayfields as $key => $val) { $queryName = 'search_'.substr($key, 2); - if (GETPOST($queryName, 'alpha')){ - $search[substr($key, 2)]=GETPOST($queryName, 'alpha'); + if (GETPOST($queryName, 'alpha')) { + $search[substr($key, 2)] = GETPOST($queryName, 'alpha'); } } - $search_array_options=$extrafields->getOptionalsFromPost($contactstatic->table_element, '', 'search_'); + $search_array_options = $extrafields->getOptionalsFromPost($contactstatic->table_element, '', 'search_'); // 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_status = ''; + $search_status = ''; $search_name = ''; $search_roles = array(); $search_address = ''; $search_poste = ''; $search = array(); - $search_array_options=array(); + $search_array_options = array(); - foreach($contactstatic->fields as $key => $val) + foreach ($contactstatic->fields as $key => $val) { - $search[$key]=''; + $search[$key] = ''; } } $contactstatic->fields = dol_sort_array($contactstatic->fields, 'position'); $arrayfields = dol_sort_array($arrayfields, 'position'); - $newcardbutton=''; + $newcardbutton = ''; if ($user->rights->societe->contact->creer) { - $addcontact = (! empty($conf->global->SOCIETE_ADDRESSES_MANAGEMENT) ? $langs->trans("AddContact") : $langs->trans("AddContactAddress")); - $newcardbutton.= dolGetButtonTitle($addcontact, '', 'fa fa-plus-circle', DOL_URL_ROOT.'/contact/card.php?socid='.$object->id.'&action=create&backtopage='.urlencode($backtopage)); + $addcontact = (!empty($conf->global->SOCIETE_ADDRESSES_MANAGEMENT) ? $langs->trans("AddContact") : $langs->trans("AddContactAddress")); + $newcardbutton .= dolGetButtonTitle($addcontact, '', 'fa fa-plus-circle', DOL_URL_ROOT.'/contact/card.php?socid='.$object->id.'&action=create&backtopage='.urlencode($backtopage)); } print "\n"; - $title = (! empty($conf->global->SOCIETE_ADDRESSES_MANAGEMENT) ? $langs->trans("ContactsForCompany") : $langs->trans("ContactsAddressesForCompany")); + $title = (!empty($conf->global->SOCIETE_ADDRESSES_MANAGEMENT) ? $langs->trans("ContactsForCompany") : $langs->trans("ContactsAddressesForCompany")); print load_fiche_titre($title, $newcardbutton, ''); print ''; @@ -998,23 +998,23 @@ function show_contacts($conf, $langs, $db, $object, $backtopage = '') print ''; print ''; - $varpage=empty($contextpage)?$_SERVER["PHP_SELF"]:$contextpage; - $selectedfields=$form->multiSelectArrayWithCheckbox('selectedfields', $arrayfields, $varpage); // This also change content of $arrayfields + $varpage = empty($contextpage) ? $_SERVER["PHP_SELF"] : $contextpage; + $selectedfields = $form->multiSelectArrayWithCheckbox('selectedfields', $arrayfields, $varpage); // This also change content of $arrayfields //if ($massactionbutton) $selectedfields.=$form->showCheckAddButtons('checkforselect', 1); - print '
    '; // You can use div-table-responsive-no-min if you dont need reserved height for your table + print '
    '; // You can use div-table-responsive-no-min if you dont need reserved height for your table print "\n".'
    '.$langs->trans("LastDoneTasks", $max).''.$langs->trans("FullList").'
    '.img_object($langs->trans("ShowProject"), ($obj->public?'projectpub':'project'))." ".$obj->ref.''.img_object($langs->trans("ShowProject"), ($obj->public ? 'projectpub' : 'project'))." ".$obj->ref.''.$obj->title.'
    '."\n"; - $param="socid=".urlencode($object->id); - if ($search_status != '') $param.='&search_status='.urlencode($search_status); - if (count($search_roles)>0) $param.=implode('&search_roles[]=', $search_roles); - if ($search_name != '') $param.='&search_name='.urlencode($search_name); - if ($search_poste != '') $param.='&search_poste='.urlencode($search_poste); - if ($search_address != '') $param.='&search_address='.urlencode($search_address); - if ($optioncss != '') $param.='&optioncss='.urlencode($optioncss); + $param = "socid=".urlencode($object->id); + if ($search_status != '') $param .= '&search_status='.urlencode($search_status); + if (count($search_roles) > 0) $param .= implode('&search_roles[]=', $search_roles); + if ($search_name != '') $param .= '&search_name='.urlencode($search_name); + if ($search_poste != '') $param .= '&search_poste='.urlencode($search_poste); + if ($search_address != '') $param .= '&search_address='.urlencode($search_address); + if ($optioncss != '') $param .= '&optioncss='.urlencode($optioncss); // Add $param from extra fields - $extrafieldsobjectkey=$contactstatic->table_element; + $extrafieldsobjectkey = $contactstatic->table_element; include DOL_DOCUMENT_ROOT.'/core/tpl/extrafields_list_search_param.tpl.php'; $sql = "SELECT t.rowid, t.lastname, t.firstname, t.fk_pays as country_id, t.civility, t.poste, t.phone as phone_pro, t.phone_mobile, t.phone_perso, t.fax, t.email, t.socialnetworks, t.statut, t.photo,"; @@ -1022,41 +1022,41 @@ function show_contacts($conf, $langs, $db, $object, $backtopage = '') $sql .= " FROM ".MAIN_DB_PREFIX."socpeople as t"; $sql .= " LEFT JOIN ".MAIN_DB_PREFIX."socpeople_extrafields as ef on (t.rowid = ef.fk_object)"; $sql .= " WHERE t.fk_soc = ".$object->id; - if ($search_status!='' && $search_status != '-1') $sql .= " AND t.statut = ".$db->escape($search_status); + if ($search_status != '' && $search_status != '-1') $sql .= " AND t.statut = ".$db->escape($search_status); if ($search_name) $sql .= natural_search(array('t.lastname', 't.firstname'), $search_name); if ($search_poste) $sql .= natural_search('t.poste', $search_poste); if ($search_address) { $sql .= natural_search($searchAddressPhoneDBFields, $search_address); } - if (count($search_roles)>0) { + if (count($search_roles) > 0) { $sql .= " AND t.rowid IN (SELECT sc.fk_socpeople FROM ".MAIN_DB_PREFIX."societe_contacts as sc WHERE sc.fk_c_type_contact IN (".implode(',', $search_roles)."))"; } // Add where from extra fields - $extrafieldsobjectkey=$contactstatic->table_element; + $extrafieldsobjectkey = $contactstatic->table_element; include DOL_DOCUMENT_ROOT.'/core/tpl/extrafields_list_search_sql.tpl.php'; - if ($sortfield == "t.name") $sql.=" ORDER BY t.lastname $sortorder, t.firstname $sortorder"; - else $sql.= " ORDER BY $sortfield $sortorder"; + if ($sortfield == "t.name") $sql .= " ORDER BY t.lastname $sortorder, t.firstname $sortorder"; + else $sql .= " ORDER BY $sortfield $sortorder"; dol_syslog('core/lib/company.lib.php :: show_contacts', LOG_DEBUG); $result = $db->query($sql); - if (! $result) dol_print_error($db); + if (!$result) dol_print_error($db); $num = $db->num_rows($result); // Fields title search // -------------------------------------------------------------------- print ''; - foreach($contactstatic->fields as $key => $val) + foreach ($contactstatic->fields as $key => $val) { - $align=''; - if (in_array($val['type'], array('date','datetime','timestamp'))) $align.=($align?' ':'').'center'; - if (in_array($val['type'], array('timestamp'))) $align.=($align?' ':'').'nowrap'; - if ($key == 'status' || $key == 'statut') $align.=($align?' ':'').'center'; - if (! empty($arrayfields['t.'.$key]['checked']) || ! empty($arrayfields['sc.'.$key]['checked'])) + $align = ''; + if (in_array($val['type'], array('date', 'datetime', 'timestamp'))) $align .= ($align ? ' ' : '').'center'; + if (in_array($val['type'], array('timestamp'))) $align .= ($align ? ' ' : '').'nowrap'; + if ($key == 'status' || $key == 'statut') $align .= ($align ? ' ' : '').'center'; + if (!empty($arrayfields['t.'.$key]['checked']) || !empty($arrayfields['sc.'.$key]['checked'])) { - print ''; - foreach($contactstatic->fields as $key => $val) + foreach ($contactstatic->fields as $key => $val) { - $align=''; - if (in_array($val['type'], array('date','datetime','timestamp'))) $align.=($align?' ':'').'center'; - if (in_array($val['type'], array('timestamp'))) $align.=($align?' ':'').'nowrap'; - if ($key == 'status' || $key == 'statut') $align.=($align?' ':'').'center'; - if (! empty($arrayfields['t.'.$key]['checked'])) print getTitleFieldOfList($val['label'], 0, $_SERVER['PHP_SELF'], 't.'.$key, '', $param, ($align?'class="'.$align.'"':''), $sortfield, $sortorder, $align.' ')."\n"; - if ($key == 'role') $align.=($align?' ':'').'left'; - if (! empty($arrayfields['sc.'.$key]['checked'])) { - print getTitleFieldOfList($arrayfields['sc.'.$key]['label'], 0, $_SERVER['PHP_SELF'], 'sc.'.$key, '', $param, ($align?'class="'.$align.'"':''), $sortfield, $sortorder, $align.' ')."\n"; + $align = ''; + if (in_array($val['type'], array('date', 'datetime', 'timestamp'))) $align .= ($align ? ' ' : '').'center'; + if (in_array($val['type'], array('timestamp'))) $align .= ($align ? ' ' : '').'nowrap'; + if ($key == 'status' || $key == 'statut') $align .= ($align ? ' ' : '').'center'; + if (!empty($arrayfields['t.'.$key]['checked'])) print getTitleFieldOfList($val['label'], 0, $_SERVER['PHP_SELF'], 't.'.$key, '', $param, ($align ? 'class="'.$align.'"' : ''), $sortfield, $sortorder, $align.' ')."\n"; + if ($key == 'role') $align .= ($align ? ' ' : '').'left'; + if (!empty($arrayfields['sc.'.$key]['checked'])) { + print getTitleFieldOfList($arrayfields['sc.'.$key]['label'], 0, $_SERVER['PHP_SELF'], 'sc.'.$key, '', $param, ($align ? 'class="'.$align.'"' : ''), $sortfield, $sortorder, $align.' ')."\n"; } } // Extra fields - $extrafieldsobjectkey=$contactstatic->table_element; + $extrafieldsobjectkey = $contactstatic->table_element; 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, $object); // Note that $action and $object may have been modified by hook + $parameters = array('arrayfields'=>$arrayfields, 'param'=>$param, 'sortfield'=>$sortfield, 'sortorder'=>$sortorder); + $reshook = $hookmanager->executeHooks('printFieldListTitle', $parameters, $object); // Note that $action and $object may have been modified by hook print $hookmanager->resPrint; print getTitleFieldOfList($selectedfields, 0, $_SERVER["PHP_SELF"], '', '', '', 'align="center"', $sortfield, $sortorder, 'maxwidthsearch ')."\n"; print ''."\n"; @@ -1140,14 +1140,14 @@ function show_contacts($conf, $langs, $db, $object, $backtopage = '') $contactstatic->setGenderFromCivility(); $contactstatic->fetch_optionals(); - $resultRole=$contactstatic->fetchRoles(); - if ($resultRole<0) { + $resultRole = $contactstatic->fetchRoles(); + if ($resultRole < 0) { setEventMessages(null, $contactstatic->errors, 'errors'); } if (is_array($contactstatic->array_options)) { - foreach($contactstatic->array_options as $key => $val) + foreach ($contactstatic->array_options as $key => $val) { $obj->$key = $val; } @@ -1156,7 +1156,7 @@ function show_contacts($conf, $langs, $db, $object, $backtopage = '') print ''; // ID - if (! empty($arrayfields['t.rowid']['checked'])) + if (!empty($arrayfields['t.rowid']['checked'])) { print ''; } // Extra fields - $extrafieldsobjectkey=$contactstatic->table_element; + $extrafieldsobjectkey = $contactstatic->table_element; include DOL_DOCUMENT_ROOT.'/core/tpl/extrafields_list_print_fields.tpl.php'; // Actions print ''; } print "\n
    '; - if (in_array($key, array('statut'))){ - print $form->selectarray('search_status', array('-1'=>'','0'=>$contactstatic->LibStatut(0, 1),'1'=>$contactstatic->LibStatut(1, 1)), $search_status); + print ''; + if (in_array($key, array('statut'))) { + print $form->selectarray('search_status', array('-1'=>'', '0'=>$contactstatic->LibStatut(0, 1), '1'=>$contactstatic->LibStatut(1, 1)), $search_status); } elseif (in_array($key, array('role'))) { print $formcompany->showRoles("search_roles", $contactstatic, 'edit', $search_roles); } else { @@ -1066,12 +1066,12 @@ function show_contacts($conf, $langs, $db, $object, $backtopage = '') } } // Extra fields - $extrafieldsobjectkey=$contactstatic->table_element; + $extrafieldsobjectkey = $contactstatic->table_element; include DOL_DOCUMENT_ROOT.'/core/tpl/extrafields_list_search_input.tpl.php'; // Fields from hook - $parameters=array('arrayfields'=>$arrayfields); - $reshook=$hookmanager->executeHooks('printFieldListOption', $parameters, $contactstatic); // Note that $action and $object may have been modified by hook + $parameters = array('arrayfields'=>$arrayfields); + $reshook = $hookmanager->executeHooks('printFieldListOption', $parameters, $contactstatic); // Note that $action and $object may have been modified by hook print $hookmanager->resPrint; // Action column print ''; @@ -1083,24 +1083,24 @@ function show_contacts($conf, $langs, $db, $object, $backtopage = '') // Fields title label // -------------------------------------------------------------------- print '
    '; print $contactstatic->id; @@ -1164,7 +1164,7 @@ function show_contacts($conf, $langs, $db, $object, $backtopage = '') } // Photo - Name - if (! empty($arrayfields['t.name']['checked'])) + if (!empty($arrayfields['t.name']['checked'])) { print ''; print $form->showphoto('contact', $contactstatic, 0, 0, 0, 'photorefnoborder valignmiddle marginrightonly', 'small', 1, 0, 1); @@ -1173,7 +1173,7 @@ function show_contacts($conf, $langs, $db, $object, $backtopage = '') } // Job position - if (! empty($arrayfields['t.poste']['checked'])) + if (!empty($arrayfields['t.poste']['checked'])) { print ''; if ($obj->poste) print $obj->poste; @@ -1181,7 +1181,7 @@ function show_contacts($conf, $langs, $db, $object, $backtopage = '') } // Address - Phone - Email - if (! empty($arrayfields['t.address']['checked'])) + if (!empty($arrayfields['t.address']['checked'])) { print ''; print $contactstatic->getBannerAddress('contact', $object); @@ -1189,7 +1189,7 @@ function show_contacts($conf, $langs, $db, $object, $backtopage = '') } // Role - if (! empty($arrayfields['sc.role']['checked'])) + if (!empty($arrayfields['sc.role']['checked'])) { print ''; print $formcompany->showRoles("roles", $contactstatic, 'view'); @@ -1197,20 +1197,20 @@ function show_contacts($conf, $langs, $db, $object, $backtopage = '') } // Status - if (! empty($arrayfields['t.statut']['checked'])) + if (!empty($arrayfields['t.statut']['checked'])) { print ''.$contactstatic->getLibStatut(5).''; // Add to agenda - if (! empty($conf->agenda->enabled) && $user->rights->agenda->myactions->create) + if (!empty($conf->agenda->enabled) && $user->rights->agenda->myactions->create) { print ''; print img_object($langs->trans("Event"), "action"); @@ -1233,8 +1233,8 @@ function show_contacts($conf, $langs, $db, $object, $backtopage = '') } else { - $colspan=1; - foreach($arrayfields as $key => $val) { if (! empty($val['checked'])) $colspan++; } + $colspan = 1; + foreach ($arrayfields as $key => $val) { if (!empty($val['checked'])) $colspan++; } print '
    '.$langs->trans("None").'
    \n"; @@ -1260,7 +1260,7 @@ function show_contacts($conf, $langs, $db, $object, $backtopage = '') */ function show_actions_todo($conf, $langs, $db, $filterobj, $objcon = '', $noprint = 0, $actioncode = '') { - global $user,$conf; + global $user, $conf; $out = show_actions_done($conf, $langs, $db, $filterobj, $objcon, 1, $actioncode, 'todo'); @@ -1295,12 +1295,12 @@ function show_actions_done($conf, $langs, $db, $filterobj, $objcon = '', $noprin 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(); - $numaction = 0 ; - $now=dol_now('tzuser'); + $out = ''; + $histo = array(); + $numaction = 0; + $now = dol_now('tzuser'); // Open DSI -- Fix order by -- Begin $sortfield_list = explode(',', $sortfield); @@ -1311,7 +1311,7 @@ function show_actions_done($conf, $langs, $db, $filterobj, $objcon = '', $noprin } $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) { @@ -1321,141 +1321,141 @@ function show_actions_done($conf, $langs, $db, $filterobj, $objcon = '', $noprin { $sql = "SELECT a.id, a.label as label,"; } - $sql.= " a.datep as dp,"; - $sql.= " a.datep2 as dp2,"; - $sql.= " a.percent as percent, 'action' as type,"; - $sql.= " a.fk_element, a.elementtype,"; - $sql.= " a.fk_contact,"; - $sql.= " c.code as acode, c.libelle as alabel, c.picto as apicto,"; - $sql.= " u.rowid as user_id, u.login as user_login, u.photo as user_photo, u.firstname as user_firstname, u.lastname as user_lastname"; - if (is_object($filterobj) && get_class($filterobj) == 'Societe') $sql.= ", sp.lastname, sp.firstname"; - elseif (is_object($filterobj) && get_class($filterobj) == 'Adherent') $sql.= ", m.lastname, m.firstname"; - elseif (is_object($filterobj) && get_class($filterobj) == 'CommandeFournisseur') $sql.= ", o.ref"; - elseif (is_object($filterobj) && get_class($filterobj) == 'Product') $sql.= ", o.ref"; - elseif (is_object($filterobj) && get_class($filterobj) == 'Ticket') $sql.= ", o.ref"; - elseif (is_object($filterobj) && get_class($filterobj) == 'BOM') $sql.= ", o.ref"; - elseif (is_object($filterobj) && get_class($filterobj) == 'Contrat') $sql.= ", o.ref"; - $sql.= " FROM ".MAIN_DB_PREFIX."actioncomm as a"; - $sql.= " LEFT JOIN ".MAIN_DB_PREFIX."user as u on u.rowid = a.fk_user_action"; - $sql.= " LEFT JOIN ".MAIN_DB_PREFIX."c_actioncomm as c ON a.fk_action = c.id"; + $sql .= " a.datep as dp,"; + $sql .= " a.datep2 as dp2,"; + $sql .= " a.percent as percent, 'action' as type,"; + $sql .= " a.fk_element, a.elementtype,"; + $sql .= " a.fk_contact,"; + $sql .= " c.code as acode, c.libelle as alabel, c.picto as apicto,"; + $sql .= " u.rowid as user_id, u.login as user_login, u.photo as user_photo, u.firstname as user_firstname, u.lastname as user_lastname"; + if (is_object($filterobj) && get_class($filterobj) == 'Societe') $sql .= ", sp.lastname, sp.firstname"; + elseif (is_object($filterobj) && get_class($filterobj) == 'Adherent') $sql .= ", m.lastname, m.firstname"; + elseif (is_object($filterobj) && get_class($filterobj) == 'CommandeFournisseur') $sql .= ", o.ref"; + elseif (is_object($filterobj) && get_class($filterobj) == 'Product') $sql .= ", o.ref"; + elseif (is_object($filterobj) && get_class($filterobj) == 'Ticket') $sql .= ", o.ref"; + elseif (is_object($filterobj) && get_class($filterobj) == 'BOM') $sql .= ", o.ref"; + elseif (is_object($filterobj) && get_class($filterobj) == 'Contrat') $sql .= ", o.ref"; + $sql .= " FROM ".MAIN_DB_PREFIX."actioncomm as a"; + $sql .= " LEFT JOIN ".MAIN_DB_PREFIX."user as u on u.rowid = a.fk_user_action"; + $sql .= " LEFT JOIN ".MAIN_DB_PREFIX."c_actioncomm as c ON a.fk_action = c.id"; $force_filter_contact = false; if (is_object($objcon) && $objcon->id > 0) { $force_filter_contact = true; - $sql.= " INNER JOIN ".MAIN_DB_PREFIX."actioncomm_resources as r ON a.id = r.fk_actioncomm"; - $sql.= " AND r.element_type = '" . $db->escape($objcon->table_element) . "' AND r.fk_element = " . $objcon->id; + $sql .= " INNER JOIN ".MAIN_DB_PREFIX."actioncomm_resources as r ON a.id = r.fk_actioncomm"; + $sql .= " AND r.element_type = '".$db->escape($objcon->table_element)."' AND r.fk_element = ".$objcon->id; } - if (is_object($filterobj) && get_class($filterobj) == 'Societe') $sql.= " LEFT JOIN ".MAIN_DB_PREFIX."socpeople as sp ON a.fk_contact = sp.rowid"; + if (is_object($filterobj) && get_class($filterobj) == 'Societe') $sql .= " LEFT JOIN ".MAIN_DB_PREFIX."socpeople as sp ON a.fk_contact = sp.rowid"; elseif (is_object($filterobj) && get_class($filterobj) == 'Dolresource') { - $sql.= " INNER JOIN ".MAIN_DB_PREFIX."element_resources as er"; - $sql.= " ON er.resource_type = 'dolresource'"; - $sql.= " AND er.element_id = a.id"; - $sql.= " AND er.resource_id = ".$filterobj->id; + $sql .= " INNER JOIN ".MAIN_DB_PREFIX."element_resources as er"; + $sql .= " ON er.resource_type = 'dolresource'"; + $sql .= " AND er.element_id = a.id"; + $sql .= " AND er.resource_id = ".$filterobj->id; } - elseif (is_object($filterobj) && get_class($filterobj) == 'Adherent') $sql.= ", ".MAIN_DB_PREFIX."adherent as m"; - elseif (is_object($filterobj) && get_class($filterobj) == 'CommandeFournisseur') $sql.= ", ".MAIN_DB_PREFIX."commande_fournisseur as o"; - elseif (is_object($filterobj) && get_class($filterobj) == 'Product') $sql.= ", ".MAIN_DB_PREFIX."product as o"; - elseif (is_object($filterobj) && get_class($filterobj) == 'Ticket') $sql.= ", ".MAIN_DB_PREFIX."ticket as o"; - elseif (is_object($filterobj) && get_class($filterobj) == 'BOM') $sql.= ", ".MAIN_DB_PREFIX."bom_bom as o"; - elseif (is_object($filterobj) && get_class($filterobj) == 'Contrat') $sql.= ", ".MAIN_DB_PREFIX."contrat as o"; + elseif (is_object($filterobj) && get_class($filterobj) == 'Adherent') $sql .= ", ".MAIN_DB_PREFIX."adherent as m"; + elseif (is_object($filterobj) && get_class($filterobj) == 'CommandeFournisseur') $sql .= ", ".MAIN_DB_PREFIX."commande_fournisseur as o"; + elseif (is_object($filterobj) && get_class($filterobj) == 'Product') $sql .= ", ".MAIN_DB_PREFIX."product as o"; + elseif (is_object($filterobj) && get_class($filterobj) == 'Ticket') $sql .= ", ".MAIN_DB_PREFIX."ticket as o"; + elseif (is_object($filterobj) && get_class($filterobj) == 'BOM') $sql .= ", ".MAIN_DB_PREFIX."bom_bom as o"; + elseif (is_object($filterobj) && get_class($filterobj) == 'Contrat') $sql .= ", ".MAIN_DB_PREFIX."contrat as o"; - $sql.= " WHERE a.entity IN (".getEntity('agenda').")"; + $sql .= " WHERE a.entity IN (".getEntity('agenda').")"; if ($force_filter_contact === false) { - if (is_object($filterobj) && in_array(get_class($filterobj), array('Societe', 'Client', 'Fournisseur')) && $filterobj->id) $sql.= " AND a.fk_soc = ".$filterobj->id; - elseif (is_object($filterobj) && get_class($filterobj) == 'Project' && $filterobj->id) $sql.= " AND a.fk_project = ".$filterobj->id; + if (is_object($filterobj) && in_array(get_class($filterobj), array('Societe', 'Client', 'Fournisseur')) && $filterobj->id) $sql .= " AND a.fk_soc = ".$filterobj->id; + elseif (is_object($filterobj) && get_class($filterobj) == 'Project' && $filterobj->id) $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; + $sql .= " AND a.fk_element = m.rowid AND a.elementtype = 'member'"; + 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; + $sql .= " AND a.fk_element = o.rowid AND a.elementtype = 'order_supplier'"; + 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; + $sql .= " AND a.fk_element = o.rowid AND a.elementtype = 'product'"; + 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; + $sql .= " AND a.fk_element = o.rowid AND a.elementtype = 'ticket'"; + 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; + $sql .= " AND a.fk_element = o.rowid AND a.elementtype = 'bom'"; + 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; + $sql .= " AND a.fk_element = o.rowid AND a.elementtype = 'contract'"; + if ($filterobj->id) $sql .= " AND a.fk_element = ".$filterobj->id; } } // Condition on actioncode - if (! empty($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'"; + 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'"; - elseif ($actioncode == 'AC_OTH_AUTO') $sql.= " AND c.type = 'systemauto'"; + if ($actioncode == 'AC_OTH') $sql .= " AND c.type != 'systemauto'"; + elseif ($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 $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) + if (!empty($conf->mailing->enabled) && !empty($objcon->email) && (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"; - $sql2.= ", '' as fk_element, '' as elementtype, '' as contact_id"; - $sql2.= ", 'AC_EMAILING' as acode, '' as alabel, '' as apicto"; - $sql2.= ", u.rowid as user_id, u.login as user_login, u.photo as user_photo, u.firstname as user_firstname, u.lastname as user_lastname"; // User that valid action - if (is_object($filterobj) && get_class($filterobj) == 'Societe') $sql2.= ", '' as lastname, '' as firstname"; - elseif (is_object($filterobj) && get_class($filterobj) == 'Adherent') $sql2.= ", '' as lastname, '' as firstname"; - elseif (is_object($filterobj) && get_class($filterobj) == 'CommandeFournisseur') $sql2.= ", '' as ref"; - elseif (is_object($filterobj) && get_class($filterobj) == 'Product') $sql2.= ", '' as ref"; - elseif (is_object($filterobj) && get_class($filterobj) == 'Ticket') $sql2.= ", '' as ref"; - $sql2.= " FROM ".MAIN_DB_PREFIX."mailing as m, ".MAIN_DB_PREFIX."mailing_cibles as mc, ".MAIN_DB_PREFIX."user as u"; - $sql2.= " WHERE mc.email = '".$db->escape($objcon->email)."'"; // Search is done on email. - $sql2.= " AND mc.statut = 1"; - $sql2.= " AND u.rowid = m.fk_user_valid"; - $sql2.= " AND mc.fk_mailing=m.rowid"; + $sql2 .= ", '' as fk_element, '' as elementtype, '' as contact_id"; + $sql2 .= ", 'AC_EMAILING' as acode, '' as alabel, '' as apicto"; + $sql2 .= ", u.rowid as user_id, u.login as user_login, u.photo as user_photo, u.firstname as user_firstname, u.lastname as user_lastname"; // User that valid action + if (is_object($filterobj) && get_class($filterobj) == 'Societe') $sql2 .= ", '' as lastname, '' as firstname"; + elseif (is_object($filterobj) && get_class($filterobj) == 'Adherent') $sql2 .= ", '' as lastname, '' as firstname"; + elseif (is_object($filterobj) && get_class($filterobj) == 'CommandeFournisseur') $sql2 .= ", '' as ref"; + elseif (is_object($filterobj) && get_class($filterobj) == 'Product') $sql2 .= ", '' as ref"; + elseif (is_object($filterobj) && get_class($filterobj) == 'Ticket') $sql2 .= ", '' as ref"; + $sql2 .= " FROM ".MAIN_DB_PREFIX."mailing as m, ".MAIN_DB_PREFIX."mailing_cibles as mc, ".MAIN_DB_PREFIX."user as u"; + $sql2 .= " WHERE mc.email = '".$db->escape($objcon->email)."'"; // Search is done on email. + $sql2 .= " AND mc.statut = 1"; + $sql2 .= " AND u.rowid = m.fk_user_valid"; + $sql2 .= " AND mc.fk_mailing=m.rowid"; } if (!empty($sql) && !empty($sql2)) { - $sql = $sql . " UNION " . $sql2; + $sql = $sql." UNION ".$sql2; } elseif (empty($sql) && !empty($sql2)) { $sql = $sql2; } //TODO Add limit in nb of results - $sql.= $db->order($sortfield_new, $sortorder); + $sql .= $db->order($sortfield_new, $sortorder); dol_syslog("company.lib::show_actions_done", LOG_DEBUG); - $resql=$db->query($sql); + $resql = $db->query($sql); if ($resql) { - $i = 0 ; + $i = 0; $num = $db->num_rows($resql); while ($i < $num) @@ -1464,19 +1464,19 @@ function show_actions_done($conf, $langs, $db, $filterobj, $objcon = '', $noprin if ($obj->type == 'action') { $contactaction = new ActionComm($db); - $contactaction->id=$obj->id; + $contactaction->id = $obj->id; $result = $contactaction->fetchResources(); - if ($result<0) { + if ($result < 0) { dol_print_error($db); setEventMessage("company.lib::show_actions_done Error fetch ressource", 'errors'); } //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'; + $tododone = ''; + if (($obj->percent >= 0 and $obj->percent < 100) || ($obj->percent == -1 && $obj->datep > $now)) $tododone = 'todo'; - $histo[$numaction]=array( + $histo[$numaction] = array( 'type'=>$obj->type, 'tododone'=>$tododone, 'id'=>$obj->id, @@ -1500,11 +1500,11 @@ function show_actions_done($conf, $langs, $db, $filterobj, $objcon = '', $noprin // Type of event 'acode'=>$obj->acode, 'alabel'=>$obj->alabel, - 'libelle'=>$obj->alabel, // deprecated + 'libelle'=>$obj->alabel, // deprecated 'apicto'=>$obj->apicto ); } else { - $histo[$numaction]=array( + $histo[$numaction] = array( 'type'=>$obj->type, 'tododone'=>'done', 'id'=>$obj->id, @@ -1531,203 +1531,203 @@ function show_actions_done($conf, $langs, $db, $filterobj, $objcon = '', $noprin dol_print_error($db); } - if (! empty($conf->agenda->enabled) || (! empty($conf->mailing->enabled) && ! empty($objcon->email))) + if (!empty($conf->agenda->enabled) || (!empty($conf->mailing->enabled) && !empty($objcon->email))) { - $delay_warning=$conf->global->MAIN_DELAY_ACTIONS_TODO*24*60*60; + $delay_warning = $conf->global->MAIN_DELAY_ACTIONS_TODO * 24 * 60 * 60; require_once DOL_DOCUMENT_ROOT.'/comm/action/class/actioncomm.class.php'; include_once DOL_DOCUMENT_ROOT.'/core/lib/functions2.lib.php'; require_once DOL_DOCUMENT_ROOT.'/core/class/html.formactions.class.php'; require_once DOL_DOCUMENT_ROOT.'/contact/class/contact.class.php'; - $formactions=new FormActions($db); + $formactions = new FormActions($db); - $actionstatic=new ActionComm($db); - $userstatic=new User($db); + $actionstatic = new ActionComm($db); + $userstatic = new User($db); $contactstatic = new Contact($db); - $out.=''; + $out .= ''; if ($objcon && get_class($objcon) == 'Contact' && (is_null($filterobj) || get_class($filterobj) == 'Societe')) { - $out.=''; + $out .= ''; } else { - $out.=''; + $out .= ''; } - if ($filterobj && get_class($filterobj) == 'Societe') $out.=''; + if ($filterobj && get_class($filterobj) == 'Societe') $out .= ''; - $out.="\n"; + $out .= "\n"; - $out.='
    '; - $out.=''; + $out .= '
    '; + $out .= '
    '; - $out.=''; + $out .= ''; if ($donetodo) { - $out.=''; + $out .= ''; } - $out.=''; - $out.=''; - $out.=''; - $out.=''; - $out.=''; - $out.=''; - $out.=''; - $out.=''; + $out .= ''; + $out .= ''; + $out .= ''; + $out .= ''; + $out .= ''; + $out .= ''; + $out .= ''; + $out .= ''; // Action column - $out.=''; - $out.=''; + $out .= ''; + $out .= ''; - $out.=''; + $out .= ''; if ($donetodo) { - $tmp=''; - if (get_class($filterobj) == 'Societe') $tmp.=''; - $tmp.=($donetodo != 'done' ? $langs->trans("ActionsToDoShort") : ''); - $tmp.=($donetodo != 'done' && $donetodo != 'todo' ? ' / ' : ''); - $tmp.=($donetodo != 'todo' ? $langs->trans("ActionsDoneShort") : ''); + $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.=''; - $out.=getTitleFieldOfList($tmp); + if (get_class($filterobj) == 'Societe') $tmp .= ''; + $out .= getTitleFieldOfList($tmp); } - $out.=getTitleFieldOfList($langs->trans("Ref"), 0, $_SERVER["PHP_SELF"], 'a.id', '', $param, '', $sortfield, $sortorder); - $out.=getTitleFieldOfList($langs->trans("Owner")); - $out.=getTitleFieldOfList($langs->trans("Type")); - $out.=getTitleFieldOfList($langs->trans("Label"), 0, $_SERVER["PHP_SELF"], '', '', $param, '', $sortfield, $sortorder); - $out.=getTitleFieldOfList($langs->trans("Date"), 0, $_SERVER["PHP_SELF"], 'a.datep,a.id', '', $param, 'align="center"', $sortfield, $sortorder); - $out.=getTitleFieldOfList($langs->trans("RelatedObjects"), 0, $_SERVER["PHP_SELF"], '', '', $param, '', $sortfield, $sortorder); - $out.=getTitleFieldOfList($langs->trans("ActionOnContact"), 0, $_SERVER["PHP_SELF"], '', '', $param, '', $sortfield, $sortorder); - $out.=getTitleFieldOfList($langs->trans("Status"), 0, $_SERVER["PHP_SELF"], 'a.percent', '', $param, 'align="center"', $sortfield, $sortorder); - $out.=getTitleFieldOfList('', 0, $_SERVER["PHP_SELF"], '', '', $param, '', $sortfield, $sortorder, 'maxwidthsearch '); - $out.=''; + $out .= getTitleFieldOfList($langs->trans("Ref"), 0, $_SERVER["PHP_SELF"], 'a.id', '', $param, '', $sortfield, $sortorder); + $out .= getTitleFieldOfList($langs->trans("Owner")); + $out .= getTitleFieldOfList($langs->trans("Type")); + $out .= getTitleFieldOfList($langs->trans("Label"), 0, $_SERVER["PHP_SELF"], '', '', $param, '', $sortfield, $sortorder); + $out .= getTitleFieldOfList($langs->trans("Date"), 0, $_SERVER["PHP_SELF"], 'a.datep,a.id', '', $param, 'align="center"', $sortfield, $sortorder); + $out .= getTitleFieldOfList($langs->trans("RelatedObjects"), 0, $_SERVER["PHP_SELF"], '', '', $param, '', $sortfield, $sortorder); + $out .= getTitleFieldOfList($langs->trans("ActionOnContact"), 0, $_SERVER["PHP_SELF"], '', '', $param, '', $sortfield, $sortorder); + $out .= getTitleFieldOfList($langs->trans("Status"), 0, $_SERVER["PHP_SELF"], 'a.percent', '', $param, 'align="center"', $sortfield, $sortorder); + $out .= getTitleFieldOfList('', 0, $_SERVER["PHP_SELF"], '', '', $param, '', $sortfield, $sortorder, 'maxwidthsearch '); + $out .= ''; require_once DOL_DOCUMENT_ROOT.'/comm/action/class/cactioncomm.class.php'; - $caction=new CActionComm($db); - $arraylist=$caction->liste_array(1, 'code', '', (empty($conf->global->AGENDA_USE_EVENT_TYPE)?1:0), '', 1); + $caction = new CActionComm($db); + $arraylist = $caction->liste_array(1, 'code', '', (empty($conf->global->AGENDA_USE_EVENT_TYPE) ? 1 : 0), '', 1); 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->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']; - $actionstatic->type_code=$histo[$key]['acode']; + $actionstatic->type_picto = $histo[$key]['apicto']; + $actionstatic->type_code = $histo[$key]['acode']; - $out.=''; + $out .= ''; // Done or todo if ($donetodo) { - $out.=''; + $out .= ''; } // Ref - $out.=''; + $out .= ''; // Author of event - $out.=''; + $out .= ''; // Type - $out.=''; + $labeltype = $actionstatic->type_code; + if (empty($conf->global->AGENDA_USE_EVENT_TYPE) && empty($arraylist[$labeltype])) $labeltype = 'AC_OTH'; + if (!empty($arraylist[$labeltype])) $labeltype = $arraylist[$labeltype]; + $out .= dol_trunc($labeltype, 28); + $out .= ''; // Title - $out.=''; + $out .= ''; // Date - $out.='\n"; + $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")).' '; + $out .= "\n"; // Title of event //$out.=''; // Objet lie - $out.=''; + else $out .= ' '; + $out .= ''; // Contact pour cette action if (empty($objcon->id) && isset($histo[$key]['contact_id']) && $histo[$key]['contact_id'] > 0) { - $contactstatic->lastname=$histo[$key]['lastname']; - $contactstatic->firstname=$histo[$key]['firstname']; - $contactstatic->id=$histo[$key]['contact_id']; - $out.=''; + $contactstatic->lastname = $histo[$key]['lastname']; + $contactstatic->firstname = $histo[$key]['firstname']; + $contactstatic->id = $histo[$key]['contact_id']; + $out .= ''; } elseif (isset($histo[$key]['socpeopleassigned']) && is_array($histo[$key]['socpeopleassigned']) && count($histo[$key]['socpeopleassigned']) > 0) { $out .= ''; } else { - $out.=''; + $out .= ''; } // Status - $out.=''; + $out .= ''; // Actions - $out.=''; + $out .= ''; - $out.="\n"; + $out .= "\n"; $i++; } - $out.="
    '; - $out.=$formactions->select_type_actions($actioncode, "actioncode", '', empty($conf->global->AGENDA_USE_EVENT_TYPE)?1:-1, 0, 0, 1); - $out.=''; + $out .= $formactions->select_type_actions($actioncode, "actioncode", '', empty($conf->global->AGENDA_USE_EVENT_TYPE) ? 1 : -1, 0, 0, 1); + $out .= ''; - $searchpicto=$form->showFilterAndCheckAddButtons($massactionbutton?1:0, 'checkforselect', 1); - $out.=$searchpicto; - $out.='
    '; + $searchpicto = $form->showFilterAndCheckAddButtons($massactionbutton ? 1 : 0, 'checkforselect', 1); + $out .= $searchpicto; + $out .= '
    '; - $out.=''; + $out .= ''; - if (isset($histo[$key]['type']) && $histo[$key]['type']=='mailing') { - $out.=''.img_object($langs->trans("ShowEMailing"), "email").' '; - $out.=$histo[$key]['id']; - $out.=''; + $out .= ''; + if (isset($histo[$key]['type']) && $histo[$key]['type'] == 'mailing') { + $out .= ''.img_object($langs->trans("ShowEMailing"), "email").' '; + $out .= $histo[$key]['id']; + $out .= ''; } else { - $out.=$actionstatic->getNomUrl(1, -1); + $out .= $actionstatic->getNomUrl(1, -1); } - $out.=''; + $out .= ''; //$userstatic->id=$histo[$key]['userid']; //$userstatic->login=$histo[$key]['login']; //$out.=$userstatic->getLoginUrl(1); if ($histo[$key]['userid'] > 0) { - $userstatic->fetch($histo[$key]['userid']); // TODO Introduce a cache on users fetched - $out.=$userstatic->getNomUrl(-1, '', 0, 0, 16, 0, 'firstelselast', ''); + $userstatic->fetch($histo[$key]['userid']); // TODO Introduce a cache on users fetched + $out .= $userstatic->getNomUrl(-1, '', 0, 0, 16, 0, 'firstelselast', ''); } - $out.=''; - if (! empty($conf->global->AGENDA_USE_EVENT_TYPE)) + $out .= ''; + if (!empty($conf->global->AGENDA_USE_EVENT_TYPE)) { if ($actionstatic->type_picto) print img_picto('', $actionstatic->type_picto); else { - if ($actionstatic->type_code == 'AC_RDV') $out.= img_picto('', 'object_group', '', false, 0, 0, '', 'paddingright').' '; - elseif ($actionstatic->type_code == 'AC_TEL') $out.= img_picto('', 'object_phoning', '', false, 0, 0, '', 'paddingright').' '; - elseif ($actionstatic->type_code == 'AC_FAX') $out.= img_picto('', 'object_phoning_fax', '', false, 0, 0, '', 'paddingright').' '; - elseif ($actionstatic->type_code == 'AC_EMAIL') $out.= img_picto('', 'object_email', '', false, 0, 0, '', 'paddingright').' '; - elseif ($actionstatic->type_code == 'AC_INT') $out.= img_picto('', 'object_intervention', '', false, 0, 0, '', 'paddingright').' '; - elseif (! preg_match('/_AUTO/', $actionstatic->type_code)) $out.= img_picto('', 'object_action', '', false, 0, 0, '', 'paddingright').' '; + if ($actionstatic->type_code == 'AC_RDV') $out .= img_picto('', 'object_group', '', false, 0, 0, '', 'paddingright').' '; + elseif ($actionstatic->type_code == 'AC_TEL') $out .= img_picto('', 'object_phoning', '', false, 0, 0, '', 'paddingright').' '; + elseif ($actionstatic->type_code == 'AC_FAX') $out .= img_picto('', 'object_phoning_fax', '', false, 0, 0, '', 'paddingright').' '; + elseif ($actionstatic->type_code == 'AC_EMAIL') $out .= img_picto('', 'object_email', '', false, 0, 0, '', 'paddingright').' '; + elseif ($actionstatic->type_code == 'AC_INT') $out .= img_picto('', 'object_intervention', '', false, 0, 0, '', 'paddingright').' '; + elseif (!preg_match('/_AUTO/', $actionstatic->type_code)) $out .= img_picto('', 'object_action', '', false, 0, 0, '', 'paddingright').' '; } } - $labeltype=$actionstatic->type_code; - if (empty($conf->global->AGENDA_USE_EVENT_TYPE) && empty($arraylist[$labeltype])) $labeltype='AC_OTH'; - if (! empty($arraylist[$labeltype])) $labeltype=$arraylist[$labeltype]; - $out.= dol_trunc($labeltype, 28); - $out.=''; - if (isset($histo[$key]['type']) && $histo[$key]['type']=='action') + $out .= ''; + if (isset($histo[$key]['type']) && $histo[$key]['type'] == 'action') { - $transcode=$langs->trans("Action".$histo[$key]['acode']); - $libelle=($transcode!="Action".$histo[$key]['acode']?$transcode:$histo[$key]['alabel']); + $transcode = $langs->trans("Action".$histo[$key]['acode']); + $libelle = ($transcode != "Action".$histo[$key]['acode'] ? $transcode : $histo[$key]['alabel']); //$actionstatic->libelle=$libelle; - $libelle=$histo[$key]['note']; - $actionstatic->id=$histo[$key]['id']; - $out.=dol_trunc($libelle, 120); + $libelle = $histo[$key]['note']; + $actionstatic->id = $histo[$key]['id']; + $out .= dol_trunc($libelle, 120); } - if (isset($histo[$key]['type']) && $histo[$key]['type']=='mailing') + if (isset($histo[$key]['type']) && $histo[$key]['type'] == 'mailing') { - $out.=''.img_object($langs->trans("ShowEMailing"), "email").' '; - $transcode=$langs->trans("Action".$histo[$key]['acode']); - $libelle=($transcode!="Action".$histo[$key]['acode']?$transcode:'Send mass mailing'); - $out.=dol_trunc($libelle, 120); + $out .= ''.img_object($langs->trans("ShowEMailing"), "email").' '; + $transcode = $langs->trans("Action".$histo[$key]['acode']); + $libelle = ($transcode != "Action".$histo[$key]['acode'] ? $transcode : 'Send mass mailing'); + $out .= dol_trunc($libelle, 120); } - $out.=''; - $out.=dol_print_date($histo[$key]['datestart'], 'dayhour'); + $out .= ''; + $out .= dol_print_date($histo[$key]['datestart'], 'dayhour'); if ($histo[$key]['dateend'] && $histo[$key]['dateend'] != $histo[$key]['datestart']) { - $tmpa=dol_getdate($histo[$key]['datestart'], true); - $tmpb=dol_getdate($histo[$key]['dateend'], true); - if ($tmpa['mday'] == $tmpb['mday'] && $tmpa['mon'] == $tmpb['mon'] && $tmpa['year'] == $tmpb['year']) $out.='-'.dol_print_date($histo[$key]['dateend'], 'hour'); - else $out.='-'.dol_print_date($histo[$key]['dateend'], 'dayhour'); + $tmpa = dol_getdate($histo[$key]['datestart'], true); + $tmpb = dol_getdate($histo[$key]['dateend'], true); + if ($tmpa['mday'] == $tmpb['mday'] && $tmpa['mon'] == $tmpb['mon'] && $tmpa['year'] == $tmpb['year']) $out .= '-'.dol_print_date($histo[$key]['dateend'], 'hour'); + else $out .= '-'.dol_print_date($histo[$key]['dateend'], 'dayhour'); } - $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")).' '; - $out.="'.dol_trunc($histo[$key]['note'], 40).''; + $out .= ''; if (isset($histo[$key]['elementtype']) && !empty($histo[$key]['fk_element'])) { - $out.=dolGetElementUrl($histo[$key]['fk_element'], $histo[$key]['elementtype'], 1); + $out .= dolGetElementUrl($histo[$key]['fk_element'], $histo[$key]['elementtype'], 1); } - else $out.=' '; - $out.=''.$contactstatic->getNomUrl(1, '', 10).''.$contactstatic->getNomUrl(1, '', 10).''; foreach ($histo[$key]['socpeopleassigned'] as $cid => $Tab) { @@ -1740,8 +1740,8 @@ function show_actions_done($conf, $langs, $db, $filterobj, $objcon = '', $noprin if ($result > 0) { $out .= $contact->getNomUrl(1); if (isset($histo[$key]['acode']) && $histo[$key]['acode'] == 'AC_TEL') { - if (! empty($contact->phone_pro)) - $out .= '(' . dol_print_phone($contact->phone_pro) . ')'; + if (!empty($contact->phone_pro)) + $out .= '('.dol_print_phone($contact->phone_pro).')'; } $out .= '
    '; } @@ -1749,23 +1749,23 @@ function show_actions_done($conf, $langs, $db, $filterobj, $objcon = '', $noprin $out .= '
      '.$actionstatic->LibStatut($histo[$key]['percent'], 3, 0, $histo[$key]['datestart']).''.$actionstatic->LibStatut($histo[$key]['percent'], 3, 0, $histo[$key]['datestart']).'
    \n"; - $out.="
    \n"; + $out .= "
    \n"; + $out .= "\n"; } - $out.=''; + $out .= ''; if ($noprint) return $out; else print $out; @@ -1784,13 +1784,13 @@ function show_subsidiaries($conf, $langs, $db, $object) { global $user; - $i=-1; + $i = -1; $sql = "SELECT s.rowid, s.client, s.fournisseur, s.nom as name, s.name_alias, s.email, s.address, s.zip, s.town, s.code_client, s.code_fournisseur, s.code_compta, s.code_compta_fournisseur, s.canvas"; - $sql.= " FROM ".MAIN_DB_PREFIX."societe as s"; - $sql.= " WHERE s.parent = ".$object->id; - $sql.= " AND s.entity IN (".getEntity('societe').")"; - $sql.= " ORDER BY s.nom"; + $sql .= " FROM ".MAIN_DB_PREFIX."societe as s"; + $sql .= " WHERE s.parent = ".$object->id; + $sql .= " AND s.entity IN (".getEntity('societe').")"; + $sql .= " ORDER BY s.nom"; $result = $db->query($sql); $num = $db->num_rows($result); @@ -1800,7 +1800,7 @@ function show_subsidiaries($conf, $langs, $db, $object) $socstatic = new Societe($db); print load_fiche_titre($langs->trans("Subsidiaries"), '', ''); - print "\n".''."\n"; + print "\n".'
    '."\n"; print ''; print ''; @@ -1808,7 +1808,7 @@ function show_subsidiaries($conf, $langs, $db, $object) print ""; print ""; - $i=0; + $i = 0; while ($i < $num) { diff --git a/htdocs/core/lib/cron.lib.php b/htdocs/core/lib/cron.lib.php index 4088b00c151..8128a449cfd 100644 --- a/htdocs/core/lib/cron.lib.php +++ b/htdocs/core/lib/cron.lib.php @@ -87,17 +87,17 @@ function dol_print_cron_urls() global $dolibarr_main_url_root; // Define $urlwithroot - $urlwithouturlroot=preg_replace('/'.preg_quote(DOL_URL_ROOT, '/').'$/i', '', trim($dolibarr_main_url_root)); - $urlwithroot=$urlwithouturlroot.DOL_URL_ROOT; // This is to use external domain name found into config file + $urlwithouturlroot = preg_replace('/'.preg_quote(DOL_URL_ROOT, '/').'$/i', '', trim($dolibarr_main_url_root)); + $urlwithroot = $urlwithouturlroot.DOL_URL_ROOT; // This is to use external domain name found into config file //$urlwithroot=DOL_MAIN_URL_ROOT; // This is to use same domain name than current // Cron launch print '
    '; print $langs->trans("URLToLaunchCronJobs").':
    '; - $url=$urlwithroot.'/public/cron/cron_run_jobs.php?'.(empty($conf->global->CRON_KEY)?'':'securitykey='.$conf->global->CRON_KEY.'&').'userlogin='.$user->login; + $url = $urlwithroot.'/public/cron/cron_run_jobs.php?'.(empty($conf->global->CRON_KEY) ? '' : 'securitykey='.$conf->global->CRON_KEY.'&').'userlogin='.$user->login; print img_picto('', 'globe').' '.$url."
    \n"; print ' '.$langs->trans("OrToLaunchASpecificJob").'
    '; - $url=$urlwithroot.'/public/cron/cron_run_jobs.php?'.(empty($conf->global->CRON_KEY)?'':'securitykey='.$conf->global->CRON_KEY.'&').'userlogin='.$user->login.'&id=cronjobid'; + $url = $urlwithroot.'/public/cron/cron_run_jobs.php?'.(empty($conf->global->CRON_KEY) ? '' : 'securitykey='.$conf->global->CRON_KEY.'&').'userlogin='.$user->login.'&id=cronjobid'; print img_picto('', 'globe').' '.$url."
    \n"; print '
    '; print '
    '; @@ -107,22 +107,22 @@ function dol_print_cron_urls() print ''.$langs->trans("FileToLaunchCronJobs").':
    '; - $file='/scripts/cron/cron_run_jobs.php'.' '.(empty($conf->global->CRON_KEY)?'securitykey':''.$conf->global->CRON_KEY.'').' '.$logintouse.' [cronjobid]'; + $file = '/scripts/cron/cron_run_jobs.php'.' '.(empty($conf->global->CRON_KEY) ? 'securitykey' : ''.$conf->global->CRON_KEY.'').' '.$logintouse.' [cronjobid]'; print '
    \n"; print '
    '; // Add note if (empty($conf->global->CRON_DISABLE_TUTORIAL_CRON)) { - $linuxlike=1; - if (preg_match('/^win/i', PHP_OS)) $linuxlike=0; - if (preg_match('/^mac/i', PHP_OS)) $linuxlike=0; + $linuxlike = 1; + if (preg_match('/^win/i', PHP_OS)) $linuxlike = 0; + if (preg_match('/^mac/i', PHP_OS)) $linuxlike = 0; print $langs->trans("Note").': '; if ($linuxlike) { print $langs->trans("CronExplainHowToRunUnix"); print '
    '; - print '
    '; + print '
    '; } else { diff --git a/htdocs/core/lib/doleditor.lib.php b/htdocs/core/lib/doleditor.lib.php index 34e8ad083f0..df9e3d94619 100644 --- a/htdocs/core/lib/doleditor.lib.php +++ b/htdocs/core/lib/doleditor.lib.php @@ -33,39 +33,39 @@ */ function show_skin($fuser, $edit = 0) { - global $conf,$langs,$db; + global $conf, $langs, $db; global $bc; - require_once DOL_DOCUMENT_ROOT . '/core/class/html.formother.class.php'; + require_once DOL_DOCUMENT_ROOT.'/core/class/html.formother.class.php'; $formother = new FormOther($db); - $dirskins=array('/includes/ckeditor/ckeditor/skins'); - if (! empty($conf->modules_parts['theme'])) // Using this feature slow down application + $dirskins = array('/includes/ckeditor/ckeditor/skins'); + if (!empty($conf->modules_parts['theme'])) // Using this feature slow down application { - foreach($conf->modules_parts['theme'] as $reldir) + foreach ($conf->modules_parts['theme'] as $reldir) { - $dirskins=array_merge($dirskins, (array) ($reldir.'theme')); + $dirskins = array_merge($dirskins, (array) ($reldir.'theme')); } } - $dirskins=array_unique($dirskins); + $dirskins = array_unique($dirskins); // Now dir_themes=array('/themes') or dir_themes=array('/theme','/mymodule/theme') - $selected_theme=''; - if (empty($conf->global->FCKEDITOR_SKIN)) $selected_theme='moono-lisa'; - else $selected_theme=$conf->global->FCKEDITOR_SKIN; + $selected_theme = ''; + if (empty($conf->global->FCKEDITOR_SKIN)) $selected_theme = 'moono-lisa'; + else $selected_theme = $conf->global->FCKEDITOR_SKIN; - $colspan=2; + $colspan = 2; - $thumbsbyrow=6; - print '
    '.$langs->trans("Company").''.$langs->trans("Address").''.$langs->trans("Zip").' 
    '; + $thumbsbyrow = 6; + print '
    '; - $var=false; + $var = false; // Title print ''; print ''; print ''; print '
    '.$langs->trans("DefaultSkin").''; - $url='http://ckeditor.com/addons/skins/all'; + $url = 'http://ckeditor.com/addons/skins/all'; /*print ''; print $langs->trans('DownloadMoreSkins'); print '';*/ @@ -74,7 +74,7 @@ function show_skin($fuser, $edit = 0) print '
    '.$langs->trans("ThemeDir").''; - foreach($dirskins as $dirskin) + foreach ($dirskins as $dirskin) { echo '"'.$dirskin.'" '; } @@ -86,22 +86,22 @@ function show_skin($fuser, $edit = 0) print '
    '; - $i=0; - foreach($dirskins as $dir) + $i = 0; + foreach ($dirskins as $dir) { //print $dirroot.$dir;exit; - $dirskin=dol_buildpath($dir, 0); // This include loop on $conf->file->dol_document_root - $urltheme=dol_buildpath($dir, 1); + $dirskin = dol_buildpath($dir, 0); // This include loop on $conf->file->dol_document_root + $urltheme = dol_buildpath($dir, 1); if (is_dir($dirskin)) { - $handle=opendir($dirskin); + $handle = opendir($dirskin); if (is_resource($handle)) { - while (($subdir = readdir($handle))!==false) + while (($subdir = readdir($handle)) !== false) { if (is_dir($dirskin."/".$subdir) && substr($subdir, 0, 1) <> '.' - && substr($subdir, 0, 3) <> 'CVS' && ! preg_match('/common|phones/i', $subdir)) + && substr($subdir, 0, 3) <> 'CVS' && !preg_match('/common|phones/i', $subdir)) { // Disable not stable themes (dir ends with _exp or _dev) if ($conf->global->MAIN_FEATURES_LEVEL < 2 && preg_match('/_dev$/i', $subdir)) continue; @@ -110,11 +110,11 @@ function show_skin($fuser, $edit = 0) print '
    '; if ($subdir == $selected_theme) { - print ' '.$subdir.''; + print ' '.$subdir.''; } else { - print ' '.$subdir; + print ' '.$subdir; } print '
    '; diff --git a/htdocs/core/lib/files.lib.php b/htdocs/core/lib/files.lib.php index 90c673e9e25..dc3581eaf20 100644 --- a/htdocs/core/lib/files.lib.php +++ b/htdocs/core/lib/files.lib.php @@ -65,23 +65,23 @@ function dol_dir_list($path, $types = "all", $recursive = 0, $filter = "", $excl dol_syslog("files.lib.php::dol_dir_list path=".$path." types=".$types." recursive=".$recursive." filter=".$filter." excludefilter=".json_encode($excludefilter)); //print 'xxx'."files.lib.php::dol_dir_list path=".$path." types=".$types." recursive=".$recursive." filter=".$filter." excludefilter=".json_encode($excludefilter); - $loaddate=($mode==1||$mode==2)?true:false; - $loadsize=($mode==1||$mode==3)?true:false; + $loaddate = ($mode == 1 || $mode == 2) ?true:false; + $loadsize = ($mode == 1 || $mode == 3) ?true:false; // Clean parameters - $path=preg_replace('/([\\/]+)$/i', '', $path); - $newpath=dol_osencode($path); + $path = preg_replace('/([\\/]+)$/i', '', $path); + $newpath = dol_osencode($path); $reshook = 0; $file_list = array(); - if (is_object($hookmanager) && ! $nohook) + if (is_object($hookmanager) && !$nohook) { - $hookmanager->resArray=array(); + $hookmanager->resArray = array(); $hookmanager->initHooks(array('fileslib')); - $parameters=array( + $parameters = array( 'path' => $newpath, 'types'=> $types, 'recursive' => $recursive, @@ -93,63 +93,63 @@ function dol_dir_list($path, $types = "all", $recursive = 0, $filter = "", $excl 'loadsize' => $loadsize, 'mode' => $mode ); - $reshook=$hookmanager->executeHooks('getDirList', $parameters, $object); + $reshook = $hookmanager->executeHooks('getDirList', $parameters, $object); } // $hookmanager->resArray may contain array stacked by other modules if (empty($reshook)) { - if (! is_dir($newpath)) return array(); + if (!is_dir($newpath)) return array(); if ($dir = opendir($newpath)) { - $filedate=''; - $filesize=''; + $filedate = ''; + $filesize = ''; while (false !== ($file = readdir($dir))) // $file is always a basename (into directory $newpath) { - if (! utf8_check($file)) $file=utf8_encode($file); // To be sure data is stored in utf8 in memory - $fullpathfile=($newpath?$newpath.'/':'').$file; + if (!utf8_check($file)) $file = utf8_encode($file); // To be sure data is stored in utf8 in memory + $fullpathfile = ($newpath ? $newpath.'/' : '').$file; - $qualified=1; + $qualified = 1; // Define excludefilterarray - $excludefilterarray=array('^\.'); + $excludefilterarray = array('^\.'); if (is_array($excludefilter)) { - $excludefilterarray=array_merge($excludefilterarray, $excludefilter); + $excludefilterarray = array_merge($excludefilterarray, $excludefilter); } - elseif ($excludefilter) $excludefilterarray[]=$excludefilter; + elseif ($excludefilter) $excludefilterarray[] = $excludefilter; // Check if file is qualified - foreach($excludefilterarray as $filt) + foreach ($excludefilterarray as $filt) { if (preg_match('/'.$filt.'/i', $file) || preg_match('/'.$filt.'/i', $fullpathfile)) { - $qualified=0; break; + $qualified = 0; break; } } //print $fullpathfile.' '.$file.' '.$qualified.'
    '; if ($qualified) { - $isdir=is_dir(dol_osencode($path."/".$file)); + $isdir = is_dir(dol_osencode($path."/".$file)); // Check whether this is a file or directory and whether we're interested in that type - if ($isdir && (($types=="directories") || ($types=="all") || $recursive)) + if ($isdir && (($types == "directories") || ($types == "all") || $recursive)) { // Add entry into file_list array - if (($types=="directories") || ($types=="all")) + if (($types == "directories") || ($types == "all")) { - if ($loaddate || $sortcriteria == 'date') $filedate=dol_filemtime($path."/".$file); - if ($loadsize || $sortcriteria == 'size') $filesize=dol_filesize($path."/".$file); + if ($loaddate || $sortcriteria == 'date') $filedate = dol_filemtime($path."/".$file); + if ($loadsize || $sortcriteria == 'size') $filesize = dol_filesize($path."/".$file); - if (! $filter || preg_match('/'.$filter.'/i', $file)) // We do not search key $filter into all $path, only into $file part + if (!$filter || preg_match('/'.$filter.'/i', $file)) // We do not search key $filter into all $path, only into $file part { preg_match('/([^\/]+)\/[^\/]+$/', $path.'/'.$file, $reg); - $level1name=(isset($reg[1])?$reg[1]:''); + $level1name = (isset($reg[1]) ? $reg[1] : ''); $file_list[] = array( "name" => $file, "path" => $path, "level1name" => $level1name, - "relativename" => ($relativename?$relativename.'/':'').$file, + "relativename" => ($relativename ? $relativename.'/' : '').$file, "fullname" => $path.'/'.$file, "date" => $filedate, "size" => $filesize, @@ -161,28 +161,28 @@ function dol_dir_list($path, $types = "all", $recursive = 0, $filter = "", $excl // if we're in a directory and we want recursive behavior, call this function again if ($recursive) { - if (empty($donotfollowsymlinks) || ! is_link($path."/".$file)) + if (empty($donotfollowsymlinks) || !is_link($path."/".$file)) { //var_dump('eee '. $path."/".$file. ' '.is_dir($path."/".$file).' '.is_link($path."/".$file)); - $file_list = array_merge($file_list, dol_dir_list($path."/".$file, $types, $recursive, $filter, $excludefilter, $sortcriteria, $sortorder, $mode, $nohook, ($relativename!=''?$relativename.'/':'').$file, $donotfollowsymlinks)); + $file_list = array_merge($file_list, dol_dir_list($path."/".$file, $types, $recursive, $filter, $excludefilter, $sortcriteria, $sortorder, $mode, $nohook, ($relativename != '' ? $relativename.'/' : '').$file, $donotfollowsymlinks)); } } } - elseif (! $isdir && (($types == "files") || ($types == "all"))) + elseif (!$isdir && (($types == "files") || ($types == "all"))) { // Add file into file_list array - if ($loaddate || $sortcriteria == 'date') $filedate=dol_filemtime($path."/".$file); - if ($loadsize || $sortcriteria == 'size') $filesize=dol_filesize($path."/".$file); + if ($loaddate || $sortcriteria == 'date') $filedate = dol_filemtime($path."/".$file); + if ($loadsize || $sortcriteria == 'size') $filesize = dol_filesize($path."/".$file); - if (! $filter || preg_match('/'.$filter.'/i', $file)) // We do not search key $filter into $path, only into $file + if (!$filter || preg_match('/'.$filter.'/i', $file)) // We do not search key $filter into $path, only into $file { preg_match('/([^\/]+)\/[^\/]+$/', $path.'/'.$file, $reg); - $level1name=(isset($reg[1])?$reg[1]:''); + $level1name = (isset($reg[1]) ? $reg[1] : ''); $file_list[] = array( "name" => $file, "path" => $path, "level1name" => $level1name, - "relativename" => ($relativename?$relativename.'/':'').$file, + "relativename" => ($relativename ? $relativename.'/' : '').$file, "fullname" => $path.'/'.$file, "date" => $filedate, "size" => $filesize, @@ -225,17 +225,17 @@ function dol_dir_list_in_database($path, $filter = "", $excludefilter = null, $s { global $conf, $db; - $sql =" SELECT rowid, label, entity, filename, filepath, fullpath_orig, keywords, cover, gen_or_uploaded, extraparams, date_c, date_m, fk_user_c, fk_user_m,"; - $sql.=" acl, position, share"; - if ($mode) $sql.=", description"; - $sql.=" FROM ".MAIN_DB_PREFIX."ecm_files"; - $sql.=" WHERE filepath = '".$db->escape($path)."'"; - $sql.=" AND entity = ".$conf->entity; + $sql = " SELECT rowid, label, entity, filename, filepath, fullpath_orig, keywords, cover, gen_or_uploaded, extraparams, date_c, date_m, fk_user_c, fk_user_m,"; + $sql .= " acl, position, share"; + if ($mode) $sql .= ", description"; + $sql .= " FROM ".MAIN_DB_PREFIX."ecm_files"; + $sql .= " WHERE filepath = '".$db->escape($path)."'"; + $sql .= " AND entity = ".$conf->entity; $resql = $db->query($sql); if ($resql) { - $file_list=array(); + $file_list = array(); $num = $db->num_rows($resql); $i = 0; while ($i < $num) @@ -244,10 +244,10 @@ function dol_dir_list_in_database($path, $filter = "", $excludefilter = null, $s if ($obj) { preg_match('/([^\/]+)\/[^\/]+$/', DOL_DATA_ROOT.'/'.$obj->filepath.'/'.$obj->filename, $reg); - $level1name=(isset($reg[1])?$reg[1]:''); + $level1name = (isset($reg[1]) ? $reg[1] : ''); $file_list[] = array( "rowid" => $obj->rowid, - "label" => $obj->label, // md5 + "label" => $obj->label, // md5 "name" => $obj->filename, "path" => DOL_DATA_ROOT.'/'.$obj->filepath, "level1name" => $level1name, @@ -267,12 +267,12 @@ function dol_dir_list_in_database($path, $filter = "", $excludefilter = null, $s } // Obtain a list of columns - if (! empty($sortcriteria)) + if (!empty($sortcriteria)) { - $myarray=array(); + $myarray = array(); foreach ($file_list as $key => $row) { - $myarray[$key] = (isset($row[$sortcriteria])?$row[$sortcriteria]:''); + $myarray[$key] = (isset($row[$sortcriteria]) ? $row[$sortcriteria] : ''); } // Sort the data if ($sortorder) array_multisort($myarray, $sortorder, $file_list); @@ -304,11 +304,11 @@ function completeFileArrayWithDatabaseInfo(&$filearray, $relativedir) // TODO Remove this when PRODUCT_USE_OLD_PATH_FOR_PHOTO will be removed global $modulepart; - if ($modulepart == 'produit' && ! empty($conf->global->PRODUCT_USE_OLD_PATH_FOR_PHOTO)) { + if ($modulepart == 'produit' && !empty($conf->global->PRODUCT_USE_OLD_PATH_FOR_PHOTO)) { global $object; - if (! empty($object->id)) + if (!empty($object->id)) { - if (! empty($conf->product->enabled)) $upload_dirold = $conf->product->multidir_output[$object->entity].'/'.substr(substr("000".$object->id, -2), 1, 1).'/'.substr(substr("000".$object->id, -2), 0, 1).'/'.$object->id."/photos"; + if (!empty($conf->product->enabled)) $upload_dirold = $conf->product->multidir_output[$object->entity].'/'.substr(substr("000".$object->id, -2), 1, 1).'/'.substr(substr("000".$object->id, -2), 0, 1).'/'.$object->id."/photos"; else $upload_dirold = $conf->service->multidir_output[$object->entity].'/'.substr(substr("000".$object->id, -2), 1, 1).'/'.substr(substr("000".$object->id, -2), 0, 1).'/'.$object->id."/photos"; $relativedirold = preg_replace('/^'.preg_quote(DOL_DATA_ROOT, '/').'/', '', $upload_dirold); @@ -322,38 +322,38 @@ function completeFileArrayWithDatabaseInfo(&$filearray, $relativedir) //var_dump($filearrayindatabase); // Complete filearray with properties found into $filearrayindatabase - foreach($filearray as $key => $val) + foreach ($filearray as $key => $val) { - $found=0; + $found = 0; // Search if it exists into $filearrayindatabase - foreach($filearrayindatabase as $key2 => $val2) + foreach ($filearrayindatabase as $key2 => $val2) { if ($filearrayindatabase[$key2]['name'] == $filearray[$key]['name']) { - $filearray[$key]['position_name']=($filearrayindatabase[$key2]['position']?$filearrayindatabase[$key2]['position']:'0').'_'.$filearrayindatabase[$key2]['name']; - $filearray[$key]['position']=$filearrayindatabase[$key2]['position']; - $filearray[$key]['cover']=$filearrayindatabase[$key2]['cover']; - $filearray[$key]['acl']=$filearrayindatabase[$key2]['acl']; - $filearray[$key]['rowid']=$filearrayindatabase[$key2]['rowid']; - $filearray[$key]['label']=$filearrayindatabase[$key2]['label']; - $filearray[$key]['share']=$filearrayindatabase[$key2]['share']; - $found=1; + $filearray[$key]['position_name'] = ($filearrayindatabase[$key2]['position'] ? $filearrayindatabase[$key2]['position'] : '0').'_'.$filearrayindatabase[$key2]['name']; + $filearray[$key]['position'] = $filearrayindatabase[$key2]['position']; + $filearray[$key]['cover'] = $filearrayindatabase[$key2]['cover']; + $filearray[$key]['acl'] = $filearrayindatabase[$key2]['acl']; + $filearray[$key]['rowid'] = $filearrayindatabase[$key2]['rowid']; + $filearray[$key]['label'] = $filearrayindatabase[$key2]['label']; + $filearray[$key]['share'] = $filearrayindatabase[$key2]['share']; + $found = 1; break; } } - if (! $found) // This happen in transition toward version 6, or if files were added manually into os dir. + if (!$found) // This happen in transition toward version 6, or if files were added manually into os dir. { - $filearray[$key]['position']='999999'; // File not indexed are at end. So if we add a file, it will not replace an existing position - $filearray[$key]['cover']=0; - $filearray[$key]['acl']=''; + $filearray[$key]['position'] = '999999'; // File not indexed are at end. So if we add a file, it will not replace an existing position + $filearray[$key]['cover'] = 0; + $filearray[$key]['acl'] = ''; $rel_filename = preg_replace('/^'.preg_quote(DOL_DATA_ROOT, '/').'/', '', $filearray[$key]['fullname']); - if (! preg_match('/([\\/]temp[\\/]|[\\/]thumbs|\.meta$)/', $rel_filetorenameafter)) // If not a tmp file + if (!preg_match('/([\\/]temp[\\/]|[\\/]thumbs|\.meta$)/', $rel_filetorenameafter)) // If not a tmp file { dol_syslog("list_of_documents We found a file called '".$filearray[$key]['name']."' not indexed into database. We add it"); include_once DOL_DOCUMENT_ROOT.'/ecm/class/ecmfiles.class.php'; - $ecmfile=new EcmFiles($db); + $ecmfile = new EcmFiles($db); // Add entry into database $filename = basename($rel_filename); @@ -363,11 +363,11 @@ function completeFileArrayWithDatabaseInfo(&$filearray, $relativedir) $ecmfile->filepath = $rel_dir; $ecmfile->filename = $filename; - $ecmfile->label = md5_file(dol_osencode($filearray[$key]['fullname'])); // $destfile is a full path to file + $ecmfile->label = md5_file(dol_osencode($filearray[$key]['fullname'])); // $destfile is a full path to file $ecmfile->fullpath_orig = $filearray[$key]['fullname']; $ecmfile->gen_or_uploaded = 'unknown'; - $ecmfile->description = ''; // indexed content - $ecmfile->keyword = ''; // keyword content + $ecmfile->description = ''; // indexed content + $ecmfile->keyword = ''; // keyword content $result = $ecmfile->create($user); if ($result < 0) { @@ -375,12 +375,12 @@ function completeFileArrayWithDatabaseInfo(&$filearray, $relativedir) } else { - $filearray[$key]['rowid']=$result; + $filearray[$key]['rowid'] = $result; } } else { - $filearray[$key]['rowid']=0; // Should not happened + $filearray[$key]['rowid'] = 0; // Should not happened } } } @@ -401,10 +401,10 @@ function dol_compare_file($a, $b) global $sortorder; global $sortfield; - $sortorder=strtoupper($sortorder); + $sortorder = strtoupper($sortorder); - if ($sortorder == 'ASC') { $retup=-1; $retdown=1; } - else { $retup=1; $retdown=-1; } + if ($sortorder == 'ASC') { $retup = -1; $retdown = 1; } + else { $retup = 1; $retdown = -1; } if ($sortfield == 'name') { @@ -432,7 +432,7 @@ function dol_compare_file($a, $b) */ function dol_is_dir($folder) { - $newfolder=dol_osencode($folder); + $newfolder = dol_osencode($folder); if (is_dir($newfolder)) return true; else return false; } @@ -457,7 +457,7 @@ function dol_is_dir_empty($dir) */ function dol_is_file($pathoffile) { - $newpathoffile=dol_osencode($pathoffile); + $newpathoffile = dol_osencode($pathoffile); return is_file($newpathoffile); } @@ -469,7 +469,7 @@ function dol_is_file($pathoffile) */ function dol_is_link($pathoffile) { - $newpathoffile=dol_osencode($pathoffile); + $newpathoffile = dol_osencode($pathoffile); return is_link($newpathoffile); } @@ -481,8 +481,8 @@ function dol_is_link($pathoffile) */ function dol_is_url($url) { - $tmpprot=array('file','http','https','ftp','zlib','data','ssh','ssh2','ogg','expect'); - foreach($tmpprot as $prot) + $tmpprot = array('file', 'http', 'https', 'ftp', 'zlib', 'data', 'ssh', 'ssh2', 'ogg', 'expect'); + foreach ($tmpprot as $prot) { if (preg_match('/^'.$prot.':/i', $url)) return true; } @@ -497,7 +497,7 @@ function dol_is_url($url) */ function dol_dir_is_emtpy($folder) { - $newfolder=dol_osencode($folder); + $newfolder = dol_osencode($folder); if (is_dir($newfolder)) { $handle = opendir($newfolder); @@ -506,7 +506,7 @@ function dol_dir_is_emtpy($folder) { $name_array[] = $name; } - foreach($name_array as $temp) $folder_content .= $temp; + foreach ($name_array as $temp) $folder_content .= $temp; closedir($handle); @@ -526,24 +526,24 @@ function dol_dir_is_emtpy($folder) */ function dol_count_nb_of_line($file) { - $nb=0; + $nb = 0; - $newfile=dol_osencode($file); + $newfile = dol_osencode($file); //print 'x'.$file; - $fp=fopen($newfile, 'r'); + $fp = fopen($newfile, 'r'); if ($fp) { while (!feof($fp)) { - $line=fgets($fp); + $line = fgets($fp); // We increase count only if read was success. We need test because feof return true only after fgets so we do n+1 fgets for a file with n lines. - if (! $line === false) $nb++; + if (!$line === false) $nb++; } fclose($fp); } else { - $nb=-1; + $nb = -1; } return $nb; @@ -559,7 +559,7 @@ function dol_count_nb_of_line($file) */ function dol_filesize($pathoffile) { - $newpathoffile=dol_osencode($pathoffile); + $newpathoffile = dol_osencode($pathoffile); return filesize($newpathoffile); } @@ -571,7 +571,7 @@ function dol_filesize($pathoffile) */ function dol_filemtime($pathoffile) { - $newpathoffile=dol_osencode($pathoffile); + $newpathoffile = dol_osencode($pathoffile); return @filemtime($newpathoffile); // @Is to avoid errors if files does not exists } @@ -594,24 +594,24 @@ function dolReplaceInFile($srcfile, $arrayreplacement, $destfile = '', $newmask dol_syslog("files.lib.php::dolReplaceInFile srcfile=".$srcfile." destfile=".$destfile." newmask=".$newmask." indexdatabase=".$indexdatabase." arrayreplacementisregex=".$arrayreplacementisregex); if (empty($srcfile)) return -1; - if (empty($destfile)) $destfile=$srcfile; + if (empty($destfile)) $destfile = $srcfile; - $destexists=dol_is_file($destfile); + $destexists = dol_is_file($destfile); if (($destfile != $srcfile) && $destexists) return 0; - $tmpdestfile=$destfile.'.tmp'; + $tmpdestfile = $destfile.'.tmp'; - $newpathofsrcfile=dol_osencode($srcfile); - $newpathoftmpdestfile=dol_osencode($tmpdestfile); - $newpathofdestfile=dol_osencode($destfile); - $newdirdestfile=dirname($newpathofdestfile); + $newpathofsrcfile = dol_osencode($srcfile); + $newpathoftmpdestfile = dol_osencode($tmpdestfile); + $newpathofdestfile = dol_osencode($destfile); + $newdirdestfile = dirname($newpathofdestfile); - if ($destexists && ! is_writable($newpathofdestfile)) + if ($destexists && !is_writable($newpathofdestfile)) { dol_syslog("files.lib.php::dolReplaceInFile failed Permission denied to overwrite target file", LOG_WARNING); return -1; } - if (! is_writable($newdirdestfile)) + if (!is_writable($newdirdestfile)) { dol_syslog("files.lib.php::dolReplaceInFile failed Permission denied to write into target directory ".$newdirdestfile, LOG_WARNING); return -2; @@ -638,17 +638,17 @@ function dolReplaceInFile($srcfile, $arrayreplacement, $destfile = '', $newmask @chmod($newpathoftmpdestfile, octdec($newmask)); // Rename - $result=dol_move($newpathoftmpdestfile, $newpathofdestfile, $newmask, (($destfile == $srcfile)?1:0), 0, $indexdatabase); - if (! $result) + $result = dol_move($newpathoftmpdestfile, $newpathofdestfile, $newmask, (($destfile == $srcfile) ? 1 : 0), 0, $indexdatabase); + if (!$result) { dol_syslog("files.lib.php::dolReplaceInFile failed to move tmp file to final dest", LOG_WARNING); return -3; } - if (empty($newmask) && ! empty($conf->global->MAIN_UMASK)) $newmask=$conf->global->MAIN_UMASK; + if (empty($newmask) && !empty($conf->global->MAIN_UMASK)) $newmask = $conf->global->MAIN_UMASK; if (empty($newmask)) // This should no happen { dol_syslog("Warning: dolReplaceInFile called with empty value for newmask and no default value defined", LOG_WARNING); - $newmask='0664'; + $newmask = '0664'; } @chmod($newpathofdestfile, octdec($newmask)); @@ -675,36 +675,36 @@ function dol_copy($srcfile, $destfile, $newmask = 0, $overwriteifexists = 1) if (empty($srcfile) || empty($destfile)) return -1; - $destexists=dol_is_file($destfile); - if (! $overwriteifexists && $destexists) return 0; + $destexists = dol_is_file($destfile); + if (!$overwriteifexists && $destexists) return 0; - $newpathofsrcfile=dol_osencode($srcfile); - $newpathofdestfile=dol_osencode($destfile); - $newdirdestfile=dirname($newpathofdestfile); + $newpathofsrcfile = dol_osencode($srcfile); + $newpathofdestfile = dol_osencode($destfile); + $newdirdestfile = dirname($newpathofdestfile); - if ($destexists && ! is_writable($newpathofdestfile)) + if ($destexists && !is_writable($newpathofdestfile)) { dol_syslog("files.lib.php::dol_copy failed Permission denied to overwrite target file", LOG_WARNING); return -1; } - if (! is_writable($newdirdestfile)) + if (!is_writable($newdirdestfile)) { dol_syslog("files.lib.php::dol_copy failed Permission denied to write into target directory ".$newdirdestfile, LOG_WARNING); return -2; } // Copy with overwriting if exists - $result=@copy($newpathofsrcfile, $newpathofdestfile); + $result = @copy($newpathofsrcfile, $newpathofdestfile); //$result=copy($newpathofsrcfile, $newpathofdestfile); // To see errors, remove @ - if (! $result) + if (!$result) { dol_syslog("files.lib.php::dol_copy failed to copy", LOG_WARNING); return -3; } - if (empty($newmask) && ! empty($conf->global->MAIN_UMASK)) $newmask=$conf->global->MAIN_UMASK; + if (empty($newmask) && !empty($conf->global->MAIN_UMASK)) $newmask = $conf->global->MAIN_UMASK; if (empty($newmask)) // This should no happen { dol_syslog("Warning: dol_copy called with empty value for newmask and no default value defined", LOG_WARNING); - $newmask='0664'; + $newmask = '0664'; } @chmod($newpathofdestfile, octdec($newmask)); @@ -727,40 +727,40 @@ function dolCopyDir($srcfile, $destfile, $newmask, $overwriteifexists, $arrayrep { global $conf; - $result=0; + $result = 0; dol_syslog("files.lib.php::dolCopyDir srcfile=".$srcfile." destfile=".$destfile." newmask=".$newmask." overwriteifexists=".$overwriteifexists); if (empty($srcfile) || empty($destfile)) return -1; - $destexists=dol_is_dir($destfile); + $destexists = dol_is_dir($destfile); //if (! $overwriteifexists && $destexists) return 0; // The overwriteifexists is for files only, so propagated to dol_copy only. - if (! $destexists) + if (!$destexists) { // We must set mask just before creating dir, becaause it can be set differently by dol_copy umask(0); - $dirmaskdec=octdec($newmask); - if (empty($newmask) && ! empty($conf->global->MAIN_UMASK)) $dirmaskdec=octdec($conf->global->MAIN_UMASK); - $dirmaskdec |= octdec('0200'); // Set w bit required to be able to create content for recursive subdirs files + $dirmaskdec = octdec($newmask); + if (empty($newmask) && !empty($conf->global->MAIN_UMASK)) $dirmaskdec = octdec($conf->global->MAIN_UMASK); + $dirmaskdec |= octdec('0200'); // Set w bit required to be able to create content for recursive subdirs files dol_mkdir($destfile, '', decoct($dirmaskdec)); } - $ossrcfile=dol_osencode($srcfile); - $osdestfile=dol_osencode($destfile); + $ossrcfile = dol_osencode($srcfile); + $osdestfile = dol_osencode($destfile); // Recursive function to copy all subdirectories and contents: if (is_dir($ossrcfile)) { - $dir_handle=opendir($ossrcfile); - while ($file=readdir($dir_handle)) + $dir_handle = opendir($ossrcfile); + while ($file = readdir($dir_handle)) { - if ($file != "." && $file != ".." && ! is_link($ossrcfile."/".$file)) + if ($file != "." && $file != ".." && !is_link($ossrcfile."/".$file)) { if (is_dir($ossrcfile."/".$file)) { //var_dump("xxx dolCopyDir $srcfile/$file, $destfile/$file, $newmask, $overwriteifexists"); - $tmpresult=dolCopyDir($srcfile."/".$file, $destfile."/".$file, $newmask, $overwriteifexists, $arrayreplacement); + $tmpresult = dolCopyDir($srcfile."/".$file, $destfile."/".$file, $newmask, $overwriteifexists, $arrayreplacement); } else { @@ -768,12 +768,12 @@ function dolCopyDir($srcfile, $destfile, $newmask, $overwriteifexists, $arrayrep // Replace destination filename with a new one if (is_array($arrayreplacement)) { - foreach($arrayreplacement as $key => $val) + foreach ($arrayreplacement as $key => $val) { $newfile = str_replace($key, $val, $newfile); } } - $tmpresult=dol_copy($srcfile."/".$file, $destfile."/".$newfile, $newmask, $overwriteifexists); + $tmpresult = dol_copy($srcfile."/".$file, $destfile."/".$newfile, $newmask, $overwriteifexists); } // Set result if ($result > 0 && $tmpresult >= 0) @@ -782,7 +782,7 @@ function dolCopyDir($srcfile, $destfile, $newmask, $overwriteifexists, $arrayrep } else { - $result=$tmpresult; + $result = $tmpresult; } if ($result < 0) break; } @@ -818,28 +818,28 @@ function dolCopyDir($srcfile, $destfile, $newmask, $overwriteifexists, $arrayrep function dol_move($srcfile, $destfile, $newmask = 0, $overwriteifexists = 1, $testvirus = 0, $indexdatabase = 1) { global $user, $db, $conf; - $result=false; + $result = false; dol_syslog("files.lib.php::dol_move srcfile=".$srcfile." destfile=".$destfile." newmask=".$newmask." overwritifexists=".$overwriteifexists); - $srcexists=dol_is_file($srcfile); - $destexists=dol_is_file($destfile); + $srcexists = dol_is_file($srcfile); + $destexists = dol_is_file($destfile); - if (! $srcexists) + if (!$srcexists) { dol_syslog("files.lib.php::dol_move srcfile does not exists. we ignore the move request."); return false; } - if ($overwriteifexists || ! $destexists) + if ($overwriteifexists || !$destexists) { - $newpathofsrcfile=dol_osencode($srcfile); - $newpathofdestfile=dol_osencode($destfile); + $newpathofsrcfile = dol_osencode($srcfile); + $newpathofdestfile = dol_osencode($destfile); // Check virus - $testvirusarray=array(); + $testvirusarray = array(); if ($testvirus) { - $testvirusarray=dolCheckVirus($newpathofsrcfile); + $testvirusarray = dolCheckVirus($newpathofsrcfile); if (count($testvirusarray)) { dol_syslog("files.lib.php::dol_move canceled because a virus was found into source file. we ignore the move request.", LOG_WARNING); @@ -847,15 +847,15 @@ function dol_move($srcfile, $destfile, $newmask = 0, $overwriteifexists = 1, $te } } - $result=@rename($newpathofsrcfile, $newpathofdestfile); // To see errors, remove @ - if (! $result) + $result = @rename($newpathofsrcfile, $newpathofdestfile); // To see errors, remove @ + if (!$result) { if ($destexists) { dol_syslog("files.lib.php::dol_move Failed. We try to delete target first and move after.", LOG_WARNING); // We force delete and try again. Rename function sometimes fails to replace dest file with some windows NTFS partitions. dol_delete_file($destfile); - $result=@rename($newpathofsrcfile, $newpathofdestfile); // To see errors, remove @ + $result = @rename($newpathofsrcfile, $newpathofdestfile); // To see errors, remove @ } else dol_syslog("files.lib.php::dol_move Failed.", LOG_WARNING); } @@ -866,7 +866,7 @@ function dol_move($srcfile, $destfile, $newmask = 0, $overwriteifexists = 1, $te // Rename entry into ecm database $rel_filetorenamebefore = preg_replace('/^'.preg_quote(DOL_DATA_ROOT, '/').'/', '', $srcfile); $rel_filetorenameafter = preg_replace('/^'.preg_quote(DOL_DATA_ROOT, '/').'/', '', $destfile); - if (! preg_match('/([\\/]temp[\\/]|[\\/]thumbs|\.meta$)/', $rel_filetorenameafter)) // If not a tmp file + if (!preg_match('/([\\/]temp[\\/]|[\\/]thumbs|\.meta$)/', $rel_filetorenameafter)) // If not a tmp file { $rel_filetorenamebefore = preg_replace('/^[\\/]/', '', $rel_filetorenamebefore); $rel_filetorenameafter = preg_replace('/^[\\/]/', '', $rel_filetorenameafter); @@ -875,14 +875,14 @@ function dol_move($srcfile, $destfile, $newmask = 0, $overwriteifexists = 1, $te dol_syslog("Try to rename also entries in database for full relative path before = ".$rel_filetorenamebefore." after = ".$rel_filetorenameafter, LOG_DEBUG); include_once DOL_DOCUMENT_ROOT.'/ecm/class/ecmfiles.class.php'; - $ecmfiletarget=new EcmFiles($db); + $ecmfiletarget = new EcmFiles($db); $resultecmtarget = $ecmfiletarget->fetch(0, '', $rel_filetorenameafter); if ($resultecmtarget > 0) // An entry for target name already exists for target, we delete it, a new one will be created. { $ecmfiletarget->delete($user); } - $ecmfile=new EcmFiles($db); + $ecmfile = new EcmFiles($db); $resultecm = $ecmfile->fetch(0, '', $rel_filetorenamebefore); if ($resultecm > 0) // If an entry was found for src file, we use it to move entry { @@ -904,11 +904,11 @@ function dol_move($srcfile, $destfile, $newmask = 0, $overwriteifexists = 1, $te $ecmfile->filepath = $rel_dir; $ecmfile->filename = $filename; - $ecmfile->label = md5_file(dol_osencode($destfile)); // $destfile is a full path to file + $ecmfile->label = md5_file(dol_osencode($destfile)); // $destfile is a full path to file $ecmfile->fullpath_orig = $srcfile; $ecmfile->gen_or_uploaded = 'unknown'; - $ecmfile->description = ''; // indexed content - $ecmfile->keyword = ''; // keyword content + $ecmfile->description = ''; // indexed content + $ecmfile->keyword = ''; // keyword content $resultecm = $ecmfile->create($user); if ($resultecm < 0) { @@ -920,13 +920,13 @@ function dol_move($srcfile, $destfile, $newmask = 0, $overwriteifexists = 1, $te setEventMessages($ecmfile->error, $ecmfile->errors, 'warnings'); } - if ($resultecm > 0) $result=true; + if ($resultecm > 0) $result = true; else $result = false; } } - if (empty($newmask)) $newmask=empty($conf->global->MAIN_UMASK)?'0755':$conf->global->MAIN_UMASK; - $newmaskdec=octdec($newmask); + if (empty($newmask)) $newmask = empty($conf->global->MAIN_UMASK) ? '0755' : $conf->global->MAIN_UMASK; + $newmaskdec = octdec($newmask); // Currently method is restricted to files (dol_delete_files previously used is for files, and mask usage if for files too) // to allow mask usage for dir, we shoul introduce a new param "isdir" to 1 to complete newmask like this // if ($isdir) $newmaskdec |= octdec('0111'); // Set x bit required for directories @@ -962,16 +962,16 @@ function dolCheckVirus($src_file) { global $conf; - if (! empty($conf->global->MAIN_ANTIVIRUS_COMMAND)) + if (!empty($conf->global->MAIN_ANTIVIRUS_COMMAND)) { - if (! class_exists('AntiVir')) { + if (!class_exists('AntiVir')) { require_once DOL_DOCUMENT_ROOT.'/core/class/antivir.class.php'; } - $antivir=new AntiVir($db); + $antivir = new AntiVir($db); $result = $antivir->dol_avscan_file($src_file); if ($result < 0) // If virus or error, we stop here { - $reterrors=$antivir->errors; + $reterrors = $antivir->errors; return $reterrors; } } @@ -1003,15 +1003,15 @@ function dol_move_uploaded_file($src_file, $dest_file, $allowoverwrite, $disable global $conf, $db, $user, $langs; global $object, $hookmanager; - $reshook=0; + $reshook = 0; $file_name = $dest_file; if (empty($nohook)) { - $reshook=$hookmanager->initHooks(array('fileslib')); + $reshook = $hookmanager->initHooks(array('fileslib')); - $parameters=array('dest_file' => $dest_file, 'src_file' => $src_file, 'file_name' => $file_name, 'varfiles' => $varfiles, 'allowoverwrite' => $allowoverwrite); - $reshook=$hookmanager->executeHooks('moveUploadedFile', $parameters, $object); + $parameters = array('dest_file' => $dest_file, 'src_file' => $src_file, 'file_name' => $file_name, 'varfiles' => $varfiles, 'allowoverwrite' => $allowoverwrite); + $reshook = $hookmanager->executeHooks('moveUploadedFile', $parameters, $object); } if (empty($reshook)) @@ -1019,7 +1019,7 @@ function dol_move_uploaded_file($src_file, $dest_file, $allowoverwrite, $disable // If an upload error has been reported if ($uploaderrorcode) { - switch($uploaderrorcode) + switch ($uploaderrorcode) { case UPLOAD_ERR_INI_SIZE: // 1 return 'ErrorFileSizeTooLarge'; @@ -1041,7 +1041,7 @@ function dol_move_uploaded_file($src_file, $dest_file, $allowoverwrite, $disable // If we need to make a virus scan if (empty($disablevirusscan) && file_exists($src_file)) { - $checkvirusarray=dolCheckVirus($src_file); + $checkvirusarray = dolCheckVirus($src_file); if (count($checkvirusarray)) { dol_syslog('Files.lib::dol_move_uploaded_file File "'.$src_file.'" (target name "'.$dest_file.'") KO with antivirus: errors='.join(',', $checkvirusarray), LOG_WARNING); @@ -1054,7 +1054,7 @@ function dol_move_uploaded_file($src_file, $dest_file, $allowoverwrite, $disable // 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($dest_file) && empty($conf->global->MAIN_DOCUMENT_IS_OUTSIDE_WEBROOT_SO_NOEXE_NOT_REQUIRED)) { - $file_name.= '.noexe'; + $file_name .= '.noexe'; } // Security: @@ -1077,24 +1077,24 @@ function dol_move_uploaded_file($src_file, $dest_file, $allowoverwrite, $disable if ($reshook < 0) // At least one blocking error returned by one hook { $errmsg = join(',', $hookmanager->errors); - if (empty($errmsg)) $errmsg = 'ErrorReturnedBySomeHooks'; // Should not occurs. Added if hook is bugged and does not set ->errors when there is error. + if (empty($errmsg)) $errmsg = 'ErrorReturnedBySomeHooks'; // Should not occurs. Added if hook is bugged and does not set ->errors when there is error. return $errmsg; } elseif (empty($reshook)) { // The file functions must be in OS filesystem encoding. - $src_file_osencoded=dol_osencode($src_file); - $file_name_osencoded=dol_osencode($file_name); + $src_file_osencoded = dol_osencode($src_file); + $file_name_osencoded = dol_osencode($file_name); // Check if destination dir is writable - if (! is_writable(dirname($file_name_osencoded))) + if (!is_writable(dirname($file_name_osencoded))) { dol_syslog("Files.lib::dol_move_uploaded_file Dir ".dirname($file_name_osencoded)." is not writable. Return 'ErrorDirNotWritable'", LOG_WARNING); return 'ErrorDirNotWritable'; } // Check if destination file already exists - if (! $allowoverwrite) + if (!$allowoverwrite) { if (file_exists($file_name_osencoded)) { @@ -1104,21 +1104,21 @@ function dol_move_uploaded_file($src_file, $dest_file, $allowoverwrite, $disable } // Move file - $return=move_uploaded_file($src_file_osencoded, $file_name_osencoded); + $return = move_uploaded_file($src_file_osencoded, $file_name_osencoded); if ($return) { - if (! empty($conf->global->MAIN_UMASK)) @chmod($file_name_osencoded, octdec($conf->global->MAIN_UMASK)); + if (!empty($conf->global->MAIN_UMASK)) @chmod($file_name_osencoded, octdec($conf->global->MAIN_UMASK)); dol_syslog("Files.lib::dol_move_uploaded_file Success to move ".$src_file." to ".$file_name." - Umask=".$conf->global->MAIN_UMASK, LOG_DEBUG); - return 1; // Success + return 1; // Success } else { dol_syslog("Files.lib::dol_move_uploaded_file Failed to move ".$src_file." to ".$file_name, LOG_ERR); - return -3; // Unknown error + return -3; // Unknown error } } - return 1; // Success + return 1; // Success } /** @@ -1147,7 +1147,7 @@ function dol_delete_file($file, $disableglob = 0, $nophperrors = 0, $nohook = 0, // Security: // We refuse transversal using .. and pipes into filenames. - if ((! $allowdotdot && preg_match('/\.\./', $file)) || preg_match('/[<>|]/', $file)) + if ((!$allowdotdot && preg_match('/\.\./', $file)) || preg_match('/[<>|]/', $file)) { dol_syslog("Refused to delete file ".$file, LOG_WARNING); return false; @@ -1157,13 +1157,13 @@ function dol_delete_file($file, $disableglob = 0, $nophperrors = 0, $nohook = 0, { $hookmanager->initHooks(array('fileslib')); - $parameters=array( + $parameters = array( 'GET' => $_GET, 'file' => $file, 'disableglob'=> $disableglob, 'nophperrors' => $nophperrors ); - $reshook=$hookmanager->executeHooks('deleteFile', $parameters, $object); + $reshook = $hookmanager->executeHooks('deleteFile', $parameters, $object); } if (empty($nohook) && $reshook != 0) // reshook = 0 to do standard actions, 1 = ok, -1 = ko @@ -1173,29 +1173,29 @@ function dol_delete_file($file, $disableglob = 0, $nophperrors = 0, $nohook = 0, } else { - $error=0; + $error = 0; //print "x".$file." ".$disableglob;exit; - $file_osencoded=dol_osencode($file); // New filename encoded in OS filesystem encoding charset - if (empty($disableglob) && ! empty($file_osencoded)) + $file_osencoded = dol_osencode($file); // New filename encoded in OS filesystem encoding charset + if (empty($disableglob) && !empty($file_osencoded)) { - $ok=true; - $globencoded=str_replace('[', '\[', $file_osencoded); - $globencoded=str_replace(']', '\]', $globencoded); - $listofdir=glob($globencoded); - if (! empty($listofdir) && is_array($listofdir)) + $ok = true; + $globencoded = str_replace('[', '\[', $file_osencoded); + $globencoded = str_replace(']', '\]', $globencoded); + $listofdir = glob($globencoded); + if (!empty($listofdir) && is_array($listofdir)) { foreach ($listofdir as $filename) { - if ($nophperrors) $ok=@unlink($filename); - else $ok=unlink($filename); + if ($nophperrors) $ok = @unlink($filename); + else $ok = unlink($filename); if ($ok) { dol_syslog("Removed file ".$filename, LOG_DEBUG); // Delete entry into ecm database $rel_filetodelete = preg_replace('/^'.preg_quote(DOL_DATA_ROOT, '/').'/', '', $filename); - if (! preg_match('/(\/temp\/|\/thumbs\/|\.meta$)/', $rel_filetodelete)) // If not a tmp file + if (!preg_match('/(\/temp\/|\/thumbs\/|\.meta$)/', $rel_filetodelete)) // If not a tmp file { $rel_filetodelete = preg_replace('/^[\\/]/', '', $rel_filetodelete); @@ -1203,7 +1203,7 @@ function dol_delete_file($file, $disableglob = 0, $nophperrors = 0, $nohook = 0, { dol_syslog("Try to remove also entries in database for full relative path = ".$rel_filetodelete, LOG_DEBUG); include_once DOL_DOCUMENT_ROOT.'/ecm/class/ecmfiles.class.php'; - $ecmfile=new EcmFiles($db); + $ecmfile = new EcmFiles($db); $result = $ecmfile->fetch(0, '', $rel_filetodelete); if ($result >= 0 && $ecmfile->id > 0) { @@ -1228,9 +1228,9 @@ function dol_delete_file($file, $disableglob = 0, $nophperrors = 0, $nohook = 0, } else { - $ok=false; - if ($nophperrors) $ok=@unlink($file_osencoded); - else $ok=unlink($file_osencoded); + $ok = false; + if ($nophperrors) $ok = @unlink($file_osencoded); + else $ok = unlink($file_osencoded); if ($ok) dol_syslog("Removed file ".$file_osencoded, LOG_DEBUG); else dol_syslog("Failed to remove file ".$file_osencoded, LOG_WARNING); } @@ -1258,8 +1258,8 @@ function dol_delete_dir($dir, $nophperrors = 0) return false; } - $dir_osencoded=dol_osencode($dir); - return ($nophperrors?@rmdir($dir_osencoded):rmdir($dir_osencoded)); + $dir_osencoded = dol_osencode($dir); + return ($nophperrors ? @rmdir($dir_osencoded) : rmdir($dir_osencoded)); } /** @@ -1277,22 +1277,22 @@ function dol_delete_dir_recursive($dir, $count = 0, $nophperrors = 0, $onlysub = dol_syslog("functions.lib:dol_delete_dir_recursive ".$dir, LOG_DEBUG); if (dol_is_dir($dir)) { - $dir_osencoded=dol_osencode($dir); + $dir_osencoded = dol_osencode($dir); if ($handle = opendir("$dir_osencoded")) { while (false !== ($item = readdir($handle))) { - if (! utf8_check($item)) $item=utf8_encode($item); // should be useless + if (!utf8_check($item)) $item = utf8_encode($item); // should be useless if ($item != "." && $item != "..") { - if (is_dir(dol_osencode("$dir/$item")) && ! is_link(dol_osencode("$dir/$item"))) + if (is_dir(dol_osencode("$dir/$item")) && !is_link(dol_osencode("$dir/$item"))) { - $count=dol_delete_dir_recursive("$dir/$item", $count, $nophperrors, 0, $countdeleted); + $count = dol_delete_dir_recursive("$dir/$item", $count, $nophperrors, 0, $countdeleted); } else { - $result=dol_delete_file("$dir/$item", 1, $nophperrors); + $result = dol_delete_file("$dir/$item", 1, $nophperrors); $count++; if ($result) $countdeleted++; //else print 'Error on '.$item."\n"; @@ -1303,7 +1303,7 @@ function dol_delete_dir_recursive($dir, $count = 0, $nophperrors = 0, $onlysub = if (empty($onlysub)) { - $result=dol_delete_dir($dir, $nophperrors); + $result = dol_delete_dir($dir, $nophperrors); $count++; if ($result) $countdeleted++; //else print 'Error on '.$dir."\n"; @@ -1325,7 +1325,7 @@ function dol_delete_dir_recursive($dir, $count = 0, $nophperrors = 0, $onlysub = */ function dol_delete_preview($object) { - global $langs,$conf; + global $langs, $conf; // Define parent dir of elements $element = $object->element; @@ -1336,54 +1336,54 @@ function dol_delete_preview($object) elseif ($object->element == 'shipping') $dir = $conf->expedition->dir_output.'/sending'; elseif ($object->element == 'delivery') $dir = $conf->expedition->dir_output.'/receipt'; elseif ($object->element == 'fichinter') $dir = $conf->ficheinter->dir_output; - else $dir=empty($conf->$element->dir_output)?'':$conf->$element->dir_output; + else $dir = empty($conf->$element->dir_output) ? '' : $conf->$element->dir_output; if (empty($dir)) return 'ErrorObjectNoSupportedByFunction'; $refsan = dol_sanitizeFileName($object->ref); - $dir = $dir . "/" . $refsan ; - $filepreviewnew = $dir . "/" . $refsan . ".pdf_preview.png"; - $filepreviewnewbis = $dir . "/" . $refsan . ".pdf_preview-0.png"; - $filepreviewold = $dir . "/" . $refsan . ".pdf.png"; + $dir = $dir."/".$refsan; + $filepreviewnew = $dir."/".$refsan.".pdf_preview.png"; + $filepreviewnewbis = $dir."/".$refsan.".pdf_preview-0.png"; + $filepreviewold = $dir."/".$refsan.".pdf.png"; // For new preview files if (file_exists($filepreviewnew) && is_writable($filepreviewnew)) { - if (! dol_delete_file($filepreviewnew, 1)) + if (!dol_delete_file($filepreviewnew, 1)) { - $object->error=$langs->trans("ErrorFailedToDeleteFile", $filepreviewnew); + $object->error = $langs->trans("ErrorFailedToDeleteFile", $filepreviewnew); return 0; } } if (file_exists($filepreviewnewbis) && is_writable($filepreviewnewbis)) { - if (! dol_delete_file($filepreviewnewbis, 1)) + if (!dol_delete_file($filepreviewnewbis, 1)) { - $object->error=$langs->trans("ErrorFailedToDeleteFile", $filepreviewnewbis); + $object->error = $langs->trans("ErrorFailedToDeleteFile", $filepreviewnewbis); return 0; } } // For old preview files if (file_exists($filepreviewold) && is_writable($filepreviewold)) { - if (! dol_delete_file($filepreviewold, 1)) + if (!dol_delete_file($filepreviewold, 1)) { - $object->error=$langs->trans("ErrorFailedToDeleteFile", $filepreviewold); + $object->error = $langs->trans("ErrorFailedToDeleteFile", $filepreviewold); return 0; } } else { - $multiple = $filepreviewold . "."; + $multiple = $filepreviewold."."; for ($i = 0; $i < 20; $i++) { $preview = $multiple.$i; if (file_exists($preview) && is_writable($preview)) { - if ( ! dol_delete_file($preview, 1) ) + if (!dol_delete_file($preview, 1)) { - $object->error=$langs->trans("ErrorFailedToOpenFile", $preview); + $object->error = $langs->trans("ErrorFailedToOpenFile", $preview); return 0; } } @@ -1406,10 +1406,10 @@ function dol_meta_create($object) global $conf; // Create meta file - if (empty($conf->global->MAIN_DOC_CREATE_METAFILE)) return 0; // By default, no metafile. + if (empty($conf->global->MAIN_DOC_CREATE_METAFILE)) return 0; // By default, no metafile. // Define parent dir of elements - $element=$object->element; + $element = $object->element; if ($object->element == 'order_supplier') $dir = $conf->fournisseur->dir_output.'/commande'; elseif ($object->element == 'invoice_supplier') $dir = $conf->fournisseur->dir_output.'/facture'; @@ -1417,17 +1417,17 @@ function dol_meta_create($object) elseif ($object->element == 'shipping') $dir = $conf->expedition->dir_output.'/sending'; elseif ($object->element == 'delivery') $dir = $conf->expedition->dir_output.'/receipt'; elseif ($object->element == 'fichinter') $dir = $conf->ficheinter->dir_output; - else $dir=empty($conf->$element->dir_output)?'':$conf->$element->dir_output; + else $dir = empty($conf->$element->dir_output) ? '' : $conf->$element->dir_output; if ($dir) { $object->fetch_thirdparty(); $objectref = dol_sanitizeFileName($object->ref); - $dir = $dir . "/" . $objectref; - $file = $dir . "/" . $objectref . ".meta"; + $dir = $dir."/".$objectref; + $file = $dir."/".$objectref.".meta"; - if (! is_dir($dir)) + if (!is_dir($dir)) { dol_mkdir($dir); } @@ -1457,7 +1457,7 @@ function dol_meta_create($object) $fp = fopen($file, "w"); fputs($fp, $meta); fclose($fp); - if (! empty($conf->global->MAIN_UMASK)) + if (!empty($conf->global->MAIN_UMASK)) @chmod($file, octdec($conf->global->MAIN_UMASK)); return 1; @@ -1482,24 +1482,24 @@ function dol_meta_create($object) */ function dol_init_file_process($pathtoscan = '', $trackid = '') { - $listofpaths=array(); - $listofnames=array(); - $listofmimes=array(); + $listofpaths = array(); + $listofnames = array(); + $listofmimes = array(); if ($pathtoscan) { - $listoffiles=dol_dir_list($pathtoscan, 'files'); - foreach($listoffiles as $key => $val) + $listoffiles = dol_dir_list($pathtoscan, 'files'); + foreach ($listoffiles as $key => $val) { - $listofpaths[]=$val['fullname']; - $listofnames[]=$val['name']; - $listofmimes[]=dol_mimetype($val['name']); + $listofpaths[] = $val['fullname']; + $listofnames[] = $val['name']; + $listofmimes[] = dol_mimetype($val['name']); } } - $keytoavoidconflict = empty($trackid)?'':'-'.$trackid; - $_SESSION["listofpaths".$keytoavoidconflict]=join(';', $listofpaths); - $_SESSION["listofnames".$keytoavoidconflict]=join(';', $listofnames); - $_SESSION["listofmimes".$keytoavoidconflict]=join(';', $listofmimes); + $keytoavoidconflict = empty($trackid) ? '' : '-'.$trackid; + $_SESSION["listofpaths".$keytoavoidconflict] = join(';', $listofpaths); + $_SESSION["listofnames".$keytoavoidconflict] = join(';', $listofnames); + $_SESSION["listofmimes".$keytoavoidconflict] = join(';', $listofmimes); } @@ -1520,11 +1520,11 @@ function dol_init_file_process($pathtoscan = '', $trackid = '') */ function dol_add_file_process($upload_dir, $allowoverwrite = 0, $donotupdatesession = 0, $varfiles = 'addedfile', $savingdocmask = '', $link = null, $trackid = '', $generatethumbs = 1) { - global $db,$user,$conf,$langs; + global $db, $user, $conf, $langs; $res = 0; - if (! empty($_FILES[$varfiles])) // For view $_FILES[$varfiles]['error'] + if (!empty($_FILES[$varfiles])) // For view $_FILES[$varfiles]['error'] { dol_syslog('dol_add_file_process upload_dir='.$upload_dir.' allowoverwrite='.$allowoverwrite.' donotupdatesession='.$donotupdatesession.' savingdocmask='.$savingdocmask, LOG_DEBUG); if (dol_mkdir($upload_dir) >= 0) @@ -1633,7 +1633,7 @@ function dol_add_file_process($upload_dir, $allowoverwrite = 0, $donotupdatesess } } } elseif ($link) { - require_once DOL_DOCUMENT_ROOT . '/core/class/link.class.php'; + require_once DOL_DOCUMENT_ROOT.'/core/class/link.class.php'; $linkObject = new Link($db); $linkObject->entity = $conf->entity; $linkObject->url = $link; @@ -1670,25 +1670,25 @@ function dol_add_file_process($upload_dir, $allowoverwrite = 0, $donotupdatesess */ function dol_remove_file_process($filenb, $donotupdatesession = 0, $donotdeletefile = 1, $trackid = '') { - global $db,$user,$conf,$langs,$_FILES; + global $db, $user, $conf, $langs, $_FILES; - $keytodelete=$filenb; + $keytodelete = $filenb; $keytodelete--; - $listofpaths=array(); - $listofnames=array(); - $listofmimes=array(); - $keytoavoidconflict = empty($trackid)?'':'-'.$trackid; - 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]); + $listofpaths = array(); + $listofnames = array(); + $listofmimes = array(); + $keytoavoidconflict = empty($trackid) ? '' : '-'.$trackid; + 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 ($keytodelete >= 0) { - $pathtodelete=$listofpaths[$keytodelete]; - $filetodelete=$listofnames[$keytodelete]; - if (empty($donotdeletefile)) $result = dol_delete_file($pathtodelete, 1); // The delete of ecm database is inside the function dol_delete_file - else $result=0; + $pathtodelete = $listofpaths[$keytodelete]; + $filetodelete = $listofnames[$keytodelete]; + if (empty($donotdeletefile)) $result = dol_delete_file($pathtodelete, 1); // The delete of ecm database is inside the function dol_delete_file + else $result = 0; if ($result >= 0) { if (empty($donotdeletefile)) @@ -1728,21 +1728,21 @@ function addFileIntoDatabaseIndex($dir, $file, $fullpathorig = '', $mode = 'uplo $rel_dir = preg_replace('/^'.preg_quote(DOL_DATA_ROOT, '/').'/', '', $dir); - if (! preg_match('/[\\/]temp[\\/]|[\\/]thumbs|\.meta$/', $rel_dir)) // If not a tmp dir + if (!preg_match('/[\\/]temp[\\/]|[\\/]thumbs|\.meta$/', $rel_dir)) // If not a tmp dir { $filename = basename($file); $rel_dir = preg_replace('/[\\/]$/', '', $rel_dir); $rel_dir = preg_replace('/^[\\/]/', '', $rel_dir); include_once DOL_DOCUMENT_ROOT.'/ecm/class/ecmfiles.class.php'; - $ecmfile=new EcmFiles($db); + $ecmfile = new EcmFiles($db); $ecmfile->filepath = $rel_dir; $ecmfile->filename = $filename; - $ecmfile->label = md5_file(dol_osencode($dir.'/'.$file)); // MD5 of file content + $ecmfile->label = md5_file(dol_osencode($dir.'/'.$file)); // MD5 of file content $ecmfile->fullpath_orig = $fullpathorig; $ecmfile->gen_or_uploaded = $mode; - $ecmfile->description = ''; // indexed content - $ecmfile->keyword = ''; // keyword content + $ecmfile->description = ''; // indexed content + $ecmfile->keyword = ''; // keyword content if ($setsharekey) { require_once DOL_DOCUMENT_ROOT.'/core/lib/security2.lib.php'; @@ -1788,26 +1788,26 @@ function deleteFilesIntoDatabaseIndex($dir, $file, $mode = 'uploaded') $rel_dir = preg_replace('/[\\/]$/', '', $rel_dir); $rel_dir = preg_replace('/^[\\/]/', '', $rel_dir); - if (! $error) + if (!$error) { - $sql = 'DELETE FROM ' . MAIN_DB_PREFIX . 'ecm_files'; - $sql.= ' WHERE entity = '.$conf->entity; - $sql.= " AND filepath = '" . $db->escape($rel_dir) . "'"; - if ($file) $sql.= " AND filename = '" . $db->escape($file) . "'"; - if ($mode) $sql.= " AND gen_or_uploaded = '" . $db->escape($mode) . "'"; + $sql = 'DELETE FROM '.MAIN_DB_PREFIX.'ecm_files'; + $sql .= ' WHERE entity = '.$conf->entity; + $sql .= " AND filepath = '".$db->escape($rel_dir)."'"; + if ($file) $sql .= " AND filename = '".$db->escape($file)."'"; + if ($mode) $sql .= " AND gen_or_uploaded = '".$db->escape($mode)."'"; $resql = $db->query($sql); if (!$resql) { $error++; - dol_syslog(__METHOD__ . ' ' . $db->lasterror(), LOG_ERR); + dol_syslog(__METHOD__.' '.$db->lasterror(), LOG_ERR); } } // Commit or rollback if ($error) { $db->rollback(); - return - 1 * $error; + return -1 * $error; } else { $db->commit(); return 1; @@ -1830,12 +1830,12 @@ function dol_convert_file($fileinput, $ext = 'png', $fileoutput = '', $page = '' global $langs; if (class_exists('Imagick')) { - $image=new Imagick(); + $image = new Imagick(); try { - $filetoconvert=$fileinput.(($page != '')?'['.$page.']':''); + $filetoconvert = $fileinput.(($page != '') ? '['.$page.']' : ''); //var_dump($filetoconvert); $ret = $image->readImage($filetoconvert); - } catch(Exception $e) { + } catch (Exception $e) { $ext = pathinfo($fileinput, PATHINFO_EXTENSION); dol_syslog("Failed to read image using Imagick (Try to install package 'apt-get install php-imagick ghostscript' and check there is no policy to disable ".$ext." convertion in /etc/ImageMagick*/policy.xml): ".$e->getMessage(), LOG_WARNING); return 0; @@ -2031,20 +2031,20 @@ function dol_uncompress($inputfile, $outputdir) dol_syslog("Constant ODTPHP_PATHTOPCLZIP for pclzip library is set to ".ODTPHP_PATHTOPCLZIP.", so we use Pclzip to unzip into ".$outputdir); include_once ODTPHP_PATHTOPCLZIP.'/pclzip.lib.php'; $archive = new PclZip($inputfile); - $result=$archive->extract(PCLZIP_OPT_PATH, $outputdir); + $result = $archive->extract(PCLZIP_OPT_PATH, $outputdir); //var_dump($result); - if (! is_array($result) && $result <= 0) return array('error'=>$archive->errorInfo(true)); + if (!is_array($result) && $result <= 0) return array('error'=>$archive->errorInfo(true)); else { - $ok=1; $errmsg=''; + $ok = 1; $errmsg = ''; // Loop on each file to check result for unzipping file - foreach($result as $key => $val) + foreach ($result as $key => $val) { if ($val['status'] == 'path_creation_fail') { $langs->load("errors"); - $ok=0; - $errmsg=$langs->trans("ErrorFailToCreateDir", $val['filename']); + $ok = 0; + $errmsg = $langs->trans("ErrorFailToCreateDir", $val['filename']); break; } } @@ -2118,7 +2118,7 @@ function dol_compress_dir($inputdir, $outputfile, $mode = "zip", $excludefiles = //if (class_exists('ZipArchive') && ! empty($conf->global->MAIN_USE_ZIPARCHIVE_FOR_ZIP_COMPRESS)) if (class_exists('ZipArchive')) { - $foundhandler=1; + $foundhandler = 1; // Initialize archive object $zip = new ZipArchive(); @@ -2161,7 +2161,7 @@ function dol_compress_dir($inputdir, $outputfile, $mode = "zip", $excludefiles = } } - if (! $foundhandler) + if (!$foundhandler) { dol_syslog("Try to zip with format ".$mode." with no handler for this format", LOG_ERR); return -2; @@ -2177,7 +2177,7 @@ function dol_compress_dir($inputdir, $outputfile, $mode = "zip", $excludefiles = $langs->load("errors"); dol_syslog("Failed to open file ".$outputfile, LOG_ERR); dol_syslog($e->getMessage(), LOG_ERR); - $errormsg=$langs->trans("ErrorFailedToWriteInDir", $outputfile); + $errormsg = $langs->trans("ErrorFailedToWriteInDir", $outputfile); return -1; } } @@ -2194,9 +2194,9 @@ function dol_compress_dir($inputdir, $outputfile, $mode = "zip", $excludefiles = * @param int $mode 0=Return array minimum keys loaded (faster), 1=Force all keys like date and size to be loaded (slower), 2=Force load of date only, 3=Force load of size only * @return string Full path to most recent file */ -function dol_most_recent_file($dir, $regexfilter = '', $excludefilter = array('(\.meta|_preview.*\.png)$','^\.'), $nohook = false, $mode = '') +function dol_most_recent_file($dir, $regexfilter = '', $excludefilter = array('(\.meta|_preview.*\.png)$', '^\.'), $nohook = false, $mode = '') { - $tmparray=dol_dir_list($dir, 'files', 0, $regexfilter, $excludefilter, 'date', SORT_DESC, $mode, $nohook); + $tmparray = dol_dir_list($dir, 'files', 0, $regexfilter, $excludefilter, 'date', SORT_DESC, $mode, $nohook); return $tmparray[0]; } @@ -2486,9 +2486,9 @@ function dol_check_secure_access_document($modulepart, $original_file, $entity, if (empty($entity) || empty($conf->societe->multidir_output[$entity])) return array('accessallowed'=>0, 'error'=>'Value entity must be provided'); if ($fuser->rights->societe->{$lire} || preg_match('/^specimen/i', $original_file)) { - $accessallowed=1; + $accessallowed = 1; } - $original_file=$conf->societe->multidir_output[$entity].'/'.$original_file; + $original_file = $conf->societe->multidir_output[$entity].'/'.$original_file; $sqlprotectagainstexternals = "SELECT rowid as fk_soc FROM ".MAIN_DB_PREFIX."societe WHERE rowid='".$db->escape($refname)."' AND entity IN (".getEntity('societe').")"; } @@ -2498,9 +2498,9 @@ function dol_check_secure_access_document($modulepart, $original_file, $entity, if (empty($entity) || empty($conf->societe->multidir_output[$entity])) return array('accessallowed'=>0, 'error'=>'Value entity must be provided'); if ($fuser->rights->societe->{$lire}) { - $accessallowed=1; + $accessallowed = 1; } - $original_file=$conf->societe->multidir_output[$entity].'/contact/'.$original_file; + $original_file = $conf->societe->multidir_output[$entity].'/contact/'.$original_file; } // Wrapping for invoices @@ -2600,9 +2600,9 @@ function dol_check_secure_access_document($modulepart, $original_file, $entity, { if ($fuser->rights->ficheinter->{$lire} || preg_match('/^specimen/i', $original_file)) { - $accessallowed=1; + $accessallowed = 1; } - $original_file=$conf->ficheinter->dir_output.'/'.$original_file; + $original_file = $conf->ficheinter->dir_output.'/'.$original_file; $sqlprotectagainstexternals = "SELECT fk_soc as fk_soc FROM ".MAIN_DB_PREFIX."fichinter WHERE ref='".$db->escape($refname)."' AND entity=".$conf->entity; } @@ -2611,9 +2611,9 @@ function dol_check_secure_access_document($modulepart, $original_file, $entity, { if ($fuser->rights->deplacement->{$lire} || preg_match('/^specimen/i', $original_file)) { - $accessallowed=1; + $accessallowed = 1; } - $original_file=$conf->deplacement->dir_output.'/'.$original_file; + $original_file = $conf->deplacement->dir_output.'/'.$original_file; //$sqlprotectagainstexternals = "SELECT fk_soc as fk_soc FROM ".MAIN_DB_PREFIX."fichinter WHERE ref='".$db->escape($refname)."' AND entity=".$conf->entity; } // Wrapping pour les propales @@ -2621,9 +2621,9 @@ function dol_check_secure_access_document($modulepart, $original_file, $entity, { if ($fuser->rights->propale->{$lire} || preg_match('/^specimen/i', $original_file)) { - $accessallowed=1; + $accessallowed = 1; } - $original_file=$conf->propal->multidir_output[$entity].'/'.$original_file; + $original_file = $conf->propal->multidir_output[$entity].'/'.$original_file; $sqlprotectagainstexternals = "SELECT fk_soc as fk_soc FROM ".MAIN_DB_PREFIX."propal WHERE ref='".$db->escape($refname)."' AND entity=".$conf->entity; } @@ -2643,18 +2643,18 @@ function dol_check_secure_access_document($modulepart, $original_file, $entity, { if ($fuser->rights->projet->{$lire} || preg_match('/^specimen/i', $original_file)) { - $accessallowed=1; + $accessallowed = 1; } - $original_file=$conf->projet->dir_output.'/'.$original_file; + $original_file = $conf->projet->dir_output.'/'.$original_file; $sqlprotectagainstexternals = "SELECT fk_soc as fk_soc FROM ".MAIN_DB_PREFIX."projet WHERE ref='".$db->escape($refname)."' AND entity IN (".getEntity('project').")"; } elseif ($modulepart == 'project_task' && !empty($conf->projet->dir_output)) { if ($fuser->rights->projet->{$lire} || preg_match('/^specimen/i', $original_file)) { - $accessallowed=1; + $accessallowed = 1; } - $original_file=$conf->projet->dir_output.'/'.$original_file; + $original_file = $conf->projet->dir_output.'/'.$original_file; $sqlprotectagainstexternals = "SELECT fk_soc as fk_soc FROM ".MAIN_DB_PREFIX."projet WHERE ref='".$db->escape($refname)."' AND entity IN (".getEntity('project').")"; } @@ -2663,9 +2663,9 @@ function dol_check_secure_access_document($modulepart, $original_file, $entity, { if ($fuser->rights->fournisseur->commande->{$lire} || preg_match('/^specimen/i', $original_file)) { - $accessallowed=1; + $accessallowed = 1; } - $original_file=$conf->fournisseur->commande->dir_output.'/'.$original_file; + $original_file = $conf->fournisseur->commande->dir_output.'/'.$original_file; $sqlprotectagainstexternals = "SELECT fk_soc as fk_soc FROM ".MAIN_DB_PREFIX."commande_fournisseur WHERE ref='".$db->escape($refname)."' AND entity=".$conf->entity; } @@ -2684,9 +2684,9 @@ function dol_check_secure_access_document($modulepart, $original_file, $entity, { if ($fuser->rights->fournisseur->facture->{$lire} || preg_match('/^specimen/i', $original_file)) { - $accessallowed=1; + $accessallowed = 1; } - $original_file=$conf->fournisseur->payment->dir_output.'/'.$original_file; + $original_file = $conf->fournisseur->payment->dir_output.'/'.$original_file; $sqlprotectagainstexternals = "SELECT fk_soc as fk_soc FROM ".MAIN_DB_PREFIX."paiementfournisseur WHERE ref='".$db->escape($refname)."' AND entity=".$conf->entity; } @@ -2695,10 +2695,10 @@ function dol_check_secure_access_document($modulepart, $original_file, $entity, { if ($fuser->rights->facture->{$lire} || preg_match('/^specimen/i', $original_file)) { - $accessallowed=1; + $accessallowed = 1; } - if ($fuser->societe_id > 0) $original_file=$conf->facture->dir_output.'/payments/private/'.$fuser->id.'/'.$original_file; - else $original_file=$conf->facture->dir_output.'/payments/'.$original_file; + if ($fuser->societe_id > 0) $original_file = $conf->facture->dir_output.'/payments/private/'.$fuser->id.'/'.$original_file; + else $original_file = $conf->facture->dir_output.'/payments/'.$original_file; } // Wrapping for accounting exports @@ -2706,9 +2706,9 @@ function dol_check_secure_access_document($modulepart, $original_file, $entity, { if ($fuser->rights->accounting->bind->write || preg_match('/^specimen/i', $original_file)) { - $accessallowed=1; + $accessallowed = 1; } - $original_file=$conf->accounting->dir_output.'/'.$original_file; + $original_file = $conf->accounting->dir_output.'/'.$original_file; } // Wrapping pour les expedition @@ -2716,18 +2716,18 @@ function dol_check_secure_access_document($modulepart, $original_file, $entity, { if ($fuser->rights->expedition->{$lire} || preg_match('/^specimen/i', $original_file)) { - $accessallowed=1; + $accessallowed = 1; } - $original_file=$conf->expedition->dir_output."/sending/".$original_file; + $original_file = $conf->expedition->dir_output."/sending/".$original_file; } // Wrapping pour les bons de livraison elseif ($modulepart == 'livraison' && !empty($conf->expedition->dir_output)) { if ($fuser->rights->expedition->livraison->{$lire} || preg_match('/^specimen/i', $original_file)) { - $accessallowed=1; + $accessallowed = 1; } - $original_file=$conf->expedition->dir_output."/receipt/".$original_file; + $original_file = $conf->expedition->dir_output."/receipt/".$original_file; } // Wrapping pour les actions @@ -2735,9 +2735,9 @@ function dol_check_secure_access_document($modulepart, $original_file, $entity, { if ($fuser->rights->agenda->myactions->{$read} || preg_match('/^specimen/i', $original_file)) { - $accessallowed=1; + $accessallowed = 1; } - $original_file=$conf->agenda->dir_output.'/'.$original_file; + $original_file = $conf->agenda->dir_output.'/'.$original_file; } // Wrapping pour les actions @@ -2745,7 +2745,7 @@ function dol_check_secure_access_document($modulepart, $original_file, $entity, { if ($fuser->rights->agenda->allactions->{$read} || preg_match('/^specimen/i', $original_file)) { - $accessallowed=1; + $accessallowed = 1; } $original_file = $conf->agenda->dir_temp."/".$original_file; } @@ -2756,10 +2756,10 @@ function dol_check_secure_access_document($modulepart, $original_file, $entity, if (empty($entity) || (empty($conf->product->multidir_output[$entity]) && empty($conf->service->multidir_output[$entity]))) return array('accessallowed'=>0, 'error'=>'Value entity must be provided'); if (($fuser->rights->produit->{$lire} || $fuser->rights->service->{$lire}) || preg_match('/^specimen/i', $original_file)) { - $accessallowed=1; + $accessallowed = 1; } - if (! empty($conf->product->enabled)) $original_file=$conf->product->multidir_output[$entity].'/'.$original_file; - elseif (! empty($conf->service->enabled)) $original_file=$conf->service->multidir_output[$entity].'/'.$original_file; + if (!empty($conf->product->enabled)) $original_file = $conf->product->multidir_output[$entity].'/'.$original_file; + elseif (!empty($conf->service->enabled)) $original_file = $conf->service->multidir_output[$entity].'/'.$original_file; } // Wrapping pour les lots produits @@ -2768,9 +2768,9 @@ function dol_check_secure_access_document($modulepart, $original_file, $entity, if (empty($entity) || (empty($conf->productbatch->multidir_output[$entity]))) return array('accessallowed'=>0, 'error'=>'Value entity must be provided'); if (($fuser->rights->produit->{$lire} ) || preg_match('/^specimen/i', $original_file)) { - $accessallowed=1; + $accessallowed = 1; } - if (! empty($conf->productbatch->enabled)) $original_file=$conf->productbatch->multidir_output[$entity].'/'.$original_file; + if (!empty($conf->productbatch->enabled)) $original_file = $conf->productbatch->multidir_output[$entity].'/'.$original_file; } // Wrapping for stock movements @@ -2779,9 +2779,9 @@ function dol_check_secure_access_document($modulepart, $original_file, $entity, if (empty($entity) || empty($conf->stock->multidir_output[$entity])) return array('accessallowed'=>0, 'error'=>'Value entity must be provided'); if (($fuser->rights->stock->{$lire} || $fuser->rights->stock->movement->{$lire} || $fuser->rights->stock->mouvement->{$lire}) || preg_match('/^specimen/i', $original_file)) { - $accessallowed=1; + $accessallowed = 1; } - if (! empty($conf->stock->enabled)) $original_file=$conf->stock->multidir_output[$entity].'/movement/'.$original_file; + if (!empty($conf->stock->enabled)) $original_file = $conf->stock->multidir_output[$entity].'/movement/'.$original_file; } // Wrapping pour les contrats @@ -2789,9 +2789,9 @@ function dol_check_secure_access_document($modulepart, $original_file, $entity, { if ($fuser->rights->contrat->{$lire} || preg_match('/^specimen/i', $original_file)) { - $accessallowed=1; + $accessallowed = 1; } - $original_file=$conf->contrat->dir_output.'/'.$original_file; + $original_file = $conf->contrat->dir_output.'/'.$original_file; $sqlprotectagainstexternals = "SELECT fk_soc as fk_soc FROM ".MAIN_DB_PREFIX."contrat WHERE ref='".$db->escape($refname)."' AND entity IN (".getEntity('contract').")"; } @@ -2800,9 +2800,9 @@ function dol_check_secure_access_document($modulepart, $original_file, $entity, { if ($fuser->rights->don->{$lire} || preg_match('/^specimen/i', $original_file)) { - $accessallowed=1; + $accessallowed = 1; } - $original_file=$conf->don->dir_output.'/'.$original_file; + $original_file = $conf->don->dir_output.'/'.$original_file; } // Wrapping pour les dons @@ -2810,9 +2810,9 @@ function dol_check_secure_access_document($modulepart, $original_file, $entity, { if ($fuser->rights->resource->{$read} || preg_match('/^specimen/i', $original_file)) { - $accessallowed=1; + $accessallowed = 1; } - $original_file=$conf->resource->dir_output.'/'.$original_file; + $original_file = $conf->resource->dir_output.'/'.$original_file; } // Wrapping pour les remises de cheques @@ -2820,10 +2820,10 @@ function dol_check_secure_access_document($modulepart, $original_file, $entity, { if ($fuser->rights->banque->{$lire} || preg_match('/^specimen/i', $original_file)) { - $accessallowed=1; + $accessallowed = 1; } - $original_file=$conf->bank->dir_output.'/checkdeposits/'.$original_file; // original_file should contains relative path so include the get_exdir result + $original_file = $conf->bank->dir_output.'/checkdeposits/'.$original_file; // original_file should contains relative path so include the get_exdir result } // Wrapping for bank @@ -2831,9 +2831,9 @@ function dol_check_secure_access_document($modulepart, $original_file, $entity, { if ($fuser->rights->banque->{$lire}) { - $accessallowed=1; + $accessallowed = 1; } - $original_file=$conf->bank->dir_output.'/'.$original_file; + $original_file = $conf->bank->dir_output.'/'.$original_file; } // Wrapping for export module @@ -2841,45 +2841,45 @@ function dol_check_secure_access_document($modulepart, $original_file, $entity, { // Aucun test necessaire car on force le rep de download sur // le rep export qui est propre a l'utilisateur - $accessallowed=1; - $original_file=$conf->export->dir_temp.'/'.$fuser->id.'/'.$original_file; + $accessallowed = 1; + $original_file = $conf->export->dir_temp.'/'.$fuser->id.'/'.$original_file; } // Wrapping for import module elseif ($modulepart == 'import' && !empty($conf->import->dir_temp)) { - $accessallowed=1; - $original_file=$conf->import->dir_temp.'/'.$original_file; + $accessallowed = 1; + $original_file = $conf->import->dir_temp.'/'.$original_file; } // Wrapping pour l'editeur wysiwyg elseif ($modulepart == 'editor' && !empty($conf->fckeditor->dir_output)) { - $accessallowed=1; - $original_file=$conf->fckeditor->dir_output.'/'.$original_file; + $accessallowed = 1; + $original_file = $conf->fckeditor->dir_output.'/'.$original_file; } // Wrapping for backups elseif ($modulepart == 'systemtools' && !empty($conf->admin->dir_output)) { - if ($fuser->admin) $accessallowed=1; - $original_file=$conf->admin->dir_output.'/'.$original_file; + if ($fuser->admin) $accessallowed = 1; + $original_file = $conf->admin->dir_output.'/'.$original_file; } // Wrapping for upload file test elseif ($modulepart == 'admin_temp' && !empty($conf->admin->dir_temp)) { - if ($fuser->admin) $accessallowed=1; - $original_file=$conf->admin->dir_temp.'/'.$original_file; + if ($fuser->admin) $accessallowed = 1; + $original_file = $conf->admin->dir_temp.'/'.$original_file; } // Wrapping pour BitTorrent elseif ($modulepart == 'bittorrent' && !empty($conf->bittorrent->dir_output)) { - $accessallowed=1; - $dir='files'; - if (dol_mimetype($original_file) == 'application/x-bittorrent') $dir='torrents'; - $original_file=$conf->bittorrent->dir_output.'/'.$dir.'/'.$original_file; + $accessallowed = 1; + $dir = 'files'; + if (dol_mimetype($original_file) == 'application/x-bittorrent') $dir = 'torrents'; + $original_file = $conf->bittorrent->dir_output.'/'.$dir.'/'.$original_file; } // Wrapping pour Foundation module @@ -2887,16 +2887,16 @@ function dol_check_secure_access_document($modulepart, $original_file, $entity, { if ($fuser->rights->adherent->{$lire} || preg_match('/^specimen/i', $original_file)) { - $accessallowed=1; + $accessallowed = 1; } - $original_file=$conf->adherent->dir_output.'/'.$original_file; + $original_file = $conf->adherent->dir_output.'/'.$original_file; } // Wrapping for Scanner elseif ($modulepart == 'scanner_user_temp' && !empty($conf->scanner->dir_temp)) { - $accessallowed=1; - $original_file=$conf->scanner->dir_temp.'/'.$fuser->id.'/'.$original_file; + $accessallowed = 1; + $original_file = $conf->scanner->dir_temp.'/'.$fuser->id.'/'.$original_file; } // GENERIC Wrapping @@ -2906,8 +2906,8 @@ function dol_check_secure_access_document($modulepart, $original_file, $entity, // If modulepart=module Allows any module to open a file if file is in directory called DOL_DATA_ROOT/modulepart else { - if (preg_match('/^specimen/i', $original_file)) $accessallowed=1; // If link to a file called specimen. Test must be done before changing $original_file int full path. - if ($fuser->admin) $accessallowed=1; // If user is admin + if (preg_match('/^specimen/i', $original_file)) $accessallowed = 1; // If link to a file called specimen. Test must be done before changing $original_file int full path. + if ($fuser->admin) $accessallowed = 1; // If user is admin // Define $accessallowed if (preg_match('/^([a-z]+)_user_temp$/i', $modulepart, $reg)) @@ -2917,8 +2917,8 @@ function dol_check_secure_access_document($modulepart, $original_file, $entity, dol_print_error('', 'Error call dol_check_secure_access_document with not supported value for modulepart parameter ('.$modulepart.')'); exit; } - if ($fuser->rights->{$reg[1]}->{$lire} || $fuser->rights->{$reg[1]}->{$read} || ($fuser->rights->{$reg[1]}->{$download})) $accessallowed=1; - $original_file=$conf->{$reg[1]}->dir_temp.'/'.$fuser->id.'/'.$original_file; + if ($fuser->rights->{$reg[1]}->{$lire} || $fuser->rights->{$reg[1]}->{$read} || ($fuser->rights->{$reg[1]}->{$download})) $accessallowed = 1; + $original_file = $conf->{$reg[1]}->dir_temp.'/'.$fuser->id.'/'.$original_file; } elseif (preg_match('/^([a-z]+)_temp$/i', $modulepart, $reg)) { @@ -2927,8 +2927,8 @@ function dol_check_secure_access_document($modulepart, $original_file, $entity, dol_print_error('', 'Error call dol_check_secure_access_document with not supported value for modulepart parameter ('.$modulepart.')'); exit; } - if ($fuser->rights->{$reg[1]}->{$lire} || $fuser->rights->{$reg[1]}->{$read} || ($fuser->rights->{$reg[1]}->{$download})) $accessallowed=1; - $original_file=$conf->{$reg[1]}->dir_temp.'/'.$original_file; + if ($fuser->rights->{$reg[1]}->{$lire} || $fuser->rights->{$reg[1]}->{$read} || ($fuser->rights->{$reg[1]}->{$download})) $accessallowed = 1; + $original_file = $conf->{$reg[1]}->dir_temp.'/'.$original_file; } elseif (preg_match('/^([a-z]+)_user$/i', $modulepart, $reg)) { @@ -2937,8 +2937,8 @@ function dol_check_secure_access_document($modulepart, $original_file, $entity, dol_print_error('', 'Error call dol_check_secure_access_document with not supported value for modulepart parameter ('.$modulepart.')'); exit; } - if ($fuser->rights->{$reg[1]}->{$lire} || $fuser->rights->{$reg[1]}->{$read} || ($fuser->rights->{$reg[1]}->{$download})) $accessallowed=1; - $original_file=$conf->{$reg[1]}->dir_output.'/'.$fuser->id.'/'.$original_file; + if ($fuser->rights->{$reg[1]}->{$lire} || $fuser->rights->{$reg[1]}->{$read} || ($fuser->rights->{$reg[1]}->{$download})) $accessallowed = 1; + $original_file = $conf->{$reg[1]}->dir_output.'/'.$fuser->id.'/'.$original_file; } elseif (preg_match('/^massfilesarea_([a-z]+)$/i', $modulepart, $reg)) { @@ -2949,9 +2949,9 @@ function dol_check_secure_access_document($modulepart, $original_file, $entity, } if ($fuser->rights->{$reg[1]}->{$lire} || preg_match('/^specimen/i', $original_file)) { - $accessallowed=1; + $accessallowed = 1; } - $original_file=$conf->{$reg[1]}->dir_output.'/temp/massgeneration/'.$user->id.'/'.$original_file; + $original_file = $conf->{$reg[1]}->dir_output.'/temp/massgeneration/'.$user->id.'/'.$original_file; } else { @@ -2961,34 +2961,34 @@ function dol_check_secure_access_document($modulepart, $original_file, $entity, exit; } - $perm=GETPOST('perm'); - $subperm=GETPOST('subperm'); + $perm = GETPOST('perm'); + $subperm = GETPOST('subperm'); if ($perm || $subperm) { - if (($perm && ! $subperm && $fuser->rights->$modulepart->$perm) || ($perm && $subperm && $fuser->rights->$modulepart->$perm->$subperm)) $accessallowed=1; - $original_file=$conf->$modulepart->dir_output.'/'.$original_file; + if (($perm && !$subperm && $fuser->rights->$modulepart->$perm) || ($perm && $subperm && $fuser->rights->$modulepart->$perm->$subperm)) $accessallowed = 1; + $original_file = $conf->$modulepart->dir_output.'/'.$original_file; } else { - if ($fuser->rights->$modulepart->{$lire} || $fuser->rights->$modulepart->{$read}) $accessallowed=1; - $original_file=$conf->$modulepart->dir_output.'/'.$original_file; + if ($fuser->rights->$modulepart->{$lire} || $fuser->rights->$modulepart->{$read}) $accessallowed = 1; + $original_file = $conf->$modulepart->dir_output.'/'.$original_file; } } // For modules who wants to manage different levels of permissions for documents $subPermCategoryConstName = strtoupper($modulepart).'_SUBPERMCATEGORY_FOR_DOCUMENTS'; - if (! empty($conf->global->$subPermCategoryConstName)) + if (!empty($conf->global->$subPermCategoryConstName)) { $subPermCategory = $conf->global->$subPermCategoryConstName; - if (! empty($subPermCategory) && (($fuser->rights->$modulepart->$subPermCategory->{$lire}) || ($fuser->rights->$modulepart->$subPermCategory->{$read}) || ($fuser->rights->$modulepart->$subPermCategory->{$download}))) + if (!empty($subPermCategory) && (($fuser->rights->$modulepart->$subPermCategory->{$lire}) || ($fuser->rights->$modulepart->$subPermCategory->{$read}) || ($fuser->rights->$modulepart->$subPermCategory->{$download}))) { - $accessallowed=1; + $accessallowed = 1; } } // Define $sqlprotectagainstexternals for modules who want to protect access using a SQL query. $sqlProtectConstName = strtoupper($modulepart).'_SQLPROTECTAGAINSTEXTERNALS_FOR_DOCUMENTS'; - if (! empty($conf->global->$sqlProtectConstName)) // If module want to define its own $sqlprotectagainstexternals + if (!empty($conf->global->$sqlProtectConstName)) // If module want to define its own $sqlprotectagainstexternals { // Example: mymodule__SQLPROTECTAGAINSTEXTERNALS_FOR_DOCUMENTS = "SELECT fk_soc FROM ".MAIN_DB_PREFIX.$modulepart." WHERE ref='".$db->escape($refname)."' AND entity=".$conf->entity; eval('$sqlprotectagainstexternals = "'.$conf->global->$sqlProtectConstName.'";'); @@ -3014,8 +3014,8 @@ function dol_check_secure_access_document($modulepart, $original_file, $entity, */ function dol_filecache($directory, $filename, $object) { - if (! dol_is_dir($directory)) dol_mkdir($directory); - $cachefile = $directory . $filename; + if (!dol_is_dir($directory)) dol_mkdir($directory); + $cachefile = $directory.$filename; file_put_contents($cachefile, serialize($object), LOCK_EX); @chmod($cachefile, 0644); } @@ -3031,8 +3031,8 @@ function dol_filecache($directory, $filename, $object) function dol_cache_refresh($directory, $filename, $cachetime) { $now = dol_now(); - $cachefile = $directory . $filename; - $refresh = !file_exists($cachefile) || ($now-$cachetime) > dol_filemtime($cachefile); + $cachefile = $directory.$filename; + $refresh = !file_exists($cachefile) || ($now - $cachetime) > dol_filemtime($cachefile); return $refresh; } @@ -3045,7 +3045,7 @@ function dol_cache_refresh($directory, $filename, $cachetime) */ function dol_readcachefile($directory, $filename) { - $cachefile = $directory . $filename; + $cachefile = $directory.$filename; $object = unserialize(file_get_contents($cachefile)); return $object; } diff --git a/htdocs/core/lib/functions.lib.php b/htdocs/core/lib/functions.lib.php index 740093ba801..00ca3f3d45f 100644 --- a/htdocs/core/lib/functions.lib.php +++ b/htdocs/core/lib/functions.lib.php @@ -37,7 +37,7 @@ * This file contains all frequently used functions. */ -include_once DOL_DOCUMENT_ROOT .'/core/lib/json.lib.php'; +include_once DOL_DOCUMENT_ROOT.'/core/lib/json.lib.php'; /** @@ -53,10 +53,10 @@ include_once DOL_DOCUMENT_ROOT .'/core/lib/json.lib.php'; */ function getDoliDBInstance($type, $host, $user, $pass, $name, $port) { - require_once DOL_DOCUMENT_ROOT ."/core/db/".$type.'.class.php'; + require_once DOL_DOCUMENT_ROOT."/core/db/".$type.'.class.php'; - $class='DoliDB'.ucfirst($type); - $dolidb=new $class($type, $host, $user, $pass, $name, $port); + $class = 'DoliDB'.ucfirst($type); + $dolidb = new $class($type, $host, $user, $pass, $name, $port); return $dolidb; } @@ -87,10 +87,10 @@ function getEntity($element, $shared = 1, $currentobject = null) } else { - $out=''; + $out = ''; $addzero = array('user', 'usergroup', 'c_email_templates', 'email_template', 'default_values'); - if (in_array($element, $addzero)) $out.= '0,'; - $out.= $conf->entity; + if (in_array($element, $addzero)) $out .= '0,'; + $out .= $conf->entity; return $out; } } @@ -135,9 +135,9 @@ function getBrowserInfo($user_agent) { include_once DOL_DOCUMENT_ROOT.'/includes/mobiledetect/mobiledetectlib/Mobile_Detect.php'; - $name='unknown'; - $version=''; - $os='unknown'; + $name = 'unknown'; + $version = ''; + $os = 'unknown'; $phone = ''; $detectmobile = new Mobile_Detect(null, $user_agent); @@ -168,22 +168,22 @@ function getBrowserInfo($user_agent) } // OS - if (preg_match('/linux/i', $user_agent)) { $os='linux'; } - elseif (preg_match('/macintosh/i', $user_agent)) { $os='macintosh'; } - elseif (preg_match('/windows/i', $user_agent)) { $os='windows'; } + if (preg_match('/linux/i', $user_agent)) { $os = 'linux'; } + elseif (preg_match('/macintosh/i', $user_agent)) { $os = 'macintosh'; } + elseif (preg_match('/windows/i', $user_agent)) { $os = 'windows'; } // Name - if (preg_match('/firefox(\/|\s)([\d\.]*)/i', $user_agent, $reg)) { $name='firefox'; $version=$reg[2]; } - elseif (preg_match('/edge(\/|\s)([\d\.]*)/i', $user_agent, $reg)) { $name='edge'; $version=$reg[2]; } - elseif (preg_match('/chrome(\/|\s)([\d\.]+)/i', $user_agent, $reg)) { $name='chrome'; $version=$reg[2]; } // we can have 'chrome (Mozilla...) chrome x.y' in one string - elseif (preg_match('/chrome/i', $user_agent, $reg)) { $name='chrome'; } - elseif (preg_match('/iceweasel/i', $user_agent)) { $name='iceweasel'; } - elseif (preg_match('/epiphany/i', $user_agent)) { $name='epiphany'; } - elseif (preg_match('/safari(\/|\s)([\d\.]*)/i', $user_agent, $reg)) { $name='safari'; $version=$reg[2]; } // Safari is often present in string for mobile but its not. - elseif (preg_match('/opera(\/|\s)([\d\.]*)/i', $user_agent, $reg)) { $name='opera'; $version=$reg[2]; } - elseif (preg_match('/(MSIE\s([0-9]+\.[0-9]))|.*(Trident\/[0-9]+.[0-9];.*rv:([0-9]+\.[0-9]+))/i', $user_agent, $reg)) { $name='ie'; $version=end($reg); } // MS products at end - elseif (preg_match('/(Windows NT\s([0-9]+\.[0-9])).*(Trident\/[0-9]+.[0-9];.*rv:([0-9]+\.[0-9]+))/i', $user_agent, $reg)) { $name='ie'; $version=end($reg); } // MS products at end - elseif (preg_match('/l(i|y)n(x|ks)(\(|\/|\s)*([\d\.]+)/i', $user_agent, $reg)) { $name='lynxlinks'; $version=$reg[4]; } + if (preg_match('/firefox(\/|\s)([\d\.]*)/i', $user_agent, $reg)) { $name = 'firefox'; $version = $reg[2]; } + elseif (preg_match('/edge(\/|\s)([\d\.]*)/i', $user_agent, $reg)) { $name = 'edge'; $version = $reg[2]; } + elseif (preg_match('/chrome(\/|\s)([\d\.]+)/i', $user_agent, $reg)) { $name = 'chrome'; $version = $reg[2]; } // we can have 'chrome (Mozilla...) chrome x.y' in one string + elseif (preg_match('/chrome/i', $user_agent, $reg)) { $name = 'chrome'; } + elseif (preg_match('/iceweasel/i', $user_agent)) { $name = 'iceweasel'; } + elseif (preg_match('/epiphany/i', $user_agent)) { $name = 'epiphany'; } + elseif (preg_match('/safari(\/|\s)([\d\.]*)/i', $user_agent, $reg)) { $name = 'safari'; $version = $reg[2]; } // Safari is often present in string for mobile but its not. + elseif (preg_match('/opera(\/|\s)([\d\.]*)/i', $user_agent, $reg)) { $name = 'opera'; $version = $reg[2]; } + elseif (preg_match('/(MSIE\s([0-9]+\.[0-9]))|.*(Trident\/[0-9]+.[0-9];.*rv:([0-9]+\.[0-9]+))/i', $user_agent, $reg)) { $name = 'ie'; $version = end($reg); } // MS products at end + elseif (preg_match('/(Windows NT\s([0-9]+\.[0-9])).*(Trident\/[0-9]+.[0-9];.*rv:([0-9]+\.[0-9]+))/i', $user_agent, $reg)) { $name = 'ie'; $version = end($reg); } // MS products at end + elseif (preg_match('/l(i|y)n(x|ks)(\(|\/|\s)*([\d\.]+)/i', $user_agent, $reg)) { $name = 'lynxlinks'; $version = $reg[4]; } if ($tablet) { $layout = 'tablet'; @@ -210,10 +210,10 @@ function getBrowserInfo($user_agent) */ function dol_shutdown() { - global $conf,$user,$langs,$db; - $disconnectdone=false; $depth=0; - if (is_object($db) && ! empty($db->connected)) { $depth=$db->transaction_opened; $disconnectdone=$db->close(); } - dol_syslog("--- End access to ".$_SERVER["PHP_SELF"].(($disconnectdone && $depth)?' (Warn: db disconnection forced, transaction depth was '.$depth.')':''), (($disconnectdone && $depth)?LOG_WARNING:LOG_INFO)); + global $conf, $user, $langs, $db; + $disconnectdone = false; $depth = 0; + if (is_object($db) && !empty($db->connected)) { $depth = $db->transaction_opened; $disconnectdone = $db->close(); } + dol_syslog("--- End access to ".$_SERVER["PHP_SELF"].(($disconnectdone && $depth) ? ' (Warn: db disconnection forced, transaction depth was '.$depth.')' : ''), (($disconnectdone && $depth) ?LOG_WARNING:LOG_INFO)); } /** @@ -253,7 +253,7 @@ function GETPOSTISSET($paramname) */ function GETPOST($paramname, $check = 'none', $method = 0, $filter = null, $options = null, $noreplace = 0) { - global $mysoc,$user,$conf; + global $mysoc, $user, $conf; if (empty($paramname)) return 'BadFirstParameterForGETPOST'; if (empty($check)) @@ -263,10 +263,10 @@ function GETPOST($paramname, $check = 'none', $method = 0, $filter = null, $opti //var_dump(debug_backtrace()[0]); } - if (empty($method)) $out = isset($_GET[$paramname])?$_GET[$paramname]:(isset($_POST[$paramname])?$_POST[$paramname]:''); - elseif ($method==1) $out = isset($_GET[$paramname])?$_GET[$paramname]:''; - elseif ($method==2) $out = isset($_POST[$paramname])?$_POST[$paramname]:''; - elseif ($method==3) $out = isset($_POST[$paramname])?$_POST[$paramname]:(isset($_GET[$paramname])?$_GET[$paramname]:''); + if (empty($method)) $out = isset($_GET[$paramname]) ? $_GET[$paramname] : (isset($_POST[$paramname]) ? $_POST[$paramname] : ''); + elseif ($method == 1) $out = isset($_GET[$paramname]) ? $_GET[$paramname] : ''; + elseif ($method == 2) $out = isset($_POST[$paramname]) ? $_POST[$paramname] : ''; + elseif ($method == 3) $out = isset($_POST[$paramname]) ? $_POST[$paramname] : (isset($_GET[$paramname]) ? $_GET[$paramname] : ''); else return 'BadThirdParameterForGETPOST'; if (empty($method) || $method == 3 || $method == 4) @@ -281,41 +281,41 @@ function GETPOST($paramname, $check = 'none', $method = 0, $filter = null, $opti // Code for search criteria persistence. // Retrieve values if restore_lastsearch_values - if (! empty($_GET['restore_lastsearch_values'])) // Use $_GET here and not GETPOST + if (!empty($_GET['restore_lastsearch_values'])) // Use $_GET here and not GETPOST { - if (! empty($_SESSION['lastsearch_values_'.$relativepathstring])) // If there is saved values + if (!empty($_SESSION['lastsearch_values_'.$relativepathstring])) // If there is saved values { - $tmp=json_decode($_SESSION['lastsearch_values_'.$relativepathstring], true); + $tmp = json_decode($_SESSION['lastsearch_values_'.$relativepathstring], true); if (is_array($tmp)) { - foreach($tmp as $key => $val) + foreach ($tmp as $key => $val) { if ($key == $paramname) // We are on the requested parameter { - $out=$val; + $out = $val; break; } } } } // If there is saved contextpage, page or limit - if ($paramname == 'contextpage' && ! empty($_SESSION['lastsearch_contextpage_'.$relativepathstring])) + if ($paramname == 'contextpage' && !empty($_SESSION['lastsearch_contextpage_'.$relativepathstring])) { $out = $_SESSION['lastsearch_contextpage_'.$relativepathstring]; } - elseif ($paramname == 'page' && ! empty($_SESSION['lastsearch_page_'.$relativepathstring])) + elseif ($paramname == 'page' && !empty($_SESSION['lastsearch_page_'.$relativepathstring])) { $out = $_SESSION['lastsearch_page_'.$relativepathstring]; } - elseif ($paramname == 'limit' && ! empty($_SESSION['lastsearch_limit_'.$relativepathstring])) + elseif ($paramname == 'limit' && !empty($_SESSION['lastsearch_limit_'.$relativepathstring])) { $out = $_SESSION['lastsearch_limit_'.$relativepathstring]; } } // Else, retreive default values if we are not doing a sort - elseif (! isset($_GET['sortfield'])) // If we did a click on a field to sort, we do no apply default values. Same if option MAIN_ENABLE_DEFAULT_VALUES is not set + elseif (!isset($_GET['sortfield'])) // If we did a click on a field to sort, we do no apply default values. Same if option MAIN_ENABLE_DEFAULT_VALUES is not set { - if (! empty($_GET['action']) && $_GET['action'] == 'create' && ! isset($_GET[$paramname]) && ! isset($_POST[$paramname])) + if (!empty($_GET['action']) && $_GET['action'] == 'create' && !isset($_GET[$paramname]) && !isset($_POST[$paramname])) { // Search default value from $object->field global $object; @@ -324,28 +324,28 @@ function GETPOST($paramname, $check = 'none', $method = 0, $filter = null, $opti $out = $object->fields[$paramname]['default']; } } - if (! empty($conf->global->MAIN_ENABLE_DEFAULT_VALUES)) + if (!empty($conf->global->MAIN_ENABLE_DEFAULT_VALUES)) { - if (! empty($_GET['action']) && (preg_match('/^create/', $_GET['action']) || preg_match('/^presend/', $_GET['action'])) && ! isset($_GET[$paramname]) && ! isset($_POST[$paramname])) + if (!empty($_GET['action']) && (preg_match('/^create/', $_GET['action']) || preg_match('/^presend/', $_GET['action'])) && !isset($_GET[$paramname]) && !isset($_POST[$paramname])) { // Now search in setup to overwrite default values - if (! empty($user->default_values)) // $user->default_values defined from menu 'Setup - Default values' + if (!empty($user->default_values)) // $user->default_values defined from menu 'Setup - Default values' { if (isset($user->default_values[$relativepathstring]['createform'])) { - foreach($user->default_values[$relativepathstring]['createform'] as $defkey => $defval) + foreach ($user->default_values[$relativepathstring]['createform'] as $defkey => $defval) { $qualified = 0; if ($defkey != '_noquery_') { - $tmpqueryarraytohave=explode('&', $defkey); - $tmpqueryarraywehave=explode('&', dol_string_nohtmltag($_SERVER['QUERY_STRING'])); - $foundintru=0; - foreach($tmpqueryarraytohave as $tmpquerytohave) + $tmpqueryarraytohave = explode('&', $defkey); + $tmpqueryarraywehave = explode('&', dol_string_nohtmltag($_SERVER['QUERY_STRING'])); + $foundintru = 0; + foreach ($tmpqueryarraytohave as $tmpquerytohave) { - if (! in_array($tmpquerytohave, $tmpqueryarraywehave)) $foundintru=1; + if (!in_array($tmpquerytohave, $tmpqueryarraywehave)) $foundintru = 1; } - if (! $foundintru) $qualified=1; + if (!$foundintru) $qualified = 1; //var_dump($defkey.'-'.$qualified); } else $qualified = 1; @@ -365,45 +365,45 @@ function GETPOST($paramname, $check = 'none', $method = 0, $filter = null, $opti } // Management of default search_filters and sort order //elseif (preg_match('/list.php$/', $_SERVER["PHP_SELF"]) && ! empty($paramname) && ! isset($_GET[$paramname]) && ! isset($_POST[$paramname])) - elseif (! empty($paramname) && ! isset($_GET[$paramname]) && ! isset($_POST[$paramname])) + elseif (!empty($paramname) && !isset($_GET[$paramname]) && !isset($_POST[$paramname])) { - if (! empty($user->default_values)) // $user->default_values defined from menu 'Setup - Default values' + if (!empty($user->default_values)) // $user->default_values defined from menu 'Setup - Default values' { //var_dump($user->default_values[$relativepathstring]); if ($paramname == 'sortfield' || $paramname == 'sortorder') // Sorted on which fields ? ASC or DESC ? { if (isset($user->default_values[$relativepathstring]['sortorder'])) // Even if paramname is sortfield, data are stored into ['sortorder...'] { - foreach($user->default_values[$relativepathstring]['sortorder'] as $defkey => $defval) + foreach ($user->default_values[$relativepathstring]['sortorder'] as $defkey => $defval) { $qualified = 0; if ($defkey != '_noquery_') { - $tmpqueryarraytohave=explode('&', $defkey); - $tmpqueryarraywehave=explode('&', dol_string_nohtmltag($_SERVER['QUERY_STRING'])); - $foundintru=0; - foreach($tmpqueryarraytohave as $tmpquerytohave) + $tmpqueryarraytohave = explode('&', $defkey); + $tmpqueryarraywehave = explode('&', dol_string_nohtmltag($_SERVER['QUERY_STRING'])); + $foundintru = 0; + foreach ($tmpqueryarraytohave as $tmpquerytohave) { - if (! in_array($tmpquerytohave, $tmpqueryarraywehave)) $foundintru=1; + if (!in_array($tmpquerytohave, $tmpqueryarraywehave)) $foundintru = 1; } - if (! $foundintru) $qualified=1; + if (!$foundintru) $qualified = 1; //var_dump($defkey.'-'.$qualified); } else $qualified = 1; if ($qualified) { - $forbidden_chars_to_replace=array(" ","'","/","\\",":","*","?","\"","<",">","|","[","]",";","="); // we accept _, -, . and , - foreach($user->default_values[$relativepathstring]['sortorder'][$defkey] as $key => $val) + $forbidden_chars_to_replace = array(" ", "'", "/", "\\", ":", "*", "?", "\"", "<", ">", "|", "[", "]", ";", "="); // we accept _, -, . and , + foreach ($user->default_values[$relativepathstring]['sortorder'][$defkey] as $key => $val) { - if ($out) $out.=', '; + if ($out) $out .= ', '; if ($paramname == 'sortfield') { - $out.=dol_string_nospecial($key, '', $forbidden_chars_to_replace); + $out .= dol_string_nospecial($key, '', $forbidden_chars_to_replace); } if ($paramname == 'sortorder') { - $out.=dol_string_nospecial($val, '', $forbidden_chars_to_replace); + $out .= dol_string_nospecial($val, '', $forbidden_chars_to_replace); } } //break; // No break for sortfield and sortorder so we can cumulate fields (is it realy usefull ?) @@ -413,19 +413,19 @@ function GETPOST($paramname, $check = 'none', $method = 0, $filter = null, $opti } elseif (isset($user->default_values[$relativepathstring]['filters'])) { - foreach($user->default_values[$relativepathstring]['filters'] as $defkey => $defval) // $defkey is a querystring like 'a=b&c=d', $defval is key of user + foreach ($user->default_values[$relativepathstring]['filters'] as $defkey => $defval) // $defkey is a querystring like 'a=b&c=d', $defval is key of user { $qualified = 0; if ($defkey != '_noquery_') { - $tmpqueryarraytohave=explode('&', $defkey); - $tmpqueryarraywehave=explode('&', dol_string_nohtmltag($_SERVER['QUERY_STRING'])); - $foundintru=0; - foreach($tmpqueryarraytohave as $tmpquerytohave) + $tmpqueryarraytohave = explode('&', $defkey); + $tmpqueryarraywehave = explode('&', dol_string_nohtmltag($_SERVER['QUERY_STRING'])); + $foundintru = 0; + foreach ($tmpqueryarraytohave as $tmpquerytohave) { - if (! in_array($tmpquerytohave, $tmpqueryarraywehave)) $foundintru=1; + if (!in_array($tmpquerytohave, $tmpqueryarraywehave)) $foundintru = 1; } - if (! $foundintru) $qualified=1; + if (!$foundintru) $qualified = 1; //var_dump($defkey.'-'.$qualified); } else $qualified = 1; @@ -437,13 +437,13 @@ function GETPOST($paramname, $check = 'none', $method = 0, $filter = null, $opti // We made a search from quick search menu, do we still use default filter ? if (empty($conf->global->MAIN_DISABLE_DEFAULT_FILTER_FOR_QUICK_SEARCH)) { - $forbidden_chars_to_replace=array(" ","'","/","\\",":","*","?","\"","<",">","|","[","]",";","="); // we accept _, -, . and , + $forbidden_chars_to_replace = array(" ", "'", "/", "\\", ":", "*", "?", "\"", "<", ">", "|", "[", "]", ";", "="); // we accept _, -, . and , $out = dol_string_nospecial($user->default_values[$relativepathstring]['filters'][$defkey][$paramname], '', $forbidden_chars_to_replace); } } else { - $forbidden_chars_to_replace=array(" ","'","/","\\",":","*","?","\"","<",">","|","[","]",";","="); // we accept _, -, . and , + $forbidden_chars_to_replace = array(" ", "'", "/", "\\", ":", "*", "?", "\"", "<", ">", "|", "[", "]", ";", "="); // we accept _, -, . and , $out = dol_string_nospecial($user->default_values[$relativepathstring]['filters'][$defkey][$paramname], '', $forbidden_chars_to_replace); } break; @@ -459,22 +459,22 @@ function GETPOST($paramname, $check = 'none', $method = 0, $filter = null, $opti // Substitution variables for GETPOST (used to get final url with variable parameters or final default value with variable parameters) // Example of variables: __DAY__, __MONTH__, __YEAR__, __MYCOMPANY_COUNTRY_ID__, __USER_ID__, ... // We do this only if var is a GET. If it is a POST, may be we want to post the text with vars as the setup text. - if (! is_array($out) && empty($_POST[$paramname]) && empty($noreplace)) + if (!is_array($out) && empty($_POST[$paramname]) && empty($noreplace)) { - $maxloop=20; $loopnb=0; // Protection against infinite loop + $maxloop = 20; $loopnb = 0; // Protection against infinite loop while (preg_match('/__([A-Z0-9]+_?[A-Z0-9]+)__/i', $out, $reg) && ($loopnb < $maxloop)) // Detect '__ABCDEF__' as key 'ABCDEF' and '__ABC_DEF__' as key 'ABC_DEF'. Detection is also correct when 2 vars are side by side. { $loopnb++; $newout = ''; - if ($reg[1] == 'DAY') { $tmp=dol_getdate(dol_now(), true); $newout = $tmp['mday']; } - elseif ($reg[1] == 'MONTH') { $tmp=dol_getdate(dol_now(), true); $newout = $tmp['mon']; } - elseif ($reg[1] == 'YEAR') { $tmp=dol_getdate(dol_now(), true); $newout = $tmp['year']; } - elseif ($reg[1] == 'PREVIOUS_DAY') { $tmp=dol_getdate(dol_now(), true); $tmp2=dol_get_prev_day($tmp['mday'], $tmp['mon'], $tmp['year']); $newout = $tmp2['day']; } - elseif ($reg[1] == 'PREVIOUS_MONTH') { $tmp=dol_getdate(dol_now(), true); $tmp2=dol_get_prev_month($tmp['mon'], $tmp['year']); $newout = $tmp2['month']; } - elseif ($reg[1] == 'PREVIOUS_YEAR') { $tmp=dol_getdate(dol_now(), true); $newout = ($tmp['year'] - 1); } - elseif ($reg[1] == 'NEXT_DAY') { $tmp=dol_getdate(dol_now(), true); $tmp2=dol_get_next_day($tmp['mday'], $tmp['mon'], $tmp['year']); $newout = $tmp2['day']; } - elseif ($reg[1] == 'NEXT_MONTH') { $tmp=dol_getdate(dol_now(), true); $tmp2=dol_get_next_month($tmp['mon'], $tmp['year']); $newout = $tmp2['month']; } - elseif ($reg[1] == 'NEXT_YEAR') { $tmp=dol_getdate(dol_now(), true); $newout = ($tmp['year'] + 1); } + if ($reg[1] == 'DAY') { $tmp = dol_getdate(dol_now(), true); $newout = $tmp['mday']; } + elseif ($reg[1] == 'MONTH') { $tmp = dol_getdate(dol_now(), true); $newout = $tmp['mon']; } + elseif ($reg[1] == 'YEAR') { $tmp = dol_getdate(dol_now(), true); $newout = $tmp['year']; } + elseif ($reg[1] == 'PREVIOUS_DAY') { $tmp = dol_getdate(dol_now(), true); $tmp2 = dol_get_prev_day($tmp['mday'], $tmp['mon'], $tmp['year']); $newout = $tmp2['day']; } + elseif ($reg[1] == 'PREVIOUS_MONTH') { $tmp = dol_getdate(dol_now(), true); $tmp2 = dol_get_prev_month($tmp['mon'], $tmp['year']); $newout = $tmp2['month']; } + elseif ($reg[1] == 'PREVIOUS_YEAR') { $tmp = dol_getdate(dol_now(), true); $newout = ($tmp['year'] - 1); } + elseif ($reg[1] == 'NEXT_DAY') { $tmp = dol_getdate(dol_now(), true); $tmp2 = dol_get_next_day($tmp['mday'], $tmp['mon'], $tmp['year']); $newout = $tmp2['day']; } + elseif ($reg[1] == 'NEXT_MONTH') { $tmp = dol_getdate(dol_now(), true); $tmp2 = dol_get_next_month($tmp['mon'], $tmp['year']); $newout = $tmp2['month']; } + elseif ($reg[1] == 'NEXT_YEAR') { $tmp = dol_getdate(dol_now(), true); $newout = ($tmp['year'] + 1); } elseif ($reg[1] == 'MYCOMPANY_COUNTRY_ID' || $reg[1] == 'MYCOUNTRY_ID' || $reg[1] == 'MYCOUNTRYID') { $newout = $mysoc->country_id; @@ -491,7 +491,7 @@ function GETPOST($paramname, $check = 'none', $method = 0, $filter = null, $opti { $newout = $conf->entity; } - else $newout = ''; // Key not found, we replace with empty string + else $newout = ''; // Key not found, we replace with empty string //var_dump('__'.$reg[1].'__ -> '.$newout); $out = preg_replace('/__'.preg_quote($reg[1], '/').'__/', $newout, $out); } @@ -503,68 +503,68 @@ function GETPOST($paramname, $check = 'none', $method = 0, $filter = null, $opti case 'none': break; case 'int': // Check param is a numeric value (integer but also float or hexadecimal) - if (! is_numeric($out)) { $out=''; } + if (!is_numeric($out)) { $out = ''; } break; case 'intcomma': - if (preg_match('/[^0-9,-]+/i', $out)) $out=''; + if (preg_match('/[^0-9,-]+/i', $out)) $out = ''; break; case 'alpha': - if (! is_array($out)) + if (!is_array($out)) { - $out=trim($out); + $out = trim($out); // '"' is dangerous because param in url can close the href= or src= and add javascript functions. // '../' is dangerous because it allows dir transversals - if (preg_match('/"/', $out)) $out=''; - elseif (preg_match('/\.\.\//', $out)) $out=''; + if (preg_match('/"/', $out)) $out = ''; + elseif (preg_match('/\.\.\//', $out)) $out = ''; } break; case 'san_alpha': - $out=filter_var($out, FILTER_SANITIZE_STRING); + $out = filter_var($out, FILTER_SANITIZE_STRING); break; case 'aZ': - if (! is_array($out)) + if (!is_array($out)) { - $out=trim($out); - if (preg_match('/[^a-z]+/i', $out)) $out=''; + $out = trim($out); + if (preg_match('/[^a-z]+/i', $out)) $out = ''; } break; case 'aZ09': - if (! is_array($out)) + if (!is_array($out)) { - $out=trim($out); - if (preg_match('/[^a-z0-9_\-\.]+/i', $out)) $out=''; + $out = trim($out); + if (preg_match('/[^a-z0-9_\-\.]+/i', $out)) $out = ''; } break; case 'aZ09comma': // great to sanitize sortfield or sortorder params that can be t.abc,t.def_gh - if (! is_array($out)) + if (!is_array($out)) { - $out=trim($out); - if (preg_match('/[^a-z0-9_\-\.,]+/i', $out)) $out=''; + $out = trim($out); + if (preg_match('/[^a-z0-9_\-\.,]+/i', $out)) $out = ''; } break; case 'array': - if (! is_array($out) || empty($out)) $out=array(); + if (!is_array($out) || empty($out)) $out = array(); break; case 'nohtml': // Recommended for most scalar parameters - $out=dol_string_nohtmltag($out, 0); + $out = dol_string_nohtmltag($out, 0); break; case 'alphanohtml': // Recommended for search parameters - if (! is_array($out)) + if (!is_array($out)) { - $out=trim($out); + $out = trim($out); // '"' is dangerous because param in url can close the href= or src= and add javascript functions. // '../' is dangerous because it allows dir transversals - if (preg_match('/"/', $out)) $out=''; - elseif (preg_match('/\.\.\//', $out)) $out=''; - $out=dol_string_nohtmltag($out); + if (preg_match('/"/', $out)) $out = ''; + elseif (preg_match('/\.\.\//', $out)) $out = ''; + $out = dol_string_nohtmltag($out); } break; case 'restricthtml': // Recommended for most html textarea - $out=dol_string_onlythesehtmltags($out, 0); + $out = dol_string_onlythesehtmltags($out, 0); break; case 'custom': if (empty($filter)) return 'BadFourthParameterForGETPOST'; - $out=filter_var($out, $filter, $options); + $out = filter_var($out, $filter, $options); break; } @@ -572,7 +572,7 @@ function GETPOST($paramname, $check = 'none', $method = 0, $filter = null, $opti // Save data into session if key start with 'search_' or is 'smonth', 'syear', 'month', 'year' if (empty($method) || $method == 3 || $method == 4) { - if (preg_match('/^search_/', $paramname) || in_array($paramname, array('sortorder','sortfield'))) + if (preg_match('/^search_/', $paramname) || in_array($paramname, array('sortorder', 'sortfield'))) { //var_dump($paramname.' - '.$out.' '.$user->default_values[$relativepathstring]['filters'][$paramname]); @@ -582,7 +582,7 @@ function GETPOST($paramname, $check = 'none', $method = 0, $filter = null, $opti if ($out != '') // $out = '0' or 'abc', it is a search criteria to keep { - $user->lastsearch_values_tmp[$relativepathstring][$paramname]=$out; + $user->lastsearch_values_tmp[$relativepathstring][$paramname] = $out; } } } @@ -591,7 +591,7 @@ function GETPOST($paramname, $check = 'none', $method = 0, $filter = null, $opti } -if (! function_exists('dol_getprefix')) +if (!function_exists('dol_getprefix')) { /** * Return a prefix to use for this Dolibarr instance, for session/cookie names or email id. @@ -608,21 +608,21 @@ if (! function_exists('dol_getprefix')) // If prefix is for email if ($mode == 'email') { - if (! empty($conf->global->MAIL_PREFIX_FOR_EMAIL_ID)) // If MAIL_PREFIX_FOR_EMAIL_ID is set (a value initialized with a random value is recommended) + if (!empty($conf->global->MAIL_PREFIX_FOR_EMAIL_ID)) // If MAIL_PREFIX_FOR_EMAIL_ID is set (a value initialized with a random value is recommended) { if ($conf->global->MAIL_PREFIX_FOR_EMAIL_ID != 'SERVER_NAME') return $conf->global->MAIL_PREFIX_FOR_EMAIL_ID; elseif (isset($_SERVER["SERVER_NAME"])) return $_SERVER["SERVER_NAME"]; } // The recommended value (may be not defined for old versions) - if (! empty($conf->file->instance_unique_id)) return $conf->file->instance_unique_id; + if (!empty($conf->file->instance_unique_id)) return $conf->file->instance_unique_id; // For backward compatibility return dol_hash(DOL_DOCUMENT_ROOT.DOL_URL_ROOT, '3'); } // The recommended value (may be not defined for old versions) - if (! empty($conf->file->instance_unique_id)) return $conf->file->instance_unique_id; + if (!empty($conf->file->instance_unique_id)) return $conf->file->instance_unique_id; // For backward compatibility if (isset($_SERVER["SERVER_NAME"]) && isset($_SERVER["DOCUMENT_ROOT"])) @@ -646,7 +646,7 @@ if (! function_exists('dol_getprefix')) */ function dol_include_once($relpath, $classname = '') { - global $conf,$langs,$user,$mysoc; // Do not remove this. They must be defined for files we include. Other globals var must be retreived with $GLOBALS['var'] + global $conf, $langs, $user, $mysoc; // Do not remove this. They must be defined for files we include. Other globals var must be retreived with $GLOBALS['var'] $fullpath = dol_buildpath($relpath); @@ -655,7 +655,7 @@ function dol_include_once($relpath, $classname = '') return false; } - if (! empty($classname) && ! class_exists($classname)) { + if (!empty($classname) && !class_exists($classname)) { return include $fullpath; } else { return include_once $fullpath; @@ -677,11 +677,11 @@ function dol_buildpath($path, $type = 0, $returnemptyifnotfound = 0) { global $conf; - $path=preg_replace('/^\//', '', $path); + $path = preg_replace('/^\//', '', $path); if (empty($type)) // For a filesystem path { - $res = DOL_DOCUMENT_ROOT.'/'.$path; // Standard default path + $res = DOL_DOCUMENT_ROOT.'/'.$path; // Standard default path if (is_array($conf->file->dol_document_root)) { foreach ($conf->file->dol_document_root as $key => $dirroot) // ex: array("main"=>"/home/main/htdocs", "alt0"=>"/home/dirmod/htdocs", ...) @@ -692,14 +692,14 @@ function dol_buildpath($path, $type = 0, $returnemptyifnotfound = 0) } if (file_exists($dirroot.'/'.$path)) { - $res=$dirroot.'/'.$path; + $res = $dirroot.'/'.$path; return $res; } } } if ($returnemptyifnotfound) // Not found into alternate dir { - if ($returnemptyifnotfound == 1 || ! file_exists($res)) return ''; + if ($returnemptyifnotfound == 1 || !file_exists($res)) return ''; } } else // For an url path @@ -708,9 +708,9 @@ function dol_buildpath($path, $type = 0, $returnemptyifnotfound = 0) // Note that trying to know if a file on disk exist by forging path on disk from url // works only for some web server and some setup. This is bugged when // using proxy, rewriting, virtual path, etc... - $res=''; - if ($type == 1) $res = DOL_URL_ROOT.'/'.$path; // Standard value - if ($type == 2) $res = DOL_MAIN_URL_ROOT.'/'.$path; // Standard value + $res = ''; + if ($type == 1) $res = DOL_URL_ROOT.'/'.$path; // Standard value + if ($type == 2) $res = DOL_MAIN_URL_ROOT.'/'.$path; // Standard value if ($type == 3) $res = DOL_URL_ROOT.'/'.$path; foreach ($conf->file->dol_document_root as $key => $dirroot) // ex: array(["main"]=>"/home/main/htdocs", ["alt0"]=>"/home/dirmod/htdocs", ...) @@ -722,38 +722,38 @@ function dol_buildpath($path, $type = 0, $returnemptyifnotfound = 0) global $dolibarr_main_url_root; // Define $urlwithroot - $urlwithouturlroot=preg_replace('/'.preg_quote(DOL_URL_ROOT, '/').'$/i', '', trim($dolibarr_main_url_root)); - $urlwithroot=$urlwithouturlroot.DOL_URL_ROOT; // This is to use external domain name found into config file + $urlwithouturlroot = preg_replace('/'.preg_quote(DOL_URL_ROOT, '/').'$/i', '', trim($dolibarr_main_url_root)); + $urlwithroot = $urlwithouturlroot.DOL_URL_ROOT; // This is to use external domain name found into config file //$urlwithroot=DOL_MAIN_URL_ROOT; // This is to use same domain name than current - $res=(preg_match('/^http/i', $conf->file->dol_url_root[$key])?'':$urlwithroot).'/'.$path; // Test on start with http is for old conf syntax + $res = (preg_match('/^http/i', $conf->file->dol_url_root[$key]) ? '' : $urlwithroot).'/'.$path; // Test on start with http is for old conf syntax } continue; } - preg_match('/^([^\?]+(\.css\.php|\.css|\.js\.php|\.js|\.png|\.jpg|\.php)?)/i', $path, $regs); // Take part before '?' - if (! empty($regs[1])) + preg_match('/^([^\?]+(\.css\.php|\.css|\.js\.php|\.js|\.png|\.jpg|\.php)?)/i', $path, $regs); // Take part before '?' + if (!empty($regs[1])) { //print $key.'-'.$dirroot.'/'.$path.'-'.$conf->file->dol_url_root[$type].'
    '."\n"; if (file_exists($dirroot.'/'.$regs[1])) { if ($type == 1) { - $res=(preg_match('/^http/i', $conf->file->dol_url_root[$key])?'':DOL_URL_ROOT).$conf->file->dol_url_root[$key].'/'.$path; + $res = (preg_match('/^http/i', $conf->file->dol_url_root[$key]) ? '' : DOL_URL_ROOT).$conf->file->dol_url_root[$key].'/'.$path; } if ($type == 2) { - $res=(preg_match('/^http/i', $conf->file->dol_url_root[$key])?'':DOL_MAIN_URL_ROOT).$conf->file->dol_url_root[$key].'/'.$path; + $res = (preg_match('/^http/i', $conf->file->dol_url_root[$key]) ? '' : DOL_MAIN_URL_ROOT).$conf->file->dol_url_root[$key].'/'.$path; } if ($type == 3) { global $dolibarr_main_url_root; // Define $urlwithroot - $urlwithouturlroot=preg_replace('/'.preg_quote(DOL_URL_ROOT, '/').'$/i', '', trim($dolibarr_main_url_root)); - $urlwithroot=$urlwithouturlroot.DOL_URL_ROOT; // This is to use external domain name found into config file + $urlwithouturlroot = preg_replace('/'.preg_quote(DOL_URL_ROOT, '/').'$/i', '', trim($dolibarr_main_url_root)); + $urlwithroot = $urlwithouturlroot.DOL_URL_ROOT; // This is to use external domain name found into config file //$urlwithroot=DOL_MAIN_URL_ROOT; // This is to use same domain name than current - $res=(preg_match('/^http/i', $conf->file->dol_url_root[$key])?'':$urlwithroot).$conf->file->dol_url_root[$key].'/'.$path; // Test on start with http is for old conf syntax + $res = (preg_match('/^http/i', $conf->file->dol_url_root[$key]) ? '' : $urlwithroot).$conf->file->dol_url_root[$key].'/'.$path; // Test on start with http is for old conf syntax } break; } @@ -778,11 +778,11 @@ function dol_clone($object, $native = 0) { if (empty($native)) { - $myclone=unserialize(serialize($object)); + $myclone = unserialize(serialize($object)); } else { - $myclone = clone $object; // PHP clone is a shallow copy only, not a real clone, so properties of references will keep references (refer to the same target/variable) + $myclone = clone $object; // PHP clone is a shallow copy only, not a real clone, so properties of references will keep references (refer to the same target/variable) } return $myclone; @@ -822,7 +822,7 @@ function dol_sanitizeFileName($str, $newstr = '_', $unaccent = 1) // Char '>' '<' '|' '$' and ';' are special chars for shells. // Char '/' and '\' are file delimiters. $filesystem_forbidden_chars = array('<', '>', '/', '\\', '?', '*', '|', '"', ':', '°', '$', ';'); - return dol_string_nospecial($unaccent?dol_string_unaccent($str):$str, $newstr, $filesystem_forbidden_chars); + return dol_string_nospecial($unaccent ?dol_string_unaccent($str) : $str, $newstr, $filesystem_forbidden_chars); } /** @@ -837,8 +837,8 @@ function dol_sanitizeFileName($str, $newstr = '_', $unaccent = 1) */ function dol_sanitizePathName($str, $newstr = '_', $unaccent = 1) { - $filesystem_forbidden_chars = array('<','>','?','*','|','"','°'); - return dol_string_nospecial($unaccent?dol_string_unaccent($str):$str, $newstr, $filesystem_forbidden_chars); + $filesystem_forbidden_chars = array('<', '>', '?', '*', '|', '"', '°'); + return dol_string_nospecial($unaccent ?dol_string_unaccent($str) : $str, $newstr, $filesystem_forbidden_chars); } /** @@ -856,21 +856,21 @@ function dol_string_unaccent($str) // See http://www.utf8-chartable.de/ $string = rawurlencode($str); $replacements = array( - '%C3%80' => 'A','%C3%81' => 'A','%C3%82' => 'A','%C3%83' => 'A','%C3%84' => 'A','%C3%85' => 'A', - '%C3%88' => 'E','%C3%89' => 'E','%C3%8A' => 'E','%C3%8B' => 'E', - '%C3%8C' => 'I','%C3%8D' => 'I','%C3%8E' => 'I','%C3%8F' => 'I', - '%C3%92' => 'O','%C3%93' => 'O','%C3%94' => 'O','%C3%95' => 'O','%C3%96' => 'O', - '%C3%99' => 'U','%C3%9A' => 'U','%C3%9B' => 'U','%C3%9C' => 'U', - '%C3%A0' => 'a','%C3%A1' => 'a','%C3%A2' => 'a','%C3%A3' => 'a','%C3%A4' => 'a','%C3%A5' => 'a', + '%C3%80' => 'A', '%C3%81' => 'A', '%C3%82' => 'A', '%C3%83' => 'A', '%C3%84' => 'A', '%C3%85' => 'A', + '%C3%88' => 'E', '%C3%89' => 'E', '%C3%8A' => 'E', '%C3%8B' => 'E', + '%C3%8C' => 'I', '%C3%8D' => 'I', '%C3%8E' => 'I', '%C3%8F' => 'I', + '%C3%92' => 'O', '%C3%93' => 'O', '%C3%94' => 'O', '%C3%95' => 'O', '%C3%96' => 'O', + '%C3%99' => 'U', '%C3%9A' => 'U', '%C3%9B' => 'U', '%C3%9C' => 'U', + '%C3%A0' => 'a', '%C3%A1' => 'a', '%C3%A2' => 'a', '%C3%A3' => 'a', '%C3%A4' => 'a', '%C3%A5' => 'a', '%C3%A7' => 'c', - '%C3%A8' => 'e','%C3%A9' => 'e','%C3%AA' => 'e','%C3%AB' => 'e', - '%C3%AC' => 'i','%C3%AD' => 'i','%C3%AE' => 'i','%C3%AF' => 'i', + '%C3%A8' => 'e', '%C3%A9' => 'e', '%C3%AA' => 'e', '%C3%AB' => 'e', + '%C3%AC' => 'i', '%C3%AD' => 'i', '%C3%AE' => 'i', '%C3%AF' => 'i', '%C3%B1' => 'n', - '%C3%B2' => 'o','%C3%B3' => 'o','%C3%B4' => 'o','%C3%B5' => 'o','%C3%B6' => 'o', - '%C3%B9' => 'u','%C3%BA' => 'u','%C3%BB' => 'u','%C3%BC' => 'u', + '%C3%B2' => 'o', '%C3%B3' => 'o', '%C3%B4' => 'o', '%C3%B5' => 'o', '%C3%B6' => 'o', + '%C3%B9' => 'u', '%C3%BA' => 'u', '%C3%BB' => 'u', '%C3%BC' => 'u', '%C3%BF' => 'y' ); - $string=strtr($string, $replacements); + $string = strtr($string, $replacements); return rawurldecode($string); } else @@ -909,9 +909,9 @@ function dol_string_unaccent($str) */ function dol_string_nospecial($str, $newstr = '_', $badcharstoreplace = '') { - $forbidden_chars_to_replace=array(" ", "'", "/", "\\", ":", "*", "?", "\"", "<", ">", "|", "[", "]", ",", ";", "=", '°'); // more complete than dol_sanitizeFileName - $forbidden_chars_to_remove=array(); - if (is_array($badcharstoreplace)) $forbidden_chars_to_replace=$badcharstoreplace; + $forbidden_chars_to_replace = array(" ", "'", "/", "\\", ":", "*", "?", "\"", "<", ">", "|", "[", "]", ",", ";", "=", '°'); // more complete than dol_sanitizeFileName + $forbidden_chars_to_remove = array(); + if (is_array($badcharstoreplace)) $forbidden_chars_to_replace = $badcharstoreplace; //$forbidden_chars_to_remove=array("(",")"); return str_replace($forbidden_chars_to_replace, $newstr, str_replace($forbidden_chars_to_remove, "", $str)); @@ -929,13 +929,13 @@ function dol_string_nospecial($str, $newstr = '_', $badcharstoreplace = '') function dol_escape_js($stringtoescape, $mode = 0, $noescapebackslashn = 0) { // escape quotes and backslashes, newlines, etc. - $substitjs=array("'"=>"\\'","\r"=>'\\r'); + $substitjs = array("'"=>"\\'", "\r"=>'\\r'); //$substitjs['"=>'',''=>'')); - if (! $keepn) $tmp=strtr($tmp, array("\r"=>'\\r',"\n"=>'\\n')); - return htmlentities($tmp, ENT_COMPAT, 'UTF-8'); // TODO Use htmlspecialchars instead, that make only required change for html tags + $tmp = html_entity_decode($stringtoescape, ENT_COMPAT, 'UTF-8'); // TODO Use htmlspecialchars_decode instead, that make only required change for html tags + if (!$keepb) $tmp = strtr($tmp, array(""=>'', ''=>'')); + if (!$keepn) $tmp = strtr($tmp, array("\r"=>'\\r', "\n"=>'\\n')); + return htmlentities($tmp, ENT_COMPAT, 'UTF-8'); // TODO Use htmlspecialchars instead, that make only required change for html tags } @@ -1022,28 +1022,28 @@ function dol_syslog($message, $level = LOG_INFO, $ident = 0, $suffixinfilename = } } - if (! empty($message)) + if (!empty($message)) { // Test log level $logLevels = array(LOG_EMERG=>'EMERG', LOG_ALERT=>'ALERT', LOG_CRIT=>'CRITICAL', LOG_ERR=>'ERR', LOG_WARNING=>'WARN', LOG_NOTICE=>'NOTICE', LOG_INFO=>'INFO', LOG_DEBUG=>'DEBUG'); - if (! array_key_exists($level, $logLevels)) + if (!array_key_exists($level, $logLevels)) { throw new Exception('Incorrect log level'); } if ($level > $conf->global->SYSLOG_LEVEL) return; - $message = preg_replace('/password=\'[^\']*\'/', 'password=\'hidden\'', $message); // protection to avoid to have value of password in log + $message = preg_replace('/password=\'[^\']*\'/', 'password=\'hidden\'', $message); // protection to avoid to have value of password in log // If adding log inside HTML page is required - if ((! empty($_REQUEST['logtohtml']) && ! empty($conf->global->MAIN_ENABLE_LOG_TO_HTML)) - || (! empty($user->rights->debugbar->read) && is_object($debugbar))) + if ((!empty($_REQUEST['logtohtml']) && !empty($conf->global->MAIN_ENABLE_LOG_TO_HTML)) + || (!empty($user->rights->debugbar->read) && is_object($debugbar))) { $conf->logbuffer[] = dol_print_date(time(), "%Y-%m-%d %H:%M:%S")." ".$logLevels[$level]." ".$message; } //TODO: Remove this. MAIN_ENABLE_LOG_INLINE_HTML should be deprecated and use a log handler dedicated to HTML output // If html log tag enabled and url parameter log defined, we show output log on HTML comments - if (! empty($conf->global->MAIN_ENABLE_LOG_INLINE_HTML) && ! empty($_GET["log"])) + if (!empty($conf->global->MAIN_ENABLE_LOG_INLINE_HTML) && !empty($_GET["log"])) { print "\n\n'; - if ((! empty($title) && $showtitle) || $morehtmlright || ! empty($links)) { - $out.= '
    '."\n"; + if ((!empty($title) && $showtitle) || $morehtmlright || !empty($links)) { + $out .= '
    '."\n"; } // Show right part - if ($morehtmlright) $out.='
    '.$morehtmlright.'
    '; // Output right area first so when space is missing, text is in front of tabs and not under. + if ($morehtmlright) $out .= '
    '.$morehtmlright.'
    '; // Output right area first so when space is missing, text is in front of tabs and not under. // Show title - if (! empty($title) && $showtitle) + if (!empty($title) && $showtitle) { - $limittitle=30; - $out.=''; - if ($picto) $out.=img_picto($title, ($pictoisfullpath?'':'object_').$picto, '', $pictoisfullpath).' '; - $out.=''.dol_trunc($title, $limittitle).''; - $out.=''; + $limittitle = 30; + $out .= ''; + if ($picto) $out .= img_picto($title, ($pictoisfullpath ? '' : 'object_').$picto, '', $pictoisfullpath).' '; + $out .= ''.dol_trunc($title, $limittitle).''; + $out .= ''; } // Show tabs // Define max of key (max may be higher than sizeof because of hole due to module disabling some tabs). - $maxkey=-1; - if (is_array($links) && ! empty($links)) + $maxkey = -1; + if (is_array($links) && !empty($links)) { - $keys=array_keys($links); - if (count($keys)) $maxkey=max($keys); + $keys = array_keys($links); + if (count($keys)) $maxkey = max($keys); } - if (! empty($conf->dol_optimize_smallscreen)) $conf->global->MAIN_MAXTABS_IN_CARD=2; + if (!empty($conf->dol_optimize_smallscreen)) $conf->global->MAIN_MAXTABS_IN_CARD = 2; // Show tabs // if =0 we don't use the feature - $limittoshow=(empty($conf->global->MAIN_MAXTABS_IN_CARD)?99:$conf->global->MAIN_MAXTABS_IN_CARD); - $displaytab=0; - $nbintab=0; - $popuptab=0; - $outmore=''; - for ($i = 0 ; $i <= $maxkey ; $i++) + $limittoshow = (empty($conf->global->MAIN_MAXTABS_IN_CARD) ? 99 : $conf->global->MAIN_MAXTABS_IN_CARD); + $displaytab = 0; + $nbintab = 0; + $popuptab = 0; + $outmore = ''; + for ($i = 0; $i <= $maxkey; $i++) { - if ((is_numeric($active) && $i == $active) || (! empty($links[$i][2]) && ! is_numeric($active) && $active == $links[$i][2])) { + if ((is_numeric($active) && $i == $active) || (!empty($links[$i][2]) && !is_numeric($active) && $active == $links[$i][2])) { // If active tab is already present if ($i >= $limittoshow) $limittoshow--; } } - for ($i = 0 ; $i <= $maxkey ; $i++) + for ($i = 0; $i <= $maxkey; $i++) { - if ((is_numeric($active) && $i == $active) || (! empty($links[$i][2]) && ! is_numeric($active) && $active == $links[$i][2])) { - $isactive=true; + if ((is_numeric($active) && $i == $active) || (!empty($links[$i][2]) && !is_numeric($active) && $active == $links[$i][2])) { + $isactive = true; } else { - $isactive=false; + $isactive = false; } if ($i < $limittoshow || $isactive) { - $out.='
    '; + $out .= '
    '; if (isset($links[$i][2]) && $links[$i][2] == 'image') { if (!empty($links[$i][0])) { - $out.=''.$links[$i][1].''."\n"; + $out .= ''.$links[$i][1].''."\n"; } else { - $out.=''.$links[$i][1].''."\n"; + $out .= ''.$links[$i][1].''."\n"; } } - elseif (! empty($links[$i][1])) + elseif (!empty($links[$i][1])) { //print "x $i $active ".$links[$i][2]." z"; if ($isactive) { - $out.=''; - $out.=$links[$i][1]; - $out.=''."\n"; + $out .= ''; + $out .= $links[$i][1]; + $out .= ''."\n"; } else { - $out.=''; - $out.=$links[$i][1]; - $out.=''."\n"; + $out .= ''; + $out .= $links[$i][1]; + $out .= ''."\n"; } } - $out.='
    '; + $out .= '
    '; } else { // The popup with the other tabs - if (! $popuptab) + if (!$popuptab) { - $popuptab=1; - $outmore.='
    '; // The css used to hide/show popup + $popuptab = 1; + $outmore .= '
    '; // The css used to hide/show popup } - $outmore.='
    '; + $outmore .= '
    '; if (isset($links[$i][2]) && $links[$i][2] == 'image') { if (!empty($links[$i][0])) - $outmore.=''.$links[$i][1].''."\n"; + $outmore .= ''.$links[$i][1].''."\n"; else - $outmore.=''.$links[$i][1].''."\n"; + $outmore .= ''.$links[$i][1].''."\n"; } - elseif (! empty($links[$i][1])) + elseif (!empty($links[$i][1])) { - $outmore.=''; - $outmore.=preg_replace('/([a-z])\/([a-z])/i', '\\1 / \\2', $links[$i][1]); // Replace x/y with x / y to allow wrap on long composed texts. - $outmore.=''."\n"; + $outmore .= ''; + $outmore .= preg_replace('/([a-z])\/([a-z])/i', '\\1 / \\2', $links[$i][1]); // Replace x/y with x / y to allow wrap on long composed texts. + $outmore .= ''."\n"; } - $outmore.='
    '; + $outmore .= '
    '; $nbintab++; } - $displaytab=$i; + $displaytab = $i; } - if ($popuptab) $outmore.='
    '; + if ($popuptab) $outmore .= '
    '; if ($popuptab) // If there is some tabs not shown { - $left=($langs->trans("DIRECTION") == 'rtl'?'right':'left'); - $right=($langs->trans("DIRECTION") == 'rtl'?'left':'right'); + $left = ($langs->trans("DIRECTION") == 'rtl' ? 'right' : 'left'); + $right = ($langs->trans("DIRECTION") == 'rtl' ? 'left' : 'right'); - $tabsname=str_replace("@", "", $picto); - $out.='
    '; - $out.=''.$langs->trans("More").'... ('.$nbintab.')'; - $out.='
    '; - $out.=$outmore; - $out.='
    '; - $out.='
    '; - $out.="
    \n"; + $tabsname = str_replace("@", "", $picto); + $out .= '
    '; + $out .= ''.$langs->trans("More").'... ('.$nbintab.')'; + $out .= '
    '; + $out .= $outmore; + $out .= '
    '; + $out .= '
    '; + $out .= "
    \n"; - $out.=""; + $out .= ""; } - if ((! empty($title) && $showtitle) || $morehtmlright || ! empty($links)) { - $out.="
    \n"; + if ((!empty($title) && $showtitle) || $morehtmlright || !empty($links)) { + $out .= "
    \n"; } - if (! $notab || $notab == -1 || $notab == -2) $out.="\n".'
    '."\n"; + if (!$notab || $notab == -1 || $notab == -2) $out .= "\n".'
    '."\n"; - $parameters=array('tabname' => $active, 'out' => $out); - $reshook=$hookmanager->executeHooks('printTabsHead', $parameters); // This hook usage is called just before output the head of tabs. Take also a look at "completeTabsHead" + $parameters = array('tabname' => $active, 'out' => $out); + $reshook = $hookmanager->executeHooks('printTabsHead', $parameters); // This hook usage is called just before output the head of tabs. Take also a look at "completeTabsHead" if ($reshook > 0) { $out = $hookmanager->resPrint; @@ -1298,7 +1298,7 @@ function dol_fiche_end($notab = 0) */ function dol_get_fiche_end($notab = 0) { - if (! $notab || $notab == -1) return "\n
    \n"; + if (!$notab || $notab == -1) return "\n
    \n"; else return ''; } @@ -1327,79 +1327,79 @@ function dol_banner_tab($object, $paramid, $morehtml = '', $shownav = 1, $fieldi $error = 0; - $maxvisiblephotos=1; - $showimage=1; - $entity=(empty($object->entity)?$conf->entity:$object->entity); - $showbarcode=empty($conf->barcode->enabled)?0:($object->barcode?1:0); - if (! empty($conf->global->MAIN_USE_ADVANCED_PERMS) && empty($user->rights->barcode->lire_advance)) $showbarcode=0; - $modulepart='unknown'; + $maxvisiblephotos = 1; + $showimage = 1; + $entity = (empty($object->entity) ? $conf->entity : $object->entity); + $showbarcode = empty($conf->barcode->enabled) ? 0 : ($object->barcode ? 1 : 0); + if (!empty($conf->global->MAIN_USE_ADVANCED_PERMS) && empty($user->rights->barcode->lire_advance)) $showbarcode = 0; + $modulepart = 'unknown'; - if ($object->element == 'societe') $modulepart='societe'; - if ($object->element == 'contact') $modulepart='contact'; - if ($object->element == 'member') $modulepart='memberphoto'; - if ($object->element == 'user') $modulepart='userphoto'; - if ($object->element == 'product') $modulepart='product'; - if ($object->element == 'ticket') $modulepart='ticket'; + if ($object->element == 'societe') $modulepart = 'societe'; + if ($object->element == 'contact') $modulepart = 'contact'; + if ($object->element == 'member') $modulepart = 'memberphoto'; + if ($object->element == 'user') $modulepart = 'userphoto'; + if ($object->element == 'product') $modulepart = 'product'; + if ($object->element == 'ticket') $modulepart = 'ticket'; if (class_exists("Imagick")) { - if ($object->element == 'propal') $modulepart='propal'; - if ($object->element == 'commande') $modulepart='commande'; - if ($object->element == 'facture') $modulepart='facture'; - if ($object->element == 'fichinter') $modulepart='ficheinter'; - if ($object->element == 'contrat') $modulepart='contract'; - if ($object->element == 'supplier_proposal') $modulepart='supplier_proposal'; - if ($object->element == 'order_supplier') $modulepart='supplier_order'; - if ($object->element == 'invoice_supplier') $modulepart='supplier_invoice'; - if ($object->element == 'expensereport') $modulepart='expensereport'; + if ($object->element == 'propal') $modulepart = 'propal'; + if ($object->element == 'commande') $modulepart = 'commande'; + if ($object->element == 'facture') $modulepart = 'facture'; + if ($object->element == 'fichinter') $modulepart = 'ficheinter'; + if ($object->element == 'contrat') $modulepart = 'contract'; + if ($object->element == 'supplier_proposal') $modulepart = 'supplier_proposal'; + if ($object->element == 'order_supplier') $modulepart = 'supplier_order'; + if ($object->element == 'invoice_supplier') $modulepart = 'supplier_invoice'; + if ($object->element == 'expensereport') $modulepart = 'expensereport'; } if ($object->element == 'product') { - $width=80; $cssclass='photoref'; - $showimage=$object->is_photo_available($conf->product->multidir_output[$entity]); - $maxvisiblephotos=(isset($conf->global->PRODUCT_MAX_VISIBLE_PHOTO)?$conf->global->PRODUCT_MAX_VISIBLE_PHOTO:5); - if ($conf->browser->layout == 'phone') $maxvisiblephotos=1; - if ($showimage) $morehtmlleft.='
    '.$object->show_photos('product', $conf->product->multidir_output[$entity], 'small', $maxvisiblephotos, 0, 0, 0, $width, 0).'
    '; + $width = 80; $cssclass = 'photoref'; + $showimage = $object->is_photo_available($conf->product->multidir_output[$entity]); + $maxvisiblephotos = (isset($conf->global->PRODUCT_MAX_VISIBLE_PHOTO) ? $conf->global->PRODUCT_MAX_VISIBLE_PHOTO : 5); + if ($conf->browser->layout == 'phone') $maxvisiblephotos = 1; + if ($showimage) $morehtmlleft .= '
    '.$object->show_photos('product', $conf->product->multidir_output[$entity], 'small', $maxvisiblephotos, 0, 0, 0, $width, 0).'
    '; else { if (!empty($conf->global->PRODUCT_NODISPLAYIFNOPHOTO)) { - $nophoto=''; - $morehtmlleft.='
    '; + $nophoto = ''; + $morehtmlleft .= '
    '; } else { // Show no photo link - $nophoto='/public/theme/common/nophoto.png'; - $morehtmlleft.='
    No photo
    '; + $nophoto = '/public/theme/common/nophoto.png'; + $morehtmlleft .= '
    No photo
    '; } } } elseif ($object->element == 'ticket') { - $width=80; $cssclass='photoref'; - $showimage=$object->is_photo_available($conf->ticket->multidir_output[$entity].'/'.$object->ref); - $maxvisiblephotos=(isset($conf->global->TICKET_MAX_VISIBLE_PHOTO)?$conf->global->TICKET_MAX_VISIBLE_PHOTO:2); - if ($conf->browser->layout == 'phone') $maxvisiblephotos=1; + $width = 80; $cssclass = 'photoref'; + $showimage = $object->is_photo_available($conf->ticket->multidir_output[$entity].'/'.$object->ref); + $maxvisiblephotos = (isset($conf->global->TICKET_MAX_VISIBLE_PHOTO) ? $conf->global->TICKET_MAX_VISIBLE_PHOTO : 2); + if ($conf->browser->layout == 'phone') $maxvisiblephotos = 1; if ($showimage) { $showphoto = $object->show_photos('ticket', $conf->ticket->multidir_output[$entity], 'small', $maxvisiblephotos, 0, 0, 0, $width, 0); if ($object->nbphoto > 0) { - $morehtmlleft.='
    '.$showphoto.'
    '; + $morehtmlleft .= '
    '.$showphoto.'
    '; } else { $showimage = 0; } } - if (! $showimage) + if (!$showimage) { if (!empty($conf->global->TICKET_NODISPLAYIFNOPHOTO)) { - $nophoto=''; - $morehtmlleft.='
    '; + $nophoto = ''; + $morehtmlleft .= '
    '; } else { // Show no photo link - $nophoto='/public/theme/common/nophoto.png'; - $morehtmlleft.='
    No photo
    '; + $nophoto = '/public/theme/common/nophoto.png'; + $morehtmlleft .= '
    No photo
    '; } } } @@ -1409,26 +1409,26 @@ function dol_banner_tab($object, $paramid, $morehtml = '', $shownav = 1, $fieldi { if ($modulepart != 'unknown') { - $phototoshow=''; + $phototoshow = ''; // Check if a preview file is available if (in_array($modulepart, array('propal', 'commande', 'facture', 'ficheinter', 'contract', 'supplier_order', 'supplier_proposal', 'supplier_invoice', 'expensereport')) && class_exists("Imagick")) { $objectref = dol_sanitizeFileName($object->ref); - $dir_output = (empty($conf->$modulepart->multidir_output[$entity]) ? $conf->$modulepart->dir_output : $conf->$modulepart->multidir_output[$entity]) . "/"; + $dir_output = (empty($conf->$modulepart->multidir_output[$entity]) ? $conf->$modulepart->dir_output : $conf->$modulepart->multidir_output[$entity])."/"; if (in_array($modulepart, array('invoice_supplier', 'supplier_invoice'))) { $subdir = get_exdir($object->id, 2, 0, 1, $object, $modulepart); - $subdir.= ((! empty($subdir) && ! preg_match('/\/$/', $subdir))?'/':'').$objectref; // the objectref dir is not included into get_exdir when used with level=2, so we add it at end + $subdir .= ((!empty($subdir) && !preg_match('/\/$/', $subdir)) ? '/' : '').$objectref; // the objectref dir is not included into get_exdir when used with level=2, so we add it at end } else { $subdir = get_exdir($object->id, 0, 0, 1, $object, $modulepart); } - if (empty($subdir)) $subdir = 'errorgettingsubdirofobject'; // Protection to avoid to return empty path + if (empty($subdir)) $subdir = 'errorgettingsubdirofobject'; // Protection to avoid to return empty path - $filepath = $dir_output . $subdir . "/"; + $filepath = $dir_output.$subdir."/"; - $filepdf = $filepath . $objectref . ".pdf"; + $filepdf = $filepath.$objectref.".pdf"; $relativepath = $subdir.'/'.$objectref.'.pdf'; // Define path to preview pdf file (preview precompiled "file.ext" are "file.ext_preview.png") @@ -1441,159 +1441,159 @@ function dol_banner_tab($object, $paramid, $morehtml = '', $shownav = 1, $fieldi if ($pdfexists) { // Conversion du PDF en image png si fichier png non existant - if (! file_exists($fileimage) || (filemtime($fileimage) < filemtime($filepdf))) + 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 + $ret = dol_convert_file($filepdf, 'png', $fileimage, '0'); // Convert first page of PDF into a file _preview.png if ($ret < 0) $error++; } } } - if ($pdfexists && ! $error) + if ($pdfexists && !$error) { - $heightforphotref=70; - if (! empty($conf->dol_optimize_smallscreen)) $heightforphotref=60; + $heightforphotref = 70; + if (!empty($conf->dol_optimize_smallscreen)) $heightforphotref = 60; // If the preview file is found if (file_exists($fileimage)) { $phototoshow = '
    '; - $phototoshow.= ''; - $phototoshow.= '
    '; + $phototoshow .= ''; + $phototoshow .= '
    '; } } } - elseif (! $phototoshow) + elseif (!$phototoshow) { - $phototoshow.= $form->showphoto($modulepart, $object, 0, 0, 0, 'photoref', 'small', 1, 0, $maxvisiblephotos); + $phototoshow .= $form->showphoto($modulepart, $object, 0, 0, 0, 'photoref', 'small', 1, 0, $maxvisiblephotos); } if ($phototoshow) { - $morehtmlleft.='
    '; - $morehtmlleft.=$phototoshow; - $morehtmlleft.='
    '; + $morehtmlleft .= '
    '; + $morehtmlleft .= $phototoshow; + $morehtmlleft .= '
    '; } } - if (! $phototoshow) // Show No photo link (picto of pbject) + if (!$phototoshow) // Show No photo link (picto of pbject) { - $morehtmlleft.='
    '; + $morehtmlleft .= '
    '; if ($object->element == 'action') { - $width=80; - $cssclass='photorefcenter'; - $nophoto=img_picto('', 'title_agenda', '', false, 1); + $width = 80; + $cssclass = 'photorefcenter'; + $nophoto = img_picto('', 'title_agenda', '', false, 1); } else { - $width=14; $cssclass='photorefcenter'; + $width = 14; $cssclass = 'photorefcenter'; $picto = $object->picto; - if ($object->element == 'project' && ! $object->public) $picto = 'project'; // instead of projectpub - $nophoto=img_picto('', 'object_'.$picto, '', false, 1); + if ($object->element == 'project' && !$object->public) $picto = 'project'; // instead of projectpub + $nophoto = img_picto('', 'object_'.$picto, '', false, 1); } - $morehtmlleft.=''; - $morehtmlleft.='
    No photo
    '; + $morehtmlleft .= ''; + $morehtmlleft .= '
    No photo
    '; - $morehtmlleft.='
    '; + $morehtmlleft .= '
    '; } } } - if ($showbarcode) $morehtmlleft.='
    '.$form->showbarcode($object).'
    '; + if ($showbarcode) $morehtmlleft .= '
    '.$form->showbarcode($object).'
    '; if ($object->element == 'societe') { - if (! empty($conf->use_javascript_ajax) && $user->rights->societe->creer && ! empty($conf->global->MAIN_DIRECT_STATUS_UPDATE)) + if (!empty($conf->use_javascript_ajax) && $user->rights->societe->creer && !empty($conf->global->MAIN_DIRECT_STATUS_UPDATE)) { - $morehtmlstatus.=ajax_object_onoff($object, 'status', 'status', 'InActivity', 'ActivityCeased'); + $morehtmlstatus .= ajax_object_onoff($object, 'status', 'status', 'InActivity', 'ActivityCeased'); } else { - $morehtmlstatus.=$object->getLibStatut(6); + $morehtmlstatus .= $object->getLibStatut(6); } } elseif ($object->element == 'product') { //$morehtmlstatus.=$langs->trans("Status").' ('.$langs->trans("Sell").') '; - if (! empty($conf->use_javascript_ajax) && $user->rights->produit->creer && ! empty($conf->global->MAIN_DIRECT_STATUS_UPDATE)) { - $morehtmlstatus.=ajax_object_onoff($object, 'status', 'tosell', 'ProductStatusOnSell', 'ProductStatusNotOnSell'); + if (!empty($conf->use_javascript_ajax) && $user->rights->produit->creer && !empty($conf->global->MAIN_DIRECT_STATUS_UPDATE)) { + $morehtmlstatus .= ajax_object_onoff($object, 'status', 'tosell', 'ProductStatusOnSell', 'ProductStatusNotOnSell'); } else { - $morehtmlstatus.=''.$object->getLibStatut(6, 0).''; + $morehtmlstatus .= ''.$object->getLibStatut(6, 0).''; } - $morehtmlstatus.='   '; + $morehtmlstatus .= '   '; //$morehtmlstatus.=$langs->trans("Status").' ('.$langs->trans("Buy").') '; - if (! empty($conf->use_javascript_ajax) && $user->rights->produit->creer && ! empty($conf->global->MAIN_DIRECT_STATUS_UPDATE)) { - $morehtmlstatus.=ajax_object_onoff($object, 'status_buy', 'tobuy', 'ProductStatusOnBuy', 'ProductStatusNotOnBuy'); + if (!empty($conf->use_javascript_ajax) && $user->rights->produit->creer && !empty($conf->global->MAIN_DIRECT_STATUS_UPDATE)) { + $morehtmlstatus .= ajax_object_onoff($object, 'status_buy', 'tobuy', 'ProductStatusOnBuy', 'ProductStatusNotOnBuy'); } else { - $morehtmlstatus.=''.$object->getLibStatut(6, 1).''; + $morehtmlstatus .= ''.$object->getLibStatut(6, 1).''; } } elseif (in_array($object->element, array('facture', 'invoice', 'invoice_supplier', 'chargesociales', 'loan'))) { - $tmptxt=$object->getLibStatut(6, $object->totalpaye); - if (empty($tmptxt) || $tmptxt == $object->getLibStatut(3)) $tmptxt=$object->getLibStatut(5, $object->totalpaye); - $morehtmlstatus.=$tmptxt; + $tmptxt = $object->getLibStatut(6, $object->totalpaye); + if (empty($tmptxt) || $tmptxt == $object->getLibStatut(3)) $tmptxt = $object->getLibStatut(5, $object->totalpaye); + $morehtmlstatus .= $tmptxt; } elseif ($object->element == 'contrat' || $object->element == 'contract') { - if ($object->statut == 0) $morehtmlstatus.=$object->getLibStatut(5); - else $morehtmlstatus.=$object->getLibStatut(4); + if ($object->statut == 0) $morehtmlstatus .= $object->getLibStatut(5); + else $morehtmlstatus .= $object->getLibStatut(4); } elseif ($object->element == 'facturerec') { - if ($object->frequency == 0) $morehtmlstatus.=$object->getLibStatut(2); - else $morehtmlstatus.=$object->getLibStatut(5); + if ($object->frequency == 0) $morehtmlstatus .= $object->getLibStatut(2); + else $morehtmlstatus .= $object->getLibStatut(5); } elseif ($object->element == 'project_task') { $object->fk_statut = 1; if ($object->progress > 0) $object->fk_statut = 2; if ($object->progress >= 100) $object->fk_statut = 3; - $tmptxt=$object->getLibStatut(5); - $morehtmlstatus.=$tmptxt; // No status on task + $tmptxt = $object->getLibStatut(5); + $morehtmlstatus .= $tmptxt; // No status on task } else { // Generic case - $tmptxt=$object->getLibStatut(6); - if (empty($tmptxt) || $tmptxt == $object->getLibStatut(3)) $tmptxt=$object->getLibStatut(5); - $morehtmlstatus.=$tmptxt; + $tmptxt = $object->getLibStatut(6); + if (empty($tmptxt) || $tmptxt == $object->getLibStatut(3)) $tmptxt = $object->getLibStatut(5); + $morehtmlstatus .= $tmptxt; } // Add if object was dispatched "into accountancy" - if (! empty($conf->accounting->enabled) && in_array($object->element, array('bank', 'facture', 'invoice', 'invoice_supplier', 'expensereport'))) + if (!empty($conf->accounting->enabled) && in_array($object->element, array('bank', 'facture', 'invoice', 'invoice_supplier', 'expensereport'))) { if (method_exists($object, 'getVentilExportCompta')) { $accounted = $object->getVentilExportCompta(); $langs->load("accountancy"); - $morehtmlstatus.='
    '.($accounted > 0 ? $langs->trans("Accounted") : ''.$langs->trans("NotYetAccounted").''); + $morehtmlstatus .= '
    '.($accounted > 0 ? $langs->trans("Accounted") : ''.$langs->trans("NotYetAccounted").''); } } // Add alias for thirdparty - if (! empty($object->name_alias)) $morehtmlref.='
    '.$object->name_alias.'
    '; + if (!empty($object->name_alias)) $morehtmlref .= '
    '.$object->name_alias.'
    '; // Add label if ($object->element == 'product' || $object->element == 'bank_account' || $object->element == 'project_task') { - if (! empty($object->label)) $morehtmlref.='
    '.$object->label.'
    '; + if (!empty($object->label)) $morehtmlref .= '
    '.$object->label.'
    '; } if (method_exists($object, 'getBannerAddress') && $object->element != 'product' && $object->element != 'bookmark' && $object->element != 'ecm_directories' && $object->element != 'ecm_files') { - $morehtmlref.='
    '; - $morehtmlref.=$object->getBannerAddress('refaddress', $object); - $morehtmlref.='
    '; + $morehtmlref .= '
    '; + $morehtmlref .= $object->getBannerAddress('refaddress', $object); + $morehtmlref .= '
    '; } - if (! empty($conf->global->MAIN_SHOW_TECHNICAL_ID) && in_array($object->element, array('societe', 'contact', 'member', 'product'))) + if (!empty($conf->global->MAIN_SHOW_TECHNICAL_ID) && in_array($object->element, array('societe', 'contact', 'member', 'product'))) { - $morehtmlref.='
    '; - $morehtmlref.=$langs->trans("TechnicalID").': '.$object->id; - $morehtmlref.='
    '; + $morehtmlref .= '
    '; + $morehtmlref .= $langs->trans("TechnicalID").': '.$object->id; + $morehtmlref .= '
    '; } - print '
    '; + print '
    '; print $form->showrefnav($object, $paramid, $morehtml, $shownav, $fieldid, $fieldref, $morehtmlref, $moreparam, $nodbprefix, $morehtmlleft, $morehtmlstatus, $morehtmlright); print '
    '; print '
    '; @@ -1611,12 +1611,12 @@ function dol_banner_tab($object, $paramid, $morehtml = '', $shownav = 1, $fieldi function fieldLabel($langkey, $fieldkey, $fieldrequired = 0) { global $langs; - $ret=''; - if ($fieldrequired) $ret.=''; - $ret.=''; - if ($fieldrequired) $ret.=''; + $ret = ''; + if ($fieldrequired) $ret .= ''; + $ret .= ''; + if ($fieldrequired) $ret .= ''; return $ret; } @@ -1630,8 +1630,8 @@ function fieldLabel($langkey, $fieldkey, $fieldrequired = 0) function dol_bc($var, $moreclass = '') { global $bc; - $ret=' '.$bc[$var]; - if ($moreclass) $ret=preg_replace('/class=\"/', 'class="'.$moreclass.' ', $ret); + $ret = ' '.$bc[$var]; + if ($moreclass) $ret = preg_replace('/class=\"/', 'class="'.$moreclass.' ', $ret); return $ret; } @@ -1648,63 +1648,63 @@ function dol_bc($var, $moreclass = '') */ function dol_format_address($object, $withcountry = 0, $sep = "\n", $outputlangs = '', $mode = 0) { - global $conf,$langs; + global $conf, $langs; - $ret=''; - $countriesusingstate=array('AU','CA','US','IN','GB','ES','UK','TR'); // See also MAIN_FORCE_STATE_INTO_ADDRESS + $ret = ''; + $countriesusingstate = array('AU', 'CA', 'US', 'IN', 'GB', 'ES', 'UK', 'TR'); // See also MAIN_FORCE_STATE_INTO_ADDRESS // Address if (empty($mode)) { $ret .= $object->address; } // Zip/Town/State - if (in_array($object->country_code, array('AU', 'CA', 'US')) || ! empty($conf->global->MAIN_FORCE_STATE_INTO_ADDRESS)) // US: title firstname name \n address lines \n town, state, zip \n country + if (in_array($object->country_code, array('AU', 'CA', 'US')) || !empty($conf->global->MAIN_FORCE_STATE_INTO_ADDRESS)) // US: title firstname name \n address lines \n town, state, zip \n country { - $ret .= ($ret ? $sep : '' ).$object->town; + $ret .= ($ret ? $sep : '').$object->town; if ($object->state) { - $ret.=($ret?", ":'').$object->state; + $ret .= ($ret ? ", " : '').$object->state; } - if ($object->zip) $ret .= ($ret?", ":'').$object->zip; + if ($object->zip) $ret .= ($ret ? ", " : '').$object->zip; } - elseif (in_array($object->country_code, array('GB','UK'))) // UK: title firstname name \n address lines \n town state \n zip \n country + elseif (in_array($object->country_code, array('GB', 'UK'))) // UK: title firstname name \n address lines \n town state \n zip \n country { - $ret .= ($ret ? $sep : '' ).$object->town; + $ret .= ($ret ? $sep : '').$object->town; if ($object->state) { - $ret.=($ret?", ":'').$object->state; + $ret .= ($ret ? ", " : '').$object->state; } - if ($object->zip) $ret .= ($ret ? $sep : '' ).$object->zip; + if ($object->zip) $ret .= ($ret ? $sep : '').$object->zip; } - elseif (in_array($object->country_code, array('ES','TR'))) // ES: title firstname name \n address lines \n zip town \n state \n country + elseif (in_array($object->country_code, array('ES', 'TR'))) // ES: title firstname name \n address lines \n zip town \n state \n country { - $ret .= ($ret ? $sep : '' ).$object->zip; - $ret .= ($object->town?(($object->zip?' ':'').$object->town):''); + $ret .= ($ret ? $sep : '').$object->zip; + $ret .= ($object->town ? (($object->zip ? ' ' : '').$object->town) : ''); if ($object->state) { - $ret.="\n".$object->state; + $ret .= "\n".$object->state; } } elseif (in_array($object->country_code, array('IT'))) // IT: tile firstname name\n address lines \n zip (Code Departement) \n country { - $ret .= ($ret ? $sep : '' ).$object->zip; - $ret .= ($object->town?(($object->zip?' ':'').$object->town):''); - $ret .= ($object->state_id?(' ('.($object->state_id).')'):''); + $ret .= ($ret ? $sep : '').$object->zip; + $ret .= ($object->town ? (($object->zip ? ' ' : '').$object->town) : ''); + $ret .= ($object->state_id ? (' ('.($object->state_id).')') : ''); } else // Other: title firstname name \n address lines \n zip town \n country { - $ret .= $object->zip ? (($ret ? $sep : '' ).$object->zip) : ''; - $ret .= ($object->town?(($object->zip?' ':($ret ? $sep : '' )).$object->town):''); + $ret .= $object->zip ? (($ret ? $sep : '').$object->zip) : ''; + $ret .= ($object->town ? (($object->zip ? ' ' : ($ret ? $sep : '')).$object->town) : ''); if ($object->state && in_array($object->country_code, $countriesusingstate)) { - $ret.=($ret?", ":'').$object->state; + $ret .= ($ret ? ", " : '').$object->state; } } - if (! is_object($outputlangs)) $outputlangs=$langs; + if (!is_object($outputlangs)) $outputlangs = $langs; if ($withcountry) { $langs->load("dict"); - $ret.=($object->country_code?($ret?$sep:'').$outputlangs->convToOutputCharset($outputlangs->transnoentitiesnoconv("Country".$object->country_code)):''); + $ret .= ($object->country_code ? ($ret ? $sep : '').$outputlangs->convToOutputCharset($outputlangs->transnoentitiesnoconv("Country".$object->country_code)) : ''); } return $ret; @@ -1723,7 +1723,7 @@ function dol_format_address($object, $withcountry = 0, $sep = "\n", $outputlangs function dol_strftime($fmt, $ts = false, $is_gmt = false) { if ((abs($ts) <= 0x7FFFFFFF)) { // check if number in 32-bit signed range - return ($is_gmt)? @gmstrftime($fmt, $ts): @strftime($fmt, $ts); + return ($is_gmt) ? @gmstrftime($fmt, $ts) : @strftime($fmt, $ts); } else return 'Error date into a not supported range'; } @@ -1751,83 +1751,83 @@ function dol_strftime($fmt, $ts = false, $is_gmt = false) */ function dol_print_date($time, $format = '', $tzoutput = 'tzserver', $outputlangs = '', $encodetooutput = false) { - global $conf,$langs; + global $conf, $langs; // Clean parameters - $to_gmt=false; - $offsettz=$offsetdst=0; + $to_gmt = false; + $offsettz = $offsetdst = 0; if ($tzoutput) { - $to_gmt=true; // For backward compatibility + $to_gmt = true; // For backward compatibility if (is_string($tzoutput)) { if ($tzoutput == 'tzserver') { - $to_gmt=false; - $offsettzstring=@date_default_timezone_get(); // Example 'Europe/Berlin' or 'Indian/Reunion' - $offsettz=0; - $offsetdst=0; + $to_gmt = false; + $offsettzstring = @date_default_timezone_get(); // Example 'Europe/Berlin' or 'Indian/Reunion' + $offsettz = 0; + $offsetdst = 0; } elseif ($tzoutput == 'tzuser' || $tzoutput == 'tzuserrel') { - $to_gmt=true; - $offsettzstring=(empty($_SESSION['dol_tz_string'])?'UTC':$_SESSION['dol_tz_string']); // Example 'Europe/Berlin' or 'Indian/Reunion' - $offsettz=(empty($_SESSION['dol_tz'])?0:$_SESSION['dol_tz'])*60*60; // Will not be used anymore - $offsetdst=(empty($_SESSION['dol_dst'])?0:$_SESSION['dol_dst'])*60*60; // Will not be used anymore + $to_gmt = true; + $offsettzstring = (empty($_SESSION['dol_tz_string']) ? 'UTC' : $_SESSION['dol_tz_string']); // Example 'Europe/Berlin' or 'Indian/Reunion' + $offsettz = (empty($_SESSION['dol_tz']) ? 0 : $_SESSION['dol_tz']) * 60 * 60; // Will not be used anymore + $offsetdst = (empty($_SESSION['dol_dst']) ? 0 : $_SESSION['dol_dst']) * 60 * 60; // Will not be used anymore } } } - if (! is_object($outputlangs)) $outputlangs=$langs; - if (! $format) $format='daytextshort'; - $reduceformat=(! empty($conf->dol_optimize_smallscreen) && in_array($format, array('day','dayhour')))?1:0; + if (!is_object($outputlangs)) $outputlangs = $langs; + if (!$format) $format = 'daytextshort'; + $reduceformat = (!empty($conf->dol_optimize_smallscreen) && in_array($format, array('day', 'dayhour'))) ? 1 : 0; $formatwithoutreduce = preg_replace('/reduceformat/', '', $format); - if ($formatwithoutreduce != $format) { $format = $formatwithoutreduce; $reduceformat=1; } // so format 'dayreduceformat' is processed like day + if ($formatwithoutreduce != $format) { $format = $formatwithoutreduce; $reduceformat = 1; } // so format 'dayreduceformat' is processed like day // Change predefined format into computer format. If found translation in lang file we use it, otherwise we use default. // TODO Add format daysmallyear and dayhoursmallyear - if ($format == 'day') $format=($outputlangs->trans("FormatDateShort")!="FormatDateShort"?$outputlangs->trans("FormatDateShort"):$conf->format_date_short); - elseif ($format == 'hour') $format=($outputlangs->trans("FormatHourShort")!="FormatHourShort"?$outputlangs->trans("FormatHourShort"):$conf->format_hour_short); - elseif ($format == 'hourduration') $format=($outputlangs->trans("FormatHourShortDuration")!="FormatHourShortDuration"?$outputlangs->trans("FormatHourShortDuration"):$conf->format_hour_short_duration); - elseif ($format == 'daytext') $format=($outputlangs->trans("FormatDateText")!="FormatDateText"?$outputlangs->trans("FormatDateText"):$conf->format_date_text); - elseif ($format == 'daytextshort') $format=($outputlangs->trans("FormatDateTextShort")!="FormatDateTextShort"?$outputlangs->trans("FormatDateTextShort"):$conf->format_date_text_short); - elseif ($format == 'dayhour') $format=($outputlangs->trans("FormatDateHourShort")!="FormatDateHourShort"?$outputlangs->trans("FormatDateHourShort"):$conf->format_date_hour_short); - elseif ($format == 'dayhoursec') $format=($outputlangs->trans("FormatDateHourSecShort")!="FormatDateHourSecShort"?$outputlangs->trans("FormatDateHourSecShort"):$conf->format_date_hour_sec_short); - elseif ($format == 'dayhourtext') $format=($outputlangs->trans("FormatDateHourText")!="FormatDateHourText"?$outputlangs->trans("FormatDateHourText"):$conf->format_date_hour_text); - elseif ($format == 'dayhourtextshort') $format=($outputlangs->trans("FormatDateHourTextShort")!="FormatDateHourTextShort"?$outputlangs->trans("FormatDateHourTextShort"):$conf->format_date_hour_text_short); + if ($format == 'day') $format = ($outputlangs->trans("FormatDateShort") != "FormatDateShort" ? $outputlangs->trans("FormatDateShort") : $conf->format_date_short); + elseif ($format == 'hour') $format = ($outputlangs->trans("FormatHourShort") != "FormatHourShort" ? $outputlangs->trans("FormatHourShort") : $conf->format_hour_short); + elseif ($format == 'hourduration') $format = ($outputlangs->trans("FormatHourShortDuration") != "FormatHourShortDuration" ? $outputlangs->trans("FormatHourShortDuration") : $conf->format_hour_short_duration); + elseif ($format == 'daytext') $format = ($outputlangs->trans("FormatDateText") != "FormatDateText" ? $outputlangs->trans("FormatDateText") : $conf->format_date_text); + elseif ($format == 'daytextshort') $format = ($outputlangs->trans("FormatDateTextShort") != "FormatDateTextShort" ? $outputlangs->trans("FormatDateTextShort") : $conf->format_date_text_short); + elseif ($format == 'dayhour') $format = ($outputlangs->trans("FormatDateHourShort") != "FormatDateHourShort" ? $outputlangs->trans("FormatDateHourShort") : $conf->format_date_hour_short); + elseif ($format == 'dayhoursec') $format = ($outputlangs->trans("FormatDateHourSecShort") != "FormatDateHourSecShort" ? $outputlangs->trans("FormatDateHourSecShort") : $conf->format_date_hour_sec_short); + elseif ($format == 'dayhourtext') $format = ($outputlangs->trans("FormatDateHourText") != "FormatDateHourText" ? $outputlangs->trans("FormatDateHourText") : $conf->format_date_hour_text); + elseif ($format == 'dayhourtextshort') $format = ($outputlangs->trans("FormatDateHourTextShort") != "FormatDateHourTextShort" ? $outputlangs->trans("FormatDateHourTextShort") : $conf->format_date_hour_text_short); // Format not sensitive to language - elseif ($format == 'dayhourlog') $format='%Y%m%d%H%M%S'; - elseif ($format == 'dayhourldap') $format='%Y%m%d%H%M%SZ'; - elseif ($format == 'dayhourxcard') $format='%Y%m%dT%H%M%SZ'; - elseif ($format == 'dayxcard') $format='%Y%m%d'; - elseif ($format == 'dayrfc') $format='%Y-%m-%d'; // DATE_RFC3339 - elseif ($format == 'dayhourrfc') $format='%Y-%m-%dT%H:%M:%SZ'; // DATETIME RFC3339 - elseif ($format == 'standard') $format='%Y-%m-%d %H:%M:%S'; + elseif ($format == 'dayhourlog') $format = '%Y%m%d%H%M%S'; + elseif ($format == 'dayhourldap') $format = '%Y%m%d%H%M%SZ'; + elseif ($format == 'dayhourxcard') $format = '%Y%m%dT%H%M%SZ'; + elseif ($format == 'dayxcard') $format = '%Y%m%d'; + elseif ($format == 'dayrfc') $format = '%Y-%m-%d'; // DATE_RFC3339 + elseif ($format == 'dayhourrfc') $format = '%Y-%m-%dT%H:%M:%SZ'; // DATETIME RFC3339 + elseif ($format == 'standard') $format = '%Y-%m-%d %H:%M:%S'; if ($reduceformat) { - $format=str_replace('%Y', '%y', $format); - $format=str_replace('yyyy', 'yy', $format); + $format = str_replace('%Y', '%y', $format); + $format = str_replace('yyyy', 'yy', $format); } // If date undefined or "", we return "" - if (dol_strlen($time) == 0) return ''; // $time=0 allowed (it means 01/01/1970 00:00:00) + if (dol_strlen($time) == 0) return ''; // $time=0 allowed (it means 01/01/1970 00:00:00) // Clean format if (preg_match('/%b/i', $format)) // There is some text to translate { // We inhibate translation to text made by strftime functions. We will use trans instead later. - $format=str_replace('%b', '__b__', $format); - $format=str_replace('%B', '__B__', $format); + $format = str_replace('%b', '__b__', $format); + $format = str_replace('%B', '__B__', $format); } if (preg_match('/%a/i', $format)) // There is some text to translate { // We inhibate translation to text made by strftime functions. We will use trans instead later. - $format=str_replace('%a', '__a__', $format); - $format=str_replace('%A', '__A__', $format); + $format = str_replace('%a', '__a__', $format); + $format = str_replace('%A', '__A__', $format); } // Analyze date - $reg=array(); + $reg = array(); if (preg_match('/^([0-9][0-9][0-9][0-9])([0-9][0-9])([0-9][0-9])([0-9][0-9])([0-9][0-9])([0-9][0-9])$/i', $time, $reg)) // Deprecated. Ex: 1970-01-01, 1970-01-01 01:00:00, 19700101010000 { dol_print_error("Functions.lib::dol_print_date function called with a bad value from page ".$_SERVER["PHP_SELF"]); @@ -1839,59 +1839,59 @@ function dol_print_date($time, $format = '', $tzoutput = 'tzserver', $outputlang dol_syslog("Functions.lib::dol_print_date function called with a bad value from page ".$_SERVER["PHP_SELF"], LOG_WARNING); //if (function_exists('debug_print_backtrace')) debug_print_backtrace(); // Date has format 'YYYY-MM-DD' or 'YYYY-MM-DD HH:MM:SS' - $syear = (! empty($reg[1]) ? $reg[1] : ''); - $smonth = (! empty($reg[2]) ? $reg[2] : ''); - $sday = (! empty($reg[3]) ? $reg[3] : ''); - $shour = (! empty($reg[4]) ? $reg[4] : ''); - $smin = (! empty($reg[5]) ? $reg[5] : ''); - $ssec = (! empty($reg[6]) ? $reg[6] : ''); + $syear = (!empty($reg[1]) ? $reg[1] : ''); + $smonth = (!empty($reg[2]) ? $reg[2] : ''); + $sday = (!empty($reg[3]) ? $reg[3] : ''); + $shour = (!empty($reg[4]) ? $reg[4] : ''); + $smin = (!empty($reg[5]) ? $reg[5] : ''); + $ssec = (!empty($reg[6]) ? $reg[6] : ''); - $time=dol_mktime($shour, $smin, $ssec, $smonth, $sday, $syear, true); - $ret=adodb_strftime($format, $time+$offsettz+$offsetdst, $to_gmt); + $time = dol_mktime($shour, $smin, $ssec, $smonth, $sday, $syear, true); + $ret = adodb_strftime($format, $time + $offsettz + $offsetdst, $to_gmt); } else { // Date is a timestamps if ($time < 100000000000) // Protection against bad date values { - $timetouse = $time+$offsettz+$offsetdst; // TODO Replace this with function Date PHP. We also should not use anymore offsettz and offsetdst but only offsettzstring. + $timetouse = $time + $offsettz + $offsetdst; // TODO Replace this with function Date PHP. We also should not use anymore offsettz and offsetdst but only offsettzstring. - $ret=adodb_strftime($format, $timetouse, $to_gmt); + $ret = adodb_strftime($format, $timetouse, $to_gmt); } - else $ret='Bad value '.$time.' for date'; + else $ret = 'Bad value '.$time.' for date'; } if (preg_match('/__b__/i', $format)) { - $timetouse = $time+$offsettz+$offsetdst; // TODO Replace this with function Date PHP. We also should not use anymore offsettz and offsetdst but only offsettzstring. + $timetouse = $time + $offsettz + $offsetdst; // TODO Replace this with function Date PHP. We also should not use anymore offsettz and offsetdst but only offsettzstring. // Here ret is string in PHP setup language (strftime was used). Now we convert to $outputlangs. - $month=adodb_strftime('%m', $timetouse); - $month=sprintf("%02d", $month); // $month may be return with format '06' on some installation and '6' on other, so we force it to '06'. + $month = adodb_strftime('%m', $timetouse); + $month = sprintf("%02d", $month); // $month may be return with format '06' on some installation and '6' on other, so we force it to '06'. if ($encodetooutput) { - $monthtext=$outputlangs->transnoentities('Month'.$month); - $monthtextshort=$outputlangs->transnoentities('MonthShort'.$month); + $monthtext = $outputlangs->transnoentities('Month'.$month); + $monthtextshort = $outputlangs->transnoentities('MonthShort'.$month); } else { - $monthtext=$outputlangs->transnoentitiesnoconv('Month'.$month); - $monthtextshort=$outputlangs->transnoentitiesnoconv('MonthShort'.$month); + $monthtext = $outputlangs->transnoentitiesnoconv('Month'.$month); + $monthtextshort = $outputlangs->transnoentitiesnoconv('MonthShort'.$month); } //print 'monthtext='.$monthtext.' monthtextshort='.$monthtextshort; - $ret=str_replace('__b__', $monthtextshort, $ret); - $ret=str_replace('__B__', $monthtext, $ret); + $ret = str_replace('__b__', $monthtextshort, $ret); + $ret = str_replace('__B__', $monthtext, $ret); //print 'x'.$outputlangs->charset_output.'-'.$ret.'x'; //return $ret; } if (preg_match('/__a__/i', $format)) { - $timetouse = $time+$offsettz+$offsetdst; // TODO Replace this with function Date PHP. We also should not use anymore offsettz and offsetdst but only offsettzstring. + $timetouse = $time + $offsettz + $offsetdst; // TODO Replace this with function Date PHP. We also should not use anymore offsettz and offsetdst but only offsettzstring. - $w=adodb_strftime('%w', $timetouse); // TODO Replace this with function Date PHP. We also should not use anymore offsettz and offsetdst but only offsettzstring. - $dayweek=$outputlangs->transnoentitiesnoconv('Day'.$w); - $ret=str_replace('__A__', $dayweek, $ret); - $ret=str_replace('__a__', dol_substr($dayweek, 0, 3), $ret); + $w = adodb_strftime('%w', $timetouse); // TODO Replace this with function Date PHP. We also should not use anymore offsettz and offsetdst but only offsettzstring. + $dayweek = $outputlangs->transnoentitiesnoconv('Day'.$w); + $ret = str_replace('__A__', $dayweek, $ret); + $ret = str_replace('__a__', dol_substr($dayweek, 0, 3), $ret); } return $ret; @@ -1935,17 +1935,17 @@ function dol_getdate($timestamp, $fast = false) { global $conf; - $usealternatemethod=false; - if ($timestamp <= 0) $usealternatemethod=true; // <= 1970 - if ($timestamp >= 2145913200) $usealternatemethod=true; // >= 2038 + $usealternatemethod = false; + if ($timestamp <= 0) $usealternatemethod = true; // <= 1970 + if ($timestamp >= 2145913200) $usealternatemethod = true; // >= 2038 if ($usealternatemethod) { - $arrayinfo=adodb_getdate($timestamp, $fast); + $arrayinfo = adodb_getdate($timestamp, $fast); } else { - $arrayinfo=getdate($timestamp); + $arrayinfo = getdate($timestamp); } return $arrayinfo; @@ -1976,47 +1976,47 @@ function dol_mktime($hour, $minute, $second, $month, $day, $year, $gm = false, $ //print "- ".$hour.",".$minute.",".$second.",".$month.",".$day.",".$year.",".$_SERVER["WINDIR"]." -"; // Clean parameters - if ($hour == -1 || empty($hour)) $hour=0; - if ($minute == -1 || empty($minute)) $minute=0; - if ($second == -1 || empty($second)) $second=0; + if ($hour == -1 || empty($hour)) $hour = 0; + if ($minute == -1 || empty($minute)) $minute = 0; + if ($second == -1 || empty($second)) $second = 0; // Check parameters if ($check) { - if (! $month || ! $day) return ''; - if ($day > 31) return ''; + if (!$month || !$day) return ''; + if ($day > 31) return ''; if ($month > 12) return ''; - if ($hour < 0 || $hour > 24) return ''; - if ($minute< 0 || $minute > 60) return ''; - if ($second< 0 || $second > 60) return ''; + if ($hour < 0 || $hour > 24) return ''; + if ($minute < 0 || $minute > 60) return ''; + if ($second < 0 || $second > 60) return ''; } if (empty($gm) || $gm === 'server') { - $default_timezone=@date_default_timezone_get(); // Example 'Europe/Berlin' + $default_timezone = @date_default_timezone_get(); // Example 'Europe/Berlin' $localtz = new DateTimeZone($default_timezone); } elseif ($gm === 'user') { // We use dol_tz_string first because it is more reliable. - $default_timezone=(empty($_SESSION["dol_tz_string"])?@date_default_timezone_get():$_SESSION["dol_tz_string"]); // Example 'Europe/Berlin' + $default_timezone = (empty($_SESSION["dol_tz_string"]) ? @date_default_timezone_get() : $_SESSION["dol_tz_string"]); // Example 'Europe/Berlin' try { $localtz = new DateTimeZone($default_timezone); } - catch(Exception $e) + catch (Exception $e) { dol_syslog("Warning dol_tz_string contains an invalid value ".$_SESSION["dol_tz_string"], LOG_WARNING); - $default_timezone=@date_default_timezone_get(); + $default_timezone = @date_default_timezone_get(); } } elseif (strrpos($gm, "tz,") !== false) { - $timezone=str_replace("tz,", "", $gm); // Example 'tz,Europe/Berlin' + $timezone = str_replace("tz,", "", $gm); // Example 'tz,Europe/Berlin' try { $localtz = new DateTimeZone($timezone); } - catch(Exception $e) + catch (Exception $e) { dol_syslog("Warning passed timezone contains an invalid value ".$timezone, LOG_WARNING); } @@ -2030,7 +2030,7 @@ function dol_mktime($hour, $minute, $second, $month, $day, $year, $gm = false, $ $dt = new DateTime(null, $localtz); $dt->setDate((int) $year, (int) $month, (int) $day); $dt->setTime((int) $hour, (int) $minute, (int) $second); - $date=$dt->getTimestamp(); // should include daylight saving time + $date = $dt->getTimestamp(); // should include daylight saving time //var_dump($date); return $date; } @@ -2047,16 +2047,16 @@ function dol_mktime($hour, $minute, $second, $month, $day, $year, $gm = false, $ */ function dol_now($mode = 'gmt') { - $ret=0; + $ret = 0; // Note that gmmktime and mktime return same value (GMT) when used without parameters //if ($mode == 'gmt') $ret=gmmktime(); // Strict Standards: gmmktime(): You should be using the time() function instead - if ($mode == 'gmt') $ret=time(); // Time for now at greenwich. + if ($mode == 'gmt') $ret = time(); // Time for now at greenwich. elseif ($mode == 'tzserver') // Time for now with PHP server timezone added { require_once DOL_DOCUMENT_ROOT.'/core/lib/date.lib.php'; - $tzsecond=getServerTimeZoneInt('now'); // Contains tz+dayling saving time - $ret=(int) (dol_now('gmt')+($tzsecond*3600)); + $tzsecond = getServerTimeZoneInt('now'); // Contains tz+dayling saving time + $ret = (int) (dol_now('gmt') + ($tzsecond * 3600)); } /*else if ($mode == 'tzref') // Time for now with parent company timezone is added { @@ -2067,9 +2067,9 @@ function dol_now($mode = 'gmt') elseif ($mode == 'tzuser') // Time for now with user timezone added { //print 'time: '.time().'-'.mktime().'-'.gmmktime(); - $offsettz=(empty($_SESSION['dol_tz'])?0:$_SESSION['dol_tz'])*60*60; - $offsetdst=(empty($_SESSION['dol_dst'])?0:$_SESSION['dol_dst'])*60*60; - $ret=(int) (dol_now('gmt')+($offsettz+$offsetdst)); + $offsettz = (empty($_SESSION['dol_tz']) ? 0 : $_SESSION['dol_tz']) * 60 * 60; + $offsetdst = (empty($_SESSION['dol_dst']) ? 0 : $_SESSION['dol_dst']) * 60 * 60; + $ret = (int) (dol_now('gmt') + ($offsettz + $offsetdst)); } return $ret; @@ -2086,27 +2086,27 @@ function dol_now($mode = 'gmt') */ function dol_print_size($size, $shortvalue = 0, $shortunit = 0) { - global $conf,$langs; - $level=1024; + global $conf, $langs; + $level = 1024; - if (! empty($conf->dol_optimize_smallscreen)) $shortunit=1; + if (!empty($conf->dol_optimize_smallscreen)) $shortunit = 1; // Set value text - if (empty($shortvalue) || $size < ($level*10)) + if (empty($shortvalue) || $size < ($level * 10)) { - $ret=$size; - $textunitshort=$langs->trans("b"); - $textunitlong=$langs->trans("Bytes"); + $ret = $size; + $textunitshort = $langs->trans("b"); + $textunitlong = $langs->trans("Bytes"); } else { - $ret=round($size/$level, 0); - $textunitshort=$langs->trans("Kb"); - $textunitlong=$langs->trans("KiloBytes"); + $ret = round($size / $level, 0); + $textunitshort = $langs->trans("Kb"); + $textunitlong = $langs->trans("KiloBytes"); } // Use long or short text unit - if (empty($shortunit)) { $ret.=' '.$textunitlong; } - else { $ret.=' '.$textunitshort; } + if (empty($shortunit)) { $ret .= ' '.$textunitlong; } + else { $ret .= ' '.$textunitshort; } return $ret; } @@ -2126,16 +2126,16 @@ function dol_print_url($url, $target = '_blank', $max = 32, $withpicto = 0) if (empty($url)) return ''; - $link=''.($withpicto?img_picto($langs->trans("Url"), 'globe').' ':'').$link.'
    '; + $link = ''.($withpicto ?img_picto($langs->trans("Url"), 'globe').' ' : '').$link.'
    '; } /** @@ -2152,47 +2152,47 @@ function dol_print_url($url, $target = '_blank', $max = 32, $withpicto = 0) */ function dol_print_email($email, $cid = 0, $socid = 0, $addlink = 0, $max = 64, $showinvalid = 1, $withpicto = 0) { - global $conf,$user,$langs,$hookmanager; + global $conf, $user, $langs, $hookmanager; - $newemail=$email; + $newemail = $email; if (empty($email)) return ' '; - if (! empty($addlink)) + if (!empty($addlink)) { - $newemail=''; - $newemail.=dol_trunc($email, $max); - $newemail.=''; - if ($showinvalid && ! isValidEmail($email)) + $newemail = ''; + $newemail .= dol_trunc($email, $max); + $newemail .= ''; + if ($showinvalid && !isValidEmail($email)) { $langs->load("errors"); - $newemail.=img_warning($langs->trans("ErrorBadEMail", $email)); + $newemail .= img_warning($langs->trans("ErrorBadEMail", $email)); } - if (($cid || $socid) && ! empty($conf->agenda->enabled) && $user->rights->agenda->myactions->create) + if (($cid || $socid) && !empty($conf->agenda->enabled) && $user->rights->agenda->myactions->create) { - $type='AC_EMAIL'; $link=''; - if (! empty($conf->global->AGENDA_ADDACTIONFOREMAIL)) $link=''.img_object($langs->trans("AddAction"), "calendar").''; - if ($link) $newemail='
    '.$newemail.' '.$link.'
    '; + $type = 'AC_EMAIL'; $link = ''; + if (!empty($conf->global->AGENDA_ADDACTIONFOREMAIL)) $link = ''.img_object($langs->trans("AddAction"), "calendar").''; + if ($link) $newemail = '
    '.$newemail.' '.$link.'
    '; } } else { - if ($showinvalid && ! isValidEmail($email)) + if ($showinvalid && !isValidEmail($email)) { $langs->load("errors"); - $newemail.=img_warning($langs->trans("ErrorBadEMail", $email)); + $newemail .= img_warning($langs->trans("ErrorBadEMail", $email)); } } - $rep = '
    '.($withpicto?img_picto($langs->trans("EMail"), 'object_email.png').' ':'').$newemail.'
    '; + $rep = '
    '.($withpicto ?img_picto($langs->trans("EMail"), 'object_email.png').' ' : '').$newemail.'
    '; if ($hookmanager) { - $parameters = array('cid' => $cid, 'socid' => $socid,'addlink' => $addlink, 'picto' => $withpicto); + $parameters = array('cid' => $cid, 'socid' => $socid, 'addlink' => $addlink, 'picto' => $withpicto); $reshook = $hookmanager->executeHooks('printEmail', $parameters, $email); - $rep.=$hookmanager->resPrint; + $rep .= $hookmanager->resPrint; } return $rep; @@ -2207,7 +2207,7 @@ function getArrayOfSocialNetworks() { global $conf, $db; $sql = "SELECT rowid, code, label, url, icon, active FROM ".MAIN_DB_PREFIX."c_socialnetworks"; - $sql.= " WHERE entity=".$conf->entity; + $sql .= " WHERE entity=".$conf->entity; $socialnetworks = array(); $resql = $db->query($sql); if ($resql) { @@ -2235,43 +2235,43 @@ function getArrayOfSocialNetworks() */ function dol_print_socialnetworks($value, $cid, $socid, $type) { - global $conf,$user,$langs; + global $conf, $user, $langs; - $htmllink=$value; + $htmllink = $value; if (empty($value)) return ' '; - if (! empty($type)) + if (!empty($type)) { $htmllink = '
    '; $htmllink .= img_picto($langs->trans(strtoupper($type)), $type.'.png', '', false, 0, 0, '', 'paddingright', 0); $htmllink .= $value; if ($type == 'skype') { - $htmllink.= ' '; - $htmllink.=''; - $htmllink.=''; - $htmllink.=''; - $htmllink.=''; - $htmllink.=''; + $htmllink .= ' '; + $htmllink .= ''; + $htmllink .= ''; + $htmllink .= ''; + $htmllink .= ''; + $htmllink .= ''; } - if (($cid || $socid) && ! empty($conf->agenda->enabled) && $user->rights->agenda->myactions->create && $type=='skype') + if (($cid || $socid) && !empty($conf->agenda->enabled) && $user->rights->agenda->myactions->create && $type == 'skype') { - $addlink='AC_SKYPE'; - $link=''; - if (! empty($conf->global->AGENDA_ADDACTIONFORSKYPE)) $link=''.img_object($langs->trans("AddAction"), "calendar").''; - $htmllink.=($link?' '.$link:''); + $addlink = 'AC_SKYPE'; + $link = ''; + if (!empty($conf->global->AGENDA_ADDACTIONFORSKYPE)) $link = ''.img_object($langs->trans("AddAction"), "calendar").''; + $htmllink .= ($link ? ' '.$link : ''); } - $htmllink.='
    '; + $htmllink .= ''; } else { $langs->load("errors"); - $htmllink.=img_warning($langs->trans("ErrorBadSocialNetworkValue", $value)); + $htmllink .= img_warning($langs->trans("ErrorBadSocialNetworkValue", $value)); } return $htmllink; } @@ -2297,104 +2297,104 @@ function dol_print_phone($phone, $countrycode = '', $cid = 0, $socid = 0, $addli // Clean phone parameter $phone = preg_replace("/[\s.-]/", "", trim($phone)); if (empty($phone)) { return ''; } - if (empty($countrycode)) $countrycode=$mysoc->country_code; + if (empty($countrycode)) $countrycode = $mysoc->country_code; // Short format for small screens - if ($conf->dol_optimize_smallscreen) $separ=''; + if ($conf->dol_optimize_smallscreen) $separ = ''; - $newphone=$phone; + $newphone = $phone; if (strtoupper($countrycode) == "FR") { // France if (dol_strlen($phone) == 10) { - $newphone=substr($newphone, 0, 2).$separ.substr($newphone, 2, 2).$separ.substr($newphone, 4, 2).$separ.substr($newphone, 6, 2).$separ.substr($newphone, 8, 2); + $newphone = substr($newphone, 0, 2).$separ.substr($newphone, 2, 2).$separ.substr($newphone, 4, 2).$separ.substr($newphone, 6, 2).$separ.substr($newphone, 8, 2); } elseif (dol_strlen($phone) == 7) { - $newphone=substr($newphone, 0, 3).$separ.substr($newphone, 3, 2).$separ.substr($newphone, 5, 2); + $newphone = substr($newphone, 0, 3).$separ.substr($newphone, 3, 2).$separ.substr($newphone, 5, 2); } elseif (dol_strlen($phone) == 9) { - $newphone=substr($newphone, 0, 2).$separ.substr($newphone, 2, 3).$separ.substr($newphone, 5, 2).$separ.substr($newphone, 7, 2); + $newphone = substr($newphone, 0, 2).$separ.substr($newphone, 2, 3).$separ.substr($newphone, 5, 2).$separ.substr($newphone, 7, 2); } elseif (dol_strlen($phone) == 11) { - $newphone=substr($newphone, 0, 3).$separ.substr($newphone, 3, 2).$separ.substr($newphone, 5, 2).$separ.substr($newphone, 7, 2).$separ.substr($newphone, 9, 2); + $newphone = substr($newphone, 0, 3).$separ.substr($newphone, 3, 2).$separ.substr($newphone, 5, 2).$separ.substr($newphone, 7, 2).$separ.substr($newphone, 9, 2); } elseif (dol_strlen($phone) == 12) { - $newphone=substr($newphone, 0, 4).$separ.substr($newphone, 4, 2).$separ.substr($newphone, 6, 2).$separ.substr($newphone, 8, 2).$separ.substr($newphone, 10, 2); + $newphone = substr($newphone, 0, 4).$separ.substr($newphone, 4, 2).$separ.substr($newphone, 6, 2).$separ.substr($newphone, 8, 2).$separ.substr($newphone, 10, 2); } } elseif (strtoupper($countrycode) == "CA") { if (dol_strlen($phone) == 10) { - $newphone=($separ!=''?'(':'').substr($newphone, 0, 3).($separ!=''?')':'').$separ.substr($newphone, 3, 3).($separ!=''?'-':'').substr($newphone, 6, 4); + $newphone = ($separ != '' ? '(' : '').substr($newphone, 0, 3).($separ != '' ? ')' : '').$separ.substr($newphone, 3, 3).($separ != '' ? '-' : '').substr($newphone, 6, 4); } } - elseif (strtoupper($countrycode) == "PT" ) + elseif (strtoupper($countrycode) == "PT") {//Portugal if (dol_strlen($phone) == 13) {//ex: +351_ABC_DEF_GHI - $newphone= substr($newphone, 0, 4).$separ.substr($newphone, 4, 3).$separ.substr($newphone, 7, 3).$separ.substr($newphone, 10, 3); + $newphone = substr($newphone, 0, 4).$separ.substr($newphone, 4, 3).$separ.substr($newphone, 7, 3).$separ.substr($newphone, 10, 3); } } - elseif (strtoupper($countrycode) == "SR" ) + elseif (strtoupper($countrycode) == "SR") {//Suriname if (dol_strlen($phone) == 10) {//ex: +597_ABC_DEF - $newphone= substr($newphone, 0, 4).$separ.substr($newphone, 4, 3).$separ.substr($newphone, 7, 3); + $newphone = substr($newphone, 0, 4).$separ.substr($newphone, 4, 3).$separ.substr($newphone, 7, 3); } elseif (dol_strlen($phone) == 11) {//ex: +597_ABC_DEFG - $newphone= substr($newphone, 0, 4).$separ.substr($newphone, 4, 3).$separ.substr($newphone, 7, 4); + $newphone = substr($newphone, 0, 4).$separ.substr($newphone, 4, 3).$separ.substr($newphone, 7, 4); } } - elseif (strtoupper($countrycode) == "DE" ) + elseif (strtoupper($countrycode) == "DE") {//Allemagne if (dol_strlen($phone) == 14) {//ex: +49_ABCD_EFGH_IJK - $newphone= substr($newphone, 0, 3).$separ.substr($newphone, 3, 4).$separ.substr($newphone, 7, 4).$separ.substr($newphone, 11, 3); + $newphone = substr($newphone, 0, 3).$separ.substr($newphone, 3, 4).$separ.substr($newphone, 7, 4).$separ.substr($newphone, 11, 3); } elseif (dol_strlen($phone) == 13) {//ex: +49_ABC_DEFG_HIJ - $newphone= substr($newphone, 0, 3).$separ.substr($newphone, 3, 3).$separ.substr($newphone, 6, 4).$separ.substr($newphone, 10, 3); + $newphone = substr($newphone, 0, 3).$separ.substr($newphone, 3, 3).$separ.substr($newphone, 6, 4).$separ.substr($newphone, 10, 3); } } elseif (strtoupper($countrycode) == "ES") {//Espagne if (dol_strlen($phone) == 12) {//ex: +34_ABC_DEF_GHI - $newphone= substr($newphone, 0, 3).$separ.substr($newphone, 3, 3).$separ.substr($newphone, 6, 3).$separ.substr($newphone, 9, 3); + $newphone = substr($newphone, 0, 3).$separ.substr($newphone, 3, 3).$separ.substr($newphone, 6, 3).$separ.substr($newphone, 9, 3); } } elseif (strtoupper($countrycode) == "BF") {// Burkina Faso if (dol_strlen($phone) == 12) {//ex : +22 A BC_DE_FG_HI - $newphone= substr($newphone, 0, 3).$separ.substr($newphone, 3, 1).$separ.substr($newphone, 4, 2).$separ.substr($newphone, 6, 2).$separ.substr($newphone, 8, 2).$separ.substr($newphone, 10, 2); + $newphone = substr($newphone, 0, 3).$separ.substr($newphone, 3, 1).$separ.substr($newphone, 4, 2).$separ.substr($newphone, 6, 2).$separ.substr($newphone, 8, 2).$separ.substr($newphone, 10, 2); } } elseif (strtoupper($countrycode) == "RO") {// Roumanie if (dol_strlen($phone) == 12) {//ex : +40 AB_CDE_FG_HI - $newphone= substr($newphone, 0, 3).$separ.substr($newphone, 3, 2).$separ.substr($newphone, 5, 3).$separ.substr($newphone, 8, 2).$separ.substr($newphone, 10, 2); + $newphone = substr($newphone, 0, 3).$separ.substr($newphone, 3, 2).$separ.substr($newphone, 5, 3).$separ.substr($newphone, 8, 2).$separ.substr($newphone, 10, 2); } } elseif (strtoupper($countrycode) == "TR") {//Turquie if (dol_strlen($phone) == 13) {//ex : +90 ABC_DEF_GHIJ - $newphone= substr($newphone, 0, 3).$separ.substr($newphone, 3, 3).$separ.substr($newphone, 6, 3).$separ.substr($newphone, 9, 4); + $newphone = substr($newphone, 0, 3).$separ.substr($newphone, 3, 3).$separ.substr($newphone, 6, 3).$separ.substr($newphone, 9, 4); } } elseif (strtoupper($countrycode) == "US") {//Etat-Unis if (dol_strlen($phone) == 12) {//ex: +1 ABC_DEF_GHIJ - $newphone= substr($newphone, 0, 2).$separ.substr($newphone, 2, 3).$separ.substr($newphone, 5, 3).$separ.substr($newphone, 8, 4); + $newphone = substr($newphone, 0, 2).$separ.substr($newphone, 2, 3).$separ.substr($newphone, 5, 3).$separ.substr($newphone, 8, 4); } } elseif (strtoupper($countrycode) == "MX") @@ -2414,18 +2414,18 @@ function dol_print_phone($phone, $countrycode = '', $cid = 0, $socid = 0, $addli } elseif (strtoupper($countrycode) == "ML") {//Mali - if(dol_strlen($phone) == 12) + if (dol_strlen($phone) == 12) {//ex: +223 AB_CD_EF_GH $newphone = substr($newphone, 0, 4).$separ.substr($newphone, 4, 2).$separ.substr($newphone, 6, 2).$separ.substr($newphone, 8, 2).$separ.substr($newphone, 10, 2); } } elseif (strtoupper($countrycode) == "TH") {//Thaïlande - if(dol_strlen($phone) == 11) + if (dol_strlen($phone) == 11) {//ex: +66_ABC_DE_FGH $newphone = substr($newphone, 0, 3).$separ.substr($newphone, 3, 3).$separ.substr($newphone, 6, 2).$separ.substr($newphone, 8, 3); } - elseif(dol_strlen($phone) == 12) + elseif (dol_strlen($phone) == 12) {//ex: +66_A_BCD_EF_GHI $newphone = substr($newphone, 0, 3).$separ.substr($newphone, 3, 1).$separ.substr($newphone, 4, 3).$separ.substr($newphone, 7, 2).$separ.substr($newphone, 9, 3); } @@ -2433,240 +2433,240 @@ function dol_print_phone($phone, $countrycode = '', $cid = 0, $socid = 0, $addli elseif (strtoupper($countrycode) == "MU") { //Maurice - if(dol_strlen($phone) == 11) + if (dol_strlen($phone) == 11) {//ex: +230_ABC_DE_FG $newphone = substr($newphone, 0, 4).$separ.substr($newphone, 4, 3).$separ.substr($newphone, 7, 2).$separ.substr($newphone, 9, 2); } - elseif(dol_strlen($phone) == 12) + elseif (dol_strlen($phone) == 12) {//ex: +230_ABCD_EF_GH $newphone = substr($newphone, 0, 4).$separ.substr($newphone, 4, 4).$separ.substr($newphone, 8, 2).$separ.substr($newphone, 10, 2); } } elseif (strtoupper($countrycode) == "ZA") {//Afrique du sud - if(dol_strlen($phone) == 12) + if (dol_strlen($phone) == 12) {//ex: +27_AB_CDE_FG_HI $newphone = substr($newphone, 0, 3).$separ.substr($newphone, 3, 2).$separ.substr($newphone, 5, 3).$separ.substr($newphone, 8, 2).$separ.substr($newphone, 10, 2); } } elseif (strtoupper($countrycode) == "SY") {//Syrie - if(dol_strlen($phone) == 12) + if (dol_strlen($phone) == 12) {//ex: +963_AB_CD_EF_GH $newphone = substr($newphone, 0, 4).$separ.substr($newphone, 4, 2).$separ.substr($newphone, 6, 2).$separ.substr($newphone, 8, 2).$separ.substr($newphone, 10, 2); } - elseif(dol_strlen($phone) == 13) + elseif (dol_strlen($phone) == 13) {//ex: +963_AB_CD_EF_GHI $newphone = substr($newphone, 0, 4).$separ.substr($newphone, 4, 2).$separ.substr($newphone, 6, 2).$separ.substr($newphone, 8, 2).$separ.substr($newphone, 10, 3); } } elseif (strtoupper($countrycode) == "AE") {//Emirats Arabes Unis - if(dol_strlen($phone) == 12) + if (dol_strlen($phone) == 12) {//ex: +971_ABC_DEF_GH $newphone = substr($newphone, 0, 4).$separ.substr($newphone, 4, 3).$separ.substr($newphone, 7, 3).$separ.substr($newphone, 10, 2); } - elseif(dol_strlen($phone) == 13) + elseif (dol_strlen($phone) == 13) {//ex: +971_ABC_DEF_GHI $newphone = substr($newphone, 0, 4).$separ.substr($newphone, 4, 3).$separ.substr($newphone, 7, 3).$separ.substr($newphone, 10, 3); } - elseif(dol_strlen($phone) == 14) + elseif (dol_strlen($phone) == 14) {//ex: +971_ABC_DEF_GHIK $newphone = substr($newphone, 0, 4).$separ.substr($newphone, 4, 3).$separ.substr($newphone, 7, 3).$separ.substr($newphone, 10, 4); } } elseif (strtoupper($countrycode) == "DZ") {//Algérie - if(dol_strlen($phone) == 13) + if (dol_strlen($phone) == 13) {//ex: +213_ABC_DEF_GHI $newphone = substr($newphone, 0, 4).$separ.substr($newphone, 4, 3).$separ.substr($newphone, 7, 3).$separ.substr($newphone, 10, 3); } } elseif (strtoupper($countrycode) == "BE") {//Belgique - if(dol_strlen($phone) == 11) + if (dol_strlen($phone) == 11) {//ex: +32_ABC_DE_FGH $newphone = substr($newphone, 0, 3).$separ.substr($newphone, 3, 3).$separ.substr($newphone, 6, 2).$separ.substr($newphone, 8, 3); } - elseif(dol_strlen($phone) == 12) + elseif (dol_strlen($phone) == 12) {//ex: +32_ABC_DEF_GHI $newphone = substr($newphone, 0, 3).$separ.substr($newphone, 3, 3).$separ.substr($newphone, 6, 3).$separ.substr($newphone, 9, 3); } } elseif (strtoupper($countrycode) == "PF") {//Polynésie française - if(dol_strlen($phone) == 12) + if (dol_strlen($phone) == 12) {//ex: +689_AB_CD_EF_GH $newphone = substr($newphone, 0, 4).$separ.substr($newphone, 4, 2).$separ.substr($newphone, 6, 2).$separ.substr($newphone, 8, 2).$separ.substr($newphone, 10, 2); } } elseif (strtoupper($countrycode) == "CO") {//Colombie - if(dol_strlen($phone) == 13) + if (dol_strlen($phone) == 13) {//ex: +57_ABC_DEF_GH_IJ $newphone = substr($newphone, 0, 3).$separ.substr($newphone, 3, 3).$separ.substr($newphone, 6, 3).$separ.substr($newphone, 9, 2).$separ.substr($newphone, 11, 2); } } elseif (strtoupper($countrycode) == "JO") {//Jordanie - if(dol_strlen($phone) == 12) + if (dol_strlen($phone) == 12) {//ex: +962_A_BCD_EF_GH $newphone = substr($newphone, 0, 4).$separ.substr($newphone, 4, 1).$separ.substr($newphone, 5, 3).$separ.substr($newphone, 7, 2).$separ.substr($newphone, 9, 2); } } elseif (strtoupper($countrycode) == "JM") {//Jamaïque - if(dol_strlen($newphone) == 12) + if (dol_strlen($newphone) == 12) {//ex: +1867_ABC_DEFG $newphone = substr($newphone, 0, 5).$separ.substr($newphone, 5, 3).$separ.substr($newphone, 8, 4); } } elseif (strtoupper($countrycode) == "MG") {//Madagascar - if(dol_strlen($phone) == 13) + if (dol_strlen($phone) == 13) {//ex: +261_AB_CD_EF_GHI $newphone = substr($newphone, 0, 4).$separ.substr($newphone, 4, 2).$separ.substr($newphone, 6, 2).$separ.substr($newphone, 8, 2).$separ.substr($newphone, 10, 3); } } elseif (strtoupper($countrycode) == "GB") {//Royaume uni - if(dol_strlen($phone) == 13) + if (dol_strlen($phone) == 13) {//ex: +44_ABCD_EFG_HIJ $newphone = substr($newphone, 0, 3).$separ.substr($newphone, 3, 4).$separ.substr($newphone, 7, 3).$separ.substr($newphone, 10, 3); } } elseif (strtoupper($countrycode) == "CH") {//Suisse - if(dol_strlen($phone) == 12) + if (dol_strlen($phone) == 12) {//ex: +41_AB_CDE_FG_HI $newphone = substr($newphone, 0, 3).$separ.substr($newphone, 3, 2).$separ.substr($newphone, 5, 3).$separ.substr($newphone, 8, 2).$separ.substr($newphone, 10, 2); } - elseif(dol_strlen($phone) == 15) + elseif (dol_strlen($phone) == 15) {// +41_AB_CDE_FGH_IJKL - $newphone =$newphone = substr($newphone, 0, 3).$separ.substr($newphone, 3, 2).$separ.substr($newphone, 5, 3).$separ.substr($newphone, 8, 3).$separ.substr($newphone, 11, 4); + $newphone = $newphone = substr($newphone, 0, 3).$separ.substr($newphone, 3, 2).$separ.substr($newphone, 5, 3).$separ.substr($newphone, 8, 3).$separ.substr($newphone, 11, 4); } } elseif (strtoupper($countrycode) == "TN") {//Tunisie - if(dol_strlen($phone) == 12) + if (dol_strlen($phone) == 12) {//ex: +216_AB_CDE_FGH $newphone = substr($newphone, 0, 4).$separ.substr($newphone, 4, 2).$separ.substr($newphone, 6, 3).$separ.substr($newphone, 9, 3); } } elseif (strtoupper($countrycode) == "GF") {//Guyane francaise - if(dol_strlen($phone) == 13) + if (dol_strlen($phone) == 13) {//ex: +594_ABC_DE_FG_HI (ABC=594 de nouveau) $newphone = substr($newphone, 0, 4).$separ.substr($newphone, 4, 3).$separ.substr($newphone, 7, 2).$separ.substr($newphone, 9, 2).$separ.substr($newphone, 11, 2); } } elseif (strtoupper($countrycode) == "GP") {//Guadeloupe - if(dol_strlen($phone) == 13) + if (dol_strlen($phone) == 13) {//ex: +590_ABC_DE_FG_HI (ABC=590 de nouveau) $newphone = substr($newphone, 0, 4).$separ.substr($newphone, 4, 3).$separ.substr($newphone, 7, 2).$separ.substr($newphone, 9, 2).$separ.substr($newphone, 11, 2); } } elseif (strtoupper($countrycode) == "MQ") {//Martinique - if(dol_strlen($phone) == 13) + if (dol_strlen($phone) == 13) {//ex: +596_ABC_DE_FG_HI (ABC=596 de nouveau) $newphone = substr($newphone, 0, 4).$separ.substr($newphone, 4, 3).$separ.substr($newphone, 7, 2).$separ.substr($newphone, 9, 2).$separ.substr($newphone, 11, 2); } } elseif (strtoupper($countrycode) == "IT") {//Italie - if(dol_strlen($phone) == 12) + if (dol_strlen($phone) == 12) {//ex: +39_ABC_DEF_GHI $newphone = substr($newphone, 0, 3).$separ.substr($newphone, 3, 3).$separ.substr($newphone, 6, 3).$separ.substr($newphone, 9, 3); } - elseif(dol_strlen($phone) == 13) + elseif (dol_strlen($phone) == 13) {//ex: +39_ABC_DEF_GH_IJ $newphone = substr($newphone, 0, 3).$separ.substr($newphone, 3, 3).$separ.substr($newphone, 6, 3).$separ.substr($newphone, 9, 2).$separ.substr($newphone, 11, 2); } } - elseif(strtoupper($countrycode) == "AU") + elseif (strtoupper($countrycode) == "AU") { //Australie - if(dol_strlen($phone) == 12) + if (dol_strlen($phone) == 12) { //ex: +61_A_BCDE_FGHI $newphone = substr($newphone, 0, 3).$separ.substr($newphone, 3, 1).$separ.substr($newphone, 4, 4).$separ.substr($newphone, 8, 4); } } - if (! empty($addlink)) // Link on phone number (+ link to add action if conf->global->AGENDA_ADDACTIONFORPHONE set) + if (!empty($addlink)) // Link on phone number (+ link to add action if conf->global->AGENDA_ADDACTIONFORPHONE set) { - if ($conf->browser->layout == 'phone' || (! empty($conf->clicktodial->enabled) && ! empty($conf->global->CLICKTODIAL_USE_TEL_LINK_ON_PHONE_NUMBERS))) // If phone or option for, we use link of phone + if ($conf->browser->layout == 'phone' || (!empty($conf->clicktodial->enabled) && !empty($conf->global->CLICKTODIAL_USE_TEL_LINK_ON_PHONE_NUMBERS))) // If phone or option for, we use link of phone { - $newphone =''; + $newphone = ''; } - elseif (! empty($conf->clicktodial->enabled) && $addlink == 'AC_TEL') // If click to dial, we use click to dial url + elseif (!empty($conf->clicktodial->enabled) && $addlink == 'AC_TEL') // If click to dial, we use click to dial url { if (empty($user->clicktodial_loaded)) $user->fetch_clicktodial(); // Define urlmask - $urlmask='ErrorClickToDialModuleNotConfigured'; - if (! empty($conf->global->CLICKTODIAL_URL)) $urlmask=$conf->global->CLICKTODIAL_URL; - if (! empty($user->clicktodial_url)) $urlmask=$user->clicktodial_url; + $urlmask = 'ErrorClickToDialModuleNotConfigured'; + if (!empty($conf->global->CLICKTODIAL_URL)) $urlmask = $conf->global->CLICKTODIAL_URL; + if (!empty($user->clicktodial_url)) $urlmask = $user->clicktodial_url; - $clicktodial_poste=(! empty($user->clicktodial_poste)?urlencode($user->clicktodial_poste):''); - $clicktodial_login=(! empty($user->clicktodial_login)?urlencode($user->clicktodial_login):''); - $clicktodial_password=(! empty($user->clicktodial_password)?urlencode($user->clicktodial_password):''); + $clicktodial_poste = (!empty($user->clicktodial_poste) ?urlencode($user->clicktodial_poste) : ''); + $clicktodial_login = (!empty($user->clicktodial_login) ?urlencode($user->clicktodial_login) : ''); + $clicktodial_password = (!empty($user->clicktodial_password) ?urlencode($user->clicktodial_password) : ''); // This line is for backward compatibility $url = sprintf($urlmask, urlencode($phone), $clicktodial_poste, $clicktodial_login, $clicktodial_password); // Thoose lines are for substitution - $substitarray=array('__PHONEFROM__'=>$clicktodial_poste, + $substitarray = array('__PHONEFROM__'=>$clicktodial_poste, '__PHONETO__'=>urlencode($phone), '__LOGIN__'=>$clicktodial_login, '__PASS__'=>$clicktodial_password); $url = make_substitutions($url, $substitarray); - $newphonesav=$newphone; - $newphone ='global->CLICKTODIAL_FORCENEWTARGET)) $newphone.=' target="_blank"'; - $newphone.='>'.$newphonesav.''; + $newphonesav = $newphone; + $newphone = 'global->CLICKTODIAL_FORCENEWTARGET)) $newphone .= ' target="_blank"'; + $newphone .= '>'.$newphonesav.''; } //if (($cid || $socid) && ! empty($conf->agenda->enabled) && $user->rights->agenda->myactions->create) - if (! empty($conf->agenda->enabled) && $user->rights->agenda->myactions->create) + if (!empty($conf->agenda->enabled) && $user->rights->agenda->myactions->create) { - $type='AC_TEL'; $link=''; - if ($addlink == 'AC_FAX') $type='AC_FAX'; - if (! empty($conf->global->AGENDA_ADDACTIONFORPHONE)) $link=''.img_object($langs->trans("AddAction"), "calendar").''; - if ($link) $newphone='
    '.$newphone.' '.$link.'
    '; + $type = 'AC_TEL'; $link = ''; + if ($addlink == 'AC_FAX') $type = 'AC_FAX'; + if (!empty($conf->global->AGENDA_ADDACTIONFORPHONE)) $link = ''.img_object($langs->trans("AddAction"), "calendar").''; + if ($link) $newphone = '
    '.$newphone.' '.$link.'
    '; } } if (empty($titlealt)) { - $titlealt=($withpicto=='fax'?$langs->trans("Fax"):$langs->trans("Phone")); + $titlealt = ($withpicto == 'fax' ? $langs->trans("Fax") : $langs->trans("Phone")); } - $rep=''; + $rep = ''; if ($hookmanager) { - $parameters = array('countrycode' => $countrycode, 'cid' => $cid, 'socid' => $socid,'titlealt' => $titlealt, 'picto' => $withpicto); + $parameters = array('countrycode' => $countrycode, 'cid' => $cid, 'socid' => $socid, 'titlealt' => $titlealt, 'picto' => $withpicto); $reshook = $hookmanager->executeHooks('printPhone', $parameters, $phone); - $rep.=$hookmanager->resPrint; + $rep .= $hookmanager->resPrint; } if (empty($reshook)) { $picto = ''; - if($withpicto){ - if($withpicto=='fax'){ + if ($withpicto) { + if ($withpicto == 'fax') { $picto = 'phoning_fax'; - }elseif($withpicto=='phone'){ + }elseif ($withpicto == 'phone') { $picto = 'phoning'; - }elseif($withpicto=='mobile'){ + }elseif ($withpicto == 'mobile') { $picto = 'phoning_mobile'; - }else{ + } else { $picto = ''; } } - if ($adddivfloat) $rep.='
    '; - else $rep.=''; - $rep.=($withpicto?img_picto($titlealt, 'object_'.$picto.'.png').' ':'').$newphone; - if ($adddivfloat) $rep.='
    '; - else $rep.=''; + if ($adddivfloat) $rep .= '
    '; + else $rep .= ''; + $rep .= ($withpicto ?img_picto($titlealt, 'object_'.$picto.'.png').' ' : '').$newphone; + if ($adddivfloat) $rep .= '
    '; + else $rep .= ''; } return $rep; @@ -2681,22 +2681,22 @@ function dol_print_phone($phone, $countrycode = '', $cid = 0, $socid = 0, $addli */ function dol_print_ip($ip, $mode = 0) { - global $conf,$langs; + global $conf, $langs; - $ret=''; + $ret = ''; - if (empty($mode)) $ret.=$ip; + if (empty($mode)) $ret .= $ip; if ($mode != 2) { - $countrycode=dolGetCountryCodeFromIp($ip); + $countrycode = dolGetCountryCodeFromIp($ip); if ($countrycode) // If success, countrycode is us, fr, ... { if (file_exists(DOL_DOCUMENT_ROOT.'/theme/common/flags/'.$countrycode.'.png')) { - $ret.=' '.img_picto($countrycode.' '.$langs->trans("AccordingToGeoIPDatabase"), DOL_URL_ROOT.'/theme/common/flags/'.$countrycode.'.png', '', 1); + $ret .= ' '.img_picto($countrycode.' '.$langs->trans("AccordingToGeoIPDatabase"), DOL_URL_ROOT.'/theme/common/flags/'.$countrycode.'.png', '', 1); } - else $ret.=' ('.$countrycode.')'; + else $ret .= ' ('.$countrycode.')'; } else { @@ -2717,7 +2717,7 @@ function dol_print_ip($ip, $mode = 0) */ function getUserRemoteIP() { - $ip = empty($_SERVER['HTTP_X_FORWARDED_FOR'])? (empty($_SERVER['HTTP_CLIENT_IP'])?(empty($_SERVER['REMOTE_ADDR'])?'':$_SERVER['REMOTE_ADDR']):$_SERVER['HTTP_CLIENT_IP']) : $_SERVER['HTTP_X_FORWARDED_FOR']; + $ip = empty($_SERVER['HTTP_X_FORWARDED_FOR']) ? (empty($_SERVER['HTTP_CLIENT_IP']) ? (empty($_SERVER['REMOTE_ADDR']) ? '' : $_SERVER['REMOTE_ADDR']) : $_SERVER['HTTP_CLIENT_IP']) : $_SERVER['HTTP_X_FORWARDED_FOR']; return $ip; } @@ -2731,17 +2731,17 @@ function dolGetCountryCodeFromIp($ip) { global $conf; - $countrycode=''; + $countrycode = ''; - if (! empty($conf->geoipmaxmind->enabled)) + if (!empty($conf->geoipmaxmind->enabled)) { - $datafile=$conf->global->GEOIPMAXMIND_COUNTRY_DATAFILE; + $datafile = $conf->global->GEOIPMAXMIND_COUNTRY_DATAFILE; //$ip='24.24.24.24'; //$datafile='/usr/share/GeoIP/GeoIP.dat'; Note that this must be downloaded datafile (not same than datafile provided with ubuntu packages) include_once DOL_DOCUMENT_ROOT.'/core/class/dolgeoip.class.php'; - $geoip=new DolGeoIP('country', $datafile); + $geoip = new DolGeoIP('country', $datafile); //print 'ip='.$ip.' databaseType='.$geoip->gi->databaseType." GEOIP_CITY_EDITION_REV1=".GEOIP_CITY_EDITION_REV1."\n"; - $countrycode=$geoip->getCountryCodeFromIP($ip); + $countrycode = $geoip->getCountryCodeFromIP($ip); } return $countrycode; @@ -2756,20 +2756,20 @@ function dolGetCountryCodeFromIp($ip) */ function dol_user_country() { - global $conf,$langs,$user; + global $conf, $langs, $user; //$ret=$user->xxx; - $ret=''; - if (! empty($conf->geoipmaxmind->enabled)) + $ret = ''; + if (!empty($conf->geoipmaxmind->enabled)) { - $ip=getUserRemoteIP(); - $datafile=$conf->global->GEOIPMAXMIND_COUNTRY_DATAFILE; + $ip = getUserRemoteIP(); + $datafile = $conf->global->GEOIPMAXMIND_COUNTRY_DATAFILE; //$ip='24.24.24.24'; //$datafile='E:\Mes Sites\Web\Admin1\awstats\maxmind\GeoIP.dat'; include_once DOL_DOCUMENT_ROOT.'/core/class/dolgeoip.class.php'; - $geoip=new DolGeoIP('country', $datafile); - $countrycode=$geoip->getCountryCodeFromIP($ip); - $ret=$countrycode; + $geoip = new DolGeoIP('country', $datafile); + $countrycode = $geoip->getCountryCodeFromIP($ip); + $ret = $countrycode; } return $ret; } @@ -2797,32 +2797,32 @@ function dol_print_address($address, $htmlid, $mode, $id, $noprint = 0, $charfor if ($hookmanager) { $parameters = array('element' => $mode, 'id' => $id); $reshook = $hookmanager->executeHooks('printAddress', $parameters, $address); - $out.=$hookmanager->resPrint; + $out .= $hookmanager->resPrint; } if (empty($reshook)) { - if (empty($charfornl)) $out.=nl2br($address); - else $out.=preg_replace('/[\r\n]+/', $charfornl, $address); + if (empty($charfornl)) $out .= nl2br($address); + else $out .= preg_replace('/[\r\n]+/', $charfornl, $address); - $showgmap=$showomap=0; + $showgmap = $showomap = 0; // TODO Add a hook here - if (($mode=='thirdparty' || $mode =='societe') && ! empty($conf->google->enabled) && ! empty($conf->global->GOOGLE_ENABLE_GMAPS)) $showgmap=1; - if ($mode=='contact' && ! empty($conf->google->enabled) && ! empty($conf->global->GOOGLE_ENABLE_GMAPS_CONTACTS)) $showgmap=1; - if ($mode=='member' && ! empty($conf->google->enabled) && ! empty($conf->global->GOOGLE_ENABLE_GMAPS_MEMBERS)) $showgmap=1; - if (($mode=='thirdparty' || $mode =='societe') && ! empty($conf->openstreetmap->enabled) && ! empty($conf->global->OPENSTREETMAP_ENABLE_MAPS)) $showomap=1; - if ($mode=='contact' && ! empty($conf->openstreetmap->enabled) && ! empty($conf->global->OPENSTREETMAP_ENABLE_MAPS_CONTACTS)) $showomap=1; - if ($mode=='member' && ! empty($conf->openstreetmap->enabled) && ! empty($conf->global->OPENSTREETMAP_ENABLE_MAPS_MEMBERS)) $showomap=1; + if (($mode == 'thirdparty' || $mode == 'societe') && !empty($conf->google->enabled) && !empty($conf->global->GOOGLE_ENABLE_GMAPS)) $showgmap = 1; + if ($mode == 'contact' && !empty($conf->google->enabled) && !empty($conf->global->GOOGLE_ENABLE_GMAPS_CONTACTS)) $showgmap = 1; + if ($mode == 'member' && !empty($conf->google->enabled) && !empty($conf->global->GOOGLE_ENABLE_GMAPS_MEMBERS)) $showgmap = 1; + if (($mode == 'thirdparty' || $mode == 'societe') && !empty($conf->openstreetmap->enabled) && !empty($conf->global->OPENSTREETMAP_ENABLE_MAPS)) $showomap = 1; + if ($mode == 'contact' && !empty($conf->openstreetmap->enabled) && !empty($conf->global->OPENSTREETMAP_ENABLE_MAPS_CONTACTS)) $showomap = 1; + if ($mode == 'member' && !empty($conf->openstreetmap->enabled) && !empty($conf->global->OPENSTREETMAP_ENABLE_MAPS_MEMBERS)) $showomap = 1; if ($showgmap) { - $url=dol_buildpath('/google/gmaps.php?mode='.$mode.'&id='.$id, 1); - $out.=' '; + $url = dol_buildpath('/google/gmaps.php?mode='.$mode.'&id='.$id, 1); + $out .= ' '; } if ($showomap) { - $url=dol_buildpath('/openstreetmap/maps.php?mode='.$mode.'&id='.$id, 1); - $out.=' '; + $url = dol_buildpath('/openstreetmap/maps.php?mode='.$mode.'&id='.$id, 1); + $out .= ' '; } } } @@ -2857,17 +2857,17 @@ function isValidMXRecord($domain) { if (function_exists('idn_to_ascii') && function_exists('checkdnsrr')) { - if (! checkdnsrr(idn_to_ascii($domain), 'MX')) + if (!checkdnsrr(idn_to_ascii($domain), 'MX')) { return 0; } if (function_exists('getmxrr')) { - $mxhosts=array(); - $weight=array(); + $mxhosts = array(); + $weight = array(); getmxrr(idn_to_ascii($domain), $mxhosts, $weight); if (count($mxhosts) > 1) return 1; - if (count($mxhosts) == 1 && ! empty($mxhosts[0])) return 1; + if (count($mxhosts) == 1 && !empty($mxhosts[0])) return 1; return 0; } @@ -2915,29 +2915,29 @@ function dol_substr($string, $start, $length, $stringencoding = '', $trunconbyte { global $langs; - if (empty($stringencoding)) $stringencoding=$langs->charset_output; + if (empty($stringencoding)) $stringencoding = $langs->charset_output; - $ret=''; + $ret = ''; if (empty($trunconbytes)) { if (function_exists('mb_substr')) { - $ret=mb_substr($string, $start, $length, $stringencoding); + $ret = mb_substr($string, $start, $length, $stringencoding); } else { - $ret=substr($string, $start, $length); + $ret = substr($string, $start, $length); } } else { if (function_exists('mb_strcut')) { - $ret=mb_strcut($string, $start, $length, $stringencoding); + $ret = mb_strcut($string, $start, $length, $stringencoding); } else { - $ret=substr($string, $start, $length); + $ret = substr($string, $start, $length); } } return $ret; @@ -2961,29 +2961,29 @@ function dol_trunc($string, $size = 40, $trunc = 'right', $stringencoding = 'UTF { global $conf; - if ($size==0 || ! empty($conf->global->MAIN_DISABLE_TRUNC)) return $string; + if ($size == 0 || !empty($conf->global->MAIN_DISABLE_TRUNC)) return $string; - if (empty($stringencoding)) $stringencoding='UTF-8'; + if (empty($stringencoding)) $stringencoding = 'UTF-8'; // reduce for small screen - if ($conf->dol_optimize_smallscreen==1 && $display==1) $size = round($size/3); + if ($conf->dol_optimize_smallscreen == 1 && $display == 1) $size = round($size / 3); // We go always here if ($trunc == 'right') { - $newstring=dol_textishtml($string)?dol_string_nohtmltag($string, 1):$string; - if (dol_strlen($newstring, $stringencoding) > ($size+($nodot?0:3))) // If nodot is 0 and size is 1,2 or 3 chars more, we don't trunc and don't add ... - return dol_substr($newstring, 0, $size, $stringencoding).($nodot?'':'...'); + $newstring = dol_textishtml($string) ?dol_string_nohtmltag($string, 1) : $string; + if (dol_strlen($newstring, $stringencoding) > ($size + ($nodot ? 0 : 3))) // If nodot is 0 and size is 1,2 or 3 chars more, we don't trunc and don't add ... + return dol_substr($newstring, 0, $size, $stringencoding).($nodot ? '' : '...'); else //return 'u'.$size.'-'.$newstring.'-'.dol_strlen($newstring,$stringencoding).'-'.$string; return $string; } elseif ($trunc == 'middle') { - $newstring=dol_textishtml($string)?dol_string_nohtmltag($string, 1):$string; - if (dol_strlen($newstring, $stringencoding) > 2 && dol_strlen($newstring, $stringencoding) > ($size+1)) + $newstring = dol_textishtml($string) ?dol_string_nohtmltag($string, 1) : $string; + if (dol_strlen($newstring, $stringencoding) > 2 && dol_strlen($newstring, $stringencoding) > ($size + 1)) { - $size1=round($size/2); - $size2=round($size/2); + $size1 = round($size / 2); + $size2 = round($size / 2); return dol_substr($newstring, 0, $size1, $stringencoding).'...'.dol_substr($newstring, dol_strlen($newstring, $stringencoding) - $size2, $size2, $stringencoding); } else @@ -2991,17 +2991,17 @@ function dol_trunc($string, $size = 40, $trunc = 'right', $stringencoding = 'UTF } elseif ($trunc == 'left') { - $newstring=dol_textishtml($string)?dol_string_nohtmltag($string, 1):$string; - if (dol_strlen($newstring, $stringencoding) > ($size+($nodot?0:3))) // If nodot is 0 and size is 1,2 or 3 chars more, we don't trunc and don't add ... + $newstring = dol_textishtml($string) ?dol_string_nohtmltag($string, 1) : $string; + if (dol_strlen($newstring, $stringencoding) > ($size + ($nodot ? 0 : 3))) // If nodot is 0 and size is 1,2 or 3 chars more, we don't trunc and don't add ... return '...'.dol_substr($newstring, dol_strlen($newstring, $stringencoding) - $size, $size, $stringencoding); else return $string; } elseif ($trunc == 'wrap') { - $newstring=dol_textishtml($string)?dol_string_nohtmltag($string, 1):$string; - if (dol_strlen($newstring, $stringencoding) > ($size+1)) - return dol_substr($newstring, 0, $size, $stringencoding)."\n".dol_trunc(dol_substr($newstring, $size, dol_strlen($newstring, $stringencoding)-$size, $stringencoding), $size, $trunc); + $newstring = dol_textishtml($string) ?dol_string_nohtmltag($string, 1) : $string; + if (dol_strlen($newstring, $stringencoding) > ($size + 1)) + return dol_substr($newstring, 0, $size, $stringencoding)."\n".dol_trunc(dol_substr($newstring, $size, dol_strlen($newstring, $stringencoding) - $size, $stringencoding), $size, $trunc); else return $string; } @@ -3039,13 +3039,13 @@ function img_picto($titlealt, $picto, $moreatt = '', $pictoisfullpath = false, $ // Define fullpathpicto to use into src if ($pictoisfullpath) { // Clean parameters - if (! preg_match('/(\.png|\.gif|\.svg)$/i', $picto)) { + if (!preg_match('/(\.png|\.gif|\.svg)$/i', $picto)) { $picto .= '.png'; } $fullpathpicto = $picto; - $reg=array(); + $reg = array(); if (preg_match('/class="([^"]+)"/', $moreatt, $reg)) { - $morecss .= ($morecss ? ' ' : '') . $reg[1]; + $morecss .= ($morecss ? ' ' : '').$reg[1]; $moreatt = str_replace('class="'.$reg[1].'"', '', $moreatt); } } else { @@ -3056,25 +3056,25 @@ function img_picto($titlealt, $picto, $moreatt = '', $pictoisfullpath = false, $ '1downarrow', '1uparrow', '1leftarrow', '1rightarrow', '1uparrow_selected', '1downarrow_selected', '1leftarrow_selected', '1rightarrow_selected', 'address', 'bank', 'bookmark', 'building', 'cash-register', 'close_title', 'cubes', 'delete', 'dolly', 'edit', 'ellipsis-h', 'filter', 'file-code', 'grip', 'grip_title', 'list', 'listlight', 'note', - 'object_bookmark', 'object_list','object_calendar', 'object_calendarweek', 'object_calendarmonth', 'object_calendarday', 'object_calendarperuser', + 'object_bookmark', 'object_list', 'object_calendar', 'object_calendarweek', 'object_calendarmonth', 'object_calendarday', 'object_calendarperuser', 'off', 'on', 'play', 'playdisabled', 'printer', 'resize', 'stats', 'note', 'setup', 'sign-out', 'split', 'switch_off', 'switch_on', 'tools', 'unlink', 'uparrow', 'user', 'wrench', 'globe', - 'jabber','skype','twitter','facebook','linkedin', - 'instagram', 'snapchat', 'youtube', 'google-plus-g','whatsapp', - 'chevron-left','chevron-right','chevron-down','chevron-top', + 'jabber', 'skype', 'twitter', 'facebook', 'linkedin', + 'instagram', 'snapchat', 'youtube', 'google-plus-g', 'whatsapp', + 'chevron-left', 'chevron-right', 'chevron-down', 'chevron-top', 'home', 'companies', 'products', 'commercial', 'invoicing', 'accountancy', 'project', 'hrm', 'members', 'ticket', 'generic', - 'error','warning', + 'error', 'warning', 'title_setup', 'title_accountancy', 'title_bank', 'title_hrm', 'title_agenda' ) )) { $fakey = $pictowithouttext; $facolor = ''; $fasize = ''; - $fa='fas'; + $fa = 'fas'; if (in_array($pictowithouttext, array('off', 'on', 'object_bookmark', 'bookmark'))) { - $fa='far'; + $fa = 'far'; } - if (in_array($pictowithouttext, array('skype', 'twitter', 'facebook', 'linkedin', 'instagram','snapchat','youtube','google-plus-g','whatsapp'))) { - $fa='fab'; + if (in_array($pictowithouttext, array('skype', 'twitter', 'facebook', 'linkedin', 'instagram', 'snapchat', 'youtube', 'google-plus-g', 'whatsapp'))) { + $fa = 'fab'; } $arrayconvpictotofa = array( @@ -3082,7 +3082,7 @@ function img_picto($titlealt, $picto, $moreatt = '', $pictoisfullpath = false, $ 'hrm'=>'umbrella-beach', 'members'=>'users', 'ticket'=>'ticket-alt', 'generic'=>'folder-open', 'switch_off'=>'toggle-off', 'switch_on'=>'toggle-on', 'object_bookmark'=>'star', 'bookmark'=>'star', 'stats' => 'chart-bar', 'bank'=>'university', 'close_title'=>'window-close', 'delete'=>'trash', 'edit'=>'pencil', 'filter'=>'filter', 'split'=>'code-fork', - 'object_list'=>'list-alt','object_calendar'=>'calendar-alt', 'object_calendarweek'=>'calendar-week', 'object_calendarmonth'=>'calendar-alt', 'object_calendarday'=>'calendar-day', 'object_calendarperuser'=>'table', + 'object_list'=>'list-alt', 'object_calendar'=>'calendar-alt', 'object_calendarweek'=>'calendar-week', 'object_calendarmonth'=>'calendar-alt', 'object_calendarday'=>'calendar-day', 'object_calendarperuser'=>'table', 'error'=>'exclamation-triangle', 'warning'=>'exclamation-triangle', 'title_setup'=>'tools', 'title_accountancy'=>'money-check-alt', 'title_bank'=>'university', 'title_hrm'=>'umbrella-beach', 'title_agenda'=>'calendar-alt' ); @@ -3129,7 +3129,7 @@ function img_picto($titlealt, $picto, $moreatt = '', $pictoisfullpath = false, $ elseif ($pictowithouttext == 'listlight') { $fakey = 'fa-download'; $facolor = '#999'; - $marginleftonlyshort=1; + $marginleftonlyshort = 1; } elseif ($pictowithouttext == 'printer') { $fakey = 'fa-print'; @@ -3144,21 +3144,21 @@ function img_picto($titlealt, $picto, $moreatt = '', $pictoisfullpath = false, $ $fakey = 'fa-sticky-note'; $fa = 'far'; $facolor = '#999'; - $marginleftonlyshort=1; + $marginleftonlyshort = 1; } elseif ($pictowithouttext == 'uparrow') { $fakey = 'fa-mail-forward'; $facolor = '#555'; } elseif (in_array($pictowithouttext, array('1uparrow', '1downarrow', '1leftarrow', '1rightarrow', '1uparrow_selected', '1downarrow_selected', '1leftarrow_selected', '1rightarrow_selected'))) { - $convertarray=array('1uparrow'=>'caret-up', '1downarrow'=>'caret-down', '1leftarrow'=>'caret-left', '1rightarrow'=>'caret-right', '1uparrow_selected'=>'caret-up', '1downarrow_selected'=>'caret-down', '1leftarrow_selected'=>'caret-left', '1rightarrow_selected'=>'caret-right'); + $convertarray = array('1uparrow'=>'caret-up', '1downarrow'=>'caret-down', '1leftarrow'=>'caret-left', '1rightarrow'=>'caret-right', '1uparrow_selected'=>'caret-up', '1downarrow_selected'=>'caret-down', '1leftarrow_selected'=>'caret-left', '1rightarrow_selected'=>'caret-right'); $fakey = 'fa-'.$convertarray[$pictowithouttext]; if (preg_match('/selected/', $pictowithouttext)) $facolor = '#888'; $marginleftonlyshort = 1; } elseif ($pictowithouttext == 'sign-out') { $fakey = 'fa-sign-out-alt'; - $marginleftonlyshort=0; + $marginleftonlyshort = 0; } elseif ($pictowithouttext == 'unlink') { $fakey = 'fa-unlink'; @@ -3178,61 +3178,61 @@ function img_picto($titlealt, $picto, $moreatt = '', $pictoisfullpath = false, $ // Img for type of views elseif (in_array($pictowithouttext, array('object_list', 'object_calendar', 'object_calendarweek', 'object_calendarmonth', 'object_calendarday', 'object_calendarperuser'))) { $fakey = 'imgforviewmode fa-'.$arrayconvpictotofa[$pictowithouttext]; - $marginleftonlyshort=0; + $marginleftonlyshort = 0; } - elseif (! empty($arrayconvpictotofa[$pictowithouttext])) + elseif (!empty($arrayconvpictotofa[$pictowithouttext])) { $fakey = 'fa-'.$arrayconvpictotofa[$pictowithouttext]; //$facolor = '#444'; - $marginleftonlyshort=0; + $marginleftonlyshort = 0; } else { $fakey = 'fa-'.$pictowithouttext; //$facolor = '#444'; - $marginleftonlyshort=0; + $marginleftonlyshort = 0; } //this snippet only needed since function img_edit accepts only one additional parameter: no separate one for css only. //class/style need to be extracted to avoid duplicate class/style validation errors when $moreatt is added to the end of the attributes - $reg=array(); + $reg = array(); if (preg_match('/class="([^"]+)"/', $moreatt, $reg)) { - $morecss .= ($morecss ? ' ' : '') . $reg[1]; + $morecss .= ($morecss ? ' ' : '').$reg[1]; $moreatt = str_replace('class="'.$reg[1].'"', '', $moreatt); } if (preg_match('/style="([^"]+)"/', $moreatt, $reg)) { - $morestyle = ' '. $reg[1]; + $morestyle = ' '.$reg[1]; $moreatt = str_replace('style="'.$reg[1].'"', '', $moreatt); } - $moreatt=trim($moreatt); + $moreatt = trim($moreatt); - $enabledisablehtml = ''; - if (! empty($conf->global->MAIN_OPTIMIZEFORTEXTBROWSER)) { - $enabledisablehtml.= $titlealt; + $enabledisablehtml = ''; + if (!empty($conf->global->MAIN_OPTIMIZEFORTEXTBROWSER)) { + $enabledisablehtml .= $titlealt; } - $enabledisablehtml.= ''; + $enabledisablehtml .= ''; return $enabledisablehtml; } - if (! empty($conf->global->MAIN_OVERWRITE_THEME_PATH)) { - $path = $conf->global->MAIN_OVERWRITE_THEME_PATH.'/theme/'.$theme; // If the theme does not have the same name as the module + if (!empty($conf->global->MAIN_OVERWRITE_THEME_PATH)) { + $path = $conf->global->MAIN_OVERWRITE_THEME_PATH.'/theme/'.$theme; // If the theme does not have the same name as the module } - elseif (! empty($conf->global->MAIN_OVERWRITE_THEME_RES)) { - $path = $conf->global->MAIN_OVERWRITE_THEME_RES.'/theme/'.$conf->global->MAIN_OVERWRITE_THEME_RES; // To allow an external module to overwrite image resources whatever is activated theme + elseif (!empty($conf->global->MAIN_OVERWRITE_THEME_RES)) { + $path = $conf->global->MAIN_OVERWRITE_THEME_RES.'/theme/'.$conf->global->MAIN_OVERWRITE_THEME_RES; // To allow an external module to overwrite image resources whatever is activated theme } - elseif (! empty($conf->modules_parts['theme']) && array_key_exists($theme, $conf->modules_parts['theme'])) { - $path = $theme.'/theme/'.$theme; // If the theme have the same name as the module + elseif (!empty($conf->modules_parts['theme']) && array_key_exists($theme, $conf->modules_parts['theme'])) { + $path = $theme.'/theme/'.$theme; // If the theme have the same name as the module } // If we ask an image into $url/$mymodule/img (instead of default path) if (preg_match('/^([^@]+)@([^@]+)$/i', $picto, $regs)) { $picto = $regs[1]; - $path = $regs[2]; // $path is $mymodule + $path = $regs[2]; // $path is $mymodule } // Clean parameters - if (! preg_match('/(\.png|\.gif|\.svg)$/i', $picto)) { + if (!preg_match('/(\.png|\.gif|\.svg)$/i', $picto)) { $picto .= '.png'; } // If alt path are defined, define url where img file is, according to physical path @@ -3256,7 +3256,7 @@ function img_picto($titlealt, $picto, $moreatt = '', $pictoisfullpath = false, $ return $fullpathpicto; } // tag title is used for tooltip on , tag alt can be used with very simple text on image for blind people - return ''.dol_escape_htmltag($alt).''; // Alt is used for accessibility, title for popup + return ''.dol_escape_htmltag($alt).''; // Alt is used for accessibility, title for popup } /** @@ -3294,11 +3294,11 @@ function img_weather($titlealt, $picto, $moreatt = '', $pictoisfullpath = 0, $mo if (is_numeric($picto)) { - $leveltopicto=array(0=>'weather-clear.png', 1=>'weather-few-clouds.png', 2=>'weather-clouds.png', 3=>'weather-many-clouds.png', 4=>'weather-storm.png'); + $leveltopicto = array(0=>'weather-clear.png', 1=>'weather-few-clouds.png', 2=>'weather-clouds.png', 3=>'weather-many-clouds.png', 4=>'weather-storm.png'); //return ''; $picto = $leveltopicto[$picto]; } - elseif (! preg_match('/(\.png|\.gif)$/i', $picto)) $picto .= '.png'; + elseif (!preg_match('/(\.png|\.gif)$/i', $picto)) $picto .= '.png'; $path = DOL_URL_ROOT.'/theme/'.$conf->theme.'/img/weather/'.$picto; @@ -3319,14 +3319,14 @@ function img_picto_common($titlealt, $picto, $moreatt = '', $pictoisfullpath = 0 { global $conf; - if (! preg_match('/(\.png|\.gif)$/i', $picto)) $picto .= '.png'; + if (!preg_match('/(\.png|\.gif)$/i', $picto)) $picto .= '.png'; if ($pictoisfullpath) $path = $picto; else { $path = DOL_URL_ROOT.'/theme/common/'.$picto; - if (! empty($conf->global->MAIN_MODULE_CAN_OVERWRITE_COMMONICONS)) + if (!empty($conf->global->MAIN_MODULE_CAN_OVERWRITE_COMMONICONS)) { $themepath = DOL_DOCUMENT_ROOT.'/theme/'.$conf->theme.'/img/'.$picto; @@ -3350,14 +3350,14 @@ function img_action($titlealt, $numaction) if (empty($titlealt) || $titlealt == 'default') { - if ($numaction == '-1' || $numaction == 'ST_NO') { $numaction = -1; $titlealt = $langs->transnoentitiesnoconv('ChangeDoNotContact'); } - elseif ($numaction == '0' || $numaction == 'ST_NEVER') { $numaction = 0; $titlealt = $langs->transnoentitiesnoconv('ChangeNeverContacted'); } - elseif ($numaction == '1' || $numaction == 'ST_TODO') { $numaction = 1; $titlealt = $langs->transnoentitiesnoconv('ChangeToContact'); } - elseif ($numaction == '2' || $numaction == 'ST_PEND') { $numaction = 2; $titlealt = $langs->transnoentitiesnoconv('ChangeContactInProcess'); } - elseif ($numaction == '3' || $numaction == 'ST_DONE') { $numaction = 3; $titlealt = $langs->transnoentitiesnoconv('ChangeContactDone'); } + if ($numaction == '-1' || $numaction == 'ST_NO') { $numaction = -1; $titlealt = $langs->transnoentitiesnoconv('ChangeDoNotContact'); } + elseif ($numaction == '0' || $numaction == 'ST_NEVER') { $numaction = 0; $titlealt = $langs->transnoentitiesnoconv('ChangeNeverContacted'); } + elseif ($numaction == '1' || $numaction == 'ST_TODO') { $numaction = 1; $titlealt = $langs->transnoentitiesnoconv('ChangeToContact'); } + elseif ($numaction == '2' || $numaction == 'ST_PEND') { $numaction = 2; $titlealt = $langs->transnoentitiesnoconv('ChangeContactInProcess'); } + elseif ($numaction == '3' || $numaction == 'ST_DONE') { $numaction = 3; $titlealt = $langs->transnoentitiesnoconv('ChangeContactDone'); } else { $titlealt = $langs->transnoentitiesnoconv('ChangeStatus '.$numaction); $numaction = 0; } } - if (! is_numeric($numaction)) $numaction=0; + if (!is_numeric($numaction)) $numaction = 0; return img_picto($titlealt, 'stcomm'.$numaction.'.png'); } @@ -3423,7 +3423,7 @@ function img_edit($titlealt = 'default', $float = 0, $other = '') if ($titlealt == 'default') $titlealt = $langs->trans('Modify'); - return img_picto($titlealt, 'edit.png', ($float ? 'style="float: '.($langs->tab_translate["DIRECTION"] == 'rtl'?'left':'right').'"' : "") . ($other?' '.$other:'')); + return img_picto($titlealt, 'edit.png', ($float ? 'style="float: '.($langs->tab_translate["DIRECTION"] == 'rtl' ? 'left' : 'right').'"' : "").($other ? ' '.$other : '')); } /** @@ -3471,8 +3471,8 @@ function img_delete($titlealt = 'default', $other = 'class="pictodelete"') */ function img_printer($titlealt = "default", $other = '') { - global $conf,$langs; - if ($titlealt=="default") $titlealt=$langs->trans("Print"); + global $conf, $langs; + if ($titlealt == "default") $titlealt = $langs->trans("Print"); return img_picto($titlealt, 'printer.png', $other); } @@ -3509,7 +3509,7 @@ function img_help($usehelpcursor = 1, $usealttitle = 1) else $usealttitle = $langs->trans('Info'); } - return img_picto($usealttitle, 'info.png', 'style="vertical-align: middle;'.($usehelpcursor == 1 ? ' cursor: help': ($usehelpcursor == 2 ? ' cursor: pointer':'')).'"'); + return img_picto($usealttitle, 'info.png', 'style="vertical-align: middle;'.($usehelpcursor == 1 ? ' cursor: help' : ($usehelpcursor == 2 ? ' cursor: pointer' : '')).'"'); } /** @@ -3542,7 +3542,7 @@ function img_warning($titlealt = 'default', $moreatt = '', $morecss = 'pictowarn if ($titlealt == 'default') $titlealt = $langs->trans('Warning'); //return '
    '.img_picto($titlealt, 'warning_white.png', 'class="pictowarning valignmiddle"'.($moreatt ? ($moreatt == '1' ? ' style="float: right"' : ' '.$moreatt): '')).'
    '; - return img_picto($titlealt, 'warning.png', 'class="'.$morecss.'"'.($moreatt ? ($moreatt == '1' ? ' style="float: right"' : ' '.$moreatt): '')); + return img_picto($titlealt, 'warning.png', 'class="'.$morecss.'"'.($moreatt ? ($moreatt == '1' ? ' style="float: right"' : ' '.$moreatt) : '')); } /** @@ -3608,7 +3608,7 @@ function img_down($titlealt = 'default', $selected = 0, $moreclass = '') if ($titlealt == 'default') $titlealt = $langs->trans('Down'); - return img_picto($titlealt, ($selected ? '1downarrow_selected.png' : '1downarrow.png'), 'class="imgdown'.($moreclass?" ".$moreclass:"").'"'); + return img_picto($titlealt, ($selected ? '1downarrow_selected.png' : '1downarrow.png'), 'class="imgdown'.($moreclass ? " ".$moreclass : "").'"'); } /** @@ -3625,7 +3625,7 @@ function img_up($titlealt = 'default', $selected = 0, $moreclass = '') if ($titlealt == 'default') $titlealt = $langs->trans('Up'); - return img_picto($titlealt, ($selected ? '1uparrow_selected.png' : '1uparrow.png'), 'class="imgup'.($moreclass?" ".$moreclass:"").'"'); + return img_picto($titlealt, ($selected ? '1uparrow_selected.png' : '1uparrow.png'), 'class="imgup'.($moreclass ? " ".$moreclass : "").'"'); } /** @@ -3688,13 +3688,13 @@ function img_allow($allow, $titlealt = 'default') */ function img_credit_card($brand) { - if ($brand == 'visa' || $brand == 'Visa') {$brand='cc-visa';} - elseif ($brand == 'mastercard' || $brand == 'MasterCard') {$brand='cc-mastercard';} - elseif ($brand == 'amex' || $brand == 'American Express') {$brand='cc-amex';} - elseif ($brand == 'discover' || $brand == 'Discover') {$brand='cc-discover';} - elseif ($brand == 'jcb' || $brand == 'JCB') {$brand='cc-jcb';} - elseif ($brand == 'diners' || $brand == 'Diners club') {$brand='cc-diners-club';} - elseif (! in_array($brand, array('cc-visa','cc-mastercard','cc-amex','cc-discover','cc-jcb','cc-diners-club'))) {$brand='credit-card';} + if ($brand == 'visa' || $brand == 'Visa') {$brand = 'cc-visa'; } + elseif ($brand == 'mastercard' || $brand == 'MasterCard') {$brand = 'cc-mastercard'; } + elseif ($brand == 'amex' || $brand == 'American Express') {$brand = 'cc-amex'; } + elseif ($brand == 'discover' || $brand == 'Discover') {$brand = 'cc-discover'; } + elseif ($brand == 'jcb' || $brand == 'JCB') {$brand = 'cc-jcb'; } + elseif ($brand == 'diners' || $brand == 'Diners club') {$brand = 'cc-diners-club'; } + elseif (!in_array($brand, array('cc-visa', 'cc-mastercard', 'cc-amex', 'cc-discover', 'cc-jcb', 'cc-diners-club'))) {$brand = 'credit-card'; } return ''; } @@ -3738,7 +3738,7 @@ function img_search($titlealt = 'default', $other = '') $img = img_picto($titlealt, 'search.png', $other, false, 1); $input = ''; + $input .= 'value="'.dol_escape_htmltag($titlealt).'" title="'.dol_escape_htmltag($titlealt).'" >'; return $input; } @@ -3759,7 +3759,7 @@ function img_searchclear($titlealt = 'default', $other = '') $img = img_picto($titlealt, 'searchclear.png', $other, false, 1); $input = ''; + $input .= 'value="'.dol_escape_htmltag($titlealt).'" title="'.dol_escape_htmltag($titlealt).'" >'; return $input; } @@ -3780,10 +3780,10 @@ function info_admin($text, $infoonimgalt = 0, $nodiv = 0, $admin = '1', $morecss if ($infoonimgalt) { - return img_picto($text, 'info', 'class="hideonsmartphone'.($morecss?' '.$morecss:'').'"'); + return img_picto($text, 'info', 'class="hideonsmartphone'.($morecss ? ' '.$morecss : '').'"'); } - return ($nodiv?'':'
    ').' '.$text.($nodiv?'':'
    '); + return ($nodiv ? '' : '
    ').' '.$text.($nodiv ? '' : '
    '); } @@ -3800,16 +3800,16 @@ function info_admin($text, $infoonimgalt = 0, $nodiv = 0, $admin = '1', $morecss */ function dol_print_error($db = '', $error = '', $errors = null) { - global $conf,$langs,$argv; + global $conf, $langs, $argv; global $dolibarr_main_prod; $out = ''; $syslog = ''; // Si erreur intervenue avant chargement langue - if (! $langs) + if (!$langs) { - require_once DOL_DOCUMENT_ROOT .'/core/class/translate.class.php'; + require_once DOL_DOCUMENT_ROOT.'/core/class/translate.class.php'; $langs = new Translate('', $conf); $langs->load("main"); } @@ -3818,62 +3818,62 @@ function dol_print_error($db = '', $error = '', $errors = null) if ($_SERVER['DOCUMENT_ROOT']) // Mode web { - $out.=$langs->trans("DolibarrHasDetectedError").".
    \n"; - if (! empty($conf->global->MAIN_FEATURES_LEVEL)) $out.="You use an experimental or develop level of features, so please do NOT report any bugs, except if problem is confirmed moving option MAIN_FEATURES_LEVEL back to 0.
    \n"; - $out.=$langs->trans("InformationToHelpDiagnose").":
    \n"; + $out .= $langs->trans("DolibarrHasDetectedError").".
    \n"; + if (!empty($conf->global->MAIN_FEATURES_LEVEL)) $out .= "You use an experimental or develop level of features, so please do NOT report any bugs, except if problem is confirmed moving option MAIN_FEATURES_LEVEL back to 0.
    \n"; + $out .= $langs->trans("InformationToHelpDiagnose").":
    \n"; - $out.="".$langs->trans("Date").": ".dol_print_date(time(), 'dayhourlog')."
    \n"; - $out.="".$langs->trans("Dolibarr").": ".DOL_VERSION."
    \n"; - if (isset($conf->global->MAIN_FEATURES_LEVEL)) $out.="".$langs->trans("LevelOfFeature").": ".$conf->global->MAIN_FEATURES_LEVEL."
    \n"; + $out .= "".$langs->trans("Date").": ".dol_print_date(time(), 'dayhourlog')."
    \n"; + $out .= "".$langs->trans("Dolibarr").": ".DOL_VERSION."
    \n"; + if (isset($conf->global->MAIN_FEATURES_LEVEL)) $out .= "".$langs->trans("LevelOfFeature").": ".$conf->global->MAIN_FEATURES_LEVEL."
    \n"; if (function_exists("phpversion")) { - $out.="".$langs->trans("PHP").": ".phpversion()."
    \n"; + $out .= "".$langs->trans("PHP").": ".phpversion()."
    \n"; } - $out.="".$langs->trans("Server").": ".$_SERVER["SERVER_SOFTWARE"]."
    \n"; + $out .= "".$langs->trans("Server").": ".$_SERVER["SERVER_SOFTWARE"]."
    \n"; if (function_exists("php_uname")) { - $out.="".$langs->trans("OS").": ".php_uname()."
    \n"; + $out .= "".$langs->trans("OS").": ".php_uname()."
    \n"; } - $out.="".$langs->trans("UserAgent").": ".$_SERVER["HTTP_USER_AGENT"]."
    \n"; - $out.="
    \n"; - $out.="".$langs->trans("RequestedUrl").": ".dol_htmlentities($_SERVER["REQUEST_URI"], ENT_COMPAT, 'UTF-8')."
    \n"; - $out.="".$langs->trans("Referer").": ".(isset($_SERVER["HTTP_REFERER"])?dol_htmlentities($_SERVER["HTTP_REFERER"], ENT_COMPAT, 'UTF-8'):'')."
    \n"; - $out.="".$langs->trans("MenuManager").": ".(isset($conf->standard_menu)?$conf->standard_menu:'')."
    \n"; - $out.="
    \n"; - $syslog.="url=".dol_escape_htmltag($_SERVER["REQUEST_URI"]); - $syslog.=", query_string=".dol_escape_htmltag($_SERVER["QUERY_STRING"]); + $out .= "".$langs->trans("UserAgent").": ".$_SERVER["HTTP_USER_AGENT"]."
    \n"; + $out .= "
    \n"; + $out .= "".$langs->trans("RequestedUrl").": ".dol_htmlentities($_SERVER["REQUEST_URI"], ENT_COMPAT, 'UTF-8')."
    \n"; + $out .= "".$langs->trans("Referer").": ".(isset($_SERVER["HTTP_REFERER"]) ?dol_htmlentities($_SERVER["HTTP_REFERER"], ENT_COMPAT, 'UTF-8') : '')."
    \n"; + $out .= "".$langs->trans("MenuManager").": ".(isset($conf->standard_menu) ? $conf->standard_menu : '')."
    \n"; + $out .= "
    \n"; + $syslog .= "url=".dol_escape_htmltag($_SERVER["REQUEST_URI"]); + $syslog .= ", query_string=".dol_escape_htmltag($_SERVER["QUERY_STRING"]); } else // Mode CLI { - $out.='> '.$langs->transnoentities("ErrorInternalErrorDetected").":\n".$argv[0]."\n"; - $syslog.="pid=".dol_getmypid(); + $out .= '> '.$langs->transnoentities("ErrorInternalErrorDetected").":\n".$argv[0]."\n"; + $syslog .= "pid=".dol_getmypid(); } - if (! empty($conf->modules)) + if (!empty($conf->modules)) { - $out.="".$langs->trans("Modules").": ".join(', ', $conf->modules)."
    \n"; + $out .= "".$langs->trans("Modules").": ".join(', ', $conf->modules)."
    \n"; } if (is_object($db)) { if ($_SERVER['DOCUMENT_ROOT']) // Mode web { - $out.="".$langs->trans("DatabaseTypeManager").": ".$db->type."
    \n"; - $out.="".$langs->trans("RequestLastAccessInError").": ".($db->lastqueryerror()?dol_escape_htmltag($db->lastqueryerror()):$langs->trans("ErrorNoRequestInError"))."
    \n"; - $out.="".$langs->trans("ReturnCodeLastAccessInError").": ".($db->lasterrno()?dol_escape_htmltag($db->lasterrno()):$langs->trans("ErrorNoRequestInError"))."
    \n"; - $out.="".$langs->trans("InformationLastAccessInError").": ".($db->lasterror()?dol_escape_htmltag($db->lasterror()):$langs->trans("ErrorNoRequestInError"))."
    \n"; - $out.="
    \n"; + $out .= "".$langs->trans("DatabaseTypeManager").": ".$db->type."
    \n"; + $out .= "".$langs->trans("RequestLastAccessInError").": ".($db->lastqueryerror() ?dol_escape_htmltag($db->lastqueryerror()) : $langs->trans("ErrorNoRequestInError"))."
    \n"; + $out .= "".$langs->trans("ReturnCodeLastAccessInError").": ".($db->lasterrno() ?dol_escape_htmltag($db->lasterrno()) : $langs->trans("ErrorNoRequestInError"))."
    \n"; + $out .= "".$langs->trans("InformationLastAccessInError").": ".($db->lasterror() ?dol_escape_htmltag($db->lasterror()) : $langs->trans("ErrorNoRequestInError"))."
    \n"; + $out .= "
    \n"; } else // Mode CLI { // No dol_escape_htmltag for output, we are in CLI mode - $out.='> '.$langs->transnoentities("DatabaseTypeManager").":\n".$db->type."\n"; - $out.='> '.$langs->transnoentities("RequestLastAccessInError").":\n".($db->lastqueryerror()?$db->lastqueryerror():$langs->transnoentities("ErrorNoRequestInError"))."\n"; - $out.='> '.$langs->transnoentities("ReturnCodeLastAccessInError").":\n".($db->lasterrno()?$db->lasterrno():$langs->transnoentities("ErrorNoRequestInError"))."\n"; - $out.='> '.$langs->transnoentities("InformationLastAccessInError").":\n".($db->lasterror()?$db->lasterror():$langs->transnoentities("ErrorNoRequestInError"))."\n"; + $out .= '> '.$langs->transnoentities("DatabaseTypeManager").":\n".$db->type."\n"; + $out .= '> '.$langs->transnoentities("RequestLastAccessInError").":\n".($db->lastqueryerror() ? $db->lastqueryerror() : $langs->transnoentities("ErrorNoRequestInError"))."\n"; + $out .= '> '.$langs->transnoentities("ReturnCodeLastAccessInError").":\n".($db->lasterrno() ? $db->lasterrno() : $langs->transnoentities("ErrorNoRequestInError"))."\n"; + $out .= '> '.$langs->transnoentities("InformationLastAccessInError").":\n".($db->lasterror() ? $db->lasterror() : $langs->transnoentities("ErrorNoRequestInError"))."\n"; } - $syslog.=", sql=".$db->lastquery(); - $syslog.=", db_error=".$db->lasterror(); + $syslog .= ", sql=".$db->lastquery(); + $syslog .= ", db_error=".$db->lasterror(); } if ($error || $errors) @@ -3881,33 +3881,33 @@ function dol_print_error($db = '', $error = '', $errors = null) $langs->load("errors"); // Merge all into $errors array - if (is_array($error) && is_array($errors)) $errors=array_merge($error, $errors); - elseif (is_array($error)) $errors=$error; - elseif (is_array($errors)) $errors=array_merge(array($error), $errors); - else $errors=array_merge(array($error)); + if (is_array($error) && is_array($errors)) $errors = array_merge($error, $errors); + elseif (is_array($error)) $errors = $error; + elseif (is_array($errors)) $errors = array_merge(array($error), $errors); + else $errors = array_merge(array($error)); - foreach($errors as $msg) + foreach ($errors as $msg) { if (empty($msg)) continue; if ($_SERVER['DOCUMENT_ROOT']) // Mode web { - $out.="".$langs->trans("Message").": ".dol_escape_htmltag($msg)."
    \n" ; + $out .= "".$langs->trans("Message").": ".dol_escape_htmltag($msg)."
    \n"; } else // Mode CLI { - $out.='> '.$langs->transnoentities("Message").":\n".$msg."\n" ; + $out .= '> '.$langs->transnoentities("Message").":\n".$msg."\n"; } - $syslog.=", msg=".$msg; + $syslog .= ", msg=".$msg; } } if (empty($dolibarr_main_prod) && $_SERVER['DOCUMENT_ROOT'] && function_exists('xdebug_print_function_stack') && function_exists('xdebug_call_file')) { xdebug_print_function_stack(); - $out.='XDebug informations:'."
    \n"; - $out.='File: '.xdebug_call_file()."
    \n"; - $out.='Line: '.xdebug_call_line()."
    \n"; - $out.='Function: '.xdebug_call_function()."
    \n"; - $out.="
    \n"; + $out .= 'XDebug informations:'."
    \n"; + $out .= 'File: '.xdebug_call_file()."
    \n"; + $out .= 'Line: '.xdebug_call_line()."
    \n"; + $out .= 'Function: '.xdebug_call_function()."
    \n"; + $out .= "
    \n"; } if (empty($dolibarr_main_prod)) print $out; @@ -3935,19 +3935,19 @@ function dol_print_error($db = '', $error = '', $errors = null) */ function dol_print_error_email($prefixcode, $errormessage = '', $errormessages = array(), $morecss = 'error', $email = '') { - global $langs,$conf; + global $langs, $conf; - if (empty($email)) $email=$conf->global->MAIN_INFO_SOCIETE_MAIL; + if (empty($email)) $email = $conf->global->MAIN_INFO_SOCIETE_MAIL; $langs->load("errors"); - $now=dol_now(); + $now = dol_now(); print '
    '."\n"; return $return; } @@ -4187,14 +4187,14 @@ function load_fiche_titre($titre, $morehtmlright = '', $picto = 'generic', $pict */ function print_barre_liste($titre, $page, $file, $options = '', $sortfield = '', $sortorder = '', $morehtmlcenter = '', $num = -1, $totalnboflines = '', $picto = 'generic', $pictoisfullpath = 0, $morehtmlright = '', $morecss = '', $limit = -1, $hideselectlimit = 0, $hidenavigation = 0) { - global $conf,$langs; + global $conf, $langs; $savlimit = $limit; $savtotalnboflines = $totalnboflines; - $totalnboflines=abs($totalnboflines); + $totalnboflines = abs($totalnboflines); - if ($picto == 'setup') $picto='title_setup.png'; - if (($conf->browser->name == 'ie') && $picto=='generic') $picto='title.gif'; + if ($picto == 'setup') $picto = 'title_setup.png'; + if (($conf->browser->name == 'ie') && $picto == 'generic') $picto = 'title.gif'; if ($limit < 0) $limit = $conf->liste_limit; if ($savlimit != 0 && (($num > $limit) || ($num == -1) || ($limit == 0))) { @@ -4208,7 +4208,7 @@ function print_barre_liste($titre, $page, $file, $options = '', $sortfield = '', print "\n"; print "\n"; - print ''; // maring bottom must be same than into load_fiche_tire + print '
    '; // maring bottom must be same than into load_fiche_tire // Left print ''; @@ -4302,34 +4304,32 @@ function print_fleche_navigation($page, $file, $options = '', $nextpage = 0, $be global $conf, $langs; print '
    '; @@ -4234,48 +4234,50 @@ function print_barre_liste($titre, $page, $file, $options = '', $sortfield = '', if ($totalnboflines) // If we know total nb of lines { // Define nb of extra page links before and after selected page + ... + first or last - $maxnbofpage=(empty($conf->dol_optimize_smallscreen) ? 4 : 1); + $maxnbofpage = (empty($conf->dol_optimize_smallscreen) ? 4 : 1); - if ($limit > 0) $nbpages=ceil($totalnboflines/$limit); - else $nbpages=1; - $cpt=($page-$maxnbofpage); - if ($cpt < 0) { $cpt=0; } + if ($limit > 0) $nbpages = ceil($totalnboflines / $limit); + else $nbpages = 1; + $cpt = ($page - $maxnbofpage); + if ($cpt < 0) { $cpt = 0; } - if ($cpt>=1) + if ($cpt >= 1) { - $pagelist.= ''; - if ($cpt > 2) $pagelist.=''; - elseif ($cpt == 2) $pagelist.=''; + $pagelist .= ''; + if ($cpt > 2) $pagelist .= ''; + elseif ($cpt == 2) $pagelist .= ''; } do { - if ($cpt==$page) + if ($cpt == $page) { - $pagelist.= ''; + $pagelist .= ''; } else { - $pagelist.= ''; + $pagelist .= ''; } $cpt++; } - while ($cpt < $nbpages && $cpt<=$page+$maxnbofpage); + while ($cpt < $nbpages && $cpt <= $page + $maxnbofpage); - if ($cpt<$nbpages) + if ($cpt < $nbpages) { - if ($cpt<$nbpages-2) $pagelist.= ''; - elseif ($cpt == $nbpages-2) $pagelist.= ''; - $pagelist.= ''; + if ($cpt < $nbpages - 2) $pagelist .= ''; + elseif ($cpt == $nbpages - 2) $pagelist .= ''; + $pagelist .= ''; } } else { - $pagelist.= '"; + $pagelist .= '"; } } - print_fleche_navigation($page, $file, $options, $nextpage, $pagelist, $morehtmlright, $savlimit, $totalnboflines, $hideselectlimit); // output the div and ul for previous/last completed with page numbers into $pagelist + if ($savlimit || $morehtmlright) { + print_fleche_navigation($page, $file, $options, $nextpage, $pagelist, $morehtmlright, $savlimit, $totalnboflines, $hideselectlimit); // output the div and ul for previous/last completed with page numbers into $pagelist + } print '
    '; // Import key - if (! empty($object->import_key)) + if (!empty($object->import_key)) { if ($usetable) print ''; else print '
    '; } // User change (old method using already loaded object and not id is kept for backward compatibility) - if (! empty($object->user_modification) || ! empty($object->user_modification_id)) + if (!empty($object->user_modification) || !empty($object->user_modification_id)) { if ($usetable) print ''; else print '
    '; } // User validation (old method using already loaded object and not id is kept for backward compatibility) - if (! empty($object->user_validation) || ! empty($object->user_validation_id)) + if (!empty($object->user_validation) || !empty($object->user_validation_id)) { if ($usetable) print ''; else print '
    '; } // User approve (old method using already loaded object and not id is kept for backward compatibility) - if (! empty($object->user_approve) || ! empty($object->user_approve_id)) + if (!empty($object->user_approve) || !empty($object->user_approve_id)) { if ($usetable) print ''; else print '
    '; } // User approve - if (! empty($object->user_approve_id2)) + if (!empty($object->user_approve_id2)) { if ($usetable) print ''; else print '
    '; } // User close - if (! empty($object->user_cloture)) + if (!empty($object->user_cloture)) { if ($usetable) print ''; else print '
    '; } // User conciliate - if (! empty($object->user_rappro)) + if (!empty($object->user_rappro)) { if ($usetable) print ''; else print '
    '; } // Date send - if (! empty($object->date_envoi)) + if (!empty($object->date_envoi)) { if ($usetable) print ''; else print '
    '; } @@ -492,8 +492,8 @@ function dol_print_object_info($object, $usetable = 0) */ function dolAddEmailTrackId($email, $trackingid) { - $tmp=explode('@', $email); - return $tmp[0].'+'.$trackingid.'@'.(isset($tmp[1])?$tmp[1]:''); + $tmp = explode('@', $email); + return $tmp[0].'+'.$trackingid.'@'.(isset($tmp[1]) ? $tmp[1] : ''); } /** @@ -535,7 +535,7 @@ function isValidUrl($url, $http = 0, $pass = 0, $port = 0, $path = 0, $query = 0 // HOSTNAME OR IP //$urlregex .= "[a-z0-9+\$_-]+(\.[a-z0-9+\$_-]+)*"; // x allowed (ex. http://localhost, http://routerlogin) //$urlregex .= "[a-z0-9+\$_-]+(\.[a-z0-9+\$_-]+)+"; // x.x - $urlregex .= "([a-z0-9+\$_\\\:-])+(\.[a-z0-9+\$_-][a-z0-9+\$_-]+)*"; // x ou x.xx (2 x ou plus) + $urlregex .= "([a-z0-9+\$_\\\:-])+(\.[a-z0-9+\$_-][a-z0-9+\$_-]+)*"; // x ou x.xx (2 x ou plus) //use only one of the above // PORT @@ -567,10 +567,12 @@ function isValidVATID($company) { 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, '/'); + 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))) { return 0; @@ -594,16 +596,16 @@ function clean_url($url, $http = 1) // Also, there's no need of escape a dot sign in a class 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]:''; + $proto = $regs[1]; + $domain = $regs[2]; + $port = isset($regs[3]) ? $regs[3] : ''; //print $url." -> ".$proto." - ".$domain." - ".$port; //$url = dol_string_nospecial(trim($url)); $url = trim($url); // Si http: defini on supprime le http (Si https on ne supprime pas) - $newproto=$proto; - if ($http==0) + $newproto = $proto; + if ($http == 0) { if (preg_match('/^http:[\\/]+/i', $url)) { @@ -635,7 +637,7 @@ 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 = ''; @@ -644,24 +646,24 @@ 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]; } - for($i=0; $i < $nbreplace; $i++){ + for ($i = 0; $i < $nbreplace; $i++) { $string_replace .= $replace; } - if(strlen($mail_name) > $nbdisplaymail){ + if (strlen($mail_name) > $nbdisplaymail) { $mail_name = substr($mail_name, 0, $nbdisplaymail); } - if(strlen($mail_domaine) > $nbdisplaydomain){ - $mail_domaine = substr($mail_domaine, strlen($mail_domaine)-$nbdisplaydomain); + if (strlen($mail_domaine) > $nbdisplaydomain) { + $mail_domaine = substr($mail_domaine, strlen($mail_domaine) - $nbdisplaydomain); } - return $mail_name . $string_replace . $mail_domaine . $mail_tld; + return $mail_name.$string_replace.$mail_domaine.$mail_tld; } @@ -676,12 +678,12 @@ function dolObfuscateEmail($mail, $replace = "*", $nbreplace = 8, $nbdisplaymail */ function array2tr($data, $troptions = '', $tdoptions = '') { - $text = '' ; - foreach($data as $key => $item){ - $text.= '' ; + $text = ''; + foreach ($data as $key => $item) { + $text .= ''; } - $text.= '' ; - return $text ; + $text .= ''; + return $text; } /** @@ -696,20 +698,20 @@ function array2tr($data, $troptions = '', $tdoptions = '') */ function array2table($data, $tableMarkup = 1, $tableoptions = '', $troptions = '', $tdoptions = '') { - $text='' ; - if($tableMarkup) $text = '
    '; print $langs->trans("ImportedWithSet"); @@ -222,7 +222,7 @@ function dol_print_object_info($object, $usetable = 0) } // User creation (old method using already loaded object and not id is kept for backward compatibility) - if (! empty($object->user_creation) || ! empty($object->user_creation_id)) + if (!empty($object->user_creation) || !empty($object->user_creation_id)) { if ($usetable) print '
    '; print $langs->trans("CreatedBy"); @@ -235,7 +235,7 @@ function dol_print_object_info($object, $usetable = 0) } else { - $userstatic=new User($db); + $userstatic = new User($db); $userstatic->fetch($object->user_creation_id ? $object->user_creation_id : $object->user_creation); if ($userstatic->id) print $userstatic->getNomUrl(1, '', 0, 0, 0); else print $langs->trans("Unknown"); @@ -245,20 +245,20 @@ function dol_print_object_info($object, $usetable = 0) } // Date creation - if (! empty($object->date_creation)) + if (!empty($object->date_creation)) { if ($usetable) print '
    '; print $langs->trans("DateCreation"); if ($usetable) print ''; else print ': '; print dol_print_date($object->date_creation, 'dayhour'); - if ($deltadateforuser) print ' '.$langs->trans("CurrentHour").'   /   '.dol_print_date($object->date_creation+($deltadateforuser*3600), "dayhour").'  '.$langs->trans("ClientHour"); + if ($deltadateforuser) print ' '.$langs->trans("CurrentHour").'   /   '.dol_print_date($object->date_creation + ($deltadateforuser * 3600), "dayhour").'  '.$langs->trans("ClientHour"); if ($usetable) print '
    '; print $langs->trans("ModifiedBy"); @@ -271,7 +271,7 @@ function dol_print_object_info($object, $usetable = 0) } else { - $userstatic=new User($db); + $userstatic = new User($db); $userstatic->fetch($object->user_modification_id ? $object->user_modification_id : $object->user_modification); if ($userstatic->id) print $userstatic->getNomUrl(1, '', 0, 0, 0); else print $langs->trans("Unknown"); @@ -281,20 +281,20 @@ function dol_print_object_info($object, $usetable = 0) } // Date change - if (! empty($object->date_modification)) + if (!empty($object->date_modification)) { if ($usetable) print '
    '; print $langs->trans("DateLastModification"); if ($usetable) print ''; else print ': '; print dol_print_date($object->date_modification, 'dayhour'); - if ($deltadateforuser) print ' '.$langs->trans("CurrentHour").'   /   '.dol_print_date($object->date_modification+($deltadateforuser*3600), "dayhour").'  '.$langs->trans("ClientHour"); + if ($deltadateforuser) print ' '.$langs->trans("CurrentHour").'   /   '.dol_print_date($object->date_modification + ($deltadateforuser * 3600), "dayhour").'  '.$langs->trans("ClientHour"); if ($usetable) print '
    '; print $langs->trans("ValidatedBy"); @@ -307,7 +307,7 @@ function dol_print_object_info($object, $usetable = 0) } else { - $userstatic=new User($db); + $userstatic = new User($db); $userstatic->fetch($object->user_validation_id ? $object->user_validation_id : $object->user_validation); if ($userstatic->id) print $userstatic->getNomUrl(1, '', 0, 0, 0); else print $langs->trans("Unknown"); @@ -317,20 +317,20 @@ function dol_print_object_info($object, $usetable = 0) } // Date validation - if (! empty($object->date_validation)) + if (!empty($object->date_validation)) { if ($usetable) print '
    '; print $langs->trans("DateValidation"); if ($usetable) print ''; else print ': '; print dol_print_date($object->date_validation, 'dayhour'); - if ($deltadateforuser) print ' '.$langs->trans("CurrentHour").'   /   '.dol_print_date($object->date_validation+($deltadateforuser*3600), "dayhour").'  '.$langs->trans("ClientHour"); + if ($deltadateforuser) print ' '.$langs->trans("CurrentHour").'   /   '.dol_print_date($object->date_validation + ($deltadateforuser * 3600), "dayhour").'  '.$langs->trans("ClientHour"); if ($usetable) print '
    '; print $langs->trans("ApprovedBy"); @@ -343,7 +343,7 @@ function dol_print_object_info($object, $usetable = 0) } else { - $userstatic=new User($db); + $userstatic = new User($db); $userstatic->fetch($object->user_approve_id ? $object->user_approve_id : $object->user_approve); if ($userstatic->id) print $userstatic->getNomUrl(1, '', 0, 0, 0); else print $langs->trans("Unknown"); @@ -353,26 +353,26 @@ function dol_print_object_info($object, $usetable = 0) } // Date approve - if (! empty($object->date_approve)) + if (!empty($object->date_approve)) { if ($usetable) print '
    '; print $langs->trans("DateApprove"); if ($usetable) print ''; else print ': '; print dol_print_date($object->date_approve, 'dayhour'); - if ($deltadateforuser) print ' '.$langs->trans("CurrentHour").'   /   '.dol_print_date($object->date_approve+($deltadateforuser*3600), "dayhour").'  '.$langs->trans("ClientHour"); + if ($deltadateforuser) print ' '.$langs->trans("CurrentHour").'   /   '.dol_print_date($object->date_approve + ($deltadateforuser * 3600), "dayhour").'  '.$langs->trans("ClientHour"); if ($usetable) print '
    '; print $langs->trans("ApprovedBy"); if ($usetable) print ''; else print ': '; - $userstatic=new User($db); + $userstatic = new User($db); $userstatic->fetch($object->user_approve_id2); if ($userstatic->id) print $userstatic->getNomUrl(1, '', 0, 0, 0); else print $langs->trans("Unknown"); @@ -381,20 +381,20 @@ function dol_print_object_info($object, $usetable = 0) } // Date approve - if (! empty($object->date_approve2)) + if (!empty($object->date_approve2)) { if ($usetable) print '
    '; print $langs->trans("DateApprove2"); if ($usetable) print ''; else print ': '; print dol_print_date($object->date_approve2, 'dayhour'); - if ($deltadateforuser) print ' '.$langs->trans("CurrentHour").'   /   '.dol_print_date($object->date_approve2+($deltadateforuser*3600), "dayhour").'  '.$langs->trans("ClientHour"); + if ($deltadateforuser) print ' '.$langs->trans("CurrentHour").'   /   '.dol_print_date($object->date_approve2 + ($deltadateforuser * 3600), "dayhour").'  '.$langs->trans("ClientHour"); if ($usetable) print '
    '; print $langs->trans("ClosedBy"); @@ -407,7 +407,7 @@ function dol_print_object_info($object, $usetable = 0) } else { - $userstatic=new User($db); + $userstatic = new User($db); $userstatic->fetch($object->user_cloture); if ($userstatic->id) print $userstatic->getNomUrl(1, '', 0, 0, 0); else print $langs->trans("Unknown"); @@ -417,20 +417,20 @@ function dol_print_object_info($object, $usetable = 0) } // Date close - if (! empty($object->date_cloture)) + if (!empty($object->date_cloture)) { if ($usetable) print '
    '; print $langs->trans("DateClosing"); if ($usetable) print ''; else print ': '; print dol_print_date($object->date_cloture, 'dayhour'); - if ($deltadateforuser) print ' '.$langs->trans("CurrentHour").'   /   '.dol_print_date($object->date_cloture+($deltadateforuser*3600), "dayhour").'  '.$langs->trans("ClientHour"); + if ($deltadateforuser) print ' '.$langs->trans("CurrentHour").'   /   '.dol_print_date($object->date_cloture + ($deltadateforuser * 3600), "dayhour").'  '.$langs->trans("ClientHour"); if ($usetable) print '
    '; print $langs->trans("ConciliatedBy"); @@ -443,7 +443,7 @@ function dol_print_object_info($object, $usetable = 0) } else { - $userstatic=new User($db); + $userstatic = new User($db); $userstatic->fetch($object->user_rappro); if ($userstatic->id) print $userstatic->getNomUrl(1, '', 0, 0, 0); else print $langs->trans("Unknown"); @@ -453,27 +453,27 @@ function dol_print_object_info($object, $usetable = 0) } // Date conciliate - if (! empty($object->date_rappro)) + if (!empty($object->date_rappro)) { if ($usetable) print '
    '; print $langs->trans("DateConciliating"); if ($usetable) print ''; else print ': '; print dol_print_date($object->date_rappro, 'dayhour'); - if ($deltadateforuser) print ' '.$langs->trans("CurrentHour").'   /   '.dol_print_date($object->date_rappro+($deltadateforuser*3600), "dayhour").'  '.$langs->trans("ClientHour"); + if ($deltadateforuser) print ' '.$langs->trans("CurrentHour").'   /   '.dol_print_date($object->date_rappro + ($deltadateforuser * 3600), "dayhour").'  '.$langs->trans("ClientHour"); if ($usetable) print '
    '; print $langs->trans("DateLastSend"); if ($usetable) print ''; else print ': '; print dol_print_date($object->date_envoi, 'dayhour'); - if ($deltadateforuser) print ' '.$langs->trans("CurrentHour").'   /   '.dol_print_date($object->date_envoi+($deltadateforuser*3600), "dayhour").'  '.$langs->trans("ClientHour"); + if ($deltadateforuser) print ' '.$langs->trans("CurrentHour").'   /   '.dol_print_date($object->date_envoi + ($deltadateforuser * 3600), "dayhour").'  '.$langs->trans("ClientHour"); if ($usetable) print '
    '.$item.'
    '.$item.'
    ' ; - foreach($data as $key => $item){ - if(is_array($item)){ - $text.=array2tr($item, $troptions, $tdoptions); + $text = ''; + if ($tableMarkup) $text = '
    '; + foreach ($data as $key => $item) { + if (is_array($item)) { + $text .= array2tr($item, $troptions, $tdoptions); } else { - $text.= '' ; - $text.= '' ; - $text.= '' ; - $text.= '' ; + $text .= ''; + $text .= ''; + $text .= ''; + $text .= ''; } } - if($tableMarkup) $text.= '
    '.$key.''.$item.'
    '.$key.''.$item.'
    ' ; - return $text ; + if ($tableMarkup) $text .= '
    '; + return $text; } /** @@ -750,42 +752,42 @@ function get_next_value($db, $mask, $table, $field, $where = '', $objsoc = '', $ //$date=dol_mktime(12, 0, 0, 1, 1, 1900); //$date=dol_stringtotime('20130101'); - $hasglobalcounter=false; + $hasglobalcounter = false; // Extract value for mask counter, mask raz and mask offset 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; + $masktri = $reg[1].(!empty($reg[2]) ? $reg[2] : '').(!empty($reg[3]) ? $reg[3] : ''); + $maskcounter = $reg[1]; + $hasglobalcounter = true; } else { // setting some defaults so the rest of the code won't fail if there is a third party counter - $masktri='00000'; - $maskcounter='00000'; + $masktri = '00000'; + $maskcounter = '00000'; } - $maskraz=-1; - $maskoffset=0; - $resetEveryMonth=false; + $maskraz = -1; + $maskoffset = 0; + $resetEveryMonth = false; if (dol_strlen($maskcounter) < 3 && empty($conf->global->MAIN_COUNTER_WITH_LESS_3_DIGITS)) return 'ErrorCounterMustHaveMoreThan3Digits'; // Extract value for third party mask counter if (preg_match('/\{(c+)(0*)\}/i', $mask, $regClientRef)) { - $maskrefclient=$regClientRef[1].$regClientRef[2]; - $maskrefclient_maskclientcode=$regClientRef[1]; - $maskrefclient_maskcounter=$regClientRef[2]; - $maskrefclient_maskoffset=0; //default value of maskrefclient_counter offset - $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 + $maskrefclient = $regClientRef[1].$regClientRef[2]; + $maskrefclient_maskclientcode = $regClientRef[1]; + $maskrefclient_maskcounter = $regClientRef[2]; + $maskrefclient_maskoffset = 0; //default value of maskrefclient_counter offset + $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=''; + else $maskrefclient = ''; // fail if there is neither a global nor a third party counter - if (! $hasglobalcounter && ($maskrefclient_maskcounter == '')) + if (!$hasglobalcounter && ($maskrefclient_maskcounter == '')) { return 'ErrorBadMask'; } @@ -793,14 +795,14 @@ function get_next_value($db, $mask, $table, $field, $where = '', $objsoc = '', $ // Extract value for third party type 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 + $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 } else { - $masktype=''; - $masktype_value=''; + $masktype = ''; + $masktype_value = ''; } // Extract value for user @@ -889,79 +891,79 @@ function get_next_value($db, $mask, $table, $field, $where = '', $objsoc = '', $ // 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; } + 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'; } 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; } + 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; + $yearlen = $posy ?dol_strlen($reg[$posy]) : 0; + $monthlen = $posm ?dol_strlen($reg[$posm]) : 0; // Define pos - $yearpos = (dol_strlen($reg[1])+1); - $monthpos = ($yearpos+$yearlen); + $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"; // Define $yearcomp and $monthcomp (that will be use in the select where to search max number) - $monthcomp=$maskraz; - $yearcomp=0; + $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); - $nextnewyeardate=dol_mktime('0', '0', '0', '1', '1', $currentyear+1); + $currentyear = date("Y", $date); + $fiscaldate = dol_mktime('0', '0', '0', $maskraz, '1', $currentyear); + $newyeardate = dol_mktime('0', '0', '0', '1', '1', $currentyear); + $nextnewyeardate = dol_mktime('0', '0', '0', '1', '1', $currentyear + 1); //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 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 ($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) $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.") = '".$yearcomp."'"; - $sqlwhere.=" AND SUBSTRING(".$field.", ".$monthpos.", ".$monthlen.") >= '".str_pad($monthcomp, $monthlen, '0', STR_PAD_LEFT)."')"; - $sqlwhere.=" OR"; - $sqlwhere.=" (SUBSTRING(".$field.", ".$yearpos.", ".$yearlen.") = '".$yearcomp1."'"; - $sqlwhere.=" AND SUBSTRING(".$field.", ".$monthpos.", ".$monthlen.") < '".str_pad($monthcomp, $monthlen, '0', STR_PAD_LEFT)."') "; - $sqlwhere.=')'; + $sqlwhere .= "("; + $sqlwhere .= " (SUBSTRING(".$field.", ".$yearpos.", ".$yearlen.") = '".$yearcomp."'"; + $sqlwhere .= " AND SUBSTRING(".$field.", ".$monthpos.", ".$monthlen.") >= '".str_pad($monthcomp, $monthlen, '0', STR_PAD_LEFT)."')"; + $sqlwhere .= " OR"; + $sqlwhere .= " (SUBSTRING(".$field.", ".$yearpos.", ".$yearlen.") = '".$yearcomp1."'"; + $sqlwhere .= " AND SUBSTRING(".$field.", ".$monthpos.", ".$monthlen.") < '".str_pad($monthcomp, $monthlen, '0', STR_PAD_LEFT)."') "; + $sqlwhere .= ')'; } elseif ($resetEveryMonth) { - $sqlwhere.="(SUBSTRING(".$field.", ".$yearpos.", ".$yearlen.") = '".$yearcomp."'"; - $sqlwhere.=" AND SUBSTRING(".$field.", ".$monthpos.", ".$monthlen.") = '".str_pad($monthcomp, $monthlen, '0', STR_PAD_LEFT)."')"; + $sqlwhere .= "(SUBSTRING(".$field.", ".$yearpos.", ".$yearlen.") = '".$yearcomp."'"; + $sqlwhere .= " AND SUBSTRING(".$field.", ".$monthpos.", ".$monthlen.") = '".str_pad($monthcomp, $monthlen, '0', STR_PAD_LEFT)."')"; } else // reset is done on january { - $sqlwhere.='(SUBSTRING('.$field.', '.$yearpos.', '.$yearlen.") = '".$yearcomp."')"; + $sqlwhere .= '(SUBSTRING('.$field.', '.$yearpos.', '.$yearlen.") = '".$yearcomp."')"; } } //print "sqlwhere=".$sqlwhere." yearcomp=".$yearcomp."
    \n"; // sqlwhere and yearcomp defined only if we ask a reset @@ -970,14 +972,14 @@ function get_next_value($db, $mask, $table, $field, $where = '', $objsoc = '', $ // Define $sqlstring if (function_exists('mb_strrpos')) { - $posnumstart=mb_strrpos($maskwithnocode, $maskcounter, 'UTF-8'); + $posnumstart = mb_strrpos($maskwithnocode, $maskcounter, 'UTF-8'); } else { - $posnumstart=strrpos($maskwithnocode, $maskcounter); + $posnumstart = strrpos($maskwithnocode, $maskcounter); } // Pos of counter in final string (from 0 to ...) if ($posnumstart < 0) return 'ErrorBadMaskFailedToLocatePosOfSequence'; - $sqlstring='SUBSTRING('.$field.', '.($posnumstart+1).', '.dol_strlen($maskcounter).')'; + $sqlstring = 'SUBSTRING('.$field.', '.($posnumstart + 1).', '.dol_strlen($maskcounter).')'; // Define $maskLike $maskLike = dol_string_nospecial($mask); @@ -993,27 +995,27 @@ function get_next_value($db, $mask, $table, $field, $where = '', $objsoc = '', $ 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) + foreach ($maskperso as $key => $val) { $maskLike = str_replace(dol_string_nospecial($maskperso[$key]), $maskpersonew[$key], $maskLike); } // Get counter in database - $counter=0; + $counter = 0; $sql = "SELECT MAX(".$sqlstring.") as val"; - $sql.= " FROM ".MAIN_DB_PREFIX.$table; - $sql.= " WHERE ".$field." LIKE '".$maskLike."'"; - $sql.= " AND ".$field." NOT LIKE '(PROV%)'"; + $sql .= " FROM ".MAIN_DB_PREFIX.$table; + $sql .= " WHERE ".$field." LIKE '".$maskLike."'"; + $sql .= " AND ".$field." NOT LIKE '(PROV%)'"; if ($bentityon) // only if entity enable - $sql.= " AND entity IN (".getEntity($sharetable).")"; - elseif (! empty($forceentity)) - $sql.= " AND entity IN (".$forceentity.")"; - if ($where) $sql.=$where; - if ($sqlwhere) $sql.=' AND '.$sqlwhere; + $sql .= " AND entity IN (".getEntity($sharetable).")"; + elseif (!empty($forceentity)) + $sql .= " AND entity IN (".$forceentity.")"; + 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); + $resql = $db->query($sql); if ($resql) { $obj = $db->fetch_object($resql); @@ -1022,17 +1024,17 @@ function get_next_value($db, $mask, $table, $field, $where = '', $objsoc = '', $ else dol_print_error($db); // Check if we must force counter to maskoffset - if (empty($counter)) $counter=$maskoffset; + if (empty($counter)) $counter = $maskoffset; elseif (preg_match('/[^0-9]/i', $counter)) { - $counter=0; + $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. { - $counterpadded=str_pad($counter, dol_strlen($maskcounter), "0", STR_PAD_LEFT); + $counterpadded = str_pad($counter, dol_strlen($maskcounter), "0", STR_PAD_LEFT); // Define $maskLike $maskLike = dol_string_nospecial($mask); @@ -1048,20 +1050,20 @@ function get_next_value($db, $mask, $table, $field, $where = '', $objsoc = '', $ 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=''; + $ref = ''; $sql = "SELECT ".$field." as ref"; - $sql.= " FROM ".MAIN_DB_PREFIX.$table; - $sql.= " WHERE ".$field." LIKE '".$maskLike."'"; - $sql.= " AND ".$field." NOT LIKE '%PROV%'"; + $sql .= " FROM ".MAIN_DB_PREFIX.$table; + $sql .= " WHERE ".$field." LIKE '".$maskLike."'"; + $sql .= " AND ".$field." NOT LIKE '%PROV%'"; if ($bentityon) // only if entity enable - $sql.= " AND entity IN (".getEntity($sharetable).")"; - elseif (! empty($forceentity)) - $sql.= " AND entity IN (".$forceentity.")"; - if ($where) $sql.=$where; - if ($sqlwhere) $sql.=' AND '.$sqlwhere; + $sql .= " AND entity IN (".getEntity($sharetable).")"; + elseif (!empty($forceentity)) + $sql .= " AND entity IN (".$forceentity.")"; + if ($where) $sql .= $where; + if ($sqlwhere) $sql .= ' AND '.$sqlwhere; dol_syslog("functions2::get_next_value mode=".$mode."", LOG_DEBUG); - $resql=$db->query($sql); + $resql = $db->query($sql); if ($resql) { $obj = $db->fetch_object($resql); @@ -1069,7 +1071,7 @@ function get_next_value($db, $mask, $table, $field, $where = '', $objsoc = '', $ } else dol_print_error($db); - $numFinal=$ref; + $numFinal = $ref; } elseif ($mode == 'next') { @@ -1078,17 +1080,17 @@ function get_next_value($db, $mask, $table, $field, $where = '', $objsoc = '', $ // If value for $counter has a length higher than $maskcounter chars if ($counter >= pow(10, dol_strlen($maskcounter))) { - $counter='ErrorMaxNumberReachForThisMask'; + $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 ...) + $maskrefclient_posnumstart = strpos($maskwithnocode, $maskrefclient_maskcounter, strpos($maskwithnocode, $maskrefclient)); // Pos of counter in final string (from 0 to ...) if ($maskrefclient_posnumstart <= 0) return 'ErrorBadMask'; - $maskrefclient_sqlstring='SUBSTRING('.$field.', '.($maskrefclient_posnumstart+1).', '.dol_strlen($maskrefclient_maskcounter).')'; + $maskrefclient_sqlstring = 'SUBSTRING('.$field.', '.($maskrefclient_posnumstart + 1).', '.dol_strlen($maskrefclient_maskcounter).')'; //print "x".$sqlstring; // Define $maskrefclient_maskLike @@ -1104,21 +1106,21 @@ function get_next_value($db, $mask, $table, $field, $where = '', $objsoc = '', $ $maskrefclient_maskLike = str_replace(dol_string_nospecial('{'.$maskrefclient.'}'), $maskrefclient_clientcode.str_pad("", dol_strlen($maskrefclient_maskcounter), "_"), $maskrefclient_maskLike); // Get counter in database - $maskrefclient_counter=0; + $maskrefclient_counter = 0; $maskrefclient_sql = "SELECT MAX(".$maskrefclient_sqlstring.") as val"; - $maskrefclient_sql.= " FROM ".MAIN_DB_PREFIX.$table; + $maskrefclient_sql .= " FROM ".MAIN_DB_PREFIX.$table; //$sql.= " WHERE ".$field." not like '(%'"; - $maskrefclient_sql.= " WHERE ".$field." LIKE '".$maskrefclient_maskLike."'"; + $maskrefclient_sql .= " WHERE ".$field." LIKE '".$maskrefclient_maskLike."'"; if ($bentityon) // only if entity enable - $maskrefclient_sql.= " AND entity IN (".getEntity($sharetable).")"; - 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 - $maskrefclient_sql.=' AND (SUBSTRING('.$field.', '.(strpos($maskwithnocode, $maskrefclient)+1).', '.dol_strlen($maskrefclient_maskclientcode).")='".$maskrefclient_clientcode."')"; + $maskrefclient_sql .= " AND entity IN (".getEntity($sharetable).")"; + 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 + $maskrefclient_sql .= ' AND (SUBSTRING('.$field.', '.(strpos($maskwithnocode, $maskrefclient) + 1).', '.dol_strlen($maskrefclient_maskclientcode).")='".$maskrefclient_clientcode."')"; dol_syslog("functions2::get_next_value maskrefclient", LOG_DEBUG); - $maskrefclient_resql=$db->query($maskrefclient_sql); + $maskrefclient_resql = $db->query($maskrefclient_sql); if ($maskrefclient_resql) { $maskrefclient_obj = $db->fetch_object($maskrefclient_resql); @@ -1126,7 +1128,7 @@ function get_next_value($db, $mask, $table, $field, $where = '', $objsoc = '', $ } 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++; } @@ -1134,11 +1136,11 @@ 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); + $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); } else // we want yyyy to be current year { @@ -1150,8 +1152,8 @@ function get_next_value($db, $mask, $table, $field, $where = '', $objsoc = '', $ $numFinal = preg_replace('/\{dd\}/i', date("d", $date), $numFinal); // Now we replace the counter - $maskbefore='{'.$masktri.'}'; - $maskafter=str_pad($counter, dol_strlen($maskcounter), "0", STR_PAD_LEFT); + $maskbefore = '{'.$masktri.'}'; + $maskafter = str_pad($counter, dol_strlen($maskcounter), "0", STR_PAD_LEFT); //print 'x'.$maskbefore.'-'.$maskafter.'y'; $numFinal = str_replace($maskbefore, $maskafter, $numFinal); @@ -1294,8 +1296,8 @@ function check_value($mask, $value) // // Check length - $len=dol_strlen($maskwithnocode); - if (dol_strlen($value) != $len) $result=-1; + $len = dol_strlen($maskwithnocode); + if (dol_strlen($value) != $len) $result = -1; // Define $maskLike /* seems not used @@ -1325,11 +1327,11 @@ 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); } + $last = dol_strlen($bin) - 1; + 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; } @@ -1341,11 +1343,11 @@ function binhex($bin, $pad = false, $upper = false) */ function hexbin($hexa) { - $bin=''; + $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); + $bin .= str_pad(decbin(hexdec($hexa{$i})), 4, '0', STR_PAD_LEFT); } return $bin; } @@ -1376,27 +1378,27 @@ function numero_semaine($time) */ // 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; + 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; + $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; + $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; + $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 { @@ -1404,7 +1406,7 @@ function numero_semaine($time) } // Definition du numero de semaine: nb de jours entre "premier Jeudi de l'annee" et "Jeudi de la semaine"; - $numeroSemaine = ( + $numeroSemaine = ( ( date("z", mktime(12, 0, 0, date("m", $jeudiSemaine), date("d", $jeudiSemaine), date("Y", $jeudiSemaine))) - @@ -1413,10 +1415,10 @@ 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; } @@ -1446,7 +1448,7 @@ function weight_convert($weight, &$from_unit, $to_unit) * weigh_convert(320, $f, 0) retournera 0.32 * */ - while ($from_unit <> $to_unit) + while ($from_unit <> $to_unit) { if ($from_unit > $to_unit) { @@ -1485,21 +1487,21 @@ function dol_set_user_param($db, $conf, &$user, $tab) // We remove old parameters for all keys in $tab $sql = "DELETE FROM ".MAIN_DB_PREFIX."user_param"; - $sql.= " WHERE fk_user = ".$user->id; - $sql.= " AND entity = ".$conf->entity; - $sql.= " AND param in ("; - $i=0; + $sql .= " WHERE fk_user = ".$user->id; + $sql .= " AND entity = ".$conf->entity; + $sql .= " AND param in ("; + $i = 0; foreach ($tab as $key => $value) { - if ($i > 0) $sql.=','; - $sql.="'".$db->escape($key)."'"; + if ($i > 0) $sql .= ','; + $sql .= "'".$db->escape($key)."'"; $i++; } - $sql.= ")"; + $sql .= ")"; dol_syslog("functions2.lib::dol_set_user_param", LOG_DEBUG); - $resql=$db->query($sql); - if (! $resql) + $resql = $db->query($sql); + if (!$resql) { dol_print_error($db); $db->rollback(); @@ -1512,12 +1514,12 @@ function dol_set_user_param($db, $conf, &$user, $tab) 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)."')"; + $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) + $result = $db->query($sql); + if (!$result) { dol_print_error($db); $db->rollback(); @@ -1566,7 +1568,7 @@ function dol_print_reduction($reduction, $langs) */ function version_os() { - $osversion=php_uname(); + $osversion = php_uname(); return $osversion; } @@ -1716,10 +1718,10 @@ 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; } @@ -1736,10 +1738,10 @@ function is_ip($ip) */ function dol_buildlogin($lastname, $firstname) { - $login=strtolower(dol_string_unaccent($firstname)); - $login.=($login?'.':''); - $login.=strtolower(dol_string_unaccent($lastname)); - $login=dol_string_nospecial($login, ''); // For special names + $login = strtolower(dol_string_unaccent($firstname)); + $login .= ($login ? '.' : ''); + $login .= strtolower(dol_string_unaccent($lastname)); + $login = dol_string_nospecial($login, ''); // For special names return $login; } @@ -1752,18 +1754,18 @@ function getSoapParams() { global $conf; - $params=array(); - $proxyuse =(empty($conf->global->MAIN_PROXY_USE)?false:true); - $proxyhost=(empty($conf->global->MAIN_PROXY_USE)?false:$conf->global->MAIN_PROXY_HOST); - $proxyport=(empty($conf->global->MAIN_PROXY_USE)?false:$conf->global->MAIN_PROXY_PORT); - $proxyuser=(empty($conf->global->MAIN_PROXY_USE)?false:$conf->global->MAIN_PROXY_USER); - $proxypass=(empty($conf->global->MAIN_PROXY_USE)?false:$conf->global->MAIN_PROXY_PASS); - $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 + $params = array(); + $proxyuse = (empty($conf->global->MAIN_PROXY_USE) ?false:true); + $proxyhost = (empty($conf->global->MAIN_PROXY_USE) ?false:$conf->global->MAIN_PROXY_HOST); + $proxyport = (empty($conf->global->MAIN_PROXY_USE) ?false:$conf->global->MAIN_PROXY_PORT); + $proxyuser = (empty($conf->global->MAIN_PROXY_USE) ?false:$conf->global->MAIN_PROXY_USER); + $proxypass = (empty($conf->global->MAIN_PROXY_USE) ?false:$conf->global->MAIN_PROXY_PASS); + $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) { - $params=array('connection_timeout'=>$timeout, + $params = array('connection_timeout'=>$timeout, 'response_timeout'=>$response_timeout, 'proxy_use' => 1, 'proxy_host' => $proxyhost, @@ -1775,7 +1777,7 @@ function getSoapParams() } else { - $params=array('connection_timeout'=>$timeout, + $params = array('connection_timeout'=>$timeout, 'response_timeout'=>$response_timeout, 'proxy_use' => 0, 'proxy_host' => false, @@ -1802,7 +1804,7 @@ function dolGetElementUrl($objectid, $objecttype, $withpicto = 0, $option = '') { global $db, $conf, $langs; - $ret=''; + $ret = ''; // Parse element/subelement (ex: project_task) $module = $element = $subelement = $objecttype; @@ -1884,34 +1886,34 @@ function dolGetElementUrl($objectid, $objecttype, $withpicto = 0, $option = '') if ($objecttype == 'invoice_supplier') { $classfile = 'fournisseur.facture'; - $classname='FactureFournisseur'; + $classname = 'FactureFournisseur'; $classpath = 'fourn/class'; - $module='fournisseur'; + $module = 'fournisseur'; } - elseif ($objecttype == 'order_supplier') { + elseif ($objecttype == 'order_supplier') { $classfile = 'fournisseur.commande'; - $classname='CommandeFournisseur'; + $classname = 'CommandeFournisseur'; $classpath = 'fourn/class'; - $module='fournisseur'; + $module = 'fournisseur'; } - elseif ($objecttype == 'stock') { + elseif ($objecttype == 'stock') { $classpath = 'product/stock/class'; - $classfile='entrepot'; - $classname='Entrepot'; + $classfile = 'entrepot'; + $classname = 'Entrepot'; } - if (! empty($conf->$module->enabled)) + if (!empty($conf->$module->enabled)) { - $res=dol_include_once('/'.$classpath.'/'.$classfile.'.class.php'); + $res = dol_include_once('/'.$classpath.'/'.$classfile.'.class.php'); if ($res) { if (class_exists($classname)) { $object = new $classname($db); - $res=$object->fetch($objectid); + $res = $object->fetch($objectid); if ($res > 0) { - $ret=$object->getNomUrl($withpicto, $option); - } elseif($res==0) { - $ret=$langs->trans('Deleted'); + $ret = $object->getNomUrl($withpicto, $option); + } elseif ($res == 0) { + $ret = $langs->trans('Deleted'); } unset($object); } @@ -1932,12 +1934,12 @@ function dolGetElementUrl($objectid, $objecttype, $withpicto = 0, $option = '') */ function cleanCorruptedTree($db, $tabletocleantree, $fieldfkparent) { - $totalnb=0; - $listofid=array(); - $listofparentid=array(); + $totalnb = 0; + $listofid = array(); + $listofparentid = array(); // 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; + $sql = 'SELECT rowid, '.$fieldfkparent.' as parent_id FROM '.MAIN_DB_PREFIX.$tabletocleantree; $resql = $db->query($sql); if ($resql) { @@ -1946,8 +1948,8 @@ function cleanCorruptedTree($db, $tabletocleantree, $fieldfkparent) while ($i < $num) { $obj = $db->fetch_object($resql); - $listofid[]=$obj->rowid; - if ($obj->parent_id > 0) $listofparentid[$obj->rowid]=$obj->parent_id; + $listofid[] = $obj->rowid; + if ($obj->parent_id > 0) $listofparentid[$obj->rowid] = $obj->parent_id; $i++; } } @@ -1961,51 +1963,51 @@ function cleanCorruptedTree($db, $tabletocleantree, $fieldfkparent) 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 + $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) { - $nb=$db->affected_rows($sql); + $nb = $db->affected_rows($sql); if ($nb > 0) { print '
    Some record that were parent of themself were cleaned.'; } - $totalnb+=$nb; + $totalnb += $nb; } //else dol_print_error($db); // Check other loops - $listofidtoclean=array(); - foreach($listofparentid as $id => $pid) + $listofidtoclean = array(); + foreach ($listofparentid as $id => $pid) { // Check depth //print 'Analyse record id='.$id.' with parent '.$pid.'
    '; - $cursor=$id; $arrayidparsed=array(); // We start from child $id + $cursor = $id; $arrayidparsed = array(); // We start from child $id while ($cursor > 0) { - $arrayidparsed[$cursor]=1; + $arrayidparsed[$cursor] = 1; 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; + $listofidtoclean[$cursor] = $id; break; } - $cursor=$listofparentid[$cursor]; + $cursor = $listofparentid[$cursor]; } 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 + $sql .= " SET ".$fieldfkparent." = 0"; + $sql .= " WHERE rowid IN (".join(',', $listofidtoclean).")"; // So we update only records detected wrong $resql = $db->query($sql); if ($resql) { - $nb=$db->affected_rows($sql); + $nb = $db->affected_rows($sql); if ($nb > 0) { // Removed orphelins records @@ -2013,18 +2015,18 @@ function cleanCorruptedTree($db, $tabletocleantree, $fieldfkparent) print join(',', $listofidtoclean); } - $totalnb+=$nb; + $totalnb += $nb; } //else dol_print_error($db); // Check and clean orphelins $sql = "UPDATE ".MAIN_DB_PREFIX.$tabletocleantree; - $sql.= " SET ".$fieldfkparent." = 0"; - $sql.= " WHERE ".$fieldfkparent." NOT IN (".join(',', $listofid).")"; // So we update only records linked to a non existing parent + $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) { - $nb=$db->affected_rows($sql); + $nb = $db->affected_rows($sql); if ($nb > 0) { // Removed orphelins records @@ -2032,7 +2034,7 @@ function cleanCorruptedTree($db, $tabletocleantree, $fieldfkparent) print join(',', $listofid); } - $totalnb+=$nb; + $totalnb += $nb; } //else dol_print_error($db); @@ -2051,7 +2053,7 @@ function getElementProperties($element_type) { // Parse element/subelement (ex: project_task) $module = $element_type; - $element = $element_type; + $element = $element_type; $subelement = $element_type; // If we ask an resource form external module (instead of default path) @@ -2061,7 +2063,7 @@ function getElementProperties($element_type) } //print '
    1. element : '.$element.' - module : '.$module .'
    '; - if ( preg_match('/^([^_]+)_([^_]+)/i', $element, $regs)) { + if (preg_match('/^([^_]+)_([^_]+)/i', $element, $regs)) { $module = $element = $regs[1]; $subelement = $regs[2]; } @@ -2076,7 +2078,7 @@ function getElementProperties($element_type) // To work with non standard path if ($element_type == 'facture' || $element_type == 'invoice') { $classpath = 'compta/facture/class'; - $module ='facture'; + $module = 'facture'; $subelement = 'facture'; } if ($element_type == 'commande' || $element_type == 'order') { @@ -2084,10 +2086,10 @@ function getElementProperties($element_type) $module = 'commande'; $subelement = 'commande'; } - if ($element_type == 'propal') { + if ($element_type == 'propal') { $classpath = 'comm/propal/class'; } - if ($element_type == 'supplier_proposal') { + if ($element_type == 'supplier_proposal') { $classpath = 'supplier_proposal/class'; } if ($element_type == 'shipping') { @@ -2102,49 +2104,49 @@ function getElementProperties($element_type) } if ($element_type == 'contract') { $classpath = 'contrat/class'; - $module='contrat'; - $subelement='contrat'; + $module = 'contrat'; + $subelement = 'contrat'; } if ($element_type == 'member') { $classpath = 'adherents/class'; - $module='adherent'; - $subelement='adherent'; + $module = 'adherent'; + $subelement = 'adherent'; } if ($element_type == 'cabinetmed_cons') { $classpath = 'cabinetmed/class'; - $module='cabinetmed'; - $subelement='cabinetmedcons'; + $module = 'cabinetmed'; + $subelement = 'cabinetmedcons'; } if ($element_type == 'fichinter') { $classpath = 'fichinter/class'; - $module='ficheinter'; - $subelement='fichinter'; + $module = 'ficheinter'; + $subelement = 'fichinter'; } if ($element_type == 'dolresource' || $element_type == 'resource') { $classpath = 'resource/class'; - $module='resource'; - $subelement='dolresource'; + $module = 'resource'; + $subelement = 'dolresource'; } if ($element_type == 'propaldet') { $classpath = 'comm/propal/class'; - $module='propal'; - $subelement='propaleligne'; + $module = 'propal'; + $subelement = 'propaleligne'; } - if ($element_type == 'order_supplier') { + if ($element_type == 'order_supplier') { $classpath = 'fourn/class'; - $module='fournisseur'; - $subelement='commandefournisseur'; - $classfile='fournisseur.commande'; + $module = 'fournisseur'; + $subelement = 'commandefournisseur'; + $classfile = 'fournisseur.commande'; } - if ($element_type == 'invoice_supplier') { + if ($element_type == 'invoice_supplier') { $classpath = 'fourn/class'; - $module='fournisseur'; - $subelement='facturefournisseur'; - $classfile='fournisseur.facture'; + $module = 'fournisseur'; + $subelement = 'facturefournisseur'; + $classfile = 'fournisseur.facture'; } if ($element_type == "service") { $classpath = 'product/class'; - $subelement='product'; + $subelement = 'product'; } if (!isset($classfile)) $classfile = strtolower($subelement); @@ -2202,7 +2204,7 @@ function fetchObjectByElement($element_id, $element_type, $element_ref = '') */ function colorArrayToHex($arraycolor, $colorifnotfound = '888888') { - if (! is_array($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])); } @@ -2217,18 +2219,18 @@ function colorArrayToHex($arraycolor, $colorifnotfound = '888888') * @return array RGB hex value (without # before). For example: FF00FF * @see colorArrayToHex(), colorHexToRgb() */ -function colorStringToArray($stringcolor, $colorifnotfound = array(88,88,88)) +function colorStringToArray($stringcolor, $colorifnotfound = array(88, 88, 88)) { - 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 (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) { - $tmp=explode(',', $stringcolor); + $tmp = explode(',', $stringcolor); if (count($tmp) < 3) return $colorifnotfound; return $tmp; } - return array(hexdec($reg[1]),hexdec($reg[2]),hexdec($reg[3])); + return array(hexdec($reg[1]), hexdec($reg[2]), hexdec($reg[3])); } /** @@ -2370,18 +2372,18 @@ function colorHexToRgb($hex, $alpha = false, $returnArray = false) $rgb['r'] = hexdec($length == 6 ? substr($hex, 0, 2) : ($length == 3 ? str_repeat(substr($hex, 0, 1), 2) : 0)); $rgb['g'] = hexdec($length == 6 ? substr($hex, 2, 2) : ($length == 3 ? str_repeat(substr($hex, 1, 1), 2) : 0)); $rgb['b'] = hexdec($length == 6 ? substr($hex, 4, 2) : ($length == 3 ? str_repeat(substr($hex, 2, 1), 2) : 0)); - if ( $alpha !== false ) { + if ($alpha !== false) { $rgb['a'] = floatval($alpha); $string = 'rgba('.implode(',', $rgb).')'; } - else{ + else { $string = 'rgb('.implode(',', $rgb).')'; } - if($returnArray){ + if ($returnArray) { return $rgb; } - else{ + else { return $string; } } @@ -2404,8 +2406,8 @@ function cartesianArray(array $input) foreach ($input as $key => $values) { $append = array(); - foreach($result as $product) { - foreach($values as $item) { + foreach ($result as $product) { + foreach ($values as $item) { $product[$key] = $item; $append[] = $product; } @@ -2426,7 +2428,7 @@ function cartesianArray(array $input) */ function getModuleDirForApiClass($module) { - $moduledirforclass=$module; + $moduledirforclass = $module; if ($moduledirforclass != 'api') $moduledirforclass = preg_replace('/api$/i', '', $moduledirforclass); if ($module == 'contracts') { @@ -2523,11 +2525,11 @@ function randomColorPart($min = 0, $max = 255) */ function randomColor($min = 0, $max = 255) { - return randomColorPart($min, $max) . randomColorPart($min, $max) . randomColorPart($min, $max); + return randomColorPart($min, $max).randomColorPart($min, $max).randomColorPart($min, $max); } -if (! function_exists('dolEscapeXML')) +if (!function_exists('dolEscapeXML')) { /** * Encode string for xml usage @@ -2537,7 +2539,7 @@ if (! function_exists('dolEscapeXML')) */ function dolEscapeXML($string) { - return strtr($string, array('\''=>''','"'=>'"','&'=>'&','<'=>'<','>'=>'>')); + return strtr($string, array('\''=>''', '"'=>'"', '&'=>'&', '<'=>'<', '>'=>'>')); } } @@ -2553,25 +2555,25 @@ if (! function_exists('dolEscapeXML')) function autoOrManual($automaticmanual, $case = 1, $color = 0) { global $langs; - $result='unknown'; $classname=''; + $result = 'unknown'; $classname = ''; 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; + $result = $langs->trans('automatic'); + if ($case == 1 || $case == 3) $result = $langs->trans("Automatic"); + if ($case == 2) $result = ''; + if ($case == 3) $result = ' '.$result; - $classname='ok'; + $classname = 'ok'; } 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; + $result = $langs->trans("manual"); + 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.''; return $result; diff --git a/htdocs/core/lib/images.lib.php b/htdocs/core/lib/images.lib.php index d8163e7f763..4c089640915 100644 --- a/htdocs/core/lib/images.lib.php +++ b/htdocs/core/lib/images.lib.php @@ -40,6 +40,7 @@ function image_format_supported($file) $regeximgext='\.gif|\.jpg|\.jpeg|\.png|\.bmp|\.xpm|\.xbm|\.svg'; // See also into product.class.php // Case filename is not a format image + $reg = array(); if (! preg_match('/('.$regeximgext.')$/i', $file, $reg)) return -1; // Case filename is a format image but not supported by this PHP @@ -51,6 +52,7 @@ function image_format_supported($file) if (strtolower($reg[1]) == '.bmp') $imgfonction = 'imagecreatefromwbmp'; 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)) diff --git a/htdocs/core/lib/modulebuilder.lib.php b/htdocs/core/lib/modulebuilder.lib.php index 4e5cbb92c02..02a9932d474 100644 --- a/htdocs/core/lib/modulebuilder.lib.php +++ b/htdocs/core/lib/modulebuilder.lib.php @@ -63,8 +63,8 @@ function rebuildObjectClass($destdir, $module, $objectname, $newmask, $readdir = setEventMessages($langs->trans('ErrorFieldRequired', $langs->transnoentitiesnoconv("Label")), null, 'errors'); return -2; } - if (! preg_match('/^(integer|price|sellist|date|varchar|double|text|html)/', $addfieldentry['type']) - && ! preg_match('/^(boolean|real|timestamp)$/', $addfieldentry['type'])) + if (! preg_match('/^(integer|price|sellist|varchar|double|text|html|duration)/', $addfieldentry['type']) + && ! preg_match('/^(boolean|real|date|datetime|timestamp)$/', $addfieldentry['type'])) { setEventMessages($langs->trans('BadValueForType', $objectname), null, 'errors'); return -2; @@ -164,7 +164,7 @@ function rebuildObjectClass($destdir, $module, $objectname, $newmask, $readdir = if (count($object->fields)) { - $typetotypephp=array('integer'=>'integer', 'varchar'=>'string'); + //$typetotypephp=array('integer'=>'integer', 'duration'=>'integer', 'varchar'=>'string'); foreach($object->fields as $key => $val) { @@ -266,7 +266,7 @@ function rebuildObjectSql($destdir, $module, $objectname, $newmask, $readdir = ' 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 ($type == 'link' || $type == 'sellist') $type = 'integer'; + 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'; diff --git a/htdocs/core/lib/order.lib.php b/htdocs/core/lib/order.lib.php index 97ab411bdfc..54d850d99b6 100644 --- a/htdocs/core/lib/order.lib.php +++ b/htdocs/core/lib/order.lib.php @@ -34,13 +34,13 @@ 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("OrderCard"); diff --git a/htdocs/core/lib/payments.lib.php b/htdocs/core/lib/payments.lib.php index 75e2ee08b8f..66b39809b29 100644 --- a/htdocs/core/lib/payments.lib.php +++ b/htdocs/core/lib/payments.lib.php @@ -97,22 +97,28 @@ function payment_supplier_prepare_head(Paiement $object) */ function getValidOnlinePaymentMethods($paymentmethod = '') { - global $conf; + global $conf, $langs; $validpaymentmethod=array(); if ((empty($paymentmethod) || $paymentmethod == 'paypal') && ! empty($conf->paypal->enabled)) { + $langs->load("paypal"); $validpaymentmethod['paypal']='valid'; } if ((empty($paymentmethod) || $paymentmethod == 'paybox') && ! empty($conf->paybox->enabled)) { + $langs->load("paybox"); $validpaymentmethod['paybox']='valid'; } if ((empty($paymentmethod) || $paymentmethod == 'stripe') && ! empty($conf->stripe->enabled)) { + $langs->load("stripe"); $validpaymentmethod['stripe']='valid'; } + // TODO Add trigger + + return $validpaymentmethod; } @@ -130,12 +136,12 @@ function showOnlinePaymentUrl($type, $ref) // Load translation files required by the page $langs->loadLangs(array('payment', 'paybox')); - $servicename=$langs->transnoentitiesnoconv('Online'); + $servicename = $langs->transnoentitiesnoconv('Online'); $out = img_picto('', 'globe').' '.$langs->trans("ToOfferALinkForOnlinePayment", $servicename).'
    '; $url = getOnlinePaymentUrl(0, $type, $ref); - $out.= ''; - $out.= ajax_autoselect("onlinepaymenturl", 0); + $out .= ''; + $out .= ajax_autoselect("onlinepaymenturl", 0); return $out; } @@ -154,12 +160,12 @@ function getOnlinePaymentUrl($mode, $type, $ref = '', $amount = '9.99', $freetag { global $conf, $dolibarr_main_url_root; - $ref=str_replace(' ', '', $ref); - $out=''; + $ref = str_replace(' ', '', $ref); + $out = ''; // Define $urlwithroot - $urlwithouturlroot=preg_replace('/'.preg_quote(DOL_URL_ROOT, '/').'$/i', '', trim($dolibarr_main_url_root)); - $urlwithroot=$urlwithouturlroot.DOL_URL_ROOT; // This is to use external domain name found into config file + $urlwithouturlroot = preg_replace('/'.preg_quote(DOL_URL_ROOT, '/').'$/i', '', trim($dolibarr_main_url_root)); + $urlwithroot = $urlwithouturlroot.DOL_URL_ROOT; // This is to use external domain name found into config file //$urlwithroot=DOL_MAIN_URL_ROOT; // This is to use same domain name than current $urltouse = DOL_MAIN_URL_ROOT; @@ -173,6 +179,7 @@ function getOnlinePaymentUrl($mode, $type, $ref = '', $amount = '9.99', $freetag 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') { @@ -288,51 +295,51 @@ function htmlPrintOnlinePaymentFooter($fromcompany, $langs, $addformmessage = 0, global $conf; // Juridical status - $line1=""; + $line1 = ""; if ($fromcompany->forme_juridique_code) { - $line1.=($line1?" - ":"").getFormeJuridiqueLabel($fromcompany->forme_juridique_code); + $line1 .= ($line1 ? " - " : "").getFormeJuridiqueLabel($fromcompany->forme_juridique_code); } // Capital if ($fromcompany->capital) { - $line1.=($line1?" - ":"").$langs->transnoentities("CapitalOf", $fromcompany->capital)." ".$langs->transnoentities("Currency".$conf->currency); + $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]; - $line1.=($line1?" - ":"").$field.": ".$fromcompany->idprof1; + $field = $langs->transcountrynoentities("ProfId1", $fromcompany->country_code); + if (preg_match('/\((.*)\)/i', $field, $reg)) $field = $reg[1]; + $line1 .= ($line1 ? " - " : "").$field.": ".$fromcompany->idprof1; } // Prof Id 2 if ($fromcompany->idprof2) { - $field=$langs->transcountrynoentities("ProfId2", $fromcompany->country_code); - if (preg_match('/\((.*)\)/i', $field, $reg)) $field=$reg[1]; - $line1.=($line1?" - ":"").$field.": ".$fromcompany->idprof2; + $field = $langs->transcountrynoentities("ProfId2", $fromcompany->country_code); + if (preg_match('/\((.*)\)/i', $field, $reg)) $field = $reg[1]; + $line1 .= ($line1 ? " - " : "").$field.": ".$fromcompany->idprof2; } // Second line of company infos - $line2=""; + $line2 = ""; // Prof Id 3 if ($fromcompany->idprof3) { - $field=$langs->transcountrynoentities("ProfId3", $fromcompany->country_code); - if (preg_match('/\((.*)\)/i', $field, $reg)) $field=$reg[1]; - $line2.=($line2?" - ":"").$field.": ".$fromcompany->idprof3; + $field = $langs->transcountrynoentities("ProfId3", $fromcompany->country_code); + if (preg_match('/\((.*)\)/i', $field, $reg)) $field = $reg[1]; + $line2 .= ($line2 ? " - " : "").$field.": ".$fromcompany->idprof3; } // Prof Id 4 if ($fromcompany->idprof4) { - $field=$langs->transcountrynoentities("ProfId4", $fromcompany->country_code); - if (preg_match('/\((.*)\)/i', $field, $reg)) $field=$reg[1]; - $line2.=($line2?" - ":"").$field.": ".$fromcompany->idprof4; + $field = $langs->transcountrynoentities("ProfId4", $fromcompany->country_code); + if (preg_match('/\((.*)\)/i', $field, $reg)) $field = $reg[1]; + $line2 .= ($line2 ? " - " : "").$field.": ".$fromcompany->idprof4; } // IntraCommunautary VAT if ($fromcompany->tva_intra != '') { - $line2.=($line2?" - ":"").$langs->transnoentities("VATIntraShort").": ".$fromcompany->tva_intra; + $line2 .= ($line2 ? " - " : "").$langs->transnoentities("VATIntraShort").": ".$fromcompany->tva_intra; } print '
    '; @@ -343,16 +350,16 @@ function htmlPrintOnlinePaymentFooter($fromcompany, $langs, $addformmessage = 0, print ''; print '
    '; - $parammessageform='ONLINE_PAYMENT_MESSAGE_FORM_'.$suffix; - if (! empty($conf->global->$parammessageform)) print $langs->transnoentities($conf->global->$parammessageform); - elseif (! empty($conf->global->ONLINE_PAYMENT_MESSAGE_FORM)) print $langs->transnoentities($conf->global->ONLINE_PAYMENT_MESSAGE_FORM); + $parammessageform = 'ONLINE_PAYMENT_MESSAGE_FORM_'.$suffix; + if (!empty($conf->global->$parammessageform)) print $langs->transnoentities($conf->global->$parammessageform); + elseif (!empty($conf->global->ONLINE_PAYMENT_MESSAGE_FORM)) print $langs->transnoentities($conf->global->ONLINE_PAYMENT_MESSAGE_FORM); // Add other message if VAT exists if ($object->total_vat != 0 || $object->total_tva != 0) { - $parammessageform='ONLINE_PAYMENT_MESSAGE_FORMIFVAT_'.$suffix; - if (! empty($conf->global->$parammessageform)) print $langs->transnoentities($conf->global->$parammessageform); - elseif (! empty($conf->global->ONLINE_PAYMENT_MESSAGE_FORMIFVAT)) print $langs->transnoentities($conf->global->ONLINE_PAYMENT_MESSAGE_FORMIFVAT); + $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); } } diff --git a/htdocs/core/lib/pdf.lib.php b/htdocs/core/lib/pdf.lib.php index 918b5ebb6a3..da7d15806f9 100644 --- a/htdocs/core/lib/pdf.lib.php +++ b/htdocs/core/lib/pdf.lib.php @@ -44,37 +44,37 @@ function pdf_getFormat(Translate $outputlangs = null, $mode = 'setup') { global $conf, $db, $langs; - dol_syslog("pdf_getFormat Get paper format with mode=".$mode." MAIN_PDF_FORMAT=".(empty($conf->global->MAIN_PDF_FORMAT)?'null':$conf->global->MAIN_PDF_FORMAT)." outputlangs->defaultlang=".(is_object($outputlangs) ? $outputlangs->defaultlang : 'null')." and langs->defaultlang=".(is_object($langs) ? $langs->defaultlang : 'null')); + dol_syslog("pdf_getFormat Get paper format with mode=".$mode." MAIN_PDF_FORMAT=".(empty($conf->global->MAIN_PDF_FORMAT) ? 'null' : $conf->global->MAIN_PDF_FORMAT)." outputlangs->defaultlang=".(is_object($outputlangs) ? $outputlangs->defaultlang : 'null')." and langs->defaultlang=".(is_object($langs) ? $langs->defaultlang : 'null')); // Default value if setup was not done and/or entry into c_paper_format not defined - $width=210; $height=297; $unit='mm'; + $width = 210; $height = 297; $unit = 'mm'; 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); + $pdfformat = dol_getDefaultFormat($outputlangs); } else { - $pdfformat=$conf->global->MAIN_PDF_FORMAT; + $pdfformat = $conf->global->MAIN_PDF_FORMAT; } - $sql="SELECT code, label, width, height, unit FROM ".MAIN_DB_PREFIX."c_paper_format"; - $sql.=" WHERE code = '".$db->escape($pdfformat)."'"; - $resql=$db->query($sql); + $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) { - $obj=$db->fetch_object($resql); + $obj = $db->fetch_object($resql); if ($obj) { - $width=(int) $obj->width; - $height=(int) $obj->height; - $unit=$obj->unit; + $width = (int) $obj->width; + $height = (int) $obj->height; + $unit = $obj->unit; } } //print "pdfformat=".$pdfformat." width=".$width." height=".$height." unit=".$unit; - return array('width'=>$width,'height'=>$height,'unit'=>$unit); + return array('width'=>$width, 'height'=>$height, 'unit'=>$unit); } /** @@ -90,9 +90,9 @@ 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_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/'); dol_mkdir(K_PATH_CACHE); @@ -119,7 +119,7 @@ function pdf_getInstance($format = '', $metric = 'mm', $pagetype = 'P') define('HEAD_MAGNIFICATION', 1.1); define('K_CELL_HEIGHT_RATIO', 1.25); define('K_TITLE_MAGNIFICATION', 1.3); - define('K_SMALL_RATIO', 2/3); + define('K_SMALL_RATIO', 2 / 3); define('K_THAI_TOPCHARS', true); define('K_TCPDF_CALLS_IN_HTML', true); define('K_TCPDF_THROW_EXCEPTION_ERROR', false); @@ -135,14 +135,14 @@ function pdf_getInstance($format = '', $metric = 'mm', $pagetype = 'P') //$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 + $pdfa = false; // PDF-1.3 + 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); // 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; @@ -157,20 +157,20 @@ function pdf_getInstance($format = '', $metric = 'mm', $pagetype = 'P') */ // For TCPDF, we specify permission we want to block - $pdfrights = (! empty($conf->global->PDF_SECURITY_ENCRYPTION_RIGHTS)?json_decode($conf->global->PDF_SECURITY_ENCRYPTION_RIGHTS, true):array('modify','copy')); // Json format in llx_const + $pdfrights = (!empty($conf->global->PDF_SECURITY_ENCRYPTION_RIGHTS) ?json_decode($conf->global->PDF_SECURITY_ENCRYPTION_RIGHTS, true) : array('modify', 'copy')); // Json format in llx_const // Password for the end user - $pdfuserpass = (! empty($conf->global->PDF_SECURITY_ENCRYPTION_USERPASS)?$conf->global->PDF_SECURITY_ENCRYPTION_USERPASS:''); + $pdfuserpass = (!empty($conf->global->PDF_SECURITY_ENCRYPTION_USERPASS) ? $conf->global->PDF_SECURITY_ENCRYPTION_USERPASS : ''); // Password of the owner, created randomly if not defined - $pdfownerpass = (! empty($conf->global->PDF_SECURITY_ENCRYPTION_OWNERPASS)?$conf->global->PDF_SECURITY_ENCRYPTION_OWNERPASS:null); + $pdfownerpass = (!empty($conf->global->PDF_SECURITY_ENCRYPTION_OWNERPASS) ? $conf->global->PDF_SECURITY_ENCRYPTION_OWNERPASS : null); // For encryption strength: 0 = RC4 40 bit; 1 = RC4 128 bit; 2 = AES 128 bit; 3 = AES 256 bit - $encstrength = (! empty($conf->global->PDF_SECURITY_ENCRYPTION_STRENGTH)?$conf->global->PDF_SECURITY_ENCRYPTION_STRENGTH:0); + $encstrength = (!empty($conf->global->PDF_SECURITY_ENCRYPTION_STRENGTH) ? $conf->global->PDF_SECURITY_ENCRYPTION_STRENGTH : 0); // Array of recipients containing public-key certificates ('c') and permissions ('p'). // For example: array(array('c' => 'file://../examples/data/cert/tcpdf.crt', 'p' => array('print'))) - $pubkeys = (! empty($conf->global->PDF_SECURITY_ENCRYPTION_PUBKEYS)?json_decode($conf->global->PDF_SECURITY_ENCRYPTION_PUBKEYS, true):null); // Json format in llx_const + $pubkeys = (!empty($conf->global->PDF_SECURITY_ENCRYPTION_PUBKEYS) ?json_decode($conf->global->PDF_SECURITY_ENCRYPTION_PUBKEYS, true) : null); // Json format in llx_const $pdf->SetProtection($pdfrights, $pdfuserpass, $pdfownerpass, $encstrength, $pubkeys); } @@ -199,11 +199,11 @@ function pdf_getEncryption($pathoffile) //ob_end_clean(); if (isset($xref['trailer']['encrypt'])) { - $isencrypted = true; // Secured pdf file are currently not supported + $isencrypted = true; // Secured pdf file are currently not supported } if (empty($data)) { - $isencrypted = true; // Object list not found. Possible secured file + $isencrypted = true; // Object list not found. Possible secured file } return $isencrypted; @@ -219,14 +219,14 @@ 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 + $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 ($outputlangs->trans('FONTFORPDF') != 'FONTFORPDF') { - $font=$outputlangs->trans('FONTFORPDF'); + $font = $outputlangs->trans('FONTFORPDF'); } } return $font; @@ -242,7 +242,7 @@ function pdf_getPDFFontSize($outputlangs) { global $conf; - $size=10; // By default, for FPDI or ISO language on TCPDF + $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') @@ -250,7 +250,7 @@ function pdf_getPDFFontSize($outputlangs) $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; } @@ -266,14 +266,14 @@ function pdf_getPDFFontSize($outputlangs) function pdf_getHeightForLogo($logo, $url = false) { global $conf; - $height=(empty($conf->global->MAIN_DOCUMENTS_LOGO_HEIGHT)?22:$conf->global->MAIN_DOCUMENTS_LOGO_HEIGHT); - $maxwidth=130; + $height = (empty($conf->global->MAIN_DOCUMENTS_LOGO_HEIGHT) ? 22 : $conf->global->MAIN_DOCUMENTS_LOGO_HEIGHT); + $maxwidth = 130; include_once DOL_DOCUMENT_ROOT.'/core/lib/images.lib.php'; - $tmp=dol_getImageSize($logo, $url); + $tmp = dol_getImageSize($logo, $url); if ($tmp['height']) { - $width=round($height*$tmp['width']/$tmp['height']); - if ($width > $maxwidth) $height=$height*$maxwidth/$width; + $width = round($height * $tmp['width'] / $tmp['height']); + if ($width > $maxwidth) $height = $height * $maxwidth / $width; } //print $tmp['width'].' '.$tmp['height'].' '.$width; exit; return $height; @@ -307,9 +307,9 @@ function pdfGetHeightForHtmlContent(&$pdf, $htmlcontent) } else { - for ($page=$start_page; $page <= $end_page; ++$page) { + for ($page = $start_page; $page <= $end_page; ++$page) { $pdf->setPage($page); - $tmpm=$pdf->getMargins(); + $tmpm = $pdf->getMargins(); $tMargin = $tmpm['top']; if ($page == $start_page) { // first page @@ -346,7 +346,7 @@ function pdfBuildThirdpartyName($thirdparty, Translate $outputlangs, $includeali if ($thirdparty instanceof Societe) { $socname .= $thirdparty->name; - if (($includealias || ! empty($conf->global->PDF_INCLUDE_ALIAS_IN_THIRDPARTY_NAME)) && !empty($thirdparty->name_alias)) { + if (($includealias || !empty($conf->global->PDF_INCLUDE_ALIAS_IN_THIRDPARTY_NAME)) && !empty($thirdparty->name_alias)) { $socname .= "\n".$thirdparty->name_alias; } } elseif ($thirdparty instanceof Contact) { @@ -375,20 +375,20 @@ 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; + $reshook = 0; $stringaddress = ''; 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; + $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)) { @@ -397,60 +397,64 @@ function pdf_build_address($outputlangs, $sourcecompany, $targetcompany = '', $t $withCountry = 0; 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"; + $stringaddress .= ($stringaddress ? "\n" : '').$outputlangs->convToOutputCharset(dol_format_address($sourcecompany, $withCountry, "\n", $outputlangs))."\n"; 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 (!empty($conf->global->MAIN_TVAINTRA_IN_SOURCE_ADDRESS)) { - if ($sourcecompany->tva_intra) $stringaddress.=($stringaddress ? "\n" : '' ).$outputlangs->transnoentities("VATIntraShort").': '.$outputlangs->convToOutputCharset($sourcecompany->tva_intra); + if ($sourcecompany->tva_intra) $stringaddress .= ($stringaddress ? "\n" : '').$outputlangs->transnoentities("VATIntraShort").': '.$outputlangs->convToOutputCharset($sourcecompany->tva_intra); } // Professionnal Ids - if (! empty($conf->global->MAIN_PROFID1_IN_SOURCE_ADDRESS) && ! empty($sourcecompany->idprof1)) + $reg = array(); + 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]; - $stringaddress.=($stringaddress ? "\n" : '' ).$tmp.': '.$outputlangs->convToOutputCharset($sourcecompany->idprof1); + $tmp = $outputlangs->transcountrynoentities("ProfId1", $sourcecompany->country_code); + 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]; - $stringaddress.=($stringaddress ? "\n" : '' ).$tmp.': '.$outputlangs->convToOutputCharset($sourcecompany->idprof2); + $tmp = $outputlangs->transcountrynoentities("ProfId2", $sourcecompany->country_code); + 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]; - $stringaddress.=($stringaddress ? "\n" : '' ).$tmp.': '.$outputlangs->convToOutputCharset($sourcecompany->idprof3); + $tmp = $outputlangs->transcountrynoentities("ProfId3", $sourcecompany->country_code); + 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]; - $stringaddress.=($stringaddress ? "\n" : '' ).$tmp.': '.$outputlangs->convToOutputCharset($sourcecompany->idprof4); + $tmp = $outputlangs->transcountrynoentities("ProfId4", $sourcecompany->country_code); + 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]; - $stringaddress.=($stringaddress ? "\n" : '' ).$tmp.': '.$outputlangs->convToOutputCharset($sourcecompany->idprof5); + $tmp = $outputlangs->transcountrynoentities("ProfId5", $sourcecompany->country_code); + 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]; - $stringaddress.=($stringaddress ? "\n" : '' ).$tmp.': '.$outputlangs->convToOutputCharset($sourcecompany->idprof6); + $tmp = $outputlangs->transcountrynoentities("ProfId6", $sourcecompany->country_code); + 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)) { + $stringaddress .= ($stringaddress ? "\n" : '').$conf->global->PDF_ADD_MORE_AFTER_SOURCE_ADDRESS; } } @@ -458,10 +462,10 @@ function pdf_build_address($outputlangs, $sourcecompany, $targetcompany = '', $t { if ($usecontact) { - $stringaddress .= ($stringaddress ? "\n" : '' ).$outputlangs->convToOutputCharset($targetcontact->getFullName($outputlangs, 1)); + $stringaddress .= ($stringaddress ? "\n" : '').$outputlangs->convToOutputCharset($targetcontact->getFullName($outputlangs, 1)); if (!empty($targetcontact->address)) { - $stringaddress .= ($stringaddress ? "\n" : '' ).$outputlangs->convToOutputCharset(dol_format_address($targetcontact)); + $stringaddress .= ($stringaddress ? "\n" : '').$outputlangs->convToOutputCharset(dol_format_address($targetcontact)); } else { $companytouseforaddress = $targetcompany; @@ -472,73 +476,73 @@ function pdf_build_address($outputlangs, $sourcecompany, $targetcompany = '', $t $companytouseforaddress = $targetcontact->thirdparty; } - $stringaddress .= ($stringaddress ? "\n" : '' ).$outputlangs->convToOutputCharset(dol_format_address($companytouseforaddress)); + $stringaddress .= ($stringaddress ? "\n" : '').$outputlangs->convToOutputCharset(dol_format_address($companytouseforaddress)); } // Country if (!empty($targetcontact->country_code) && $targetcontact->country_code != $sourcecompany->country_code) { - $stringaddress.= ($stringaddress ? "\n" : '' ).$outputlangs->convToOutputCharset($outputlangs->transnoentitiesnoconv("Country".$targetcontact->country_code)); + $stringaddress .= ($stringaddress ? "\n" : '').$outputlangs->convToOutputCharset($outputlangs->transnoentitiesnoconv("Country".$targetcontact->country_code)); } elseif (empty($targetcontact->country_code) && !empty($targetcompany->country_code) && ($targetcompany->country_code != $sourcecompany->country_code)) { - $stringaddress.= ($stringaddress ? "\n" : '' ).$outputlangs->convToOutputCharset($outputlangs->transnoentitiesnoconv("Country".$targetcompany->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($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($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 (!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 ($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 (!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 ($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 (!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 ($targetcontact->url) $stringaddress .= ($stringaddress ? "\n" : '').$outputlangs->transnoentities("Web").": ".$outputlangs->convToOutputCharset($targetcontact->url); } } } else { - $stringaddress .= ($stringaddress ? "\n" : '' ).$outputlangs->convToOutputCharset(dol_format_address($targetcompany)); + $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($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($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 (!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 ($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 (!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 ($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 (!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 ($targetcompany->url) $stringaddress .= ($stringaddress ? "\n" : '').$outputlangs->transnoentities("Web").": ".$outputlangs->convToOutputCharset($targetcompany->url); } } } @@ -546,57 +550,57 @@ function pdf_build_address($outputlangs, $sourcecompany, $targetcompany = '', $t // 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 ($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]; - $stringaddress.=($stringaddress ? "\n" : '' ).$tmp.': '.$outputlangs->convToOutputCharset($targetcompany->idprof1); + $tmp = $outputlangs->transcountrynoentities("ProfId1", $targetcompany->country_code); + 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]; - $stringaddress.=($stringaddress ? "\n" : '' ).$tmp.': '.$outputlangs->convToOutputCharset($targetcompany->idprof2); + $tmp = $outputlangs->transcountrynoentities("ProfId2", $targetcompany->country_code); + 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]; - $stringaddress.=($stringaddress ? "\n" : '' ).$tmp.': '.$outputlangs->convToOutputCharset($targetcompany->idprof3); + $tmp = $outputlangs->transcountrynoentities("ProfId3", $targetcompany->country_code); + 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]; - $stringaddress.=($stringaddress ? "\n" : '' ).$tmp.': '.$outputlangs->convToOutputCharset($targetcompany->idprof4); + $tmp = $outputlangs->transcountrynoentities("ProfId4", $targetcompany->country_code); + 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]; - $stringaddress.=($stringaddress ? "\n" : '' ).$tmp.': '.$outputlangs->convToOutputCharset($targetcompany->idprof5); + $tmp = $outputlangs->transcountrynoentities("ProfId5", $targetcompany->country_code); + 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]; - $stringaddress.=($stringaddress ? "\n" : '' ).$tmp.': '.$outputlangs->convToOutputCharset($targetcompany->idprof6); + $tmp = $outputlangs->transcountrynoentities("ProfId6", $targetcompany->country_code); + 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 (!empty($conf->global->MAIN_PUBLIC_NOTE_IN_ADDRESS)) { - if ($mode == 'source' && ! empty($sourcecompany->note_public)) + if ($mode == 'source' && !empty($sourcecompany->note_public)) { - $stringaddress.=($stringaddress ? "\n" : '' ).dol_string_nohtmltag($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); + $stringaddress .= ($stringaddress ? "\n" : '').dol_string_nohtmltag($targetcompany->note_public); } } } @@ -619,11 +623,11 @@ 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 + $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 } } @@ -640,8 +644,8 @@ function pdf_pagehead(&$pdf, $outputlangs, $page_height) function pdf_getSubstitutionArray($outputlangs, $exclude = null, $object = null, $onlykey = 0) { $substitutionarray = getCommonSubstitutionArray($outputlangs, $onlykey, $exclude, $object); - $substitutionarray['__FROM_NAME__']='__FROM_NAME__'; - $substitutionarray['__FROM_EMAIL__']='__FROM_EMAIL__'; + $substitutionarray['__FROM_NAME__'] = '__FROM_NAME__'; + $substitutionarray['__FROM_EMAIL__'] = '__FROM_EMAIL__'; return $substitutionarray; } @@ -662,31 +666,31 @@ 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); + $substitutionarray = pdf_getSubstitutionArray($outputlangs, null, null); complete_substitutions_array($substitutionarray, $outputlangs, null); - $text=make_substitutions($text, $substitutionarray, $outputlangs); - $text=$outputlangs->convToOutputCharset($text); + $text = make_substitutions($text, $substitutionarray, $outputlangs); + $text = $outputlangs->convToOutputCharset($text); - $savx=$pdf->getX(); $savy=$pdf->getY(); + $savx = $pdf->getX(); $savy = $pdf->getY(); - $watermark_angle=atan($h/$w)/2; - $watermark_x_pos=0; - $watermark_y_pos=$h/3; - $watermark_x=$w/2; - $watermark_y=$h/3; + $watermark_angle = atan($h / $w) / 2; + $watermark_x_pos = 0; + $watermark_y_pos = $h / 3; + $watermark_x = $w / 2; + $watermark_y = $h / 3; $pdf->SetFont('', 'B', 40); $pdf->SetTextColor(255, 192, 203); //rotate - $pdf->_out(sprintf('q %.5F %.5F %.5F %.5F %.2F %.2F cm 1 0 0 1 %.2F %.2F cm', cos($watermark_angle), sin($watermark_angle), -sin($watermark_angle), cos($watermark_angle), $watermark_x*$k, ($h-$watermark_y)*$k, -$watermark_x*$k, -($h-$watermark_y)*$k)); + $pdf->_out(sprintf('q %.5F %.5F %.5F %.5F %.2F %.2F cm 1 0 0 1 %.2F %.2F cm', cos($watermark_angle), sin($watermark_angle), -sin($watermark_angle), cos($watermark_angle), $watermark_x * $k, ($h - $watermark_y) * $k, -$watermark_x * $k, -($h - $watermark_y) * $k)); //print watermark $pdf->SetXY($watermark_x_pos, $watermark_y_pos); - $pdf->Cell($w-20, 25, $outputlangs->convToOutputCharset($text), "", 2, "C", 0); + $pdf->Cell($w - 20, 25, $outputlangs->convToOutputCharset($text), "", 2, "C", 0); //antirotate $pdf->_out('Q'); @@ -712,37 +716,37 @@ function pdf_bank(&$pdf, $outputlangs, $curx, $cury, $account, $onlynumber = 0, require_once DOL_DOCUMENT_ROOT.'/core/class/html.formbank.class.php'; - $diffsizetitle=(empty($conf->global->PDF_DIFFSIZE_TITLE)?3:$conf->global->PDF_DIFFSIZE_TITLE); - $diffsizecontent=(empty($conf->global->PDF_DIFFSIZE_CONTENT)?4:$conf->global->PDF_DIFFSIZE_CONTENT); + $diffsizetitle = (empty($conf->global->PDF_DIFFSIZE_TITLE) ? 3 : $conf->global->PDF_DIFFSIZE_TITLE); + $diffsizecontent = (empty($conf->global->PDF_DIFFSIZE_CONTENT) ? 4 : $conf->global->PDF_DIFFSIZE_CONTENT); $pdf->SetXY($curx, $cury); if (empty($onlynumber)) { $pdf->SetFont('', 'B', $default_font_size - $diffsizetitle); $pdf->MultiCell(100, 3, $outputlangs->transnoentities('PaymentByTransferOnThisBankAccount').':', 0, 'L', 0); - $cury+=4; + $cury += 4; } $outputlangs->load("banks"); // Use correct name of bank id according to country - $bickey="BICNumber"; - if ($account->getCountryCode() == 'IN') $bickey="SWIFT"; + $bickey = "BICNumber"; + if ($account->getCountryCode() == 'IN') $bickey = "SWIFT"; // Get format of bank account according to its country - $usedetailedbban=$account->useDetailedBBAN(); + $usedetailedbban = $account->useDetailedBBAN(); //$onlynumber=0; $usedetailedbban=1; // For tests if ($usedetailedbban) { - $savcurx=$curx; + $savcurx = $curx; 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; + $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 @@ -752,12 +756,12 @@ function pdf_bank(&$pdf, $outputlangs, $curx, $cury, $account, $onlynumber = 0, // 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) { - $pdf->SetXY($curx, $cury+4); + $pdf->SetXY($curx, $cury + 4); $pdf->SetFont('', '', $default_font_size - 3); if ($val == 'BankCode') { @@ -795,54 +799,54 @@ function pdf_bank(&$pdf, $outputlangs, $curx, $cury, $account, $onlynumber = 0, } } - $curx=$savcurx; - $cury+=8; + $curx = $savcurx; + $cury += 8; } } else { $pdf->SetFont('', 'B', $default_font_size - $diffsizecontent); $pdf->SetXY($curx, $cury); - $pdf->MultiCell(100, 3, $outputlangs->transnoentities("Bank").': ' . $outputlangs->convToOutputCharset($account->bank), 0, 'L', 0); - $cury+=3; + $pdf->MultiCell(100, 3, $outputlangs->transnoentities("Bank").': '.$outputlangs->convToOutputCharset($account->bank), 0, 'L', 0); + $cury += 3; $pdf->SetFont('', 'B', $default_font_size - $diffsizecontent); $pdf->SetXY($curx, $cury); - $pdf->MultiCell(100, 3, $outputlangs->transnoentities("BankAccountNumber").': ' . $outputlangs->convToOutputCharset($account->number), 0, 'L', 0); - $cury+=3; + $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); - if (empty($onlynumber) && ! empty($account->domiciliation)) + if (empty($onlynumber) && !empty($account->domiciliation)) { $pdf->SetXY($curx, $cury); - $val=$outputlangs->transnoentities("Residence").': ' . $outputlangs->convToOutputCharset($account->domiciliation); + $val = $outputlangs->transnoentities("Residence").': '.$outputlangs->convToOutputCharset($account->domiciliation); $pdf->MultiCell(100, 3, $val, 0, 'L', 0); //$nboflines=dol_nboflines_bis($val,120); //$cury+=($nboflines*3)+2; - $tmpy=$pdf->getStringHeight(100, $val); - $cury+=$tmpy; + $tmpy = $pdf->getStringHeight(100, $val); + $cury += $tmpy; } - if (! empty($account->proprio)) + if (!empty($account->proprio)) { $pdf->SetXY($curx, $cury); - $val=$outputlangs->transnoentities("BankAccountOwner").': ' . $outputlangs->convToOutputCharset($account->proprio); + $val = $outputlangs->transnoentities("BankAccountOwner").': '.$outputlangs->convToOutputCharset($account->proprio); $pdf->MultiCell(100, 3, $val, 0, 'L', 0); - $tmpy=$pdf->getStringHeight(100, $val); - $cury+=$tmpy; - $cur+=1; + $tmpy = $pdf->getStringHeight(100, $val); + $cury += $tmpy; + $cur += 1; } - elseif (! $usedetailedbban) $cury+=1; + elseif (!$usedetailedbban) $cury += 1; // 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)); @@ -852,20 +856,20 @@ function pdf_bank(&$pdf, $outputlangs, $curx, $cury, $account, $onlynumber = 0, 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); $pdf->SetXY($curx, $cury); - $pdf->MultiCell(100, 3, $outputlangs->transnoentities($ibankey).': ' . $ibanDisplay, 0, 'L', 0); - $cury+=3; + $pdf->MultiCell(100, 3, $outputlangs->transnoentities($ibankey).': '.$ibanDisplay, 0, 'L', 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); + $pdf->MultiCell(100, 3, $outputlangs->transnoentities($bickey).': '.$outputlangs->convToOutputCharset($account->bic), 0, 'L', 0); } return $pdf->getY(); @@ -888,82 +892,82 @@ function pdf_bank(&$pdf, $outputlangs, $curx, $cury, $account, $onlynumber = 0, */ function pdf_pagefoot(&$pdf, $outputlangs, $paramfreetext, $fromcompany, $marge_basse, $marge_gauche, $page_hauteur, $object, $showdetails = 0, $hidefreetext = 0) { - global $conf,$user,$mysoc; + global $conf, $user, $mysoc; $outputlangs->load("dict"); - $line=''; + $line = ''; - $dims=$pdf->getPageDimensions(); + $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); + $substitutionarray = pdf_getSubstitutionArray($outputlangs, null, $object); // More substitution keys - $substitutionarray['__FROM_NAME__']=$fromcompany->name; - $substitutionarray['__FROM_EMAIL__']=$fromcompany->email; + $substitutionarray['__FROM_NAME__'] = $fromcompany->name; + $substitutionarray['__FROM_EMAIL__'] = $fromcompany->email; complete_substitutions_array($substitutionarray, $outputlangs, $object); - $newfreetext=make_substitutions($conf->global->$paramfreetext, $substitutionarray, $outputlangs); + $newfreetext = make_substitutions($conf->global->$paramfreetext, $substitutionarray, $outputlangs); // Make a change into HTML code to allow to include images from medias directory. // // become // - $newfreetext=preg_replace('/()/', '\1'.DOL_DATA_ROOT.'/medias/\2\3', $newfreetext); + $newfreetext = preg_replace('/()/', '\1'.DOL_DATA_ROOT.'/medias/\2\3', $newfreetext); - $line.=$outputlangs->convToOutputCharset($newfreetext); + $line .= $outputlangs->convToOutputCharset($newfreetext); } // First line of company infos - $line1=""; $line2=""; $line3=""; $line4=""; + $line1 = ""; $line2 = ""; $line3 = ""; $line4 = ""; if ($showdetails == 1 || $showdetails == 3) { // Company name if ($fromcompany->name) { - $line1.=($line1?" - ":"").$outputlangs->transnoentities("RegisteredOffice").": ".$fromcompany->name; + $line1 .= ($line1 ? " - " : "").$outputlangs->transnoentities("RegisteredOffice").": ".$fromcompany->name; } // Address if ($fromcompany->address) { - $line1.=($line1?" - ":"").str_replace("\n", ", ", $fromcompany->address); + $line1 .= ($line1 ? " - " : "").str_replace("\n", ", ", $fromcompany->address); } // Zip code if ($fromcompany->zip) { - $line1.=($line1?" - ":"").$fromcompany->zip; + $line1 .= ($line1 ? " - " : "").$fromcompany->zip; } // Town if ($fromcompany->town) { - $line1.=($line1?" ":"").$fromcompany->town; + $line1 .= ($line1 ? " " : "").$fromcompany->town; } // Country if ($fromcompany->country) { - $line1.=($line1?", ":"").$fromcompany->country; + $line1 .= ($line1 ? ", " : "").$fromcompany->country; } // Phone if ($fromcompany->phone) { - $line2.=($line2?" - ":"").$outputlangs->transnoentities("Phone").": ".$fromcompany->phone; + $line2 .= ($line2 ? " - " : "").$outputlangs->transnoentities("Phone").": ".$fromcompany->phone; } // Fax if ($fromcompany->fax) { - $line2.=($line2?" - ":"").$outputlangs->transnoentities("Fax").": ".$fromcompany->fax; + $line2 .= ($line2 ? " - " : "").$outputlangs->transnoentities("Fax").": ".$fromcompany->fax; } // URL if ($fromcompany->url) { - $line2.=($line2?" - ":"").$fromcompany->url; + $line2 .= ($line2 ? " - " : "").$fromcompany->url; } // Email if ($fromcompany->email) { - $line2.=($line2?" - ":"").$fromcompany->email; + $line2 .= ($line2 ? " - " : "").$fromcompany->email; } } if ($showdetails == 2 || $showdetails == 3 || ($fromcompany->country_code == 'DE')) @@ -971,7 +975,7 @@ function pdf_pagefoot(&$pdf, $outputlangs, $paramfreetext, $fromcompany, $marge_ // Managers if ($fromcompany->managers) { - $line2.=($line2?" - ":"").$fromcompany->managers; + $line2 .= ($line2 ? " - " : "").$fromcompany->managers; } } @@ -979,90 +983,90 @@ function pdf_pagefoot(&$pdf, $outputlangs, $paramfreetext, $fromcompany, $marge_ // Juridical status if ($fromcompany->forme_juridique_code) { - $line3.=($line3?" - ":"").$outputlangs->convToOutputCharset(getFormeJuridiqueLabel($fromcompany->forme_juridique_code)); + $line3 .= ($line3 ? " - " : "").$outputlangs->convToOutputCharset(getFormeJuridiqueLabel($fromcompany->forme_juridique_code)); } // 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]; - $line3.=($line3?" - ":"").$field.": ".$outputlangs->convToOutputCharset($fromcompany->idprof1); + $field = $outputlangs->transcountrynoentities("ProfId1", $fromcompany->country_code); + if (preg_match('/\((.*)\)/i', $field, $reg)) $field = $reg[1]; + $line3 .= ($line3 ? " - " : "").$field.": ".$outputlangs->convToOutputCharset($fromcompany->idprof1); } // Prof Id 2 if ($fromcompany->idprof2) { - $field=$outputlangs->transcountrynoentities("ProfId2", $fromcompany->country_code); - if (preg_match('/\((.*)\)/i', $field, $reg)) $field=$reg[1]; - $line3.=($line3?" - ":"").$field.": ".$outputlangs->convToOutputCharset($fromcompany->idprof2); + $field = $outputlangs->transcountrynoentities("ProfId2", $fromcompany->country_code); + 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) { - $field=$outputlangs->transcountrynoentities("ProfId3", $fromcompany->country_code); - if (preg_match('/\((.*)\)/i', $field, $reg)) $field=$reg[1]; - $line4.=($line4?" - ":"").$field.": ".$outputlangs->convToOutputCharset($fromcompany->idprof3); + $field = $outputlangs->transcountrynoentities("ProfId3", $fromcompany->country_code); + if (preg_match('/\((.*)\)/i', $field, $reg)) $field = $reg[1]; + $line4 .= ($line4 ? " - " : "").$field.": ".$outputlangs->convToOutputCharset($fromcompany->idprof3); } // Prof Id 4 if ($fromcompany->idprof4) { - $field=$outputlangs->transcountrynoentities("ProfId4", $fromcompany->country_code); - if (preg_match('/\((.*)\)/i', $field, $reg)) $field=$reg[1]; - $line4.=($line4?" - ":"").$field.": ".$outputlangs->convToOutputCharset($fromcompany->idprof4); + $field = $outputlangs->transcountrynoentities("ProfId4", $fromcompany->country_code); + if (preg_match('/\((.*)\)/i', $field, $reg)) $field = $reg[1]; + $line4 .= ($line4 ? " - " : "").$field.": ".$outputlangs->convToOutputCharset($fromcompany->idprof4); } // Prof Id 5 if ($fromcompany->idprof5) { - $field=$outputlangs->transcountrynoentities("ProfId5", $fromcompany->country_code); - if (preg_match('/\((.*)\)/i', $field, $reg)) $field=$reg[1]; - $line4.=($line4?" - ":"").$field.": ".$outputlangs->convToOutputCharset($fromcompany->idprof5); + $field = $outputlangs->transcountrynoentities("ProfId5", $fromcompany->country_code); + if (preg_match('/\((.*)\)/i', $field, $reg)) $field = $reg[1]; + $line4 .= ($line4 ? " - " : "").$field.": ".$outputlangs->convToOutputCharset($fromcompany->idprof5); } // Prof Id 6 if ($fromcompany->idprof6) { - $field=$outputlangs->transcountrynoentities("ProfId6", $fromcompany->country_code); - if (preg_match('/\((.*)\)/i', $field, $reg)) $field=$reg[1]; - $line4.=($line4?" - ":"").$field.": ".$outputlangs->convToOutputCharset($fromcompany->idprof6); + $field = $outputlangs->transcountrynoentities("ProfId6", $fromcompany->country_code); + if (preg_match('/\((.*)\)/i', $field, $reg)) $field = $reg[1]; + $line4 .= ($line4 ? " - " : "").$field.": ".$outputlangs->convToOutputCharset($fromcompany->idprof6); } // IntraCommunautary VAT if ($fromcompany->tva_intra != '') { - $line4.=($line4?" - ":"").$outputlangs->transnoentities("VATIntraShort").": ".$outputlangs->convToOutputCharset($fromcompany->tva_intra); + $line4 .= ($line4 ? " - " : "").$outputlangs->transnoentities("VATIntraShort").": ".$outputlangs->convToOutputCharset($fromcompany->tva_intra); } $pdf->SetFont('', '', 7); $pdf->SetDrawColor(224, 224, 224); // The start of the bottom of this page footer is positioned according to # of lines - $freetextheight=0; + $freetextheight = 0; if ($line) // Free text { //$line="sample text
    \nfdsfsdf
    \nghfghg
    "; 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'; + $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'; } - $freetextheight=$pdf->getStringHeight($width, $line); + $freetextheight = $pdf->getStringHeight($width, $line); } else { - $freetextheight=pdfGetHeightForHtmlContent($pdf, dol_htmlentitiesbr($line, 1, 'UTF-8', 0)); // New method (works for HTML content) + $freetextheight = pdfGetHeightForHtmlContent($pdf, dol_htmlentitiesbr($line, 1, 'UTF-8', 0)); // New method (works for HTML content) //print '
    '.$freetextheight;exit; } } - $marginwithfooter=$marge_basse + $freetextheight + (! empty($line1)?3:0) + (! empty($line2)?3:0) + (! empty($line3)?3:0) + (! empty($line4)?3:0); - $posy=$marginwithfooter+0; + $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 { @@ -1073,50 +1077,50 @@ function pdf_pagefoot(&$pdf, $outputlangs, $paramfreetext, $fromcompany, $marge_ } 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)); + $pdf->writeHTMLCell($pdf->page_largeur - $pdf->margin_left - $pdf->margin_right, $freetextheight, $dims['lm'], $dims['hk'] - $marginwithfooter, dol_htmlentitiesbr($line, 1, 'UTF-8', 0)); } - $posy-=$freetextheight; + $posy -= $freetextheight; } $pdf->SetY(-$posy); - $pdf->line($dims['lm'], $dims['hk']-$posy, $dims['wk']-$dims['rm'], $dims['hk']-$posy); + $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); - $posy-=3; + $pdf->MultiCell($dims['wk'] - $dims['rm'] - $dims['lm'], 2, $line1, 0, 'C', 0); + $posy -= 3; $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); - $posy-=3; + $pdf->MultiCell($dims['wk'] - $dims['rm'] - $dims['lm'], 2, $line2, 0, 'C', 0); + $posy -= 3; $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); + $pdf->MultiCell($dims['wk'] - $dims['rm'] - $dims['lm'], 2, $line3, 0, 'C', 0); } - if (! empty($line4)) + if (!empty($line4)) { - $posy-=3; + $posy -= 3; $pdf->SetXY($dims['lm'], -$posy); - $pdf->MultiCell($dims['wk']-$dims['rm']-$dims['lm'], 2, $line4, 0, 'C', 0); + $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') { - $pdf->SetXY($dims['wk']-$dims['rm']-15, -$posy); + $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); } @@ -1141,17 +1145,17 @@ 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)) + if (!empty($linkedobjects)) { - foreach($linkedobjects as $linkedobject) + 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"]; } - $posy+=3; + $posy += 3; $pdf->SetXY($posx, $posy); $pdf->SetFont('', '', $default_font_size - 2); $pdf->MultiCell($w, $h, $reftoshow, '', $align); @@ -1181,22 +1185,22 @@ function pdf_writelinedesc(&$pdf, $object, $i, $outputlangs, $w, $h, $posx, $pos { global $db, $conf, $langs, $hookmanager; - $reshook=0; - $result=''; + $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 { $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); - $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($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)) { - $labelproductservice=pdf_getlinedesc($object, $i, $outputlangs, $hideref, $hidedesc, $issupplierline); + $labelproductservice = pdf_getlinedesc($object, $i, $outputlangs, $hideref, $hidedesc, $issupplierline); //var_dump($labelproductservice);exit; @@ -1208,7 +1212,7 @@ function pdf_writelinedesc(&$pdf, $object, $i, $outputlangs, $w, $h, $posx, $pos // Description $pdf->writeHTMLCell($w, $h, $posx, $posy, $outputlangs->convToOutputCharset($labelproductservice), 0, 1, false, true, 'J', true); - $result.=$labelproductservice; + $result .= $labelproductservice; } return $result; } @@ -1228,12 +1232,12 @@ function pdf_getlinedesc($object, $i, $outputlangs, $hideref = 0, $hidedesc = 0, { global $db, $conf, $langs; - $idprod=(! empty($object->lines[$i]->fk_product)?$object->lines[$i]->fk_product:false); - $label=(! empty($object->lines[$i]->label)?$object->lines[$i]->label:(! empty($object->lines[$i]->product_label)?$object->lines[$i]->product_label:'')); - $desc=(! empty($object->lines[$i]->desc)?$object->lines[$i]->desc:(! empty($object->lines[$i]->description)?$object->lines[$i]->description:'')); - $ref_supplier=(! empty($object->lines[$i]->ref_supplier)?$object->lines[$i]->ref_supplier:(! empty($object->lines[$i]->ref_fourn)?$object->lines[$i]->ref_fourn:'')); // TODO Not yet saved for supplier invoices, only supplier orders - $note=(! empty($object->lines[$i]->note)?$object->lines[$i]->note:''); - $dbatch=(! empty($object->lines[$i]->detail_batch)?$object->lines[$i]->detail_batch:false); + $idprod = (!empty($object->lines[$i]->fk_product) ? $object->lines[$i]->fk_product : false); + $label = (!empty($object->lines[$i]->label) ? $object->lines[$i]->label : (!empty($object->lines[$i]->product_label) ? $object->lines[$i]->product_label : '')); + $desc = (!empty($object->lines[$i]->desc) ? $object->lines[$i]->desc : (!empty($object->lines[$i]->description) ? $object->lines[$i]->description : '')); + $ref_supplier = (!empty($object->lines[$i]->ref_supplier) ? $object->lines[$i]->ref_supplier : (!empty($object->lines[$i]->ref_fourn) ? $object->lines[$i]->ref_fourn : '')); // TODO Not yet saved for supplier invoices, only supplier orders + $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) { @@ -1250,9 +1254,9 @@ function pdf_getlinedesc($object, $i, $outputlangs, $hideref = 0, $hidedesc = 0, { $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) + $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 // ($textwasmodified is replaced with $textwasmodifiedorcompleted and we add completion). @@ -1260,63 +1264,63 @@ function pdf_getlinedesc($object, $i, $outputlangs, $hideref = 0, $hidedesc = 0, // Set label // If we want another language, and if label is same than default language (we did force it to a specific value), we can use translation. //var_dump($outputlangs->defaultlang.' - '.$langs->defaultlang.' - '.$label.' - '.$prodser->label);exit; - $textwasmodified=($label == $prodser->label); - if (! empty($prodser->multilangs[$outputlangs->defaultlang]["label"]) && ($textwasmodified || $translatealsoifmodified)) $label=$prodser->multilangs[$outputlangs->defaultlang]["label"]; + $textwasmodified = ($label == $prodser->label); + if (!empty($prodser->multilangs[$outputlangs->defaultlang]["label"]) && ($textwasmodified || $translatealsoifmodified)) $label = $prodser->multilangs[$outputlangs->defaultlang]["label"]; // Set desc // Manage HTML entities description test because $prodser->description is store with htmlentities but $desc no - $textwasmodified=false; + $textwasmodified = false; if (!empty($desc) && dol_textishtml($desc) && !empty($prodser->description) && dol_textishtml($prodser->description)) { - $textwasmodified=(strpos(dol_html_entity_decode($desc, ENT_QUOTES | ENT_HTML401), dol_html_entity_decode($prodser->description, ENT_QUOTES | ENT_HTML401))!==false); + $textwasmodified = (strpos(dol_html_entity_decode($desc, ENT_QUOTES | ENT_HTML401), dol_html_entity_decode($prodser->description, ENT_QUOTES | ENT_HTML401)) !== false); } else { - $textwasmodified=($desc == $prodser->description); + $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"]; + $textwasmodified = ($note == $prodser->note); + if (!empty($prodser->multilangs[$outputlangs->defaultlang]["note"]) && ($textwasmodified || $translatealsoifmodified)) $note = $prodser->multilangs[$outputlangs->defaultlang]["note"]; } } // Description short of product line - $libelleproduitservice=$label; + $libelleproduitservice = $label; // Description long of product line - if (! empty($desc) && ($desc != $label)) + if (!empty($desc) && ($desc != $label)) { if ($libelleproduitservice && empty($hidedesc)) { - $libelleproduitservice.='__N__'; + $libelleproduitservice .= '__N__'; } if ($desc == '(CREDIT_NOTE)' && $object->lines[$i]->fk_remise_except) { - $discount=new DiscountAbsolute($db); + $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); + $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) { - $discount=new DiscountAbsolute($db); + $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); + $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)) echo ' ('.dol_print_date($discount->datec, 'day', '', $outputlangs).')'; + if (!empty($conf->global->INVOICE_ADD_DEPOSIT_DATE)) echo ' ('.dol_print_date($discount->datec, 'day', '', $outputlangs).')'; } if ($desc == '(EXCESS RECEIVED)' && $object->lines[$i]->fk_remise_except) { - $discount=new DiscountAbsolute($db); + $discount = new DiscountAbsolute($db); $discount->fetch($object->lines[$i]->fk_remise_except); - $libelleproduitservice=$outputlangs->transnoentitiesnoconv("DiscountFromExcessReceived", $discount->ref_facture_source); + $libelleproduitservice = $outputlangs->transnoentitiesnoconv("DiscountFromExcessReceived", $discount->ref_facture_source); } elseif ($desc == '(EXCESS PAID)' && $object->lines[$i]->fk_remise_except) { - $discount=new DiscountAbsolute($db); + $discount = new DiscountAbsolute($db); $discount->fetch($object->lines[$i]->fk_remise_except); - $libelleproduitservice=$outputlangs->transnoentitiesnoconv("DiscountFromExcessPaid", $discount->ref_invoice_supplier_source); + $libelleproduitservice = $outputlangs->transnoentitiesnoconv("DiscountFromExcessPaid", $discount->ref_invoice_supplier_source); } else { @@ -1326,17 +1330,17 @@ function pdf_getlinedesc($object, $i, $outputlangs, $hideref = 0, $hidedesc = 0, { if (!empty($conf->global->MAIN_DOCUMENTS_DESCRIPTION_FIRST)) { - $libelleproduitservice=$desc."\n".$libelleproduitservice; + $libelleproduitservice = $desc."\n".$libelleproduitservice; } else { - $libelleproduitservice.=$desc; + $libelleproduitservice .= $desc; } } } else { - $libelleproduitservice.=$desc; + $libelleproduitservice .= $desc; } } } @@ -1344,7 +1348,7 @@ function pdf_getlinedesc($object, $i, $outputlangs, $hideref = 0, $hidedesc = 0, // We add ref of product (and supplier ref if defined) $prefix_prodserv = ""; $ref_prodserv = ""; - if (! empty($conf->global->PRODUCT_ADD_TYPE_IN_DOCUMENTS)) // In standard mode, we do not show this + if (!empty($conf->global->PRODUCT_ADD_TYPE_IN_DOCUMENTS)) // In standard mode, we do not show this { if ($prodser->isService()) { @@ -1363,11 +1367,11 @@ function pdf_getlinedesc($object, $i, $outputlangs, $hideref = 0, $hidedesc = 0, if ($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) - $ref_prodserv = $ref_supplier. ' ('.$outputlangs->transnoentitiesnoconv("InternalRef").' '.$prodser->ref.')'; + $ref_prodserv = $ref_supplier.' ('.$outputlangs->transnoentitiesnoconv("InternalRef").' '.$prodser->ref.')'; else // 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 ? ')' : ''); } } else @@ -1375,72 +1379,72 @@ function pdf_getlinedesc($object, $i, $outputlangs, $hideref = 0, $hidedesc = 0, $ref_prodserv = $prodser->ref; // Show local ref only } - if (! empty($libelleproduitservice) && ! empty($ref_prodserv)) $ref_prodserv .= " - "; + if (!empty($libelleproduitservice) && !empty($ref_prodserv)) $ref_prodserv .= " - "; } - if(!empty($ref_prodserv) && !empty($conf->global->ADD_HTML_FORMATING_INTO_DESC_DOC)){ $ref_prodserv = ''.$ref_prodserv.''; } - $libelleproduitservice=$prefix_prodserv.$ref_prodserv.$libelleproduitservice; + if (!empty($ref_prodserv) && !empty($conf->global->ADD_HTML_FORMATING_INTO_DESC_DOC)) { $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); + $categstatic = new Categorie($db); // recovering the list of all the categories linked to product - $tblcateg=$categstatic->containing($idprod, Categorie::TYPE_PRODUCT); + $tblcateg = $categstatic->containing($idprod, Categorie::TYPE_PRODUCT); foreach ($tblcateg as $cate) { // Adding the descriptions if they are filled - $desccateg=$cate->add_description; + $desccateg = $cate->add_description; if ($desccateg) - $libelleproduitservice.='__N__'.$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'; + $format = 'day'; $period = ''; // Show duration if exists 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)).')'; + $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)).')'; + $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)).')'; + $period = '('.$outputlangs->transnoentitiesnoconv('DateUntil', dol_print_date($object->lines[$i]->date_end, $format, false, $outputlangs)).')'; } //print '>'.$outputlangs->charset_output.','.$period; - if(!empty($conf->global->ADD_HTML_FORMATING_INTO_DESC_DOC)){ - $libelleproduitservice.= ''."__N__ ".$period.''; + if (!empty($conf->global->ADD_HTML_FORMATING_INTO_DESC_DOC)) { + $libelleproduitservice .= ''."__N__ ".$period.''; } else { - $libelleproduitservice.="__N__".$period; + $libelleproduitservice .= "__N__".$period; } //print $libelleproduitservice; } if ($dbatch) { - $format='day'; + $format = 'day'; 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); - $dte[]=$outputlangs->transnoentitiesnoconv('printQty', $detail->qty); - $libelleproduitservice.= "__N__ ".implode(" - ", $dte); + $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); + $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); - $libelleproduitservice=dol_htmlentitiesbr($libelleproduitservice, 1); + if (dol_textishtml($libelleproduitservice)) $libelleproduitservice = preg_replace('/__N__/', '
    ', $libelleproduitservice); + else $libelleproduitservice = preg_replace('/__N__/', "\n", $libelleproduitservice); + $libelleproduitservice = dol_htmlentitiesbr($libelleproduitservice, 1); return $libelleproduitservice; } @@ -1458,21 +1462,21 @@ function pdf_getlinenum($object, $i, $outputlangs, $hidedetails = 0) { global $hookmanager; - $reshook=0; - $result=''; + $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 { $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); - $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($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)) { - $result.=dol_htmlentitiesbr($object->lines[$i]->num); + $result .= dol_htmlentitiesbr($object->lines[$i]->num); } return $result; } @@ -1491,21 +1495,21 @@ function pdf_getlineref($object, $i, $outputlangs, $hidedetails = 0) { global $hookmanager; - $reshook=0; - $result=''; + $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 { $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); - $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($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)) { - $result.=dol_htmlentitiesbr($object->lines[$i]->product_ref); + $result .= dol_htmlentitiesbr($object->lines[$i]->product_ref); } return $result; } @@ -1523,21 +1527,21 @@ function pdf_getlineref_supplier($object, $i, $outputlangs, $hidedetails = 0) { global $hookmanager; - $reshook=0; - $result=''; + $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 { $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); - $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($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)) { - $result.=dol_htmlentitiesbr($object->lines[$i]->ref_supplier); + $result .= dol_htmlentitiesbr($object->lines[$i]->ref_supplier); } return $result; } @@ -1555,47 +1559,47 @@ function pdf_getlinevatrate($object, $i, $outputlangs, $hidedetails = 0) { global $conf, $hookmanager, $mysoc; - $result=''; - $reshook=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 { $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); - $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($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) { - $tmpresult=''; + $tmpresult = ''; - $tmpresult.=vatrate($object->lines[$i]->tva_tx, 0, $object->lines[$i]->info_bits, -1); + $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=''; - $tmpresult.=vatrate(abs($object->lines[$i]->localtax1_tx), 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=''; - $tmpresult.=vatrate(abs($object->lines[$i]->localtax2_tx), 0); + if (preg_replace('/[\s0%]/', '', $tmpresult)) $tmpresult .= '/'; + else $tmpresult = ''; + $tmpresult .= vatrate(abs($object->lines[$i]->localtax2_tx), 0); } } - $tmpresult.= '%'; + $tmpresult .= '%'; - $result.=$tmpresult; + $result .= $tmpresult; } } return $result; @@ -1614,28 +1618,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; + $sign = 1; + if (isset($object->type) && $object->type == 2 && !empty($conf->global->INVOICE_POSITIVE_CREDIT_NOTE)) $sign = -1; - $result=''; - $reshook=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 { $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); - $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($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) { $subprice = ($conf->multicurrency->enabled && $object->multicurrency_tx != 1 ? $object->lines[$i]->multicurrency_subprice : $object->lines[$i]->subprice); - $result.=price($sign * $subprice, 0, $outputlangs); + $result .= price($sign * $subprice, 0, $outputlangs); } } return $result; @@ -1652,27 +1656,27 @@ function pdf_getlineupexcltax($object, $i, $outputlangs, $hidedetails = 0) */ function pdf_getlineupwithtax($object, $i, $outputlangs, $hidedetails = 0) { - global $hookmanager,$conf; + global $hookmanager, $conf; - $sign=1; - if (isset($object->type) && $object->type == 2 && ! empty($conf->global->INVOICE_POSITIVE_CREDIT_NOTE)) $sign=-1; + $sign = 1; + if (isset($object->type) && $object->type == 2 && !empty($conf->global->INVOICE_POSITIVE_CREDIT_NOTE)) $sign = -1; - $result=''; - $reshook=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 { $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); - $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($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($hidedetails) || $hidedetails > 1) $result .= price($sign * (($object->lines[$i]->subprice) + ($object->lines[$i]->subprice) * ($object->lines[$i]->tva_tx) / 100), 0, $outputlangs); } return $result; } @@ -1690,23 +1694,23 @@ function pdf_getlineqty($object, $i, $outputlangs, $hidedetails = 0) { global $hookmanager; - $result=''; - $reshook=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 { $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); - $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($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($hidedetails) || $hidedetails > 1) $result .= $object->lines[$i]->qty; } return $result; } @@ -1724,23 +1728,23 @@ function pdf_getlineqty_asked($object, $i, $outputlangs, $hidedetails = 0) { global $hookmanager; - $reshook=0; - $result=''; + $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 { $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); - $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($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($hidedetails) || $hidedetails > 1) $result .= $object->lines[$i]->qty_asked; } return $result; } @@ -1758,23 +1762,23 @@ function pdf_getlineqty_shipped($object, $i, $outputlangs, $hidedetails = 0) { global $hookmanager; - $reshook=0; - $result=''; + $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 { $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); - $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($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($hidedetails) || $hidedetails > 1) $result .= $object->lines[$i]->qty_shipped; } return $result; } @@ -1792,23 +1796,23 @@ function pdf_getlineqty_keeptoship($object, $i, $outputlangs, $hidedetails = 0) { global $hookmanager; - $reshook=0; - $result=''; + $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 { $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); - $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($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($hidedetails) || $hidedetails > 1) $result .= ($object->lines[$i]->qty_asked - $object->lines[$i]->qty_shipped); } return $result; } @@ -1827,8 +1831,8 @@ function pdf_getlineunit($object, $i, $outputlangs, $hidedetails = 0, $hookmanag { global $langs; - $reshook=0; - $result=''; + $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 { @@ -1843,14 +1847,14 @@ function pdf_getlineunit($object, $i, $outputlangs, $hidedetails = 0, $hookmanag 'special_code' => $special_code ); $action = ''; - $reshook = $hookmanager->executeHooks('pdf_getlineunit', $parameters, $object, $action); // Note that $action and $object may have been modified by some hooks + $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 ($object->lines[$i]->special_code == 3) return ''; - if (empty($hidedetails) || $hidedetails > 1) $result.=$langs->transnoentitiesnoconv($object->lines[$i]->getLabelOfUnit('short')); + if (empty($hidedetails) || $hidedetails > 1) $result .= $langs->transnoentitiesnoconv($object->lines[$i]->getLabelOfUnit('short')); } return $result; } @@ -1871,23 +1875,23 @@ function pdf_getlineremisepercent($object, $i, $outputlangs, $hidedetails = 0) include_once DOL_DOCUMENT_ROOT.'/core/lib/functions2.lib.php'; - $reshook=0; - $result=''; + $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 { $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); - $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($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($hidedetails) || $hidedetails > 1) $result .= dol_print_reduction($object->lines[$i]->remise_percent, $outputlangs); } return $result; } @@ -1907,8 +1911,8 @@ function pdf_getlineprogress($object, $i, $outputlangs, $hidedetails = 0, $hookm if (empty($hookmanager)) global $hookmanager; global $conf; - $reshook=0; - $result=''; + $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 { @@ -1916,9 +1920,9 @@ function pdf_getlineprogress($object, $i, $outputlangs, $hidedetails = 0, $hookm 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 + $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)) { @@ -1932,10 +1936,10 @@ function pdf_getlineprogress($object, $i, $outputlangs, $hidedetails = 0, $hookm { $prev_progress = $object->lines[$i]->get_prev_progress($object->id); } - $result = ($object->lines[$i]->situation_percent - $prev_progress) . '%'; + $result = ($object->lines[$i]->situation_percent - $prev_progress).'%'; } else - $result = $object->lines[$i]->situation_percent . '%'; + $result = $object->lines[$i]->situation_percent.'%'; } } return $result; @@ -1954,21 +1958,21 @@ 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; + $sign = 1; + if (isset($object->type) && $object->type == 2 && !empty($conf->global->INVOICE_POSITIVE_CREDIT_NOTE)) $sign = -1; - $reshook=0; - $result=''; + $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 { $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); - $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($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($hookmanager->resPrint)) $result .= $hookmanager->resPrint; } if (empty($reshook)) { @@ -1989,11 +1993,11 @@ function pdf_getlinetotalexcltax($object, $i, $outputlangs, $hidedetails = 0) $prev_progress = $object->lines[$i]->get_prev_progress($object->id); $progress = ($object->lines[$i]->situation_percent - $prev_progress) / 100; } - $result.=price($sign * ($total_ht/($object->lines[$i]->situation_percent/100)) * $progress, 0, $outputlangs); + $result .= price($sign * ($total_ht / ($object->lines[$i]->situation_percent / 100)) * $progress, 0, $outputlangs); } else { - $result.=price($sign * $total_ht, 0, $outputlangs); + $result .= price($sign * $total_ht, 0, $outputlangs); } } } @@ -2011,31 +2015,31 @@ function pdf_getlinetotalexcltax($object, $i, $outputlangs, $hidedetails = 0) */ function pdf_getlinetotalwithtax($object, $i, $outputlangs, $hidedetails = 0) { - global $hookmanager,$conf; + global $hookmanager, $conf; - $sign=1; - if (isset($object->type) && $object->type == 2 && ! empty($conf->global->INVOICE_POSITIVE_CREDIT_NOTE)) $sign=-1; + $sign = 1; + if (isset($object->type) && $object->type == 2 && !empty($conf->global->INVOICE_POSITIVE_CREDIT_NOTE)) $sign = -1; - $reshook=0; - $result=''; + $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 { $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); - $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($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($hookmanager->resPrint)) $result .= $hookmanager->resPrint; } if (empty($reshook)) { if ($object->lines[$i]->special_code == 3) { - $result.=$outputlangs->transnoentities("Option"); + $result .= $outputlangs->transnoentities("Option"); } - elseif (empty($hidedetails) || $hidedetails > 1) $result.=price($sign * ($object->lines[$i]->total_ht) + ($object->lines[$i]->total_ht)*($object->lines[$i]->tva_tx)/100, 0, $outputlangs); + elseif (empty($hidedetails) || $hidedetails > 1) $result .= price($sign * ($object->lines[$i]->total_ht) + ($object->lines[$i]->total_ht) * ($object->lines[$i]->tva_tx) / 100, 0, $outputlangs); } return $result; } @@ -2053,32 +2057,32 @@ function pdf_getTotalQty($object, $type, $outputlangs) { global $hookmanager; - $total=0; - $nblines=count($object->lines); + $total = 0; + $nblines = count($object->lines); // Loop on each lines - for ($i = 0 ; $i < $nblines ; $i++) + for ($i = 0; $i < $nblines; $i++) { if ($object->lines[$i]->special_code != 3) { - if ($type=='all') + 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); - $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 + 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; } @@ -2100,11 +2104,11 @@ function pdf_getLinkedObjects($object, $outputlangs) { global $hookmanager; - $linkedobjects=array(); + $linkedobjects = array(); $object->fetchObjectLinked(); - foreach($object->linkedObjects as $objecttype => $objects) + foreach ($object->linkedObjects as $objecttype => $objects) { if ($objecttype == 'facture') { @@ -2114,7 +2118,7 @@ function pdf_getLinkedObjects($object, $outputlangs) { $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); @@ -2125,10 +2129,10 @@ function pdf_getLinkedObjects($object, $outputlangs) 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]['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); } @@ -2136,7 +2140,7 @@ function pdf_getLinkedObjects($object, $outputlangs) 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); @@ -2148,29 +2152,29 @@ function pdf_getLinkedObjects($object, $outputlangs) { $outputlangs->loadLangs(array("orders", "sendings")); - foreach($objects as $x => $elementobject) + foreach ($objects as $x => $elementobject) { - $order=null; + $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 { $elementobject->fetchObjectLinked(); - if (! empty($elementobject->linkedObjects['commande'])) $order = reset($elementobject->linkedObjects['commande']); + if (!empty($elementobject->linkedObjects['commande'])) $order = reset($elementobject->linkedObjects['commande']); } - 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'].=' / '; - $linkedobjects[$objecttype]['ref_value'].= $outputlangs->transnoentities($elementobject->ref); + 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.')' : ''); - $linkedobjects[$objecttype]['ref_value'].= ' / ' . $outputlangs->transnoentities($elementobject->ref); + $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.')' : ''); + $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); //$linkedobjects[$objecttype]['date_value'].= ($elementobject->date_delivery ? ' / ' . dol_print_date($elementobject->date_delivery,'day','',$outputlangs) : ''); @@ -2183,9 +2187,9 @@ function pdf_getLinkedObjects($object, $outputlangs) 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; + $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; } return $linkedobjects; @@ -2202,24 +2206,24 @@ function pdf_getSizeForImage($realpath) { global $conf; - $maxwidth=(empty($conf->global->MAIN_DOCUMENTS_WITH_PICTURE_WIDTH)?20:$conf->global->MAIN_DOCUMENTS_WITH_PICTURE_WIDTH); - $maxheight=(empty($conf->global->MAIN_DOCUMENTS_WITH_PICTURE_HEIGHT)?32:$conf->global->MAIN_DOCUMENTS_WITH_PICTURE_HEIGHT); + $maxwidth = (empty($conf->global->MAIN_DOCUMENTS_WITH_PICTURE_WIDTH) ? 20 : $conf->global->MAIN_DOCUMENTS_WITH_PICTURE_WIDTH); + $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); + $tmp = dol_getImageSize($realpath); if ($tmp['height']) { - $width=(int) round($maxheight*$tmp['width']/$tmp['height']); // I try to use maxheight + $width = (int) round($maxheight * $tmp['width'] / $tmp['height']); // I try to use maxheight if ($width > $maxwidth) // Pb with maxheight, so i use maxwidth { - $width=$maxwidth; - $height=(int) round($maxwidth*$tmp['height']/$tmp['width']); + $width = $maxwidth; + $height = (int) round($maxwidth * $tmp['height'] / $tmp['width']); } else // No pb with maxheight { - $height=$maxheight; + $height = $maxheight; } } - return array('width'=>$width,'height'=>$height); + return array('width'=>$width, 'height'=>$height); } /** @@ -2234,8 +2238,8 @@ function pdf_getSizeForImage($realpath) function pdfGetLineTotalDiscountAmount($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; + $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) { return $outputlangs->transnoentities("Option"); @@ -2245,7 +2249,7 @@ function pdfGetLineTotalDiscountAmount($object, $i, $outputlangs, $hidedetails = 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, @@ -2254,15 +2258,15 @@ function pdfGetLineTotalDiscountAmount($object, $i, $outputlangs, $hidedetails = 'special_code'=>$special_code ); - $action=''; + $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 + 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/product.lib.php b/htdocs/core/lib/product.lib.php index bdeb9181d3b..095a65c3584 100644 --- a/htdocs/core/lib/product.lib.php +++ b/htdocs/core/lib/product.lib.php @@ -45,7 +45,7 @@ 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"); @@ -53,10 +53,10 @@ function product_prepare_head($object) $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) && $user->rights->fournisseur->lire) - || (! empty($conf->margin->enabled) && $user->rights->margin->liretous) + if ((!empty($conf->fournisseur->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; @@ -67,7 +67,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"); @@ -130,16 +130,16 @@ function product_prepare_head($object) // Tab to link resources if (!empty($conf->resource->enabled)) { - if ($object->isProduct() && ! empty($conf->global->RESOURCE_ON_PRODUCTS)) + 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][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][0] = DOL_URL_ROOT.'/resource/element_resource.php?element=service&ref='.$object->ref; $head[$h][1] = $langs->trans("Resources"); $head[$h][2] = 'resources'; $h++; @@ -188,10 +188,10 @@ 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"); + $head[$h][1] .= '/'; + $head[$h][1] .= $langs->trans("Agenda"); } $head[$h][2] = 'agenda'; $h++; @@ -210,7 +210,7 @@ function productlot_prepare_head($object) global $db, $langs, $conf, $user; // Load translation files required by the page - $langs->loadLangs(array("products","productbatch")); + $langs->loadLangs(array("products", "productbatch")); $h = 0; $head = array(); @@ -270,7 +270,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", @@ -342,7 +342,7 @@ function product_lot_admin_prepare_head() */ function show_stats_for_company($product, $socid) { - global $conf,$langs,$user,$db; + global $conf, $langs, $user, $db; $nblines = 0; @@ -354,10 +354,10 @@ function show_stats_for_company($product, $socid) print '
    '; @@ -372,10 +372,10 @@ function show_stats_for_company($product, $socid) print '
    '; @@ -390,10 +390,10 @@ function show_stats_for_company($product, $socid) print '
    '; @@ -408,10 +408,10 @@ function show_stats_for_company($product, $socid) print '
    '; @@ -426,10 +426,10 @@ function show_stats_for_company($product, $socid) print '
    '; @@ -444,10 +444,10 @@ function show_stats_for_company($product, $socid) print '
    '; @@ -463,10 +463,10 @@ 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); + $ret = $product->load_stats_contrat($socid); if ($ret < 0) dol_print_error($db); $langs->load("contracts"); print '
    '; @@ -514,7 +514,7 @@ function measuringUnitString($unit, $measuring_style = '', $scale = '', $use_sho { global $langs, $db; require_once DOL_DOCUMENT_ROOT.'/core/class/cunits.class.php'; - $measuringUnits= new CUnits($db); + $measuringUnits = new CUnits($db); if ($scale !== '') { @@ -534,10 +534,10 @@ function measuringUnitString($unit, $measuring_style = '', $scale = '', $use_sho } $result = $measuringUnits->fetchAll('', '', 0, 0, $arrayforfilter); - if ($result<0) { + if ($result < 0) { return -1; } else { - if (is_array($measuringUnits->records) && count($measuringUnits->records)>0) { + if (is_array($measuringUnits->records) && count($measuringUnits->records) > 0) { if ($use_short_label) return $measuringUnits->records[key($measuringUnits->records)]->short_label; else return $langs->transnoentitiesnoconv($measuringUnits->records[key($measuringUnits->records)]->label); } else { @@ -555,8 +555,8 @@ function measuringUnitString($unit, $measuring_style = '', $scale = '', $use_sho */ function measuring_units_squared($unit) { - $measuring_units=array(); - $measuring_units[0] = 0; // m -> m3 + $measuring_units = array(); + $measuring_units[0] = 0; // m -> m3 $measuring_units[-1] = -2; // dm-> dm2 $measuring_units[-2] = -4; // cm -> cm2 $measuring_units[-3] = -6; // mm -> mm2 @@ -575,8 +575,8 @@ function measuring_units_squared($unit) */ function measuring_units_cubed($unit) { - $measuring_units=array(); - $measuring_units[0] = 0; // m -> m2 + $measuring_units = array(); + $measuring_units[0] = 0; // m -> m2 $measuring_units[-1] = -3; // dm-> dm3 $measuring_units[-2] = -6; // cm -> cm3 $measuring_units[-3] = -9; // mm -> mm3 diff --git a/htdocs/core/lib/project.lib.php b/htdocs/core/lib/project.lib.php index 8ceca03b0b2..875705cd8c3 100644 --- a/htdocs/core/lib/project.lib.php +++ b/htdocs/core/lib/project.lib.php @@ -48,7 +48,7 @@ function project_prepare_head($object) $nbContact = count($object->liste_contact(-1, 'internal')) + count($object->liste_contact(-1, 'external')); $head[$h][0] = DOL_URL_ROOT.'/projet/contact.php?id='.$object->id; $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++; @@ -59,13 +59,13 @@ function project_prepare_head($object) $head[$h][1] = $langs->trans("Tasks"); require_once DOL_DOCUMENT_ROOT.'/projet/class/task.class.php'; - $taskstatic=new Task($db); - $nbTasks=count($taskstatic->getTasksArray(0, 0, $object->id, 0, 0)); - if ($nbTasks > 0) $head[$h][1].= ''.($nbTasks).''; + $taskstatic = new Task($db); + $nbTasks = count($taskstatic->getTasksArray(0, 0, $object->id, 0, 0)); + if ($nbTasks > 0) $head[$h][1] .= ''.($nbTasks).''; $head[$h][2] = 'tasks'; $h++; - $nbTimeSpent=0; + $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"; @@ -76,20 +76,20 @@ function project_prepare_head($object) if ($resql) { $obj = $db->fetch_object($resql); - if ($obj) $nbTimeSpent=1; + if ($obj) $nbTimeSpent = 1; } else dol_print_error($db); $head[$h][0] = DOL_URL_ROOT.'/projet/tasks/time.php?withproject=1&projectid='.$object->id; $head[$h][1] = $langs->trans("TimeSpent"); - if ($nbTimeSpent > 0) $head[$h][1].= '...'; + if ($nbTimeSpent > 0) $head[$h][1] .= '...'; $head[$h][2] = 'timespent'; $h++; } - if (! empty($conf->fournisseur->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)) + if (!empty($conf->fournisseur->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)) { $head[$h][0] = DOL_URL_ROOT.'/projet/element.php?id='.$object->id; $head[$h][1] = $langs->trans("ProjectOverview"); @@ -107,23 +107,23 @@ function project_prepare_head($object) 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/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] = '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($object->ref); + $upload_dir = $conf->projet->dir_output."/".dol_sanitizeFileName($object->ref); $nbFiles = count(dol_dir_list($upload_dir, 'files', 0, '', '(\.meta|_preview.*\.png)$')); - $nbLinks=Link::count($db, $object->element, $object->id); + $nbLinks = Link::count($db, $object->element, $object->id); $head[$h][0] = DOL_URL_ROOT.'/projet/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++; @@ -133,17 +133,17 @@ function project_prepare_head($object) $nbComments = $object->getNbComments(); $head[$h][0] = DOL_URL_ROOT.'/projet/comment.php?id='.$object->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='.$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) )) + $head[$h][1] .= $langs->trans("Events"); + 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"); + $head[$h][1] .= '/'; + $head[$h][1] .= $langs->trans("Agenda"); } $head[$h][2] = 'agenda'; $h++; @@ -166,20 +166,20 @@ function task_prepare_head($object) $h = 0; $head = array(); - $head[$h][0] = DOL_URL_ROOT.'/projet/tasks/task.php?id='.$object->id.(GETPOST('withproject')?'&withproject=1':''); + $head[$h][0] = DOL_URL_ROOT.'/projet/tasks/task.php?id='.$object->id.(GETPOST('withproject') ? '&withproject=1' : ''); $head[$h][1] = $langs->trans("Card"); $head[$h][2] = 'task_task'; $h++; $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][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++; // Is there timespent ? - $nbTimeSpent=0; + $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"; @@ -189,13 +189,13 @@ function task_prepare_head($object) if ($resql) { $obj = $db->fetch_object($resql); - if ($obj) $nbTimeSpent=1; + 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][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++; @@ -208,23 +208,23 @@ function task_prepare_head($object) if (empty($conf->global->MAIN_DISABLE_NOTES_TAB)) { $nbNote = 0; - if(!empty($object->note_private)) $nbNote++; - if(!empty($object->note_public)) $nbNote++; - $head[$h][0] = DOL_URL_ROOT.'/projet/tasks/note.php?id='.$object->id.(GETPOST('withproject')?'&withproject=1':''); + 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++; } - $head[$h][0] = DOL_URL_ROOT.'/projet/tasks/document.php?id='.$object->id.(GETPOST('withproject')?'&withproject=1':''); - $filesdir = $conf->projet->dir_output . "/" . dol_sanitizeFileName($object->project->ref) . '/' .dol_sanitizeFileName($object->ref); + $head[$h][0] = DOL_URL_ROOT.'/projet/tasks/document.php?id='.$object->id.(GETPOST('withproject') ? '&withproject=1' : ''); + $filesdir = $conf->projet->dir_output."/".dol_sanitizeFileName($object->project->ref).'/'.dol_sanitizeFileName($object->ref); include_once DOL_DOCUMENT_ROOT.'/core/lib/files.lib.php'; include_once DOL_DOCUMENT_ROOT.'/core/class/link.class.php'; $nbFiles = count(dol_dir_list($filesdir, 'files', 0, '', '(\.meta|_preview.*\.png)$')); - $nbLinks=Link::count($db, $object->element, $object->id); + $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++; @@ -232,9 +232,9 @@ function task_prepare_head($object) 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][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++; } @@ -259,13 +259,13 @@ function project_timesheet_prepare_head($mode, $fuser = null) $h = 0; - $param=''; - $param.=($mode?'&mode='.$mode:''); - if (is_object($fuser) && $fuser->id > 0 && $fuser->id != $user->id) $param.='&search_usertoprocessid='.$fuser->id; + $param = ''; + $param .= ($mode ? '&mode='.$mode : ''); + if (is_object($fuser) && $fuser->id > 0 && $fuser->id != $user->id) $param .= '&search_usertoprocessid='.$fuser->id; if (empty($conf->global->PROJECT_DISABLE_TIMESHEET_PERWEEK)) { - $head[$h][0] = DOL_URL_ROOT."/projet/activity/perweek.php".($param?'?'.$param:''); + $head[$h][0] = DOL_URL_ROOT."/projet/activity/perweek.php".($param ? '?'.$param : ''); $head[$h][1] = $langs->trans("InputPerWeek"); $head[$h][2] = 'inputperweek'; $h++; @@ -273,7 +273,7 @@ function project_timesheet_prepare_head($mode, $fuser = null) if (empty($conf->global->PROJECT_DISABLE_TIMESHEET_PERTIME)) { - $head[$h][0] = DOL_URL_ROOT."/projet/activity/perday.php".($param?'?'.$param:''); + $head[$h][0] = DOL_URL_ROOT."/projet/activity/perday.php".($param ? '?'.$param : ''); $head[$h][1] = $langs->trans("InputPerDay"); $head[$h][2] = 'inputperday'; $h++; @@ -353,10 +353,10 @@ function projectLinesa(&$inc, $parent, &$lines, &$level, $var, $showproject, &$t global $user, $bc, $langs, $conf, $db; global $projectstatic, $taskstatic; - $lastprojectid=0; + $lastprojectid = 0; - $projectsArrayId=explode(',', $projectsListId); - if ($filterprogresscalc!=='') { + $projectsArrayId = explode(',', $projectsListId); + if ($filterprogresscalc !== '') { foreach ($lines as $key=>$line) { if (!empty($line->planned_workload) && !empty($line->duration)) { $filterprogresscalc = str_replace(' = ', ' == ', $filterprogresscalc); @@ -365,27 +365,27 @@ function projectLinesa(&$inc, $parent, &$lines, &$level, $var, $showproject, &$t } } } - $lines=array_values($lines); + $lines = array_values($lines); } - $numlines=count($lines); + $numlines = count($lines); // 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) { - $total_projectlinesa_spent=0; - $total_projectlinesa_planned=0; - $total_projectlinesa_spent_if_planned=0; - $total_projectlinesa_declared_if_planned=0; - $total_projectlinesa_tobill=0; - $total_projectlinesa_billed=0; + $total_projectlinesa_spent = 0; + $total_projectlinesa_planned = 0; + $total_projectlinesa_spent_if_planned = 0; + $total_projectlinesa_declared_if_planned = 0; + $total_projectlinesa_tobill = 0; + $total_projectlinesa_billed = 0; } - for ($i = 0 ; $i < $numlines ; $i++) + 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 + 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.'
    '; @@ -393,26 +393,26 @@ function projectLinesa(&$inc, $parent, &$lines, &$level, $var, $showproject, &$t 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; + $showline = 1; + $showlineingray = 0; // If there is filters to use 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; + $foundtaskforuserdeeper = 0; searchTaskInChild($foundtaskforuserdeeper, $lines[$i]->id, $lines, $taskrole); //print '$foundtaskforuserpeeper='.$foundtaskforuserdeeper.'
    '; if ($foundtaskforuserdeeper > 0) { - $showlineingray=1; // We will show line but in gray + $showlineingray = 1; // We will show line but in gray } else { - $showline=0; // No reason to show line + $showline = 0; // No reason to show line } } } @@ -423,12 +423,12 @@ function projectLinesa(&$inc, $parent, &$lines, &$level, $var, $showproject, &$t 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. - $showline=0; + $showline = 0; } } } @@ -439,26 +439,26 @@ function projectLinesa(&$inc, $parent, &$lines, &$level, $var, $showproject, &$t if ($parent == 0 && $lines[$i]->fk_project != $lastprojectid) { $var = !$var; - $lastprojectid=$lines[$i]->fk_project; + $lastprojectid = $lines[$i]->fk_project; } 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); + 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 "'; - $projectstatic->statut=$lines[$i]->projectstatus; + $projectstatic->statut = $lines[$i]->projectstatus; print $projectstatic->getLibStatut(2); print ""; if ($showlineingray) print ''; //else print ''; - for ($k = 0 ; $k < $level ; $k++) + for ($k = 0; $k < $level; $k++) { print '
    '; } print $lines[$i]->label; - for ($k = 0 ; $k < $level ; $k++) + for ($k = 0; $k < $level; $k++) { print '
    '; } @@ -518,15 +518,15 @@ function projectLinesa(&$inc, $parent, &$lines, &$level, $var, $showproject, &$t if ($taskstatic->hasDelay()) print img_warning($langs->trans("Late")); print '
    '; - $fullhour=convertSecondToTime($lines[$i]->planned_workload, $plannedworkloadoutputformat); - $workingdelay=convertSecondToTime($lines[$i]->planned_workload, 'all', 86400, 7); // TODO Replace 86400 and 7 to take account working hours per day and working day per weeks + $fullhour = convertSecondToTime($lines[$i]->planned_workload, $plannedworkloadoutputformat); + $workingdelay = convertSecondToTime($lines[$i]->planned_workload, 'all', 86400, 7); // TODO Replace 86400 and 7 to take account working hours per day and working day per weeks if ($lines[$i]->planned_workload != '') { print $fullhour; @@ -539,7 +539,7 @@ function projectLinesa(&$inc, $parent, &$lines, &$level, $var, $showproject, &$t // Time spent print ''; if ($showlineingray) print ''; - else print ''; + else print ''; if ($lines[$i]->duration) print convertSecondToTime($lines[$i]->duration, $timespentoutputformat); else print '--:--'; if ($showlineingray) print ''; @@ -600,20 +600,20 @@ 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){ + $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); $c->fetch($contacttask['id']); - print $c->getNomUrl(1) . ' (' . $contacttask['libelle'] . ')' . '
    '; + print $c->getNomUrl(1).' ('.$contacttask['libelle'].')'.'
    '; } } } @@ -628,7 +628,7 @@ function projectLinesa(&$inc, $parent, &$lines, &$level, $var, $showproject, &$t print "
    '; - if ($projectidfortotallink > 0) print ''; + if ($projectidfortotallink > 0) print ''; print convertSecondToTime($total_projectlinesa_spent, 'allhourmin'); if ($projectidfortotallink > 0) print ''; 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 "   "; @@ -878,20 +878,20 @@ function projectLinesPerAction(&$inc, $parent, $fuser, $lines, &$level, &$projec print dol_print_date($lines[$i]->timespent_datehour, 'day'); print '
    '; + print ''; $dayWorkLoad = $lines[$i]->timespent_duration; - $totalforeachline[$preselectedday]+=$lines[$i]->timespent_duration; + $totalforeachline[$preselectedday] += $lines[$i]->timespent_duration; - $alreadyspent=''; - if ($dayWorkLoad > 0) $alreadyspent=convertSecondToTime($lines[$i]->timespent_duration, 'allhourmin'); + $alreadyspent = ''; + if ($dayWorkLoad > 0) $alreadyspent = convertSecondToTime($lines[$i]->timespent_duration, 'allhourmin'); print convertSecondToTime($lines[$i]->timespent_duration, 'allhourmin'); - $modeinput='hours'; + $modeinput = 'hours'; print ''."\n"; print '
    '; $formproject->select_projects(-1, $line->fk_project, 'fk_project', 0, 0, 1, 1, 0, 0, 0, '', 0, 0, 'maxwidth300'); @@ -2396,7 +2396,7 @@ else // VAT print ''; - print $form->load_tva('vatrate', (isset($_POST["vatrate"])?$_POST["vatrate"]:$line->vatrate), $mysoc, '', 0, 0, '', false, 1); + print $form->load_tva('vatrate', (isset($_POST["vatrate"]) ? $_POST["vatrate"] : $line->vatrate), $mysoc, '', 0, 0, '', false, 1); print '
    '.$langs->trans('Date').''.$form->textwithpicto($langs->trans('Project'), $langs->trans("ClosedProjectsAreHidden")).''.$form->textwithpicto($langs->trans('Project'), $langs->trans("ClosedProjectsAreHidden")).''.$langs->trans('CarCategory').''.$langs->trans('Type').''.$langs->trans('Description').''; - print $form->selectDate($date?$date:-1, 'date', 0, 0, 0, '', 1, 1); + print $form->selectDate($date ? $date : -1, 'date', 0, 0, 0, '', 1, 1); print ''; $formproject->select_projects(-1, $fk_project, 'fk_project', 0, 0, 1, -1, 0, 0, 0, '', 0, 0, 'maxwidth300'); print ''; $params = array('fk_expense' => $object->id); @@ -2551,9 +2551,9 @@ else // Select VAT print ''; - $defaultvat=-1; - if (! empty($conf->global->EXPENSEREPORT_NO_DEFAULT_VAT)) $conf->global->MAIN_VAT_DEFAULT_IF_AUTODETECT_FAILS = 'none'; - print $form->load_tva('vatrate', ($vatrate!=''?$vatrate:$defaultvat), $mysoc, '', 0, 0, '', false, 1); + $defaultvat = -1; + if (!empty($conf->global->EXPENSEREPORT_NO_DEFAULT_VAT)) $conf->global->MAIN_VAT_DEFAULT_IF_AUTODETECT_FAILS = 'none'; + print $form->load_tva('vatrate', ($vatrate != '' ? $vatrate : $defaultvat), $mysoc, '', 0, 0, '', false, 1); print ''; - print ''; // We must be able to enter decimal qty + print ''; // We must be able to enter decimal qty print '
    '; - $linkback = ''.$langs->trans("BackToList").''; + $linkback = ''.$langs->trans("BackToList").''; print ''; print ''; @@ -130,8 +130,8 @@ if ($object->id) $modulepart = 'expensereport'; $permission = $user->rights->expensereport->creer; $permtoedit = $user->rights->expensereport->creer; - $param = '&id=' . $object->id; - include_once DOL_DOCUMENT_ROOT . '/core/tpl/document_actions_post_headers.tpl.php'; + $param = '&id='.$object->id; + include_once DOL_DOCUMENT_ROOT.'/core/tpl/document_actions_post_headers.tpl.php'; } else { diff --git a/htdocs/expensereport/index.php b/htdocs/expensereport/index.php index c849a5c62f9..ec6f78d91f7 100644 --- a/htdocs/expensereport/index.php +++ b/htdocs/expensereport/index.php @@ -29,8 +29,8 @@ */ require '../main.inc.php'; -require_once DOL_DOCUMENT_ROOT . '/compta/tva/class/tva.class.php'; -require_once DOL_DOCUMENT_ROOT . '/expensereport/class/expensereport.class.php'; +require_once DOL_DOCUMENT_ROOT.'/compta/tva/class/tva.class.php'; +require_once DOL_DOCUMENT_ROOT.'/expensereport/class/expensereport.class.php'; $hookmanager = new HookManager($db); @@ -42,7 +42,7 @@ $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', '', ''); $sortfield = GETPOST("sortfield", 'alpha'); @@ -52,41 +52,41 @@ if (empty($page) || $page == -1) { $page = 0; } // If $page is not defined, $offset = $conf->liste_limit * $page; $pageprev = $page - 1; $pagenext = $page + 1; -if (! $sortorder) $sortorder="DESC"; -if (! $sortfield) $sortfield="d.date_create"; -$limit = GETPOST('limit', 'int')?GETPOST('limit', 'int'):$conf->liste_limit; +if (!$sortorder) $sortorder = "DESC"; +if (!$sortfield) $sortfield = "d.date_create"; +$limit = GETPOST('limit', 'int') ?GETPOST('limit', 'int') : $conf->liste_limit; /* * View */ -$tripandexpense_static=new ExpenseReport($db); +$tripandexpense_static = new ExpenseReport($db); $childids = $user->getAllChildIds(); -$childids[]=$user->id; +$childids[] = $user->id; //$help_url='EN:Module_Donations|FR:Module_Dons|ES:Módulo_Donaciones'; -$help_url=''; +$help_url = ''; llxHeader('', $langs->trans("ListOfFees"), $help_url); -$label=$somme=$nb=array(); +$label = $somme = $nb = array(); -$totalnb=$totalsum=0; +$totalnb = $totalsum = 0; $sql = "SELECT tf.code, tf.label, count(de.rowid) as nb, sum(de.total_ht) as km"; -$sql.= " FROM ".MAIN_DB_PREFIX."expensereport as d, ".MAIN_DB_PREFIX."expensereport_det as de, ".MAIN_DB_PREFIX."c_type_fees as tf"; -$sql.= " WHERE de.fk_expensereport = d.rowid AND d.entity IN (".getEntity('expensereport').") AND de.fk_c_type_fees = tf.id"; +$sql .= " FROM ".MAIN_DB_PREFIX."expensereport as d, ".MAIN_DB_PREFIX."expensereport_det as de, ".MAIN_DB_PREFIX."c_type_fees as tf"; +$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))) { $childids = $user->getAllChildIds(); - $childids[]=$user->id; - $sql.= " AND d.fk_user_author IN (".join(',', $childids).")\n"; + $childids[] = $user->id; + $sql .= " AND d.fk_user_author IN (".join(',', $childids).")\n"; } -$sql.= " GROUP BY tf.code, tf.label"; +$sql .= " GROUP BY tf.code, tf.label"; $result = $db->query($sql); if ($result) @@ -116,15 +116,15 @@ print load_fiche_titre($langs->trans("ExpensesArea")); print '
    '; print '
    '; -print '
    '.$langs->trans("NbOfAttachedFiles").''.count($filearray).'
    '.$langs->trans("TotalSizeOfAttachedFiles").''.dol_print_size($totalsize, 1, 1).'
    '; +print '
    '; print ''; print ''; print "\n"; -$listoftype=$tripandexpense_static->listOfTypes(); +$listoftype = $tripandexpense_static->listOfTypes(); foreach ($listoftype as $code => $label) { - $dataseries[]=array($label, (isset($somme[$code])?(int) $somme[$code]:0)); + $dataseries[] = array($label, (isset($somme[$code]) ? (int) $somme[$code] : 0)); } if ($conf->use_javascript_ajax) @@ -135,13 +135,13 @@ if ($conf->use_javascript_ajax) $dolgraph = new DolGraph(); $dolgraph->SetData($dataseries); $dolgraph->setHeight(350); - $dolgraph->combine = empty($conf->global->MAIN_EXPENSEREPORT_COMBINE_GRAPH_STAT)?0.05:$conf->global->MAIN_EXPENSEREPORT_COMBINE_GRAPH_STAT; + $dolgraph->combine = empty($conf->global->MAIN_EXPENSEREPORT_COMBINE_GRAPH_STAT) ? 0.05 : $conf->global->MAIN_EXPENSEREPORT_COMBINE_GRAPH_STAT; $dolgraph->setShowLegend(1); $dolgraph->setShowPercent(1); $dolgraph->SetType(array('pie')); $dolgraph->setWidth('100%'); $dolgraph->draw('idgraphstatus'); - print $dolgraph->show($totalnb?0:1); + print $dolgraph->show($totalnb ? 0 : 1); print ''; } @@ -160,38 +160,39 @@ print ''; print '
    '; -$max=10; +$max = 10; $langs->load("boxes"); -$sql = "SELECT u.rowid as uid, u.lastname, u.firstname, u.login, u.statut, u.photo, 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 fk_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"; -$sql.= " WHERE u.rowid = d.fk_user_author"; +$sql = "SELECT u.rowid as uid, u.lastname, u.firstname, u.login, u.statut, 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 fk_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"; +$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))) { $childids = $user->getAllChildIds(); - $childids[]=$user->id; - $sql.= " AND d.fk_user_author IN (".join(',', $childids).")\n"; + $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; -$sql.= $db->order($sortfield, $sortorder); -$sql.= $db->plimit($max, 0); +$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; +$sql .= $db->order($sortfield, $sortorder); +$sql .= $db->plimit($max, 0); $result = $db->query($sql); if ($result) { - $var=false; + $var = false; $num = $db->num_rows($result); $i = 0; print '
    '; - print '
    '.$langs->trans("Statistics").'
    '; + print '
    '; print ''; print ''; print ''; @@ -203,19 +204,21 @@ if ($result) { $total_ttc = $totalam = $total = 0; - $expensereportstatic=new ExpenseReport($db); - $userstatic=new User($db); + $expensereportstatic = new ExpenseReport($db); + $userstatic = new User($db); while ($i < $num && $i < $max) { $obj = $db->fetch_object($result); - $expensereportstatic->id=$obj->rowid; - $expensereportstatic->ref=$obj->ref; - $userstatic->id=$obj->uid; - $userstatic->lastname=$obj->lastname; - $userstatic->firstname=$obj->firstname; - $userstatic->login=$obj->login; - $userstatic->statut=$obj->statut; - $userstatic->photo=$obj->photo; + $expensereportstatic->id = $obj->rowid; + $expensereportstatic->ref = $obj->ref; + $userstatic->id = $obj->uid; + $userstatic->admin = $obj->admin; + $userstatic->email = $obj->email; + $userstatic->lastname = $obj->lastname; + $userstatic->firstname = $obj->firstname; + $userstatic->login = $obj->login; + $userstatic->statut = $obj->statut; + $userstatic->photo = $obj->photo; print ''; print ''; print ''; diff --git a/htdocs/expensereport/list.php b/htdocs/expensereport/list.php index 91d0efec9cc..385277bb7d3 100644 --- a/htdocs/expensereport/list.php +++ b/htdocs/expensereport/list.php @@ -45,35 +45,35 @@ $action = GETPOST('action', 'aZ09'); $massaction = GETPOST('massaction', 'alpha'); $show_files = GETPOST('show_files', 'int'); $confirm = GETPOST('confirm', 'alpha'); -$cancel = GETPOST('cancel', 'alpha'); // We click on a Cancel button +$cancel = GETPOST('cancel', 'alpha'); // We click on a Cancel button $toselect = GETPOST('toselect', 'array'); -$contextpage = GETPOST('contextpage', 'aZ')?GETPOST('contextpage', 'aZ'):'expensereportlist'; +$contextpage = GETPOST('contextpage', 'aZ') ?GETPOST('contextpage', 'aZ') : 'expensereportlist'; $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) { - $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) + $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) { accessforbidden(); } } -$diroutputmassaction=$conf->expensereport->dir_output . '/temp/massgeneration/'.$user->id; +$diroutputmassaction = $conf->expensereport->dir_output.'/temp/massgeneration/'.$user->id; // Load variable for pagination -$limit = GETPOST('limit', 'int')?GETPOST('limit', 'int'):$conf->liste_limit; +$limit = GETPOST('limit', 'int') ?GETPOST('limit', 'int') : $conf->liste_limit; $sortfield = GETPOST('sortfield', 'alpha'); $sortorder = GETPOST('sortorder', 'alpha'); $page = GETPOST('page', 'int'); @@ -81,17 +81,17 @@ if (empty($page) || $page == -1) { $page = 0; } // If $page is not defined, $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')); +$sall = trim((GETPOST('search_all', 'alphanohtml') != '') ?GETPOST('search_all', 'alphanohtml') : GETPOST('sall', 'alphanohtml')); $search_ref = GETPOST('search_ref', 'alpha'); $search_user = GETPOST('search_user', 'int'); $search_amount_ht = GETPOST('search_amount_ht', 'alpha'); $search_amount_vat = GETPOST('search_amount_vat', 'alpha'); $search_amount_ttc = GETPOST('search_amount_ttc', 'alpha'); -$search_status = (GETPOST('search_status', 'intcomma')!=''?GETPOST('search_status', 'intcomma'):GETPOST('statut', 'intcomma')); +$search_status = (GETPOST('search_status', 'intcomma') != '' ?GETPOST('search_status', 'intcomma') : GETPOST('statut', 'intcomma')); $month_start = GETPOST("month_start", "int"); $year_start = GETPOST("year_start", "int"); $day_start = GETPOST("day_start", "int"); @@ -100,8 +100,8 @@ $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); @@ -111,7 +111,7 @@ $extrafields = new ExtraFields($db); // fetch optionals attributes and labels $extrafields->fetch_name_optionals_label('expensereport'); -$search_array_options=$extrafields->getOptionalsFromPost($object->table_element, '', 'search_'); +$search_array_options = $extrafields->getOptionalsFromPost($object->table_element, '', 'search_'); // List of fields to search into when doing a "search in all" @@ -122,9 +122,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( +$arrayfields = array( 'd.ref'=>array('label'=>$langs->trans("Ref"), 'checked'=>1), 'user'=>array('label'=>$langs->trans("User"), 'checked'=>1), 'd.date_debut'=>array('label'=>$langs->trans("DateStart"), 'checked'=>1), @@ -141,14 +141,14 @@ $arrayfields=array( // 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) + 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], 'checked'=>(($extrafields->attributes[$object->table_element]['list'][$key]<0)?0:1), 'position'=>$extrafields->attributes[$object->table_element]['pos'][$key], 'enabled'=>(abs($extrafields->attributes[$object->table_element]['list'][$key])!=3 && $extrafields->attributes[$object->table_element]['perms'][$key])); + if (!empty($extrafields->attributes[$object->table_element]['list'][$key])) + $arrayfields["ef.".$key] = array('label'=>$extrafields->attributes[$object->table_element]['label'][$key], 'checked'=>(($extrafields->attributes[$object->table_element]['list'][$key] < 0) ? 0 : 1), 'position'=>$extrafields->attributes[$object->table_element]['pos'][$key], 'enabled'=>(abs($extrafields->attributes[$object->table_element]['list'][$key]) != 3 && $extrafields->attributes[$object->table_element]['perms'][$key])); } } -$canedituser=(! empty($user->admin) || $user->rights->user->user->creer); +$canedituser = (!empty($user->admin) || $user->rights->user->user->creer); $objectuser = new User($db); @@ -157,11 +157,11 @@ $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 +$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)) @@ -172,35 +172,35 @@ if (empty($reshook)) // Purge search criteria if (GETPOST('button_removefilter_x', 'alpha') || GETPOST('button_removefilter.x', 'alpha') || GETPOST('button_removefilter', 'alpha')) // All tests are required to be compatible with all browsers { - $search_ref=""; - $search_user=""; - $search_amount_ht=""; - $search_amount_vat=""; - $search_amount_ttc=""; - $search_status=""; - $month_start=""; - $year_start=""; - $month_end=""; - $year_end=""; + $search_ref = ""; + $search_user = ""; + $search_amount_ht = ""; + $search_amount_vat = ""; + $search_amount_ttc = ""; + $search_status = ""; + $month_start = ""; + $year_start = ""; + $month_end = ""; + $year_end = ""; $day_end = ""; - $toselect=''; - $search_array_options=array(); + $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')) { - $massaction=''; // Protection to avoid mass action if we force a new search during a mass action confirmation + $massaction = ''; // Protection to avoid mass action if we force a new search during a mass action confirmation } // Mass actions - $objectclass='ExpenseReport'; - $objectlabel='ExpenseReport'; + $objectclass = 'ExpenseReport'; + $objectlabel = 'ExpenseReport'; $permissiontoread = $user->rights->expensereport->lire; $permissiontodelete = $user->rights->expensereport->supprimer; $uploaddir = $conf->expensereport->dir_output; include DOL_DOCUMENT_ROOT.'/core/actions_massactions.inc.php'; - if ($action == 'update' && ! $cancel) + if ($action == 'update' && !$cancel) { require_once DOL_DOCUMENT_ROOT.'/core/lib/files.lib.php'; @@ -277,49 +277,49 @@ if ($id > 0) } $sql = "SELECT d.rowid, d.ref, d.fk_user_author, d.total_ht, d.total_tva, d.total_ttc, d.fk_statut as status,"; -$sql.= " d.date_debut, d.date_fin, d.date_create, d.tms as date_modif, d.date_valid, d.date_approve, d.note_private, d.note_public,"; -$sql.= " u.rowid as id_user, u.firstname, u.lastname, u.login, u.email, u.statut, u.photo"; +$sql .= " d.date_debut, d.date_fin, d.date_create, d.tms as date_modif, d.date_valid, d.date_approve, d.note_private, d.note_public,"; +$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 : ''); +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 : ''); } // 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)"; -$sql.= ", ".MAIN_DB_PREFIX."user as u"; -$sql.= " WHERE d.fk_user_author = u.rowid AND d.entity IN (".getEntity('expensereport').")"; +$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)"; +$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); +$sql .= dolSqlDateFilter("d.date_debut", $day_start, $month_start, $year_start); // Date End -$sql.= dolSqlDateFilter("d.date_fin", $day_end, $month_end, $year_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->escape($search_status).")"; +if ($search_status != '' && $search_status >= 0) $sql .= " AND d.fk_statut IN (".$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))) { - $sql.= " AND d.fk_user_author IN (".join(',', $childids).")\n"; + $sql .= " AND d.fk_user_author IN (".join(',', $childids).")\n"; } // Add where from extra fields include DOL_DOCUMENT_ROOT.'/core/tpl/extrafields_list_search_sql.tpl.php'; // Add where from hooks -$parameters=array(); -$reshook=$hookmanager->executeHooks('printFieldListWhere', $parameters); // Note that $action and $object may have been modified by hook -$sql.=$hookmanager->resPrint; +$parameters = array(); +$reshook = $hookmanager->executeHooks('printFieldListWhere', $parameters); // Note that $action and $object may have been modified by hook +$sql .= $hookmanager->resPrint; -$sql.= $db->order($sortfield, $sortorder); +$sql .= $db->order($sortfield, $sortorder); // Count total nb of records $nbtotalofrecords = ''; @@ -334,7 +334,7 @@ if (empty($conf->global->MAIN_DISABLE_FULL_SCANLIST)) } } -$sql.= $db->plimit($limit+1, $offset); +$sql .= $db->plimit($limit + 1, $offset); //print $sql; $resql = $db->query($sql); @@ -342,37 +342,37 @@ if ($resql) { $num = $db->num_rows($resql); - $arrayofselected=is_array($toselect)?$toselect:array(); + $arrayofselected = is_array($toselect) ? $toselect : array(); - $param=''; - if (! empty($contextpage) && $contextpage != $_SERVER["PHP_SELF"]) $param.='&contextpage='.urlencode($contextpage); - if ($limit > 0 && $limit != $conf->liste_limit) $param.='&limit='.urlencode($limit); - if ($sall) $param.="&sall=".urlencode($sall); - 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); + $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); // Add $param from extra fields include DOL_DOCUMENT_ROOT.'/core/tpl/extrafields_list_search_param.tpl.php'; // List of mass actions available - $arrayofmassactions = array( + $arrayofmassactions = array( 'generate_doc'=>$langs->trans("ReGeneratePDF"), 'builddoc'=>$langs->trans("PDFMerge"), 'presend'=>$langs->trans("SendByMail"), ); - if ($user->rights->expensereport->supprimer) $arrayofmassactions['predelete']=''.$langs->trans("Delete"); - if (in_array($massaction, array('presend','predelete'))) $arrayofmassactions=array(); - $massactionbutton=$form->selectMassAction('', $arrayofmassactions); + 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 ''; print ''; print ''; - print ''; + print ''; print ''; print ''; print ''; @@ -449,7 +449,7 @@ if ($resql) $childids = $user->getAllChildIds(1); - $canedit=((in_array($user_id, $childids) && $user->rights->expensereport->creer) + $canedit = ((in_array($user_id, $childids) && $user->rights->expensereport->creer) || ($conf->global->MAIN_USE_ADVANCED_PERMS && $user->rights->expensereport->writeall_advance)); // Buttons for actions @@ -471,58 +471,58 @@ if ($resql) { $title = $langs->trans("ListTripsAndExpenses"); - $newcardbutton=''; + $newcardbutton = ''; if ($user->rights->expensereport->creer) { - $newcardbutton.= dolGetButtonTitle($langs->trans('NewTrip'), '', 'fa fa-plus-circle', DOL_URL_ROOT.'/expensereport/card.php?action=create'); + $newcardbutton .= dolGetButtonTitle($langs->trans('NewTrip'), '', 'fa fa-plus-circle', DOL_URL_ROOT.'/expensereport/card.php?action=create'); } print_barre_liste($title, $page, $_SERVER["PHP_SELF"], $param, $sortfield, $sortorder, $massactionbutton, $num, $nbtotalofrecords, 'generic', 0, $newcardbutton, '', $limit); } - $topicmail="SendExpenseReport"; - $modelmail="expensereport"; - $objecttmp=new ExpenseReport($db); - $trackid='exp'.$object->id; + $topicmail = "SendExpenseReport"; + $modelmail = "expensereport"; + $objecttmp = new ExpenseReport($db); + $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); - print '
    '.$langs->trans("FilterOnInto", $sall) . join(', ', $fieldstosearchall).'
    '; + foreach ($fieldstosearchall as $key => $val) $fieldstosearchall[$key] = $langs->trans($val); + print '
    '.$langs->trans("FilterOnInto", $sall).join(', ', $fieldstosearchall).'
    '; } - $moreforfilter=''; + $moreforfilter = ''; - $parameters=array(); - $reshook=$hookmanager->executeHooks('printFieldPreListTitle', $parameters); // Note that $action and $object may have been modified by hook + $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($moreforfilter)) + if (!empty($moreforfilter)) { print '
    '; print $moreforfilter; print '
    '; } - $varpage=empty($contextpage)?$_SERVER["PHP_SELF"]:$contextpage; - $selectedfields=$form->multiSelectArrayWithCheckbox('selectedfields', $arrayfields, $varpage); // This also change content of $arrayfields - $selectedfields.=(count($arrayofmassactions) ? $form->showCheckAddButtons('checkforselect', 1) : ''); + $varpage = empty($contextpage) ? $_SERVER["PHP_SELF"] : $contextpage; + $selectedfields = $form->multiSelectArrayWithCheckbox('selectedfields', $arrayfields, $varpage); // This also change content of $arrayfields + $selectedfields .= (count($arrayofmassactions) ? $form->showCheckAddButtons('checkforselect', 1) : ''); print '
    '; - print '
    '.$langs->trans("BoxTitleLastModifiedExpenses", min($max, $num)).''.$langs->trans("AmountHT").'
    '.$expensereportstatic->getNomUrl(1).''.$userstatic->getNomUrl(-1).'
    '."\n"; + print '
    '."\n"; // Filters print ''; - if (! empty($arrayfields['d.ref']['checked'])) + if (!empty($arrayfields['d.ref']['checked'])) { print ''; } // User - if (! empty($arrayfields['user']['checked'])) + if (!empty($arrayfields['user']['checked'])) { if ($user->rights->expensereport->readall || $user->rights->expensereport->lire_tous) { @@ -534,10 +534,10 @@ if ($resql) } } // Date start - if (! empty($arrayfields['d.date_debut']['checked'])) + if (!empty($arrayfields['d.date_debut']['checked'])) { print ''; } // Date end - if (! empty($arrayfields['d.date_fin']['checked'])) + if (!empty($arrayfields['d.date_fin']['checked'])) { print ''; } // Date valid - if (! empty($arrayfields['d.date_valid']['checked'])) + if (!empty($arrayfields['d.date_valid']['checked'])) { print ''; } // Date approve - if (! empty($arrayfields['d.date_approve']['checked'])) + if (!empty($arrayfields['d.date_approve']['checked'])) { 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 ''; } @@ -590,23 +590,23 @@ if ($resql) include DOL_DOCUMENT_ROOT.'/core/tpl/extrafields_list_search_input.tpl.php'; // Fields from hook - $parameters=array('arrayfields'=>$arrayfields); - $reshook=$hookmanager->executeHooks('printFieldListOption', $parameters); // Note that $action and $object may have been modified by hook + $parameters = array('arrayfields'=>$arrayfields); + $reshook = $hookmanager->executeHooks('printFieldListOption', $parameters); // Note that $action and $object may have been modified by hook print $hookmanager->resPrint; // Date creation - if (! empty($arrayfields['d.date_create']['checked'])) + if (!empty($arrayfields['d.date_create']['checked'])) { print ''; } // Date modification - if (! empty($arrayfields['d.tms']['checked'])) + if (!empty($arrayfields['d.tms']['checked'])) { print ''; } // Status - if (! empty($arrayfields['d.fk_statut']['checked'])) + if (!empty($arrayfields['d.fk_statut']['checked'])) { print ''; 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 + $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"; @@ -646,33 +646,33 @@ if ($resql) $total_total_ttc = 0; $total_total_tva = 0; - $expensereportstatic=new ExpenseReport($db); + $expensereportstatic = new ExpenseReport($db); $usertmp = new User($db); if ($num > 0) { - $i=0; - $totalarray=array(); + $i = 0; + $totalarray = array(); while ($i < min($num, $limit)) { $obj = $db->fetch_object($resql); - $expensereportstatic->id=$obj->rowid; - $expensereportstatic->ref=$obj->ref; - $expensereportstatic->status=$obj->status; - $expensereportstatic->date_debut=$db->jdate($obj->date_debut); - $expensereportstatic->date_fin=$db->jdate($obj->date_fin); - $expensereportstatic->date_create=$db->jdate($obj->date_create); - $expensereportstatic->date_modif=$db->jdate($obj->date_modif); - $expensereportstatic->date_valid=$db->jdate($obj->date_valid); - $expensereportstatic->date_approve=$db->jdate($obj->date_approve); - $expensereportstatic->note_private=$obj->note_private; - $expensereportstatic->note_public=$obj->note_public; + $expensereportstatic->id = $obj->rowid; + $expensereportstatic->ref = $obj->ref; + $expensereportstatic->status = $obj->status; + $expensereportstatic->date_debut = $db->jdate($obj->date_debut); + $expensereportstatic->date_fin = $db->jdate($obj->date_fin); + $expensereportstatic->date_create = $db->jdate($obj->date_create); + $expensereportstatic->date_modif = $db->jdate($obj->date_modif); + $expensereportstatic->date_valid = $db->jdate($obj->date_valid); + $expensereportstatic->date_approve = $db->jdate($obj->date_approve); + $expensereportstatic->note_private = $obj->note_private; + $expensereportstatic->note_public = $obj->note_public; print ''; // Ref - if (! empty($arrayfields['d.ref']['checked'])) { + if (!empty($arrayfields['d.ref']['checked'])) { print ''; $out .= ''; foreach ($productFournLogList as $productFournLog) { - $out.= ''; - $out.= ''; + $out .= ''; + $out .= ''; //$out.= ''; - $out.= ''; + $out .= ''; } $out .= '
    '; print ''; print ''; - if (! empty($conf->global->MAIN_LIST_FILTER_ON_DAY)) { + if (!empty($conf->global->MAIN_LIST_FILTER_ON_DAY)) { print ''; } @@ -546,10 +546,10 @@ if ($resql) print ''; - if (! empty($conf->global->MAIN_LIST_FILTER_ON_DAY)) { + if (!empty($conf->global->MAIN_LIST_FILTER_ON_DAY)) { print ''; } print ''; @@ -557,7 +557,7 @@ if ($resql) print ''; //print ''; @@ -565,7 +565,7 @@ if ($resql) print ''; //print ''; @@ -573,16 +573,16 @@ if ($resql) print ''; print ''; print ''; select_expensereport_statut($search_status, 'search_status', 1, 1); @@ -614,31 +614,31 @@ if ($resql) } // Action column print ''; - $searchpicto=$form->showFilterButtons(); + $searchpicto = $form->showFilterButtons(); print $searchpicto; print '
    '; print ''; print ''; } @@ -819,8 +819,8 @@ if ($resql) $db->free($resql); - $parameters=array('arrayfields'=>$arrayfields, 'sql'=>$sql); - $reshook=$hookmanager->executeHooks('printFieldListFooter', $parameters); // Note that $action and $object may have been modified by hook + $parameters = array('arrayfields'=>$arrayfields, 'sql'=>$sql); + $reshook = $hookmanager->executeHooks('printFieldListFooter', $parameters); // Note that $action and $object may have been modified by hook print $hookmanager->resPrint; print '
    '; @@ -809,8 +809,8 @@ if ($resql) } else { - $colspan=1; - foreach($arrayfields as $key => $val) { if (! empty($val['checked'])) $colspan++; } + $colspan = 1; + foreach ($arrayfields as $key => $val) { if (!empty($val['checked'])) $colspan++; } print '
    '.$langs->trans("NoRecordFound").'
    '."\n"; @@ -830,16 +830,16 @@ if ($resql) if (empty($id)) { - $hidegeneratedfilelistifempty=1; - if ($massaction == 'builddoc' || $action == 'remove_file' || $show_files) $hidegeneratedfilelistifempty=0; + $hidegeneratedfilelistifempty = 1; + if ($massaction == 'builddoc' || $action == 'remove_file' || $show_files) $hidegeneratedfilelistifempty = 0; // Show list of available documents - $urlsource=$_SERVER['PHP_SELF'].'?sortfield='.$sortfield.'&sortorder='.$sortorder; - $urlsource.=str_replace('&', '&', $param); + $urlsource = $_SERVER['PHP_SELF'].'?sortfield='.$sortfield.'&sortorder='.$sortorder; + $urlsource .= str_replace('&', '&', $param); - $filedir=$diroutputmassaction; - $genallowed=$user->rights->expensereport->lire; - $delallowed=$user->rights->expensereport->creer; + $filedir = $diroutputmassaction; + $genallowed = $user->rights->expensereport->lire; + $delallowed = $user->rights->expensereport->creer; print $formfile->showdocuments('massfilesarea_expensereport', '', $filedir, $urlsource, 0, $delallowed, '', 1, 1, 0, 48, 1, $param, $title, '', '', '', null, $hidegeneratedfilelistifempty); } diff --git a/htdocs/expensereport/payment/card.php b/htdocs/expensereport/payment/card.php index 72b7296ac6b..830349dbdcd 100644 --- a/htdocs/expensereport/payment/card.php +++ b/htdocs/expensereport/payment/card.php @@ -225,7 +225,7 @@ if ($resql) print '
    '; print '
    '; - print ''; + print '
    '; print ''; print ''; diff --git a/htdocs/expensereport/payment/payment.php b/htdocs/expensereport/payment/payment.php index 7fb79573ab2..b7a0d4f4c78 100644 --- a/htdocs/expensereport/payment/payment.php +++ b/htdocs/expensereport/payment/payment.php @@ -289,7 +289,7 @@ if ($action == 'create' || empty($action)) $num = 1; $i = 0; - print '
    '.$langs->trans('ExpenseReport').'
    '; + print '
    '; print ''; print ''; print ''; diff --git a/htdocs/expensereport/stats/index.php b/htdocs/expensereport/stats/index.php index 5d6301353db..12959e7946f 100644 --- a/htdocs/expensereport/stats/index.php +++ b/htdocs/expensereport/stats/index.php @@ -31,14 +31,14 @@ require_once DOL_DOCUMENT_ROOT.'/expensereport/class/expensereportstats.class.ph // Load translation files required by the page $langs->loadLangs(array('trips', 'companies')); -$WIDTH=DolGraph::getDefaultGraphSizeForStats('width'); -$HEIGHT=DolGraph::getDefaultGraphSizeForStats('height'); +$WIDTH = DolGraph::getDefaultGraphSizeForStats('width'); +$HEIGHT = DolGraph::getDefaultGraphSizeForStats('height'); -$mode=GETPOST("mode")?GETPOST("mode"):'customer'; -$object_status=GETPOST('object_status'); +$mode = GETPOST("mode") ?GETPOST("mode") : 'customer'; +$object_status = GETPOST('object_status'); -$userid=GETPOST('userid', 'int'); -$socid=GETPOST('socid', 'int'); if ($socid < 0) $socid=0; +$userid = GETPOST('userid', 'int'); +$socid = GETPOST('socid', 'int'); if ($socid < 0) $socid = 0; $id = GETPOST('id', 'int'); // Security check @@ -62,11 +62,11 @@ $endyear=$year; * View */ -$form=new Form($db); -$tmpexpensereport=new ExpenseReport($db); +$form = new Form($db); +$tmpexpensereport = new ExpenseReport($db); -$title=$langs->trans("TripsAndExpensesStatistics"); -$dir=$conf->expensereport->dir_temp; +$title = $langs->trans("TripsAndExpensesStatistics"); +$dir = $conf->expensereport->dir_temp; llxHeader('', $title); @@ -120,13 +120,13 @@ $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(); + $i = $startyear; $legend = array(); while ($i <= $endyear) { - $legend[]=$i; + $legend[] = $i; $i++; } $px2->SetLegend($legend); @@ -161,13 +161,13 @@ else $px3 = new DolGraph(); $mesg = $px3->isGraphKo(); -if (! $mesg) +if (!$mesg) { $px3->SetData($data); - $i = $startyear;$legend=array(); + $i = $startyear; $legend = array(); while ($i <= $endyear) { - $legend[]=$i; + $legend[] = $i; $i++; } $px3->SetLegend($legend); @@ -187,16 +187,16 @@ if (! $mesg) // Show array $data = $stats->getAllByYear(); -$arrayyears=array(); -foreach($data as $val) { - $arrayyears[$val['year']]=$val['year']; +$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; +$h = 0; $head = array(); -$head[$h][0] = DOL_URL_ROOT . '/expensereport/stats/index.php'; +$head[$h][0] = DOL_URL_ROOT.'/expensereport/stats/index.php'; $head[$h][1] = $langs->trans("ByMonthYear"); $head[$h][2] = 'byyear'; $h++; @@ -212,7 +212,7 @@ print '
    '; // Show filter box print ''; print ''; -print '
    '.$langs->trans("ExpenseReport").''.$langs->trans("Amount").'
    '; +print '
    '; print ''; // Company /* @@ -222,18 +222,18 @@ print ''; */ // User print ''; // Status print ''; // Year print ''; @@ -243,7 +243,7 @@ print ''; print '

    '; print '
    '; -print '
    '.$langs->trans("Filter").'
    '.$langs->trans("User").''; -$include=''; -if (empty($user->rights->expensereport->readall) && empty($user->rights->expensereport->lire_tous)) $include='hierarchy'; +$include = ''; +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 '
    '.$langs->trans("Status").''; -$liststatus=$tmpexpensereport->statuts; +$liststatus = $tmpexpensereport->statuts; print $form->selectarray('object_status', $liststatus, GETPOST('object_status', 'int'), -4, 0, 0, '', 1); print '
    '.$langs->trans("Year").''; -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 '
    '; +print '
    '; print ''; print ''; print ''; @@ -251,11 +251,11 @@ print ''; print ''; print ''; -$oldyear=0; +$oldyear = 0; foreach ($data as $val) { $year = $val['year']; - while ($year && $oldyear > $year+1) + while ($year && $oldyear > $year + 1) { // If we have empty year $oldyear--; @@ -274,7 +274,7 @@ foreach ($data as $val) print ''; print ''; print ''; - $oldyear=$year; + $oldyear = $year; } print '
    '.$langs->trans("Year").''.$langs->trans("Number").''.$langs->trans("AmountTotal").''.$langs->trans("AmountAverage").'
    '.price(price2num($val['total'], 'MT'), 1).''.price(price2num($val['avg'], 'MT'), 1).'
    '; @@ -284,7 +284,7 @@ print '
    '; // Show graphs -print ''; print ''; @@ -820,7 +820,7 @@ if ($object->id > 0) if ($user->rights->fournisseur->facture->creer) { - if (! empty($orders2invoice) && $orders2invoice > 0) + if (!empty($orders2invoice) && $orders2invoice > 0) { if ($object->status == 1) { @@ -836,7 +836,7 @@ if ($object->id > 0) } // Add action - if (! empty($conf->agenda->enabled) && ! empty($conf->global->MAIN_REPEATTASKONEACHTAB) && $object->status==1) + if (!empty($conf->agenda->enabled) && !empty($conf->global->MAIN_REPEATTASKONEACHTAB) && $object->status == 1) { if ($user->rights->agenda->myactions->create) { @@ -852,14 +852,14 @@ if ($object->id > 0) print ''; - if (! empty($conf->global->MAIN_DUPLICATE_CONTACTS_TAB_ON_MAIN_CARD)) + if (!empty($conf->global->MAIN_DUPLICATE_CONTACTS_TAB_ON_MAIN_CARD)) { print '
    '; // 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"), '', ''); diff --git a/htdocs/fourn/class/fournisseur.commande.class.php b/htdocs/fourn/class/fournisseur.commande.class.php index b46077ee930..b1ebe4a3895 100644 --- a/htdocs/fourn/class/fournisseur.commande.class.php +++ b/htdocs/fourn/class/fournisseur.commande.class.php @@ -34,7 +34,7 @@ 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'; /** @@ -45,12 +45,12 @@ class CommandeFournisseur extends CommonOrder /** * @var string ID to identify managed object */ - public $element='order_supplier'; + public $element = 'order_supplier'; /** * @var string Name of table without prefix where object is stored */ - public $table_element='commande_fournisseur'; + public $table_element = 'commande_fournisseur'; /** * @var int Name of subtable line @@ -97,19 +97,19 @@ class CommandeFournisseur extends CommonOrder public $ref_supplier; public $brouillon; - public $statut; // 0=Draft -> 1=Validated -> 2=Approved -> 3=Ordered/Process runing -> 4=Received partially -> 5=Received totally -> (reopen) 4=Received partially + public $statut; // 0=Draft -> 1=Validated -> 2=Approved -> 3=Ordered/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 // -> 9=Refused -> (reopen) 1=Validated // Note: billed or not is on another field "billed" - public $statuts; // List of status + public $statuts; // List of status public $socid; public $fourn_id; public $date; public $date_valid; public $date_approve; - public $date_approve2; // Used when SUPPLIER_ORDER_3_STEPS_TO_BE_APPROVED is set + public $date_approve2; // Used when SUPPLIER_ORDER_3_STEPS_TO_BE_APPROVED is set public $date_commande; /** @@ -119,8 +119,8 @@ class CommandeFournisseur extends CommonOrder public $total_ht; public $total_tva; - public $total_localtax1; // Total Local tax 1 - public $total_localtax2; // Total Local tax 2 + public $total_localtax1; // Total Local tax 1 + public $total_localtax2; // Total Local tax 2 public $total_ttc; public $source; @@ -152,14 +152,14 @@ class CommandeFournisseur extends CommonOrder public $user_author_id; public $user_valid_id; public $user_approve_id; - public $user_approve_id2; // Used when SUPPLIER_ORDER_3_STEPS_TO_BE_APPROVED is set + public $user_approve_id2; // Used when SUPPLIER_ORDER_3_STEPS_TO_BE_APPROVED is set //Incoterms public $fk_incoterms; public $location_incoterms; - public $label_incoterms; //Used into tooltip + public $label_incoterms; //Used into tooltip - public $extraparams=array(); + public $extraparams = array(); /** * @var CommandeFournisseurLigne[] @@ -169,7 +169,7 @@ class CommandeFournisseur extends CommonOrder //Add for supplier_proposal public $origin; public $origin_id; - public $linked_objects=array(); + public $linked_objects = array(); // Multicurrency /** @@ -259,81 +259,81 @@ class CommandeFournisseur extends CommonOrder 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.tva as total_vat,"; - $sql.= " c.localtax1, c.localtax2, "; - $sql.= " c.date_creation, c.date_valid, c.date_approve, c.date_approve2,"; - $sql.= " c.fk_user_author, c.fk_user_valid, c.fk_user_approve, c.fk_user_approve2,"; - $sql.= " c.date_commande as date_commande, c.date_livraison as date_livraison, c.fk_cond_reglement, c.fk_mode_reglement, c.fk_projet as fk_project, c.remise_percent, c.source, c.fk_input_method,"; - $sql.= " c.fk_account,"; - $sql.= " c.note_private, c.note_public, c.model_pdf, c.extraparams, c.billed,"; - $sql.= " c.fk_multicurrency, c.multicurrency_code, c.multicurrency_tx, c.multicurrency_total_ht, c.multicurrency_total_tva, c.multicurrency_total_ttc,"; - $sql.= " cm.libelle as methode_commande,"; - $sql.= " cr.code as cond_reglement_code, cr.libelle as cond_reglement_libelle, cr.libelle_facture as cond_reglement_libelle_doc,"; - $sql.= " p.code as mode_reglement_code, p.libelle as mode_reglement_libelle"; - $sql.= ', c.fk_incoterms, c.location_incoterms'; - $sql.= ', i.libelle as label_incoterms'; - $sql.= " FROM ".MAIN_DB_PREFIX."commande_fournisseur as c"; - $sql.= " LEFT JOIN ".MAIN_DB_PREFIX."c_payment_term as cr ON c.fk_cond_reglement = cr.rowid"; - $sql.= " LEFT JOIN ".MAIN_DB_PREFIX."c_paiement as p ON c.fk_mode_reglement = p.id"; - $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'; - $sql.= " WHERE c.entity = ".$conf->entity; - if ($ref) $sql.= " AND c.ref='".$this->db->escape($ref)."'"; - else $sql.= " AND c.rowid=".$id; + $sql .= " c.localtax1, c.localtax2, "; + $sql .= " c.date_creation, c.date_valid, c.date_approve, c.date_approve2,"; + $sql .= " c.fk_user_author, c.fk_user_valid, c.fk_user_approve, c.fk_user_approve2,"; + $sql .= " c.date_commande as date_commande, c.date_livraison as date_livraison, c.fk_cond_reglement, c.fk_mode_reglement, c.fk_projet as fk_project, c.remise_percent, c.source, c.fk_input_method,"; + $sql .= " c.fk_account,"; + $sql .= " c.note_private, c.note_public, c.model_pdf, c.extraparams, c.billed,"; + $sql .= " c.fk_multicurrency, c.multicurrency_code, c.multicurrency_tx, c.multicurrency_total_ht, c.multicurrency_total_tva, c.multicurrency_total_ttc,"; + $sql .= " cm.libelle as methode_commande,"; + $sql .= " cr.code as cond_reglement_code, cr.libelle as cond_reglement_libelle, cr.libelle_facture as cond_reglement_libelle_doc,"; + $sql .= " p.code as mode_reglement_code, p.libelle as mode_reglement_libelle"; + $sql .= ', c.fk_incoterms, c.location_incoterms'; + $sql .= ', i.libelle as label_incoterms'; + $sql .= " FROM ".MAIN_DB_PREFIX."commande_fournisseur as c"; + $sql .= " LEFT JOIN ".MAIN_DB_PREFIX."c_payment_term as cr ON c.fk_cond_reglement = cr.rowid"; + $sql .= " LEFT JOIN ".MAIN_DB_PREFIX."c_paiement as p ON c.fk_mode_reglement = p.id"; + $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'; + $sql .= " WHERE c.entity = ".$conf->entity; + if ($ref) $sql .= " AND c.ref='".$this->db->escape($ref)."'"; + else $sql .= " AND c.rowid=".$id; dol_syslog(get_class($this)."::fetch", LOG_DEBUG); $resql = $this->db->query($sql); if ($resql) { $obj = $this->db->fetch_object($resql); - if (! $obj) + if (!$obj) { - $this->error='Bill with id '.$id.' not found'; + $this->error = 'Bill with id '.$id.' not found'; dol_syslog(get_class($this).'::fetch '.$this->error); return 0; } - $this->id = $obj->rowid; - $this->entity = $obj->entity; + $this->id = $obj->rowid; + $this->entity = $obj->entity; - $this->ref = $obj->ref; - $this->ref_supplier = $obj->ref_supplier; - $this->socid = $obj->fk_soc; - $this->fourn_id = $obj->fk_soc; + $this->ref = $obj->ref; + $this->ref_supplier = $obj->ref_supplier; + $this->socid = $obj->fk_soc; + $this->fourn_id = $obj->fk_soc; $this->statut = $obj->fk_statut; $this->billed = $obj->billed; - $this->user_author_id = $obj->fk_user_author; - $this->user_valid_id = $obj->fk_user_valid; - $this->user_approve_id = $obj->fk_user_approve; - $this->user_approve_id2 = $obj->fk_user_approve2; + $this->user_author_id = $obj->fk_user_author; + $this->user_valid_id = $obj->fk_user_valid; + $this->user_approve_id = $obj->fk_user_approve; + $this->user_approve_id2 = $obj->fk_user_approve2; $this->total_ht = $obj->total_ht; $this->total_tva = $obj->total_vat; $this->total_localtax1 = $obj->localtax1; $this->total_localtax2 = $obj->localtax2; $this->total_ttc = $obj->total_ttc; - $this->date = $this->db->jdate($obj->date_creation); - $this->date_valid = $this->db->jdate($obj->date_valid); + $this->date = $this->db->jdate($obj->date_creation); + $this->date_valid = $this->db->jdate($obj->date_valid); $this->date_approve = $this->db->jdate($obj->date_approve); $this->date_approve2 = $this->db->jdate($obj->date_approve2); $this->date_commande = $this->db->jdate($obj->date_commande); // date we make the order to supplier - $this->date_livraison = $this->db->jdate($obj->date_livraison); - $this->remise_percent = $obj->remise_percent; - $this->methode_commande_id = $obj->fk_input_method; - $this->methode_commande = $obj->methode_commande; + $this->date_livraison = $this->db->jdate($obj->date_livraison); + $this->remise_percent = $obj->remise_percent; + $this->methode_commande_id = $obj->fk_input_method; + $this->methode_commande = $obj->methode_commande; - $this->source = $obj->source; - $this->fk_project = $obj->fk_project; - $this->cond_reglement_id = $obj->fk_cond_reglement; - $this->cond_reglement_code = $obj->cond_reglement_code; - $this->cond_reglement = $obj->cond_reglement_libelle; - $this->cond_reglement_doc = $obj->cond_reglement_libelle_doc; - $this->fk_account = $obj->fk_account; - $this->mode_reglement_id = $obj->fk_mode_reglement; - $this->mode_reglement_code = $obj->mode_reglement_code; - $this->mode_reglement = $obj->mode_reglement_libelle; - $this->note = $obj->note_private; // deprecated - $this->note_private = $obj->note_private; - $this->note_public = $obj->note_public; - $this->modelpdf = $obj->model_pdf; + $this->source = $obj->source; + $this->fk_project = $obj->fk_project; + $this->cond_reglement_id = $obj->fk_cond_reglement; + $this->cond_reglement_code = $obj->cond_reglement_code; + $this->cond_reglement = $obj->cond_reglement_libelle; + $this->cond_reglement_doc = $obj->cond_reglement_libelle_doc; + $this->fk_account = $obj->fk_account; + $this->mode_reglement_id = $obj->fk_mode_reglement; + $this->mode_reglement_code = $obj->mode_reglement_code; + $this->mode_reglement = $obj->mode_reglement_libelle; + $this->note = $obj->note_private; // deprecated + $this->note_private = $obj->note_private; + $this->note_public = $obj->note_public; + $this->modelpdf = $obj->model_pdf; //Incoterms $this->fk_incoterms = $obj->fk_incoterms; @@ -342,13 +342,13 @@ class CommandeFournisseur extends CommonOrder // Multicurrency $this->fk_multicurrency = $obj->fk_multicurrency; - $this->multicurrency_code = $obj->multicurrency_code; + $this->multicurrency_code = $obj->multicurrency_code; $this->multicurrency_tx = $obj->multicurrency_tx; - $this->multicurrency_total_ht = $obj->multicurrency_total_ht; + $this->multicurrency_total_ht = $obj->multicurrency_total_ht; $this->multicurrency_total_tva = $obj->multicurrency_total_tva; $this->multicurrency_total_ttc = $obj->multicurrency_total_ttc; - $this->extraparams = (array) json_decode($obj->extraparams, true); + $this->extraparams = (array) json_decode($obj->extraparams, true); $this->db->free($resql); @@ -361,7 +361,7 @@ class CommandeFournisseur extends CommonOrder /* * Lines */ - $result=$this->fetch_lines(); + $result = $this->fetch_lines(); if ($result < 0) { return -1; @@ -373,7 +373,7 @@ class CommandeFournisseur extends CommonOrder } else { - $this->error=$this->db->error()." sql=".$sql; + $this->error = $this->db->error()." sql=".$sql; return -1; } } @@ -389,21 +389,21 @@ class CommandeFournisseur extends CommonOrder { // phpcs:enable //$result=$this->fetch_lines(); - $this->lines=array(); + $this->lines = array(); $sql = "SELECT l.rowid, l.ref as ref_supplier, l.fk_product, l.product_type, l.label, l.description, l.qty,"; - $sql.= " l.vat_src_code, l.tva_tx, l.remise_percent, l.subprice,"; - $sql.= " l.localtax1_tx, l. localtax2_tx, l.localtax1_type, l. localtax2_type, l.total_localtax1, l.total_localtax2,"; - $sql.= " l.total_ht, l.total_tva, l.total_ttc, l.special_code, l.fk_parent_line, l.rang,"; - $sql.= " p.rowid as product_id, p.ref as product_ref, p.label as product_label, p.description as product_desc,"; - $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'; - $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 = ".$this->id; + $sql .= " l.vat_src_code, l.tva_tx, l.remise_percent, l.subprice,"; + $sql .= " l.localtax1_tx, l. localtax2_tx, l.localtax1_type, l. localtax2_type, l.total_localtax1, l.total_localtax2,"; + $sql .= " l.total_ht, l.total_tva, l.total_ttc, l.special_code, l.fk_parent_line, l.rang,"; + $sql .= " p.rowid as product_id, p.ref as product_ref, p.label as product_label, p.description as product_desc,"; + $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'; + $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 = ".$this->id; if ($only_product) $sql .= ' AND p.fk_product_type = 0'; - $sql.= " ORDER BY l.rang, l.rowid"; + $sql .= " ORDER BY l.rang, l.rowid"; //print $sql; dol_syslog(get_class($this)."::fetch get lines", LOG_DEBUG); @@ -415,9 +415,9 @@ class CommandeFournisseur extends CommonOrder while ($i < $num) { - $objp = $this->db->fetch_object($result); + $objp = $this->db->fetch_object($result); - $line = new CommandeFournisseurLigne($this->db); + $line = new CommandeFournisseurLigne($this->db); $line->id = $objp->rowid; $line->desc = $objp->description; @@ -429,7 +429,7 @@ class CommandeFournisseur extends CommonOrder $line->localtax1_type = $objp->localtax1_type; $line->localtax2_type = $objp->localtax2_type; $line->subprice = $objp->subprice; - $line->pu_ht = $objp->subprice; + $line->pu_ht = $objp->subprice; $line->remise_percent = $objp->remise_percent; $line->vat_src_code = $objp->vat_src_code; @@ -446,18 +446,18 @@ class CommandeFournisseur extends CommonOrder $line->product_label = $objp->product_label; $line->product_desc = $objp->product_desc; - $line->ref = $objp->product_ref; // Ref of product - $line->product_ref = $objp->product_ref; // Ref of product - $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 + $line->ref = $objp->product_ref; // Ref of product + $line->product_ref = $objp->product_ref; // Ref of product + $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 $line->date_start = $this->db->jdate($objp->date_start); $line->date_end = $this->db->jdate($objp->date_end); $line->fk_unit = $objp->fk_unit; // Multicurrency - $line->fk_multicurrency = $objp->fk_multicurrency; - $line->multicurrency_code = $objp->multicurrency_code; + $line->fk_multicurrency = $objp->fk_multicurrency; + $line->multicurrency_code = $objp->multicurrency_code; $line->multicurrency_subprice = $objp->multicurrency_subprice; $line->multicurrency_total_ht = $objp->multicurrency_total_ht; $line->multicurrency_total_tva = $objp->multicurrency_total_tva; @@ -472,7 +472,7 @@ class CommandeFournisseur extends CommonOrder // fetch optionals attributes and labels $line->fetch_optionals(); - $this->lines[$i] = $line; + $this->lines[$i] = $line; $i++; } @@ -482,7 +482,7 @@ class CommandeFournisseur extends CommonOrder } else { - $this->error=$this->db->error()." sql=".$sql; + $this->error = $this->db->error()." sql=".$sql; return -1; } } @@ -497,15 +497,15 @@ class CommandeFournisseur extends CommonOrder */ public function valid($user, $idwarehouse = 0, $notrigger = 0) { - global $langs,$conf; + global $langs, $conf; require_once DOL_DOCUMENT_ROOT.'/core/lib/files.lib.php'; - $error=0; + $error = 0; 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))) + 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))) { $this->db->begin(); @@ -525,29 +525,29 @@ class CommandeFournisseur extends CommonOrder $this->newref = $num; $sql = 'UPDATE '.MAIN_DB_PREFIX."commande_fournisseur"; - $sql.= " SET ref='".$this->db->escape($num)."',"; - $sql.= " fk_statut = ".self::STATUS_VALIDATED.","; - $sql.= " date_valid='".$this->db->idate(dol_now())."',"; - $sql.= " fk_user_valid = ".$user->id; - $sql.= " WHERE rowid = ".$this->id; - $sql.= " AND fk_statut = ".self::STATUS_DRAFT; + $sql .= " SET ref='".$this->db->escape($num)."',"; + $sql .= " fk_statut = ".self::STATUS_VALIDATED.","; + $sql .= " date_valid='".$this->db->idate(dol_now())."',"; + $sql .= " fk_user_valid = ".$user->id; + $sql .= " WHERE rowid = ".$this->id; + $sql .= " AND fk_statut = ".self::STATUS_DRAFT; - $resql=$this->db->query($sql); - if (! $resql) + $resql = $this->db->query($sql); + if (!$resql) { dol_print_error($this->db); $error++; } - if (! $error && ! $notrigger) + if (!$error && !$notrigger) { // Call trigger - $result=$this->call_trigger('ORDER_SUPPLIER_VALIDATE', $user); + $result = $this->call_trigger('ORDER_SUPPLIER_VALIDATE', $user); if ($result < 0) $error++; // End call triggers } - if (! $error) + if (!$error) { $this->oldref = $this->ref; @@ -555,17 +555,17 @@ class CommandeFournisseur extends CommonOrder 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; + $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); @@ -573,13 +573,13 @@ class CommandeFournisseur extends CommonOrder { 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) + $listoffiles = dol_dir_list($conf->fournisseur->commande->dir_output.'/'.$newref, 'files', 1, '^'.preg_quote($oldref, '/')); + foreach ($listoffiles as $fileentry) { - $dirsource=$fileentry['name']; - $dirdest=preg_replace('/^'.preg_quote($oldref, '/').'/', $newref, $dirsource); - $dirsource=$fileentry['path'].'/'.$dirsource; - $dirdest=$fileentry['path'].'/'.$dirdest; + $dirsource = $fileentry['name']; + $dirdest = preg_replace('/^'.preg_quote($oldref, '/').'/', $newref, $dirsource); + $dirsource = $fileentry['path'].'/'.$dirsource; + $dirdest = $fileentry['path'].'/'.$dirdest; @rename($dirsource, $dirdest); } } @@ -587,14 +587,14 @@ 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; @@ -607,7 +607,7 @@ class CommandeFournisseur extends CommonOrder } else { - $this->error='NotAuthorized'; + $this->error = 'NotAuthorized'; dol_syslog(get_class($this)."::valid ".$this->error, LOG_ERR); return -1; } @@ -638,7 +638,7 @@ class CommandeFournisseur extends CommonOrder // phpcs:enable global $conf, $langs; - if (empty($this->statuts) || empty($this->statutshort)){ + if (empty($this->statuts) || empty($this->statutshort)) { $langs->load('orders'); $this->statuts[0] = 'StatusSupplierOrderDraft'; @@ -648,8 +648,8 @@ class CommandeFournisseur extends CommonOrder else $this->statuts[3] = 'StatusSupplierOrderOnProcessWithValidation'; $this->statuts[4] = 'StatusSupplierOrderReceivedPartially'; $this->statuts[5] = 'StatusSupplierOrderReceivedAll'; - $this->statuts[6] = 'StatusSupplierOrderCanceled'; // Approved->Canceled - $this->statuts[7] = 'StatusSupplierOrderCanceled'; // Process running->canceled + $this->statuts[6] = 'StatusSupplierOrderCanceled'; // Approved->Canceled + $this->statuts[7] = 'StatusSupplierOrderCanceled'; // Process running->canceled $this->statuts[9] = 'StatusSupplierOrderRefused'; // List of language codes for status @@ -678,12 +678,12 @@ class CommandeFournisseur extends CommonOrder ); $statusClass = 'status0'; - if(!empty($statustrans[$status])){ + if (!empty($statustrans[$status])) { $statusClass = $statustrans[$status]; } $billedtext = ''; - if($mode == 4 && $billed){ + if ($mode == 4 && $billed) { $billedtext = ' - '.$langs->trans("Billed"); } @@ -707,49 +707,49 @@ class CommandeFournisseur extends CommonOrder { global $langs, $conf; - $result=''; - $label = '' . $langs->trans("ShowOrder") . ''; - if (! empty($this->ref)) - $label .= '
    ' . $langs->trans('Ref') . ': ' . $this->ref; - if (! empty($this->ref_supplier)) - $label.= '
    ' . $langs->trans('RefSupplier') . ': ' . $this->ref_supplier; - if (! empty($this->total_ht)) - $label.= '
    ' . $langs->trans('AmountHT') . ': ' . price($this->total_ht, 0, $langs, 0, -1, -1, $conf->currency); - if (! empty($this->total_tva)) - $label.= '
    ' . $langs->trans('VAT') . ': ' . price($this->total_tva, 0, $langs, 0, -1, -1, $conf->currency); - if (! empty($this->total_ttc)) - $label.= '
    ' . $langs->trans('AmountTTC') . ': ' . price($this->total_ttc, 0, $langs, 0, -1, -1, $conf->currency); + $result = ''; + $label = ''.$langs->trans("ShowOrder").''; + if (!empty($this->ref)) + $label .= '
    '.$langs->trans('Ref').': '.$this->ref; + if (!empty($this->ref_supplier)) + $label .= '
    '.$langs->trans('RefSupplier').': '.$this->ref_supplier; + if (!empty($this->total_ht)) + $label .= '
    '.$langs->trans('AmountHT').': '.price($this->total_ht, 0, $langs, 0, -1, -1, $conf->currency); + if (!empty($this->total_tva)) + $label .= '
    '.$langs->trans('VAT').': '.price($this->total_tva, 0, $langs, 0, -1, -1, $conf->currency); + if (!empty($this->total_ttc)) + $label .= '
    '.$langs->trans('AmountTTC').': '.price($this->total_ttc, 0, $langs, 0, -1, -1, $conf->currency); - $picto='order'; + $picto = 'order'; $url = DOL_URL_ROOT.'/fourn/commande/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'; + $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=''; + $linkclose = ''; if (empty($notooltip)) { - if (! empty($conf->global->MAIN_OPTIMIZEFORTEXTBROWSER)) + if (!empty($conf->global->MAIN_OPTIMIZEFORTEXTBROWSER)) { - $label=$langs->trans("ShowOrder"); - $linkclose.=' alt="'.dol_escape_htmltag($label, 1).'"'; + $label = $langs->trans("ShowOrder"); + $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"'; } $linkstart = ''; - $linkend=''; + $linkstart .= $linkclose.'>'; + $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; + if ($withpicto) $result .= img_object(($notooltip ? '' : $label), $this->picto, ($notooltip ? (($withpicto != 2) ? 'class="paddingright"' : '') : 'class="'.(($withpicto != 2) ? 'paddingright ' : '').'classfortooltip"'), 0, 0, $notooltip ? 0 : 1); + if ($withpicto != 2) $result .= $this->ref; $result .= $linkend; return $result; @@ -768,12 +768,12 @@ 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'; - $classname=$conf->global->COMMANDE_SUPPLIER_ADDON_NUMBER; + $classname = $conf->global->COMMANDE_SUPPLIER_ADDON_NUMBER; // Include file with class $dirmodels = array_merge(array('/'), (array) $conf->modules_parts['models']); @@ -782,7 +782,7 @@ class CommandeFournisseur extends CommonOrder $dir = dol_buildpath($reldir."core/modules/supplier_order/"); // Load file with numbering class (if found) - $mybool|=@include_once $dir.$file; + $mybool |= @include_once $dir.$file; } if ($mybool === false) { @@ -793,7 +793,7 @@ class CommandeFournisseur extends CommonOrder $obj = new $classname(); $numref = $obj->getNextValue($soc, $this); - if ( $numref != "") + if ($numref != "") { return $numref; } @@ -817,24 +817,24 @@ class CommandeFournisseur extends CommonOrder */ public function classifyBilled(User $user) { - $error=0; + $error = 0; $this->db->begin(); $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 (!$error) { // Call trigger - $result=$this->call_trigger('ORDER_SUPPLIER_CLASSIFY_BILLED', $user); + $result = $this->call_trigger('ORDER_SUPPLIER_CLASSIFY_BILLED', $user); if ($result < 0) $error++; // End call triggers } - if (! $error) + if (!$error) { - $this->billed=1; + $this->billed = 1; $this->db->commit(); return 1; @@ -864,10 +864,10 @@ class CommandeFournisseur extends CommonOrder */ public function approve($user, $idwarehouse = 0, $secondlevel = 0) { - global $langs,$conf; + global $langs, $conf; require_once DOL_DOCUMENT_ROOT.'/core/lib/files.lib.php'; - $error=0; + $error = 0; dol_syslog(get_class($this)."::approve"); @@ -893,42 +893,42 @@ class CommandeFournisseur extends CommonOrder $this->newref = $num; // Do we have to change status now ? (If double approval is required and first approval, we keep status to 1 = validated) - $movetoapprovestatus=true; - $comment=''; + $movetoapprovestatus = true; + $comment = ''; $sql = "UPDATE ".MAIN_DB_PREFIX."commande_fournisseur"; - $sql.= " SET ref='".$this->db->escape($num)."',"; + $sql .= " SET ref='".$this->db->escape($num)."',"; 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) + $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)) { - $movetoapprovestatus=false; // second level approval not done - $comment=' (first level)'; + $movetoapprovestatus = false; // second level approval not done + $comment = ' (first level)'; } } } else // request a second level approval { - $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 - $comment=' (second level)'; + $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 + $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; - $sql.= " WHERE rowid = ".$this->id; - $sql.= " AND 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 (!empty($conf->global->SUPPLIER_ORDER_AUTOADD_USER_CONTACT)) { - $result=$this->add_contact($user->id, 'SALESREPFOLL', 'internal', 1); + $result = $this->add_contact($user->id, 'SALESREPFOLL', 'internal', 1); if ($result < 0 && $result != -2) // -2 means already exists { $error++; @@ -936,12 +936,12 @@ class CommandeFournisseur extends CommonOrder } // 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); + $cpt = count($this->lines); for ($i = 0; $i < $cpt; $i++) { // Product with reference @@ -951,24 +951,24 @@ class CommandeFournisseur extends CommonOrder $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'); - $result=$mouvP->reception($user, $this->lines[$i]->fk_product, $idwarehouse, $this->lines[$i]->qty, $up_ht_disc, $langs->trans("OrderApprovedInDolibarr", $this->ref)); + $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'); + $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++; } unset($this->line); } } } - if (! $error) + if (!$error) { // Call trigger - $result=$this->call_trigger('ORDER_SUPPLIER_APPROVE', $user); + $result = $this->call_trigger('ORDER_SUPPLIER_APPROVE', $user); if ($result < 0) $error++; // End call triggers } - if (! $error) + if (!$error) { $this->ref = $this->newref; @@ -997,7 +997,7 @@ class CommandeFournisseur extends CommonOrder else { $this->db->rollback(); - $this->error=$this->db->lasterror(); + $this->error = $this->db->lasterror(); return -1; } } @@ -1018,7 +1018,7 @@ class CommandeFournisseur extends CommonOrder { global $conf, $langs; - $error=0; + $error = 0; dol_syslog(get_class($this)."::refuse"); $result = 0; @@ -1036,7 +1036,7 @@ class CommandeFournisseur extends CommonOrder if ($error == 0) { // Call trigger - $result=$this->call_trigger('ORDER_SUPPLIER_REFUSE', $user); + $result = $this->call_trigger('ORDER_SUPPLIER_REFUSE', $user); if ($result < 0) { $error++; @@ -1050,7 +1050,7 @@ class CommandeFournisseur extends CommonOrder else { $this->db->rollback(); - $this->error=$this->db->lasterror(); + $this->error = $this->db->lasterror(); dol_syslog(get_class($this)."::refuse Error -1"); $result = -1; } @@ -1059,7 +1059,7 @@ class CommandeFournisseur extends CommonOrder { dol_syslog(get_class($this)."::refuse Not Authorized"); } - return $result ; + return $result; } // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps @@ -1074,9 +1074,9 @@ class CommandeFournisseur extends CommonOrder public function Cancel($user, $idwarehouse = -1) { // phpcs:enable - global $langs,$conf; + global $langs, $conf; - $error=0; + $error = 0; //dol_syslog("CommandeFournisseur::Cancel"); $result = 0; @@ -1094,7 +1094,7 @@ class CommandeFournisseur extends CommonOrder $result = 0; // Call trigger - $result=$this->call_trigger('ORDER_SUPPLIER_CANCEL', $user); + $result = $this->call_trigger('ORDER_SUPPLIER_CANCEL', $user); if ($result < 0) $error++; // End call triggers @@ -1112,7 +1112,7 @@ class CommandeFournisseur extends CommonOrder else { $this->db->rollback(); - $this->error=$this->db->lasterror(); + $this->error = $this->db->lasterror(); dol_syslog(get_class($this)."::cancel ".$this->error); return -1; } @@ -1153,7 +1153,7 @@ class CommandeFournisseur extends CommonOrder $this->date_commande = $date; // Call trigger - $result=$this->call_trigger('ORDER_SUPPLIER_SUBMIT', $user); + $result = $this->call_trigger('ORDER_SUPPLIER_SUBMIT', $user); if ($result < 0) $error++; // End call triggers } @@ -1164,7 +1164,7 @@ class CommandeFournisseur extends CommonOrder $this->errors[] = $this->db->lasterror(); } - if (! $error) + if (!$error) { $this->db->commit(); } @@ -1193,18 +1193,18 @@ class CommandeFournisseur extends CommonOrder */ public function create($user, $notrigger = 0) { - global $langs,$conf,$hookmanager; + global $langs, $conf, $hookmanager; $this->db->begin(); - $error=0; - $now=dol_now(); + $error = 0; + $now = dol_now(); // Clean parameters 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); + if (!empty($this->multicurrency_code) && empty($this->multicurrency_tx)) list($this->fk_multicurrency, $this->multicurrency_tx) = MultiCurrency::getIdAndTxFromCode($this->db, $this->multicurrency_code); else $this->fk_multicurrency = MultiCurrency::getIdFromCode($this->db, $this->multicurrency_code); if (empty($this->fk_multicurrency)) { @@ -1217,50 +1217,50 @@ class CommandeFournisseur extends CommonOrder $this->brouillon = 1; $sql = "INSERT INTO ".MAIN_DB_PREFIX."commande_fournisseur ("; - $sql.= "ref"; - $sql.= ", ref_supplier"; - $sql.= ", note_private"; - $sql.= ", note_public"; - $sql.= ", entity"; - $sql.= ", fk_soc"; - $sql.= ", fk_projet"; - $sql.= ", date_creation"; - $sql.= ", date_livraison"; - $sql.= ", fk_user_author"; - $sql.= ", fk_statut"; - $sql.= ", source"; - $sql.= ", model_pdf"; - $sql.= ", fk_mode_reglement"; - $sql.= ", fk_cond_reglement"; - $sql.= ", fk_account"; - $sql.= ", fk_incoterms, location_incoterms"; - $sql.= ", fk_multicurrency"; - $sql.= ", multicurrency_code"; - $sql.= ", multicurrency_tx"; - $sql.= ") "; - $sql.= " VALUES ("; - $sql.= "''"; - $sql.= ", '".$this->db->escape($this->ref_supplier)."'"; - $sql.= ", '".$this->db->escape($this->note_private)."'"; - $sql.= ", '".$this->db->escape($this->note_public)."'"; - $sql.= ", ".$conf->entity; - $sql.= ", ".$this->socid; - $sql.= ", ".($this->fk_project > 0 ? $this->fk_project : "null"); - $sql.= ", '".$this->db->idate($now)."'"; - $sql.= ", ".($this->date_livraison?"'".$this->db->idate($this->date_livraison)."'":"null"); - $sql.= ", ".$user->id; - $sql.= ", ".self::STATUS_DRAFT; - $sql.= ", ".$this->db->escape($this->source); - $sql.= ", '".$conf->global->COMMANDE_SUPPLIER_ADDON_PDF."'"; - $sql.= ", ".($this->mode_reglement_id > 0 ? $this->mode_reglement_id : 'null'); - $sql.= ", ".($this->cond_reglement_id > 0 ? $this->cond_reglement_id : 'null'); - $sql.= ", ".($this->fk_account>0?$this->fk_account:'NULL'); - $sql.= ", ".(int) $this->fk_incoterms; - $sql.= ", '".$this->db->escape($this->location_incoterms)."'"; - $sql.= ", ".(int) $this->fk_multicurrency; - $sql.= ", '".$this->db->escape($this->multicurrency_code)."'"; - $sql.= ", ".(double) $this->multicurrency_tx; - $sql.= ")"; + $sql .= "ref"; + $sql .= ", ref_supplier"; + $sql .= ", note_private"; + $sql .= ", note_public"; + $sql .= ", entity"; + $sql .= ", fk_soc"; + $sql .= ", fk_projet"; + $sql .= ", date_creation"; + $sql .= ", date_livraison"; + $sql .= ", fk_user_author"; + $sql .= ", fk_statut"; + $sql .= ", source"; + $sql .= ", model_pdf"; + $sql .= ", fk_mode_reglement"; + $sql .= ", fk_cond_reglement"; + $sql .= ", fk_account"; + $sql .= ", fk_incoterms, location_incoterms"; + $sql .= ", fk_multicurrency"; + $sql .= ", multicurrency_code"; + $sql .= ", multicurrency_tx"; + $sql .= ") "; + $sql .= " VALUES ("; + $sql .= "''"; + $sql .= ", '".$this->db->escape($this->ref_supplier)."'"; + $sql .= ", '".$this->db->escape($this->note_private)."'"; + $sql .= ", '".$this->db->escape($this->note_public)."'"; + $sql .= ", ".$conf->entity; + $sql .= ", ".$this->socid; + $sql .= ", ".($this->fk_project > 0 ? $this->fk_project : "null"); + $sql .= ", '".$this->db->idate($now)."'"; + $sql .= ", ".($this->date_livraison ? "'".$this->db->idate($this->date_livraison)."'" : "null"); + $sql .= ", ".$user->id; + $sql .= ", ".self::STATUS_DRAFT; + $sql .= ", ".$this->db->escape($this->source); + $sql .= ", '".$conf->global->COMMANDE_SUPPLIER_ADDON_PDF."'"; + $sql .= ", ".($this->mode_reglement_id > 0 ? $this->mode_reglement_id : 'null'); + $sql .= ", ".($this->cond_reglement_id > 0 ? $this->cond_reglement_id : 'null'); + $sql .= ", ".($this->fk_account > 0 ? $this->fk_account : 'NULL'); + $sql .= ", ".(int) $this->fk_incoterms; + $sql .= ", '".$this->db->escape($this->location_incoterms)."'"; + $sql .= ", ".(int) $this->fk_multicurrency; + $sql .= ", '".$this->db->escape($this->multicurrency_code)."'"; + $sql .= ", ".(double) $this->multicurrency_tx; + $sql .= ")"; dol_syslog(get_class($this)."::create", LOG_DEBUG); if ($this->db->query($sql)) @@ -1268,10 +1268,10 @@ class CommandeFournisseur extends CommonOrder $this->id = $this->db->last_insert_id(MAIN_DB_PREFIX."commande_fournisseur"); if ($this->id) { - $num=count($this->lines); + $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() @@ -1285,7 +1285,7 @@ class CommandeFournisseur extends CommonOrder $this->lines[$i]->localtax2_tx, $this->lines[$i]->fk_product, 0, - $this->lines[$i]->ref_fourn, // $this->lines[$i]->ref_fourn comes from field ref into table of lines. Value may ba a ref that does not exists anymore, so we first try with value of product + $this->lines[$i]->ref_fourn, // $this->lines[$i]->ref_fourn comes from field ref into table of lines. Value may ba a ref that does not exists anymore, so we first try with value of product $this->lines[$i]->remise_percent, 'HT', 0, @@ -1299,39 +1299,39 @@ class CommandeFournisseur extends CommonOrder ); 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 + 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; } } $sql = "UPDATE ".MAIN_DB_PREFIX."commande_fournisseur"; - $sql.= " SET ref='(PROV".$this->id.")'"; - $sql.= " WHERE rowid=".$this->id; + $sql .= " SET ref='(PROV".$this->id.")'"; + $sql .= " WHERE rowid=".$this->id; dol_syslog(get_class($this)."::create", LOG_DEBUG); if ($this->db->query($sql)) { // Add link with price request and supplier order if ($this->id) { - $this->ref="(PROV".$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 + $this->linked_objects = $this->linkedObjectsIds; // TODO Replace linked_objects with linkedObjectsIds } // Add object linked - if (! $error && $this->id && is_array($this->linked_objects) && ! empty($this->linked_objects)) + if (!$error && $this->id && is_array($this->linked_objects) && !empty($this->linked_objects)) { - foreach($this->linked_objects as $origin => $tmp_origin_id) + 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) + 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++; @@ -1342,7 +1342,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++; @@ -1352,16 +1352,16 @@ class CommandeFournisseur extends CommonOrder } } - if (! $error) + if (!$error) { - $result=$this->insertExtraFields(); + $result = $this->insertExtraFields(); if ($result < 0) $error++; } - if (! $error && ! $notrigger) + if (!$error && !$notrigger) { // Call trigger - $result=$this->call_trigger('ORDER_SUPPLIER_CREATE', $user); + $result = $this->call_trigger('ORDER_SUPPLIER_CREATE', $user); if ($result < 0) { $this->db->rollback(); @@ -1375,7 +1375,7 @@ class CommandeFournisseur extends CommonOrder } else { - $this->error=$this->db->lasterror(); + $this->error = $this->db->lasterror(); $this->db->rollback(); return -2; } @@ -1383,7 +1383,7 @@ class CommandeFournisseur extends CommonOrder } else { - $this->error=$this->db->lasterror(); + $this->error = $this->db->lasterror(); $this->db->rollback(); return -1; } @@ -1444,17 +1444,17 @@ class CommandeFournisseur extends CommonOrder // Create clone $this->context['createfromclone'] = 'createfromclone'; - $result=$this->create($user); + $result = $this->create($user); if ($result < 0) $error++; - if (! $error) + if (!$error) { // Hook of thirdparty module if (is_object($hookmanager)) { - $parameters=array('objFrom'=>$objFrom); - $action=''; - $reshook=$hookmanager->executeHooks('createFrom', $parameters, $this, $action); // Note that $action and $object may have been modified by some hooks + $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++; } } @@ -1462,7 +1462,7 @@ class CommandeFournisseur extends CommonOrder unset($this->context['createfromclone']); // End - if (! $error) + if (!$error) { $this->db->commit(); return $this->id; @@ -1503,7 +1503,7 @@ class CommandeFournisseur extends CommonOrder */ public function addline($desc, $pu_ht, $qty, $txtva, $txlocaltax1 = 0.0, $txlocaltax2 = 0.0, $fk_product = 0, $fk_prod_fourn_price = 0, $ref_supplier = '', $remise_percent = 0.0, $price_base_type = 'HT', $pu_ttc = 0.0, $type = 0, $info_bits = 0, $notrigger = false, $date_start = null, $date_end = null, $array_options = 0, $fk_unit = null, $pu_ht_devise = 0, $origin = '', $origin_id = 0) { - global $langs,$mysoc,$conf; + global $langs, $mysoc, $conf; $error = 0; @@ -1515,43 +1515,43 @@ class CommandeFournisseur extends CommonOrder include_once DOL_DOCUMENT_ROOT.'/core/lib/price.lib.php'; // Clean parameters - if (! $qty) $qty=1; - 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 (!$qty) $qty = 1; + 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); - $pu_ht=price2num($pu_ht); - $pu_ht_devise=price2num($pu_ht_devise); - $pu_ttc=price2num($pu_ttc); + $remise_percent = price2num($remise_percent); + $qty = price2num($qty); + $pu_ht = price2num($pu_ht); + $pu_ht_devise = price2num($pu_ht_devise); + $pu_ttc = price2num($pu_ttc); if (!preg_match('/\((.*)\)/', $txtva)) { - $txtva = price2num($txtva); // $txtva can have format '5.0(XXX)' or '5' + $txtva = price2num($txtva); // $txtva can have format '5.0(XXX)' or '5' } $txlocaltax1 = price2num($txlocaltax1); $txlocaltax2 = price2num($txlocaltax2); - if ($price_base_type=='HT') + if ($price_base_type == 'HT') { - $pu=$pu_ht; + $pu = $pu_ht; } else { - $pu=$pu_ttc; + $pu = $pu_ttc; } - $desc=trim($desc); + $desc = trim($desc); // Check parameters - if ($qty < 0 && ! $fk_product) + if ($qty < 0 && !$fk_product) { - $this->error=$langs->trans("ErrorFieldRequired", $langs->transnoentitiesnoconv("Product")); + $this->error = $langs->trans("ErrorFieldRequired", $langs->transnoentitiesnoconv("Product")); return -1; } if ($type < 0) return -1; if ($date_start && $date_end && $date_start > $date_end) { $langs->load("errors"); - $this->error=$langs->trans('ErrorStartDateGreaterEnd'); + $this->error = $langs->trans('ErrorStartDateGreaterEnd'); return -1; } @@ -1560,7 +1560,7 @@ class CommandeFournisseur extends CommonOrder if ($fk_product > 0) { - if (! empty($conf->global->SUPPLIER_ORDER_WITH_PREDEFINED_PRICES_ONLY)) + if (!empty($conf->global->SUPPLIER_ORDER_WITH_PREDEFINED_PRICES_ONLY)) { // Check quantity is enough dol_syslog(get_class($this)."::addline we check supplier prices fk_product=".$fk_product." fk_prod_fourn_price=".$fk_prod_fourn_price." qty=".$qty." ref_supplier=".$ref_supplier); @@ -1572,20 +1572,20 @@ class CommandeFournisseur extends CommonOrder // We use 'none' instead of $ref_supplier, because fourn_ref 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 + $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 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 === '')) { - $pu = $prod->fourn_pu; // Unit price supplier price set by get_buyprice - $ref_supplier = $prod->ref_supplier; // Ref supplier price set by get_buyprice + $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 { $langs->load("errors"); - $this->error = "Ref " . $prod->ref . " " . $langs->trans("ErrorQtyTooLowForThisSupplier"); + $this->error = "Ref ".$prod->ref." ".$langs->trans("ErrorQtyTooLowForThisSupplier"); $this->db->rollback(); dol_syslog(get_class($this)."::addline we did not found supplier price, so we can't guess unit price"); //$pu = $prod->fourn_pu; // We do not overwrite unit price @@ -1595,14 +1595,14 @@ class CommandeFournisseur extends CommonOrder if ($result == -1) { $langs->load("errors"); - $this->error = "Ref " . $prod->ref . " " . $langs->trans("ErrorQtyTooLowForThisSupplier"); + $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) { - $this->error=$prod->error; + $this->error = $prod->error; $this->db->rollback(); dol_syslog(get_class($this)."::addline result=".$result." - ".$this->error, LOG_ERR); return -1; @@ -1610,7 +1610,7 @@ class CommandeFournisseur extends CommonOrder } else { - $this->error=$prod->error; + $this->error = $prod->error; $this->db->rollback(); return -1; } @@ -1625,14 +1625,14 @@ class CommandeFournisseur extends CommonOrder $pu = 0; } - $localtaxes_type=getLocalTaxesFromRate($txtva, 0, $mysoc, $this->thirdparty); + $localtaxes_type = getLocalTaxesFromRate($txtva, 0, $mysoc, $this->thirdparty); // Clean vat code - $vat_src_code=''; + $vat_src_code = ''; if (preg_match('/\((.*)\)/', $txtva, $reg)) { $vat_src_code = $reg[1]; - $txtva = preg_replace('/\s*\(.*\)/', '', $txtva); // Remove code into vatrate. + $txtva = preg_replace('/\s*\(.*\)/', '', $txtva); // Remove code into vatrate. } // Calcul du total TTC et de la TVA pour la ligne a partir de @@ -1650,13 +1650,13 @@ class CommandeFournisseur extends CommonOrder $pu = $pu_ht = $tabprice[3]; // MultiCurrency - $multicurrency_total_ht = $tabprice[16]; + $multicurrency_total_ht = $tabprice[16]; $multicurrency_total_tva = $tabprice[17]; $multicurrency_total_ttc = $tabprice[18]; $pu_ht_devise = $tabprice[19]; - $localtax1_type=$localtaxes_type[0]; - $localtax2_type=$localtaxes_type[2]; + $localtax1_type = $localtaxes_type[0]; + $localtax2_type = $localtaxes_type[2]; $subprice = price2num($pu, 'MU'); @@ -1664,68 +1664,68 @@ class CommandeFournisseur extends CommonOrder $rang = $rangmax + 1; // Insert line - $this->line=new CommandeFournisseurLigne($this->db); + $this->line = new CommandeFournisseurLigne($this->db); $this->line->context = $this->context; - $this->line->fk_commande=$this->id; - $this->line->label=$label; + $this->line->fk_commande = $this->id; + $this->line->label = $label; $this->line->ref_fourn = $ref_supplier; $this->line->ref_supplier = $ref_supplier; - $this->line->desc=$desc; - $this->line->qty=$qty; - $this->line->tva_tx=$txtva; - $this->line->localtax1_tx=($total_localtax1?$localtaxes_type[1]:0); - $this->line->localtax2_tx=($total_localtax2?$localtaxes_type[3]:0); + $this->line->desc = $desc; + $this->line->qty = $qty; + $this->line->tva_tx = $txtva; + $this->line->localtax1_tx = ($total_localtax1 ? $localtaxes_type[1] : 0); + $this->line->localtax2_tx = ($total_localtax2 ? $localtaxes_type[3] : 0); $this->line->localtax1_type = $localtaxes_type[0]; $this->line->localtax2_type = $localtaxes_type[2]; - $this->line->fk_product=$fk_product; - $this->line->product_type=$product_type; - $this->line->remise_percent=$remise_percent; - $this->line->subprice=$pu_ht; - $this->line->rang=$rang; - $this->line->info_bits=$info_bits; + $this->line->fk_product = $fk_product; + $this->line->product_type = $product_type; + $this->line->remise_percent = $remise_percent; + $this->line->subprice = $pu_ht; + $this->line->rang = $rang; + $this->line->info_bits = $info_bits; - $this->line->vat_src_code=$vat_src_code; - $this->line->total_ht=$total_ht; - $this->line->total_tva=$total_tva; - $this->line->total_localtax1=$total_localtax1; - $this->line->total_localtax2=$total_localtax2; - $this->line->total_ttc=$total_ttc; - $this->line->product_type=$type; - $this->line->special_code=$this->special_code; - $this->line->origin=$origin; - $this->line->origin_id=$origin_id; - $this->line->fk_unit=$fk_unit; + $this->line->vat_src_code = $vat_src_code; + $this->line->total_ht = $total_ht; + $this->line->total_tva = $total_tva; + $this->line->total_localtax1 = $total_localtax1; + $this->line->total_localtax2 = $total_localtax2; + $this->line->total_ttc = $total_ttc; + $this->line->product_type = $type; + $this->line->special_code = $this->special_code; + $this->line->origin = $origin; + $this->line->origin_id = $origin_id; + $this->line->fk_unit = $fk_unit; - $this->line->date_start=$date_start; - $this->line->date_end=$date_end; + $this->line->date_start = $date_start; + $this->line->date_end = $date_end; // Multicurrency - $this->line->fk_multicurrency = $this->fk_multicurrency; - $this->line->multicurrency_code = $this->multicurrency_code; + $this->line->fk_multicurrency = $this->fk_multicurrency; + $this->line->multicurrency_code = $this->multicurrency_code; $this->line->multicurrency_subprice = $pu_ht_devise; $this->line->multicurrency_total_ht = $multicurrency_total_ht; $this->line->multicurrency_total_tva = $multicurrency_total_tva; $this->line->multicurrency_total_ttc = $multicurrency_total_ttc; - $this->line->subprice=$pu_ht; - $this->line->price=$this->line->subprice; + $this->line->subprice = $pu_ht; + $this->line->price = $this->line->subprice; - $this->line->remise_percent=$remise_percent; + $this->line->remise_percent = $remise_percent; - if (is_array($array_options) && count($array_options)>0) { - $this->line->array_options=$array_options; + if (is_array($array_options) && count($array_options) > 0) { + $this->line->array_options = $array_options; } - $result=$this->line->insert($notrigger); + $result = $this->line->insert($notrigger); 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. + $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) { $this->db->commit(); @@ -1739,8 +1739,8 @@ class CommandeFournisseur extends CommonOrder } else { - $this->error=$this->line->error; - $this->errors=$this->line->errors; + $this->error = $this->line->error; + $this->errors = $this->line->errors; dol_syslog(get_class($this)."::addline error=".$this->error, LOG_ERR); $this->db->rollback(); return -1; @@ -1770,44 +1770,44 @@ class CommandeFournisseur extends CommonOrder global $conf, $langs; $error = 0; - require_once DOL_DOCUMENT_ROOT .'/product/stock/class/mouvementstock.class.php'; + 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) { - $this->error='ErrorBadValueForParameterWarehouse'; + $this->error = 'ErrorBadValueForParameterWarehouse'; return -1; } if ($qty == 0) { - $this->error='ErrorBadValueForParameterQty'; + $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(); + $now = dol_now(); 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"; - $sql.= " (fk_commande, fk_product, qty, fk_entrepot, fk_user, datec, fk_commandefourndet, status, comment, eatby, sellby, batch) VALUES"; - $sql.= " ('".$this->id."','".$product."','".$qty."',".($entrepot>0?"'".$entrepot."'":"null").",'".$user->id."','".$this->db->idate($now)."','".$fk_commandefourndet."', ".$dispatchstatus.", '".$this->db->escape($comment)."', "; - $sql.= ($eatby?"'".$this->db->idate($eatby)."'":"null").", ".($sellby?"'".$this->db->idate($sellby)."'":"null").", ".($batch?"'".$batch."'":"null"); - $sql.= ")"; + $sql .= " (fk_commande, fk_product, qty, fk_entrepot, fk_user, datec, fk_commandefourndet, status, comment, eatby, sellby, batch) VALUES"; + $sql .= " ('".$this->id."','".$product."','".$qty."',".($entrepot > 0 ? "'".$entrepot."'" : "null").",'".$user->id."','".$this->db->idate($now)."','".$fk_commandefourndet."', ".$dispatchstatus.", '".$this->db->escape($comment)."', "; + $sql .= ($eatby ? "'".$this->db->idate($eatby)."'" : "null").", ".($sellby ? "'".$this->db->idate($sellby)."'" : "null").", ".($batch ? "'".$batch."'" : "null"); + $sql .= ")"; dol_syslog(get_class($this)."::dispatchProduct", LOG_DEBUG); $resql = $this->db->query($sql); if ($resql) { - if (! $notrigger) + if (!$notrigger) { global $conf, $langs, $user; // Call trigger - $result=$this->call_trigger('LINEORDER_SUPPLIER_DISPATCH', $user); + $result = $this->call_trigger('LINEORDER_SUPPLIER_DISPATCH', $user); if ($result < 0) { $error++; @@ -1818,23 +1818,23 @@ class CommandeFournisseur extends CommonOrder } else { - $this->error=$this->db->lasterror(); + $this->error = $this->db->lasterror(); $error++; } // 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) { // $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); + $result = $mouv->reception($user, $product, $entrepot, $qty, $price, $comment, $eatby, $sellby, $batch); if ($result < 0) { - $this->error=$mouv->error; - $this->errors=$mouv->errors; + $this->error = $mouv->error; + $this->errors = $mouv->errors; dol_syslog(get_class($this)."::dispatchProduct ".$this->error." ".join(',', $this->errors), LOG_ERR); $error++; } @@ -1854,7 +1854,7 @@ class CommandeFournisseur extends CommonOrder } else { - $this->error='BadStatusForObject'; + $this->error = 'BadStatusForObject'; return -2; } } @@ -1904,7 +1904,7 @@ class CommandeFournisseur extends CommonOrder */ public function delete(User $user, $notrigger = 0) { - global $langs,$conf; + global $langs, $conf; require_once DOL_DOCUMENT_ROOT.'/core/lib/files.lib.php'; $error = 0; @@ -1914,51 +1914,51 @@ class CommandeFournisseur extends CommonOrder if (empty($notrigger)) { // Call trigger - $result=$this->call_trigger('ORDER_SUPPLIER_DELETE', $user); + $result = $this->call_trigger('ORDER_SUPPLIER_DELETE', $user); if ($result < 0) { - $this->errors[]='ErrorWhenRunningTrigger'; + $this->errors[] = 'ErrorWhenRunningTrigger'; dol_syslog(get_class($this)."::delete ".$this->error, LOG_ERR); return -1; } // End call triggers } - $sql = "DELETE FROM ".MAIN_DB_PREFIX."commande_fournisseurdet WHERE fk_commande =". $this->id ; + $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(); + $this->error = $this->db->lasterror(); + $this->errors[] = $this->db->lasterror(); $error++; } $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 ($resql = $this->db->query($sql)) { if ($this->db->affected_rows($resql) < 1) { - $this->error=$this->db->lasterror(); - $this->errors[]=$this->db->lasterror(); + $this->error = $this->db->lasterror(); + $this->errors[] = $this->db->lasterror(); $error++; } } else { - $this->error=$this->db->lasterror(); - $this->errors[]=$this->db->lasterror(); + $this->error = $this->db->lasterror(); + $this->errors[] = $this->db->lasterror(); $error++; } // Remove extrafields - if ((! $error) && (empty($conf->global->MAIN_EXTRAFIELDS_DISABLED))) // For avoid conflicts if trigger used + if ((!$error) && (empty($conf->global->MAIN_EXTRAFIELDS_DISABLED))) // For avoid conflicts if trigger used { - $result=$this->deleteExtraFields(); + $result = $this->deleteExtraFields(); if ($result < 0) { - $this->error='FailToDeleteExtraFields'; - $this->errors[]='FailToDeleteExtraFields'; + $this->error = 'FailToDeleteExtraFields'; + $this->errors[] = 'FailToDeleteExtraFields'; $error++; dol_syslog(get_class($this)."::delete error -4 ".$this->error, LOG_ERR); } @@ -1967,42 +1967,42 @@ class CommandeFournisseur extends CommonOrder // Delete linked object $res = $this->deleteObjectLinked(); if ($res < 0) { - $this->error='FailToDeleteObjectLinked'; - $this->errors[]='FailToDeleteObjectLinked'; + $this->error = 'FailToDeleteObjectLinked'; + $this->errors[] = 'FailToDeleteObjectLinked'; $error++; } - if (! $error) + if (!$error) { // We remove directory $ref = dol_sanitizeFileName($this->ref); if ($conf->fournisseur->commande->dir_output) { - $dir = $conf->fournisseur->commande->dir_output . "/" . $ref ; - $file = $dir . "/" . $ref . ".pdf"; + $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 (!dol_delete_file($file, 0, 0, 0, $this)) // For triggers { - $this->error='ErrorFailToDeleteFile'; - $this->errors[]='ErrorFailToDeleteFile'; + $this->error = 'ErrorFailToDeleteFile'; + $this->errors[] = 'ErrorFailToDeleteFile'; $error++; } } if (file_exists($dir)) { - $res=@dol_delete_dir_recursive($dir); - if (! $res) + $res = @dol_delete_dir_recursive($dir); + if (!$res) { - $this->error='ErrorFailToDeleteDir'; - $this->errors[]='ErrorFailToDeleteDir'; + $this->error = 'ErrorFailToDeleteDir'; + $this->errors[] = 'ErrorFailToDeleteDir'; $error++; } } } } - if (! $error) + if (!$error) { dol_syslog(get_class($this)."::delete $this->id by $user->id", LOG_DEBUG); $this->db->commit(); @@ -2026,10 +2026,10 @@ class CommandeFournisseur extends CommonOrder { // phpcs:enable $sql = "SELECT rowid, libelle"; - $sql.= " FROM ".MAIN_DB_PREFIX."c_input_method"; - $sql.= " WHERE active = 1"; + $sql .= " FROM ".MAIN_DB_PREFIX."c_input_method"; + $sql .= " WHERE active = 1"; - $resql=$this->db->query($sql); + $resql = $this->db->query($sql); if ($resql) { $i = 0; @@ -2065,15 +2065,15 @@ class CommandeFournisseur extends CommonOrder // List of already dispatched lines $sql = "SELECT p.ref, p.label,"; - $sql.= " e.rowid as warehouse_id, e.ref as entrepot,"; - $sql.= " cfd.rowid as dispatchedlineid, cfd.fk_product, cfd.qty, cfd.eatby, cfd.sellby, cfd.batch, cfd.comment, cfd.status"; - $sql.= " FROM ".MAIN_DB_PREFIX."product as p,"; - $sql.= " ".MAIN_DB_PREFIX."commande_fournisseur_dispatch as cfd"; - $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; - $sql.= " ORDER BY cfd.rowid ASC"; + $sql .= " e.rowid as warehouse_id, e.ref as entrepot,"; + $sql .= " cfd.rowid as dispatchedlineid, cfd.fk_product, cfd.qty, cfd.eatby, cfd.sellby, cfd.batch, cfd.comment, cfd.status"; + $sql .= " FROM ".MAIN_DB_PREFIX."product as p,"; + $sql .= " ".MAIN_DB_PREFIX."commande_fournisseur_dispatch as cfd"; + $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; + $sql .= " ORDER BY cfd.rowid ASC"; $resql = $this->db->query($sql); if ($resql) @@ -2137,28 +2137,28 @@ class CommandeFournisseur extends CommonOrder } // 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); + $dispatchedlinearray = $this->getDispachedLines(0); if (count($dispatchedlinearray) > 0) { - $result=-1; + $result = -1; $error++; - $this->errors[]='ErrorCantSetReceptionToTotalDoneWithReceptionToApprove'; + $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); + $dispatcheddenied = $this->getDispachedLines(2); if (count($dispatchedlinearray) > 0) { - $result=-1; + $result = -1; $error++; - $this->errors[]='ErrorCantSetReceptionToTotalDoneWithReceptionDenied'; + $this->errors[] = 'ErrorCantSetReceptionToTotalDoneWithReceptionDenied'; dol_syslog('ErrorCantSetReceptionToTotalDoneWithReceptionDenied', LOG_DEBUG); } } @@ -2167,17 +2167,17 @@ class CommandeFournisseur extends CommonOrder // TODO LDR01 Add a control test to accept only if ALL predefined products are received (same qty). - if (! $error) + if (!$error) { $this->db->begin(); $sql = "UPDATE ".MAIN_DB_PREFIX."commande_fournisseur"; - $sql.= " SET fk_statut = ".$statut; - $sql.= " WHERE rowid = ".$this->id; - $sql.= " AND fk_statut IN (".self::STATUS_ORDERSENT.",".self::STATUS_RECEIVED_PARTIALLY.")"; // Process running or Partially received + $sql .= " SET fk_statut = ".$statut; + $sql .= " WHERE rowid = ".$this->id; + $sql .= " AND fk_statut IN (".self::STATUS_ORDERSENT.",".self::STATUS_RECEIVED_PARTIALLY.")"; // Process running or Partially received dol_syslog(get_class($this)."::Livraison", LOG_DEBUG); - $resql=$this->db->query($sql); + $resql = $this->db->query($sql); if ($resql) { $result = 0; @@ -2186,11 +2186,11 @@ class CommandeFournisseur extends CommonOrder $this->actionmsg2 = $comment; // Call trigger - $result=$this->call_trigger('ORDER_SUPPLIER_RECEIVE', $user); + $result = $this->call_trigger('ORDER_SUPPLIER_RECEIVE', $user); if ($result < 0) $error++; // End call triggers - if (! $error) + if (!$error) { $this->db->commit(); } @@ -2198,14 +2198,14 @@ class CommandeFournisseur extends CommonOrder { $this->statut = $old_statut; $this->db->rollback(); - $this->error=$this->db->lasterror(); + $this->error = $this->db->lasterror(); $result = -1; } } else { $this->db->rollback(); - $this->error=$this->db->lasterror(); + $this->error = $this->db->lasterror(); $result = -1; } } @@ -2217,7 +2217,7 @@ class CommandeFournisseur extends CommonOrder dol_syslog(get_class($this)."::Livraison Not Authorized"); $result = -3; } - return $result ; + return $result; } // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps @@ -2234,50 +2234,50 @@ class CommandeFournisseur extends CommonOrder // phpcs:enable if ($user->rights->fournisseur->commande->creer) { - $error=0; + $error = 0; $this->db->begin(); $sql = "UPDATE ".MAIN_DB_PREFIX."commande_fournisseur"; - $sql.= " SET date_livraison = ".($date_livraison ? "'".$this->db->idate($date_livraison)."'" : 'null'); - $sql.= " WHERE rowid = ".$this->id; + $sql .= " SET date_livraison = ".($date_livraison ? "'".$this->db->idate($date_livraison)."'" : 'null'); + $sql .= " WHERE rowid = ".$this->id; dol_syslog(__METHOD__, LOG_DEBUG); - $resql=$this->db->query($sql); + $resql = $this->db->query($sql); if (!$resql) { - $this->errors[]=$this->db->error(); + $this->errors[] = $this->db->error(); $error++; } - if (! $error) + if (!$error) { - $this->oldcopy= clone $this; + $this->oldcopy = clone $this; $this->date_livraison = $date_livraison; } - if (! $notrigger && empty($error)) + if (!$notrigger && empty($error)) { // Call trigger - $result=$this->call_trigger('ORDER_SUPPLIER_MODIFY', $user); + $result = $this->call_trigger('ORDER_SUPPLIER_MODIFY', $user); 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); + $this->error .= ($this->error ? ', '.$errmsg : $errmsg); } $this->db->rollback(); - return -1*$error; + return -1 * $error; } } else @@ -2300,51 +2300,51 @@ class CommandeFournisseur extends CommonOrder // phpcs:enable if ($user->rights->fournisseur->commande->creer) { - $error=0; + $error = 0; $this->db->begin(); $sql = "UPDATE ".MAIN_DB_PREFIX."commande_fournisseur"; - $sql.= " SET fk_projet = ".($id_projet > 0 ? (int) $id_projet : 'null'); - $sql.= " WHERE rowid = ".$this->id; + $sql .= " SET fk_projet = ".($id_projet > 0 ? (int) $id_projet : 'null'); + $sql .= " WHERE rowid = ".$this->id; dol_syslog(__METHOD__, LOG_DEBUG); - $resql=$this->db->query($sql); + $resql = $this->db->query($sql); if (!$resql) { - $this->errors[]=$this->db->error(); + $this->errors[] = $this->db->error(); $error++; } - if (! $error) + if (!$error) { - $this->oldcopy= clone $this; + $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); + $result = $this->call_trigger('ORDER_SUPPLIER_MODIFY', $user); 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); + $this->error .= ($this->error ? ', '.$errmsg : $errmsg); } $this->db->rollback(); - return -1*$error; + return -1 * $error; } } else @@ -2370,7 +2370,7 @@ class CommandeFournisseur extends CommonOrder $this->lines = array(); - $num=count($comclient->lines); + $num = count($comclient->lines); for ($i = 0; $i < $num; $i++) { $prod = new Product($this->db); @@ -2406,14 +2406,14 @@ class CommandeFournisseur extends CommonOrder */ public function setStatus($user, $status) { - global $conf,$langs; - $error=0; + global $conf, $langs; + $error = 0; $this->db->begin(); $sql = 'UPDATE '.MAIN_DB_PREFIX.'commande_fournisseur'; - $sql.= ' SET fk_statut='.$status; - $sql.= ' WHERE rowid = '.$this->id; + $sql .= ' SET fk_statut='.$status; + $sql .= ' WHERE rowid = '.$this->id; dol_syslog(get_class($this)."::setStatus", LOG_DEBUG); $resql = $this->db->query($sql); @@ -2423,7 +2423,7 @@ class CommandeFournisseur extends CommonOrder $trigger_name[0] = 'DRAFT'; $trigger_name[1] = 'VALIDATED'; $trigger_name[2] = 'APPROVED'; - $trigger_name[3] = 'ORDERED'; // Ordered + $trigger_name[3] = 'ORDERED'; // Ordered $trigger_name[4] = 'RECEIVED_PARTIALLY'; $trigger_name[5] = 'RECEIVED_COMPLETELY'; $trigger_name[6] = 'CANCELED'; @@ -2431,18 +2431,18 @@ class CommandeFournisseur extends CommonOrder $trigger_name[9] = 'REFUSED'; // Call trigger - $result=$this->call_trigger("ORDER_SUPPLIER_STATUS_".$trigger_name[$status], $user); + $result = $this->call_trigger("ORDER_SUPPLIER_STATUS_".$trigger_name[$status], $user); if ($result < 0) { $error++; } // End call triggers } else { $error++; - $this->error=$this->db->lasterror(); + $this->error = $this->db->lasterror(); dol_syslog(get_class($this)."::setStatus ".$this->error); } - if (! $error) + if (!$error) { $this->statut = $status; $this->db->commit(); @@ -2489,28 +2489,28 @@ class CommandeFournisseur extends CommonOrder 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; + $remise_percent = price2num($remise_percent); + $qty = price2num($qty); + if (!$qty) $qty = 1; $pu = price2num($pu); - $pu_ht_devise=price2num($pu_ht_devise); - $txtva=price2num($txtva); - $txlocaltax1=price2num($txlocaltax1); - $txlocaltax2=price2num($txlocaltax2); + $pu_ht_devise = price2num($pu_ht_devise); + $txtva = price2num($txtva); + $txlocaltax1 = price2num($txlocaltax1); + $txlocaltax2 = price2num($txlocaltax2); // Check parameters if ($type < 0) return -1; if ($date_start && $date_end && $date_start > $date_end) { $langs->load("errors"); - $this->error=$langs->trans('ErrorStartDateGreaterEnd'); + $this->error = $langs->trans('ErrorStartDateGreaterEnd'); return -1; } @@ -2521,17 +2521,17 @@ class CommandeFournisseur extends CommonOrder // TRES IMPORTANT: C'est au moment de l'insertion ligne qu'on doit stocker // la part ht, tva et ttc, et ce au niveau de la ligne qui a son propre taux tva. - $localtaxes_type=getLocalTaxesFromRate($txtva, 0, $mysoc, $this->thirdparty); + $localtaxes_type = getLocalTaxesFromRate($txtva, 0, $mysoc, $this->thirdparty); // Clean vat code - $vat_src_code=''; + $vat_src_code = ''; if (preg_match('/\((.*)\)/', $txtva, $reg)) { $vat_src_code = $reg[1]; - $txtva = preg_replace('/\s*\(.*\)/', '', $txtva); // Remove code into vatrate. + $txtva = preg_replace('/\s*\(.*\)/', '', $txtva); // Remove code into vatrate. } - $tabprice=calcul_price_total($qty, $pu, $remise_percent, $txtva, $txlocaltax1, $txlocaltax2, 0, $price_base_type, $info_bits, $type, $this->thirdparty, $localtaxes_type, 100, $this->multicurrency_tx, $pu_ht_devise); + $tabprice = calcul_price_total($qty, $pu, $remise_percent, $txtva, $txlocaltax1, $txlocaltax2, 0, $price_base_type, $info_bits, $type, $this->thirdparty, $localtaxes_type, 100, $this->multicurrency_tx, $pu_ht_devise); $total_ht = $tabprice[0]; $total_tva = $tabprice[1]; $total_ttc = $tabprice[2]; @@ -2542,31 +2542,31 @@ class CommandeFournisseur extends CommonOrder $pu_ttc = $tabprice[5]; // MultiCurrency - $multicurrency_total_ht = $tabprice[16]; + $multicurrency_total_ht = $tabprice[16]; $multicurrency_total_tva = $tabprice[17]; $multicurrency_total_ttc = $tabprice[18]; $pu_ht_devise = $tabprice[19]; - $localtax1_type=$localtaxes_type[0]; - $localtax2_type=$localtaxes_type[2]; + $localtax1_type = $localtaxes_type[0]; + $localtax2_type = $localtaxes_type[2]; $subprice = price2num($pu_ht, 'MU'); //Fetch current line from the database and then clone the object and set it in $oldline property - $this->line=new CommandeFournisseurLigne($this->db); + $this->line = new CommandeFournisseurLigne($this->db); $this->line->fetch($rowid); $oldline = clone $this->line; $this->line->oldline = $oldline; $this->line->context = $this->context; - $this->line->fk_commande=$this->id; + $this->line->fk_commande = $this->id; //$this->line->label=$label; - $this->line->desc=$desc; - $this->line->qty=$qty; - $this->line->ref_supplier=$ref_supplier; + $this->line->desc = $desc; + $this->line->qty = $qty; + $this->line->ref_supplier = $ref_supplier; - $this->line->vat_src_code = $vat_src_code; + $this->line->vat_src_code = $vat_src_code; $this->line->tva_tx = $txtva; $this->line->localtax1_tx = $txlocaltax1; $this->line->localtax2_tx = $txlocaltax2; @@ -2578,8 +2578,8 @@ class CommandeFournisseur extends CommonOrder $this->line->info_bits = $info_bits; $this->line->total_ht = $total_ht; $this->line->total_tva = $total_tva; - $this->line->total_localtax1= $total_localtax1; - $this->line->total_localtax2= $total_localtax2; + $this->line->total_localtax1 = $total_localtax1; + $this->line->total_localtax2 = $total_localtax2; $this->line->total_ttc = $total_ttc; $this->line->product_type = $type; $this->line->special_code = $this->special_code; @@ -2590,23 +2590,23 @@ class CommandeFournisseur extends CommonOrder $this->line->date_end = $date_end; // Multicurrency - $this->line->fk_multicurrency = $this->fk_multicurrency; - $this->line->multicurrency_code = $this->multicurrency_code; + $this->line->fk_multicurrency = $this->fk_multicurrency; + $this->line->multicurrency_code = $this->multicurrency_code; $this->line->multicurrency_subprice = $pu_ht_devise; $this->line->multicurrency_total_ht = $multicurrency_total_ht; $this->line->multicurrency_total_tva = $multicurrency_total_tva; $this->line->multicurrency_total_ttc = $multicurrency_total_ttc; - $this->line->subprice=$pu_ht; - $this->line->price=$this->line->subprice; + $this->line->subprice = $pu_ht; + $this->line->price = $this->line->subprice; - $this->line->remise_percent=$remise_percent; + $this->line->remise_percent = $remise_percent; - if (is_array($array_options) && count($array_options)>0) { - $this->line->array_options=$array_options; + if (is_array($array_options) && count($array_options) > 0) { + $this->line->array_options = $array_options; } - $result=$this->line->update($notrigger); + $result = $this->line->update($notrigger); // Mise a jour info denormalisees au niveau facture @@ -2618,14 +2618,14 @@ class CommandeFournisseur extends CommonOrder } else { - $this->error=$this->db->lasterror(); + $this->error = $this->db->lasterror(); $this->db->rollback(); return -1; } } else { - $this->error="Order status makes operation forbidden"; + $this->error = "Order status makes operation forbidden"; dol_syslog(get_class($this)."::updateline ".$this->error, LOG_ERR); return -2; } @@ -2641,22 +2641,22 @@ class CommandeFournisseur extends CommonOrder */ public function initAsSpecimen() { - global $user,$langs,$conf; + global $user, $langs, $conf; include_once DOL_DOCUMENT_ROOT.'/fourn/class/fournisseur.product.class.php'; dol_syslog(get_class($this)."::initAsSpecimen"); - $now=dol_now(); + $now = dol_now(); // Find first product - $prodid=0; - $product=new ProductFournisseur($this->db); + $prodid = 0; + $product = new ProductFournisseur($this->db); $sql = "SELECT rowid"; - $sql.= " FROM ".MAIN_DB_PREFIX."product"; - $sql.= " WHERE entity IN (".getEntity('product').")"; - $sql.=$this->db->order("rowid", "ASC"); - $sql.=$this->db->plimit(1); + $sql .= " FROM ".MAIN_DB_PREFIX."product"; + $sql .= " WHERE entity IN (".getEntity('product').")"; + $sql .= $this->db->order("rowid", "ASC"); + $sql .= $this->db->plimit(1); $resql = $this->db->query($sql); if ($resql) { @@ -2665,49 +2665,49 @@ class CommandeFournisseur extends CommonOrder } // Initialise parametres - $this->id=0; + $this->id = 0; $this->ref = 'SPECIMEN'; - $this->specimen=1; + $this->specimen = 1; $this->socid = 1; $this->date = $now; $this->date_commande = $now; - $this->date_lim_reglement=$this->date+3600*24*30; + $this->date_lim_reglement = $this->date + 3600 * 24 * 30; $this->cond_reglement_code = 'RECEP'; $this->mode_reglement_code = 'CHQ'; - $this->note_public='This is a comment (public)'; - $this->note_private='This is a comment (private)'; - $this->statut=0; + $this->note_public = 'This is a comment (public)'; + $this->note_private = 'This is a comment (private)'; + $this->statut = 0; // Lines $nbp = 5; $xnbp = 0; while ($xnbp < $nbp) { - $line=new CommandeFournisseurLigne($this->db); - $line->desc=$langs->trans("Description")." ".$xnbp; - $line->qty=1; - $line->subprice=100; - $line->price=100; - $line->tva_tx=19.6; - $line->localtax1_tx=0; - $line->localtax2_tx=0; + $line = new CommandeFournisseurLigne($this->db); + $line->desc = $langs->trans("Description")." ".$xnbp; + $line->qty = 1; + $line->subprice = 100; + $line->price = 100; + $line->tva_tx = 19.6; + $line->localtax1_tx = 0; + $line->localtax2_tx = 0; if ($xnbp == 2) { - $line->total_ht=50; - $line->total_ttc=59.8; - $line->total_tva=9.8; - $line->remise_percent=50; + $line->total_ht = 50; + $line->total_ttc = 59.8; + $line->total_tva = 9.8; + $line->remise_percent = 50; } else { - $line->total_ht=100; - $line->total_ttc=119.6; - $line->total_tva=19.6; - $line->remise_percent=00; + $line->total_ht = 100; + $line->total_ttc = 119.6; + $line->total_tva = 19.6; + $line->remise_percent = 00; } - $line->fk_product=$prodid; + $line->fk_product = $prodid; - $this->lines[$xnbp]=$line; + $this->lines[$xnbp] = $line; $this->total_ht += $line->total_ht; $this->total_tva += $line->total_tva; @@ -2726,11 +2726,11 @@ class CommandeFournisseur extends CommonOrder public function info($id) { $sql = 'SELECT c.rowid, date_creation as datec, tms as datem, date_valid as date_validation, date_approve as datea, date_approve2 as datea2,'; - $sql.= ' fk_user_author, fk_user_modif, fk_user_valid, fk_user_approve, fk_user_approve2'; - $sql.= ' FROM '.MAIN_DB_PREFIX.'commande_fournisseur as c'; - $sql.= ' WHERE c.rowid = '.$id; + $sql .= ' fk_user_author, fk_user_modif, fk_user_valid, fk_user_approve, fk_user_approve2'; + $sql .= ' FROM '.MAIN_DB_PREFIX.'commande_fournisseur as c'; + $sql .= ' WHERE c.rowid = '.$id; - $result=$this->db->query($sql); + $result = $this->db->query($sql); if ($result) { if ($this->db->num_rows($result)) @@ -2739,7 +2739,7 @@ class CommandeFournisseur extends CommonOrder $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_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; @@ -2795,7 +2795,7 @@ class CommandeFournisseur extends CommonOrder else { dol_print_error($this->db); - $this->error=$this->db->error(); + $this->error = $this->db->error(); return -1; } } @@ -2867,7 +2867,7 @@ class CommandeFournisseur extends CommonOrder } else { - $this->error=$this->db->error(); + $this->error = $this->db->error(); return -1; } } @@ -2885,8 +2885,8 @@ class CommandeFournisseur extends CommonOrder 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 = ".$db->escape($this->methode_commande_id); + $sql .= " FROM ".MAIN_DB_PREFIX.'c_input_method'; + $sql .= " WHERE active=1 AND rowid = ".$db->escape($this->methode_commande_id); $resql = $db->query($sql); if ($resql) @@ -3009,7 +3009,7 @@ class CommandeFournisseur extends CommonOrder { global $conf; - if (empty($this->date_delivery) && ! empty($this->date_livraison)) $this->date_delivery = $this->date_livraison; // For backward compatibility + if (empty($this->date_delivery) && !empty($this->date_livraison)) $this->date_delivery = $this->date_livraison; // For backward compatibility $now = dol_now(); $date_to_test = empty($this->date_delivery) ? $this->date_commande : $this->date_delivery; @@ -3026,11 +3026,11 @@ class CommandeFournisseur extends CommonOrder { global $conf, $langs; - if (empty($this->date_delivery) && ! empty($this->date_livraison)) $this->date_delivery = $this->date_livraison; // For backward compatibility + if (empty($this->date_delivery) && !empty($this->date_livraison)) $this->date_delivery = $this->date_livraison; // For backward compatibility - if (empty($this->date_delivery)) $text=$langs->trans("OrderDate").' '.dol_print_date($this->date_commande, 'day'); - else $text=$text=$langs->trans("DeliveryDate").' '.dol_print_date($this->date_delivery, 'day'); - $text.=' '.($conf->commande->fournisseur->warning_delay>0?'+':'-').' '.round(abs($conf->commande->fournisseur->warning_delay)/3600/24, 1).' '.$langs->trans("days").' < '.$langs->trans("Today"); + if (empty($this->date_delivery)) $text = $langs->trans("OrderDate").' '.dol_print_date($this->date_commande, 'day'); + else $text = $text = $langs->trans("DeliveryDate").' '.dol_print_date($this->date_delivery, 'day'); + $text .= ' '.($conf->commande->fournisseur->warning_delay > 0 ? '+' : '-').' '.round(abs($conf->commande->fournisseur->warning_delay) / 3600 / 24, 1).' '.$langs->trans("days").' < '.$langs->trans("Today"); return $text; } @@ -3048,42 +3048,42 @@ class CommandeFournisseur extends CommonOrder { global $conf, $langs; - if (! empty($conf->fournisseur->enabled)) + if (!empty($conf->fournisseur->enabled)) { require_once DOL_DOCUMENT_ROOT.'/fourn/class/fournisseur.commande.dispatch.class.php'; - $qtydelivered=array(); - $qtywished=array(); + $qtydelivered = array(); + $qtywished = array(); $supplierorderdispatch = new CommandeFournisseurDispatch($this->db); - $filter=array('t.fk_commande'=>$this->id); - if (! empty($conf->global->SUPPLIER_ORDER_USE_DISPATCH_STATUS)) { - $filter['t.status']=1; // Restrict to lines with status validated + $filter = array('t.fk_commande'=>$this->id); + if (!empty($conf->global->SUPPLIER_ORDER_USE_DISPATCH_STATUS)) { + $filter['t.status'] = 1; // Restrict to lines with status validated } - $ret=$supplierorderdispatch->fetchAll('', '', 0, 0, $filter); - if ($ret<0) + $ret = $supplierorderdispatch->fetchAll('', '', 0, 0, $filter); + if ($ret < 0) { - $this->error=$supplierorderdispatch->error; $this->errors=$supplierorderdispatch->errors; + $this->error = $supplierorderdispatch->error; $this->errors = $supplierorderdispatch->errors; return $ret; } else { - if (is_array($supplierorderdispatch->lines) && count($supplierorderdispatch->lines)>0) + if (is_array($supplierorderdispatch->lines) && count($supplierorderdispatch->lines) > 0) { $date_liv = dol_now(); // Build array with quantity deliverd by product - foreach($supplierorderdispatch->lines as $line) { - $qtydelivered[$line->fk_product]+=$line->qty; + foreach ($supplierorderdispatch->lines as $line) { + $qtydelivered[$line->fk_product] += $line->qty; } - foreach($this->lines as $line) { - $qtywished[$line->fk_product]+=$line->qty; + foreach ($this->lines as $line) { + $qtywished[$line->fk_product] += $line->qty; } //Compare array - $diff_array=array_diff_assoc($qtydelivered, $qtywished); // Warning: $diff_array is done only on common keys. - $keysinwishednotindelivered=array_diff(array_keys($qtywished), array_keys($qtydelivered)); // To check we also have same number of keys - $keysindeliverednotinwished=array_diff(array_keys($qtydelivered), array_keys($qtywished)); // To check we also have same number of keys + $diff_array = array_diff_assoc($qtydelivered, $qtywished); // Warning: $diff_array is done only on common keys. + $keysinwishednotindelivered = array_diff(array_keys($qtywished), array_keys($qtydelivered)); // To check we also have same number of keys + $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); @@ -3091,13 +3091,13 @@ class CommandeFournisseur extends CommonOrder var_dump($keysindeliverednotinwished); exit;*/ - if (count($diff_array)==0 && count($keysinwishednotindelivered)==0 && count($keysindeliverednotinwished)==0) //No diff => mean everythings is received + 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) { + $ret = $this->Livraison($user, $date_liv, 'tot', $comment); // GETPOST("type") is 'tot', 'par', 'nev', 'can' + if ($ret < 0) { return -1; } return 5; @@ -3106,26 +3106,26 @@ class CommandeFournisseur extends CommonOrder { //Diff => received partially //$ret=$this->setStatus($user,4); - $ret = $this->Livraison($user, $date_liv, 'par', $comment); // GETPOST("type") is 'tot', 'par', 'nev', 'can' - if ($ret<0) { + $ret = $this->Livraison($user, $date_liv, 'par', $comment); // GETPOST("type") is 'tot', 'par', 'nev', 'can' + if ($ret < 0) { return -1; } return 4; } - } elseif (! empty($conf->global->SUPPLIER_ORDER_MORE_THAN_WISHED) ) { + } elseif (!empty($conf->global->SUPPLIER_ORDER_MORE_THAN_WISHED)) { //set livraison to 'tot' if more products received than wished. (and if $closeopenorder is set to 1 of course...) - $close=0; + $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++; } @@ -3133,11 +3133,11 @@ class CommandeFournisseur extends CommonOrder } - if($close == count($diff_array)) { + if ($close == count($diff_array)) { //all the products are received equal or more than the wished quantity if ($closeopenorder) { - $ret = $this->Livraison($user, $date_liv, 'tot', $comment); // GETPOST("type") is 'tot', 'par', 'nev', 'can' - if ($ret<0) { + $ret = $this->Livraison($user, $date_liv, 'tot', $comment); // GETPOST("type") is 'tot', 'par', 'nev', 'can' + if ($ret < 0) { return -1; } return 5; @@ -3145,8 +3145,8 @@ class CommandeFournisseur extends CommonOrder else { //Diff => received partially - $ret = $this->Livraison($user, $date_liv, 'par', $comment); // GETPOST("type") is 'tot', 'par', 'nev', 'can' - if ($ret<0) { + $ret = $this->Livraison($user, $date_liv, 'par', $comment); // GETPOST("type") is 'tot', 'par', 'nev', 'can' + if ($ret < 0) { return -1; } return 4; @@ -3155,8 +3155,8 @@ class CommandeFournisseur extends CommonOrder else { //all the products are not received - $ret = $this->Livraison($user, $date_liv, 'par', $comment); // GETPOST("type") is 'tot', 'par', 'nev', 'can' - if ($ret<0) { + $ret = $this->Livraison($user, $date_liv, 'par', $comment); // GETPOST("type") is 'tot', 'par', 'nev', 'can' + if ($ret < 0) { return -1; } return 4; @@ -3165,8 +3165,8 @@ class CommandeFournisseur extends CommonOrder else { //Diff => received partially - $ret = $this->Livraison($user, $date_liv, 'par', $comment); // GETPOST("type") is 'tot', 'par', 'nev', 'can' - if ($ret<0) { + $ret = $this->Livraison($user, $date_liv, 'par', $comment); // GETPOST("type") is 'tot', 'par', 'nev', 'can' + if ($ret < 0) { return -1; } return 4; @@ -3190,17 +3190,17 @@ class CommandeFournisseur extends CommonOrder $this->receptions = array(); $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,'; - $sql.= ' '.MAIN_DB_PREFIX.'commande_fournisseurdet as cd'; - $sql.= ' WHERE'; - 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; - $sql.= ' GROUP BY 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,'; + $sql .= ' '.MAIN_DB_PREFIX.'commande_fournisseurdet as cd'; + $sql .= ' WHERE'; + 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; + $sql .= ' GROUP BY cd.rowid, cd.fk_product'; dol_syslog(get_class($this)."::loadReceptions", LOG_DEBUG); @@ -3212,7 +3212,7 @@ class CommandeFournisseur extends CommonOrder 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; + empty($this->receptions[$obj->rowid]) ? $this->receptions[$obj->rowid] = $obj->qty : $this->receptions[$obj->rowid] += $obj->qty; $i++; } $this->db->free(); @@ -3221,7 +3221,7 @@ class CommandeFournisseur extends CommonOrder } else { - $this->error=$this->db->lasterror(); + $this->error = $this->db->lasterror(); return -1; } } @@ -3237,12 +3237,12 @@ class CommandeFournisseurLigne extends CommonOrderLine /** * @var string ID to identify managed object */ - public $element='commande_fournisseurdet'; + public $element = 'commande_fournisseurdet'; /** * @var string Name of table without prefix where object is stored */ - public $table_element='commande_fournisseurdet'; + public $table_element = 'commande_fournisseurdet'; public $oldline; @@ -3298,7 +3298,7 @@ class CommandeFournisseurLigne extends CommonOrderLine */ public function __construct($db) { - $this->db= $db; + $this->db = $db; } /** @@ -3310,16 +3310,16 @@ class CommandeFournisseurLigne extends CommonOrderLine public function fetch($rowid) { $sql = 'SELECT cd.rowid, cd.fk_commande, cd.fk_product, cd.product_type, cd.description, cd.qty, cd.tva_tx, cd.special_code,'; - $sql.= ' cd.localtax1_tx, cd.localtax2_tx, cd.localtax1_type, cd.localtax2_type, cd.ref,'; - $sql.= ' cd.remise, cd.remise_percent, cd.subprice,'; - $sql.= ' cd.info_bits, cd.total_ht, cd.total_tva, cd.total_ttc,'; - $sql.= ' cd.total_localtax1, cd.total_localtax2,'; - $sql.= ' p.ref as product_ref, p.label as product_libelle, 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'; - $sql.= ' FROM '.MAIN_DB_PREFIX.'commande_fournisseurdet as cd'; - $sql.= ' LEFT JOIN '.MAIN_DB_PREFIX.'product as p ON cd.fk_product = p.rowid'; - $sql.= ' WHERE cd.rowid = '.$rowid; + $sql .= ' cd.localtax1_tx, cd.localtax2_tx, cd.localtax1_type, cd.localtax2_type, cd.ref,'; + $sql .= ' cd.remise, cd.remise_percent, cd.subprice,'; + $sql .= ' cd.info_bits, cd.total_ht, cd.total_tva, cd.total_ttc,'; + $sql .= ' cd.total_localtax1, cd.total_localtax2,'; + $sql .= ' p.ref as product_ref, p.label as product_libelle, 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'; + $sql .= ' FROM '.MAIN_DB_PREFIX.'commande_fournisseurdet as cd'; + $sql .= ' LEFT JOIN '.MAIN_DB_PREFIX.'product as p ON cd.fk_product = p.rowid'; + $sql .= ' WHERE cd.rowid = '.$rowid; $result = $this->db->query($sql); if ($result) { @@ -3327,7 +3327,7 @@ class CommandeFournisseurLigne extends CommonOrderLine if (!empty($objp)) { - $this->rowid = $objp->rowid; + $this->rowid = $objp->rowid; $this->id = $objp->rowid; $this->fk_commande = $objp->fk_commande; $this->desc = $objp->description; @@ -3352,14 +3352,14 @@ class CommandeFournisseurLigne extends CommonOrderLine $this->product_type = $objp->product_type; $this->special_code = $objp->special_code; - $this->ref = $objp->product_ref; + $this->ref = $objp->product_ref; $this->product_ref = $objp->product_ref; $this->product_libelle = $objp->product_libelle; $this->product_desc = $objp->product_desc; $this->date_start = $this->db->jdate($objp->date_start); $this->date_end = $this->db->jdate($objp->date_end); - $this->fk_unit = $objp->fk_unit; + $this->fk_unit = $objp->fk_unit; $this->multicurrency_subprice = $objp->multicurrency_subprice; $this->multicurrency_total_ht = $objp->multicurrency_total_ht; @@ -3373,7 +3373,7 @@ class CommandeFournisseurLigne extends CommonOrderLine } else { - $this->error='Supplier order line with id='.$rowid.' not found'; + $this->error = 'Supplier order line with id='.$rowid.' not found'; dol_syslog(get_class($this)."::fetch Error ".$this->error, LOG_ERR); return 0; } @@ -3395,28 +3395,28 @@ class CommandeFournisseurLigne extends CommonOrderLine { global $conf, $user; - $error=0; + $error = 0; 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->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; @@ -3431,62 +3431,62 @@ class CommandeFournisseurLigne extends CommonOrderLine // Insertion dans base de la ligne $sql = 'INSERT INTO '.MAIN_DB_PREFIX.$this->table_element; - $sql.= " (fk_commande, label, description, date_start, date_end,"; - $sql.= " fk_product, product_type, special_code, rang,"; - $sql.= " qty, vat_src_code, tva_tx, localtax1_tx, localtax2_tx, localtax1_type, localtax2_type, remise_percent, subprice, ref,"; - $sql.= " total_ht, total_tva, total_localtax1, total_localtax2, total_ttc, fk_unit,"; - $sql.= " fk_multicurrency, multicurrency_code, multicurrency_subprice, multicurrency_total_ht, multicurrency_total_tva, multicurrency_total_ttc"; - $sql.= ")"; - $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,"; } - $sql.= "'".$this->db->escape($this->product_type)."',"; - $sql.= "'".$this->db->escape($this->special_code)."',"; - $sql.= "'".$this->db->escape($this->rang)."',"; - $sql.= "'".$this->db->escape($this->qty)."', "; - $sql.= " ".(empty($this->vat_src_code)?"''":"'".$this->db->escape($this->vat_src_code)."'").","; - $sql.= " ".$this->tva_tx.", "; - $sql.= " ".$this->localtax1_tx.","; - $sql.= " ".$this->localtax2_tx.","; - $sql.= " '".$this->db->escape($this->localtax1_type)."',"; - $sql.= " '".$this->db->escape($this->localtax2_type)."',"; - $sql.= " ".$this->remise_percent.", ".price2num($this->subprice, 'MU').", '".$this->db->escape($this->ref_supplier)."',"; - $sql.= " ".price2num($this->total_ht).","; - $sql.= " ".price2num($this->total_tva).","; - $sql.= " ".price2num($this->total_localtax1).","; - $sql.= " ".price2num($this->total_localtax2).","; - $sql.= " ".price2num($this->total_ttc).","; - $sql.= ($this->fk_unit ? "'".$this->db->escape($this->fk_unit)."'":"null"); - $sql.= ", ".($this->fk_multicurrency ? $this->fk_multicurrency : "null"); - $sql.= ", '".$this->db->escape($this->multicurrency_code)."'"; - $sql.= ", ".($this->multicurrency_subprice ? price2num($this->multicurrency_subprice) : '0'); - $sql.= ", ".($this->multicurrency_total_ht ? price2num($this->multicurrency_total_ht) : '0'); - $sql.= ", ".($this->multicurrency_total_tva ? price2num($this->multicurrency_total_tva) : '0'); - $sql.= ", ".($this->multicurrency_total_ttc ? price2num($this->multicurrency_total_ttc) : '0'); - $sql.= ")"; + $sql .= " (fk_commande, label, description, date_start, date_end,"; + $sql .= " fk_product, product_type, special_code, rang,"; + $sql .= " qty, vat_src_code, tva_tx, localtax1_tx, localtax2_tx, localtax1_type, localtax2_type, remise_percent, subprice, ref,"; + $sql .= " total_ht, total_tva, total_localtax1, total_localtax2, total_ttc, fk_unit,"; + $sql .= " fk_multicurrency, multicurrency_code, multicurrency_subprice, multicurrency_total_ht, multicurrency_total_tva, multicurrency_total_ttc"; + $sql .= ")"; + $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,"; } + $sql .= "'".$this->db->escape($this->product_type)."',"; + $sql .= "'".$this->db->escape($this->special_code)."',"; + $sql .= "'".$this->db->escape($this->rang)."',"; + $sql .= "'".$this->db->escape($this->qty)."', "; + $sql .= " ".(empty($this->vat_src_code) ? "''" : "'".$this->db->escape($this->vat_src_code)."'").","; + $sql .= " ".$this->tva_tx.", "; + $sql .= " ".$this->localtax1_tx.","; + $sql .= " ".$this->localtax2_tx.","; + $sql .= " '".$this->db->escape($this->localtax1_type)."',"; + $sql .= " '".$this->db->escape($this->localtax2_type)."',"; + $sql .= " ".$this->remise_percent.", ".price2num($this->subprice, 'MU').", '".$this->db->escape($this->ref_supplier)."',"; + $sql .= " ".price2num($this->total_ht).","; + $sql .= " ".price2num($this->total_tva).","; + $sql .= " ".price2num($this->total_localtax1).","; + $sql .= " ".price2num($this->total_localtax2).","; + $sql .= " ".price2num($this->total_ttc).","; + $sql .= ($this->fk_unit ? "'".$this->db->escape($this->fk_unit)."'" : "null"); + $sql .= ", ".($this->fk_multicurrency ? $this->fk_multicurrency : "null"); + $sql .= ", '".$this->db->escape($this->multicurrency_code)."'"; + $sql .= ", ".($this->multicurrency_subprice ? price2num($this->multicurrency_subprice) : '0'); + $sql .= ", ".($this->multicurrency_total_ht ? price2num($this->multicurrency_total_ht) : '0'); + $sql .= ", ".($this->multicurrency_total_tva ? price2num($this->multicurrency_total_tva) : '0'); + $sql .= ", ".($this->multicurrency_total_ttc ? price2num($this->multicurrency_total_ttc) : '0'); + $sql .= ")"; dol_syslog(get_class($this)."::insert", LOG_DEBUG); - $resql=$this->db->query($sql); + $resql = $this->db->query($sql); if ($resql) { - $this->id=$this->db->last_insert_id(MAIN_DB_PREFIX.$this->table_element); - $this->rowid =$this->id; + $this->id = $this->db->last_insert_id(MAIN_DB_PREFIX.$this->table_element); + $this->rowid = $this->id; if (empty($conf->global->MAIN_EXTRAFIELDS_DISABLED)) // For avoid conflicts if trigger used { - $result=$this->insertExtraFields(); + $result = $this->insertExtraFields(); if ($result < 0) { $error++; } } - if (! $error && ! $notrigger) + if (!$error && !$notrigger) { // Call trigger - $result=$this->call_trigger('LINEORDER_SUPPLIER_CREATE', $user); + $result = $this->call_trigger('LINEORDER_SUPPLIER_CREATE', $user); if ($result < 0) $error++; // End call triggers } @@ -3496,17 +3496,17 @@ 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); + $this->errors[] = ($this->errors ? ', '.$errmsg : $errmsg); } $this->db->rollback(); - return -1*$error; + return -1 * $error; } else { - $this->errors[]=$this->db->error(); + $this->errors[] = $this->db->error(); $this->db->rollback(); return -2; } @@ -3519,46 +3519,46 @@ class CommandeFournisseurLigne extends CommonOrderLine */ public function update($notrigger = 0) { - global $conf,$user; + global $conf, $user; - $error=0; + $error = 0; $this->db->begin(); // Mise a jour ligne en base $sql = "UPDATE ".MAIN_DB_PREFIX.$this->table_element." SET"; - $sql.= " description='".$this->db->escape($this->desc)."'"; - $sql.= ", ref='".$this->db->escape($this->ref_supplier)."'"; - $sql.= ", subprice='".price2num($this->subprice)."'"; + $sql .= " description='".$this->db->escape($this->desc)."'"; + $sql .= ", ref='".$this->db->escape($this->ref_supplier)."'"; + $sql .= ", subprice='".price2num($this->subprice)."'"; //$sql.= ",remise='".price2num($remise)."'"; - $sql.= ", remise_percent='".price2num($this->remise_percent)."'"; + $sql .= ", remise_percent='".price2num($this->remise_percent)."'"; - $sql.= ", vat_src_code = '".(empty($this->vat_src_code)?'':$this->vat_src_code)."'"; - $sql.= ", tva_tx='".price2num($this->tva_tx)."'"; - $sql.= ", localtax1_tx='".price2num($this->total_localtax1)."'"; - $sql.= ", localtax2_tx='".price2num($this->total_localtax2)."'"; - $sql.= ", localtax1_type='".$this->db->escape($this->localtax1_type)."'"; - $sql.= ", localtax2_type='".$this->db->escape($this->localtax2_type)."'"; - $sql.= ", qty='".price2num($this->qty)."'"; - $sql.= ", date_start=".(! empty($this->date_start)?"'".$this->db->idate($this->date_start)."'":"null"); - $sql.= ", date_end=".(! empty($this->date_end)?"'".$this->db->idate($this->date_end)."'":"null"); - $sql.= ", info_bits='".$this->db->escape($this->info_bits)."'"; - $sql.= ", total_ht='".price2num($this->total_ht)."'"; - $sql.= ", total_tva='".price2num($this->total_tva)."'"; - $sql.= ", total_localtax1='".price2num($this->total_localtax1)."'"; - $sql.= ", total_localtax2='".price2num($this->total_localtax2)."'"; - $sql.= ", total_ttc='".price2num($this->total_ttc)."'"; - $sql.= ", product_type=".$this->product_type; - $sql.= ", special_code=".(!empty($this->special_code) ? $this->special_code : 0); - $sql.= ($this->fk_unit ? ", fk_unit='".$this->db->escape($this->fk_unit)."'":", fk_unit=null"); + $sql .= ", vat_src_code = '".(empty($this->vat_src_code) ? '' : $this->vat_src_code)."'"; + $sql .= ", tva_tx='".price2num($this->tva_tx)."'"; + $sql .= ", localtax1_tx='".price2num($this->total_localtax1)."'"; + $sql .= ", localtax2_tx='".price2num($this->total_localtax2)."'"; + $sql .= ", localtax1_type='".$this->db->escape($this->localtax1_type)."'"; + $sql .= ", localtax2_type='".$this->db->escape($this->localtax2_type)."'"; + $sql .= ", qty='".price2num($this->qty)."'"; + $sql .= ", date_start=".(!empty($this->date_start) ? "'".$this->db->idate($this->date_start)."'" : "null"); + $sql .= ", date_end=".(!empty($this->date_end) ? "'".$this->db->idate($this->date_end)."'" : "null"); + $sql .= ", info_bits='".$this->db->escape($this->info_bits)."'"; + $sql .= ", total_ht='".price2num($this->total_ht)."'"; + $sql .= ", total_tva='".price2num($this->total_tva)."'"; + $sql .= ", total_localtax1='".price2num($this->total_localtax1)."'"; + $sql .= ", total_localtax2='".price2num($this->total_localtax2)."'"; + $sql .= ", total_ttc='".price2num($this->total_ttc)."'"; + $sql .= ", product_type=".$this->product_type; + $sql .= ", special_code=".(!empty($this->special_code) ? $this->special_code : 0); + $sql .= ($this->fk_unit ? ", fk_unit='".$this->db->escape($this->fk_unit)."'" : ", fk_unit=null"); // Multicurrency - $sql.= ", multicurrency_subprice=".price2num($this->multicurrency_subprice).""; - $sql.= ", multicurrency_total_ht=".price2num($this->multicurrency_total_ht).""; - $sql.= ", multicurrency_total_tva=".price2num($this->multicurrency_total_tva).""; - $sql.= ", multicurrency_total_ttc=".price2num($this->multicurrency_total_ttc).""; + $sql .= ", multicurrency_subprice=".price2num($this->multicurrency_subprice).""; + $sql .= ", multicurrency_total_ht=".price2num($this->multicurrency_total_ht).""; + $sql .= ", multicurrency_total_tva=".price2num($this->multicurrency_total_tva).""; + $sql .= ", multicurrency_total_ttc=".price2num($this->multicurrency_total_ttc).""; - $sql.= " WHERE rowid = ".$this->id; + $sql .= " WHERE rowid = ".$this->id; dol_syslog(get_class($this)."::updateline", LOG_DEBUG); $result = $this->db->query($sql); @@ -3566,18 +3566,18 @@ class CommandeFournisseurLigne extends CommonOrderLine { if (empty($conf->global->MAIN_EXTRAFIELDS_DISABLED)) // For avoid conflicts if trigger used { - $result=$this->insertExtraFields(); + $result = $this->insertExtraFields(); if ($result < 0) { $error++; } } - if (! $error && ! $notrigger) + if (!$error && !$notrigger) { global $user; // Call trigger - $result=$this->call_trigger('LINEORDER_SUPPLIER_UPDATE', $user); + $result = $this->call_trigger('LINEORDER_SUPPLIER_UPDATE', $user); if ($result < 0) { $this->db->rollback(); @@ -3586,7 +3586,7 @@ class CommandeFournisseurLigne extends CommonOrderLine // End call triggers } - if (! $error) + if (!$error) { $this->db->commit(); return $result; @@ -3599,7 +3599,7 @@ class CommandeFournisseurLigne extends CommonOrderLine } else { - $this->error=$this->db->lasterror(); + $this->error = $this->db->lasterror(); $this->db->rollback(); return -1; } @@ -3639,17 +3639,17 @@ 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->error.=($this->error?', '.$errmsg:$errmsg); + $this->error .= ($this->error ? ', '.$errmsg : $errmsg); } $this->db->rollback(); - return -1*$error; + return -1 * $error; } else { - $this->error=$this->db->lasterror(); + $this->error = $this->db->lasterror(); return -1; } } diff --git a/htdocs/fourn/class/fournisseur.facture.class.php b/htdocs/fourn/class/fournisseur.facture.class.php index 4cc39f781df..7ec271c84ec 100644 --- a/htdocs/fourn/class/fournisseur.facture.class.php +++ b/htdocs/fourn/class/fournisseur.facture.class.php @@ -148,16 +148,16 @@ class FactureFournisseur extends CommonInvoice */ public $date_echeance; - public $amount=0; - public $remise=0; - public $tva=0; + public $amount = 0; + public $remise = 0; + public $tva = 0; public $localtax1; public $localtax2; - public $total_ht=0; - public $total_tva=0; - public $total_localtax1=0; - public $total_localtax2=0; - public $total_ttc=0; + public $total_ht = 0; + public $total_tva = 0; + public $total_localtax1 = 0; + public $total_localtax2 = 0; + public $total_ttc = 0; /** * @deprecated @@ -290,15 +290,15 @@ class FactureFournisseur extends CommonInvoice */ public function create($user) { - global $langs,$conf,$hookmanager; + global $langs, $conf, $hookmanager; - $error=0; - $now=dol_now(); + $error = 0; + $now = dol_now(); // Clean parameters - if (isset($this->ref_supplier)) $this->ref_supplier=trim($this->ref_supplier); + 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 (empty($this->date)) $this->date = $now; $socid = $this->socid; $ref_supplier = $this->ref_supplier; @@ -306,7 +306,7 @@ 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); + if (!empty($this->multicurrency_code) && empty($this->multicurrency_tx)) list($this->fk_multicurrency, $this->multicurrency_tx) = MultiCurrency::getIdAndTxFromCode($this->db, $this->multicurrency_code); else $this->fk_multicurrency = MultiCurrency::getIdFromCode($this->db, $this->multicurrency_code); if (empty($this->fk_multicurrency)) { @@ -407,7 +407,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++; @@ -424,7 +424,7 @@ class FactureFournisseur extends CommonInvoice $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); + $resql_insert = $this->db->query($sql); if ($resql_insert) { $idligne = $this->db->last_insert_id(MAIN_DB_PREFIX.'facture_fourn_det'); @@ -439,7 +439,7 @@ class FactureFournisseur extends CommonInvoice $this->lines[$i]->qty, $this->lines[$i]->fk_product, 'HT', - (! empty($this->lines[$i]->info_bits)?$this->lines[$i]->info_bits:''), + (!empty($this->lines[$i]->info_bits) ? $this->lines[$i]->info_bits : ''), $this->lines[$i]->product_type, $this->lines[$i]->remise_percent, false, @@ -452,7 +452,7 @@ class FactureFournisseur extends CommonInvoice } else { - $this->error=$this->db->lasterror(); + $this->error = $this->db->lasterror(); $this->db->rollback(); return -5; } @@ -467,12 +467,12 @@ class FactureFournisseur extends CommonInvoice // 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); + $resql_insert = $this->db->query($sql); if ($resql_insert) { $idligne = $this->db->last_insert_id(MAIN_DB_PREFIX.'facture_fourn_det'); @@ -487,13 +487,13 @@ class FactureFournisseur extends CommonInvoice $line->qty, $line->fk_product, 'HT', - (! empty($line->info_bits)?$line->info_bits:''), + (!empty($line->info_bits) ? $line->info_bits : ''), $line->product_type ); } else { - $this->error=$this->db->lasterror(); + $this->error = $this->db->lasterror(); $this->db->rollback(); return -5; } @@ -535,7 +535,7 @@ class FactureFournisseur extends CommonInvoice } else { - $this->error=$langs->trans('FailedToUpdatePrice'); + $this->error = $langs->trans('FailedToUpdatePrice'); $this->db->rollback(); return -3; } @@ -544,13 +544,13 @@ class FactureFournisseur extends CommonInvoice { if ($this->db->errno() == 'DB_ERROR_RECORD_ALREADY_EXISTS') { - $this->error=$langs->trans('ErrorRefAlreadyExists'); + $this->error = $langs->trans('ErrorRefAlreadyExists'); $this->db->rollback(); return -1; } else { - $this->error=$this->db->lasterror(); + $this->error = $this->db->lasterror(); $this->db->rollback(); return -2; } @@ -653,26 +653,26 @@ class FactureFournisseur extends CommonInvoice $this->total_ttc = $obj->total_ttc; $this->fk_statut = $obj->fk_statut; $this->statut = $obj->fk_statut; - $this->fk_user_author = $obj->fk_user_author; + $this->fk_user_author = $obj->fk_user_author; $this->author = $obj->fk_user_author; - $this->fk_user_valid = $obj->fk_user_valid; + $this->fk_user_valid = $obj->fk_user_valid; $this->fk_facture_source = $obj->fk_facture_source; $this->fk_project = $obj->fk_project; $this->cond_reglement_id = $obj->fk_cond_reglement; - $this->cond_reglement_code = $obj->cond_reglement_code; + $this->cond_reglement_code = $obj->cond_reglement_code; $this->cond_reglement = $obj->cond_reglement_libelle; - $this->cond_reglement_doc = $obj->cond_reglement_libelle; - $this->fk_account = $obj->fk_account; + $this->cond_reglement_doc = $obj->cond_reglement_libelle; + $this->fk_account = $obj->fk_account; $this->mode_reglement_id = $obj->fk_mode_reglement; - $this->mode_reglement_code = $obj->mode_reglement_code; - $this->mode_reglement = $obj->mode_reglement_libelle; + $this->mode_reglement_code = $obj->mode_reglement_code; + $this->mode_reglement = $obj->mode_reglement_libelle; $this->date_echeance = $this->db->jdate($obj->date_lim_reglement); - $this->note = $obj->note_private; // deprecated + $this->note = $obj->note_private; // deprecated $this->note_private = $obj->note_private; - $this->note_public = $obj->note_public; - $this->model_pdf = $obj->model_pdf; + $this->note_public = $obj->note_public; + $this->model_pdf = $obj->model_pdf; $this->modelpdf = $obj->model_pdf; - $this->import_key = $obj->import_key; + $this->import_key = $obj->import_key; //Incoterms $this->fk_incoterms = $obj->fk_incoterms; @@ -681,13 +681,13 @@ class FactureFournisseur extends CommonInvoice // Multicurrency $this->fk_multicurrency = $obj->fk_multicurrency; - $this->multicurrency_code = $obj->multicurrency_code; + $this->multicurrency_code = $obj->multicurrency_code; $this->multicurrency_tx = $obj->multicurrency_tx; - $this->multicurrency_total_ht = $obj->multicurrency_total_ht; + $this->multicurrency_total_ht = $obj->multicurrency_total_ht; $this->multicurrency_total_tva = $obj->multicurrency_total_tva; $this->multicurrency_total_ttc = $obj->multicurrency_total_ttc; - $this->extraparams = (array) json_decode($obj->extraparams, true); + $this->extraparams = (array) json_decode($obj->extraparams, true); $this->socid = $obj->socid; $this->socnom = $obj->socnom; @@ -698,16 +698,16 @@ class FactureFournisseur extends CommonInvoice if ($this->statut == self::STATUS_DRAFT) $this->brouillon = 1; - $result=$this->fetch_lines(); + $result = $this->fetch_lines(); if ($result < 0) { - $this->error=$this->db->lasterror(); + $this->error = $this->db->lasterror(); return -3; } } else { - $this->error='Bill with id '.$id.' not found'; + $this->error = 'Bill with id '.$id.' not found'; dol_syslog(get_class($this).'::fetch '.$this->error); return 0; } @@ -717,7 +717,7 @@ class FactureFournisseur extends CommonInvoice } else { - $this->error="Error ".$this->db->lasterror(); + $this->error = "Error ".$this->db->lasterror(); return -1; } } @@ -735,14 +735,14 @@ class FactureFournisseur extends CommonInvoice $this->lines = array(); $sql = 'SELECT f.rowid, f.ref as ref_supplier, f.description, f.date_start, f.date_end, f.pu_ht, f.pu_ttc, f.qty, f.remise_percent, f.vat_src_code, f.tva_tx'; - $sql.= ', f.localtax1_tx, f.localtax2_tx, f.localtax1_type, f.localtax2_type, f.total_localtax1, f.total_localtax2, f.fk_facture_fourn '; - $sql.= ', f.total_ht, f.tva as total_tva, f.total_ttc, f.fk_product, f.product_type, f.info_bits, f.rang, f.special_code, f.fk_parent_line, f.fk_unit'; - $sql.= ', p.rowid as product_id, p.ref as product_ref, p.label as label, p.description as product_desc'; - $sql.= ', f.fk_multicurrency, f.multicurrency_code, f.multicurrency_subprice, f.multicurrency_total_ht, f.multicurrency_total_tva, f.multicurrency_total_ttc'; - $sql.= ' FROM '.MAIN_DB_PREFIX.'facture_fourn_det as f'; - $sql.= ' LEFT JOIN '.MAIN_DB_PREFIX.'product as p ON f.fk_product = p.rowid'; - $sql.= ' WHERE fk_facture_fourn='.$this->id; - $sql.= ' ORDER BY f.rang, f.rowid'; + $sql .= ', f.localtax1_tx, f.localtax2_tx, f.localtax1_type, f.localtax2_type, f.total_localtax1, f.total_localtax2, f.fk_facture_fourn '; + $sql .= ', f.total_ht, f.tva as total_tva, f.total_ttc, f.fk_product, f.product_type, f.info_bits, f.rang, f.special_code, f.fk_parent_line, f.fk_unit'; + $sql .= ', p.rowid as product_id, p.ref as product_ref, p.label as label, p.description as product_desc'; + $sql .= ', f.fk_multicurrency, f.multicurrency_code, f.multicurrency_subprice, f.multicurrency_total_ht, f.multicurrency_total_tva, f.multicurrency_total_ttc'; + $sql .= ' FROM '.MAIN_DB_PREFIX.'facture_fourn_det as f'; + $sql .= ' LEFT JOIN '.MAIN_DB_PREFIX.'product as p ON f.fk_product = p.rowid'; + $sql .= ' WHERE fk_facture_fourn='.$this->id; + $sql .= ' ORDER BY f.rang, f.rowid'; dol_syslog(get_class($this)."::fetch_lines", LOG_DEBUG); $resql_rows = $this->db->query($sql); @@ -816,7 +816,7 @@ class FactureFournisseur extends CommonInvoice } else { - $this->error=$this->db->error(); + $this->error = $this->db->error(); return -3; } } @@ -921,12 +921,12 @@ class FactureFournisseur extends CommonInvoice } } - if (! $error) + if (!$error) { - if (! $notrigger) + if (!$notrigger) { // Call trigger - $result=$this->call_trigger('BILL_SUPPLIER_UPDATE', $user); + $result = $this->call_trigger('BILL_SUPPLIER_UPDATE', $user); if ($result < 0) $error++; // End call triggers } @@ -935,13 +935,13 @@ class FactureFournisseur extends CommonInvoice // Commit or rollback if ($error) { - foreach($this->errors as $errmsg) + foreach ($this->errors as $errmsg) { dol_syslog(get_class($this)."::update ".$errmsg, LOG_ERR); - $this->error.=($this->error?', '.$errmsg:$errmsg); + $this->error .= ($this->error ? ', '.$errmsg : $errmsg); } $this->db->rollback(); - return -1*$error; + return -1 * $error; } else { @@ -967,41 +967,41 @@ class FactureFournisseur extends CommonInvoice $this->db->begin(); - $remise=new DiscountAbsolute($this->db); - $result=$remise->fetch($idremise); + $remise = new DiscountAbsolute($this->db); + $result = $remise->fetch($idremise); if ($result > 0) { if ($remise->fk_invoice_supplier) // Protection against multiple submission { - $this->error=$langs->trans("ErrorDiscountAlreadyUsed"); + $this->error = $langs->trans("ErrorDiscountAlreadyUsed"); $this->db->rollback(); return -5; } - $facligne=new SupplierInvoiceLine($this->db); - $facligne->fk_facture_fourn=$this->id; - $facligne->fk_remise_except=$remise->id; - $facligne->desc=$remise->description; // Description ligne - $facligne->vat_src_code=$remise->vat_src_code; - $facligne->tva_tx=$remise->tva_tx; + $facligne = new SupplierInvoiceLine($this->db); + $facligne->fk_facture_fourn = $this->id; + $facligne->fk_remise_except = $remise->id; + $facligne->desc = $remise->description; // Description ligne + $facligne->vat_src_code = $remise->vat_src_code; + $facligne->tva_tx = $remise->tva_tx; $facligne->subprice = -$remise->amount_ht; - $facligne->fk_product=0; // Id produit predefini - $facligne->product_type=0; - $facligne->qty=1; - $facligne->remise_percent=0; - $facligne->rang=-1; - $facligne->info_bits=2; + $facligne->fk_product = 0; // Id produit predefini + $facligne->product_type = 0; + $facligne->qty = 1; + $facligne->remise_percent = 0; + $facligne->rang = -1; + $facligne->info_bits = 2; // Get buy/cost price of invoice that is source of discount if ($remise->fk_invoice_supplier_source > 0) { - $srcinvoice=new FactureFournisseur($this->db); + $srcinvoice = new FactureFournisseur($this->db); $srcinvoice->fetch($remise->fk_invoice_supplier_source); - $totalcostpriceofinvoice=0; - include_once DOL_DOCUMENT_ROOT.'/core/class/html.formmargin.class.php'; // TODO Move this into commonobject - $formmargin=new FormMargin($this->db); - $arraytmp=$formmargin->getMarginInfosArray($srcinvoice, false); + $totalcostpriceofinvoice = 0; + include_once DOL_DOCUMENT_ROOT.'/core/class/html.formmargin.class.php'; // TODO Move this into commonobject + $formmargin = new FormMargin($this->db); + $arraytmp = $formmargin->getMarginInfosArray($srcinvoice, false); $facligne->pa_ht = $arraytmp['pa_total']; } @@ -1014,17 +1014,17 @@ class FactureFournisseur extends CommonInvoice $facligne->multicurrency_total_tva = -$remise->multicurrency_total_tva; $facligne->multicurrency_total_ttc = -$remise->multicurrency_total_ttc; - $lineid=$facligne->insert(); + $lineid = $facligne->insert(); if ($lineid > 0) { - $result=$this->update_price(1); + $result = $this->update_price(1); if ($result > 0) { // Create link between discount and invoice line - $result=$remise->link_to_invoice($lineid, 0, 'supplier'); + $result = $remise->link_to_invoice($lineid, 0, 'supplier'); if ($result < 0) { - $this->error=$remise->error; + $this->error = $remise->error; $this->db->rollback(); return -4; } @@ -1034,14 +1034,14 @@ class FactureFournisseur extends CommonInvoice } else { - $this->error=$facligne->error; + $this->error = $facligne->error; $this->db->rollback(); return -1; } } else { - $this->error=$facligne->error; + $this->error = $facligne->error; $this->db->rollback(); return -2; } @@ -1063,21 +1063,21 @@ class FactureFournisseur extends CommonInvoice */ public function delete(User $user, $notrigger = 0) { - global $langs,$conf; + global $langs, $conf; - $rowid=$this->id; + $rowid = $this->id; dol_syslog("FactureFournisseur::delete rowid=".$rowid, LOG_DEBUG); // TODO Test if there is at least on payment. If yes, refuse to delete. - $error=0; + $error = 0; $this->db->begin(); - if (! $error && ! $notrigger) + if (!$error && !$notrigger) { // Call trigger - $result=$this->call_trigger('BILL_SUPPLIER_DELETE', $user); + $result = $this->call_trigger('BILL_SUPPLIER_DELETE', $user); if ($result < 0) { $this->db->rollback(); @@ -1086,34 +1086,34 @@ class FactureFournisseur extends CommonInvoice // Fin appel triggers } - 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_invoice_supplier_source = ' . $rowid; + $sql = 'DELETE FROM '.MAIN_DB_PREFIX.'societe_remise_except'; + $sql .= ' WHERE fk_invoice_supplier_source = '.$rowid; $sql .= ' AND fk_invoice_supplier_line IS NULL'; $resql = $this->db->query($sql); // If invoice has consumned discounts $this->fetch_lines(); - $list_rowid_det = array (); + $list_rowid_det = array(); foreach ($this->lines as $key => $invoiceline) { $list_rowid_det[] = $invoiceline->rowid; } // Consumned discounts are freed if (count($list_rowid_det)) { - $sql = 'UPDATE ' . MAIN_DB_PREFIX . 'societe_remise_except'; + $sql = 'UPDATE '.MAIN_DB_PREFIX.'societe_remise_except'; $sql .= ' SET fk_invoice_supplier = NULL, fk_invoice_supplier_line = NULL'; - $sql .= ' WHERE fk_invoice_supplier_line IN (' . join(',', $list_rowid_det) . ')'; + $sql .= ' WHERE fk_invoice_supplier_line IN ('.join(',', $list_rowid_det).')'; - dol_syslog(get_class($this) . "::delete", LOG_DEBUG); - if (! $this->db->query($sql)) { - $error ++; + dol_syslog(get_class($this)."::delete", LOG_DEBUG); + if (!$this->db->query($sql)) { + $error++; } } } - if (! $error) + if (!$error) { $sql = 'DELETE FROM '.MAIN_DB_PREFIX.'facture_fourn_det WHERE fk_facture_fourn = '.$rowid.';'; dol_syslog(get_class($this)."::delete", LOG_DEBUG); @@ -1123,7 +1123,7 @@ class FactureFournisseur extends CommonInvoice $sql = 'DELETE FROM '.MAIN_DB_PREFIX.'facture_fourn WHERE rowid = '.$rowid; dol_syslog(get_class($this)."::delete", LOG_DEBUG); $resql2 = $this->db->query($sql); - if (! $resql2) { + if (!$resql2) { $error++; } } @@ -1132,21 +1132,21 @@ class FactureFournisseur extends CommonInvoice } } - if (! $error) + if (!$error) { // Delete linked object $res = $this->deleteObjectLinked(); if ($res < 0) $error++; } - if (! $error) + if (!$error) { // Delete linked object $res = $this->deleteObjectLinked(); if ($res < 0) $error++; } - if (! $error) + if (!$error) { // We remove directory if ($conf->fournisseur->facture->dir_output) @@ -1155,22 +1155,22 @@ class FactureFournisseur extends CommonInvoice $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"; + $file = $dir."/".$ref.".pdf"; if (file_exists($file)) { - if (! dol_delete_file($file, 0, 0, 0, $this)) // For triggers + if (!dol_delete_file($file, 0, 0, 0, $this)) // For triggers { - $this->error='ErrorFailToDeleteFile'; + $this->error = 'ErrorFailToDeleteFile'; $error++; } } if (file_exists($dir)) { - $res=@dol_delete_dir_recursive($dir); + $res = @dol_delete_dir_recursive($dir); - if (! $res) + if (!$res) { - $this->error='ErrorFailToDeleteDir'; + $this->error = 'ErrorFailToDeleteDir'; $error++; } } @@ -1178,9 +1178,9 @@ class FactureFournisseur extends CommonInvoice } // Remove extrafields - if ((! $error) && (empty($conf->global->MAIN_EXTRAFIELDS_DISABLED))) // For avoid conflicts if trigger used + if ((!$error) && (empty($conf->global->MAIN_EXTRAFIELDS_DISABLED))) // For avoid conflicts if trigger used { - $result=$this->deleteExtraFields(); + $result = $this->deleteExtraFields(); if ($result < 0) { $error++; @@ -1188,7 +1188,7 @@ class FactureFournisseur extends CommonInvoice } } - if (! $error) + if (!$error) { dol_syslog(get_class($this)."::delete $this->id by $user->id", LOG_DEBUG); $this->db->commit(); @@ -1196,7 +1196,7 @@ class FactureFournisseur extends CommonInvoice } else { - $this->error=$this->db->lasterror(); + $this->error = $this->db->lasterror(); $this->db->rollback(); return -$error; } @@ -1215,32 +1215,32 @@ class FactureFournisseur extends CommonInvoice public function set_paid($user, $close_code = '', $close_note = '') { // phpcs:enable - global $conf,$langs; - $error=0; + global $conf, $langs; + $error = 0; $this->db->begin(); $sql = 'UPDATE '.MAIN_DB_PREFIX.'facture_fourn'; - $sql.= ' SET paye = 1, fk_statut=2'; - $sql.= ' WHERE rowid = '.$this->id; + $sql .= ' SET paye = 1, fk_statut=2'; + $sql .= ' WHERE rowid = '.$this->id; dol_syslog("FactureFournisseur::set_paid", LOG_DEBUG); $resql = $this->db->query($sql); if ($resql) { // Call trigger - $result=$this->call_trigger('BILL_SUPPLIER_PAYED', $user); + $result = $this->call_trigger('BILL_SUPPLIER_PAYED', $user); if ($result < 0) $error++; // End call triggers } else { $error++; - $this->error=$this->db->error(); + $this->error = $this->db->error(); dol_print_error($this->db); } - if (! $error) + if (!$error) { $this->db->commit(); return 1; @@ -1265,32 +1265,32 @@ class FactureFournisseur extends CommonInvoice public function set_unpaid($user) { // phpcs:enable - global $conf,$langs; - $error=0; + global $conf, $langs; + $error = 0; $this->db->begin(); $sql = 'UPDATE '.MAIN_DB_PREFIX.'facture_fourn'; - $sql.= ' SET paye=0, fk_statut=1, close_code=null, close_note=null'; - $sql.= ' WHERE rowid = '.$this->id; + $sql .= ' SET paye=0, fk_statut=1, close_code=null, close_note=null'; + $sql .= ' WHERE rowid = '.$this->id; dol_syslog("FactureFournisseur::set_unpaid", LOG_DEBUG); $resql = $this->db->query($sql); if ($resql) { // Call trigger - $result=$this->call_trigger('BILL_SUPPLIER_UNPAYED', $user); + $result = $this->call_trigger('BILL_SUPPLIER_UNPAYED', $user); if ($result < 0) $error++; // End call triggers } else { $error++; - $this->error=$this->db->lasterror(); + $this->error = $this->db->lasterror(); dol_syslog("FactureFournisseur::set_unpaid ".$this->error); } - if (! $error) + if (!$error) { $this->db->commit(); return 1; @@ -1335,13 +1335,13 @@ class FactureFournisseur extends CommonInvoice 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")); + $this->error = $langs->trans("ErrorFieldFormat", $langs->transnoentities("RefSupplier")).'. '.$langs->trans('RemoveString', $langs->transnoentitiesnoconv("CopyOf")); return -1; } if (count($this->lines) <= 0) { $langs->load("errors"); - $this->error=$langs->trans("ErrorObjectMustHaveLinesToBeValidated", $this->ref); + $this->error = $langs->trans("ErrorObjectMustHaveLinesToBeValidated", $this->ref); return -1; } @@ -1363,20 +1363,20 @@ class FactureFournisseur extends CommonInvoice $this->newref = $num; $sql = "UPDATE ".MAIN_DB_PREFIX."facture_fourn"; - $sql.= " SET ref='".$num."', fk_statut = 1, fk_user_valid = ".$user->id.", date_valid = '".$this->db->idate($now)."'"; - $sql.= " WHERE rowid = ".$this->id; + $sql .= " SET ref='".$num."', fk_statut = 1, fk_user_valid = ".$user->id.", date_valid = '".$this->db->idate($now)."'"; + $sql .= " WHERE rowid = ".$this->id; dol_syslog(get_class($this)."::validate", LOG_DEBUG); $resql = $this->db->query($sql); 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); + $cpt = count($this->lines); for ($i = 0; $i < $cpt; $i++) { if ($this->lines[$i]->fk_product > 0) @@ -1396,15 +1396,15 @@ class FactureFournisseur extends CommonInvoice } // Triggers call - if (! $error && empty($notrigger)) + if (!$error && empty($notrigger)) { // Call trigger - $result=$this->call_trigger('BILL_SUPPLIER_VALIDATE', $user); + $result = $this->call_trigger('BILL_SUPPLIER_VALIDATE', $user); if ($result < 0) $error++; // End call triggers } - if (! $error) + if (!$error) { $this->oldref = $this->ref; @@ -1430,13 +1430,13 @@ class FactureFournisseur extends CommonInvoice { 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) + $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) { - $dirsource=$fileentry['name']; - $dirdest=preg_replace('/^'.preg_quote($oldref, '/').'/', $newref, $dirsource); - $dirsource=$fileentry['path'].'/'.$dirsource; - $dirdest=$fileentry['path'].'/'.$dirdest; + $dirsource = $fileentry['name']; + $dirdest = preg_replace('/^'.preg_quote($oldref, '/').'/', $newref, $dirsource); + $dirsource = $fileentry['path'].'/'.$dirsource; + $dirdest = $fileentry['path'].'/'.$dirdest; @rename($dirsource, $dirdest); } } @@ -1445,14 +1445,14 @@ class FactureFournisseur extends CommonInvoice } // Set new ref and define current statut - if (! $error) + if (!$error) { $this->ref = $num; - $this->statut=self::STATUS_VALIDATED; + $this->statut = self::STATUS_VALIDATED; //$this->date_validation=$now; this is stored into log table } - if (! $error) + if (!$error) { $this->db->commit(); return 1; @@ -1465,7 +1465,7 @@ class FactureFournisseur extends CommonInvoice } else { - $this->error=$this->db->error(); + $this->error = $this->db->error(); $this->db->rollback(); return -1; } @@ -1481,9 +1481,9 @@ class FactureFournisseur extends CommonInvoice public function setDraft($user, $idwarehouse = -1) { // phpcs:enable - global $conf,$langs; + global $conf, $langs; - $error=0; + $error = 0; if ($this->statut == self::STATUS_DRAFT) { @@ -1496,24 +1496,24 @@ class FactureFournisseur extends CommonInvoice $this->db->begin(); $sql = "UPDATE ".MAIN_DB_PREFIX."facture_fourn"; - $sql.= " SET fk_statut = ".self::STATUS_DRAFT; - $sql.= " WHERE rowid = ".$this->id; + $sql .= " SET fk_statut = ".self::STATUS_DRAFT; + $sql .= " WHERE rowid = ".$this->id; - $result=$this->db->query($sql); + $result = $this->db->query($sql); if ($result) { - if (! $error) + if (!$error) { - $this->oldcopy= clone $this; + $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); + $cpt = count($this->lines); for ($i = 0; $i < $cpt; $i++) { if ($this->lines[$i]->fk_product > 0) @@ -1547,7 +1547,7 @@ class FactureFournisseur extends CommonInvoice } else { - $this->error=$this->db->error(); + $this->error = $this->db->error(); $this->db->rollback(); return -1; } @@ -1623,7 +1623,7 @@ class FactureFournisseur extends CommonInvoice if ($fk_product > 0) { - if (! empty($conf->global->SUPPLIER_INVOICE_WITH_PREDEFINED_PRICES_ONLY)) + 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); @@ -1636,19 +1636,19 @@ 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 + $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) { - $pu = $prod->fourn_pu; // Unit price supplier price set by get_buyprice - $ref_supplier = $prod->ref_supplier; // Ref supplier price set by get_buyprice + $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 { $langs->load("errors"); - $this->error = "Ref " . $prod->ref . " " . $langs->trans("ErrorQtyTooLowForThisSupplier"); + $this->error = "Ref ".$prod->ref." ".$langs->trans("ErrorQtyTooLowForThisSupplier"); $this->db->rollback(); dol_syslog(get_class($this)."::addline we did not found supplier price, so we can't guess unit price"); //$pu = $prod->fourn_pu; // We do not overwrite unit price @@ -1658,14 +1658,14 @@ class FactureFournisseur extends CommonInvoice if ($result == -1) { $langs->load("errors"); - $this->error = "Ref " . $prod->ref . " " . $langs->trans("ErrorQtyTooLowForThisSupplier"); + $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) { - $this->error=$prod->error; + $this->error = $prod->error; $this->db->rollback(); dol_syslog(get_class($this)."::addline result=".$result." - ".$this->error, LOG_ERR); return -1; @@ -1673,7 +1673,7 @@ class FactureFournisseur extends CommonInvoice } else { - $this->error=$prod->error; + $this->error = $prod->error; $this->db->rollback(); return -1; } @@ -1688,14 +1688,14 @@ class FactureFournisseur extends CommonInvoice $pu = 0; } - $localtaxes_type=getLocalTaxesFromRate($txtva, 0, $mysoc, $this->thirdparty); + $localtaxes_type = getLocalTaxesFromRate($txtva, 0, $mysoc, $this->thirdparty); // Clean vat code - $vat_src_code=''; + $vat_src_code = ''; if (preg_match('/\((.*)\)/', $txtva, $reg)) { $vat_src_code = $reg[1]; - $txtva = preg_replace('/\s*\(.*\)/', '', $txtva); // Remove code into vatrate. + $txtva = preg_replace('/\s*\(.*\)/', '', $txtva); // Remove code into vatrate. } // Calcul du total TTC et de la TVA pour la ligne a partir de @@ -1727,66 +1727,66 @@ class FactureFournisseur extends CommonInvoice } // Insert line - $this->line=new SupplierInvoiceLine($this->db); + $this->line = new SupplierInvoiceLine($this->db); $this->line->context = $this->context; - $this->line->fk_facture_fourn=$this->id; + $this->line->fk_facture_fourn = $this->id; //$this->line->label=$label; // deprecated - $this->line->desc=$desc; - $this->line->ref_supplier=$ref_supplier; + $this->line->desc = $desc; + $this->line->ref_supplier = $ref_supplier; - $this->line->qty= ($this->type==self::TYPE_CREDIT_NOTE?abs($qty):$qty); // For credit note, quantity is always positive and unit price negative - $this->line->subprice= ($this->type==self::TYPE_CREDIT_NOTE?-abs($pu_ht):$pu_ht); // For credit note, unit price always negative, always positive otherwise + $this->line->qty = ($this->type == self::TYPE_CREDIT_NOTE ?abs($qty) : $qty); // For credit note, quantity is always positive and unit price negative + $this->line->subprice = ($this->type == self::TYPE_CREDIT_NOTE ?-abs($pu_ht) : $pu_ht); // For credit note, unit price always negative, always positive otherwise - $this->line->vat_src_code=$vat_src_code; - $this->line->tva_tx=$txtva; - $this->line->localtax1_tx=($total_localtax1?$localtaxes_type[1]:0); - $this->line->localtax2_tx=($total_localtax2?$localtaxes_type[3]:0); + $this->line->vat_src_code = $vat_src_code; + $this->line->tva_tx = $txtva; + $this->line->localtax1_tx = ($total_localtax1 ? $localtaxes_type[1] : 0); + $this->line->localtax2_tx = ($total_localtax2 ? $localtaxes_type[3] : 0); $this->line->localtax1_type = $localtaxes_type[0]; $this->line->localtax2_type = $localtaxes_type[2]; - $this->line->total_ht= (($this->type==self::TYPE_CREDIT_NOTE||$qty<0)?-abs($total_ht):$total_ht); // For credit note and if qty is negative, total is negative - $this->line->total_tva= (($this->type==self::TYPE_CREDIT_NOTE||$qty<0)?-abs($total_tva):$total_tva); - $this->line->total_localtax1=(($this->type==self::TYPE_CREDIT_NOTE||$qty<0)?-abs($total_localtax1):$total_localtax1); - $this->line->total_localtax2=(($this->type==self::TYPE_CREDIT_NOTE||$qty<0)?-abs($total_localtax2):$total_localtax2); - $this->line->total_ttc= (($this->type==self::TYPE_CREDIT_NOTE||$qty<0)?-abs($total_ttc):$total_ttc); + $this->line->total_ht = (($this->type == self::TYPE_CREDIT_NOTE || $qty < 0) ?-abs($total_ht) : $total_ht); // For credit note and if qty is negative, total is negative + $this->line->total_tva = (($this->type == self::TYPE_CREDIT_NOTE || $qty < 0) ?-abs($total_tva) : $total_tva); + $this->line->total_localtax1 = (($this->type == self::TYPE_CREDIT_NOTE || $qty < 0) ?-abs($total_localtax1) : $total_localtax1); + $this->line->total_localtax2 = (($this->type == self::TYPE_CREDIT_NOTE || $qty < 0) ?-abs($total_localtax2) : $total_localtax2); + $this->line->total_ttc = (($this->type == self::TYPE_CREDIT_NOTE || $qty < 0) ?-abs($total_ttc) : $total_ttc); - $this->line->fk_product=$fk_product; - $this->line->product_type=$type; - $this->line->remise_percent=$remise_percent; - $this->line->date_start=$date_start; - $this->line->date_end=$date_end; - $this->line->ventil=$ventil; - $this->line->rang=$rang; - $this->line->info_bits=$info_bits; + $this->line->fk_product = $fk_product; + $this->line->product_type = $type; + $this->line->remise_percent = $remise_percent; + $this->line->date_start = $date_start; + $this->line->date_end = $date_end; + $this->line->ventil = $ventil; + $this->line->rang = $rang; + $this->line->info_bits = $info_bits; - $this->line->special_code=((string) $special_code != '' ? $special_code : $this->special_code); - $this->line->fk_parent_line=$this->fk_parent_line; - $this->line->origin=$this->origin; - $this->line->origin_id=$origin_id; - $this->line->fk_unit=$fk_unit; + $this->line->special_code = ((string) $special_code != '' ? $special_code : $this->special_code); + $this->line->fk_parent_line = $this->fk_parent_line; + $this->line->origin = $this->origin; + $this->line->origin_id = $origin_id; + $this->line->fk_unit = $fk_unit; // Multicurrency - $this->line->fk_multicurrency = $this->fk_multicurrency; - $this->line->multicurrency_code = $this->multicurrency_code; + $this->line->fk_multicurrency = $this->fk_multicurrency; + $this->line->multicurrency_code = $this->multicurrency_code; $this->line->multicurrency_subprice = $pu_ht_devise; $this->line->multicurrency_total_ht = $multicurrency_total_ht; $this->line->multicurrency_total_tva = $multicurrency_total_tva; $this->line->multicurrency_total_ttc = $multicurrency_total_ttc; - if (is_array($array_options) && count($array_options)>0) { - $this->line->array_options=$array_options; + if (is_array($array_options) && count($array_options) > 0) { + $this->line->array_options = $array_options; } - $result=$this->line->insert($notrigger); + $result = $this->line->insert($notrigger); 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. + $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) { $this->db->commit(); @@ -1794,15 +1794,15 @@ class FactureFournisseur extends CommonInvoice } else { - $this->error=$this->db->error(); + $this->error = $this->db->error(); $this->db->rollback(); return -1; } } else { - $this->error=$this->line->error; - $this->errors=$this->line->errors; + $this->error = $this->line->error; + $this->errors = $this->line->errors; $this->db->rollback(); return -2; } @@ -1844,8 +1844,8 @@ class FactureFournisseur extends CommonInvoice include_once DOL_DOCUMENT_ROOT.'/core/lib/price.lib.php'; $pu = price2num($pu); - $qty = price2num($qty); - $remise_percent=price2num($remise_percent); + $qty = price2num($qty); + $remise_percent = price2num($remise_percent); $pu_ht_devise = price2num($pu_ht_devise); // Check parameters @@ -1854,33 +1854,33 @@ class FactureFournisseur extends CommonInvoice if ($date_start && $date_end && $date_start > $date_end) { $langs->load("errors"); - $this->error=$langs->trans('ErrorStartDateGreaterEnd'); + $this->error = $langs->trans('ErrorStartDateGreaterEnd'); return -1; } // 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); + $txlocaltax1 = price2num($txlocaltax1); + $txlocaltax2 = price2num($txlocaltax2); - $localtaxes_type = array($txlocaltax1,$txlocaltax2); + $localtaxes_type = array($txlocaltax1, $txlocaltax2); // Calcul du total TTC et de la TVA pour la ligne a partir de // qty, pu, remise_percent et txtva // TRES IMPORTANT: C'est au moment de l'insertion ligne qu'on doit stocker // la part ht, tva et ttc, et ce au niveau de la ligne qui a son propre taux tva. - $localtaxes_type=getLocalTaxesFromRate($vatrate, 0, $mysoc, $this->thirdparty); + $localtaxes_type = getLocalTaxesFromRate($vatrate, 0, $mysoc, $this->thirdparty); // Clean vat code - $vat_src_code=''; + $vat_src_code = ''; if (preg_match('/\((.*)\)/', $vatrate, $reg)) { $vat_src_code = $reg[1]; - $vatrate = preg_replace('/\s*\(.*\)/', '', $vatrate); // Remove code into vatrate. + $vatrate = preg_replace('/\s*\(.*\)/', '', $vatrate); // Remove code into vatrate. } $tabprice = calcul_price_total($qty, $pu, $remise_percent, $vatrate, $txlocaltax1, $txlocaltax2, 0, $price_base_type, $info_bits, $type, $this->thirdparty, $localtaxes_type, 100, $this->multicurrency_tx, $pu_ht_devise); @@ -1894,17 +1894,17 @@ class FactureFournisseur extends CommonInvoice $total_localtax2 = $tabprice[10]; // MultiCurrency - $multicurrency_total_ht = $tabprice[16]; + $multicurrency_total_ht = $tabprice[16]; $multicurrency_total_tva = $tabprice[17]; $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) { - $product=new Product($this->db); - $result=$product->fetch($idproduct); + $product = new Product($this->db); + $result = $product->fetch($idproduct); $product_type = $product->type; } else @@ -1929,17 +1929,17 @@ class FactureFournisseur extends CommonInvoice $line->date_start = $date_start; $line->date_end = $date_end; - $line->vat_src_code=$vat_src_code; + $line->vat_src_code = $vat_src_code; $line->tva_tx = $vatrate; $line->localtax1_tx = $txlocaltax1; $line->localtax2_tx = $txlocaltax2; $line->localtax1_type = $localtaxes_type[0]; $line->localtax2_type = $localtaxes_type[2]; - $line->total_ht = (($this->type==self::TYPE_CREDIT_NOTE||$qty<0)?-abs($total_ht):$total_ht); - $line->total_tva = (($this->type==self::TYPE_CREDIT_NOTE||$qty<0)?-abs($total_tva):$total_tva); + $line->total_ht = (($this->type == self::TYPE_CREDIT_NOTE || $qty < 0) ?-abs($total_ht) : $total_ht); + $line->total_tva = (($this->type == self::TYPE_CREDIT_NOTE || $qty < 0) ?-abs($total_tva) : $total_tva); $line->total_localtax1 = $total_localtax1; $line->total_localtax2 = $total_localtax2; - $line->total_ttc = (($this->type==self::TYPE_CREDIT_NOTE||$qty<0)?-abs($total_ttc):$total_ttc); + $line->total_ttc = (($this->type == self::TYPE_CREDIT_NOTE || $qty < 0) ?-abs($total_ttc) : $total_ttc); $line->fk_product = $idproduct; $line->product_type = $product_type; $line->info_bits = $info_bits; @@ -1947,8 +1947,8 @@ class FactureFournisseur extends CommonInvoice $line->array_options = $array_options; // Multicurrency - $line->multicurrency_subprice = $pu_ht_devise; - $line->multicurrency_total_ht = $multicurrency_total_ht; + $line->multicurrency_subprice = $pu_ht_devise; + $line->multicurrency_total_ht = $multicurrency_total_ht; $line->multicurrency_total_tva = $multicurrency_total_tva; $line->multicurrency_total_ttc = $multicurrency_total_ttc; @@ -1980,17 +1980,17 @@ class FactureFournisseur extends CommonInvoice $this->db->begin(); // Libere remise liee a ligne de facture - $sql = 'UPDATE ' . MAIN_DB_PREFIX . 'societe_remise_except'; + $sql = 'UPDATE '.MAIN_DB_PREFIX.'societe_remise_except'; $sql .= ' SET fk_invoice_supplier_line = NULL'; - $sql .= ' WHERE fk_invoice_supplier_line = ' . $rowid; + $sql .= ' WHERE fk_invoice_supplier_line = '.$rowid; - dol_syslog(get_class($this) . "::deleteline", LOG_DEBUG); + 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; + return -2; } $line = new SupplierInvoiceLine($this->db); @@ -2004,7 +2004,7 @@ class FactureFournisseur extends CommonInvoice if ($res < 1) { $this->errors[] = $line->error; $this->db->rollback(); - return - 3; + return -3; } else { $res = $this->update_price(); @@ -2017,7 +2017,7 @@ class FactureFournisseur extends CommonInvoice { $this->db->rollback(); $this->error = $this->db->lasterror(); - return - 4; + return -4; } } } @@ -2032,11 +2032,11 @@ class FactureFournisseur extends CommonInvoice public function info($id) { $sql = 'SELECT c.rowid, datec, tms as datem, '; - $sql.= ' fk_user_author, fk_user_modif, fk_user_valid'; - $sql.= ' FROM '.MAIN_DB_PREFIX.'facture_fourn as c'; - $sql.= ' WHERE c.rowid = '.$id; + $sql .= ' fk_user_author, fk_user_modif, fk_user_valid'; + $sql .= ' FROM '.MAIN_DB_PREFIX.'facture_fourn as c'; + $sql .= ' WHERE c.rowid = '.$id; - $result=$this->db->query($sql); + $result = $this->db->query($sql); if ($result) { if ($this->db->num_rows($result)) @@ -2047,7 +2047,7 @@ class FactureFournisseur extends CommonInvoice { $cuser = new User($this->db); $cuser->fetch($obj->fk_user_author); - $this->user_creation = $cuser; + $this->user_creation = $cuser; } if ($obj->fk_user_valid) { @@ -2090,25 +2090,25 @@ class FactureFournisseur extends CommonInvoice $return = array(); $sql = "SELECT f.rowid as rowid, f.ref, f.fk_statut,"; - $sql.= " ff.rowid as rowidnext"; - $sql.= " FROM ".MAIN_DB_PREFIX."facture_fourn as f"; - $sql.= " LEFT JOIN ".MAIN_DB_PREFIX."paiementfourn_facturefourn as pf ON f.rowid = pf.fk_facturefourn"; - $sql.= " LEFT JOIN ".MAIN_DB_PREFIX."facture_fourn as ff ON f.rowid = ff.fk_facture_source"; - $sql.= " WHERE (f.fk_statut = ".self::STATUS_VALIDATED." OR (f.fk_statut = ".self::STATUS_ABANDONED." AND f.close_code = '".self::CLOSECODE_ABANDONED."'))"; - $sql.= " AND f.entity = ".$conf->entity; - $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; - $sql.= " ORDER BY f.ref"; + $sql .= " ff.rowid as rowidnext"; + $sql .= " FROM ".MAIN_DB_PREFIX."facture_fourn as f"; + $sql .= " LEFT JOIN ".MAIN_DB_PREFIX."paiementfourn_facturefourn as pf ON f.rowid = pf.fk_facturefourn"; + $sql .= " LEFT JOIN ".MAIN_DB_PREFIX."facture_fourn as ff ON f.rowid = ff.fk_facture_source"; + $sql .= " WHERE (f.fk_statut = ".self::STATUS_VALIDATED." OR (f.fk_statut = ".self::STATUS_ABANDONED." AND f.close_code = '".self::CLOSECODE_ABANDONED."'))"; + $sql .= " AND f.entity = ".$conf->entity; + $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; + $sql .= " ORDER BY f.ref"; dol_syslog(get_class($this)."::list_replacable_supplier_invoices", LOG_DEBUG); - $resql=$this->db->query($sql); + $resql = $this->db->query($sql); if ($resql) { - while ($obj=$this->db->fetch_object($resql)) + while ($obj = $this->db->fetch_object($resql)) { - $return[$obj->rowid]=array( + $return[$obj->rowid] = array( 'id' => $obj->rowid, 'ref' => $obj->ref, 'status' => $obj->fk_statut @@ -2119,7 +2119,7 @@ class FactureFournisseur extends CommonInvoice } else { - $this->error=$this->db->error(); + $this->error = $this->db->error(); return -1; } } @@ -2142,29 +2142,29 @@ class FactureFournisseur extends CommonInvoice $return = array(); $sql = "SELECT f.rowid as rowid, f.ref, f.fk_statut, f.type, f.paye, pf.fk_paiementfourn"; - $sql.= " FROM ".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_statut in (".self::STATUS_VALIDATED.",".self::STATUS_CLOSED.")"; - $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; - $sql.= " ORDER BY f.ref"; + $sql .= " FROM ".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_statut in (".self::STATUS_VALIDATED.",".self::STATUS_CLOSED.")"; + $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; + $sql .= " ORDER BY f.ref"; dol_syslog(get_class($this)."::list_qualified_avoir_supplier_invoices", LOG_DEBUG); - $resql=$this->db->query($sql); + $resql = $this->db->query($sql); if ($resql) { - while ($obj=$this->db->fetch_object($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; + $qualified = 0; + 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); + $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); } } @@ -2172,7 +2172,7 @@ class FactureFournisseur extends CommonInvoice } else { - $this->error=$this->db->error(); + $this->error = $this->db->error(); return -1; } } @@ -2231,7 +2231,7 @@ class FactureFournisseur extends CommonInvoice else { dol_print_error($this->db); - $this->error=$this->db->error(); + $this->error = $this->db->error(); return -1; } } @@ -2253,7 +2253,7 @@ class FactureFournisseur extends CommonInvoice { global $langs, $conf; - $result=''; + $result = ''; if ($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; @@ -2334,9 +2334,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; + $mybool = false; $file = $conf->global->INVOICE_SUPPLIER_ADDON_NUMBER.".php"; $classname = $conf->global->INVOICE_SUPPLIER_ADDON_NUMBER; @@ -2348,7 +2348,7 @@ class FactureFournisseur extends CommonInvoice $dir = dol_buildpath($reldir."core/modules/supplier_invoice/"); // Load file with numbering class (if found) - $mybool|=@include_once $dir.$file; + $mybool |= @include_once $dir.$file; } if ($mybool === false) { @@ -2383,7 +2383,7 @@ class FactureFournisseur extends CommonInvoice */ public function initAsSpecimen($option = '') { - global $langs,$conf; + global $langs, $conf; include_once DOL_DOCUMENT_ROOT.'/compta/facture/class/facture.class.php'; $now = dol_now(); @@ -2393,8 +2393,8 @@ class FactureFournisseur extends CommonInvoice $prodids = array(); $sql = "SELECT rowid"; - $sql.= " FROM ".MAIN_DB_PREFIX."product"; - $sql.= " WHERE entity IN (".getEntity('product').")"; + $sql .= " FROM ".MAIN_DB_PREFIX."product"; + $sql .= " WHERE entity IN (".getEntity('product').")"; $resql = $this->db->query($sql); if ($resql) @@ -2410,17 +2410,17 @@ class FactureFournisseur extends CommonInvoice } // Initialise parametres - $this->id=0; + $this->id = 0; $this->ref = 'SPECIMEN'; $this->ref_supplier = 'SUPPLIER_REF_SPECIMEN'; - $this->specimen=1; + $this->specimen = 1; $this->socid = 1; $this->date = $now; - $this->date_lim_reglement=$this->date+3600*24*30; + $this->date_lim_reglement = $this->date + 3600 * 24 * 30; $this->cond_reglement_code = 'RECEP'; $this->mode_reglement_code = 'CHQ'; - $this->note_public='This is a comment (public)'; - $this->note_private='This is a comment (private)'; + $this->note_public = 'This is a comment (public)'; + $this->note_private = 'This is a comment (private)'; if (empty($option) || $option != 'nolines') { @@ -2429,38 +2429,38 @@ class FactureFournisseur extends CommonInvoice $xnbp = 0; while ($xnbp < $nbp) { - $line=new FactureLigne($this->db); - $line->desc=$langs->trans("Description")." ".$xnbp; - $line->qty=1; - $line->subprice=100; - $line->pu_ht=100; // the canelle template use pu_ht and not subprice - $line->price=100; - $line->tva_tx=19.6; - $line->localtax1_tx=0; - $line->localtax2_tx=0; + $line = new FactureLigne($this->db); + $line->desc = $langs->trans("Description")." ".$xnbp; + $line->qty = 1; + $line->subprice = 100; + $line->pu_ht = 100; // the canelle template use pu_ht and not subprice + $line->price = 100; + $line->tva_tx = 19.6; + $line->localtax1_tx = 0; + $line->localtax2_tx = 0; if ($xnbp == 2) { - $line->total_ht=50; - $line->total_ttc=59.8; - $line->total_tva=9.8; - $line->remise_percent=50; + $line->total_ht = 50; + $line->total_ttc = 59.8; + $line->total_tva = 9.8; + $line->remise_percent = 50; } else { - $line->total_ht=100; - $line->total_ttc=119.6; - $line->total_tva=19.6; - $line->remise_percent=0; + $line->total_ht = 100; + $line->total_ttc = 119.6; + $line->total_tva = 19.6; + $line->remise_percent = 0; } if ($num_prods > 0) { $prodid = mt_rand(1, $num_prods); - $line->fk_product=$prodids[$prodid]; + $line->fk_product = $prodids[$prodid]; } - $line->product_type=0; + $line->product_type = 0; - $this->lines[$xnbp]=$line; + $this->lines[$xnbp] = $line; $this->total_ht += $line->total_ht; $this->total_tva += $line->total_tva; @@ -2470,10 +2470,10 @@ class FactureFournisseur extends CommonInvoice } } - $this->amount_ht = $xnbp*100; - $this->total_ht = $xnbp*100; - $this->total_tva = $xnbp*19.6; - $this->total_ttc = $xnbp*119.6; + $this->amount_ht = $xnbp * 100; + $this->total_ht = $xnbp * 100; + $this->total_tva = $xnbp * 19.6; + $this->total_ttc = $xnbp * 119.6; } // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps @@ -2515,7 +2515,7 @@ class FactureFournisseur extends CommonInvoice else { dol_print_error($this->db); - $this->error=$this->db->error(); + $this->error = $this->db->error(); return -1; } } @@ -2557,7 +2557,7 @@ class FactureFournisseur extends CommonInvoice $object->close_note = ''; // Loop on each line of new invoice - foreach($object->lines as $i => $line) + 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 { @@ -2567,23 +2567,23 @@ class FactureFournisseur extends CommonInvoice // Create clone $object->context['createfromclone'] = 'createfromclone'; - $result=$object->create($user); + $result = $object->create($user); // Other options if ($result < 0) { - $this->error=$object->error; + $this->error = $object->error; $error++; } - if (! $error) + if (!$error) { } unset($object->context['createfromclone']); // End - if (! $error) + if (!$error) { $this->db->commit(); return $object->id; @@ -2615,13 +2615,13 @@ class FactureFournisseur extends CommonInvoice // Set the model on the model name to use if (empty($modele)) { - if (! empty($conf->global->INVOICE_SUPPLIER_ADDON_PDF)) + 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 + $modele = ''; // No default value. For supplier invoice, we allow to disable all PDF generation } } @@ -2715,12 +2715,12 @@ class SupplierInvoiceLine extends CommonObjectLine /** * @var string ID to identify managed object */ - public $element='facture_fourn_det'; + public $element = 'facture_fourn_det'; /** * @var string Name of table without prefix where object is stored */ - public $table_element='facture_fourn_det'; + public $table_element = 'facture_fourn_det'; public $oldline; @@ -2853,7 +2853,7 @@ class SupplierInvoiceLine extends CommonObjectLine */ public function __construct($db) { - $this->db= $db; + $this->db = $db; } /** @@ -2887,18 +2887,18 @@ class SupplierInvoiceLine extends CommonObjectLine $obj = $this->db->fetch_object($query); - $this->id = $obj->rowid; - $this->rowid = $obj->rowid; - $this->fk_facture_fourn = $obj->fk_facture_fourn; + $this->id = $obj->rowid; + $this->rowid = $obj->rowid; + $this->fk_facture_fourn = $obj->fk_facture_fourn; $this->description = $obj->description; - $this->date_start = $obj->date_start; - $this->date_end = $obj->date_end; + $this->date_start = $obj->date_start; + $this->date_end = $obj->date_end; $this->product_ref = $obj->product_ref; $this->ref_supplier = $obj->ref_supplier; $this->libelle = $obj->label; $this->label = $obj->label; $this->product_desc = $obj->product_desc; - $this->subprice = $obj->pu_ht; + $this->subprice = $obj->pu_ht; $this->pu_ht = $obj->pu_ht; $this->pu_ttc = $obj->pu_ttc; $this->tva_tx = $obj->tva_tx; @@ -2970,7 +2970,7 @@ class SupplierInvoiceLine extends CommonObjectLine } } - if (! $error) + if (!$error) { $this->db->commit(); return 1; @@ -2993,10 +2993,10 @@ class SupplierInvoiceLine extends CommonObjectLine global $conf; $pu = price2num($this->pu_ht); - $qty = price2num($this->qty); + $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; @@ -3024,37 +3024,37 @@ class SupplierInvoiceLine extends CommonObjectLine } $sql = "UPDATE ".MAIN_DB_PREFIX."facture_fourn_det SET"; - $sql.= " description ='".$this->db->escape($this->description)."'"; - $sql.= ", ref ='".$this->db->escape($this->ref_supplier ? $this->ref_supplier : $this->ref)."'"; - $sql.= ", date_start = ".($this->date_start != '' ? "'".$this->db->idate($this->date_start)."'" : "null"); - $sql.= ", date_end = ".($this->date_end != '' ? "'".$this->db->idate($this->date_end)."'" : "null"); - $sql.= ", pu_ht = ".price2num($this->pu_ht); - $sql.= ", pu_ttc = ".price2num($this->pu_ttc); - $sql.= ", qty = ".price2num($this->qty); - $sql.= ", remise_percent = ".price2num($this->remise_percent); - $sql.= ", vat_src_code = '".$this->db->escape(empty($this->vat_src_code)?'':$this->vat_src_code)."'"; - $sql.= ", tva_tx = ".price2num($this->tva_tx); - $sql.= ", localtax1_tx = ".price2num($this->localtax1_tx); - $sql.= ", localtax2_tx = ".price2num($this->localtax2_tx); - $sql.= ", localtax1_type = '".$this->db->escape($this->localtax1_type)."'"; - $sql.= ", localtax2_type = '".$this->db->escape($this->localtax2_type)."'"; - $sql.= ", total_ht = ".price2num($this->total_ht); - $sql.= ", tva= ".price2num($this->total_tva); - $sql.= ", total_localtax1= ".price2num($this->total_localtax1); - $sql.= ", total_localtax2= ".price2num($this->total_localtax2); - $sql.= ", total_ttc = ".price2num($this->total_ttc); - $sql.= ", fk_product = ".$fk_product; - $sql.= ", product_type = ".$this->product_type; - $sql.= ", info_bits = ".$this->info_bits; - $sql.= ", fk_unit = ".$fk_unit; + $sql .= " description ='".$this->db->escape($this->description)."'"; + $sql .= ", ref ='".$this->db->escape($this->ref_supplier ? $this->ref_supplier : $this->ref)."'"; + $sql .= ", date_start = ".($this->date_start != '' ? "'".$this->db->idate($this->date_start)."'" : "null"); + $sql .= ", date_end = ".($this->date_end != '' ? "'".$this->db->idate($this->date_end)."'" : "null"); + $sql .= ", pu_ht = ".price2num($this->pu_ht); + $sql .= ", pu_ttc = ".price2num($this->pu_ttc); + $sql .= ", qty = ".price2num($this->qty); + $sql .= ", remise_percent = ".price2num($this->remise_percent); + $sql .= ", vat_src_code = '".$this->db->escape(empty($this->vat_src_code) ? '' : $this->vat_src_code)."'"; + $sql .= ", tva_tx = ".price2num($this->tva_tx); + $sql .= ", localtax1_tx = ".price2num($this->localtax1_tx); + $sql .= ", localtax2_tx = ".price2num($this->localtax2_tx); + $sql .= ", localtax1_type = '".$this->db->escape($this->localtax1_type)."'"; + $sql .= ", localtax2_type = '".$this->db->escape($this->localtax2_type)."'"; + $sql .= ", total_ht = ".price2num($this->total_ht); + $sql .= ", tva= ".price2num($this->total_tva); + $sql .= ", total_localtax1= ".price2num($this->total_localtax1); + $sql .= ", total_localtax2= ".price2num($this->total_localtax2); + $sql .= ", total_ttc = ".price2num($this->total_ttc); + $sql .= ", fk_product = ".$fk_product; + $sql .= ", product_type = ".$this->product_type; + $sql .= ", info_bits = ".$this->info_bits; + $sql .= ", fk_unit = ".$fk_unit; // Multicurrency - $sql.= " , multicurrency_subprice=".price2num($this->multicurrency_subprice).""; - $sql.= " , multicurrency_total_ht=".price2num($this->multicurrency_total_ht).""; - $sql.= " , multicurrency_total_tva=".price2num($this->multicurrency_total_tva).""; - $sql.= " , multicurrency_total_ttc=".price2num($this->multicurrency_total_ttc).""; + $sql .= " , multicurrency_subprice=".price2num($this->multicurrency_subprice).""; + $sql .= " , multicurrency_total_ht=".price2num($this->multicurrency_total_ht).""; + $sql .= " , multicurrency_total_tva=".price2num($this->multicurrency_total_tva).""; + $sql .= " , multicurrency_total_ttc=".price2num($this->multicurrency_total_ttc).""; - $sql.= " WHERE rowid = ".$this->id; + $sql .= " WHERE rowid = ".$this->id; dol_syslog(get_class($this)."::update", LOG_DEBUG); $resql = $this->db->query($sql); @@ -3077,7 +3077,7 @@ class SupplierInvoiceLine extends CommonObjectLine } } - if (! $error && ! $notrigger) + if (!$error && !$notrigger) { global $langs, $user; @@ -3158,70 +3158,70 @@ class SupplierInvoiceLine extends CommonObjectLine // Insertion dans base de la ligne $sql = 'INSERT INTO '.MAIN_DB_PREFIX.$this->table_element; - $sql.= ' (fk_facture_fourn, fk_parent_line, label, description, ref, qty,'; - $sql.= ' vat_src_code, tva_tx, localtax1_tx, localtax2_tx, localtax1_type, localtax2_type,'; - $sql.= ' fk_product, product_type, remise_percent, pu_ht, pu_ttc,'; - $sql.= ' date_start, date_end, fk_code_ventilation, rang, special_code,'; - $sql.= ' info_bits, total_ht, tva, total_ttc, total_localtax1, total_localtax2, fk_unit'; - $sql.= ', fk_multicurrency, multicurrency_code, multicurrency_subprice, multicurrency_total_ht, multicurrency_total_tva, multicurrency_total_ttc'; - $sql.= ')'; - $sql.= " VALUES (".$this->fk_facture_fourn.","; - $sql.= " ".($this->fk_parent_line>0?"'".$this->db->escape($this->fk_parent_line)."'":"null").","; - $sql.= " ".(! empty($this->label)?"'".$this->db->escape($this->label)."'":"null").","; - $sql.= " '".$this->db->escape($this->desc ? $this->desc : $this->description)."',"; - $sql.= " '".$this->db->escape($this->ref_supplier)."',"; - $sql.= " ".price2num($this->qty).","; + $sql .= ' (fk_facture_fourn, fk_parent_line, label, description, ref, qty,'; + $sql .= ' vat_src_code, tva_tx, localtax1_tx, localtax2_tx, localtax1_type, localtax2_type,'; + $sql .= ' fk_product, product_type, remise_percent, pu_ht, pu_ttc,'; + $sql .= ' date_start, date_end, fk_code_ventilation, rang, special_code,'; + $sql .= ' info_bits, total_ht, tva, total_ttc, total_localtax1, total_localtax2, fk_unit'; + $sql .= ', fk_multicurrency, multicurrency_code, multicurrency_subprice, multicurrency_total_ht, multicurrency_total_tva, multicurrency_total_ttc'; + $sql .= ')'; + $sql .= " VALUES (".$this->fk_facture_fourn.","; + $sql .= " ".($this->fk_parent_line > 0 ? "'".$this->db->escape($this->fk_parent_line)."'" : "null").","; + $sql .= " ".(!empty($this->label) ? "'".$this->db->escape($this->label)."'" : "null").","; + $sql .= " '".$this->db->escape($this->desc ? $this->desc : $this->description)."',"; + $sql .= " '".$this->db->escape($this->ref_supplier)."',"; + $sql .= " ".price2num($this->qty).","; - $sql.= " ".(empty($this->vat_src_code)?"''":"'".$this->db->escape($this->vat_src_code)."'").","; - $sql.= " ".price2num($this->tva_tx).","; - $sql.= " ".price2num($this->localtax1_tx).","; - $sql.= " ".price2num($this->localtax2_tx).","; - $sql.= " '".$this->db->escape($this->localtax1_type)."',"; - $sql.= " '".$this->db->escape($this->localtax2_type)."',"; - $sql.= ' '.(! empty($this->fk_product)?$this->fk_product:"null").','; - $sql.= " ".$this->product_type.","; - $sql.= " ".price2num($this->remise_percent).","; - $sql.= " ".price2num($this->subprice).","; - $sql.= " ".(! empty($this->qty)?price2num($this->total_ttc / $this->qty):price2num($this->total_ttc)).","; - $sql.= " ".(! empty($this->date_start)?"'".$this->db->idate($this->date_start)."'":"null").","; - $sql.= " ".(! empty($this->date_end)?"'".$this->db->idate($this->date_end)."'":"null").","; - $sql.= ' '.(! empty($this->fk_code_ventilation)?$this->fk_code_ventilation:0).','; - $sql.= ' '.$this->rang.','; - $sql.= ' '.$this->special_code.','; - $sql.= " '".$this->db->escape($this->info_bits)."',"; - $sql.= " ".price2num($this->total_ht).","; - $sql.= " ".price2num($this->total_tva).","; - $sql.= " ".price2num($this->total_ttc).","; - $sql.= " ".price2num($this->total_localtax1).","; - $sql.= " ".price2num($this->total_localtax2); + $sql .= " ".(empty($this->vat_src_code) ? "''" : "'".$this->db->escape($this->vat_src_code)."'").","; + $sql .= " ".price2num($this->tva_tx).","; + $sql .= " ".price2num($this->localtax1_tx).","; + $sql .= " ".price2num($this->localtax2_tx).","; + $sql .= " '".$this->db->escape($this->localtax1_type)."',"; + $sql .= " '".$this->db->escape($this->localtax2_type)."',"; + $sql .= ' '.(!empty($this->fk_product) ? $this->fk_product : "null").','; + $sql .= " ".$this->product_type.","; + $sql .= " ".price2num($this->remise_percent).","; + $sql .= " ".price2num($this->subprice).","; + $sql .= " ".(!empty($this->qty) ?price2num($this->total_ttc / $this->qty) : price2num($this->total_ttc)).","; + $sql .= " ".(!empty($this->date_start) ? "'".$this->db->idate($this->date_start)."'" : "null").","; + $sql .= " ".(!empty($this->date_end) ? "'".$this->db->idate($this->date_end)."'" : "null").","; + $sql .= ' '.(!empty($this->fk_code_ventilation) ? $this->fk_code_ventilation : 0).','; + $sql .= ' '.$this->rang.','; + $sql .= ' '.$this->special_code.','; + $sql .= " '".$this->db->escape($this->info_bits)."',"; + $sql .= " ".price2num($this->total_ht).","; + $sql .= " ".price2num($this->total_tva).","; + $sql .= " ".price2num($this->total_ttc).","; + $sql .= " ".price2num($this->total_localtax1).","; + $sql .= " ".price2num($this->total_localtax2); $sql .= ", ".(!$this->fk_unit ? 'NULL' : $this->fk_unit); - $sql.= ", ".(int) $this->fk_multicurrency; - $sql.= ", '".$this->db->escape($this->multicurrency_code)."'"; - $sql.= ", ".price2num($this->multicurrency_subprice); - $sql.= ", ".price2num($this->multicurrency_total_ht); - $sql.= ", ".price2num($this->multicurrency_total_tva); - $sql.= ", ".price2num($this->multicurrency_total_ttc); - $sql.= ')'; + $sql .= ", ".(int) $this->fk_multicurrency; + $sql .= ", '".$this->db->escape($this->multicurrency_code)."'"; + $sql .= ", ".price2num($this->multicurrency_subprice); + $sql .= ", ".price2num($this->multicurrency_total_ht); + $sql .= ", ".price2num($this->multicurrency_total_tva); + $sql .= ", ".price2num($this->multicurrency_total_ttc); + $sql .= ')'; - $resql=$this->db->query($sql); + $resql = $this->db->query($sql); if ($resql) { - $this->id=$this->db->last_insert_id(MAIN_DB_PREFIX.$this->table_element); - $this->rowid=$this->id; // backward compatibility + $this->id = $this->db->last_insert_id(MAIN_DB_PREFIX.$this->table_element); + $this->rowid = $this->id; // backward compatibility if (empty($conf->global->MAIN_EXTRAFIELDS_DISABLED)) // For avoid conflicts if trigger used { - $result=$this->insertExtraFields(); + $result = $this->insertExtraFields(); if ($result < 0) { $error++; } } - if (! $error && ! $notrigger) + if (!$error && !$notrigger) { // Call trigger - $result=$this->call_trigger('LINEBILL_SUPPLIER_CREATE', $user); + $result = $this->call_trigger('LINEBILL_SUPPLIER_CREATE', $user); if ($result < 0) { $this->db->rollback(); @@ -3235,7 +3235,7 @@ class SupplierInvoiceLine extends CommonObjectLine } else { - $this->error=$this->db->error(); + $this->error = $this->db->error(); $this->db->rollback(); return -2; } @@ -3254,16 +3254,16 @@ class SupplierInvoiceLine extends CommonObjectLine // Mise a jour ligne en base $sql = "UPDATE ".MAIN_DB_PREFIX."facture_fourn_det SET"; - $sql.= " total_ht='".price2num($this->total_ht)."'"; - $sql.= ", tva='".price2num($this->total_tva)."'"; - $sql.= ", total_localtax1='".price2num($this->total_localtax1)."'"; - $sql.= ", total_localtax2='".price2num($this->total_localtax2)."'"; - $sql.= ", total_ttc='".price2num($this->total_ttc)."'"; - $sql.= " WHERE rowid = ".$this->rowid; + $sql .= " total_ht='".price2num($this->total_ht)."'"; + $sql .= ", tva='".price2num($this->total_tva)."'"; + $sql .= ", total_localtax1='".price2num($this->total_localtax1)."'"; + $sql .= ", total_localtax2='".price2num($this->total_localtax2)."'"; + $sql .= ", total_ttc='".price2num($this->total_ttc)."'"; + $sql .= " WHERE rowid = ".$this->rowid; dol_syslog("FactureFournisseurLigne.class.php::update_total", LOG_DEBUG); - $resql=$this->db->query($sql); + $resql = $this->db->query($sql); if ($resql) { $this->db->commit(); @@ -3271,7 +3271,7 @@ class SupplierInvoiceLine extends CommonObjectLine } else { - $this->error=$this->db->error(); + $this->error = $this->db->error(); $this->db->rollback(); return -2; } diff --git a/htdocs/fourn/class/fournisseur.product.class.php b/htdocs/fourn/class/fournisseur.product.class.php index 8c750f2f425..069380249db 100644 --- a/htdocs/fourn/class/fournisseur.product.class.php +++ b/htdocs/fourn/class/fournisseur.product.class.php @@ -46,9 +46,9 @@ class ProductFournisseur extends Product /** * @var string Error code (or message) */ - public $error=''; + public $error = ''; - public $product_fourn_price_id; // id of ligne product-supplier + public $product_fourn_price_id; // id of ligne product-supplier /** * @var int ID @@ -61,18 +61,18 @@ class ProductFournisseur extends Product */ public $fourn_ref; public $delivery_time_days; - public $ref_supplier; // ref supplier (can be set by get_buyprice) + public $ref_supplier; // ref supplier (can be set by get_buyprice) public $desc_supplier; - public $vatrate_supplier; // default vat rate for this supplier/qty/product (can be set by get_buyprice) + public $vatrate_supplier; // default vat rate for this supplier/qty/product (can be set by get_buyprice) - public $fourn_id; //supplier id - public $fourn_qty; // quantity for price (can be set by get_buyprice) - public $fourn_pu; // unit price for quantity (can be set by get_buyprice) + public $fourn_id; //supplier id + public $fourn_qty; // quantity for price (can be set by get_buyprice) + public $fourn_pu; // unit price for quantity (can be set by get_buyprice) - public $fourn_price; // price for quantity - public $fourn_remise_percent; // discount for quantity (percent) - public $fourn_remise; // discount for quantity (amount) - public $product_fourn_id; // product-supplier id + public $fourn_price; // price for quantity + public $fourn_remise_percent; // discount for quantity (percent) + public $fourn_remise; // discount for quantity (amount) + public $product_fourn_id; // product-supplier id /** * @var int ID user_id - user who created/updated supplier price @@ -93,8 +93,8 @@ class ProductFournisseur extends Product */ public $fk_supplier_price_expression; - public $supplier_reputation; // reputation of supplier - public $reputations=array(); // list of available supplier reputations + public $supplier_reputation; // reputation of supplier + public $reputations = array(); // list of available supplier reputations // Multicurreny public $fourn_multicurrency_id; @@ -114,7 +114,7 @@ class ProductFournisseur extends Product $this->db = $db; $langs->load("suppliers"); - $this->reputations= array('-1'=>'', 'FAVORITE'=>$langs->trans('Favorite'),'NOTTHGOOD'=>$langs->trans('NotTheGoodQualitySupplier'), 'DONOTORDER'=>$langs->trans('DoNotOrderThisProductToThisSupplier')); + $this->reputations = array('-1'=>'', 'FAVORITE'=>$langs->trans('Favorite'), 'NOTTHGOOD'=>$langs->trans('NotTheGoodQualitySupplier'), 'DONOTORDER'=>$langs->trans('DoNotOrderThisProductToThisSupplier')); } @@ -129,19 +129,19 @@ class ProductFournisseur extends Product public function remove_fournisseur($id_fourn) { // phpcs:enable - $ok=1; + $ok = 1; $this->db->begin(); $sql = "DELETE FROM ".MAIN_DB_PREFIX."product_fournisseur_price"; - $sql.= " WHERE fk_product = ".$this->id." AND fk_soc = ".$id_fourn; + $sql .= " WHERE fk_product = ".$this->id." AND fk_soc = ".$id_fourn; dol_syslog(get_class($this)."::remove_fournisseur", LOG_DEBUG); - $resql2=$this->db->query($sql); - if (! $resql2) + $resql2 = $this->db->query($sql); + if (!$resql2) { - $this->error=$this->db->lasterror(); - $ok=0; + $this->error = $this->db->lasterror(); + $ok = 0; } if ($ok) @@ -169,25 +169,25 @@ class ProductFournisseur extends Product // phpcs:enable global $conf, $user; - $error=0; + $error = 0; $this->db->begin(); // Call trigger - $result=$this->call_trigger('SUPPLIER_PRODUCT_BUYPRICE_DELETE', $user); + $result = $this->call_trigger('SUPPLIER_PRODUCT_BUYPRICE_DELETE', $user); if ($result < 0) $error++; // End call triggers if (empty($error)) { $sql = "DELETE FROM ".MAIN_DB_PREFIX."product_fournisseur_price"; - $sql.= " WHERE rowid = ".$rowid; + $sql .= " WHERE rowid = ".$rowid; dol_syslog(get_class($this)."::remove_product_fournisseur_price", LOG_DEBUG); $resql = $this->db->query($sql); if (!$resql) { - $this->error=$this->db->lasterror(); + $this->error = $this->db->lasterror(); $error++; } } @@ -238,66 +238,66 @@ 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 (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)); + $buyprice = $buyprice / (1 + ($ttx / 100)); } // Multicurrency if ($conf->multicurrency->enabled) { - if (empty($multicurrency_tx)) $multicurrency_tx=1; - if (empty($multicurrency_buyprice)) $multicurrency_buyprice=0; + if (empty($multicurrency_tx)) $multicurrency_tx = 1; + if (empty($multicurrency_buyprice)) $multicurrency_buyprice = 0; - if (empty($multicurrency_buyprice)) $multicurrency_buyprice=0; + if (empty($multicurrency_buyprice)) $multicurrency_buyprice = 0; if ($multicurrency_price_base_type == 'TTC') { $ttx = $tva_tx; - $multicurrency_buyprice = $multicurrency_buyprice/(1+($ttx/100)); + $multicurrency_buyprice = $multicurrency_buyprice / (1 + ($ttx / 100)); } - $multicurrency_buyprice=price2num($multicurrency_buyprice, 'MU'); - $multicurrency_unitBuyPrice=price2num($multicurrency_buyprice/$qty, 'MU'); + $multicurrency_buyprice = price2num($multicurrency_buyprice, 'MU'); + $multicurrency_unitBuyPrice = price2num($multicurrency_buyprice / $qty, 'MU'); - $buyprice=$multicurrency_buyprice/$multicurrency_tx; + $buyprice = $multicurrency_buyprice / $multicurrency_tx; $fk_multicurrency = MultiCurrency::getIdFromCode($this->db, $multicurrency_code); } - $buyprice=price2num($buyprice, 'MU'); - $charges=price2num($charges, 'MU'); - $qty=price2num($qty, 'MS'); - $unitBuyPrice = price2num($buyprice/$qty, 'MU'); + $buyprice = price2num($buyprice, 'MU'); + $charges = price2num($charges, 'MU'); + $qty = price2num($qty, 'MS'); + $unitBuyPrice = price2num($buyprice / $qty, 'MU'); - $error=0; - $now=dol_now(); + $error = 0; + $now = dol_now(); $newvat = $tva_tx; if (count($localtaxes_array) > 0) { - $localtaxtype1=$localtaxes_array['0']; - $localtax1=$localtaxes_array['1']; - $localtaxtype2=$localtaxes_array['2']; - $localtax2=$localtaxes_array['3']; + $localtaxtype1 = $localtaxes_array['0']; + $localtax1 = $localtaxes_array['1']; + $localtaxtype2 = $localtaxes_array['2']; + $localtax2 = $localtaxes_array['3']; } else // old method. deprecated because ot can't retreive type { - $localtaxtype1='0'; - $localtax1=get_localtax($newvat, 1); - $localtaxtype2='0'; - $localtax2=get_localtax($newvat, 2); + $localtaxtype1 = '0'; + $localtax1 = get_localtax($newvat, 1); + $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)) { } @@ -310,7 +310,7 @@ class ProductFournisseur extends Product if (is_array($logPrices) && count($logPrices) == 0) { $currentPfp = new self($this->db); - $result = $currentPfp->fetch_product_fournisseur_price($this->product_fourn_price_id); + $result = $currentPfp->fetch_product_fournisseur_price($this->product_fourn_price_id); if ($result > 0 && $currentPfp->fourn_price != 0) { $currentPfpUser = new User($this->db); @@ -331,35 +331,35 @@ class ProductFournisseur extends Product } } $sql = "UPDATE ".MAIN_DB_PREFIX."product_fournisseur_price"; - $sql.= " SET fk_user = " . $user->id." ,"; - $sql.= " ref_fourn = '" . $this->db->escape($ref_fourn) . "',"; - $sql.= " desc_fourn = '" . $this->db->escape($desc_fourn) . "',"; - $sql.= " price = ".$buyprice.","; - $sql.= " quantity = ".$qty.","; - $sql.= " remise_percent = ".$remise_percent.","; - $sql.= " remise = ".$remise.","; - $sql.= " unitprice = ".$unitBuyPrice.","; - $sql.= " fk_availability = ".$availability.","; - $sql.= " multicurrency_price = ".(isset($multicurrency_buyprice)?"'".$this->db->escape(price2num($multicurrency_buyprice))."'":'null').","; - $sql.= " multicurrency_unitprice = ".(isset($multicurrency_unitBuyPrice)?"'".$this->db->escape(price2num($multicurrency_unitBuyPrice))."'":'null').","; - $sql.= " multicurrency_tx = ".(isset($multicurrency_tx)?"'".$this->db->escape($multicurrency_tx)."'":'1').","; - $sql.= " fk_multicurrency = ".(isset($fk_multicurrency)?"'".$this->db->escape($fk_multicurrency)."'":'null').","; - $sql.= " multicurrency_code = ".(isset($multicurrency_code)?"'".$this->db->escape($multicurrency_code)."'":'null').","; - $sql.= " entity = ".$conf->entity.","; - $sql.= " tva_tx = ".price2num($tva_tx).","; + $sql .= " SET fk_user = ".$user->id." ,"; + $sql .= " ref_fourn = '".$this->db->escape($ref_fourn)."',"; + $sql .= " desc_fourn = '".$this->db->escape($desc_fourn)."',"; + $sql .= " price = ".$buyprice.","; + $sql .= " quantity = ".$qty.","; + $sql .= " remise_percent = ".$remise_percent.","; + $sql .= " remise = ".$remise.","; + $sql .= " unitprice = ".$unitBuyPrice.","; + $sql .= " fk_availability = ".$availability.","; + $sql .= " multicurrency_price = ".(isset($multicurrency_buyprice) ? "'".$this->db->escape(price2num($multicurrency_buyprice))."'" : 'null').","; + $sql .= " multicurrency_unitprice = ".(isset($multicurrency_unitBuyPrice) ? "'".$this->db->escape(price2num($multicurrency_unitBuyPrice))."'" : 'null').","; + $sql .= " multicurrency_tx = ".(isset($multicurrency_tx) ? "'".$this->db->escape($multicurrency_tx)."'" : '1').","; + $sql .= " fk_multicurrency = ".(isset($fk_multicurrency) ? "'".$this->db->escape($fk_multicurrency)."'" : 'null').","; + $sql .= " multicurrency_code = ".(isset($multicurrency_code) ? "'".$this->db->escape($multicurrency_code)."'" : 'null').","; + $sql .= " entity = ".$conf->entity.","; + $sql .= " tva_tx = ".price2num($tva_tx).","; // TODO Add localtax1 and localtax2 //$sql.= " localtax1_tx=".($localtax1>=0?$localtax1:'NULL').","; //$sql.= " localtax2_tx=".($localtax2>=0?$localtax2:'NULL').","; //$sql.= " localtax1_type=".($localtaxtype1!=''?"'".$localtaxtype1."'":"'0'").","; //$sql.= " localtax2_type=".($localtaxtype2!=''?"'".$localtaxtype2."'":"'0'").","; - $sql.= " default_vat_code=".($newdefaultvatcode?"'".$this->db->escape($newdefaultvatcode)."'":"null").","; - $sql.= " info_bits = ".$newnpr.","; - $sql.= " charges = ".$charges.","; // deprecated - $sql.= " delivery_time_days = ".($delivery_time_days != '' ? $delivery_time_days : 'null').","; - $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)."'"); - $sql.= " WHERE rowid = ".$this->product_fourn_price_id; + $sql .= " default_vat_code=".($newdefaultvatcode ? "'".$this->db->escape($newdefaultvatcode)."'" : "null").","; + $sql .= " info_bits = ".$newnpr.","; + $sql .= " charges = ".$charges.","; // deprecated + $sql .= " delivery_time_days = ".($delivery_time_days != '' ? $delivery_time_days : 'null').","; + $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)."'"); + $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); @@ -367,10 +367,10 @@ class ProductFournisseur extends Product if ($resql) { // Call trigger - $result=$this->call_trigger('SUPPLIER_PRODUCT_BUYPRICE_UPDATE', $user); + $result = $this->call_trigger('SUPPLIER_PRODUCT_BUYPRICE_UPDATE', $user); 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) { @@ -390,7 +390,7 @@ class ProductFournisseur extends Product } else { - $this->error=$this->db->error()." sql=".$sql; + $this->error = $this->db->error()." sql=".$sql; $this->db->rollback(); return -2; } @@ -398,57 +398,57 @@ class ProductFournisseur extends Product else { - dol_syslog(get_class($this) . '::update_buyprice without knowing id of line, so we delete from company, quantity and supplier_ref and insert again', LOG_DEBUG); + dol_syslog(get_class($this).'::update_buyprice without knowing id of line, so we delete from company, quantity and supplier_ref and insert again', LOG_DEBUG); // Delete price for this quantity - $sql = "DELETE FROM " . MAIN_DB_PREFIX . "product_fournisseur_price"; - $sql .= " WHERE fk_soc = " . $fourn->id . " AND ref_fourn = '" . $this->db->escape($ref_fourn) . "' AND quantity = " . $qty . " AND entity = " . $conf->entity; + $sql = "DELETE FROM ".MAIN_DB_PREFIX."product_fournisseur_price"; + $sql .= " WHERE fk_soc = ".$fourn->id." AND ref_fourn = '".$this->db->escape($ref_fourn)."' AND quantity = ".$qty." AND entity = ".$conf->entity; $resql = $this->db->query($sql); if ($resql) { // Add price for this quantity to supplier - $sql = "INSERT INTO " . MAIN_DB_PREFIX . "product_fournisseur_price("; - $sql.= " multicurrency_price, multicurrency_unitprice, multicurrency_tx, fk_multicurrency, multicurrency_code,"; + $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)"; $sql .= " values("; - $sql.= (isset($multicurrency_buyprice)?"'".$this->db->escape(price2num($multicurrency_buyprice))."'":'null').","; - $sql.= (isset($multicurrency_unitBuyPrice)?"'".$this->db->escape(price2num($multicurrency_unitBuyPrice))."'":'null').","; - $sql.= (isset($multicurrency_tx)?"'".$this->db->escape($multicurrency_tx)."'":'1').","; - $sql.= (isset($fk_multicurrency)?"'".$this->db->escape($fk_multicurrency)."'":'null').","; - $sql.= (isset($multicurrency_code)?"'".$this->db->escape($multicurrency_code)."'":'null').","; - $sql .= " '" . $this->db->idate($now) . "',"; - $sql .= " " . $this->id . ","; - $sql .= " " . $fourn->id . ","; - $sql .= " '" . $this->db->escape($ref_fourn) . "',"; - $sql .= " '" . $this->db->escape($desc_fourn) . "',"; - $sql .= " " . $user->id . ","; - $sql .= " " . $buyprice . ","; - $sql .= " " . $qty . ","; - $sql .= " " . $remise_percent . ","; - $sql .= " " . $remise . ","; - $sql .= " " . $unitBuyPrice . ","; - $sql .= " " . $tva_tx . ","; - $sql .= " " . $charges . ","; - $sql .= " " . $availability . ","; - $sql .= " ".($newdefaultvatcode?"'".$this->db->escape($newdefaultvatcode)."'":"null").","; - $sql .= " " . $newnpr . ","; - $sql .= $conf->entity . ","; - $sql .= $delivery_time_days . ","; - $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) . "'"); + $sql .= (isset($multicurrency_buyprice) ? "'".$this->db->escape(price2num($multicurrency_buyprice))."'" : 'null').","; + $sql .= (isset($multicurrency_unitBuyPrice) ? "'".$this->db->escape(price2num($multicurrency_unitBuyPrice))."'" : 'null').","; + $sql .= (isset($multicurrency_tx) ? "'".$this->db->escape($multicurrency_tx)."'" : '1').","; + $sql .= (isset($fk_multicurrency) ? "'".$this->db->escape($fk_multicurrency)."'" : 'null').","; + $sql .= (isset($multicurrency_code) ? "'".$this->db->escape($multicurrency_code)."'" : 'null').","; + $sql .= " '".$this->db->idate($now)."',"; + $sql .= " ".$this->id.","; + $sql .= " ".$fourn->id.","; + $sql .= " '".$this->db->escape($ref_fourn)."',"; + $sql .= " '".$this->db->escape($desc_fourn)."',"; + $sql .= " ".$user->id.","; + $sql .= " ".$buyprice.","; + $sql .= " ".$qty.","; + $sql .= " ".$remise_percent.","; + $sql .= " ".$remise.","; + $sql .= " ".$unitBuyPrice.","; + $sql .= " ".$tva_tx.","; + $sql .= " ".$charges.","; + $sql .= " ".$availability.","; + $sql .= " ".($newdefaultvatcode ? "'".$this->db->escape($newdefaultvatcode)."'" : "null").","; + $sql .= " ".$newnpr.","; + $sql .= $conf->entity.","; + $sql .= $delivery_time_days.","; + $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)."'"); $sql .= ")"; $idinserted = 0; $resql = $this->db->query($sql); if ($resql) { - $idinserted = $this->db->last_insert_id(MAIN_DB_PREFIX . "product_fournisseur_price"); + $idinserted = $this->db->last_insert_id(MAIN_DB_PREFIX."product_fournisseur_price"); } else { $error++; } - if (! $error && empty($conf->global->PRODUCT_PRICE_SUPPLIER_NO_LOG)) { + if (!$error && empty($conf->global->PRODUCT_PRICE_SUPPLIER_NO_LOG)) { // Add record into log table $result = $this->logPrice($user, $now, $buyprice, $qty, $multicurrency_buyprice, $multicurrency_unitBuyPrice, $multicurrency_tx, $fk_multicurrenc, $multicurrency_code); if ($result < 0) { @@ -456,7 +456,7 @@ class ProductFournisseur extends Product } } - if (! $error) { + if (!$error) { // Call trigger $result = $this->call_trigger('SUPPLIER_PRODUCT_BUYPRICE_CREATE', $user); if ($result < 0) @@ -472,14 +472,14 @@ class ProductFournisseur extends Product return -1; } } else { - $this->error = $this->db->lasterror() . " sql=" . $sql; + $this->error = $this->db->lasterror()." sql=".$sql; $this->db->rollback(); return -2; } } else { - $this->error = $this->db->lasterror() . " sql=" . $sql; + $this->error = $this->db->lasterror()." sql=".$sql; $this->db->rollback(); - return - 1; + return -1; } } } @@ -498,12 +498,12 @@ class ProductFournisseur extends Product global $conf; $sql = "SELECT pfp.rowid, pfp.price, pfp.quantity, pfp.unitprice, pfp.remise_percent, pfp.remise, pfp.tva_tx, pfp.default_vat_code, pfp.info_bits as fourn_tva_npr, pfp.fk_availability,"; - $sql.= " pfp.fk_soc, pfp.ref_fourn, pfp.desc_fourn, pfp.fk_product, pfp.charges, pfp.fk_supplier_price_expression, pfp.delivery_time_days,"; - $sql.= " pfp.supplier_reputation, pfp.fk_user, pfp.datec,"; - $sql.= " pfp.multicurrency_price, pfp.multicurrency_unitprice, pfp.multicurrency_tx, pfp.fk_multicurrency, pfp.multicurrency_code,"; - $sql.=" pfp.barcode, pfp.fk_barcode_type"; - $sql.= " FROM ".MAIN_DB_PREFIX."product_fournisseur_price as pfp"; - $sql.= " WHERE pfp.rowid = ".$rowid; + $sql .= " pfp.fk_soc, pfp.ref_fourn, pfp.desc_fourn, pfp.fk_product, pfp.charges, pfp.fk_supplier_price_expression, pfp.delivery_time_days,"; + $sql .= " pfp.supplier_reputation, pfp.fk_user, pfp.datec,"; + $sql .= " pfp.multicurrency_price, pfp.multicurrency_unitprice, pfp.multicurrency_tx, pfp.fk_multicurrency, pfp.multicurrency_code,"; + $sql .= " pfp.barcode, pfp.fk_barcode_type"; + $sql .= " FROM ".MAIN_DB_PREFIX."product_fournisseur_price as pfp"; + $sql .= " WHERE pfp.rowid = ".(int) $rowid; dol_syslog(get_class($this)."::fetch_product_fournisseur_price", LOG_DEBUG); $resql = $this->db->query($sql); @@ -512,16 +512,16 @@ class ProductFournisseur extends Product $obj = $this->db->fetch_object($resql); if ($obj) { - $this->product_fourn_price_id = $rowid; - $this->id = $obj->fk_product; + $this->product_fourn_price_id = $rowid; + $this->id = $obj->fk_product; $this->fk_product = $obj->fk_product; - $this->product_id = $obj->fk_product; // deprecated + $this->product_id = $obj->fk_product; // deprecated $this->fourn_id = $obj->fk_soc; $this->fourn_ref = $obj->ref_fourn; // deprecated $this->ref_supplier = $obj->ref_fourn; $this->desc_supplier = $obj->desc_fourn; - $this->fourn_price = $obj->price; - $this->fourn_charges = $obj->charges; // deprecated + $this->fourn_price = $obj->price; + $this->fourn_charges = $obj->charges; // deprecated $this->fourn_qty = $obj->quantity; $this->fourn_remise_percent = $obj->remise_percent; $this->fourn_remise = $obj->remise; @@ -529,9 +529,9 @@ class ProductFournisseur extends Product $this->fourn_tva_tx = $obj->tva_tx; $this->fourn_tva_npr = $obj->fourn_tva_npr; // Add also localtaxes - $this->fk_availability = $obj->fk_availability; - $this->delivery_time_days = $obj->delivery_time_days; - $this->fk_supplier_price_expression = $obj->fk_supplier_price_expression; + $this->fk_availability = $obj->fk_availability; + $this->delivery_time_days = $obj->delivery_time_days; + $this->fk_supplier_price_expression = $obj->fk_supplier_price_expression; $this->supplier_reputation = $obj->supplier_reputation; $this->default_vat_code = $obj->default_vat_code; $this->user_id = $obj->fk_user; @@ -541,7 +541,7 @@ class ProductFournisseur extends Product $this->fourn_multicurrency_tx = $obj->multicurrency_tx; $this->fourn_multicurrency_id = $obj->fk_multicurrency; $this->fourn_multicurrency_code = $obj->multicurrency_code; - if($conf->barcode->enabled) { + if ($conf->barcode->enabled) { $this->fourn_barcode = $obj->barcode; $this->fourn_fk_barcode_type = $obj->fk_barcode_type; } @@ -552,13 +552,13 @@ class ProductFournisseur extends Product 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'); + $this->fourn_unitprice = price2num($this->fourn_price / $this->fourn_qty, 'MU'); } else { - $this->fourn_unitprice=""; + $this->fourn_unitprice = ""; } } } @@ -572,7 +572,7 @@ class ProductFournisseur extends Product } else { - $this->error=$this->db->error(); + $this->error = $this->db->error(); return -1; } } @@ -595,18 +595,18 @@ class ProductFournisseur extends Product global $conf; $sql = "SELECT s.nom as supplier_name, s.rowid as fourn_id,"; - $sql.= " pfp.rowid as product_fourn_pri_id, pfp.ref_fourn, pfp.desc_fourn, pfp.fk_product as product_fourn_id, pfp.fk_supplier_price_expression,"; - $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"; - $sql.= " FROM ".MAIN_DB_PREFIX."product_fournisseur_price as pfp, ".MAIN_DB_PREFIX."societe as s"; - $sql.= " WHERE pfp.entity IN (".getEntity('productsupplierprice').")"; - $sql.= " AND pfp.fk_soc = s.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); - $sql.=$this->db->plimit($limit, $offset); + $sql .= " pfp.rowid as product_fourn_pri_id, pfp.ref_fourn, pfp.desc_fourn, pfp.fk_product as product_fourn_id, pfp.fk_supplier_price_expression,"; + $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"; + $sql .= " FROM ".MAIN_DB_PREFIX."product_fournisseur_price as pfp, ".MAIN_DB_PREFIX."societe as s"; + $sql .= " WHERE pfp.entity IN (".getEntity('productsupplierprice').")"; + $sql .= " AND pfp.fk_soc = s.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); + $sql .= $this->db->plimit($limit, $offset); dol_syslog(get_class($this)."::list_product_fournisseur_price", LOG_DEBUG); $resql = $this->db->query($sql); @@ -619,26 +619,26 @@ class ProductFournisseur extends Product //define base attribute $prodfourn = new ProductFournisseur($this->db); - $prodfourn->product_fourn_price_id = $record["product_fourn_pri_id"]; - $prodfourn->product_fourn_id = $record["product_fourn_id"]; - $prodfourn->fourn_ref = $record["ref_fourn"]; + $prodfourn->product_fourn_price_id = $record["product_fourn_pri_id"]; + $prodfourn->product_fourn_id = $record["product_fourn_id"]; + $prodfourn->fourn_ref = $record["ref_fourn"]; $prodfourn->ref_supplier = $record["ref_fourn"]; - $prodfourn->desc_supplier = $record["desc_fourn"]; + $prodfourn->desc_supplier = $record["desc_fourn"]; $prodfourn->fourn_price = $record["price"]; - $prodfourn->fourn_qty = $record["quantity"]; - $prodfourn->fourn_remise_percent = $record["remise_percent"]; - $prodfourn->fourn_remise = $record["remise"]; - $prodfourn->fourn_unitprice = $record["unitprice"]; - $prodfourn->fourn_charges = $record["charges"]; // deprecated - $prodfourn->fourn_tva_tx = $record["tva_tx"]; + $prodfourn->fourn_qty = $record["quantity"]; + $prodfourn->fourn_remise_percent = $record["remise_percent"]; + $prodfourn->fourn_remise = $record["remise"]; + $prodfourn->fourn_unitprice = $record["unitprice"]; + $prodfourn->fourn_charges = $record["charges"]; // deprecated + $prodfourn->fourn_tva_tx = $record["tva_tx"]; $prodfourn->fourn_id = $record["fourn_id"]; - $prodfourn->fourn_name = $record["supplier_name"]; + $prodfourn->fourn_name = $record["supplier_name"]; $prodfourn->fk_availability = $record["fk_availability"]; $prodfourn->delivery_time_days = $record["delivery_time_days"]; $prodfourn->id = $prodid; $prodfourn->fourn_tva_npr = $record["info_bits"]; - $prodfourn->fk_supplier_price_expression = $record["fk_supplier_price_expression"]; - $prodfourn->supplier_reputation = $record["supplier_reputation"]; + $prodfourn->fk_supplier_price_expression = $record["fk_supplier_price_expression"]; + $prodfourn->supplier_reputation = $record["supplier_reputation"]; $prodfourn->fourn_date_creation = $this->db->jdate($record['datec']); $prodfourn->fourn_date_modification = $this->db->jdate($record['tms']); @@ -648,9 +648,9 @@ class ProductFournisseur extends Product $prodfourn->fourn_multicurrency_id = $record["fk_multicurrency"]; $prodfourn->fourn_multicurrency_code = $record["multicurrency_code"]; - if($conf->barcode->enabled){ - $prodfourn->barcode = $record["barcode"]; - $prodfourn->fk_barcode_type = $record["fk_barcode_type"]; + if ($conf->barcode->enabled) { + $prodfourn->barcode = $record["barcode"]; + $prodfourn->fk_barcode_type = $record["fk_barcode_type"]; } if (!empty($conf->dynamicprices->enabled) && !empty($prodfourn->fk_supplier_price_expression)) { @@ -664,17 +664,17 @@ class ProductFournisseur extends Product if (!isset($prodfourn->fourn_unitprice)) { - if ($prodfourn->fourn_qty!=0) + if ($prodfourn->fourn_qty != 0) { - $prodfourn->fourn_unitprice = price2num($prodfourn->fourn_price/$prodfourn->fourn_qty, 'MU'); + $prodfourn->fourn_unitprice = price2num($prodfourn->fourn_price / $prodfourn->fourn_qty, 'MU'); } else { - $prodfourn->fourn_unitprice=""; + $prodfourn->fourn_unitprice = ""; } } - $retarray[]=$prodfourn; + $retarray[] = $prodfourn; } $this->db->free($resql); @@ -682,7 +682,7 @@ class ProductFournisseur extends Product } else { - $this->error=$this->db->error(); + $this->error = $this->db->error(); return -1; } } @@ -717,7 +717,7 @@ class ProductFournisseur extends Product $this->fourn_unitprice = ''; $this->fourn_id = ''; $this->fourn_name = ''; - $this->delivery_time_days = ''; + $this->delivery_time_days = ''; $this->id = ''; $this->fourn_multicurrency_price = ''; @@ -727,18 +727,18 @@ class ProductFournisseur extends Product $this->fourn_multicurrency_code = ''; $sql = "SELECT s.nom as supplier_name, s.rowid as fourn_id,"; - $sql.= " pfp.rowid as product_fourn_price_id, pfp.ref_fourn,"; - $sql.= " pfp.price, pfp.quantity, pfp.unitprice, pfp.tva_tx, pfp.charges,"; - $sql.= " pfp.remise, pfp.remise_percent, pfp.fk_supplier_price_expression, pfp.delivery_time_days"; - $sql.= " ,pfp.multicurrency_price, pfp.multicurrency_unitprice, pfp.multicurrency_tx, pfp.fk_multicurrency, pfp.multicurrency_code"; - $sql.= " FROM ".MAIN_DB_PREFIX."societe as s, ".MAIN_DB_PREFIX."product_fournisseur_price as pfp"; - $sql.= " WHERE s.entity IN (".getEntity('societe').")"; - $sql.= " AND pfp.entity = ".$conf->entity; // only current entity - $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; + $sql .= " pfp.rowid as product_fourn_price_id, pfp.ref_fourn,"; + $sql .= " pfp.price, pfp.quantity, pfp.unitprice, pfp.tva_tx, pfp.charges,"; + $sql .= " pfp.remise, pfp.remise_percent, pfp.fk_supplier_price_expression, pfp.delivery_time_days"; + $sql .= " ,pfp.multicurrency_price, pfp.multicurrency_unitprice, pfp.multicurrency_tx, pfp.fk_multicurrency, pfp.multicurrency_code"; + $sql .= " FROM ".MAIN_DB_PREFIX."societe as s, ".MAIN_DB_PREFIX."product_fournisseur_price as pfp"; + $sql .= " WHERE s.entity IN (".getEntity('societe').")"; + $sql .= " AND pfp.entity = ".$conf->entity; // only current entity + $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; dol_syslog(get_class($this)."::find_min_price_product_fournisseur", LOG_DEBUG); @@ -750,7 +750,7 @@ class ProductFournisseur extends Product //Store each record to array for later search of min while ($record = $this->db->fetch_array($resql)) { - $record_array[]=$record; + $record_array[] = $record; } if (count($record_array) == 0) @@ -761,7 +761,7 @@ class ProductFournisseur extends Product else { $min = -1; - foreach($record_array as $record) + foreach ($record_array as $record) { $fourn_price = $record["price"]; // discount calculated buy price @@ -779,7 +779,7 @@ class ProductFournisseur extends Product $fourn_price = price2num($price_result, 'MU'); if ($record["quantity"] != 0) { - $fourn_unitprice = price2num($fourn_price/$record["quantity"], 'MU'); + $fourn_unitprice = price2num($fourn_price / $record["quantity"], 'MU'); } else { @@ -791,19 +791,19 @@ class ProductFournisseur extends Product { $this->product_fourn_price_id = $record["product_fourn_price_id"]; $this->ref_supplier = $record["ref_fourn"]; - $this->ref_fourn = $record["ref_fourn"]; // deprecated - $this->fourn_ref = $record["ref_fourn"]; // deprecated + $this->ref_fourn = $record["ref_fourn"]; // deprecated + $this->fourn_ref = $record["ref_fourn"]; // deprecated $this->fourn_price = $fourn_price; $this->fourn_qty = $record["quantity"]; $this->fourn_remise_percent = $record["remise_percent"]; $this->fourn_remise = $record["remise"]; $this->fourn_unitprice = $record["unitprice"]; - $this->fourn_charges = $record["charges"]; // deprecated + $this->fourn_charges = $record["charges"]; // deprecated $this->fourn_tva_tx = $record["tva_tx"]; $this->fourn_id = $record["fourn_id"]; $this->fourn_name = $record["supplier_name"]; - $this->delivery_time_days = $record["delivery_time_days"]; - $this->fk_supplier_price_expression = $record["fk_supplier_price_expression"]; + $this->delivery_time_days = $record["delivery_time_days"]; + $this->fk_supplier_price_expression = $record["fk_supplier_price_expression"]; $this->id = $prodid; $this->fourn_multicurrency_price = $record["multicurrency_price"]; $this->fourn_multicurrency_unitprice = $record["multicurrency_unitprice"]; @@ -820,7 +820,7 @@ class ProductFournisseur extends Product } else { - $this->error=$this->db->error(); + $this->error = $this->db->error(); return -1; } } @@ -840,8 +840,8 @@ class ProductFournisseur extends Product $expression_id = $expression_id != 0 ? $expression_id : 'NULL'; $sql = "UPDATE ".MAIN_DB_PREFIX."product_fournisseur_price"; - $sql.= " SET fk_supplier_price_expression = ".$expression_id; - $sql.= " WHERE rowid = ".$this->product_fourn_price_id; + $sql .= " SET fk_supplier_price_expression = ".$expression_id; + $sql .= " WHERE rowid = ".$this->product_fourn_price_id; dol_syslog(get_class($this)."::setSupplierPriceExpression", LOG_DEBUG); @@ -853,7 +853,7 @@ class ProductFournisseur extends Product } else { - $this->error=$this->db->error()." sql=".$sql; + $this->error = $this->db->error()." sql=".$sql; $this->db->rollback(); return -1; } @@ -898,19 +898,19 @@ class ProductFournisseur extends Product $langs->load("suppliers"); if (count($productFournList) > 0) { $out .= '
    '; +print '
    '; if ($mesg) { print $mesg; } else { print $px1->show(); diff --git a/htdocs/expensereport/tpl/linkedobjectblock.tpl.php b/htdocs/expensereport/tpl/linkedobjectblock.tpl.php index 009b1b9ea75..43f612ea3f6 100644 --- a/htdocs/expensereport/tpl/linkedobjectblock.tpl.php +++ b/htdocs/expensereport/tpl/linkedobjectblock.tpl.php @@ -18,7 +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; diff --git a/htdocs/exports/export.php b/htdocs/exports/export.php index ed6966eb083..07d368ef264 100644 --- a/htdocs/exports/export.php +++ b/htdocs/exports/export.php @@ -127,153 +127,153 @@ $entitytolang = array( 'bomline' => 'BOMLine' ); -$array_selected=isset($_SESSION["export_selected_fields"])?$_SESSION["export_selected_fields"]:array(); -$array_filtervalue=isset($_SESSION["export_filtered_fields"])?$_SESSION["export_filtered_fields"]:array(); -$datatoexport=GETPOST("datatoexport", "aZ09"); -$action=GETPOST('action', 'alpha'); -$confirm=GETPOST('confirm', 'alpha'); -$step=GETPOST("step", "int")?GETPOST("step", "int"):1; -$export_name=GETPOST("export_name", "alphanohtml"); -$hexa=GETPOST("hexa", "alpha"); -$exportmodelid=GETPOST("exportmodelid", "int"); -$field=GETPOST("field", "alpa"); +$array_selected = isset($_SESSION["export_selected_fields"]) ? $_SESSION["export_selected_fields"] : array(); +$array_filtervalue = isset($_SESSION["export_filtered_fields"]) ? $_SESSION["export_filtered_fields"] : array(); +$datatoexport = GETPOST("datatoexport", "aZ09"); +$action = GETPOST('action', 'alpha'); +$confirm = GETPOST('confirm', 'alpha'); +$step = GETPOST("step", "int") ?GETPOST("step", "int") : 1; +$export_name = GETPOST("export_name", "alphanohtml"); +$hexa = GETPOST("hexa", "alpha"); +$exportmodelid = GETPOST("exportmodelid", "int"); +$field = GETPOST("field", "alpa"); -$objexport=new Export($db); +$objexport = new Export($db); $objexport->load_arrays($user, $datatoexport); -$objmodelexport=new ModeleExports($db); +$objmodelexport = new ModeleExports($db); $form = new Form($db); $htmlother = new FormOther($db); $formfile = new FormFile($db); -$sqlusedforexport=''; +$sqlusedforexport = ''; $upload_dir = $conf->export->dir_temp.'/'.$user->id; //$usefilters=($conf->global->MAIN_FEATURES_LEVEL > 1); -$usefilters=1; +$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]; + $fieldsarray = $objexport->array_export_fields[0]; + $fieldsentitiesarray = $objexport->array_export_entities[0]; + $fieldsdependenciesarray = $objexport->array_export_dependencies[0]; - if ($field=='all') + if ($field == 'all') { - foreach($fieldsarray as $key=>$val) + foreach ($fieldsarray as $key=>$val) { - if (! empty($array_selected[$key])) continue; // If already selected, check next - $array_selected[$key]=count($array_selected)+1; + 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; + $_SESSION["export_selected_fields"] = $array_selected; } } else { - $warnings=array(); + $warnings = array(); - $array_selected[$field]=count($array_selected)+1; // We tag the key $field as "selected" + $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);*/ - $listofdependencies=array(); - if (! empty($fieldsentitiesarray[$field]) && ! empty($fieldsdependenciesarray[$fieldsentitiesarray[$field]])) + $listofdependencies = array(); + 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); + $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])) + 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); + $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 (count($listofdependencies)) { - foreach($listofdependencies as $fieldid) + 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])); + $array_selected[$fieldid] = count($array_selected) + 1; // We tag the key $fieldid as "selected" + $warnings[] = $langs->trans("ExportFieldAutomaticallyAdded", $langs->transnoentitiesnoconv($fieldsarray[$fieldid])); } } } //print_r($array_selected); - $_SESSION["export_selected_fields"]=$array_selected; + $_SESSION["export_selected_fields"] = $array_selected; setEventMessages($warnings, null, 'warnings'); } } -if ($action=='unselectfield') +if ($action == 'unselectfield') { - if ($_GET["field"]=='all') + if ($_GET["field"] == 'all') { - $array_selected=array(); - $_SESSION["export_selected_fields"]=$array_selected; + $array_selected = array(); + $_SESSION["export_selected_fields"] = $array_selected; } else { unset($array_selected[$_GET["field"]]); // Renumber fields of array_selected (from 1 to nb_elements) asort($array_selected); - $i=0; - $array_selected_save=$array_selected; - foreach($array_selected as $code=>$value) + $i = 0; + $array_selected_save = $array_selected; + foreach ($array_selected as $code=>$value) { $i++; - $array_selected[$code]=$i; + $array_selected[$code] = $i; //print "x $code x $i y
    "; } - $_SESSION["export_selected_fields"]=$array_selected; + $_SESSION["export_selected_fields"] = $array_selected; } } -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; + $pos = $array_selected[$_GET["field"]]; + if ($action == 'downfield') $newpos = $pos + 1; + if ($action == 'upfield') $newpos = $pos - 1; // Recherche code avec qui switcher - $newcode=""; - foreach($array_selected as $code=>$value) + $newcode = ""; + foreach ($array_selected as $code=>$value) { if ($value == $newpos) { - $newcode=$code; + $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) { - $array_selected[$_GET["field"]]=$newpos; - $array_selected[$newcode]=$pos; - $_SESSION["export_selected_fields"]=$array_selected; + $array_selected[$_GET["field"]] = $newpos; + $array_selected[$newcode] = $pos; + $_SESSION["export_selected_fields"] = $array_selected; } } if ($step == 1 || $action == 'cleanselect') { - $_SESSION["export_selected_fields"]=array(); - $_SESSION["export_filtered_fields"]=array(); - $array_selected=array(); - $array_filtervalue=array(); + $_SESSION["export_selected_fields"] = array(); + $_SESSION["export_filtered_fields"] = array(); + $array_selected = array(); + $array_filtervalue = array(); } if ($action == 'builddoc') { - $max_execution_time_for_export = (empty($conf->global->EXPORT_MAX_EXECUTION_TIME)?300:$conf->global->EXPORT_MAX_EXECUTION_TIME); // 5mn if not defined + $max_execution_time_for_export = (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_export) { @@ -281,25 +281,25 @@ if ($action == 'builddoc') } // Build export file - $result=$objexport->build_file($user, GETPOST('model', 'alpha'), $datatoexport, $array_selected, $array_filtervalue); + $result = $objexport->build_file($user, GETPOST('model', 'alpha'), $datatoexport, $array_selected, $array_filtervalue); if ($result < 0) { setEventMessages($objexport->error, $objexport->errors, 'errors'); - $sqlusedforexport=$objexport->sqlusedforexport; + $sqlusedforexport = $objexport->sqlusedforexport; } else { setEventMessages($langs->trans("FileSuccessfullyBuilt"), null, 'mesgs'); - $sqlusedforexport=$objexport->sqlusedforexport; + $sqlusedforexport = $objexport->sqlusedforexport; } } // Delete file 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). + $file = $upload_dir."/".GETPOST('file'); // Do not use urldecode here ($_GET and $_REQUEST are already decoded by PHP). - $ret=dol_delete_file($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'); header('Location: '.$_SERVER["PHP_SELF"].'?step='.$step.'&datatoexport='.$datatoexport); @@ -311,7 +311,7 @@ if ($action == 'deleteprof') if ($_GET["id"]) { $objexport->fetch($_GET["id"]); - $result=$objexport->delete($user); + $result = $objexport->delete($user); } } @@ -323,20 +323,20 @@ if ($action == 'add_export_model') asort($array_selected); // Set save string - $hexa=''; - foreach($array_selected as $key=>$val) + $hexa = ''; + foreach ($array_selected as $key=>$val) { - if ($hexa) $hexa.=','; - $hexa.=$key; + if ($hexa) $hexa .= ','; + $hexa .= $key; } - $hexafiltervalue=''; - if (! empty($array_filtervalue) && is_array($array_filtervalue)) + $hexafiltervalue = ''; + if (!empty($array_filtervalue) && is_array($array_filtervalue)) { - foreach($array_filtervalue as $key=>$val) + foreach ($array_filtervalue as $key=>$val) { - if ($hexafiltervalue) $hexafiltervalue.=','; - $hexafiltervalue.=$key.'='.$val; + if ($hexafiltervalue) $hexafiltervalue .= ','; + $hexafiltervalue .= $key.'='.$val; } } @@ -368,33 +368,33 @@ if ($action == 'add_export_model') // Reload a predefined export model if ($step == 2 && $action == 'select_model') { - $_SESSION["export_selected_fields"]=array(); - $_SESSION["export_filtered_fields"]=array(); + $_SESSION["export_selected_fields"] = array(); + $_SESSION["export_filtered_fields"] = array(); - $array_selected=array(); - $array_filtervalue=array(); + $array_selected = array(); + $array_filtervalue = array(); $result = $objexport->fetch($exportmodelid); if ($result > 0) { - $fieldsarray=explode(',', $objexport->hexa); - $i=1; - foreach($fieldsarray as $val) + $fieldsarray = explode(',', $objexport->hexa); + $i = 1; + foreach ($fieldsarray as $val) { - $array_selected[$val]=$i; + $array_selected[$val] = $i; $i++; } - $_SESSION["export_selected_fields"]=$array_selected; + $_SESSION["export_selected_fields"] = $array_selected; - $fieldsarrayvalue=explode(',', $objexport->hexafiltervalue); - $i=1; - foreach($fieldsarrayvalue as $val) + $fieldsarrayvalue = explode(',', $objexport->hexafiltervalue); + $i = 1; + foreach ($fieldsarrayvalue as $val) { - $tmp=explode('=', $val); - $array_filtervalue[$tmp[0]]=$tmp[1]; + $tmp = explode('=', $val); + $array_filtervalue[$tmp[0]] = $tmp[1]; $i++; } - $_SESSION["export_filtered_fields"]=$array_filtervalue; + $_SESSION["export_filtered_fields"] = $array_filtervalue; } } @@ -404,22 +404,22 @@ if ($step == 4 && $action == 'submitFormField') // on boucle sur les champs selectionne pour recuperer la valeur 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 + $_SESSION["export_filtered_fields"] = array(); + foreach ($objexport->array_export_TypeFields[0] as $code => $type) // $code: s.fieldname $value: Text|Boolean|List:ccc { - $newcode=(string) preg_replace('/\./', '_', $code); + $newcode = (string) preg_replace('/\./', '_', $code); //print 'xxx'.$code."=".$newcode."=".$type."=".$_POST[$newcode]."\n
    "; - $filterqualified=1; - if (! isset($_POST[$newcode]) || $_POST[$newcode] == '') $filterqualified=0; - elseif (preg_match('/^List/', $type) && (is_numeric($_POST[$newcode]) && $_POST[$newcode] <= 0)) $filterqualified=0; + $filterqualified = 1; + if (!isset($_POST[$newcode]) || $_POST[$newcode] == '') $filterqualified = 0; + elseif (preg_match('/^List/', $type) && (is_numeric($_POST[$newcode]) && $_POST[$newcode] <= 0)) $filterqualified = 0; if ($filterqualified) { //print 'Filter on '.$newcode.' type='.$type.' value='.$_POST[$newcode]."\n"; $objexport->array_export_FilterValue[0][$code] = $_POST[$newcode]; } } - $array_filtervalue=(! empty($objexport->array_export_FilterValue[0])?$objexport->array_export_FilterValue[0]:''); - $_SESSION["export_filtered_fields"]=$array_filtervalue; + $array_filtervalue = (!empty($objexport->array_export_FilterValue[0]) ? $objexport->array_export_FilterValue[0] : ''); + $_SESSION["export_filtered_fields"] = $array_filtervalue; } } @@ -428,7 +428,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'); @@ -436,7 +436,7 @@ if ($step == 1 || ! $datatoexport) $head[$h][0] = DOL_URL_ROOT.'/exports/export.php?step=1'; $head[$h][1] = $langs->trans("Step")." 1"; - $hselected=$h; + $hselected = $h; $h++; dol_fiche_head($head, $hselected, $langs->trans("NewExport"), -1); @@ -445,8 +445,8 @@ if ($step == 1 || ! $datatoexport) print '
    '.$langs->trans("SelectExportDataSet").'

    '; // Affiche les modules d'exports - print '
    '; // You can use div-table-responsive-no-min if you dont need reserved height for your table - print ''; + print '
    '; // You can use div-table-responsive-no-min if you dont need reserved height for your table + print '
    '; print ''; print ''; print ''; @@ -462,8 +462,8 @@ if ($step == 1 || ! $datatoexport) //print img_object($objexport->array_export_module[$key]->getName(),$export->array_export_module[$key]->picto).' '; print $objexport->array_export_module[$key]->getName(); print ''; print '
    '.$langs->trans("Module").''.$langs->trans("ExportableDatas").''; - $icon=preg_replace('/:.*$/', '', $objexport->array_export_icon[$key]); - $label=$objexport->array_export_label[$key]; + $icon = preg_replace('/:.*$/', '', $objexport->array_export_icon[$key]); + $label = $objexport->array_export_label[$key]; //print $value.'-'.$icon.'-'.$label."
    "; print img_object($objexport->array_export_module[$key]->getName(), $icon).' '; print $label; @@ -501,7 +501,7 @@ if ($step == 2 && $datatoexport) $head[$h][0] = DOL_URL_ROOT.'/exports/export.php?step=2&datatoexport='.$datatoexport; $head[$h][1] = $langs->trans("Step")." 2"; - $hselected=$h; + $hselected = $h; $h++; dol_fiche_head($head, $hselected, $langs->trans("NewExport"), -2); @@ -521,8 +521,8 @@ if ($step == 2 && $datatoexport) // Lot de donnees a exporter print '
    '.$langs->trans("DatasetToExport").''; - $icon=preg_replace('/:.*$/', '', $objexport->array_export_icon[0]); - $label=$objexport->array_export_label[0]; + $icon = preg_replace('/:.*$/', '', $objexport->array_export_icon[0]); + $label = $objexport->array_export_label[0]; //print $value.'-'.$icon.'-'.$label."
    "; print img_object($objexport->array_export_module[0]->getName(), $icon).' '; print $label; @@ -543,7 +543,7 @@ if ($step == 2 && $datatoexport) print ''; print '
    '; print ''.$langs->trans("SelectExportFields").' '; - if(empty($conf->global->EXPORTS_SHARE_MODELS))$htmlother->select_export_model($exportmodelid, 'exportmodelid', $datatoexport, 1, $user->id); + if (empty($conf->global->EXPORTS_SHARE_MODELS))$htmlother->select_export_model($exportmodelid, 'exportmodelid', $datatoexport, 1, $user->id); else $htmlother->select_export_model($exportmodelid, 'exportmodelid', $datatoexport, 1); print ' '; print ''; @@ -551,8 +551,8 @@ if ($step == 2 && $datatoexport) print ''; - print '
    '; // You can use div-table-responsive-no-min if you dont need reserved height for your table - print ''; + print '
    '; // You can use div-table-responsive-no-min if you dont need reserved height for your table + print '
    '; print ''; print ''; print ''; @@ -565,9 +565,9 @@ if ($step == 2 && $datatoexport) print ''; // Champs exportables - $fieldsarray=$objexport->array_export_fields[0]; + $fieldsarray = $objexport->array_export_fields[0]; // Select request if all fields are selected - $sqlmaxforexport=$objexport->build_sql(0, array(), array()); + $sqlmaxforexport = $objexport->build_sql(0, array(), array()); // $this->array_export_module[0]=$module; // $this->array_export_code[0]=$module->export_code[$r]; @@ -579,48 +579,48 @@ if ($step == 2 && $datatoexport) $i = 0; - foreach($fieldsarray as $code=>$label) + foreach ($fieldsarray as $code=>$label) { print ''; $i++; - $entity=(! empty($objexport->array_export_entities[0][$code])?$objexport->array_export_entities[0][$code]:$objexport->array_export_icon[0]); - $entityicon=strtolower(! empty($entitytoicon[$entity])?$entitytoicon[$entity]:$entity); - $entitylang=(! empty($entitytolang[$entity])?$entitytolang[$entity]:$entity); + $entity = (!empty($objexport->array_export_entities[0][$code]) ? $objexport->array_export_entities[0][$code] : $objexport->array_export_icon[0]); + $entityicon = strtolower(!empty($entitytoicon[$entity]) ? $entitytoicon[$entity] : $entity); + $entitylang = (!empty($entitytolang[$entity]) ? $entitytolang[$entity] : $entity); print ''; - $text=(empty($objexport->array_export_special[0][$code])?'':'').$langs->trans($label).(empty($objexport->array_export_special[0][$code])?'':''); + $text = (empty($objexport->array_export_special[0][$code]) ? '' : '').$langs->trans($label).(empty($objexport->array_export_special[0][$code]) ? '' : ''); - $tablename=getablenamefromfield($code, $sqlmaxforexport); - $htmltext =''.$langs->trans("Name").": ".$text.'
    '; - if (! empty($objexport->array_export_special[0][$code])) + $tablename = getablenamefromfield($code, $sqlmaxforexport); + $htmltext = ''.$langs->trans("Name").": ".$text.'
    '; + if (!empty($objexport->array_export_special[0][$code])) { - $htmltext.=''.$langs->trans("ComputedField")." -> ".$langs->trans("Method")." : ".$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)."
    "; + $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].'
    '; + $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].'
    '; + $htmltext .= ''.$langs->trans("Type").': '.$objexport->array_export_TypeFields[0][$code].'
    '; } if (isset($array_selected[$code]) && $array_selected[$code]) @@ -700,7 +700,7 @@ if ($step == 3 && $datatoexport) $head[$h][0] = DOL_URL_ROOT.'/exports/export.php?step=3&datatoexport='.$datatoexport; $head[$h][1] = $langs->trans("Step")." 3"; - $hselected=$h; + $hselected = $h; $h++; dol_fiche_head($head, $hselected, $langs->trans("NewExport"), -2); @@ -719,8 +719,8 @@ if ($step == 3 && $datatoexport) // Lot de donnees a exporter print ''; print ''; - $list=''; - foreach($array_selected as $code=>$value) + $list = ''; + 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]):''); + $list .= (!empty($list) ? ', ' : ''); + $list .= (isset($objexport->array_export_fields[0][$code]) ? $langs->trans($objexport->array_export_fields[0][$code]) : ''); } print ''; @@ -749,9 +749,9 @@ if ($step == 3 && $datatoexport) print ''; print ''; - print '
    '; // You can use div-table-responsive-no-min if you dont need reserved height for your table + print '
    '; // You can use div-table-responsive-no-min if you dont need reserved height for your table - print '
    '.$langs->trans("Entities").''.$langs->trans("ExportableFields").'
    '; // If value of entityicon=entitylang='icon:Label' //print $code.'-'.$label.'-'.$entity; - $tmparray=explode(':', $entityicon); - if (count($tmparray) >=2) + $tmparray = explode(':', $entityicon); + if (count($tmparray) >= 2) { - $entityicon=$tmparray[0]; - $entitylang=$tmparray[1]; + $entityicon = $tmparray[0]; + $entitylang = $tmparray[1]; } print img_object('', $entityicon).' '.$langs->trans($entitylang); print '
    '.$langs->trans("DatasetToExport").''; - $icon=preg_replace('/:.*$/', '', $objexport->array_export_icon[0]); - $label=$objexport->array_export_label[0]; + $icon = preg_replace('/:.*$/', '', $objexport->array_export_icon[0]); + $label = $objexport->array_export_label[0]; //print $value.'-'.$icon.'-'.$label."
    "; print img_object($objexport->array_export_module[0]->getName(), $icon).' '; print $label; @@ -728,11 +728,11 @@ if ($step == 3 && $datatoexport) // Nbre champs exportes print '
    '.$langs->trans("ExportedFields").''.$list.'
    '; + print '
    '; print ''; print ''; //print ''; @@ -761,58 +761,58 @@ if ($step == 3 && $datatoexport) print ''; // Champs exportables - $fieldsarray=$objexport->array_export_fields[0]; + $fieldsarray = $objexport->array_export_fields[0]; // Champs filtrable - $Typefieldsarray=$objexport->array_export_TypeFields[0]; + $Typefieldsarray = $objexport->array_export_TypeFields[0]; // valeur des filtres - $ValueFiltersarray=(! empty($objexport->array_export_FilterValue[0])?$objexport->array_export_FilterValue[0]:''); + $ValueFiltersarray = (!empty($objexport->array_export_FilterValue[0]) ? $objexport->array_export_FilterValue[0] : ''); // Select request if all fields are selected - $sqlmaxforexport=$objexport->build_sql(0, array(), array()); + $sqlmaxforexport = $objexport->build_sql(0, array(), array()); $i = 0; // on boucle sur les champs - foreach($fieldsarray as $code => $label) + foreach ($fieldsarray as $code => $label) { print ''; $i++; - $entity=(! empty($objexport->array_export_entities[0][$code])?$objexport->array_export_entities[0][$code]:$objexport->array_export_icon[0]); - $entityicon=strtolower(! empty($entitytoicon[$entity])?$entitytoicon[$entity]:$entity); - $entitylang=(! empty($entitytolang[$entity])?$entitytolang[$entity]:$entity); + $entity = (!empty($objexport->array_export_entities[0][$code]) ? $objexport->array_export_entities[0][$code] : $objexport->array_export_icon[0]); + $entityicon = strtolower(!empty($entitytoicon[$entity]) ? $entitytoicon[$entity] : $entity); + $entitylang = (!empty($entitytolang[$entity]) ? $entitytolang[$entity] : $entity); print ''; // Field name - $labelName=(! empty($fieldsarray[$code])?$fieldsarray[$code]:''); - $ValueFilter=(! empty($array_filtervalue[$code])?$array_filtervalue[$code]:''); - $text=(empty($objexport->array_export_special[0][$code])?'':'').$langs->trans($labelName).(empty($objexport->array_export_special[0][$code])?'':''); + $labelName = (!empty($fieldsarray[$code]) ? $fieldsarray[$code] : ''); + $ValueFilter = (!empty($array_filtervalue[$code]) ? $array_filtervalue[$code] : ''); + $text = (empty($objexport->array_export_special[0][$code]) ? '' : '').$langs->trans($labelName).(empty($objexport->array_export_special[0][$code]) ? '' : ''); - $tablename=getablenamefromfield($code, $sqlmaxforexport); - $htmltext =''.$langs->trans("Name").': '.$text.'
    '; - if (! empty($objexport->array_export_special[0][$code])) + $tablename = getablenamefromfield($code, $sqlmaxforexport); + $htmltext = ''.$langs->trans("Name").': '.$text.'
    '; + if (!empty($objexport->array_export_special[0][$code])) { - $htmltext.=''.$langs->trans("ComputedField")." -> ".$langs->trans("Method")." : ".$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)."
    "; + $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].'
    '; + $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].'
    '; + $htmltext .= $langs->trans("Type").': '.$objexport->array_export_TypeFields[0][$code].'
    '; } print ''; print ''; // List of exported fields print ''; - $list=''; - foreach($array_selected as $code=>$value) + $list = ''; + foreach ($array_selected as $code=>$value) { - $list.=(! empty($list)?', ':''); - $list.=$langs->trans($objexport->array_export_fields[0][$code]); + $list .= (!empty($list) ? ', ' : ''); + $list .= $langs->trans($objexport->array_export_fields[0][$code]); } print ''; print ''; @@ -927,20 +927,20 @@ if ($step == 4 && $datatoexport) if (isset($objexport->array_export_TypeFields[0]) && is_array($objexport->array_export_TypeFields[0])) { print ''; - $list=''; - if (! empty($array_filtervalue)) + $list = ''; + if (!empty($array_filtervalue)) { - foreach($array_filtervalue as $code=>$value) + 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]:'')."'"; + $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] : '')."'"; } } } - print ''; + print ''; print ''; } @@ -950,12 +950,12 @@ if ($step == 4 && $datatoexport) print '
    '; // Select request if all fields are selected - $sqlmaxforexport=$objexport->build_sql(0, array(), array()); + $sqlmaxforexport = $objexport->build_sql(0, array(), array()); print '
    '.$langs->trans("ChooseFieldsOrdersAndTitle").'
    '; - print '
    '; // You can use div-table-responsive-no-min if you dont need reserved height for your table - print '
    '.$langs->trans("Entities").''.$langs->trans("ExportableFields").'
    '; // If value of entityicon=entitylang='icon:Label' - $tmparray=explode(':', $entityicon); - if (count($tmparray) >=2) + $tmparray = explode(':', $entityicon); + if (count($tmparray) >= 2) { - $entityicon=$tmparray[0]; - $entitylang=$tmparray[1]; + $entityicon = $tmparray[0]; + $entitylang = $tmparray[1]; } print img_object('', $entityicon).' '.$langs->trans($entitylang); print ''; @@ -821,12 +821,12 @@ 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]); + $szInfoFiltre = $objexport->genDocFilter($Typefieldsarray[$code]); if ($szInfoFiltre) // Is there an info help for this filter ? { - $tmp=$objexport->build_filterField($Typefieldsarray[$code], $code, $ValueFilter); + $tmp = $objexport->build_filterField($Typefieldsarray[$code], $code, $ValueFilter); print $form->textwithpicto($tmp, $szInfoFiltre); } else @@ -866,7 +866,7 @@ if ($step == 4 && $datatoexport) llxHeader('', $langs->trans("NewExport"), 'EN:Module_Exports_En|FR:Module_Exports|ES:Módulo_Exportaciones'); - $stepoffset=0; + $stepoffset = 0; $h = 0; $head[$h][0] = DOL_URL_ROOT.'/exports/export.php?step=1'; @@ -887,8 +887,8 @@ if ($step == 4 && $datatoexport) } $head[$h][0] = DOL_URL_ROOT.'/exports/export.php?step=4&datatoexport='.$datatoexport; - $head[$h][1] = $langs->trans("Step")." ".(3+$stepoffset); - $hselected=$h; + $head[$h][1] = $langs->trans("Step")." ".(3 + $stepoffset); + $hselected = $h; $h++; dol_fiche_head($head, $hselected, $langs->trans("NewExport"), -2); @@ -907,18 +907,18 @@ if ($step == 4 && $datatoexport) // Lot de donnees a exporter print '
    '.$langs->trans("DatasetToExport").''; - $icon=preg_replace('/:.*$/', '', $objexport->array_export_icon[0]); + $icon = preg_replace('/:.*$/', '', $objexport->array_export_icon[0]); print img_object($objexport->array_export_module[0]->getName(), $icon).' '; print $objexport->array_export_label[0]; print '
    '.$langs->trans("ExportedFields").''.$list.'
    '.$langs->trans("FilteredFields").''.(! empty($list)?$list:$langs->trans("None")).''.(!empty($list) ? $list : $langs->trans("None")).'
    '; + print '
    '; // You can use div-table-responsive-no-min if you dont need reserved height for your table + print '
    '; print ''; print ''; print ''; @@ -964,46 +964,46 @@ if ($step == 4 && $datatoexport) //print ''; 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]); - $entityicon=strtolower(! empty($entitytoicon[$entity])?$entitytoicon[$entity]:$entity); - $entitylang=(! empty($entitytolang[$entity])?$entitytolang[$entity]:$entity); + $entity = (!empty($objexport->array_export_entities[0][$code]) ? $objexport->array_export_entities[0][$code] : $objexport->array_export_icon[0]); + $entityicon = strtolower(!empty($entitytoicon[$entity]) ? $entitytoicon[$entity] : $entity); + $entitylang = (!empty($entitytolang[$entity]) ? $entitytolang[$entity] : $entity); print ''; - $labelName=$objexport->array_export_fields[0][$code]; + $labelName = $objexport->array_export_fields[0][$code]; - $text=(empty($objexport->array_export_special[0][$code])?'':'').$langs->trans($labelName).(empty($objexport->array_export_special[0][$code])?'':''); + $text = (empty($objexport->array_export_special[0][$code]) ? '' : '').$langs->trans($labelName).(empty($objexport->array_export_special[0][$code]) ? '' : ''); - $tablename=getablenamefromfield($code, $sqlmaxforexport); - $htmltext =''.$langs->trans("Name").': '.$text.'
    '; - if (! empty($objexport->array_export_special[0][$code])) + $tablename = getablenamefromfield($code, $sqlmaxforexport); + $htmltext = ''.$langs->trans("Name").': '.$text.'
    '; + if (!empty($objexport->array_export_special[0][$code])) { - $htmltext.=''.$langs->trans("ComputedField")." -> ".$langs->trans("Method")." : ".$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)."
    "; + $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].'
    '; + $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].'
    '; + $htmltext .= $langs->trans("Type").': '.$objexport->array_export_TypeFields[0][$code].'
    '; } print '
    '.$langs->trans("Entities").''.$langs->trans("ExportedFields").''.$langs->trans("FieldsTitle").'
    '; // If value of entityicon=entitylang='icon:Label' - $tmparray=explode(':', $entityicon); - if (count($tmparray) >=2) + $tmparray = explode(':', $entityicon); + if (count($tmparray) >= 2) { - $entityicon=$tmparray[0]; - $entitylang=$tmparray[1]; + $entityicon = $tmparray[0]; + $entitylang = $tmparray[1]; } print img_object('', $entityicon).' '.$langs->trans($entitylang); print ''; @@ -1056,8 +1056,8 @@ if ($step == 4 && $datatoexport) print ''; print ''; - print '
    '; // You can use div-table-responsive-no-min if you dont need reserved height for your table - print ''; + print '
    '; // You can use div-table-responsive-no-min if you dont need reserved height for your table + print '
    '; print ''; print ''; print ''; @@ -1070,10 +1070,10 @@ if ($step == 4 && $datatoexport) // List of existing export profils $sql = "SELECT rowid, label"; - $sql.= " FROM ".MAIN_DB_PREFIX."export_model"; - $sql.= " WHERE type = '".$datatoexport."'"; - if(empty($conf->global->EXPORTS_SHARE_MODELS))$sql.=" AND fk_user=".$user->id; - $sql.= " ORDER BY rowid"; + $sql .= " FROM ".MAIN_DB_PREFIX."export_model"; + $sql .= " WHERE type = '".$datatoexport."'"; + if (empty($conf->global->EXPORTS_SHARE_MODELS))$sql .= " AND fk_user=".$user->id; + $sql .= " ORDER BY rowid"; $resql = $db->query($sql); if ($resql) { @@ -1117,7 +1117,7 @@ if ($step == 5 && $datatoexport) llxHeader('', $langs->trans("NewExport"), 'EN:Module_Exports_En|FR:Module_Exports|ES:Módulo_Exportaciones'); $h = 0; - $stepoffset=0; + $stepoffset = 0; $head[$h][0] = DOL_URL_ROOT.'/exports/export.php?step=1'; $head[$h][1] = $langs->trans("Step")." 1"; @@ -1137,12 +1137,12 @@ if ($step == 5 && $datatoexport) } $head[$h][0] = DOL_URL_ROOT.'/exports/export.php?step=4&datatoexport='.$datatoexport; - $head[$h][1] = $langs->trans("Step")." ".(3+$stepoffset); + $head[$h][1] = $langs->trans("Step")." ".(3 + $stepoffset); $h++; $head[$h][0] = DOL_URL_ROOT.'/exports/export.php?step=5&datatoexport='.$datatoexport; - $head[$h][1] = $langs->trans("Step")." ".(4+$stepoffset); - $hselected=$h; + $head[$h][1] = $langs->trans("Step")." ".(4 + $stepoffset); + $hselected = $h; $h++; dol_fiche_head($head, $hselected, $langs->trans("NewExport"), -2); @@ -1170,18 +1170,18 @@ if ($step == 5 && $datatoexport) // Lot de donnees a exporter print ''; print ''; // List of exported fields print ''; - $list=''; - foreach($array_selected as $code=>$label) + $list = ''; + foreach ($array_selected as $code=>$label) { - $list.=(! empty($list)?', ':''); - $list.=$langs->trans($objexport->array_export_fields[0][$code]); + $list .= (!empty($list) ? ', ' : ''); + $list .= $langs->trans($objexport->array_export_fields[0][$code]); } print ''; @@ -1189,20 +1189,20 @@ if ($step == 5 && $datatoexport) if (isset($objexport->array_export_TypeFields[0]) && is_array($objexport->array_export_TypeFields[0])) { print ''; - $list=''; - if (! empty($array_filtervalue)) + $list = ''; + if (!empty($array_filtervalue)) { - foreach($array_filtervalue as $code=>$value) + 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]:'')."'"; + $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] : '')."'"; } } } - print ''; + print ''; print ''; } @@ -1212,33 +1212,33 @@ if ($step == 5 && $datatoexport) print '
    '; // List of available export formats - $htmltabloflibs = '
    '.$langs->trans("ExportModelName").' 
    '.$langs->trans("DatasetToExport").''; - $icon=preg_replace('/:.*$/', '', $objexport->array_export_icon[0]); + $icon = preg_replace('/:.*$/', '', $objexport->array_export_icon[0]); print img_object($objexport->array_export_module[0]->getName(), $icon).' '; print $objexport->array_export_label[0]; print '
    '.$langs->trans("ExportedFields").''.$list.'
    '.$langs->trans("FilteredFields").''.(! empty($list)?$list:''.$langs->trans("None").'').''.(!empty($list) ? $list : ''.$langs->trans("None").'').'
    '; - $htmltabloflibs.= ''; - $htmltabloflibs.= ''; - $htmltabloflibs.= ''; - $htmltabloflibs.= ''; - $htmltabloflibs.= ''."\n"; + $htmltabloflibs = '
    '.$langs->trans("AvailableFormats").''.$langs->trans("LibraryUsed").''.$langs->trans("LibraryVersion").'
    '; + $htmltabloflibs .= ''; + $htmltabloflibs .= ''; + $htmltabloflibs .= ''; + $htmltabloflibs .= ''; + $htmltabloflibs .= ''."\n"; - $liste=$objmodelexport->liste_modeles($db); - $listeall=$liste; - foreach($listeall as $key => $val) + $liste = $objmodelexport->liste_modeles($db); + $listeall = $liste; + foreach ($listeall as $key => $val) { if (preg_match('/__\(Disabled\)__/', $listeall[$key])) { - $listeall[$key]=preg_replace('/__\(Disabled\)__/', '('.$langs->transnoentitiesnoconv("Disabled").')', $listeall[$key]); + $listeall[$key] = preg_replace('/__\(Disabled\)__/', '('.$langs->transnoentitiesnoconv("Disabled").')', $listeall[$key]); unset($liste[$key]); } - $htmltabloflibs.= ''; - $htmltabloflibs.= ''; - $htmltabloflibs.= ''; - $htmltabloflibs.= ''; - $htmltabloflibs.= ''."\n"; + $htmltabloflibs .= ''; + $htmltabloflibs .= ''; + $htmltabloflibs .= ''; + $htmltabloflibs .= ''; + $htmltabloflibs .= ''."\n"; } - $htmltabloflibs.= '
    '.$langs->trans("AvailableFormats").''.$langs->trans("LibraryUsed").''.$langs->trans("LibraryVersion").'
    '.img_picto_common($key, $objmodelexport->getPictoForKey($key)).' '; - $text=$objmodelexport->getDriverDescForKey($key); - $label=$listeall[$key]; - $htmltabloflibs.= $form->textwithpicto($label, $text).''.$objmodelexport->getLibLabelForKey($key).''.$objmodelexport->getLibVersionForKey($key).'
    '.img_picto_common($key, $objmodelexport->getPictoForKey($key)).' '; + $text = $objmodelexport->getDriverDescForKey($key); + $label = $listeall[$key]; + $htmltabloflibs .= $form->textwithpicto($label, $text).''.$objmodelexport->getLibLabelForKey($key).''.$objmodelexport->getLibVersionForKey($key).'
    '; + $htmltabloflibs .= '
    '; print ''.$form->textwithpicto($langs->trans("NowClickToGenerateToBuildExportFile"), $htmltabloflibs, 1, 'help', '', 0, 2, 'helphonformat').''; //print $htmltabloflibs; @@ -1258,18 +1258,18 @@ if ($step == 5 && $datatoexport) print '
    '; - 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 - print $formfile->showdocuments('export', '', $upload_dir, $_SERVER["PHP_SELF"].'?step=5&datatoexport='.$datatoexport, $liste, 1, (! empty($_POST['model'])?$_POST['model']:'csv'), 1, 1, 0, 0, 0, '', ' ', '', '', ''); + print $formfile->showdocuments('export', '', $upload_dir, $_SERVER["PHP_SELF"].'?step=5&datatoexport='.$datatoexport, $liste, 1, (!empty($_POST['model']) ? $_POST['model'] : 'csv'), 1, 1, 0, 0, 0, '', ' ', '', '', ''); } llxFooter(); $db->close(); -exit; // don't know why but apache hangs with php 5.3.10-1ubuntu3.12 and apache 2.2.2 if i remove this exit or replace with return +exit; // don't know why but apache hangs with php 5.3.10-1ubuntu3.12 and apache 2.2.2 if i remove this exit or replace with return /** @@ -1281,16 +1281,16 @@ exit; // don't know why but apache hangs with php 5.3.10-1ubuntu3.12 and apache */ function getablenamefromfield($code, $sqlmaxforexport) { - $alias=preg_replace('/\.(.*)$/i', '', $code); // Keep only 'Alias' and remove '.Fieldname' - $regexstring='/([a-zA-Z_]+) as '.preg_quote($alias).'[, \)]/i'; + $alias = preg_replace('/\.(.*)$/i', '', $code); // Keep only 'Alias' and remove '.Fieldname' + $regexstring = '/([a-zA-Z_]+) as '.preg_quote($alias).'[, \)]/i'; - $newsql=$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 + $newsql = $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)) { - return $reg[1]; // The tablename + return $reg[1]; // The tablename } else return ''; } diff --git a/htdocs/exports/index.php b/htdocs/exports/index.php index 7236a3f45dc..0210ee608b0 100644 --- a/htdocs/exports/index.php +++ b/htdocs/exports/index.php @@ -28,16 +28,16 @@ require_once DOL_DOCUMENT_ROOT.'/exports/class/export.class.php'; $langs->load("exports"); // Security check -$result=restrictedArea($user, 'export'); +$result = restrictedArea($user, 'export'); -$export=new Export($db); +$export = new Export($db); $export->load_arrays($user); /* * View */ -$form=new Form($db); +$form = new Form($db); llxHeader('', $langs->trans("ExportsArea"), 'EN:Module_Exports_En|FR:Module_Exports|ES:Módulo_Exportaciones'); @@ -59,8 +59,8 @@ print '
    '; // List of available export formats -print '
    '; // You can use div-table-responsive-no-min if you dont need reserved height for your table -print ''; +print '
    '; // You can use div-table-responsive-no-min if you dont need reserved height for your table +print '
    '; print ''; print ''; print ''; @@ -68,20 +68,20 @@ print ''; print ''; 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 +$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) +foreach ($liste as $key => $val) { if (preg_match('/__\(Disabled\)__/', $liste[$key])) { - $liste[$key]=preg_replace('/__\(Disabled\)__/', '('.$langs->transnoentitiesnoconv("Disabled").')', $liste[$key]); + $liste[$key] = preg_replace('/__\(Disabled\)__/', '('.$langs->transnoentitiesnoconv("Disabled").')', $liste[$key]); } print ''; print ''; - $text=$model->getDriverDescForKey($key); - $label=$liste[$key]; + $text = $model->getDriverDescForKey($key); + $label = $liste[$key]; print ''; print ''; print ''; diff --git a/htdocs/fichinter/card-rec.php b/htdocs/fichinter/card-rec.php index aaf2aec0490..7d0b704cf31 100644 --- a/htdocs/fichinter/card-rec.php +++ b/htdocs/fichinter/card-rec.php @@ -37,43 +37,43 @@ require_once DOL_DOCUMENT_ROOT.'/core/lib/fichinter.lib.php'; require_once DOL_DOCUMENT_ROOT.'/product/class/product.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'; - require_once DOL_DOCUMENT_ROOT . '/core/class/html.formprojet.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'; } -if (! empty($conf->contrat->enabled)) { +if (!empty($conf->contrat->enabled)) { require_once DOL_DOCUMENT_ROOT.'/contrat/class/contrat.class.php'; - require_once DOL_DOCUMENT_ROOT . '/core/class/html.formcontract.class.php'; + require_once DOL_DOCUMENT_ROOT.'/core/class/html.formcontract.class.php'; } // Load translation files required by the page -$langs->loadLangs(array("interventions","admin","compta","bills")); +$langs->loadLangs(array("interventions", "admin", "compta", "bills")); // Security check -$id=(GETPOST('fichinterid', 'int')?GETPOST('fichinterid', 'int'):GETPOST('id', 'int')); -$action=GETPOST('action', 'alpha'); -if ($user->socid) $socid=$user->socid; +$id = (GETPOST('fichinterid', 'int') ?GETPOST('fichinterid', 'int') : GETPOST('id', 'int')); +$action = GETPOST('action', 'alpha'); +if ($user->socid) $socid = $user->socid; $objecttype = 'fichinter_rec'; if ($action == "create" || $action == "add") $objecttype = ''; $result = restrictedArea($user, 'ficheinter', $id, $objecttype); if ($page == -1) - $page = 0 ; + $page = 0; -$limit = GETPOST('limit', 'int')?GETPOST('limit', 'int'):$conf->liste_limit; -$offset = $limit * $page ; +$limit = GETPOST('limit', 'int') ?GETPOST('limit', 'int') : $conf->liste_limit; +$offset = $limit * $page; if ($sortorder == "") - $sortorder="DESC"; + $sortorder = "DESC"; if ($sortfield == "") - $sortfield="f.datec"; + $sortfield = "f.datec"; $object = new FichinterRec($db); $extrafields = new ExtraFields($db); -$arrayfields=array( +$arrayfields = array( 'f.titre'=>array('label'=>$langs->trans("Ref"), 'checked'=>1), 's.nom'=>array('label'=>$langs->trans("ThirdParty"), 'checked'=>1), 'f.fk_contrat'=>array('label'=>$langs->trans("Contract"), 'checked'=>1), @@ -95,26 +95,26 @@ $arrayfields=array( // Create predefined intervention if ($action == 'add') { - if (! GETPOST('titre')) { + if (!GETPOST('titre')) { setEventMessages($langs->transnoentities("ErrorFieldRequired", $langs->trans("Title")), null, 'errors'); $action = "create"; $error++; } - if (! GETPOST('socid')) { + if (!GETPOST('socid')) { setEventMessages($langs->transnoentities("ErrorFieldRequired", $langs->trans("Customer")), null, 'errors'); $action = "create"; $error++; } // gestion des fréquences et des échéances - $frequency=GETPOST('frequency', 'int'); - $reyear=GETPOST('reyear'); - $remonth=GETPOST('remonth'); - $reday=GETPOST('reday'); - $rehour=GETPOST('rehour'); - $remin=GETPOST('remin'); - $nb_gen_max = (GETPOST('nb_gen_max', 'int')?GETPOST('nb_gen_max', 'int'):0); + $frequency = GETPOST('frequency', 'int'); + $reyear = GETPOST('reyear'); + $remonth = GETPOST('remonth'); + $reday = GETPOST('reday'); + $rehour = GETPOST('rehour'); + $remin = GETPOST('remin'); + $nb_gen_max = (GETPOST('nb_gen_max', 'int') ?GETPOST('nb_gen_max', 'int') : 0); if (GETPOST('frequency')) { if (empty($reyear) || empty($remonth) || empty($reday)) { setEventMessages($langs->transnoentities("ErrorFieldRequired", $langs->trans("Date")), null, 'errors'); @@ -128,8 +128,8 @@ if ($action == 'add') { } } - if (! $error) { - $object->id_origin = $id; + if (!$error) { + $object->id_origin = $id; $object->title = GETPOST('titre', 'alpha'); $object->description = GETPOST('description', 'alpha'); $object->socid = GETPOST('socid', 'alpha'); @@ -160,19 +160,19 @@ if ($action == 'add') { // on transfert les données de l'un vers l'autre if ($object->socid > 0) { - $newinter->socid=$object->socid; - $newinter->fk_project=$object->fk_project; - $newinter->fk_contrat=$object->fk_contrat; + $newinter->socid = $object->socid; + $newinter->fk_project = $object->fk_project; + $newinter->fk_contrat = $object->fk_contrat; } else { - $newinter->socid=GETPOST("socid"); + $newinter->socid = GETPOST("socid"); } - $newinter->entity=$object->entity; - $newinter->duree=$object->duree; + $newinter->entity = $object->entity; + $newinter->duree = $object->duree; - $newinter->description=$object->description; - $newinter->note_private=$object->note_private; - $newinter->note_public=$object->note_public; + $newinter->description = $object->description; + $newinter->note_private = $object->note_private; + $newinter->note_public = $object->note_public; // on créer un nouvelle intervention $extrafields->fetch_name_optionals_label($newinter->table_element); @@ -195,13 +195,13 @@ if ($action == 'add') { exit; } else { setEventMessages($newinter->error, $newinter->errors, 'errors'); - $action=''; + $action = ''; } } elseif ($action == 'delete' && $user->rights->ficheinter->supprimer) { // delete modele $object->fetch($id); $object->delete(); - $id = 0 ; + $id = 0; header('Location: '.$_SERVER["PHP_SELF"]); exit; } elseif ($action == 'setfrequency' && $user->rights->ficheinter->creer) { @@ -228,16 +228,16 @@ llxHeader('', $langs->trans("RepeatableInterventional"), 'ch-fichinter.html#s-fa $form = new Form($db); $companystatic = new Societe($db); -if (! empty($conf->contrat->enabled)) { +if (!empty($conf->contrat->enabled)) { $contratstatic = new Contrat($db); } -if (! empty($conf->projet->enabled)) { +if (!empty($conf->projet->enabled)) { $projectstatic = new Project($db); } $now = dol_now(); -$tmparray=dol_getdate($now); -$today = dol_mktime(23, 59, 59, $tmparray['mon'], $tmparray['mday'], $tmparray['year']); // Today is last second of current day +$tmparray = dol_getdate($now); +$today = dol_mktime(23, 59, 59, $tmparray['mon'], $tmparray['mday'], $tmparray['year']); // Today is last second of current day @@ -247,7 +247,7 @@ $today = dol_mktime(23, 59, 59, $tmparray['mon'], $tmparray['mday'], $tmparray[' if ($action == 'create') { print load_fiche_titre($langs->trans("CreateRepeatableIntervention"), '', 'fichinter'); - $object = new Fichinter($db); // Source invoice + $object = new Fichinter($db); // Source invoice //$object = new Managementfichinter($db); // Source invoice if ($object->fetch($id, $ref) > 0) { @@ -258,11 +258,11 @@ if ($action == 'create') { dol_fiche_head(); - $rowspan=4; - if (! empty($conf->projet->enabled) && $object->fk_project > 0) $rowspan++; - if (! empty($conf->contrat->enabled) && $object->fk_contrat > 0) $rowspan++; + $rowspan = 4; + if (!empty($conf->projet->enabled) && $object->fk_project > 0) $rowspan++; + if (!empty($conf->contrat->enabled) && $object->fk_contrat > 0) $rowspan++; - print '
    '.$langs->trans("AvailableFormats").''.$langs->trans("LibraryShort").''.$langs->trans("LibraryVersion").'
    '.img_picto_common($model->getDriverLabelForKey($key), $model->getPictoForKey($key)).''.$form->textwithpicto($label, $text).''.$model->getLibLabelForKey($key).''.$model->getLibVersionForKey($key).'
    '; + print '
    '; $object->fetch_thirdparty(); @@ -297,24 +297,24 @@ if ($action == 'create') { } // Project - if (! empty($conf->projet->enabled)) { + if (!empty($conf->projet->enabled)) { $formproject = new FormProjets($db); print ""; } // Contrat - if (! empty($conf->contrat->enabled)) { + if (!empty($conf->contrat->enabled)) { $formcontract = new FormContract($db); print ""; } @@ -327,14 +327,14 @@ if ($action == 'create') { $title = $langs->trans("Recurrence"); print load_fiche_titre($title, '', 'calendar'); - print '
    ".$langs->trans("Project").""; - $projectid = GETPOST('projectid')?GETPOST('projectid'):$object->fk_project; + $projectid = GETPOST('projectid') ?GETPOST('projectid') : $object->fk_project; $numprojet = $formproject->select_projects($object->thirdparty->id, $projectid, 'projectid', 0, 0, 1, 0, 0, 0, 0, '', 0, 0, ''); print '   '; + print '&socid='.$object->thirdparty->id.(!empty($id) ? '&id='.$id : '').'">'; print $langs->trans("AddProject").''; print "
    ".$langs->trans("Contract").""; - $contractid = GETPOST('contractid')?GETPOST('contractid'):$object->fk_contract; + $contractid = GETPOST('contractid') ?GETPOST('contractid') : $object->fk_contract; $numcontract = $formcontract->select_contract($object->thirdparty->id, $contractid, 'contracttid'); print "
    '; + print '
    '; // Frequency print '"; // First date of execution for cron @@ -370,10 +370,10 @@ if ($action == 'create') { print ''; print ''; print ''; @@ -681,7 +681,7 @@ if ($action == 'create') { print load_fiche_titre($title); - print '
    '; print $form->textwithpicto($langs->trans("Frequency"), $langs->transnoentitiesnoconv('toolTipFrequency')); print ""; print ' '; - print $form->selectarray('unit_frequency', array('d'=>$langs->trans('Day'), 'm'=>$langs->trans('Month'), 'y'=>$langs->trans('Year')), (GETPOST('unit_frequency')?GETPOST('unit_frequency'):'m')); + print $form->selectarray('unit_frequency', array('d'=>$langs->trans('Day'), 'm'=>$langs->trans('Month'), 'y'=>$langs->trans('Year')), (GETPOST('unit_frequency') ?GETPOST('unit_frequency') : 'm')); print "
    '; $sql = 'SELECT l.rowid, l.description, l.duree'; - $sql.= " FROM ".MAIN_DB_PREFIX."fichinterdet as l"; - $sql.= " WHERE l.fk_fichinter= ".$object->id; + $sql .= " FROM ".MAIN_DB_PREFIX."fichinterdet as l"; + $sql .= " WHERE l.fk_fichinter= ".$object->id; //$sql.= " AND l.fk_product is null "; - $sql.= " ORDER BY l.rang"; + $sql .= " ORDER BY l.rang"; $result = $db->query($sql); if ($result) { @@ -381,7 +381,7 @@ if ($action == 'create') { $i = 0; $total = 0; - echo ''; + echo '
    '; if ($num) { print ''; print ''; @@ -433,7 +433,7 @@ if ($action == 'create') { dol_fiche_head(''); print ''; - print '
    '.$langs->trans("Description").'
    '; + print '
    '; print ''; @@ -467,44 +467,44 @@ if ($action == 'create') { // Intervention card $linkback = ''.$langs->trans("BackToList").''; - $morehtmlref='
    '; + $morehtmlref = '
    '; // Thirdparty - $morehtmlref.=$langs->trans('ThirdParty') . ' : ' . $object->thirdparty->getNomUrl(1); + $morehtmlref .= $langs->trans('ThirdParty').' : '.$object->thirdparty->getNomUrl(1); // Project - if (! empty($conf->projet->enabled)) { + if (!empty($conf->projet->enabled)) { $formproject = new FormProjets($db); $langs->load("projects"); - $morehtmlref.='
    '.$langs->trans('Project') . ' '; + $morehtmlref .= '
    '.$langs->trans('Project').' '; if ($user->rights->ficheinter->creer) { if ($action != 'classify') { - $morehtmlref.=''; - $morehtmlref.=img_edit($langs->transnoentitiesnoconv('SetProject')).' : '; + $morehtmlref .= ''; + $morehtmlref .= img_edit($langs->transnoentitiesnoconv('SetProject')).' : '; } if ($action == 'classify') { - $morehtmlref.= ''; - $morehtmlref.= ''; - $morehtmlref.= ''; - $morehtmlref.= $formproject->select_projects($object->socid, $object->fk_project, 'projectid', $maxlength, 0, 1, 0, 1, 0, 0, '', 1); - $morehtmlref.= ''; - $morehtmlref.= ''; + $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); + $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)) { + if (!empty($object->fk_project)) { $proj = new Project($db); $proj->fetch($object->fk_project); - $morehtmlref.= 'trans('ShowProject').'">'; - $morehtmlref.= $proj->ref; - $morehtmlref.= ''; + $morehtmlref .= 'trans('ShowProject').'">'; + $morehtmlref .= $proj->ref; + $morehtmlref .= ''; } else { - $morehtmlref.= ''; + $morehtmlref .= ''; } } } - $morehtmlref.='
    '; + $morehtmlref .= '
    '; dol_banner_tab($object, 'ref', $linkback, 1, 'ref', 'ref', $morehtmlref); @@ -512,7 +512,7 @@ if ($action == 'create') { print '
    '; print '
    '; - print '
    '.$langs->trans("ThirdParty").''; print $form->select_company('', 'socid', '', 1, 1); print '
    '; + print '
    '; print ""; @@ -527,7 +527,7 @@ if ($action == 'create') { print '"; // Contract - if (! empty($conf->contrat->enabled)) { + if (!empty($conf->contrat->enabled)) { $langs->load('contracts'); print ''; print '
    ".$langs->trans("Author").''.$author->getFullName($langs)."
    '.$langs->trans("Description").''.nl2br($object->description)."
    '; @@ -543,7 +543,7 @@ if ($action == 'create') { print '
    '; print '
    '; if ($action == 'contrat') { - $formcontract= new Formcontract($db); + $formcontract = new Formcontract($db); $formcontract->formSelectContract($_SERVER["PHP_SELF"].'?id='.$object->id, $object->socid, $object->fk_contrat, 'contratid', 0, 1); } else { if ($object->fk_contrat) { @@ -569,7 +569,7 @@ if ($action == 'create') { $title = $langs->trans("Recurrence"); print load_fiche_titre($title, '', 'calendar'); - print ''; + print '
    '; // if "frequency" is empty or = 0, the reccurence is disabled print ''; if ($action != 'editfrequency' && $user->rights->ficheinter->creer) { print ''; + print img_edit($langs->trans('Edit'), 1).''; } print '
    '; @@ -578,18 +578,18 @@ if ($action == 'create') { print ''; - print img_edit($langs->trans('Edit'), 1) . '
    '; print '
    '; if ($action == 'editfrequency') { - print '
    '; + print ''; print ''; print ''; print ''; print ''; print ''; print '
    '; print ' '; - print $form->selectarray('unit_frequency', array('d'=>$langs->trans('Day'), 'm'=>$langs->trans('Month'), 'y'=>$langs->trans('Year')), ($object->unit_frequency?$object->unit_frequency:'m')); + print $form->selectarray('unit_frequency', array('d'=>$langs->trans('Day'), 'm'=>$langs->trans('Month'), 'y'=>$langs->trans('Year')), ($object->unit_frequency ? $object->unit_frequency : 'm')); print '
    '; @@ -603,7 +603,7 @@ if ($action == 'create') { // Date when print '
    '; - if ( $user->rights->ficheinter->creer && ($action == 'date_when' || $object->frequency > 0)) { + if ($user->rights->ficheinter->creer && ($action == 'date_when' || $object->frequency > 0)) { print $form->editfieldkey($langs->trans("NextDateToExecution"), 'date_when', $object->date_when, $object, $user->rights->facture->creer, 'day'); } else { print $langs->trans("NextDateToExecution"); @@ -624,7 +624,7 @@ if ($action == 'create') { print ''; 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); + print $form->editfieldval($langs->trans("MaxPeriodNumber"), 'nb_gen_max', $object->nb_gen_max ? $object->nb_gen_max : '', $object, $user->rights->facture->creer); } else print ''; @@ -647,7 +647,7 @@ if ($action == 'create') { // Nb of generation already done print '
    '.$langs->trans("NbOfGenerationDone").''; - print $object->nb_gen_done?$object->nb_gen_done:'0'; + print $object->nb_gen_done ? $object->nb_gen_done : '0'; print '
    '; + print '
    '; print ''; print ''; print ''; @@ -692,13 +692,13 @@ if ($action == 'create') { while ($i < $num) { // Show product and description if (isset($object->lines[$i]->product_type)) - $type=$object->lines[$i]->product_type; + $type = $object->lines[$i]->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 ''; @@ -738,24 +738,24 @@ if ($action == 'create') { * List mode */ $sql = "SELECT f.rowid as fich_rec, s.nom as name, s.rowid as socid, f.rowid as facid, f.titre as title,"; - $sql.= " f.duree, f.fk_contrat, f.fk_projet as fk_project, f.frequency, f.nb_gen_done, f.nb_gen_max,"; - $sql.= " f.date_last_gen, f.date_when, f.datec"; + $sql .= " f.duree, f.fk_contrat, f.fk_projet as fk_project, f.frequency, f.nb_gen_done, f.nb_gen_max,"; + $sql .= " f.date_last_gen, f.date_when, f.datec"; - $sql.= " FROM ".MAIN_DB_PREFIX."fichinter_rec as f"; - $sql.= " , ".MAIN_DB_PREFIX."societe as s "; - if (! $user->rights->societe->client->voir && ! $socid) { + $sql .= " FROM ".MAIN_DB_PREFIX."fichinter_rec as f"; + $sql .= " , ".MAIN_DB_PREFIX."societe as s "; + 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 = ".$conf->entity; + $sql .= " WHERE f.fk_soc = s.rowid"; + $sql .= " AND f.entity = ".$conf->entity; if ($socid) $sql .= " AND s.rowid = ".$socid; - if (! $user->rights->societe->client->voir && ! $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_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 "; @@ -780,14 +780,14 @@ if ($action == 'create') { print $langs->trans("ToCreateAPredefinedInterventional").'

    '; $i = 0; - print '
    '.$langs->trans("Description").''.$langs->trans("Duration").'
    '; + print '
    '; print ''; print_liste_field_titre("Ref", $_SERVER['PHP_SELF'], "f.titre", "", "", 'width="200px"', $sortfield, $sortorder, 'left '); print_liste_field_titre("Company", $_SERVER['PHP_SELF'], "s.nom", "", "", 'width="200px"', $sortfield, $sortorder, 'left '); - if (! empty($conf->contrat->enabled)) { + if (!empty($conf->contrat->enabled)) { print_liste_field_titre("Contract", $_SERVER['PHP_SELF'], "f.fk_contrat", "", "", 'width="100px"', $sortfield, $sortorder, 'left '); } - if (! empty($conf->projet->enabled)) { + if (!empty($conf->projet->enabled)) { print_liste_field_titre("Project", $_SERVER['PHP_SELF'], "f.fk_project", "", "", 'width="100px"', $sortfield, $sortorder, 'left '); } print_liste_field_titre("Duration", $_SERVER['PHP_SELF'], 'f.duree', '', '', 'width="50px"', $sortfield, $sortorder, 'right '); @@ -811,22 +811,22 @@ if ($action == 'create') { print img_object($langs->trans("ShowIntervention"), "intervention").' '.$objp->title; print "\n"; if ($objp->socid) { - $companystatic->id=$objp->socid; - $companystatic->name=$objp->name; + $companystatic->id = $objp->socid; + $companystatic->name = $objp->name; print ''; } else { print ''; } - if (! empty($conf->contrat->enabled)) { + if (!empty($conf->contrat->enabled)) { print ''; } - if (! empty($conf->projet->enabled)) { + if (!empty($conf->projet->enabled)) { print ''; - print ''; + print ''; print ''; print ''; print '
    '.$companystatic->getNomUrl(1, 'customer').''.$langs->trans("None").''; - if ($objp->fk_contrat >0) { + if ($objp->fk_contrat > 0) { $contratstatic->fetch($objp->fk_contrat); print $contratstatic->getNomUrl(1); } print ''; if ($objp->fk_project > 0) { $projectstatic->fetch($objp->fk_project); @@ -837,15 +837,15 @@ if ($action == 'create') { print ''.convertSecondToTime($objp->duree).''.yn($objp->frequency?1:0).''.yn($objp->frequency ? 1 : 0).''; if ($objp->frequency) { - print $objp->nb_gen_done.($objp->nb_gen_max>0?' / '. $objp->nb_gen_max:'') ; + print $objp->nb_gen_done.($objp->nb_gen_max > 0 ? ' / '.$objp->nb_gen_max : ''); print ''; - print dol_print_date($db->jdate($objp->date_last_gen), 'day') ; + print dol_print_date($db->jdate($objp->date_last_gen), 'day'); print ''; diff --git a/htdocs/fichinter/card.php b/htdocs/fichinter/card.php index 684d67346ab..9371c6a308a 100644 --- a/htdocs/fichinter/card.php +++ b/htdocs/fichinter/card.php @@ -35,7 +35,7 @@ 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'; @@ -45,9 +45,9 @@ 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/modules/fichinter/mod_".$conf->global->FICHEINTER_ADDON.'.php'; } require_once DOL_DOCUMENT_ROOT.'/core/class/doleditor.class.php'; require_once DOL_DOCUMENT_ROOT.'/core/class/extrafields.class.php'; @@ -57,28 +57,28 @@ $langs->loadLangs(array('bills', 'companies', 'interventions')); $id = GETPOST('id', 'int'); $ref = GETPOST('ref', 'alpha'); -$socid = GETPOST('socid', 'int'); -$contratid = GETPOST('contratid', 'int'); +$socid = GETPOST('socid', 'int'); +$contratid = GETPOST('contratid', 'int'); $action = GETPOST('action', 'alpha'); $cancel = GETPOST('cancel', 'alpha'); $confirm = GETPOST('confirm', 'alpha'); $mesg = GETPOST('msg', 'alpha'); -$origin=GETPOST('origin', 'alpha'); -$originid=(GETPOST('originid', 'int')?GETPOST('originid', 'int'):GETPOST('origin_id', 'int')); // For backward compatibility +$origin = GETPOST('origin', 'alpha'); +$originid = (GETPOST('originid', 'int') ?GETPOST('originid', 'int') : GETPOST('origin_id', 'int')); // For backward compatibility $note_public = GETPOST('note_public', 'none'); $lineid = GETPOST('line_id', 'int'); //PDF -$hidedetails = (GETPOST('hidedetails', 'int') ? GETPOST('hidedetails', 'int') : (! empty($conf->global->MAIN_GENERATE_DOCUMENTS_HIDE_DETAILS) ? 1 : 0)); -$hidedesc = (GETPOST('hidedesc', 'int') ? GETPOST('hidedesc', 'int') : (! empty($conf->global->MAIN_GENERATE_DOCUMENTS_HIDE_DESC) ? 1 : 0)); -$hideref = (GETPOST('hideref', 'int') ? GETPOST('hideref', 'int') : (! empty($conf->global->MAIN_GENERATE_DOCUMENTS_HIDE_REF) ? 1 : 0)); +$hidedetails = (GETPOST('hidedetails', 'int') ? GETPOST('hidedetails', 'int') : (!empty($conf->global->MAIN_GENERATE_DOCUMENTS_HIDE_DETAILS) ? 1 : 0)); +$hidedesc = (GETPOST('hidedesc', 'int') ? GETPOST('hidedesc', 'int') : (!empty($conf->global->MAIN_GENERATE_DOCUMENTS_HIDE_DESC) ? 1 : 0)); +$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 -$hookmanager->initHooks(array('interventioncard','globalcard')); +$hookmanager->initHooks(array('interventioncard', 'globalcard')); $object = new Fichinter($db); $extrafields = new ExtraFields($db); @@ -86,45 +86,45 @@ $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(); + $ret = $object->fetch($id, $ref); + 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 -$permissiondellink=$user->rights->ficheinter->creer; // Used by the include of actions_dellink.inc.php +$permissionnote = $user->rights->ficheinter->creer; // Used by the include of actions_setnotes.inc.php +$permissiondellink = $user->rights->ficheinter->creer; // Used by the include of actions_dellink.inc.php /* * Actions */ -$parameters=array('socid'=>$socid); -$reshook=$hookmanager->executeHooks('doActions', $parameters, $object, $action); // Note that $action and $object may have been modified by some hooks +$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 ($cancel) { - if (! empty($backtopage)) + if (!empty($backtopage)) { header("Location: ".$backtopage); exit; } - $action=''; + $action = ''; } - include DOL_DOCUMENT_ROOT.'/core/actions_setnotes.inc.php'; // Must be include, not include_once + include DOL_DOCUMENT_ROOT.'/core/actions_setnotes.inc.php'; // Must be include, not include_once - include DOL_DOCUMENT_ROOT.'/core/actions_dellink.inc.php'; // Must be include, not include_once + include DOL_DOCUMENT_ROOT.'/core/actions_dellink.inc.php'; // Must be include, not include_once // Action clone object if ($action == 'confirm_clone' && $confirm == 'yes' && $user->rights->ficheinter->creer) { - if (1==0 && ! GETPOST('clone_content') && ! GETPOST('clone_receivers')) + if (1 == 0 && !GETPOST('clone_content') && !GETPOST('clone_receivers')) { setEventMessages($langs->trans("NoCloneOptionsSpecified"), null, 'errors'); } @@ -135,7 +135,7 @@ if (empty($reshook)) // Because createFromClone modifies the object, we must clone it so that we can restore it later $orig = clone $object; - $result=$object->createFromClone($user, $socid); + $result = $object->createFromClone($user, $socid); if ($result > 0) { header("Location: ".$_SERVER['PHP_SELF'].'?id='.$result); @@ -145,7 +145,7 @@ if (empty($reshook)) { setEventMessages($object->error, $object->errors, 'errors'); $object = $orig; - $action=''; + $action = ''; } } } @@ -161,15 +161,15 @@ 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)) + $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); } - $result=fichinter_create($db, $object, (!GETPOST('model', 'alpha'))?$object->modelpdf:GETPOST('model', 'alpha'), $outputlangs); + $result = fichinter_create($db, $object, (!GETPOST('model', 'alpha')) ? $object->modelpdf : GETPOST('model', 'alpha'), $outputlangs); } header('Location: '.$_SERVER["PHP_SELF"].'?id='.$object->id); @@ -177,7 +177,7 @@ if (empty($reshook)) } else { - $mesg='
    '.$object->error.'
    '; + $mesg = '
    '.$object->error.'
    '; } } @@ -190,15 +190,15 @@ 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)) + $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); } - $result=fichinter_create($db, $object, (!GETPOST('model', 'alpha'))?$object->modelpdf:GETPOST('model', 'alpha'), $outputlangs); + $result = fichinter_create($db, $object, (!GETPOST('model', 'alpha')) ? $object->modelpdf : GETPOST('model', 'alpha'), $outputlangs); } header('Location: '.$_SERVER["PHP_SELF"].'?id='.$object->id); @@ -206,27 +206,27 @@ if (empty($reshook)) } else { - $mesg='
    '.$object->error.'
    '; + $mesg = '
    '.$object->error.'
    '; } } elseif ($action == 'add' && $user->rights->ficheinter->creer) { - $object->socid = $socid; - $object->duration = GETPOST('duration', 'int'); + $object->socid = $socid; + $object->duration = GETPOST('duration', 'int'); $object->fk_project = GETPOST('projectid', 'int'); $object->fk_contrat = GETPOST('contratid', 'int'); - $object->author = $user->id; + $object->author = $user->id; $object->description = GETPOST('description', 'none'); - $object->ref = $ref; - $object->modelpdf = GETPOST('model', 'alpha'); - $object->note_private = GETPOST('note_private', 'none'); - $object->note_public = GETPOST('note_public', 'none'); + $object->ref = $ref; + $object->modelpdf = GETPOST('model', 'alpha'); + $object->note_private = GETPOST('note_private', 'none'); + $object->note_public = GETPOST('note_public', 'none'); 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) $element = $subelement = $_POST['origin']; @@ -237,10 +237,10 @@ if (empty($reshook)) } // For compatibility - if ($element == 'order') { + if ($element == 'order') { $element = $subelement = 'commande'; } - if ($element == 'propal') { + if ($element == 'propal') { $element = 'comm/propal'; $subelement = 'propal'; } if ($element == 'contract') { @@ -252,7 +252,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']); } @@ -273,7 +273,7 @@ if (empty($reshook)) $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); + $result = $srcobject->fetch($object->origin_id); if ($result > 0) { $srcobject->fetch_thirdparty(); @@ -284,12 +284,12 @@ if (empty($reshook)) $lines = $srcobject->lines; } - $fk_parent_line=0; - $num=count($lines); + $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:Product::TYPE_PRODUCT); + $product_type = ($lines[$i]->product_type ? $lines[$i]->product_type : Product::TYPE_PRODUCT); if ($product_type == Product::TYPE_SERVICE || !empty($conf->global->FICHINTER_PRINT_PRODUCTS)) { //only services except if config includes products $duration = 3600; // Default to one hour @@ -301,19 +301,19 @@ if (empty($reshook)) $prod->id = $lines[$i]->fk_product; // 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->getMultiLangs(); // We show if duration is present on service (so we get it) $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)) { + $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); } - $label = (! empty($prod->multilangs[$outputlangs->defaultlang]["libelle"])) ? $prod->multilangs[$outputlangs->defaultlang]["libelle"] : $lines[$i]->product_label; + $label = (!empty($prod->multilangs[$outputlangs->defaultlang]["libelle"])) ? $prod->multilangs[$outputlangs->defaultlang]["libelle"] : $lines[$i]->product_label; } else { $prod->fetch($lines[$i]->fk_product); $label = $lines[$i]->product_label; @@ -349,10 +349,10 @@ if (empty($reshook)) // Common part (predefined or free line) $desc .= dol_htmlentitiesbr($lines[$i]->desc); $desc .= '
    '; - $desc .= ' (' . $langs->trans('Quantity') . ': ' . $lines[$i]->qty . ')'; + $desc .= ' ('.$langs->trans('Quantity').': '.$lines[$i]->qty.')'; - $timearray=dol_getdate(mktime()); - $date_intervention=dol_mktime(0, 0, 0, $timearray['mon'], $timearray['mday'], $timearray['year']); + $timearray = dol_getdate(mktime()); + $date_intervention = dol_mktime(0, 0, 0, $timearray['mon'], $timearray['mday'], $timearray['year']); if ($product_type == Product::TYPE_PRODUCT) { $duration = 0; @@ -383,13 +383,13 @@ if (empty($reshook)) } else { - $mesg=$srcobject->error; + $mesg = $srcobject->error; $error++; } } else { - $mesg=$object->error; + $mesg = $object->error; $error++; } } @@ -398,11 +398,11 @@ if (empty($reshook)) // Fill array 'array_options' with data from add form $ret = $extrafields->setOptionalsFromPost(null, $object); if ($ret < 0) { - $error ++; + $error++; $action = 'create'; } - if (! $error) + if (!$error) { // Extrafields $array_options = $extrafields->getOptionalsFromPost($object->table_element); @@ -412,7 +412,7 @@ if (empty($reshook)) $result = $object->create($user); if ($result > 0) { - $id=$result; // Force raffraichissement sur fiche venant d'etre cree + $id = $result; // Force raffraichissement sur fiche venant d'etre cree } else { @@ -425,22 +425,22 @@ if (empty($reshook)) } else { - $mesg='
    '.$langs->trans("ErrorFieldRequired", $langs->transnoentitiesnoconv("ThirdParty")).'
    '; + $mesg = '
    '.$langs->trans("ErrorFieldRequired", $langs->transnoentitiesnoconv("ThirdParty")).'
    '; $action = 'create'; } } elseif ($action == 'update' && $user->rights->ficheinter->creer) { - $object->socid = $socid; + $object->socid = $socid; $object->fk_project = GETPOST('projectid', 'int'); $object->fk_contrat = GETPOST('contratid', 'int'); - $object->author = $user->id; + $object->author = $user->id; $object->description = GETPOST('description', 'alpha'); - $object->ref = $ref; + $object->ref = $ref; - $result=$object->update($user); - if ($result<0) { + $result = $object->update($user); + if ($result < 0) { setEventMessages($object->error, $object->errors, 'errors'); } } @@ -448,21 +448,21 @@ if (empty($reshook)) // Set into a project elseif ($action == 'classin' && $user->rights->ficheinter->creer) { - $result=$object->setProject(GETPOST('projectid', 'int')); + $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) { - $result=$object->set_contrat($user, GETPOST('contratid', 'int')); + $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) { - $result=$object->delete($user); - if ($result<0) { + $result = $object->delete($user); + if ($result < 0) { setEventMessages($object->error, $object->errors, 'errors'); } @@ -472,42 +472,42 @@ if (empty($reshook)) elseif ($action == 'setdescription' && $user->rights->ficheinter->creer) { - $result=$object->set_description($user, GETPOST('description')); + $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', 'none') && empty($conf->global->FICHINTER_EMPTY_LINE_DESC) ) + if (!GETPOST('np_desc', 'none') && empty($conf->global->FICHINTER_EMPTY_LINE_DESC)) { - $mesg='
    '.$langs->trans("ErrorFieldRequired", $langs->transnoentitiesnoconv("Description")).'
    '; + $mesg = '
    '.$langs->trans("ErrorFieldRequired", $langs->transnoentitiesnoconv("Description")).'
    '; $error++; } if (empty($conf->global->FICHINTER_WITHOUT_DURATION) && !GETPOST('durationhour', 'int') && !GETPOST('durationmin', 'int')) { - $mesg='
    '.$langs->trans("ErrorFieldRequired", $langs->transnoentitiesnoconv("Duration")).'
    '; + $mesg = '
    '.$langs->trans("ErrorFieldRequired", $langs->transnoentitiesnoconv("Duration")).'
    '; $error++; } if (empty($conf->global->FICHINTER_WITHOUT_DURATION) && GETPOST('durationhour', 'int') >= 24 && GETPOST('durationmin', 'int') > 0) { - $mesg='
    '.$langs->trans("ErrorValueTooHigh").'
    '; + $mesg = '
    '.$langs->trans("ErrorValueTooHigh").'
    '; $error++; } - if (! $error) + if (!$error) { $db->begin(); - $desc=GETPOST('np_desc', 'none'); + $desc = GETPOST('np_desc', 'none'); $date_intervention = dol_mktime(GETPOST('dihour', 'int'), GETPOST('dimin', 'int'), 0, GETPOST('dimonth', 'int'), GETPOST('diday', 'int'), GETPOST('diyear', 'int')); - $duration = empty($conf->global->FICHINTER_WITHOUT_DURATION)?convertTime2Seconds(GETPOST('durationhour', 'int'), GETPOST('durationmin', 'int')) : 0; + $duration = empty($conf->global->FICHINTER_WITHOUT_DURATION) ?convertTime2Seconds(GETPOST('durationhour', 'int'), GETPOST('durationmin', 'int')) : 0; // Extrafields $extrafields->fetch_name_optionals_label($object->table_element_line); $array_options = $extrafields->getOptionalsFromPost($object->table_element_line); - $result=$object->addline( + $result = $object->addline( $user, $id, $desc, @@ -518,10 +518,10 @@ 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)) + $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); @@ -537,7 +537,7 @@ if (empty($reshook)) } else { - $mesg=$object->error; + $mesg = $object->error; $db->rollback(); } } @@ -546,7 +546,7 @@ if (empty($reshook)) // Classify Billed elseif ($action == 'classifybilled' && $user->rights->ficheinter->creer) { - $result=$object->setStatut(2); + $result = $object->setStatut(2); if ($result > 0) { header('Location: '.$_SERVER["PHP_SELF"].'?id='.$object->id); @@ -561,7 +561,7 @@ if (empty($reshook)) // Classify unbilled elseif ($action == 'classifyunbilled' && $user->rights->ficheinter->creer) { - $result=$object->setStatut(1); + $result = $object->setStatut(1); if ($result > 0) { header('Location: '.$_SERVER["PHP_SELF"].'?id='.$object->id); @@ -569,14 +569,14 @@ if (empty($reshook)) } else { - $mesg='
    '.$object->error.'
    '; + $mesg = '
    '.$object->error.'
    '; } } // Classify Done elseif ($action == 'classifydone' && $user->rights->ficheinter->creer) { - $result=$object->setStatut(3); + $result = $object->setStatut(3); if ($result > 0) { header('Location: '.$_SERVER["PHP_SELF"].'?id='.$object->id); @@ -606,13 +606,13 @@ if (empty($reshook)) } $object->fetch_thirdparty(); - $desc = GETPOST('np_desc'); - $date_inter = dol_mktime(GETPOST('dihour', 'int'), GETPOST('dimin', 'int'), 0, GETPOST('dimonth', 'int'), GETPOST('diday', 'int'), GETPOST('diyear', 'int')); - $duration = convertTime2Seconds(GETPOST('durationhour', 'int'), GETPOST('durationmin', 'int')); + $desc = GETPOST('np_desc'); + $date_inter = dol_mktime(GETPOST('dihour', 'int'), GETPOST('dimin', 'int'), 0, GETPOST('dimonth', 'int'), GETPOST('diday', 'int'), GETPOST('diyear', 'int')); + $duration = convertTime2Seconds(GETPOST('durationhour', 'int'), GETPOST('durationmin', 'int')); - $objectline->datei = $date_inter; - $objectline->desc = $desc; - $objectline->duration = $duration; + $objectline->datei = $date_inter; + $objectline->desc = $desc; + $objectline->duration = $duration; // Extrafields $extrafields->fetch_name_optionals_label($object->table_element_line); @@ -628,10 +628,10 @@ 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)) + $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); @@ -653,7 +653,7 @@ if (empty($reshook)) dol_print_error($db); exit; } - $result=$objectline->deleteline($user); + $result = $objectline->deleteline($user); if ($object->fetch($objectline->fk_fichinter) <= 0) { @@ -663,10 +663,10 @@ 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)) + $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); @@ -683,10 +683,10 @@ 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)) + $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); @@ -703,10 +703,10 @@ 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)) + $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); @@ -721,9 +721,9 @@ if (empty($reshook)) include DOL_DOCUMENT_ROOT.'/core/actions_printing.inc.php'; // Actions to send emails - $trigger_name='FICHINTER_SENTBYMAIL'; - $autocopy='MAIN_MAIL_AUTOCOPY_FICHINTER_TO'; - $trackid='int'.$object->id; + $trigger_name = 'FICHINTER_SENTBYMAIL'; + $autocopy = 'MAIN_MAIL_AUTOCOPY_FICHINTER_TO'; + $trackid = 'int'.$object->id; include DOL_DOCUMENT_ROOT.'/core/actions_sendmails.inc.php'; // Actions to build doc @@ -739,10 +739,10 @@ if (empty($reshook)) $ret = $extrafields->setOptionalsFromPost(null, $object, GETPOST('attribute', 'none')); if ($ret < 0) $error++; - if (! $error) + if (!$error) { // Actions on extra fields - $result=$object->insertExtraFields('INTERVENTION_MODIFY'); + $result = $object->insertExtraFields('INTERVENTION_MODIFY'); if ($result < 0) { $error++; @@ -752,7 +752,7 @@ if (empty($reshook)) if ($error) $action = 'edit_extras'; } - if (! empty($conf->global->MAIN_DISABLE_CONTACTS_TAB) && $user->rights->ficheinter->creer) + if (!empty($conf->global->MAIN_DISABLE_CONTACTS_TAB) && $user->rights->ficheinter->creer) { if ($action == 'addcontact') { @@ -784,7 +784,7 @@ if (empty($reshook)) // bascule du statut d'un contact elseif ($action == 'swapstatut') { - $result=$object->swapContactStatus(GETPOST('ligne', 'int')); + $result = $object->swapContactStatus(GETPOST('ligne', 'int')); } // Efface un contact @@ -812,7 +812,7 @@ 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 (!empty($conf->projet->enabled)) { $formproject = new FormProjets($db); } llxHeader('', $langs->trans("Intervention")); @@ -823,13 +823,13 @@ if ($action == 'create') * Creation d'une nouvelle fiche d'intervention */ - $soc=new Societe($db); + $soc = new Societe($db); print load_fiche_titre($langs->trans("AddIntervention"), '', 'title_commercial'); dol_htmloutput_mesg($mesg); - if ($socid) $res=$soc->fetch($socid); + if ($socid) $res = $soc->fetch($socid); if (GETPOST('origin') && GETPOST('originid')) { @@ -843,15 +843,15 @@ if ($action == 'create') if ($element == 'project') { - $projectid=GETPOST('originid'); + $projectid = GETPOST('originid'); } else { // For compatibility - if ($element == 'order' || $element == 'commande') { + if ($element == 'order' || $element == 'commande') { $element = $subelement = 'commande'; } - if ($element == 'propal') { + if ($element == 'propal') { $element = 'comm/propal'; $subelement = 'propal'; } if ($element == 'contract') { @@ -870,12 +870,12 @@ if ($action == 'create') } $objectsrc->fetch_thirdparty(); - $projectid = (!empty($objectsrc->fk_project)?$objectsrc->fk_project:''); + $projectid = (!empty($objectsrc->fk_project) ? $objectsrc->fk_project : ''); $soc = $objectsrc->thirdparty; - $note_private = (! empty($objectsrc->note) ? $objectsrc->note : (! empty($objectsrc->note_private) ? $objectsrc->note_private : GETPOST('note_private', 'none'))); - $note_public = (! empty($objectsrc->note_public) ? $objectsrc->note_public : GETPOST('note_public', 'none')); + $note_private = (!empty($objectsrc->note) ? $objectsrc->note : (!empty($objectsrc->note_private) ? $objectsrc->note_private : GETPOST('note_private', 'none'))); + $note_public = (!empty($objectsrc->note_public) ? $objectsrc->note_public : GETPOST('note_public', 'none')); // Object source contacts list $srccontactslist = $objectsrc->liste_contact(-1, 'external', 1); @@ -885,7 +885,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; @@ -901,23 +901,22 @@ if ($action == 'create') if ($socid > 0) { - $soc=new Societe($db); + $soc = new Societe($db); $soc->fetch($socid); print '
    '; print ''; + print ''; + print ''; dol_fiche_head(''); - print ''; + print '
    '; - print ''; print ''; - print ''; - // Ref - print ''; + print ''; // Description (must be a textarea and not html must be allowed (used in list view) print ''; @@ -926,9 +925,9 @@ if ($action == 'create') print ''; // Project - if (! empty($conf->projet->enabled)) + if (!empty($conf->projet->enabled)) { - $formproject=new FormProjets($db); + $formproject = new FormProjets($db); $langs->load("project"); @@ -939,8 +938,8 @@ if ($action == 'create') else $numprojet=select_projects($societe->id,$_POST["projectid"],'projectid'); */ - $numprojet=$formproject->select_projects($soc->id, $projectid, 'projectid'); - if ($numprojet==0) + $numprojet = $formproject->select_projects($soc->id, $projectid, 'projectid'); + if ($numprojet == 0) { print '   '.$langs->trans("AddProject").''; } @@ -952,8 +951,8 @@ if ($action == 'create') { $langs->load("contracts"); print ''; print ''; - print '"; // Public note print ''; - print ''; - print ''; + print ''; print ''; - print ''; // Amount @@ -1037,7 +1036,7 @@ if ($action == 'create') print ''; print ''; } elseif ($origin == 'project' && !empty($projectid)) { - print ''; + print ''; } dol_fiche_end(); @@ -1045,19 +1044,19 @@ if ($action == 'create') print '
    '; print ''; print '     '; - print ''; + print ''; print '
    '; print ''; // Show origin lines - if (! empty($origin) && ! empty($originid) && is_object($objectsrc)) { + if (!empty($origin) && !empty($originid) && is_object($objectsrc)) { $title = $langs->trans('Services'); print load_fiche_titre($title); - print '
    '.$langs->trans("ThirdParty").''.$soc->getNomUrl(1).'
    '.$langs->trans('Ref').''.$langs->trans("Draft").'
    '.$langs->trans('Ref').''.$langs->trans("Draft").'
    '.$langs->trans("Description").'
    '.$langs->trans("Contract").''; - $numcontrat=$formcontract->select_contract($soc->id, GETPOST('contratid', 'int'), 'contratid', 0, 1); - if ($numcontrat==0) + $numcontrat = $formcontract->select_contract($soc->id, GETPOST('contratid', 'int'), 'contratid', 0, 1); + if ($numcontrat == 0) { print '   '.$langs->trans("AddContract").''; } @@ -963,15 +962,15 @@ if ($action == 'create') // Model print '
    '.$langs->trans("DefaultModel").''; - $liste=ModelePDFFicheinter::liste_modeles($db); + print ''; + $liste = ModelePDFFicheinter::liste_modeles($db); print $form->selectarray('model', $liste, $conf->global->FICHEINTER_ADDON_PDF); print "
    '.$langs->trans('NotePublic').''; + print ''.$langs->trans('NotePublic').''; $doleditor = new DolEditor('note_public', $note_public, '', 80, 'dolibarr_notes', 'In', 0, false, true, ROWS_3, '90%'); print $doleditor->Create(1); //print ''; @@ -982,7 +981,7 @@ if ($action == 'create') { print '
    '.$langs->trans('NotePrivate').''; + print ''; $doleditor = new DolEditor('note_private', $note_private, '', 80, 'dolibarr_notes', 'In', 0, false, true, ROWS_3, '90%'); print $doleditor->Create(1); //print ''; @@ -990,8 +989,8 @@ if ($action == 'create') } // Other attributes - $parameters=array('colspan' => ' colspan="2"'); - $reshook=$hookmanager->executeHooks('formObjectOptions', $parameters, $object, $action); // Note that $action and $object may have been modified by hook + $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)) { @@ -999,10 +998,10 @@ if ($action == 'create') } // 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'; + $newclassname = $classname; + if ($newclassname == 'Propal') $newclassname = 'CommercialProposal'; print '
    '.$langs->trans($newclassname).''.$objectsrc->getNomUrl(1).'
    '; + print '
    '; - $objectsrc->printOriginLinesList(empty($conf->global->FICHINTER_PRINT_PRODUCTS)?'services':''); // Show only service, except if option FICHINTER_PRINT_PRODUCTS is on + $objectsrc->printOriginLinesList(empty($conf->global->FICHINTER_PRINT_PRODUCTS) ? 'services' : ''); // Show only service, except if option FICHINTER_PRINT_PRODUCTS is on print '
    '; } @@ -1072,9 +1071,9 @@ if ($action == 'create') print ''; print ''; } elseif ($origin == 'project' && !empty($projectid)) { - print ''; + print ''; } - print ''; + print '
    '; print ''; @@ -1086,13 +1085,13 @@ if ($action == 'create') print ''; print ''; print '     '; - print ''; + print ''; print ''; print ''; } } -elseif ($id > 0 || ! empty($ref)) +elseif ($id > 0 || !empty($ref)) { /* * Affichage en mode visu @@ -1101,7 +1100,7 @@ elseif ($id > 0 || ! empty($ref)) $object->fetch($id, $ref); $object->fetch_thirdparty(); - $soc=new Societe($db); + $soc = new Societe($db); $soc->fetch($object->socid); dol_htmloutput_mesg($mesg); @@ -1110,7 +1109,7 @@ elseif ($id > 0 || ! empty($ref)) dol_fiche_head($head, 'card', $langs->trans("InterventionCard"), -1, 'intervention'); - $formconfirm=''; + $formconfirm = ''; // Confirm deletion of intervention if ($action == 'delete') @@ -1136,7 +1135,7 @@ elseif ($id > 0 || ! empty($ref)) { $numref = $object->ref; } - $text=$langs->trans('ConfirmValidateIntervention', $numref); + $text = $langs->trans('ConfirmValidateIntervention', $numref); $formconfirm = $form->formconfirm($_SERVER["PHP_SELF"].'?id='.$object->id, $langs->trans('ValidateIntervention'), $text, 'confirm_validate', '', 1, 1); } @@ -1162,17 +1161,17 @@ elseif ($id > 0 || ! empty($ref)) // 1), // array('type' => 'checkbox', 'name' => 'update_prices', 'label' => $langs->trans("PuttingPricesUpToDate"), 'value' // => 1), - array('type' => 'other','name' => 'socid','label' => $langs->trans("SelectThirdParty"),'value' => $form->select_company(GETPOST('socid', 'int'), 'socid', '', '', 0, 0, null, 0, 'minwidth200'))); + array('type' => 'other', 'name' => 'socid', 'label' => $langs->trans("SelectThirdParty"), 'value' => $form->select_company(GETPOST('socid', 'int'), 'socid', '', '', 0, 0, null, 0, 'minwidth200'))); // Paiement incomplet. On demande si motif = escompte ou autre - $formconfirm = $form->formconfirm($_SERVER["PHP_SELF"] . '?id=' . $object->id, $langs->trans('ToClone'), $langs->trans('ConfirmCloneIntervention', $object->ref), 'confirm_clone', $formquestion, 'yes', 1); + $formconfirm = $form->formconfirm($_SERVER["PHP_SELF"].'?id='.$object->id, $langs->trans('ToClone'), $langs->trans('ConfirmCloneIntervention', $object->ref), 'confirm_clone', $formquestion, 'yes', 1); } if (!$formconfirm) { - $parameters=array('lineid'=>$lineid); + $parameters = array('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 @@ -1180,49 +1179,49 @@ elseif ($id > 0 || ! empty($ref)) // Intervention card - $linkback = ''.$langs->trans("BackToList").''; + $linkback = ''.$langs->trans("BackToList").''; - $morehtmlref='
    '; + $morehtmlref = '
    '; // Ref customer //$morehtmlref.=$form->editfieldkey("RefCustomer", 'ref_client', $object->ref_client, $object, $user->rights->fichinter->creer, 'string', '', 0, 1); //$morehtmlref.=$form->editfieldval("RefCustomer", 'ref_client', $object->ref_client, $object, $user->rights->fichinter->creer, 'string', '', null, null, '', 1); // Thirdparty - $morehtmlref.=$langs->trans('ThirdParty') . ' : ' . $object->thirdparty->getNomUrl(1); + $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').' '; if ($user->rights->ficheinter->creer) { if ($action != 'classify') { - $morehtmlref.='' . img_edit($langs->transnoentitiesnoconv('SetProject')) . ' : '; + $morehtmlref .= ''.img_edit($langs->transnoentitiesnoconv('SetProject')).' : '; } if ($action == 'classify') { //$morehtmlref.=$form->form_project($_SERVER['PHP_SELF'] . '?id=' . $object->id, $object->socid, $object->fk_project, 'projectid', 0, 0, 1, 1); - $morehtmlref.='
    '; - $morehtmlref.=''; - $morehtmlref.=''; - $morehtmlref.=$formproject->select_projects($object->socid, $object->fk_project, 'projectid', $maxlength, 0, 1, 0, 1, 0, 0, '', 1); - $morehtmlref.=''; - $morehtmlref.=''; + $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); + $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)) { + if (!empty($object->fk_project)) { $proj = new Project($db); $proj->fetch($object->fk_project); - $morehtmlref.=''; - $morehtmlref.=$proj->ref; - $morehtmlref.=''; + $morehtmlref .= ''; + $morehtmlref .= $proj->ref; + $morehtmlref .= ''; } else { - $morehtmlref.=''; + $morehtmlref .= ''; } } } - $morehtmlref.='
    '; + $morehtmlref .= '
    '; dol_banner_tab($object, 'ref', $linkback, 1, 'ref', 'ref', $morehtmlref); @@ -1233,7 +1232,7 @@ elseif ($id > 0 || ! empty($ref)) print '
    '.$langs->trans("ThirdParty").''; print $form->select_company('', 'socid', '', 'SelectThirdParty', 1, 0, null, 0, 'minwidth300'); print '
    '; - if (! empty($conf->global->FICHINTER_USE_PLANNED_AND_DONE_DATES)) + if (!empty($conf->global->FICHINTER_USE_PLANNED_AND_DONE_DATES)) { // Date Start print ''; @@ -1285,7 +1284,7 @@ elseif ($id > 0 || ! empty($ref)) print '
    '.$langs->trans("Dateo").''; if ($action == 'contrat') { - $formcontract= new Formcontract($db); + $formcontract = new Formcontract($db); $formcontract->formSelectContract($_SERVER["PHP_SELF"].'?id='.$object->id, $object->socid, $object->fk_contrat, 'contratid', 0, 1); } else @@ -1308,7 +1307,7 @@ elseif ($id > 0 || ! empty($ref)) // Other attributes $cols = 2; - include DOL_DOCUMENT_ROOT . '/core/tpl/extrafields_view.tpl.php'; + include DOL_DOCUMENT_ROOT.'/core/tpl/extrafields_view.tpl.php'; print '
    '; @@ -1336,14 +1335,14 @@ elseif ($id > 0 || ! empty($ref)) print '

    '; - 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'); @@ -1368,12 +1367,12 @@ elseif ($id > 0 || ! empty($ref)) // Intervention lines $sql = 'SELECT ft.rowid, ft.description, ft.fk_fichinter, ft.duree, ft.rang,'; - $sql.= ' ft.date as date_intervention'; - $sql.= ' FROM '.MAIN_DB_PREFIX.'fichinterdet as ft'; - $sql.= ' WHERE ft.fk_fichinter = '.$object->id; + $sql .= ' ft.date as date_intervention'; + $sql .= ' FROM '.MAIN_DB_PREFIX.'fichinterdet as ft'; + $sql .= ' WHERE ft.fk_fichinter = '.$object->id; if (!empty($conf->global->FICHINTER_HIDE_EMPTY_DURATION)) - $sql.= ' AND ft.duree <> 0'; - $sql.= ' ORDER BY ft.rang ASC, ft.date ASC, ft.rowid'; + $sql .= ' AND ft.duree <> 0'; + $sql .= ' ORDER BY ft.rang ASC, ft.date ASC, ft.rowid'; $resql = $db->query($sql); if ($resql) @@ -1384,12 +1383,12 @@ elseif ($id > 0 || ! empty($ref)) if ($num) { print '
    '; - print ''; + print '
    '; print ''; print ''; print ''; - print ''; + print ''; print ''; print ''; print ''; @@ -1409,16 +1408,16 @@ elseif ($id > 0 || ! empty($ref)) print dol_htmlentitiesbr($objp->description); // Date - print ''; + print ''; // Duration - print ''; + print ''; print "\n"; // Icone d'edition et suppression - if ($object->statut == 0 && $user->rights->ficheinter->creer) + if ($object->statut == 0 && $user->rights->ficheinter->creer) { print ''; @@ -1498,7 +1497,7 @@ elseif ($id > 0 || ! empty($ref)) print ''; - print '' . "\n"; + print ''."\n"; $line = new FichinterLigne($db); $line->fetch($objp->rowid); @@ -1517,16 +1516,16 @@ elseif ($id > 0 || ! empty($ref)) // Add new line if ($object->statut == 0 && $user->rights->ficheinter->creer && $action <> 'editline' && empty($conf->global->FICHINTER_DISABLE_DETAILS)) { - if (! $num) + if (!$num) { - print '
    '.$langs->trans('Description').''.$langs->trans('Date').''.(empty($conf->global->FICHINTER_WITHOUT_DURATION)?$langs->trans('Duration'):'').''.(empty($conf->global->FICHINTER_WITHOUT_DURATION) ? $langs->trans('Duration') : '').'   '.(empty($conf->global->FICHINTER_DATE_WITHOUT_HOUR)?dol_print_date($db->jdate($objp->date_intervention), 'dayhour'):dol_print_date($db->jdate($objp->date_intervention), 'day')).''.(empty($conf->global->FICHINTER_DATE_WITHOUT_HOUR) ?dol_print_date($db->jdate($objp->date_intervention), 'dayhour') : dol_print_date($db->jdate($objp->date_intervention), 'day')).''.(empty($conf->global->FICHINTER_WITHOUT_DURATION)?convertSecondToTime($objp->duree):'').''.(empty($conf->global->FICHINTER_WITHOUT_DURATION) ?convertSecondToTime($objp->duree) : '').''; print 'rowid.'#'.$objp->rowid.'">'; @@ -1438,7 +1437,7 @@ elseif ($id > 0 || ! empty($ref)) print img_up(); print ''; } - if ($i < $num-1) + if ($i < $num - 1) { print 'rowid.'">'; print img_down(); @@ -1473,7 +1472,7 @@ elseif ($id > 0 || ! empty($ref)) // Editeur wysiwyg require_once DOL_DOCUMENT_ROOT.'/core/class/doleditor.class.php'; - $doleditor=new DolEditor('np_desc', $objp->description, '', 164, 'dolibarr_details', '', false, true, $conf->global->FCKEDITOR_ENABLE_DETAILS, ROWS_2, '90%'); + $doleditor = new DolEditor('np_desc', $objp->description, '', 164, 'dolibarr_details', '', false, true, $conf->global->FCKEDITOR_ENABLE_DETAILS, ROWS_2, '90%'); $doleditor->Create(); print ''; print '
    '; + print '
    '; print ''; print ''; print ''; - print ''; + print ''; print ''; print "\n"; } @@ -1535,7 +1534,7 @@ elseif ($id > 0 || ! empty($ref)) print '
    '; print ''; // ancre print $langs->trans('Description').''.$langs->trans('Date').''.(empty($conf->global->FICHINTER_WITHOUT_DURATION)?$langs->trans('Duration'):'').''.(empty($conf->global->FICHINTER_WITHOUT_DURATION) ? $langs->trans('Duration') : '').' 
    '; // editeur wysiwyg if (empty($conf->global->FICHINTER_EMPTY_LINE_DESC)) { - require_once DOL_DOCUMENT_ROOT . '/core/class/doleditor.class.php'; + require_once DOL_DOCUMENT_ROOT.'/core/class/doleditor.class.php'; $doleditor = new DolEditor('np_desc', GETPOST('np_desc', 'alpha'), '', 100, 'dolibarr_details', '', false, true, $conf->global->FCKEDITOR_ENABLE_DETAILS, ROWS_2, '90%'); $doleditor->Create(); } @@ -1543,12 +1542,12 @@ elseif ($id > 0 || ! empty($ref)) // Date intervention print ''; - $now=dol_now(); - $timearray=dol_getdate($now); - if (! GETPOST('diday', 'int')) { - $timewithnohour=dol_mktime(0, 0, 0, $timearray['mon'], $timearray['mday'], $timearray['year']); + $now = dol_now(); + $timearray = dol_getdate($now); + if (!GETPOST('diday', 'int')) { + $timewithnohour = dol_mktime(0, 0, 0, $timearray['mon'], $timearray['mday'], $timearray['year']); } else { - $timewithnohour=dol_mktime(GETPOST('dihour', 'int'), GETPOST('dimin', 'int'), 0, GETPOST('dimonth', 'int'), GETPOST('diday', 'int'), GETPOST('diyear', 'int')); + $timewithnohour = dol_mktime(GETPOST('dihour', 'int'), GETPOST('dimin', 'int'), 0, GETPOST('dimonth', 'int'), GETPOST('diday', 'int'), GETPOST('diyear', 'int')); } if (!empty($conf->global->FICHINTER_DATE_WITHOUT_HOUR)) { print $form->selectDate($timewithnohour, 'di', 0, 0, 0, "addinter"); @@ -1579,7 +1578,7 @@ elseif ($id > 0 || ! empty($ref)) print $lineadd->showOptionals($extrafields, 'edit', array('colspan'=>5)); - if (! $num) print '
    '; + if (!$num) print '
    '; } if ($num) print '
    '; @@ -1614,8 +1613,8 @@ elseif ($id > 0 || ! empty($ref)) // Validate if ($object->statut == Fichinter::STATUS_DRAFT && (count($object->lines) > 0 || !empty($conf->global->FICHINTER_DISABLE_DETAILS))) { if ((empty($conf->global->MAIN_USE_ADVANCED_PERMS) && $user->rights->ficheinter->creer) || (!empty($conf->global->MAIN_USE_ADVANCED_PERMS) && $user->rights->ficheinter->ficheinter_advance->validate)) { - print ''; + print ''; } } @@ -1639,14 +1638,14 @@ elseif ($id > 0 || ! empty($ref)) } // create intervention model - if ($conf->global->MAIN_FEATURES_LEVEL >=2 && $object->statut == Fichinter::STATUS_DRAFT && $user->rights->ficheinter->creer && (count($object->lines) > 0)) { + if ($conf->global->MAIN_FEATURES_LEVEL >= 2 && $object->statut == Fichinter::STATUS_DRAFT && $user->rights->ficheinter->creer && (count($object->lines) > 0)) { print ''; } // 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) @@ -1657,7 +1656,7 @@ elseif ($id > 0 || ! empty($ref)) } // 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) @@ -1666,7 +1665,7 @@ elseif ($id > 0 || ! empty($ref)) else print ''; } - 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 (!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) { @@ -1687,7 +1686,7 @@ elseif ($id > 0 || ! empty($ref)) // Clone if ($user->rights->ficheinter->creer) { - print ''; + print ''; } // Delete @@ -1709,11 +1708,11 @@ elseif ($id > 0 || ! empty($ref)) /* * Built documents */ - $filename=dol_sanitizeFileName($object->ref); - $filedir=$conf->ficheinter->dir_output . "/".$filename; - $urlsource=$_SERVER["PHP_SELF"]."?id=".$object->id; - $genallowed=$user->rights->ficheinter->lire; - $delallowed=$user->rights->ficheinter->creer; + $filename = dol_sanitizeFileName($object->ref); + $filedir = $conf->ficheinter->dir_output."/".$filename; + $urlsource = $_SERVER["PHP_SELF"]."?id=".$object->id; + $genallowed = $user->rights->ficheinter->lire; + $delallowed = $user->rights->ficheinter->creer; print $formfile->showdocuments('ficheinter', $filename, $filedir, $urlsource, $genallowed, $delallowed, $object->modelpdf, 1, 0, 0, 28, 0, '', '', '', $soc->default_lang); // Show links to link elements @@ -1725,7 +1724,7 @@ elseif ($id > 0 || ! empty($ref)) // List of actions on element include_once DOL_DOCUMENT_ROOT.'/core/class/html.formactions.class.php'; - $formactions=new FormActions($db); + $formactions = new FormActions($db); $somethingshown = $formactions->showactions($object, 'fichinter', $socid, 1); print ''; @@ -1738,8 +1737,8 @@ elseif ($id > 0 || ! empty($ref)) } // Presend form - $modelmail='fichinter_send'; - $defaulttopic='SendInterventionRef'; + $modelmail = 'fichinter_send'; + $defaulttopic = 'SendInterventionRef'; $diroutput = $conf->ficheinter->dir_output; $trackid = 'int'.$object->id; diff --git a/htdocs/fichinter/class/fichinterrec.class.php b/htdocs/fichinter/class/fichinterrec.class.php index f599cccf801..d4f526d9847 100644 --- a/htdocs/fichinter/class/fichinterrec.class.php +++ b/htdocs/fichinter/class/fichinterrec.class.php @@ -78,14 +78,14 @@ class FichinterRec extends Fichinter $this->db = $db; //status dans l'ordre de l'intervention - $this->statuts[0]='Draft'; - $this->statuts[1]='Closed'; + $this->statuts[0] = 'Draft'; + $this->statuts[1] = 'Closed'; - $this->statuts_short[0]='Draft'; - $this->statuts_short[1]='Closed'; + $this->statuts_short[0] = 'Draft'; + $this->statuts_short[1] = 'Closed'; - $this->statuts_logo[0]='statut0'; - $this->statuts_logo[1]='statut1'; + $this->statuts_logo[0] = 'statut0'; + $this->statuts_logo[1] = 'statut1'; } /** @@ -111,8 +111,8 @@ class FichinterRec extends Fichinter { global $conf; - $error=0; - $now=dol_now(); + $error = 0; + $now = dol_now(); // Clean parameters $this->title = trim($this->title); @@ -133,56 +133,56 @@ class FichinterRec extends Fichinter $this->brouillon = 1; $sql = "INSERT INTO ".MAIN_DB_PREFIX."fichinter_rec ("; - $sql.= "titre"; - $sql.= ", fk_soc"; - $sql.= ", entity"; - $sql.= ", datec"; - $sql.= ", duree"; - $sql.= ", description"; - $sql.= ", note_private"; - $sql.= ", note_public"; - $sql.= ", fk_user_author"; - $sql.= ", fk_projet"; - $sql.= ", fk_contrat"; - $sql.= ", modelpdf"; + $sql .= "titre"; + $sql .= ", fk_soc"; + $sql .= ", entity"; + $sql .= ", datec"; + $sql .= ", duree"; + $sql .= ", description"; + $sql .= ", note_private"; + $sql .= ", note_public"; + $sql .= ", fk_user_author"; + $sql .= ", fk_projet"; + $sql .= ", fk_contrat"; + $sql .= ", modelpdf"; - $sql.= ", frequency"; - $sql.= ", unit_frequency"; - $sql.= ", date_when"; - $sql.= ", date_last_gen"; - $sql.= ", nb_gen_done"; - $sql.= ", nb_gen_max"; + $sql .= ", frequency"; + $sql .= ", unit_frequency"; + $sql .= ", date_when"; + $sql .= ", date_last_gen"; + $sql .= ", nb_gen_done"; + $sql .= ", nb_gen_max"; // $sql.= ", auto_validate"; - $sql.= ") VALUES ("; - $sql.= "'".$this->db->escape($this->title)."'"; - $sql.= ", ".($this->socid >0 ? $this->socid : 'null'); - $sql.= ", ".$conf->entity; - $sql.= ", '".$this->db->idate($now)."'"; - $sql.= ", ".(!empty($fichintsrc->duration)?$fichintsrc->duration:'0'); - $sql.= ", ".(!empty($this->description)?("'".$this->db->escape($this->description)."'"):"null"); - $sql.= ", ".(!empty($fichintsrc->note_private)?("'".$this->db->escape($fichintsrc->note_private)."'"):"null"); - $sql.= ", ".(!empty($fichintsrc->note_public)?("'".$this->db->escape($fichintsrc->note_public)."'"):"null"); - $sql.= ", '".$user->id."'"; + $sql .= ") VALUES ("; + $sql .= "'".$this->db->escape($this->title)."'"; + $sql .= ", ".($this->socid > 0 ? $this->socid : 'null'); + $sql .= ", ".$conf->entity; + $sql .= ", '".$this->db->idate($now)."'"; + $sql .= ", ".(!empty($fichintsrc->duration) ? $fichintsrc->duration : '0'); + $sql .= ", ".(!empty($this->description) ? ("'".$this->db->escape($this->description)."'") : "null"); + $sql .= ", ".(!empty($fichintsrc->note_private) ? ("'".$this->db->escape($fichintsrc->note_private)."'") : "null"); + $sql .= ", ".(!empty($fichintsrc->note_public) ? ("'".$this->db->escape($fichintsrc->note_public)."'") : "null"); + $sql .= ", '".$user->id."'"; // si c'est la même société on conserve les liens vers le projet et le contrat if ($this->socid == $fichintsrc->socid) { - $sql.= ", ".(! empty($fichintsrc->fk_project)?$fichintsrc->fk_project:"null"); - $sql.= ", ".(! empty($fichintsrc->fk_contrat)?$fichintsrc->fk_contrat:"null"); + $sql .= ", ".(!empty($fichintsrc->fk_project) ? $fichintsrc->fk_project : "null"); + $sql .= ", ".(!empty($fichintsrc->fk_contrat) ? $fichintsrc->fk_contrat : "null"); } else { - $sql.= ", null, null"; + $sql .= ", null, null"; } - $sql.= ", ".(! empty($fichintsrc->modelpdf)?"'".$this->db->escape($fichintsrc->modelpdf)."'":"''"); + $sql .= ", ".(!empty($fichintsrc->modelpdf) ? "'".$this->db->escape($fichintsrc->modelpdf)."'" : "''"); // récurrence - $sql.= ", ".(! empty($this->frequency)?$this->frequency:"null"); - $sql.= ", '".$this->db->escape($this->unit_frequency)."'"; - $sql.= ", ".(!empty($this->date_when)?"'".$this->db->idate($this->date_when)."'":'null'); - $sql.= ", ".(!empty($this->date_last_gen)?"'".$this->db->idate($this->date_last_gen)."'":'null'); - $sql.= ", 0"; // we start à 0 - $sql.= ", ".$this->nb_gen_max; + $sql .= ", ".(!empty($this->frequency) ? $this->frequency : "null"); + $sql .= ", '".$this->db->escape($this->unit_frequency)."'"; + $sql .= ", ".(!empty($this->date_when) ? "'".$this->db->idate($this->date_when)."'" : 'null'); + $sql .= ", ".(!empty($this->date_last_gen) ? "'".$this->db->idate($this->date_last_gen)."'" : 'null'); + $sql .= ", 0"; // we start à 0 + $sql .= ", ".$this->nb_gen_max; // $sql.= ", ".$this->auto_validate; - $sql.= ")"; + $sql .= ")"; if ($this->db->query($sql)) { $this->id = $this->db->last_insert_id(MAIN_DB_PREFIX.$this->table_element); @@ -190,7 +190,7 @@ class FichinterRec extends Fichinter /* * Lines */ - $num=count($fichintsrc->lines); + $num = count($fichintsrc->lines); for ($i = 0; $i < $num; $i++) { //$result=$fichintlignesrc->fetch($fichintsrc->lines[$i]->id); @@ -226,7 +226,7 @@ class FichinterRec extends Fichinter return $this->id; } } else { - $this->error=$this->db->error().' sql='.$sql; + $this->error = $this->db->error().' sql='.$sql; $this->db->rollback(); return -2; } @@ -249,14 +249,14 @@ class FichinterRec extends Fichinter public function fetch($rowid = 0, $ref = '', $ref_ext = '', $ref_int = '') { $sql = 'SELECT f.titre, f.fk_soc'; - $sql.= ', f.datec, f.duree, f.fk_projet, f.fk_contrat, f.description'; - $sql.= ', f.note_private, f.note_public, f.fk_user_author'; - $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 .= ', f.datec, f.duree, f.fk_projet, f.fk_contrat, f.description'; + $sql .= ', f.note_private, f.note_public, f.fk_user_author'; + $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)."'"; + $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)."'"; /* This field are not used for template fichinter if ($ref_ext) $sql.= " AND f.ref_ext='".$this->db->escape($ref_ext)."'"; @@ -270,28 +270,28 @@ class FichinterRec extends Fichinter if ($this->db->num_rows($result)) { $obj = $this->db->fetch_object($result); - $this->id = $rowid; + $this->id = $rowid; $this->titre = $obj->titre; - $this->ref = $obj->titre; - $this->description = $obj->description; + $this->ref = $obj->titre; + $this->description = $obj->description; $this->datec = $obj->datec; $this->duration = $obj->duree; $this->socid = $obj->fk_soc; - $this->statut = 0; + $this->statut = 0; $this->fk_project = $obj->fk_projet; $this->fk_contrat = $obj->fk_contrat; - $this->note_private = $obj->note_private; + $this->note_private = $obj->note_private; $this->note_public = $obj->note_public; $this->user_author = $obj->fk_user_author; $this->modelpdf = $obj->model_pdf; - $this->rang = $obj->rang; - $this->special_code = $obj->special_code; + $this->rang = $obj->rang; + $this->special_code = $obj->special_code; $this->frequency = $obj->frequency; - $this->unit_frequency = $obj->unit_frequency; + $this->unit_frequency = $obj->unit_frequency; $this->date_when = $this->db->jdate($obj->date_when); $this->date_last_gen = $this->db->jdate($obj->date_last_gen); - $this->nb_gen_done = $obj->nb_gen_done; - $this->nb_gen_max = $obj->nb_gen_max; + $this->nb_gen_done = $obj->nb_gen_done; + $this->nb_gen_max = $obj->nb_gen_max; $this->auto_validate = $obj->auto_validate; $this->brouillon = 1; @@ -299,19 +299,19 @@ class FichinterRec extends Fichinter /* * Lines */ - $result=$this->fetch_lines(); + $result = $this->fetch_lines(); if ($result < 0) { - $this->error=$this->db->error(); + $this->error = $this->db->error(); return -3; } return 1; } else { - $this->error='Interventional with id '.$rowid.' not found sql='.$sql; + $this->error = 'Interventional with id '.$rowid.' not found sql='.$sql; dol_syslog(get_class($this).'::Fetch Error '.$this->error, LOG_ERR); return -2; } } else { - $this->error=$this->db->error(); + $this->error = $this->db->error(); return -1; } } @@ -328,14 +328,14 @@ class FichinterRec extends Fichinter { // phpcs:enable $sql = 'SELECT l.rowid, l.fk_product, l.product_type, l.label as custom_label, l.description, '; - $sql.= ' l.price, l.qty, l.tva_tx, l.remise, l.remise_percent, l.subprice, l.duree, '; - $sql.= ' l.total_ht, l.total_tva, l.total_ttc,'; - $sql.= ' l.rang, l.special_code,'; - $sql.= ' l.fk_unit, p.ref as product_ref, p.fk_product_type as fk_product_type,'; - $sql.= ' p.label as product_label, p.description as product_desc'; - $sql.= ' FROM '.MAIN_DB_PREFIX.'fichinterdet_rec as l'; - $sql.= ' LEFT JOIN '.MAIN_DB_PREFIX.'product as p ON l.fk_product = p.rowid'; - $sql.= ' WHERE l.fk_fichinter = '.$this->id; + $sql .= ' l.price, l.qty, l.tva_tx, l.remise, l.remise_percent, l.subprice, l.duree, '; + $sql .= ' l.total_ht, l.total_tva, l.total_ttc,'; + $sql .= ' l.rang, l.special_code,'; + $sql .= ' l.fk_unit, p.ref as product_ref, p.fk_product_type as fk_product_type,'; + $sql .= ' p.label as product_label, p.description as product_desc'; + $sql .= ' FROM '.MAIN_DB_PREFIX.'fichinterdet_rec as l'; + $sql .= ' LEFT JOIN '.MAIN_DB_PREFIX.'product as p ON l.fk_product = p.rowid'; + $sql .= ' WHERE l.fk_fichinter = '.$this->id; dol_syslog('FichInter-rec::fetch_lines', LOG_DEBUG); $result = $this->db->query($sql); @@ -388,7 +388,7 @@ class FichinterRec extends Fichinter $this->db->free($result); return 1; } else { - $this->error=$this->db->error(); + $this->error = $this->db->error(); return -3; } } @@ -404,11 +404,11 @@ 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); - $error=0; + $error = 0; $this->db->begin(); $sql = "DELETE FROM ".MAIN_DB_PREFIX."fichinterdet_rec WHERE fk_fichinter = ".$rowid; @@ -416,16 +416,16 @@ class FichinterRec extends Fichinter if ($this->db->query($sql)) { $sql = "DELETE FROM ".MAIN_DB_PREFIX."fichinter_rec WHERE rowid = ".$rowid; dol_syslog($sql); - if (! $this->db->query($sql)) { - $this->error=$this->db->lasterror(); - $error=-1; + if (!$this->db->query($sql)) { + $this->error = $this->db->lasterror(); + $error = -1; } } else { - $this->error=$this->db->lasterror(); - $error=-2; + $this->error = $this->db->lasterror(); + $error = -2; } - if (! $error) { + if (!$error) { $this->db->commit(); return 1; } else { @@ -470,16 +470,16 @@ class FichinterRec extends Fichinter // 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); $txtva = price2num($txtva); - if ($price_base_type=='HT') { - $pu=$pu_ht; + if ($price_base_type == 'HT') { + $pu = $pu_ht; } else { - $pu=$pu_ttc; + $pu = $pu_ttc; } @@ -501,52 +501,52 @@ class FichinterRec extends Fichinter } $sql = "INSERT INTO ".MAIN_DB_PREFIX."fichinterdet_rec ("; - $sql.= "fk_fichinter"; - $sql.= ", label"; - $sql.= ", description"; - $sql.= ", date"; - $sql.= ", duree"; + $sql .= "fk_fichinter"; + $sql .= ", label"; + $sql .= ", description"; + $sql .= ", date"; + $sql .= ", duree"; //$sql.= ", price"; //$sql.= ", qty"; //$sql.= ", tva_tx"; - $sql.= ", fk_product"; - $sql.= ", product_type"; - $sql.= ", remise_percent"; + $sql .= ", fk_product"; + $sql .= ", product_type"; + $sql .= ", remise_percent"; //$sql.= ", subprice"; - $sql.= ", remise"; - $sql.= ", total_ht"; - $sql.= ", total_tva"; - $sql.= ", total_ttc"; - $sql.= ", rang"; + $sql .= ", remise"; + $sql .= ", total_ht"; + $sql .= ", total_tva"; + $sql .= ", total_ttc"; + $sql .= ", rang"; //$sql.= ", special_code"; - $sql.= ", fk_unit"; - $sql.= ") VALUES ("; - $sql.= (int) $this->id; - $sql.= ", ".(! empty($label)?"'".$this->db->escape($label)."'":"null"); - $sql.= ", ".(! empty($desc)?"'".$this->db->escape($desc)."'":"null"); - $sql.= ", ".(! empty($datei)?"'".$this->db->idate($datei)."'":"null"); - $sql.= ", ".$duration; + $sql .= ", fk_unit"; + $sql .= ") VALUES ("; + $sql .= (int) $this->id; + $sql .= ", ".(!empty($label) ? "'".$this->db->escape($label)."'" : "null"); + $sql .= ", ".(!empty($desc) ? "'".$this->db->escape($desc)."'" : "null"); + $sql .= ", ".(!empty($datei) ? "'".$this->db->idate($datei)."'" : "null"); + $sql .= ", ".$duration; //$sql.= ", ".price2num($pu_ht); //$sql.= ", ".(!empty($qty)? $qty :(!empty($duration)? $duration :"null")); //$sql.= ", ".price2num($txtva); - $sql.= ", ".(! empty($fk_product)? $fk_product :"null"); - $sql.= ", ".$product_type; - $sql.= ", ".(! empty($remise_percent)? $remise_percent:"null"); + $sql .= ", ".(!empty($fk_product) ? $fk_product : "null"); + $sql .= ", ".$product_type; + $sql .= ", ".(!empty($remise_percent) ? $remise_percent : "null"); //$sql.= ", '".price2num($pu_ht)."'"; - $sql.= ", null"; - $sql.= ", '".price2num($total_ht)."'"; - $sql.= ", '".price2num($total_tva)."'"; - $sql.= ", '".price2num($total_ttc)."'"; - $sql.= ", ".(int) $rang; + $sql .= ", null"; + $sql .= ", '".price2num($total_ht)."'"; + $sql .= ", '".price2num($total_tva)."'"; + $sql .= ", '".price2num($total_ttc)."'"; + $sql .= ", ".(int) $rang; //$sql.= ", ".$special_code; - $sql.= ", ".(! empty($fk_unit) ? $fk_unit :"null"); - $sql.= ")"; + $sql .= ", ".(!empty($fk_unit) ? $fk_unit : "null"); + $sql .= ")"; dol_syslog(get_class($this)."::addline", LOG_DEBUG); if ($this->db->query($sql)) { return 1; } else { - $this->error=$this->db->lasterror(); + $this->error = $this->db->lasterror(); return -1; } } @@ -600,26 +600,26 @@ class FichinterRec extends Fichinter { global $langs; - $result=''; - $label=$langs->trans("ShowInterventionModel").': '.$this->ref; + $result = ''; + $label = $langs->trans("ShowInterventionModel").': '.$this->ref; $url = DOL_URL_ROOT.'/fichinter/card-rec.php?id='.$this->id; if ($short) return $url; - $picto='intervention'; + $picto = 'intervention'; $link = ''; - $linkend=''; + $linkend = ''; if ($withpicto) { - $result.= $link.img_object($label, $picto, 'class="classfortooltip"').$linkend; + $result .= $link.img_object($label, $picto, 'class="classfortooltip"').$linkend; } if ($withpicto && $withpicto != 2) { - $result.=' '; + $result .= ' '; } if ($withpicto != 2) { - $result.=$link.$this->ref.$linkend; + $result .= $link.$this->ref.$linkend; } return $result; } @@ -637,9 +637,9 @@ class FichinterRec extends Fichinter { global $user, $langs, $conf; - $now=dol_now(); - $arraynow=dol_getdate($now); - $nownotime=dol_mktime(0, 0, 0, $arraynow['mon'], $arraynow['mday'], $arraynow['year']); + $now = dol_now(); + $arraynow = dol_getdate($now); + $nownotime = dol_mktime(0, 0, 0, $arraynow['mon'], $arraynow['mday'], $arraynow['year']); parent::initAsSpecimen($option); @@ -656,7 +656,7 @@ class FichinterRec extends Fichinter */ public static function replaceThirdparty(DoliDB $db, $origin_id, $dest_id) { - $tables = array( 'fichinter_rec' ); + $tables = array('fichinter_rec'); return CommonObject::commonReplaceThirdparty($db, $origin_id, $dest_id, $tables); } @@ -671,7 +671,7 @@ class FichinterRec extends Fichinter */ public function setFrequencyAndUnit($frequency, $unit) { - if (! $this->table_element) { + if (!$this->table_element) { dol_syslog(get_class($this)."::setFrequencyAndUnit called with table_element not defined", LOG_ERR); return -1; } @@ -682,11 +682,11 @@ class FichinterRec extends Fichinter } $sql = 'UPDATE '.MAIN_DB_PREFIX.$this->table_element; - $sql.= ' SET frequency = '.($frequency?$this->db->escape($frequency):'null'); + $sql .= ' SET frequency = '.($frequency ? $this->db->escape($frequency) : 'null'); if (!empty($unit)) { - $sql.= ', unit_frequency = "'.$this->db->escape($unit).'"'; + $sql .= ', unit_frequency = "'.$this->db->escape($unit).'"'; } - $sql.= ' WHERE rowid = '.$this->id; + $sql .= ' WHERE rowid = '.$this->id; dol_syslog(get_class($this)."::setFrequencyAndUnit", LOG_DEBUG); if ($this->db->query($sql)) { @@ -708,19 +708,19 @@ class FichinterRec extends Fichinter */ 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'; - $sql.= ' WHERE rowid = '.$this->id; + $sql .= " SET date_when = ".($date ? "'".$this->db->idate($date)."'" : "null"); + 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); @@ -736,16 +736,16 @@ class FichinterRec extends Fichinter */ 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; + $sql .= ' SET nb_gen_max = '.$nb; + $sql .= ' WHERE rowid = '.$this->id; dol_syslog(get_class($this)."::setMaxPeriod", LOG_DEBUG); if ($this->db->query($sql)) { @@ -765,14 +765,14 @@ class FichinterRec extends Fichinter */ public function setAutoValidate($validate) { - if (! $this->table_element) { + if (!$this->table_element) { dol_syslog(get_class($this)."::setAutoValidate called with property table_element not defined", LOG_ERR); return -1; } $sql = 'UPDATE '.MAIN_DB_PREFIX.$this->table_element; - $sql.= ' SET auto_validate = '.$validate; - $sql.= ' WHERE rowid = '.$this->id; + $sql .= ' SET auto_validate = '.$validate; + $sql .= ' WHERE rowid = '.$this->id; dol_syslog(get_class($this)."::setAutoValidate", LOG_DEBUG); if ($this->db->query($sql)) { @@ -791,23 +791,23 @@ class FichinterRec extends Fichinter */ public function updateNbGenDone() { - if (! $this->table_element) { + if (!$this->table_element) { dol_syslog(get_class($this)."::updateNbGenDone called with property table_element not defined", LOG_ERR); return -1; } $sql = 'UPDATE '.MAIN_DB_PREFIX.$this->table_element; - $sql.= ' SET nb_gen_done = nb_gen_done + 1'; - $sql.= ' , date_last_gen = now()'; + $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) - $sql.= ' , statut = 1'; + if ($this->nb_gen_max == $this->nb_gen_done + 1) + $sql .= ' , statut = 1'; - $sql.= ' WHERE rowid = '.$this->id; + $sql .= ' WHERE rowid = '.$this->id; dol_syslog(get_class($this)."::setAutoValidate", LOG_DEBUG); if ($this->db->query($sql)) { - $this->nb_gen_done = $this->nb_gen_done+1; + $this->nb_gen_done = $this->nb_gen_done + 1; $this->nb_gen_done = dol_now(); return 1; } else { diff --git a/htdocs/fichinter/contact.php b/htdocs/fichinter/contact.php index 562a38f7ea8..2d3531a838a 100644 --- a/htdocs/fichinter/contact.php +++ b/htdocs/fichinter/contact.php @@ -83,7 +83,7 @@ if ($action == 'addcontact' && $user->rights->ficheinter->creer) // Toggle the status of a contact elseif ($action == 'swapstatut' && $user->rights->ficheinter->creer) { - $result=$object->swapContactStatus(GETPOST('ligne', 'int')); + $result = $object->swapContactStatus(GETPOST('ligne', 'int')); } // Deletes a contact @@ -108,15 +108,15 @@ elseif ($action == 'deletecontact' && $user->rights->ficheinter->creer) $form = new Form($db); $formcompany = new FormCompany($db); -$contactstatic=new Contact($db); -$userstatic=new User($db); -$formproject=new FormProjets($db); +$contactstatic = new Contact($db); +$userstatic = new User($db); +$formproject = new FormProjets($db); llxHeader('', $langs->trans("Intervention")); // Mode vue et edition -if ($id > 0 || ! empty($ref)) +if ($id > 0 || !empty($ref)) { $object->fetch_thirdparty(); @@ -176,14 +176,14 @@ if ($id > 0 || ! empty($ref)) print '
    '; - 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) + $dirtpls = array_merge($conf->modules_parts['tpl'], array('/core/tpl')); + foreach ($dirtpls as $reldir) { - $res=@include dol_buildpath($reldir.'/contacts.tpl.php'); + $res = @include dol_buildpath($reldir.'/contacts.tpl.php'); if ($res) break; } } diff --git a/htdocs/fichinter/document.php b/htdocs/fichinter/document.php index 3b6b2bd6299..08bd5930cb1 100644 --- a/htdocs/fichinter/document.php +++ b/htdocs/fichinter/document.php @@ -34,8 +34,8 @@ 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/fichinter.lib.php'; require_once DOL_DOCUMENT_ROOT.'/core/class/html.formfile.class.php'; -if (! empty($conf->projet->enabled)) { - require_once DOL_DOCUMENT_ROOT . '/projet/class/project.class.php'; +if (!empty($conf->projet->enabled)) { + require_once DOL_DOCUMENT_ROOT.'/projet/class/project.class.php'; } // Load translation files required by the page @@ -59,22 +59,22 @@ if (empty($page) || $page == -1) { $page = 0; } // If $page is not defined, $offset = $conf->liste_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); $object->fetch($id, $ref); $upload_dir = $conf->ficheinter->dir_output.'/'.dol_sanitizeFileName($object->ref); -$modulepart='fichinter'; +$modulepart = 'fichinter'; /* * Actions */ -include_once DOL_DOCUMENT_ROOT . '/core/actions_linkedfiles.inc.php'; +include_once DOL_DOCUMENT_ROOT.'/core/actions_linkedfiles.inc.php'; /* @@ -167,8 +167,8 @@ if ($object->id) $modulepart = 'ficheinter'; $permission = $user->rights->ficheinter->creer; $permtoedit = $user->rights->ficheinter->creer; - $param = '&id=' . $object->id; - include_once DOL_DOCUMENT_ROOT . '/core/tpl/document_actions_post_headers.tpl.php'; + $param = '&id='.$object->id; + include_once DOL_DOCUMENT_ROOT.'/core/tpl/document_actions_post_headers.tpl.php'; } else { diff --git a/htdocs/fichinter/index.php b/htdocs/fichinter/index.php index 147d3f13570..01eee972ffb 100644 --- a/htdocs/fichinter/index.php +++ b/htdocs/fichinter/index.php @@ -27,8 +27,8 @@ require '../main.inc.php'; 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'; +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(); @@ -41,7 +41,7 @@ $hookmanager->initHooks(array('interventionindex')); $langs->load("interventions"); // Security check -$socid=GETPOST('socid', 'int'); +$socid = GETPOST('socid', 'int'); if ($user->socid > 0) { $action = ''; @@ -54,10 +54,10 @@ if ($user->socid > 0) * View */ -$fichinterstatic=new Fichinter($db); +$fichinterstatic = new Fichinter($db); $form = new Form($db); $formfile = new FormFile($db); -$help_url="EN:ModuleFichinters|FR:Module_Fiche_Interventions|ES:Módulo_FichaInterventiones"; +$help_url = "EN:ModuleFichinters|FR:Module_Fiche_Interventions|ES:Módulo_FichaInterventiones"; llxHeader("", $langs->trans("Interventions"), $help_url); @@ -65,14 +65,14 @@ print load_fiche_titre($langs->trans("InterventionsArea")); 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 ficheinter - $var=false; + $var = false; print '
    '; print ''; print '
    '; - print ''; + print '
    '; print ''; print ''; @@ -85,25 +85,25 @@ if (! empty($conf->global->MAIN_SEARCH_FORM_ON_HOME_AREAS)) // This is usele */ $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"; -$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; -$sql.= " GROUP BY 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"; +$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; +$sql .= " GROUP BY f.fk_statut"; $resql = $db->query($sql); if ($resql) { $num = $db->num_rows($resql); $i = 0; - $total=0; - $totalinprocess=0; - $dataseries=array(); - $vals=array(); - $bool=false; + $total = 0; + $totalinprocess = 0; + $dataseries = array(); + $vals = array(); + $bool = false; // -1=Canceled, 0=Draft, 1=Validated, 2=Accepted/On process, 3=Closed (Sent/Received, billed or not) while ($i < $num) { @@ -112,26 +112,26 @@ if ($resql) { //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; - $vals[$row[1].$bool]+=$row[0]; - $totalinprocess+=$row[0]; + $bool = (!empty($row[2]) ?true:false); + if (!isset($vals[$row[1].$bool])) $vals[$row[1].$bool] = 0; + $vals[$row[1].$bool] += $row[0]; + $totalinprocess += $row[0]; } - $total+=$row[0]; + $total += $row[0]; } $i++; } $db->free($resql); print '
    '; - print '
    '.$langs->trans("Search").'
    '; print $langs->trans("Intervention").':
    '; + print '
    '; print ''."\n"; - $listofstatus=array(0,1,2); - $bool=false; + $listofstatus = array(0, 1, 2); + $bool = false; 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; + $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 ($conf->use_javascript_ajax) { @@ -145,25 +145,25 @@ if ($resql) $dolgraph->SetType(array('pie')); $dolgraph->setWidth('100%'); $dolgraph->draw('idgraphstatus'); - print $dolgraph->show($total?0:1); - $data=array('series'=>$dataseries); + print $dolgraph->show($total ? 0 : 1); + $data = array('series'=>$dataseries); print ''; } - $bool=false; + $bool = false; foreach ($listofstatus as $status) { - if (! $conf->use_javascript_ajax) + if (!$conf->use_javascript_ajax) { print ''; print ''; - print ''; print "\n"; - if ($status==3 && ! $bool) $bool=true; - else $bool=false; + if ($status == 3 && !$bool) $bool = true; + else $bool = false; } } //if ($totalinprocess != $total) @@ -180,23 +180,23 @@ else /* * 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"; - $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; + $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"; + $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; - $resql=$db->query($sql); + $resql = $db->query($sql); if ($resql) { print '
    '; - print '
    '.$langs->trans("Statistics").' - '.$langs->trans("Interventions").'
    '.$fichinterstatic->LibStatut($status, $bool, 0).''.(isset($vals[$status.$bool])?$vals[$status.$bool]:0).' '; + print ''.(isset($vals[$status.$bool]) ? $vals[$status.$bool] : 0).' '; print $fichinterstatic->LibStatut($status, $bool, 3); print ''; print '
    '; + print '
    '; print ''; print ''; $langs->load("fichinter"); @@ -222,30 +222,30 @@ if (! empty($conf->ficheinter->enabled)) print '
    '; -$max=5; +$max = 5; /* * Last modified interventions */ $sql = "SELECT f.rowid, f.ref, f.fk_statut, f.date_valid as datec, f.tms as datem,"; -$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"; -$sql.= " WHERE f.entity IN (".getEntity('intervention').")"; -$sql.= " AND f.fk_soc = s.rowid"; +$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"; +$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; -$sql.= " ORDER BY f.tms DESC"; -$sql.= $db->plimit($max, 0); +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); +$resql = $db->query($sql); if ($resql) { print '
    '; - print '
    '.$langs->trans("DraftFichinter").'
    '; + print '
    '; print ''; print ''; @@ -260,8 +260,8 @@ if ($resql) print ''; print '
    '.$langs->trans("LastModifiedInterventions", $max).'
    '; - $fichinterstatic->id=$obj->rowid; - $fichinterstatic->ref=$obj->ref; + $fichinterstatic->id = $obj->rowid; + $fichinterstatic->ref = $obj->ref; print ''; print ''; print '
    '; @@ -273,9 +273,9 @@ if ($resql) print ''; - $filename=dol_sanitizeFileName($obj->ref); - $filedir=$conf->commande->dir_output . '/' . dol_sanitizeFileName($obj->ref); - $urlsource=$_SERVER['PHP_SELF'].'?id='.$obj->rowid; + $filename = dol_sanitizeFileName($obj->ref); + $filedir = $conf->commande->dir_output.'/'.dol_sanitizeFileName($obj->ref); + $urlsource = $_SERVER['PHP_SELF'].'?id='.$obj->rowid; print $formfile->getDocumentsLink($fichinterstatic->element, $filename, $filedir); print '
    '; @@ -297,26 +297,26 @@ 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"; - $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; - $sql.= " ORDER BY f.rowid DESC"; + $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"; + $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; + $sql .= " ORDER BY f.rowid DESC"; - $resql=$db->query($sql); + $resql = $db->query($sql); if ($resql) { $num = $db->num_rows($resql); print '
    '; - print ''; + print '
    '; print ''; print ''; @@ -329,8 +329,8 @@ if (! empty($conf->ficheinter->enabled)) print ''; print ''; print '
    '.$langs->trans("FichinterToProcess").' '.$num.'
    '; - $fichinterstatic->id=$obj->rowid; - $fichinterstatic->ref=$obj->ref; + $fichinterstatic->id = $obj->rowid; + $fichinterstatic->ref = $obj->ref; print ''; print ''; print '
    '; @@ -342,9 +342,9 @@ if (! empty($conf->ficheinter->enabled)) print ''; - $filename=dol_sanitizeFileName($obj->ref); - $filedir=$conf->commande->dir_output . '/' . dol_sanitizeFileName($obj->ref); - $urlsource=$_SERVER['PHP_SELF'].'?id='.$obj->rowid; + $filename = dol_sanitizeFileName($obj->ref); + $filedir = $conf->commande->dir_output.'/'.dol_sanitizeFileName($obj->ref); + $urlsource = $_SERVER['PHP_SELF'].'?id='.$obj->rowid; print $formfile->getDocumentsLink($fichinterstatic->element, $filename, $filedir); print '
    '; diff --git a/htdocs/fichinter/info.php b/htdocs/fichinter/info.php index 3261ce84d89..993d675f15d 100644 --- a/htdocs/fichinter/info.php +++ b/htdocs/fichinter/info.php @@ -67,49 +67,49 @@ $head = fichinter_prepare_head($object); dol_fiche_head($head, 'info', $langs->trans('InterventionCard'), -1, 'intervention'); // Intervention card -$linkback = ''.$langs->trans("BackToList").''; +$linkback = ''.$langs->trans("BackToList").''; -$morehtmlref='
    '; +$morehtmlref = '
    '; // Ref customer //$morehtmlref.=$form->editfieldkey("RefCustomer", 'ref_client', $object->ref_client, $object, 0, 'string', '', 0, 1); //$morehtmlref.=$form->editfieldval("RefCustomer", 'ref_client', $object->ref_client, $object, 0, 'string', '', null, null, '', 1); // Thirdparty -$morehtmlref.=$langs->trans('ThirdParty') . ' : ' . $object->thirdparty->getNomUrl(1); +$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').' '; if ($user->rights->commande->creer) { if ($action != 'classify') //$morehtmlref.='' . img_edit($langs->transnoentitiesnoconv('SetProject')) . ' : '; - $morehtmlref.=' : '; + $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.=''; + $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); + $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)) { + if (!empty($object->fk_project)) { $proj = new Project($db); $proj->fetch($object->fk_project); - $morehtmlref.=''; - $morehtmlref.=$proj->ref; - $morehtmlref.=''; + $morehtmlref .= ''; + $morehtmlref .= $proj->ref; + $morehtmlref .= ''; } else { - $morehtmlref.=''; + $morehtmlref .= ''; } } } -$morehtmlref.='
    '; +$morehtmlref .= '
    '; dol_banner_tab($object, 'ref', $linkback, 1, 'ref', 'ref', $morehtmlref); diff --git a/htdocs/fichinter/list.php b/htdocs/fichinter/list.php index eeebd317977..9564481eab4 100644 --- a/htdocs/fichinter/list.php +++ b/htdocs/fichinter/list.php @@ -32,39 +32,39 @@ 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"); -$action=GETPOST('action', 'alpha'); -$massaction=GETPOST('massaction', 'alpha'); -$show_files=GETPOST('show_files', 'int'); -$confirm=GETPOST('confirm', 'alpha'); +$action = GETPOST('action', 'alpha'); +$massaction = GETPOST('massaction', 'alpha'); +$show_files = GETPOST('show_files', 'int'); +$confirm = GETPOST('confirm', 'alpha'); $toselect = GETPOST('toselect', 'array'); -$contextpage=GETPOST('contextpage', 'aZ')?GETPOST('contextpage', 'aZ'):'interventionlist'; +$contextpage = GETPOST('contextpage', 'aZ') ?GETPOST('contextpage', 'aZ') : 'interventionlist'; -$search_ref=GETPOST('search_ref')?GETPOST('search_ref', 'alpha'):GETPOST('search_inter', 'alpha'); -$search_company=GETPOST('search_company', 'alpha'); -$search_desc=GETPOST('search_desc', 'alpha'); -$search_projet_ref=GETPOST('search_projet_ref', 'alpha'); -$search_contrat_ref=GETPOST('search_contrat_ref', 'alpha'); -$search_status=GETPOST('search_status', 'alpha'); -$sall=trim((GETPOST('search_all', 'alphanohtml')!='')?GETPOST('search_all', 'alphanohtml'):GETPOST('sall', 'alphanohtml')); +$search_ref = GETPOST('search_ref') ?GETPOST('search_ref', 'alpha') : GETPOST('search_inter', 'alpha'); +$search_company = GETPOST('search_company', 'alpha'); +$search_desc = GETPOST('search_desc', 'alpha'); +$search_projet_ref = GETPOST('search_projet_ref', 'alpha'); +$search_contrat_ref = GETPOST('search_contrat_ref', 'alpha'); +$search_status = GETPOST('search_status', 'alpha'); +$sall = trim((GETPOST('search_all', 'alphanohtml') != '') ?GETPOST('search_all', 'alphanohtml') : GETPOST('sall', 'alphanohtml')); $optioncss = GETPOST('optioncss', 'alpha'); -$socid=GETPOST('socid', 'int'); +$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; +$diroutputmassaction = $conf->ficheinter->dir_output.'/temp/massgeneration/'.$user->id; -$limit = GETPOST('limit', 'int')?GETPOST('limit', 'int'):$conf->liste_limit; +$limit = GETPOST('limit', 'int') ?GETPOST('limit', 'int') : $conf->liste_limit; $sortfield = GETPOST('sortfield', 'alpha'); $sortorder = GETPOST('sortorder', 'alpha'); $page = GETPOST('page', 'int'); @@ -72,12 +72,12 @@ if (empty($page) || $page == -1) { $page = 0; } // If $page is not defined, $offset = $limit * $page; $pageprev = $page - 1; $pagenext = $page + 1; -if (! $sortorder) $sortorder="DESC"; -if (! $sortfield) +if (!$sortorder) $sortorder = "DESC"; +if (!$sortfield) { //if (empty($conf->global->FICHINTER_DISABLE_DETAILS)) $sortfield="fd.date"; //else - $sortfield="f.ref"; + $sortfield = "f.ref"; } // Initialize technical object to manage hooks of page. Note that conf->hooks_modules contains array of hook context @@ -89,7 +89,7 @@ $extrafields = new ExtraFields($db); // fetch optionals attributes and labels $extrafields->fetch_name_optionals_label('fichinter'); -$search_array_options=$extrafields->getOptionalsFromPost($object->table_element, '', 'search_'); +$search_array_options = $extrafields->getOptionalsFromPost($object->table_element, '', 'search_'); // List of fields to search into when doing a "search in all" $fieldstosearchall = array( @@ -98,30 +98,30 @@ $fieldstosearchall = array( 'f.description'=>'Description', 'f.note_public'=>'NotePublic', ); -if (empty($user->socid)) $fieldstosearchall["f.note_private"]="NotePrivate"; -if (! empty($conf->global->FICHINTER_DISABLE_DETAILS)) unset($fieldstosearchall['f.description']); +if (empty($user->socid)) $fieldstosearchall["f.note_private"] = "NotePrivate"; +if (!empty($conf->global->FICHINTER_DISABLE_DETAILS)) unset($fieldstosearchall['f.description']); // Definition of fields for list -$arrayfields=array( +$arrayfields = array( 'f.ref'=>array('label'=>'Ref', 'checked'=>1), 's.nom'=>array('label'=>'ThirdParty', 'checked'=>1), - 'pr.ref'=>array('label'=>'Project', 'checked'=>1, 'enabled'=>(empty($conf->projet->enabled)?0:1)), - 'c.ref'=>array('label'=>'Contract', 'checked'=>1, 'enabled'=>(empty($conf->contrat->enabled)?0:1)), + 'pr.ref'=>array('label'=>'Project', 'checked'=>1, 'enabled'=>(empty($conf->projet->enabled) ? 0 : 1)), + 'c.ref'=>array('label'=>'Contract', 'checked'=>1, 'enabled'=>(empty($conf->contrat->enabled) ? 0 : 1)), 'f.description'=>array('label'=>'Description', 'checked'=>1), 'f.datec'=>array('label'=>'DateCreation', 'checked'=>0, 'position'=>500), 'f.tms'=>array('label'=>'DateModificationShort', 'checked'=>0, 'position'=>500), 'f.fk_statut'=>array('label'=>'Status', 'checked'=>1, 'position'=>1000), - 'fd.description'=>array('label'=>"DescriptionOfLine", 'checked'=>1, 'enabled'=>empty($conf->global->FICHINTER_DISABLE_DETAILS)?1:0), - 'fd.date'=>array('label'=>'DateOfLine', 'checked'=>1, 'enabled'=>empty($conf->global->FICHINTER_DISABLE_DETAILS)?1:0), - 'fd.duree'=>array('label'=>'DurationOfLine', 'checked'=>1, 'enabled'=>empty($conf->global->FICHINTER_DISABLE_DETAILS)?1:0), + 'fd.description'=>array('label'=>"DescriptionOfLine", 'checked'=>1, 'enabled'=>empty($conf->global->FICHINTER_DISABLE_DETAILS) ? 1 : 0), + 'fd.date'=>array('label'=>'DateOfLine', 'checked'=>1, 'enabled'=>empty($conf->global->FICHINTER_DISABLE_DETAILS) ? 1 : 0), + 'fd.duree'=>array('label'=>'DurationOfLine', 'checked'=>1, 'enabled'=>empty($conf->global->FICHINTER_DISABLE_DETAILS) ? 1 : 0), ); // 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) + 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], 'checked'=>(($extrafields->attributes[$object->table_element]['list'][$key]<0)?0:1), 'position'=>$extrafields->attributes[$object->table_element]['pos'][$key], 'enabled'=>(abs($extrafields->attributes[$object->table_element]['list'][$key])!=3 && $extrafields->attributes[$object->table_element]['perms'][$key])); + if (!empty($extrafields->attributes[$object->table_element]['list'][$key])) + $arrayfields["ef.".$key] = array('label'=>$extrafields->attributes[$object->table_element]['label'][$key], 'checked'=>(($extrafields->attributes[$object->table_element]['list'][$key] < 0) ? 0 : 1), 'position'=>$extrafields->attributes[$object->table_element]['pos'][$key], 'enabled'=>(abs($extrafields->attributes[$object->table_element]['list'][$key]) != 3 && $extrafields->attributes[$object->table_element]['perms'][$key])); } } $object->fields = dol_sort_array($object->fields, 'position'); @@ -132,11 +132,11 @@ $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 +$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)) @@ -147,19 +147,19 @@ if (empty($reshook)) // Purge search criteria if (GETPOST('button_removefilter_x', 'alpha') || GETPOST('button_removefilter.x', 'alpha') || GETPOST('button_removefilter', 'alpha')) // All tests are required to be compatible with all browsers { - $search_ref=""; - $search_company=""; - $search_projet_ref=""; - $search_contrat_ref=""; - $search_desc=""; - $search_status=""; - $toselect=''; - $search_array_options=array(); + $search_ref = ""; + $search_company = ""; + $search_projet_ref = ""; + $search_contrat_ref = ""; + $search_desc = ""; + $search_status = ""; + $toselect = ''; + $search_array_options = array(); } // Mass actions - $objectclass='Fichinter'; - $objectlabel='Interventions'; + $objectclass = 'Fichinter'; + $objectlabel = 'Interventions'; $permissiontoread = $user->rights->ficheinter->lire; $permissiontodelete = $user->rights->ficheinter->supprimer; $uploaddir = $conf->ficheinter->dir_output; @@ -172,29 +172,29 @@ if (empty($reshook)) * View */ -$now=dol_now(); +$now = dol_now(); $form = new Form($db); $formfile = new FormFile($db); -$objectstatic=new Fichinter($db); -$companystatic=new Societe($db); +$objectstatic = new Fichinter($db); +$companystatic = new Societe($db); if (!empty($conf->projet->enabled)) { - $projetstatic=new Project($db); + $projetstatic = new Project($db); } if (!empty($conf->contrat->enabled)) { - $contratstatic=new Contrat($db); + $contratstatic = new Contrat($db); } -$title=$langs->trans("ListOfInterventions"); +$title = $langs->trans("ListOfInterventions"); llxHeader('', $title); -$varpage=empty($contextpage)?$_SERVER["PHP_SELF"]:$contextpage; -$selectedfields=$form->multiSelectArrayWithCheckbox('selectedfields', $arrayfields, $varpage); // This also change content of $arrayfields +$varpage = empty($contextpage) ? $_SERVER["PHP_SELF"] : $contextpage; +$selectedfields = $form->multiSelectArrayWithCheckbox('selectedfields', $arrayfields, $varpage); // This also change content of $arrayfields -$atleastonefieldinlines=0; -foreach($arrayfields as $tmpkey => $tmpval) +$atleastonefieldinlines = 0; +foreach ($arrayfields as $tmpkey => $tmpval) { - if (preg_match('/^fd\./', $tmpkey) && ! empty($arrayfields[$tmpkey]['checked'])) + if (preg_match('/^fd\./', $tmpkey) && !empty($arrayfields[$tmpkey]['checked'])) { $atleastonefieldinlines++; break; @@ -202,9 +202,9 @@ foreach($arrayfields as $tmpkey => $tmpval) } $sql = "SELECT"; -$sql.= " f.ref, f.rowid, f.fk_statut, f.description, f.datec as date_creation, f.tms as date_update, 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,"; -$sql.= " s.nom as name, s.rowid as socid, s.client"; +$sql .= " f.ref, f.rowid, f.fk_statut, f.description, f.datec as date_creation, f.tms as date_update, 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,"; +$sql .= " s.nom as name, s.rowid as socid, s.client"; if (!empty($conf->projet->enabled)) { $sql .= ", pr.rowid as projet_id, pr.ref as projet_ref, pr.title as projet_title"; } @@ -212,26 +212,26 @@ if (!empty($conf->contrat->enabled)) { $sql .= ", c.rowid as contrat_id, c.ref as contrat_ref, c.ref_customer as contrat_ref_supplier, c.ref_supplier as contrat_ref_supplier"; } // 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 : ''); +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 : ''); } // 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."fichinter as f"; +$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."fichinter as f"; if (!empty($conf->projet->enabled)) { - $sql.= " LEFT JOIN ".MAIN_DB_PREFIX."projet as pr on f.fk_projet = pr.rowid"; + $sql .= " LEFT JOIN ".MAIN_DB_PREFIX."projet as pr on f.fk_projet = pr.rowid"; } 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"; -$sql.= ", ".MAIN_DB_PREFIX."societe as s"; -$sql.= " WHERE f.entity IN (".getEntity('intervention').")"; -$sql.= " AND f.fk_soc = s.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"; +$sql .= ", ".MAIN_DB_PREFIX."societe as s"; +$sql .= " WHERE f.entity IN (".getEntity('intervention').")"; +$sql .= " AND f.fk_soc = s.rowid"; if ($search_ref) { $sql .= natural_search('f.ref', $search_ref); } @@ -251,20 +251,20 @@ if ($search_desc) { if ($search_status != '' && $search_status >= 0) { $sql .= ' AND f.fk_statut = '.$search_status; } -if (! $user->rights->societe->client->voir && empty($socid)) - $sql .= " AND s.rowid = sc.fk_soc AND sc.fk_user = " .$user->id; +if (!$user->rights->societe->client->voir && empty($socid)) + $sql .= " AND s.rowid = sc.fk_soc AND sc.fk_user = ".$user->id; if ($socid) - $sql.= " AND s.rowid = " . $socid; + $sql .= " AND s.rowid = ".$socid; if ($sall) { $sql .= natural_search(array_keys($fieldstosearchall), $sall); } // Add where from extra fields include DOL_DOCUMENT_ROOT.'/core/tpl/extrafields_list_search_sql.tpl.php'; // Add where from hooks -$parameters=array(); -$reshook=$hookmanager->executeHooks('printFieldListWhere', $parameters); // Note that $action and $object may have been modified by hook -$sql.=$hookmanager->resPrint; -$sql.= $db->order($sortfield, $sortorder); +$parameters = array(); +$reshook = $hookmanager->executeHooks('printFieldListWhere', $parameters); // Note that $action and $object may have been modified by hook +$sql .= $hookmanager->resPrint; +$sql .= $db->order($sortfield, $sortorder); // Count total nb of records $nbtotalofrecords = ''; @@ -279,15 +279,15 @@ if (empty($conf->global->MAIN_DISABLE_FULL_SCANLIST)) } } -$sql.= $db->plimit($limit+1, $offset); +$sql .= $db->plimit($limit + 1, $offset); //print $sql; -$resql=$db->query($sql); +$resql = $db->query($sql); if ($resql) { $num = $db->num_rows($resql); - $arrayofselected=is_array($toselect)?$toselect:array(); + $arrayofselected = is_array($toselect) ? $toselect : array(); if ($socid > 0) { @@ -296,32 +296,32 @@ if ($resql) 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); + $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); // Add $param from extra fields include DOL_DOCUMENT_ROOT.'/core/tpl/extrafields_list_search_param.tpl.php'; // List of mass actions available - $arrayofmassactions = array( + $arrayofmassactions = array( 'generate_doc'=>$langs->trans("ReGeneratePDF"), 'builddoc'=>$langs->trans("PDFMerge"), //'presend'=>$langs->trans("SendByMail"), ); - if ($user->rights->ficheinter->supprimer) $arrayofmassactions['predelete']=''.$langs->trans("Delete"); - if (in_array($massaction, array('presend','predelete'))) $arrayofmassactions=array(); - $massactionbutton=$form->selectMassAction('', $arrayofmassactions); + if ($user->rights->ficheinter->supprimer) $arrayofmassactions['predelete'] = ''.$langs->trans("Delete"); + if (in_array($massaction, array('presend', 'predelete'))) $arrayofmassactions = array(); + $massactionbutton = $form->selectMassAction('', $arrayofmassactions); - $newcardbutton=''; - $morehtmlcenter.= dolGetButtonTitle($langs->trans('NewIntervention'), '', 'fa fa-plus-circle', DOL_URL_ROOT.'/fichinter/card.php?action=create', '', $user->rights->ficheinter->creer); + $newcardbutton = ''; + $morehtmlcenter .= dolGetButtonTitle($langs->trans('NewIntervention'), '', 'fa fa-plus-circle', DOL_URL_ROOT.'/fichinter/card.php?action=create', '', $user->rights->ficheinter->creer); // Lines of title fields print '
    '."\n"; @@ -336,63 +336,63 @@ if ($resql) print_barre_liste($title, $page, $_SERVER['PHP_SELF'], $param, $sortfield, $sortorder, $massactionbutton, $num, $nbtotalofrecords, 'commercial', 0, $newcardbutton, '', $limit); - $topicmail="Information"; - $modelmail="intervention"; - $objecttmp=new Fichinter($db); - $trackid='int'.$object->id; + $topicmail = "Information"; + $modelmail = "intervention"; + $objecttmp = new Fichinter($db); + $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); - print '
    '.$langs->trans("FilterOnInto", $sall) . join(', ', $fieldstosearchall).'
    '; + foreach ($fieldstosearchall as $key => $val) $fieldstosearchall[$key] = $langs->trans($val); + print '
    '.$langs->trans("FilterOnInto", $sall).join(', ', $fieldstosearchall).'
    '; } - $moreforfilter=''; + $moreforfilter = ''; - $parameters=array(); - $reshook=$hookmanager->executeHooks('printFieldPreListTitle', $parameters); // Note that $action and $object may have been modified by hook + $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($moreforfilter)) + if (!empty($moreforfilter)) { print '
    '; print $moreforfilter; print '
    '; } - if ($massactionbutton) $selectedfields.=$form->showCheckAddButtons('checkforselect', 1); + if ($massactionbutton) $selectedfields .= $form->showCheckAddButtons('checkforselect', 1); print '
    '; - print ''."\n"; + print '
    '."\n"; print ''; - if (! empty($arrayfields['f.ref']['checked'])) + if (!empty($arrayfields['f.ref']['checked'])) { print ''; } - if (! empty($arrayfields['s.nom']['checked'])) + if (!empty($arrayfields['s.nom']['checked'])) { print ''; } - if (! empty($arrayfields['pr.ref']['checked'])) + if (!empty($arrayfields['pr.ref']['checked'])) { print ''; } - if (! empty($arrayfields['c.ref']['checked'])) + if (!empty($arrayfields['c.ref']['checked'])) { print ''; } - if (! empty($arrayfields['f.description']['checked'])) + if (!empty($arrayfields['f.description']['checked'])) { print ''; } - if (! empty($arrayfields['f.tms']['checked'])) + if (!empty($arrayfields['f.tms']['checked'])) { // Date modification print ''; } // Status - if (! empty($arrayfields['f.fk_statut']['checked'])) + if (!empty($arrayfields['f.fk_statut']['checked'])) { print ''; } // Fields of detail line - if (! empty($arrayfields['fd.description']['checked'])) + if (!empty($arrayfields['fd.description']['checked'])) { print ''; } - if (! empty($arrayfields['fd.date']['checked'])) + if (!empty($arrayfields['fd.date']['checked'])) { print ''; } - if (! empty($arrayfields['fd.duree']['checked'])) + if (!empty($arrayfields['fd.duree']['checked'])) { print ''; } print ''; print "\n"; print ''; - 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 + $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"], "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.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 "\n"; $total = 0; $i = 0; - $totalarray=array(); + $totalarray = array(); while ($i < min($num, $limit)) { $obj = $db->fetch_object($resql); - $objectstatic->id=$obj->rowid; - $objectstatic->ref=$obj->ref; - $objectstatic->statut=$obj->fk_statut; + $objectstatic->id = $obj->rowid; + $objectstatic->ref = $obj->ref; + $objectstatic->statut = $obj->fk_statut; print ''; - if (! empty($arrayfields['f.ref']['checked'])) + if (!empty($arrayfields['f.ref']['checked'])) { print "'; // Warning - $warnornote=''; + $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.= ''; - $warnornote.= ''.img_picto($langs->trans("ViewPrivateNote"), 'object_generic').''; - $warnornote.= ''; + $warnornote .= ($warnornote ? ' ' : ''); + $warnornote .= ''; + $warnornote .= ''.img_picto($langs->trans("ViewPrivateNote"), 'object_generic').''; + $warnornote .= ''; } if ($warnornote) { @@ -627,8 +627,8 @@ if ($resql) $db->free($resql); - $parameters=array('arrayfields'=>$arrayfields, 'sql'=>$sql); - $reshook=$hookmanager->executeHooks('printFieldListFooter', $parameters); // Note that $action and $object may have been modified by hook + $parameters = array('arrayfields'=>$arrayfields, 'sql'=>$sql); + $reshook = $hookmanager->executeHooks('printFieldListFooter', $parameters); // Note that $action and $object may have been modified by hook print $hookmanager->resPrint; print '
    '; print ''; print ''; print ''; print ''; print ''; print ''; print ''; print ''; print ''; @@ -402,86 +402,86 @@ if ($resql) include DOL_DOCUMENT_ROOT.'/core/tpl/extrafields_list_search_input.tpl.php'; // Fields from hook - $parameters=array('arrayfields'=>$arrayfields); - $reshook=$hookmanager->executeHooks('printFieldListOption', $parameters); // Note that $action and $object may have been modified by hook + $parameters = array('arrayfields'=>$arrayfields); + $reshook = $hookmanager->executeHooks('printFieldListOption', $parameters); // Note that $action and $object may have been modified by hook print $hookmanager->resPrint; - if (! empty($arrayfields['f.datec']['checked'])) + if (!empty($arrayfields['f.datec']['checked'])) { // Date creation print ''; print ''; print ''; - $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 + $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 print $form->selectarray('search_status', $liststatus, $search_status, 1, 0, 0, '', 1); print '   '; - $searchpicto=$form->showFilterButtons(); + $searchpicto = $form->showFilterButtons(); print $searchpicto; print '
    "; @@ -491,14 +491,14 @@ if ($resql) print $objectstatic->getNomUrl(1); print '
    '."\n"; @@ -636,16 +636,16 @@ if ($resql) print "\n"; - $hidegeneratedfilelistifempty=1; - if ($massaction == 'builddoc' || $action == 'remove_file' || $show_files) $hidegeneratedfilelistifempty=0; + $hidegeneratedfilelistifempty = 1; + if ($massaction == 'builddoc' || $action == 'remove_file' || $show_files) $hidegeneratedfilelistifempty = 0; // Show list of available documents - $urlsource=$_SERVER['PHP_SELF'].'?sortfield='.$sortfield.'&sortorder='.$sortorder; - $urlsource.=str_replace('&', '&', $param); + $urlsource = $_SERVER['PHP_SELF'].'?sortfield='.$sortfield.'&sortorder='.$sortorder; + $urlsource .= str_replace('&', '&', $param); - $filedir=$diroutputmassaction; - $genallowed=$user->rights->ficheinter->lire; - $delallowed=$user->rights->ficheinter->creer; + $filedir = $diroutputmassaction; + $genallowed = $user->rights->ficheinter->lire; + $delallowed = $user->rights->ficheinter->creer; print $formfile->showdocuments('massfilesarea_interventions', '', $filedir, $urlsource, 0, $delallowed, '', 1, 1, 0, 48, 1, $param, $title, '', '', '', null, $hidegeneratedfilelistifempty); } diff --git a/htdocs/fichinter/note.php b/htdocs/fichinter/note.php index 2982a0ea8c8..b4dc53f9f8a 100644 --- a/htdocs/fichinter/note.php +++ b/htdocs/fichinter/note.php @@ -27,8 +27,8 @@ require '../main.inc.php'; require_once DOL_DOCUMENT_ROOT.'/fichinter/class/fichinter.class.php'; require_once DOL_DOCUMENT_ROOT.'/core/lib/fichinter.lib.php'; -if (! empty($conf->projet->enabled)) { - require_once DOL_DOCUMENT_ROOT . '/projet/class/project.class.php'; +if (!empty($conf->projet->enabled)) { + require_once DOL_DOCUMENT_ROOT.'/projet/class/project.class.php'; } // Load translation files required by the page @@ -62,7 +62,7 @@ llxHeader('', $langs->trans("Intervention")); $form = new Form($db); -if ($id > 0 || ! empty($ref)) +if ($id > 0 || !empty($ref)) { $object->fetch_thirdparty(); diff --git a/htdocs/fichinter/stats/index.php b/htdocs/fichinter/stats/index.php index 02bec47ed86..78f3289d638 100644 --- a/htdocs/fichinter/stats/index.php +++ b/htdocs/fichinter/stats/index.php @@ -226,7 +226,7 @@ print '
    '; // Show filter box print '
    '; print ''; - print ''; + print '
    '; print ''; // Company print ''; print ''; print ''; - if (! empty($conf->fournisseur->enabled) && ! empty($conf->global->ORDER_MANAGE_MIN_AMOUNT)) + if (!empty($conf->fournisseur->enabled) && !empty($conf->global->ORDER_MANAGE_MIN_AMOUNT)) { print ''; print ''; print ''; } // Categories - if (! empty($conf->categorie->enabled)) + if (!empty($conf->categorie->enabled)) { $langs->load("categories"); - print ''; + print ''; print '"; } // Other attributes - $parameters=array('socid'=>$object->id, 'colspan' => ' colspan="3"', 'colspanvalue' => '3'); - include DOL_DOCUMENT_ROOT . '/core/tpl/extrafields_view.tpl.php'; + $parameters = array('socid'=>$object->id, 'colspan' => ' colspan="3"', 'colspanvalue' => '3'); + 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 ''; print '
    '.$langs->trans("Filter").'
    '.$langs->trans("ThirdParty").''; @@ -257,7 +257,7 @@ print '
    '; //} print '
    '; -print ''; +print '
    '; print ''; print ''; print ''; @@ -310,7 +310,7 @@ print '
    '; // Show graphs -print '
    '.$langs->trans("Year").''.$langs->trans("NbOfinterventions").'
    '; + print ''; print ''; // Absolute discounts (Discounts-Drawbacks-Rebates) @@ -287,51 +287,51 @@ if ($object->id > 0) print '
    '; +print ''; - print ''; @@ -271,7 +271,7 @@ if ($object->id > 0) print ''.img_edit($langs->trans("Modify")).''; } print '
    '; if ($mesg) { print $mesg; } else { print $px1->show(); diff --git a/htdocs/fourn/card.php b/htdocs/fourn/card.php index 47f44aff059..2fabe28728d 100644 --- a/htdocs/fourn/card.php +++ b/htdocs/fourn/card.php @@ -35,7 +35,7 @@ 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->adherent->enabled)) require_once DOL_DOCUMENT_ROOT.'/adherents/class/adherent.class.php'; // Load translation files required by page $langs->loadLangs(array( @@ -62,15 +62,15 @@ $extrafields = new ExtraFields($db); $extrafields->fetch_name_optionals_label($object->table_element); // Initialize technical object to manage hooks of page. Note that conf->hooks_modules contains array of hook context -$hookmanager->initHooks(array('suppliercard','globalcard')); +$hookmanager->initHooks(array('suppliercard', 'globalcard')); /* * Action */ -$parameters=array('id'=>$id); -$reshook=$hookmanager->executeHooks('doActions', $parameters, $object, $action); // Note that $action and $object may have been modified by some hooks +$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 (empty($reshook)) @@ -106,8 +106,8 @@ if (empty($reshook)) 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); + $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'); } @@ -121,7 +121,7 @@ if (empty($reshook)) if ($ret < 0) $error++; - if (! $error) + if (!$error) { $result = $object->insertExtraFields('COMPANY_MODIFY'); if ($result < 0) $error++; @@ -142,15 +142,15 @@ $form = new Form($db); if ($id > 0 && empty($object->id)) { // Load data of third party - $res=$object->fetch($id); + $res = $object->fetch($id); if ($object->id <= 0) dol_print_error($db, $object->error); } 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'); - $help_url=''; + $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'); + $help_url = ''; llxHeader('', $title, $help_url); /* @@ -177,7 +177,7 @@ if ($object->id > 0) if ($object->fournisseur) { print '
    '.$langs->trans("SupplierCode"). ''; + print ''.$langs->trans("SupplierCode").''; print $object->code_fournisseur; if ($object->check_codefournisseur() <> 0) print ' ('.$langs->trans("WrongSupplierCode").')'; print '
    '; - print '
    '.($object->remise_supplier_percent?''.$object->remise_supplier_percent.'%':'').''.($object->remise_supplier_percent ? ''.$object->remise_supplier_percent.'%' : '').'
    '; print '
    '; - $amount_discount=$object->getAvailableDiscounts('', '', 0, 1); + $amount_discount = $object->getAvailableDiscounts('', '', 0, 1); if ($amount_discount < 0) dol_print_error($db, $object->error); if ($amount_discount > 0) print ''.price($amount_discount, 1, $langs, 1, -1, -1, $conf->currency).''; //else print $langs->trans("DiscountNone"); print '
    '; print $form->editfieldkey("OrderMinAmount", 'supplier_order_min_amount', $object->supplier_order_min_amount, $object, $user->rights->societe->creer); print ''; - $limit_field_type = (! empty($conf->global->MAIN_USE_JQUERY_JEDITABLE)) ? 'numeric' : 'amount'; + $limit_field_type = (!empty($conf->global->MAIN_USE_JQUERY_JEDITABLE)) ? 'numeric' : 'amount'; print $form->editfieldval("OrderMinAmount", 'supplier_order_min_amount', $object->supplier_order_min_amount, $object, $user->rights->societe->creer, $limit_field_type, ($object->supplier_order_min_amount != '' ? price($object->supplier_order_min_amount) : '')); print '
    ' . $langs->trans("SuppliersCategoriesShort") . '
    '.$langs->trans("SuppliersCategoriesShort").''; print $form->showCategories($object->id, 'supplier', 1); print "
    '.$langs->trans("LinkedToDolibarrMember").''; - $adh=new Adherent($db); - $result=$adh->fetch('', '', $object->id); + $adh = new Adherent($db); + $result = $adh->fetch('', '', $object->id); if ($result > 0) { - $adh->ref=$adh->getFullName($langs); + $adh->ref = $adh->getFullName($langs); print $adh->getNomUrl(1); } else @@ -350,92 +350,92 @@ if ($object->id > 0) $boxstat = ''; // Nbre max d'elements des petites listes - $MAXLIST=$conf->global->MAIN_SIZE_SHORTLIST_LIMIT; + $MAXLIST = $conf->global->MAIN_SIZE_SHORTLIST_LIMIT; print '
    '; // Lien recap - $boxstat.='
    '; - $boxstat.=''; - $boxstat.=''; + $boxstat .= '
    '; + $boxstat .= '
    '; + $boxstat .= ''; + $boxstat .= ''; - $boxstat.='
    '; if ($conf->supplier_proposal->enabled) { // Box proposals $tmp = $object->getOutstandingProposals('supplier'); - $outstandingOpened=$tmp['opened']; - $outstandingTotal=$tmp['total_ht']; - $outstandingTotalIncTax=$tmp['total_ttc']; - $text=$langs->trans("OverAllSupplierProposals"); - $link=DOL_URL_ROOT.'/supplier_proposal/list.php?socid='.$object->id; - $icon='bill'; - if ($link) $boxstat.=''; - $boxstat.='
    '; - $boxstat.=''.img_object("", $icon).' '.$text.'
    '; - $boxstat.=''.price($outstandingTotal, 1, $langs, 1, -1, -1, $conf->currency).''; - $boxstat.='
    '; - if ($link) $boxstat.='
    '; + $outstandingOpened = $tmp['opened']; + $outstandingTotal = $tmp['total_ht']; + $outstandingTotalIncTax = $tmp['total_ttc']; + $text = $langs->trans("OverAllSupplierProposals"); + $link = DOL_URL_ROOT.'/supplier_proposal/list.php?socid='.$object->id; + $icon = 'bill'; + if ($link) $boxstat .= ''; + $boxstat .= '
    '; + $boxstat .= ''.img_object("", $icon).' '.$text.'
    '; + $boxstat .= ''.price($outstandingTotal, 1, $langs, 1, -1, -1, $conf->currency).''; + $boxstat .= '
    '; + if ($link) $boxstat .= '
    '; } if ($conf->fournisseur->enabled) { // Box proposals $tmp = $object->getOutstandingOrders('supplier'); - $outstandingOpened=$tmp['opened']; - $outstandingTotal=$tmp['total_ht']; - $outstandingTotalIncTax=$tmp['total_ttc']; - $text=$langs->trans("OverAllOrders"); - $link=DOL_URL_ROOT.'/fourn/commande/list.php?socid='.$object->id; - $icon='bill'; - if ($link) $boxstat.=''; - $boxstat.='
    '; - $boxstat.=''.img_object("", $icon).' '.$text.'
    '; - $boxstat.=''.price($outstandingTotal, 1, $langs, 1, -1, -1, $conf->currency).''; - $boxstat.='
    '; - if ($link) $boxstat.='
    '; + $outstandingOpened = $tmp['opened']; + $outstandingTotal = $tmp['total_ht']; + $outstandingTotalIncTax = $tmp['total_ttc']; + $text = $langs->trans("OverAllOrders"); + $link = DOL_URL_ROOT.'/fourn/commande/list.php?socid='.$object->id; + $icon = 'bill'; + if ($link) $boxstat .= ''; + $boxstat .= '
    '; + $boxstat .= ''.img_object("", $icon).' '.$text.'
    '; + $boxstat .= ''.price($outstandingTotal, 1, $langs, 1, -1, -1, $conf->currency).''; + $boxstat .= '
    '; + if ($link) $boxstat .= '
    '; } if ($conf->fournisseur->enabled) { $tmp = $object->getOutstandingBills('supplier'); - $outstandingOpened=$tmp['opened']; - $outstandingTotal=$tmp['total_ht']; - $outstandingTotalIncTax=$tmp['total_ttc']; + $outstandingOpened = $tmp['opened']; + $outstandingTotal = $tmp['total_ht']; + $outstandingTotalIncTax = $tmp['total_ttc']; - $text=$langs->trans("OverAllInvoices"); - $link=DOL_URL_ROOT.'/fourn/facture/list.php?socid='.$object->id; - $icon='bill'; - if ($link) $boxstat.=''; - $boxstat.='
    '; - $boxstat.=''.img_object("", $icon).' '.$text.'
    '; - $boxstat.=''.price($outstandingTotal, 1, $langs, 1, -1, -1, $conf->currency).''; - $boxstat.='
    '; - if ($link) $boxstat.='
    '; + $text = $langs->trans("OverAllInvoices"); + $link = DOL_URL_ROOT.'/fourn/facture/list.php?socid='.$object->id; + $icon = 'bill'; + if ($link) $boxstat .= ''; + $boxstat .= '
    '; + $boxstat .= ''.img_object("", $icon).' '.$text.'
    '; + $boxstat .= ''.price($outstandingTotal, 1, $langs, 1, -1, -1, $conf->currency).''; + $boxstat .= '
    '; + if ($link) $boxstat .= '
    '; // Box outstanding bill - $text=$langs->trans("CurrentOutstandingBill"); - $link=DOL_URL_ROOT.'/fourn/recap-fourn.php?socid='.$object->id; - $icon='bill'; - if ($link) $boxstat.=''; - $boxstat.='
    '; - $boxstat.=''.img_object("", $icon).' '.$text.'
    '; - $boxstat.=''.price($outstandingOpened, 1, $langs, 1, -1, -1, $conf->currency).$warn.''; - $boxstat.='
    '; - if ($link) $boxstat.='
    '; + $text = $langs->trans("CurrentOutstandingBill"); + $link = DOL_URL_ROOT.'/fourn/recap-fourn.php?socid='.$object->id; + $icon = 'bill'; + if ($link) $boxstat .= ''; + $boxstat .= '
    '; + $boxstat .= ''.img_object("", $icon).' '.$text.'
    '; + $boxstat .= ''.price($outstandingOpened, 1, $langs, 1, -1, -1, $conf->currency).$warn.''; + $boxstat .= '
    '; + if ($link) $boxstat .= '
    '; } - $boxstat.='
    '; - $boxstat.='
    '; + $boxstat .= '
    '; + $boxstat .= '
    '; print $boxstat; - $MAXLIST=$conf->global->MAIN_SIZE_SHORTLIST_LIMIT; + $MAXLIST = $conf->global->MAIN_SIZE_SHORTLIST_LIMIT; // Lien recap /* - print ''; + print '
    '; print ''; print ''; @@ -447,26 +447,26 @@ if ($object->id > 0) /* * 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,'; - $sql.= ' pfp.tms, pfp.ref_fourn as supplier_ref, pfp.price, pfp.quantity, pfp.unitprice'; - $sql.= ' FROM '.MAIN_DB_PREFIX.'product_fournisseur_price as pfp'; - $sql.= " LEFT JOIN ".MAIN_DB_PREFIX."product as p ON p.rowid = pfp.fk_product"; - $sql.= ' WHERE p.entity IN ('.getEntity('product').')'; - $sql.= ' AND pfp.fk_soc = '.$object->id; + $sql .= ' pfp.tms, pfp.ref_fourn as supplier_ref, pfp.price, pfp.quantity, pfp.unitprice'; + $sql .= ' FROM '.MAIN_DB_PREFIX.'product_fournisseur_price as pfp'; + $sql .= " LEFT JOIN ".MAIN_DB_PREFIX."product as p ON p.rowid = pfp.fk_product"; + $sql .= ' WHERE p.entity IN ('.getEntity('product').')'; + $sql .= ' AND pfp.fk_soc = '.$object->id; $sql .= $db->order('pfp.tms', 'desc'); - $sql.= $db->plimit($MAXLIST); + $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); print '
    '; print '
    '.$langs->trans("Summary").''.$langs->trans("ShowSupplierPreview").'
    '; - print ''; + print ''; print ''; @@ -522,17 +522,17 @@ if ($object->id > 0) if ($user->rights->supplier_proposal->lire) { - $sql = "SELECT p.rowid, p.ref, p.date_valid as dc, p.fk_statut, p.total_ht, p.tva as total_tva, p.total as total_ttc"; - $sql.= " FROM ".MAIN_DB_PREFIX."supplier_proposal as p "; - $sql.= " WHERE p.fk_soc =".$object->id; - $sql.= " AND p.entity IN (".getEntity('supplier_proposal').")"; - $sql.= " ORDER BY p.date_valid DESC"; - $sql.= " ".$db->plimit($MAXLIST); + $sql = "SELECT p.rowid, p.ref, p.date_valid as dc, p.fk_statut, p.total_ht, p.tva as total_tva, p.total as total_ttc"; + $sql .= " FROM ".MAIN_DB_PREFIX."supplier_proposal as p "; + $sql .= " WHERE p.fk_soc =".$object->id; + $sql .= " AND p.entity IN (".getEntity('supplier_proposal').")"; + $sql .= " ORDER BY p.date_valid DESC"; + $sql .= " ".$db->plimit($MAXLIST); - $resql=$db->query($sql); + $resql = $db->query($sql); if ($resql) { - $i = 0 ; + $i = 0; $num = $db->num_rows($resql); if ($num > 0) @@ -541,7 +541,7 @@ if ($object->id > 0) print ''; print '
    '.$langs->trans("ProductsAndServices").''; print ''.$langs->trans("AllProductReferencesOfSupplier").' '.$object->nbOfProductRefs().''; print '
    '; - print ''; + print '
    '.$langs->trans("LastSupplierProposals", ($num<$MAXLIST?"":$MAXLIST)).'
    '; print ''; print ''; print '
    '.$langs->trans("LastSupplierProposals", ($num < $MAXLIST ? "" : $MAXLIST)).''.$langs->trans("AllPriceRequests").' '.$num.''.img_picto($langs->trans("Statistics"), 'stats').'
    '; @@ -577,7 +577,7 @@ if ($object->id > 0) } $db->free($resql); - if ($num >0) print "
    "; + if ($num > 0) print "
    "; } else { @@ -595,27 +595,27 @@ if ($object->id > 0) // 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,'; - $sql2.= ' c.date_valid, c.date_commande, c.date_livraison, c.fk_statut'; - $sql2.= ' FROM '.MAIN_DB_PREFIX.'societe as s'; - $sql2.= ', '.MAIN_DB_PREFIX.'commande_fournisseur as c'; - $sql2.= ' WHERE c.fk_soc = s.rowid'; - $sql2.= " AND c.entity IN (".getEntity('commande_fournisseur').")"; - $sql2.= ' AND s.rowid = '.$object->id; + $sql2 .= ' c.date_valid, c.date_commande, c.date_livraison, c.fk_statut'; + $sql2 .= ' FROM '.MAIN_DB_PREFIX.'societe as s'; + $sql2 .= ', '.MAIN_DB_PREFIX.'commande_fournisseur as c'; + $sql2 .= ' WHERE c.fk_soc = s.rowid'; + $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)) { - $sql2.= " AND c.fk_statut IN (".CommandeFournisseur::STATUS_RECEIVED_COMPLETELY.")"; // Must match filter in htdocs/fourn/orderstoinvoice.php + $sql2 .= " AND c.fk_statut IN (".CommandeFournisseur::STATUS_RECEIVED_COMPLETELY.")"; // Must match filter in htdocs/fourn/orderstoinvoice.php } else { // CommandeFournisseur::STATUS_ORDERSENT.", ".CommandeFournisseur::STATUS_RECEIVED_PARTIALLY.", ".CommandeFournisseur::STATUS_RECEIVED_COMPLETELY - $sql2.= " AND c.fk_statut IN (".$db->escape($conf->global->SUPPLIER_ORDER_TO_INVOICE_STATUS).")"; + $sql2 .= " AND c.fk_statut IN (".$db->escape($conf->global->SUPPLIER_ORDER_TO_INVOICE_STATUS).")"; } - $sql2.= " AND c.billed = 0"; + $sql2 .= " AND c.billed = 0"; // Find order that are not already invoiced // just need to check received status because we have the billed status now //$sql2 .= " AND c.rowid NOT IN (SELECT fk_source FROM " . MAIN_DB_PREFIX . "element_element WHERE targettype='invoice_supplier')"; - $resql2=$db->query($sql2); + $resql2 = $db->query($sql2); if ($resql2) { $orders2invoice = $db->num_rows($resql2); $db->free($resql2); @@ -624,11 +624,11 @@ if ($object->id > 0) } // TODO move to DAO class - $sql = "SELECT count(p.rowid) as total"; - $sql.= " FROM ".MAIN_DB_PREFIX."commande_fournisseur as p"; - $sql.= " WHERE p.fk_soc =".$object->id; - $sql.= " AND p.entity IN (".getEntity('commande_fournisseur').")"; - $resql=$db->query($sql); + $sql = "SELECT count(p.rowid) as total"; + $sql .= " FROM ".MAIN_DB_PREFIX."commande_fournisseur as p"; + $sql .= " WHERE p.fk_soc =".$object->id; + $sql .= " AND p.entity IN (".getEntity('commande_fournisseur').")"; + $resql = $db->query($sql); if ($resql) { $object_count = $db->fetch_object($resql); @@ -636,15 +636,15 @@ if ($object->id > 0) } $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.= " FROM ".MAIN_DB_PREFIX."commande_fournisseur as p"; - $sql.= " WHERE p.fk_soc =".$object->id; - $sql.= " AND p.entity IN (".getEntity('commande_fournisseur').")"; - $sql.= " ORDER BY p.date_commande DESC"; - $sql.= " ".$db->plimit($MAXLIST); - $resql=$db->query($sql); + $sql .= " FROM ".MAIN_DB_PREFIX."commande_fournisseur as p"; + $sql .= " WHERE p.fk_soc =".$object->id; + $sql .= " AND p.entity IN (".getEntity('commande_fournisseur').")"; + $sql .= " ORDER BY p.date_commande DESC"; + $sql .= " ".$db->plimit($MAXLIST); + $resql = $db->query($sql); if ($resql) { - $i = 0 ; + $i = 0; if ($num > 0) { @@ -652,7 +652,7 @@ if ($object->id > 0) print '
    '; - print ''; + print '
    '.$langs->trans("LastSupplierOrders", ($num<$MAXLIST?"":$MAXLIST)).'
    '; print ''; print ''; print '
    '.$langs->trans("LastSupplierOrders", ($num < $MAXLIST ? "" : $MAXLIST)).''.$langs->trans("AllOrders").' '.$num.''.img_picto($langs->trans("Statistics"), 'stats').'
    '; @@ -688,7 +688,7 @@ if ($object->id > 0) } $db->free($resql); - if ($num >0) print "
    "; + if ($num > 0) print "
    "; } else { @@ -725,7 +725,7 @@ if ($object->id > 0) print '
    '; - print ''; + print '
    '.$langs->trans('LastSuppliersBills', ($num<=$MAXLIST?"":$MAXLIST)).''.$langs->trans('AllBills').' '.$num.'
    '; print ''; print '
    '.$langs->trans('LastSuppliersBills', ($num <= $MAXLIST ? "" : $MAXLIST)).''.$langs->trans('AllBills').' '.$num.''.img_picto($langs->trans("Statistics"), 'stats').'
    '; print '
    '; - $out .= ''; - $out .= ''; + $out .= ''; + $out .= ''; $out .= ''; $out .= ''; foreach ($productFournList as $productFourn) { - $out.= ''; - $out.= ''; - $out.= ''; - $out.= ''; + $out .= ''; + $out .= ''; + $out .= ''; + $out .= ''; } $out .= '
    '.($showunitprice?$langs->trans("Price").' '.$langs->trans("HT"):'').''.($showunitprice?$langs->trans("QtyMin"):'').'
    '.($showunitprice ? $langs->trans("Price").' '.$langs->trans("HT") : '').''.($showunitprice ? $langs->trans("QtyMin") : '').''.$langs->trans("Supplier").''.$langs->trans("SupplierRef").'
    '.($showunitprice?price($productFourn->fourn_unitprice * (1 -$productFourn->fourn_remise_percent/100) - $productFourn->fourn_remise):'').''.($showunitprice?$productFourn->fourn_qty:'').''.$productFourn->getSocNomUrl(1, 'supplier', $maxlen, $notooltip).''.$productFourn->fourn_ref.'
    '.($showunitprice ?price($productFourn->fourn_unitprice * (1 - $productFourn->fourn_remise_percent / 100) - $productFourn->fourn_remise) : '').''.($showunitprice ? $productFourn->fourn_qty : '').''.$productFourn->getSocNomUrl(1, 'supplier', $maxlen, $notooltip).''.$productFourn->fourn_ref.'
    '; } else { - $out=($showunitprice?price($this->fourn_unitprice * (1 - $this->fourn_remise_percent/100) + $this->fourn_remise).' '.$langs->trans("HT").'   (':'').($showsuptitle?$langs->trans("Supplier").': ':'').$this->getSocNomUrl(1, 'supplier', $maxlen, $notooltip).' / '.$langs->trans("SupplierRef").': '.$this->fourn_ref.($showunitprice?')':''); + $out = ($showunitprice ?price($this->fourn_unitprice * (1 - $this->fourn_remise_percent / 100) + $this->fourn_remise).' '.$langs->trans("HT").'   (' : '').($showsuptitle ? $langs->trans("Supplier").': ' : '').$this->getSocNomUrl(1, 'supplier', $maxlen, $notooltip).' / '.$langs->trans("SupplierRef").': '.$this->fourn_ref.($showunitprice ? ')' : ''); } return $out; } @@ -947,18 +947,18 @@ class ProductFournisseur extends Product global $conf; $sql = "SELECT"; - $sql.= " pfpl.rowid, pfp.ref_fourn as supplier_ref, pfpl.datec, u.lastname,"; - $sql.= " pfpl.price, pfpl.quantity"; - $sql.= " FROM ".MAIN_DB_PREFIX."product_fournisseur_price_log as pfpl"; - $sql.= ", ".MAIN_DB_PREFIX."product_fournisseur_price as pfp"; - $sql.= ", ".MAIN_DB_PREFIX."user as u"; - $sql.= " WHERE pfp.entity IN (".getEntity('productprice').")"; - $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); - $sql.=$this->db->plimit($limit, $offset); + $sql .= " pfpl.rowid, pfp.ref_fourn as supplier_ref, pfpl.datec, u.lastname,"; + $sql .= " pfpl.price, pfpl.quantity"; + $sql .= " FROM ".MAIN_DB_PREFIX."product_fournisseur_price_log as pfpl"; + $sql .= ", ".MAIN_DB_PREFIX."product_fournisseur_price as pfp"; + $sql .= ", ".MAIN_DB_PREFIX."user as u"; + $sql .= " WHERE pfp.entity IN (".getEntity('productprice').")"; + $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); + $sql .= $this->db->plimit($limit, $offset); dol_syslog(get_class($this)."::list_product_fournisseur_price_log", LOG_DEBUG); $resql = $this->db->query($sql); @@ -968,7 +968,7 @@ class ProductFournisseur extends Product while ($record = $this->db->fetch_array($resql)) { - $retarray[]=$record; + $retarray[] = $record; } $this->db->free($resql); @@ -976,7 +976,7 @@ class ProductFournisseur extends Product } else { - $this->error=$this->db->error(); + $this->error = $this->db->error(); return -1; } } @@ -1001,10 +1001,10 @@ class ProductFournisseur extends Product //$out .= '
    '.$langs->trans("QtyMin").''.$langs->trans("User").'
    '.dol_print_date($this->db->jdate($productFournLog['datec']), 'dayhour', 'tzuser').''.price($productFournLog['price']).'
    '.dol_print_date($this->db->jdate($productFournLog['datec']), 'dayhour', 'tzuser').''.price($productFournLog['price']).''.$productFournLog['quantity'].''.$productFournLog['lastname'].'
    '.$productFournLog['lastname'].'
    '; } @@ -1027,19 +1027,19 @@ class ProductFournisseur extends Product { global $db, $conf, $langs; - 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("SupplierRef") . ''; - $label.= '
    '; - $label.= '' . $langs->trans('Ref') . ': ' . $this->ref_supplier; + $label = ''.$langs->trans("SupplierRef").''; + $label .= '
    '; + $label .= ''.$langs->trans('Ref').': '.$this->ref_supplier; $logPrices = $this->listProductFournisseurPriceLog($this->product_fourn_price_id, 'pfpl.datec', 'DESC'); // set sort order here if (is_array($logPrices) && count($logPrices) > 0) { - $label.= '
    '; - $label.= '' . $langs->trans("History") . ''; - $label.= $this->displayPriceProductFournisseurLog($logPrices); + $label .= '
    '; + $label .= ''.$langs->trans("History").''; + $label .= $this->displayPriceProductFournisseurLog($logPrices); } $url = dol_buildpath('/product/fournisseurs.php', 1).'?id='.$this->id.'&action=add_price&socid='.$this->fourn_id.'&rowid='.$this->product_fourn_price_id; @@ -1047,31 +1047,31 @@ class ProductFournisseur extends Product 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'; + $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=''; + $linkclose = ''; if (empty($notooltip)) { - if (! empty($conf->global->MAIN_OPTIMIZEFORTEXTBROWSER)) + if (!empty($conf->global->MAIN_OPTIMIZEFORTEXTBROWSER)) { - $label=$langs->trans("SupplierRef"); - $linkclose.=' alt="'.dol_escape_htmltag($label, 1).'"'; + $label = $langs->trans("SupplierRef"); + $linkclose .= ' alt="'.dol_escape_htmltag($label, 1).'"'; } - $linkclose.=' title="'.dol_escape_htmltag($label, 1).'"'; - $linkclose.=' class="classfortooltip'.($morecss?' '.$morecss:'').'"'; + $linkclose .= ' title="'.dol_escape_htmltag($label, 1).'"'; + $linkclose .= ' class="classfortooltip'.($morecss ? ' '.$morecss : '').'"'; } - else $linkclose = ($morecss?' class="'.$morecss.'"':''); + else $linkclose = ($morecss ? ' class="'.$morecss.'"' : ''); $linkstart = ''; - $linkend=''; + $linkstart .= $linkclose.'>'; + $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->fourn_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->fourn_ref; $result .= $linkend; //if ($withpicto != 2) $result.=(($addlabel && $this->label) ? $sep . dol_trunc($this->label, ($addlabel > 1 ? $addlabel : 0)) : ''); @@ -1096,24 +1096,24 @@ class ProductFournisseur extends Product private function logPrice($user, $datec, $buyprice, $qty, $multicurrency_buyprice = null, $multicurrency_unitBuyPrice = null, $multicurrency_tx = null, $fk_multicurrency = null, $multicurrency_code = null) { // Add record into log table - $sql = "INSERT INTO " . MAIN_DB_PREFIX . "product_fournisseur_price_log("; - $sql.= " multicurrency_price, multicurrency_unitprice, multicurrency_tx, fk_multicurrency, multicurrency_code,"; + $sql = "INSERT INTO ".MAIN_DB_PREFIX."product_fournisseur_price_log("; + $sql .= " multicurrency_price, multicurrency_unitprice, multicurrency_tx, fk_multicurrency, multicurrency_code,"; $sql .= "datec, fk_product_fournisseur,fk_user,price,quantity)"; $sql .= "values("; - $sql.= (isset($multicurrency_buyprice)?"'".$this->db->escape(price2num($multicurrency_buyprice))."'":'null').","; - $sql.= (isset($multicurrency_unitBuyPrice)?"'".$this->db->escape(price2num($multicurrency_unitBuyPrice))."'":'null').","; - $sql.= (isset($multicurrency_tx)?"'".$this->db->escape($multicurrency_tx)."'":'1').","; - $sql.= (isset($fk_multicurrency)?"'".$this->db->escape($fk_multicurrency)."'":'null').","; - $sql.= (isset($multicurrency_code)?"'".$this->db->escape($multicurrency_code)."'":'null').","; - $sql .= "'" . $this->db->idate($datec) . "',"; - $sql .= " " . $this->product_fourn_price_id . ","; - $sql .= " " . $user->id . ","; - $sql .= " " . price2num($buyprice) . ","; - $sql .= " " . $qty; + $sql .= (isset($multicurrency_buyprice) ? "'".$this->db->escape(price2num($multicurrency_buyprice))."'" : 'null').","; + $sql .= (isset($multicurrency_unitBuyPrice) ? "'".$this->db->escape(price2num($multicurrency_unitBuyPrice))."'" : 'null').","; + $sql .= (isset($multicurrency_tx) ? "'".$this->db->escape($multicurrency_tx)."'" : '1').","; + $sql .= (isset($fk_multicurrency) ? "'".$this->db->escape($fk_multicurrency)."'" : 'null').","; + $sql .= (isset($multicurrency_code) ? "'".$this->db->escape($multicurrency_code)."'" : 'null').","; + $sql .= "'".$this->db->idate($datec)."',"; + $sql .= " ".$this->product_fourn_price_id.","; + $sql .= " ".$user->id.","; + $sql .= " ".price2num($buyprice).","; + $sql .= " ".$qty; $sql .= ")"; $resql = $this->db->query($sql); - if (! $resql) { + if (!$resql) { return -1; } else { return 1; diff --git a/htdocs/fourn/commande/card.php b/htdocs/fourn/commande/card.php index 4c6e98eda78..7e330635de8 100644 --- a/htdocs/fourn/commande/card.php +++ b/htdocs/fourn/commande/card.php @@ -41,30 +41,30 @@ 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)) - require_once DOL_DOCUMENT_ROOT . '/supplier_proposal/class/supplier_proposal.class.php'; +if (!empty($conf->supplier_proposal->enabled)) + require_once DOL_DOCUMENT_ROOT.'/supplier_proposal/class/supplier_proposal.class.php'; 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'; } -require_once NUSOAP_PATH.'/nusoap.php'; // Include SOAP +require_once NUSOAP_PATH.'/nusoap.php'; // Include SOAP if (!empty($conf->variants->enabled)) { require_once DOL_DOCUMENT_ROOT.'/variants/class/ProductCombination.class.php'; } -$langs->loadLangs(array('admin','orders','sendings','companies','bills','propal','supplier_proposal','deliveries','products','stocks','productbatch')); +$langs->loadLangs(array('admin', 'orders', 'sendings', 'companies', 'bills', 'propal', 'supplier_proposal', 'deliveries', 'products', 'stocks', 'productbatch')); if (!empty($conf->incoterm->enabled)) $langs->load('incoterm'); -$id = GETPOST('id', 'int'); -$ref = GETPOST('ref', 'alpha'); +$id = GETPOST('id', 'int'); +$ref = GETPOST('ref', 'alpha'); $action = GETPOST('action', 'alpha'); $confirm = GETPOST('confirm', 'alpha'); -$comclientid = GETPOST('comid', 'int'); -$socid = GETPOST('socid', 'int'); -$projectid = GETPOST('projectid', 'int'); +$comclientid = GETPOST('comid', 'int'); +$socid = GETPOST('socid', 'int'); +$projectid = GETPOST('projectid', 'int'); $cancel = GETPOST('cancel', 'alpha'); $lineid = GETPOST('lineid', 'int'); @@ -73,19 +73,19 @@ $origin = GETPOST('origin', 'alpha'); $originid = (GETPOST('originid', 'int') ? GETPOST('originid', 'int') : GETPOST('origin_id', 'int')); // For backward compatibility //PDF -$hidedetails = (GETPOST('hidedetails', 'int') ? GETPOST('hidedetails', 'int') : (! empty($conf->global->MAIN_GENERATE_DOCUMENTS_HIDE_DETAILS) ? 1 : 0)); -$hidedesc = (GETPOST('hidedesc', 'int') ? GETPOST('hidedesc', 'int') : (! empty($conf->global->MAIN_GENERATE_DOCUMENTS_HIDE_DESC) ? 1 : 0)); -$hideref = (GETPOST('hideref', 'int') ? GETPOST('hideref', 'int') : (! empty($conf->global->MAIN_GENERATE_DOCUMENTS_HIDE_REF) ? 1 : 0)); +$hidedetails = (GETPOST('hidedetails', 'int') ? GETPOST('hidedetails', 'int') : (!empty($conf->global->MAIN_GENERATE_DOCUMENTS_HIDE_DETAILS) ? 1 : 0)); +$hidedesc = (GETPOST('hidedesc', 'int') ? GETPOST('hidedesc', 'int') : (!empty($conf->global->MAIN_GENERATE_DOCUMENTS_HIDE_DESC) ? 1 : 0)); +$hideref = (GETPOST('hideref', 'int') ? GETPOST('hideref', 'int') : (!empty($conf->global->MAIN_GENERATE_DOCUMENTS_HIDE_REF) ? 1 : 0)); -$datelivraison=dol_mktime(GETPOST('liv_hour', 'int'), GETPOST('liv_min', 'int'), GETPOST('liv_sec', 'int'), GETPOST('liv_month', 'int'), GETPOST('liv_day', 'int'), GETPOST('liv_year', 'int')); +$datelivraison = dol_mktime(GETPOST('liv_hour', 'int'), GETPOST('liv_min', 'int'), GETPOST('liv_sec', 'int'), GETPOST('liv_month', 'int'), GETPOST('liv_day', 'int'), GETPOST('liv_year', '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 -$hookmanager->initHooks(array('ordersuppliercard','globalcard')); +$hookmanager->initHooks(array('ordersuppliercard', 'globalcard')); $object = new CommandeFournisseur($db); $extrafields = new ExtraFields($db); @@ -94,58 +94,58 @@ $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); $ret = $object->fetch_thirdparty(); if ($ret < 0) dol_print_error($db, $object->error); } -elseif (! empty($socid) && $socid > 0) +elseif (!empty($socid) && $socid > 0) { $fourn = new Fournisseur($db); - $ret=$fourn->fetch($socid); + $ret = $fourn->fetch($socid); 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); } -$permissionnote=$user->rights->fournisseur->commande->creer; // Used by the include of actions_setnotes.inc.php -$permissiondellink=$user->rights->fournisseur->commande->creer; // Used by the include of actions_dellink.inc.php -$permissiontoedit=$user->rights->fournisseur->commande->creer; // Used by the include of actions_lineupdown.inc.php -$permissiontoadd=$user->rights->fournisseur->commande->creer; // Used by the include of actions_addupdatedelete.inc.php +$permissionnote = $user->rights->fournisseur->commande->creer; // Used by the include of actions_setnotes.inc.php +$permissiondellink = $user->rights->fournisseur->commande->creer; // Used by the include of actions_dellink.inc.php +$permissiontoedit = $user->rights->fournisseur->commande->creer; // Used by the include of actions_lineupdown.inc.php +$permissiontoadd = $user->rights->fournisseur->commande->creer; // Used by the include of actions_addupdatedelete.inc.php /* * Actions */ -$parameters=array('socid'=>$socid); -$reshook=$hookmanager->executeHooks('doActions', $parameters, $object, $action); // Note that $action and $object may have been modified by some hooks +$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 ($cancel) { - if (! empty($backtopage)) + if (!empty($backtopage)) { header("Location: ".$backtopage); exit; } - $action=''; + $action = ''; } - include DOL_DOCUMENT_ROOT.'/core/actions_setnotes.inc.php'; // Must be include, not include_once + include DOL_DOCUMENT_ROOT.'/core/actions_setnotes.inc.php'; // Must be include, not include_once - include DOL_DOCUMENT_ROOT.'/core/actions_dellink.inc.php'; // Must be include, not include_once + include DOL_DOCUMENT_ROOT.'/core/actions_dellink.inc.php'; // Must be include, not include_once - include DOL_DOCUMENT_ROOT.'/core/actions_lineupdown.inc.php'; // Must be include, not include_once + include DOL_DOCUMENT_ROOT.'/core/actions_lineupdown.inc.php'; // Must be include, not include_once if ($action == 'setref_supplier' && $user->rights->fournisseur->commande->creer) { - $result=$object->setValueFrom('ref_supplier', GETPOST('ref_supplier', 'alpha'), '', null, 'text', '', $user, 'ORDER_SUPPLIER_MODIFY'); + $result = $object->setValueFrom('ref_supplier', GETPOST('ref_supplier', 'alpha'), '', null, 'text', '', $user, 'ORDER_SUPPLIER_MODIFY'); if ($result < 0) setEventMessages($object->error, $object->errors, 'errors'); } @@ -159,7 +159,7 @@ if (empty($reshook)) // payment conditions if ($action == 'setconditions' && $user->rights->fournisseur->commande->creer) { - $result=$object->setPaymentTerms(GETPOST('cond_reglement_id', 'int')); + $result = $object->setPaymentTerms(GETPOST('cond_reglement_id', 'int')); if ($result < 0) setEventMessages($object->error, $object->errors, 'errors'); } @@ -183,55 +183,55 @@ if (empty($reshook)) // bank account if ($action == 'setbankaccount' && $user->rights->fournisseur->commande->creer) { - $result=$object->setBankAccount(GETPOST('fk_account', 'int')); + $result = $object->setBankAccount(GETPOST('fk_account', 'int')); if ($result < 0) setEventMessages($object->error, $object->errors, 'errors'); } // date of delivery if ($action == 'setdate_livraison' && $user->rights->fournisseur->commande->creer) { - $result=$object->set_date_livraison($user, $datelivraison); + $result = $object->set_date_livraison($user, $datelivraison); if ($result < 0) setEventMessages($object->error, $object->errors, 'errors'); } // Set project - if ($action == 'classin' && $user->rights->fournisseur->commande->creer) + if ($action == 'classin' && $user->rights->fournisseur->commande->creer) { - $result=$object->setProject($projectid); + $result = $object->setProject($projectid); 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' && $user->rights->fournisseur->commande->creer && $object->statut == CommandeFournisseur::STATUS_DRAFT) + if (!empty($conf->global->MAIN_CAN_EDIT_SUPPLIER_ON_SUPPLIER_ORDER) && $action == 'set_thirdparty' && $user->rights->fournisseur->commande->creer && $object->statut == CommandeFournisseur::STATUS_DRAFT) { $new_socid = GETPOST('new_socid', 'int'); - if(! empty($new_socid) && $new_socid != $object->thirdparty->id) { + if (!empty($new_socid) && $new_socid != $object->thirdparty->id) { $db->begin(); // Update supplier $sql = 'UPDATE '.MAIN_DB_PREFIX.'commande_fournisseur'; $sql .= ' SET fk_soc='.$new_socid; - $sql.= ' WHERE fk_soc='.$object->thirdparty->id; - $sql.= ' AND rowid='.$object->id; + $sql .= ' WHERE fk_soc='.$object->thirdparty->id; + $sql .= ' AND rowid='.$object->id; $res = $db->query($sql); - if(! $res) $db->rollback(); + if (!$res) $db->rollback(); else { $db->commit(); // Replace prices for each lines by new supplier prices - foreach($object->lines as $l) { + foreach ($object->lines as $l) { $sql = 'SELECT price, unitprice, tva_tx, ref_fourn'; - $sql.= ' FROM '.MAIN_DB_PREFIX.'product_fournisseur_price'; - $sql.= ' WHERE fk_product='.$l->fk_product; - $sql.= ' AND fk_soc='.$new_socid; - $sql.= ' ORDER BY unitprice ASC'; + $sql .= ' FROM '.MAIN_DB_PREFIX.'product_fournisseur_price'; + $sql .= ' WHERE fk_product='.$l->fk_product; + $sql .= ' AND fk_soc='.$new_socid; + $sql .= ' ORDER BY unitprice ASC'; $resql = $db->query($sql); - if($resql) { + if ($resql) { $num_row = $db->num_rows($resql); - if(empty($num_row)) { + if (empty($num_row)) { // No product price for this supplier ! $l->subprice = 0; $l->total_ht = 0; @@ -246,7 +246,7 @@ if (empty($reshook)) $l->subprice = $obj->unitprice; $l->total_ht = $obj->price; $l->tva_tx = $obj->tva_tx; - $l->total_tva = $l->total_ht * ($obj->tva_tx/100); + $l->total_tva = $l->total_ht * ($obj->tva_tx / 100); $l->total_ttc = $l->total_ht + $l->total_tva; $l->ref_supplier = $obj->ref_fourn; $l->update(); @@ -274,21 +274,21 @@ if (empty($reshook)) { 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; + 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 + $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 + 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; @@ -299,18 +299,18 @@ if (empty($reshook)) { // 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'; - $sql.= ' WHERE rowid = '.$object->id; + $sql .= ' SET billed = 0'; + $sql .= ' WHERE rowid = '.$object->id; - $resql=$db->query($sql); + $resql = $db->query($sql); 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; + $sql .= ' SET fk_user_approve = null, fk_user_approve2 = null, date_approve = null, date_approve2 = null'; + $sql .= ' WHERE rowid = '.$object->id; - $resql=$db->query($sql); + $resql = $db->query($sql); } $db->commit(); @@ -332,7 +332,7 @@ if (empty($reshook)) */ if ($action == 'classifybilled' && $user->rights->fournisseur->commande->creer) { - $ret=$object->classifyBilled($user); + $ret = $object->classifyBilled($user); if ($ret < 0) { setEventMessages($object->error, $object->errors, 'errors'); } @@ -347,26 +347,26 @@ if (empty($reshook)) $error = 0; // Set if we used free entry or predefined product - $predef=''; - $product_desc=(GETPOST('dp_desc')?GETPOST('dp_desc'):''); - $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')); + $predef = ''; + $product_desc = (GETPOST('dp_desc') ?GETPOST('dp_desc') : ''); + $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') { - $idprod=0; + $idprod = 0; $price_ht = GETPOST('price_ht'); $tva_tx = (GETPOST('tva_tx') ? GETPOST('tva_tx') : 0); } else { - $idprod=GETPOST('idprod', 'int'); + $idprod = GETPOST('idprod', 'int'); $price_ht = ''; $tva_tx = ''; } $qty = GETPOST('qty'.$predef); - $remise_percent=GETPOST('remise_percent'.$predef); + $remise_percent = GETPOST('remise_percent'.$predef); $price_ht_devise = GETPOST('multicurrency_price_ht'); // Extrafields @@ -376,31 +376,31 @@ if (empty($reshook)) if (is_array($extralabelsline)) { // Get extra fields foreach ($extralabelsline as $key => $value) { - unset($_POST["options_" . $key]); + unset($_POST["options_".$key]); } } - 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++; @@ -415,7 +415,7 @@ if (empty($reshook)) $idprod = $res->fk_product_child; } else { setEventMessages($langs->trans('ErrorProductCombinationNotFound'), null, 'errors'); - $error ++; + $error++; } } } @@ -427,18 +427,18 @@ if (empty($reshook)) { $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, ...) + $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 (preg_match('/^idprod_([0-9]+)$/', GETPOST('idprodfournprice', 'alpha'), $reg)) { - $idprod=$reg[1]; - $res=$productsupplier->fetch($idprod); // Load product from its id + $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 + $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 { $productsupplier->ref_supplier = ''; @@ -447,15 +447,15 @@ if (empty($reshook)) 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 + $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) { - $qtytosearch=$qty; // Just to see if a price exists for the quantity. Not used to found vat. + $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); + $idprod = $productsupplier->get_buyprice(GETPOST('idprodfournprice', 'alpha'), $qtytosearch); + $res = $productsupplier->fetch($idprod); } if ($idprod > 0) @@ -463,27 +463,27 @@ if (empty($reshook)) $label = $productsupplier->label; // if we use supplier description of the products - if(!empty($productsupplier->desc_supplier) && !empty($conf->global->PRODUIT_FOURN_TEXTS)) { + if (!empty($productsupplier->desc_supplier) && !empty($conf->global->PRODUIT_FOURN_TEXTS)) { $desc = $productsupplier->desc_supplier; } else $desc = $productsupplier->description; if (trim($product_desc) != trim($desc)) $desc = dol_concatdesc($desc, $product_desc, '', !empty($conf->global->MAIN_CHANGE_ORDER_CONCAT_DESCRIPTION)); $type = $productsupplier->type; - $price_base_type = ($productsupplier->fourn_price_base_type?$productsupplier->fourn_price_base_type:'HT'); + $price_base_type = ($productsupplier->fourn_price_base_type ? $productsupplier->fourn_price_base_type : 'HT'); $ref_supplier = $productsupplier->ref_supplier; - $tva_tx = get_default_tva($object->thirdparty, $mysoc, $productsupplier->id, GETPOST('idprodfournprice', 'alpha')); + $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; - $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($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); $pu = $productsupplier->fourn_pu; - 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( + $result = $object->addline( $desc, $pu, $qty, @@ -491,7 +491,7 @@ if (empty($reshook)) $localtax1_tx, $localtax2_tx, $idprod, - 0, // We already have the $idprod always defined + 0, // We already have the $idprod always defined $ref_supplier, $remise_percent, $price_base_type, @@ -530,13 +530,13 @@ if (empty($reshook)) $type = GETPOST('type'); $ref_supplier = GETPOST('fourn_ref', 'alpha'); - $fk_unit= GETPOST('units', 'alpha'); + $fk_unit = GETPOST('units', 'alpha'); - $tva_tx = price2num($tva_tx); // When vat is text input field + $tva_tx = price2num($tva_tx); // When vat is text input field // Local Taxes - $localtax1_tx= get_localtax($tva_tx, 1, $mysoc, $object->thirdparty); - $localtax2_tx= get_localtax($tva_tx, 2, $mysoc, $object->thirdparty); + $localtax1_tx = get_localtax($tva_tx, 1, $mysoc, $object->thirdparty); + $localtax2_tx = get_localtax($tva_tx, 2, $mysoc, $object->thirdparty); if ($price_ht !== '') { @@ -554,11 +554,11 @@ 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 + $ret = $object->fetch($object->id); // Reload to get new records // Define output language if (empty($conf->global->MAIN_DISABLE_PDF_AUTOUPDATE)) @@ -567,14 +567,14 @@ if (empty($reshook)) $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 (!empty($newlang)) { $outputlangs = new Translate("", $conf); $outputlangs->setDefaultLang($newlang); } - $model=$object->modelpdf; + $model = $object->modelpdf; $ret = $object->fetch($id); // Reload to get new records - $result=$object->generateDocument($model, $outputlangs, $hidedetails, $hidedesc, $hideref); + $result = $object->generateDocument($model, $outputlangs, $hidedetails, $hidedesc, $hideref); if ($result < 0) dol_print_error($db, $result); } @@ -622,9 +622,9 @@ if (empty($reshook)) /* * Updating a line in the order */ - if ($action == 'updateline' && $user->rights->fournisseur->commande->creer && ! GETPOST('cancel', 'alpha')) + if ($action == 'updateline' && $user->rights->fournisseur->commande->creer && !GETPOST('cancel', 'alpha')) { - $vat_rate=(GETPOST('tva_tx')?GETPOST('tva_tx'):0); + $vat_rate = (GETPOST('tva_tx') ?GETPOST('tva_tx') : 0); if ($lineid) { @@ -634,16 +634,16 @@ if (empty($reshook)) } $productsupplier = new ProductFournisseur($db); - if (! empty($conf->global->SUPPLIER_ORDER_WITH_PREDEFINED_PRICES_ONLY)) + if (!empty($conf->global->SUPPLIER_ORDER_WITH_PREDEFINED_PRICES_ONLY)) { - if ($line->fk_product > 0 && $productsupplier->get_buyprice(0, price2num($_POST['qty']), $line->fk_product, 'none', GETPOST('socid', 'int')) < 0 ) + if ($line->fk_product > 0 && $productsupplier->get_buyprice(0, price2num($_POST['qty']), $line->fk_product, 'none', GETPOST('socid', 'int')) < 0) { setEventMessages($langs->trans("ErrorQtyTooLowForThisSupplier"), null, 'warnings'); } } - $date_start=dol_mktime(GETPOST('date_starthour'), GETPOST('date_startmin'), GETPOST('date_startsec'), GETPOST('date_startmonth'), GETPOST('date_startday'), GETPOST('date_startyear')); - $date_end=dol_mktime(GETPOST('date_endhour'), GETPOST('date_endmin'), GETPOST('date_endsec'), GETPOST('date_endmonth'), GETPOST('date_endday'), GETPOST('date_endyear')); + $date_start = dol_mktime(GETPOST('date_starthour'), GETPOST('date_startmin'), GETPOST('date_startsec'), GETPOST('date_startmonth'), GETPOST('date_startday'), GETPOST('date_startyear')); + $date_end = dol_mktime(GETPOST('date_endhour'), GETPOST('date_endmin'), GETPOST('date_endsec'), GETPOST('date_endmonth'), GETPOST('date_endday'), GETPOST('date_endyear')); // Define info_bits $info_bits = 0; @@ -683,11 +683,11 @@ if (empty($reshook)) // Unset extrafield POST Data if (is_array($extralabelsline)) { foreach ($extralabelsline as $key => $value) { - unset($_POST["options_" . $key]); + unset($_POST["options_".$key]); } } - $result = $object->updateline( + $result = $object->updateline( $lineid, $_POST['product_desc'], $ht, @@ -698,7 +698,7 @@ if (empty($reshook)) $localtax2_rate, $price_base_type, 0, - isset($_POST["type"])?$_POST["type"]:$line->product_type, + isset($_POST["type"]) ? $_POST["type"] : $line->product_type, false, $date_start, $date_end, @@ -735,7 +735,7 @@ 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)) @@ -744,14 +744,14 @@ if (empty($reshook)) $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 (!empty($newlang)) { $outputlangs = new Translate("", $conf); $outputlangs->setDefaultLang($newlang); } - $model=$object->modelpdf; + $model = $object->modelpdf; $ret = $object->fetch($id); // Reload to get new records - $result=$object->generateDocument($model, $outputlangs, $hidedetails, $hidedesc, $hideref); + $result = $object->generateDocument($model, $outputlangs, $hidedetails, $hidedesc, $hideref); if ($result < 0) dol_print_error($db, $result); } } @@ -775,7 +775,7 @@ if (empty($reshook)) $newlang = GETPOST('lang_id', 'aZ09'); 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); } @@ -791,19 +791,19 @@ if (empty($reshook)) { setEventMessages($object->error, $object->errors, 'errors'); /* Fix bug 1485 : Reset action to avoid asking again confirmation on failure */ - $action=''; + $action = ''; } } // Validate if ($action == 'confirm_valid' && $confirm == 'yes' && - ((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->commande->creer)) + || (!empty($conf->global->MAIN_USE_ADVANCED_PERMS) && !empty($user->rights->fournisseur->supplier_order_advance->validate))) ) { - $object->date_commande=dol_now(); + $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)) @@ -812,14 +812,14 @@ if (empty($reshook)) $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 (!empty($newlang)) { $outputlangs = new Translate("", $conf); $outputlangs->setDefaultLang($newlang); } - $model=$object->modelpdf; + $model = $object->modelpdf; $ret = $object->fetch($id); // Reload to get new records - $result=$object->generateDocument($model, $outputlangs, $hidedetails, $hidedesc, $hideref); + $result = $object->generateDocument($model, $outputlangs, $hidedetails, $hidedesc, $hideref); if ($result < 0) dol_print_error($db, $result); } } @@ -829,40 +829,40 @@ if (empty($reshook)) } // If we have permission, and if we don't need to provide the idwarehouse, we go directly on approved step - if (empty($conf->global->SUPPLIER_ORDER_NO_DIRECT_APPROVE) && $user->rights->fournisseur->commande->approuver && ! (! empty($conf->global->STOCK_CALCULATE_ON_SUPPLIER_VALIDATE_ORDER) && $object->hasProductsOrServices(1))) + if (empty($conf->global->SUPPLIER_ORDER_NO_DIRECT_APPROVE) && $user->rights->fournisseur->commande->approuver && !(!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 + $action = 'confirm_approve'; // can make standard or first level approval also if permission is set } } if (($action == 'confirm_approve' || $action == 'confirm_approve2') && $confirm == 'yes' && $user->rights->fournisseur->commande->approuver) { - $idwarehouse=GETPOST('idwarehouse', 'int'); + $idwarehouse = GETPOST('idwarehouse', 'int'); - $qualified_for_stock_change=0; + $qualified_for_stock_change = 0; if (empty($conf->global->STOCK_SUPPORTS_SERVICES)) { - $qualified_for_stock_change=$object->hasProductsOrServices(2); + $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 (!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 (!$idwarehouse || $idwarehouse == -1) { $error++; setEventMessages($langs->trans('ErrorFieldRequired', $langs->transnoentitiesnoconv("Warehouse")), null, 'errors'); - $action=''; + $action = ''; } } - if (! $error) + if (!$error) { - $result = $object->approve($user, $idwarehouse, ($action=='confirm_approve2'?1:0)); + $result = $object->approve($user, $idwarehouse, ($action == 'confirm_approve2' ? 1 : 0)); if ($result > 0) { if (empty($conf->global->MAIN_DISABLE_PDF_AUTOUPDATE)) { @@ -870,7 +870,7 @@ if (empty($reshook)) $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 (!empty($newlang)) { $outputlangs = new Translate("", $conf); $outputlangs->setDefaultLang($newlang); } @@ -886,7 +886,7 @@ if (empty($reshook)) } } - if ($action == 'confirm_refuse' && $confirm == 'yes' && $user->rights->fournisseur->commande->approuver) + if ($action == 'confirm_refuse' && $confirm == 'yes' && $user->rights->fournisseur->commande->approuver) { $result = $object->refuse($user); if ($result > 0) @@ -910,7 +910,7 @@ if (empty($reshook)) } } - if ($action == 'confirm_commande' && $confirm == 'yes' && $user->rights->fournisseur->commande->commander) + if ($action == 'confirm_commande' && $confirm == 'yes' && $user->rights->fournisseur->commande->commander) { $result = $object->commande($user, $_REQUEST["datecommande"], $_REQUEST["methode"], $_REQUEST['comment']); if ($result > 0) @@ -921,7 +921,7 @@ if (empty($reshook)) $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 (!empty($newlang)) { $outputlangs = new Translate("", $conf); $outputlangs->setDefaultLang($newlang); } @@ -940,7 +940,7 @@ if (empty($reshook)) if ($action == 'confirm_delete' && $confirm == 'yes' && $user->rights->fournisseur->commande->supprimer) { - $result=$object->delete($user); + $result = $object->delete($user); if ($result > 0) { header("Location: ".DOL_URL_ROOT.'/fourn/commande/list.php?restore_lastsearch_values=1'); @@ -955,7 +955,7 @@ if (empty($reshook)) // Action clone object if ($action == 'confirm_clone' && $confirm == 'yes' && $user->rights->fournisseur->commande->creer) { - if (1==0 && ! GETPOST('clone_content') && ! GETPOST('clone_receivers')) + if (1 == 0 && !GETPOST('clone_content') && !GETPOST('clone_receivers')) { setEventMessages($langs->trans("NoCloneOptionsSpecified"), null, 'errors'); } @@ -965,7 +965,7 @@ if (empty($reshook)) { $orig = clone $object; - $result=$object->createFromClone($user, $socid); + $result = $object->createFromClone($user, $socid); if ($result > 0) { header("Location: ".$_SERVER['PHP_SELF'].'?id='.$result); @@ -975,7 +975,7 @@ if (empty($reshook)) { setEventMessages($object->error, $object->errors, 'errors'); $object = $orig; - $action=''; + $action = ''; } } } @@ -988,14 +988,14 @@ if (empty($reshook)) { $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' + $result = $object->Livraison($user, $date_liv, GETPOST("type"), GETPOST("comment")); // GETPOST("type") is 'tot', 'par', 'nev', 'can' if ($result > 0) { $langs->load("deliveries"); setEventMessages($langs->trans("DeliveryStateSaved"), null); $action = ''; } - elseif($result == -3) + elseif ($result == -3) { setEventMessages($object->error, $object->errors, 'errors'); } @@ -1010,9 +1010,9 @@ if (empty($reshook)) } } - if ($action == 'confirm_cancel' && $confirm == 'yes' && $user->rights->fournisseur->commande->commander) + if ($action == 'confirm_cancel' && $confirm == 'yes' && $user->rights->fournisseur->commande->commander) { - $result = $object->cancel($user); + $result = $object->cancel($user); if ($result > 0) { header("Location: ".$_SERVER["PHP_SELF"]."?id=".$object->id); @@ -1028,9 +1028,9 @@ if (empty($reshook)) include DOL_DOCUMENT_ROOT.'/core/actions_printing.inc.php'; // Actions to send emails - $trigger_name='ORDER_SUPPLIER_SENTBYMAIL'; - $autocopy='MAIN_MAIL_AUTOCOPY_SUPPLIER_ORDER_TO'; - $trackid='sor'.$object->id; + $trigger_name = 'ORDER_SUPPLIER_SENTBYMAIL'; + $autocopy = 'MAIN_MAIL_AUTOCOPY_SUPPLIER_ORDER_TO'; + $trackid = 'sor'.$object->id; include DOL_DOCUMENT_ROOT.'/core/actions_sendmails.inc.php'; // Actions to build doc @@ -1047,12 +1047,12 @@ if (empty($reshook)) $ret = $extrafields->setOptionalsFromPost(null, $object, GETPOST('attribute', 'none')); if ($ret < 0) $error++; - if (! $error) + if (!$error) { // Actions on extra fields if (empty($conf->global->MAIN_EXTRAFIELDS_DISABLED)) // For avoid conflicts if trigger used { - $result=$object->insertExtraFields('ORDER_SUPPLIER_MODIFY'); + $result = $object->insertExtraFields('ORDER_SUPPLIER_MODIFY'); if ($result < 0) { $error++; @@ -1070,16 +1070,16 @@ if (empty($reshook)) */ if ($action == 'add' && $user->rights->fournisseur->commande->creer) { - $error=0; + $error = 0; - if ($socid <1) + if ($socid < 1) { setEventMessages($langs->trans('ErrorFieldRequired', $langs->transnoentities('Supplier')), null, 'errors'); - $action='create'; + $action = 'create'; $error++; } - if (! $error) + if (!$error) { $db->begin(); @@ -1099,16 +1099,16 @@ 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 (! $error) + if (!$error) { // If creation from another object of another module (Example: origin=propal, originid=1) - if (! empty($origin) && ! empty($originid)) + if (!empty($origin) && !empty($originid)) { if ($origin == 'propal' || $origin == 'proposal') { @@ -1133,18 +1133,18 @@ if (empty($reshook)) // Possibility to add external linked objects with hooks $object->linked_objects [$object->origin] = $object->origin_id; $other_linked_objects = GETPOST('other_linked_objects', 'array'); - if (! empty($other_linked_objects)) { + if (!empty($other_linked_objects)) { $object->linked_objects = array_merge($object->linked_objects, $other_linked_objects); } $id = $object->create($user); if ($id > 0) { - dol_include_once('/' . $element . '/class/' . $subelement . '.class.php'); + 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"); + 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) { @@ -1161,14 +1161,14 @@ if (empty($reshook)) $fk_parent_line = 0; $num = count($lines); - for($i = 0; $i < $num; $i ++) + for ($i = 0; $i < $num; $i++) { if (empty($lines[$i]->subprice) || $lines[$i]->qty <= 0) continue; - $label = (! empty($lines[$i]->label) ? $lines[$i]->label : ''); - $desc = (! empty($lines[$i]->desc) ? $lines[$i]->desc : $lines[$i]->product_desc); - $product_type = (! empty($lines[$i]->product_type) ? $lines[$i]->product_type : 0); + $label = (!empty($lines[$i]->label) ? $lines[$i]->label : ''); + $desc = (!empty($lines[$i]->desc) ? $lines[$i]->desc : $lines[$i]->product_desc); + $product_type = (!empty($lines[$i]->product_type) ? $lines[$i]->product_type : 0); // 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) { @@ -1202,11 +1202,11 @@ if (empty($reshook)) $tva_tx = $lines[$i]->tva_tx; - if ($origin=="commande") + if ($origin == "commande") { - $soc=new societe($db); + $soc = new societe($db); $soc->fetch($socid); - $tva_tx=get_default_tva($soc, $mysoc, $lines[$i]->fk_product, $product_fourn_price_id); + $tva_tx = get_default_tva($soc, $mysoc, $lines[$i]->fk_product, $product_fourn_price_id); } $result = $object->addline( @@ -1253,14 +1253,14 @@ if (empty($reshook)) $reshook = $hookmanager->executeHooks('createFrom', $parameters, $object, $action); // Note that $action and $object may have been if ($reshook < 0) - $error ++; + $error++; } else { setEventMessages($srcobject->error, $srcobject->errors, 'errors'); - $error ++; + $error++; } } else { setEventMessages($object->error, $object->errors, 'errors'); - $error ++; + $error++; } } else @@ -1278,8 +1278,8 @@ if (empty($reshook)) { $langs->load("errors"); $db->rollback(); - $action='create'; - $_GET['socid']=$_POST['socid']; + $action = 'create'; + $_GET['socid'] = $_POST['socid']; } else { @@ -1290,7 +1290,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; @@ -1300,8 +1300,8 @@ if (empty($reshook)) $ws_thirdparty = GETPOST('ws_thirdparty', 'int'); // NS and Authentication parameters - $ws_ns='http://www.dolibarr.org/ns/'; - $ws_authentication=array( + $ws_ns = 'http://www.dolibarr.org/ns/'; + $ws_authentication = array( 'dolibarrkey'=>$ws_key, 'sourceapplication'=>'DolibarrWebServiceClient', 'login'=>$ws_user, @@ -1319,12 +1319,12 @@ if (empty($reshook)) } else { //Create SOAP client and connect it to order $soapclient_order = new nusoap_client($ws_url."/webservices/server_order.php"); - $soapclient_order->soap_defencoding='UTF-8'; + $soapclient_order->soap_defencoding = 'UTF-8'; $soapclient_order->decodeUTF8(false); //Create SOAP client and connect it to product/service $soapclient_product = new nusoap_client($ws_url."/webservices/server_productorservice.php"); - $soapclient_product->soap_defencoding='UTF-8'; + $soapclient_product->soap_defencoding = 'UTF-8'; $soapclient_product->decodeUTF8(false); //Prepare the order lines from order @@ -1381,7 +1381,7 @@ if (empty($reshook)) } } - if (! empty($conf->global->MAIN_DISABLE_CONTACTS_TAB) && $user->rights->fournisseur->commande->creer) + if (!empty($conf->global->MAIN_DISABLE_CONTACTS_TAB) && $user->rights->fournisseur->commande->creer) { if ($action == 'addcontact') { @@ -1413,7 +1413,7 @@ if (empty($reshook)) // bascule du statut d'un contact elseif ($action == 'swapstatut' && $object->id > 0) { - $result=$object->swapContactStatus(GETPOST('ligne')); + $result = $object->swapContactStatus(GETPOST('ligne')); } // Efface un contact @@ -1438,18 +1438,18 @@ if (empty($reshook)) * View */ -$form = new Form($db); +$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'; +$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') +$now = dol_now(); +if ($action == 'create') { print load_fiche_titre($langs->trans('NewOrderSupplier')); @@ -1457,18 +1457,18 @@ if ($action=='create') $currency_code = $conf->currency; - $societe=''; - if ($socid>0) + $societe = ''; + if ($socid > 0) { - $societe=new Societe($db); + $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(); + $regs = array(); if (preg_match('/^([^_]+)_([^_]+)/i', $origin, $regs)) { $element = $regs[1]; $subelement = $regs[2]; @@ -1491,7 +1491,7 @@ if ($action=='create') $subelement = 'supplier_proposal'; } - dol_include_once('/' . $element . '/class/' . $subelement . '.class.php'); + dol_include_once('/'.$element.'/class/'.$subelement.'.class.php'); $objectsrc = new $classname($db); $objectsrc->fetch($originid); @@ -1503,21 +1503,21 @@ if ($action=='create') $objectsrc->fetch_optionals($originid); $object->array_options = $objectsrc->array_options; - $projectid = (! empty($objectsrc->fk_project) ? $objectsrc->fk_project : ''); - $ref_client = (! empty($objectsrc->ref_client) ? $objectsrc->ref_client : ''); + $projectid = (!empty($objectsrc->fk_project) ? $objectsrc->fk_project : ''); + $ref_client = (!empty($objectsrc->ref_client) ? $objectsrc->ref_client : ''); $soc = $objectsrc->client; - $cond_reglement_id = (!empty($objectsrc->cond_reglement_id)?$objectsrc->cond_reglement_id:(!empty($soc->cond_reglement_id)?$soc->cond_reglement_id:0)); - $mode_reglement_id = (!empty($objectsrc->mode_reglement_id)?$objectsrc->mode_reglement_id:(!empty($soc->mode_reglement_id)?$soc->mode_reglement_id:0)); - $fk_account = (! empty($objectsrc->fk_account)?$objectsrc->fk_account:(! empty($soc->fk_account)?$soc->fk_account:0)); - $availability_id = (!empty($objectsrc->availability_id)?$objectsrc->availability_id:(!empty($soc->availability_id)?$soc->availability_id:0)); - $shipping_method_id = (! empty($objectsrc->shipping_method_id)?$objectsrc->shipping_method_id:(! empty($soc->shipping_method_id)?$soc->shipping_method_id:0)); - $demand_reason_id = (!empty($objectsrc->demand_reason_id)?$objectsrc->demand_reason_id:(!empty($soc->demand_reason_id)?$soc->demand_reason_id:0)); - $remise_percent = (!empty($objectsrc->remise_percent)?$objectsrc->remise_percent:(!empty($soc->remise_supplier_percent)?$soc->remise_supplier_percent:0)); - $remise_absolue = (!empty($objectsrc->remise_absolue)?$objectsrc->remise_absolue:(!empty($soc->remise_absolue)?$soc->remise_absolue:0)); - $dateinvoice = empty($conf->global->MAIN_AUTOFILL_DATE)?-1:''; + $cond_reglement_id = (!empty($objectsrc->cond_reglement_id) ? $objectsrc->cond_reglement_id : (!empty($soc->cond_reglement_id) ? $soc->cond_reglement_id : 0)); + $mode_reglement_id = (!empty($objectsrc->mode_reglement_id) ? $objectsrc->mode_reglement_id : (!empty($soc->mode_reglement_id) ? $soc->mode_reglement_id : 0)); + $fk_account = (!empty($objectsrc->fk_account) ? $objectsrc->fk_account : (!empty($soc->fk_account) ? $soc->fk_account : 0)); + $availability_id = (!empty($objectsrc->availability_id) ? $objectsrc->availability_id : (!empty($soc->availability_id) ? $soc->availability_id : 0)); + $shipping_method_id = (!empty($objectsrc->shipping_method_id) ? $objectsrc->shipping_method_id : (!empty($soc->shipping_method_id) ? $soc->shipping_method_id : 0)); + $demand_reason_id = (!empty($objectsrc->demand_reason_id) ? $objectsrc->demand_reason_id : (!empty($soc->demand_reason_id) ? $soc->demand_reason_id : 0)); + $remise_percent = (!empty($objectsrc->remise_percent) ? $objectsrc->remise_percent : (!empty($soc->remise_supplier_percent) ? $soc->remise_supplier_percent : 0)); + $remise_absolue = (!empty($objectsrc->remise_absolue) ? $objectsrc->remise_absolue : (!empty($soc->remise_absolue) ? $soc->remise_absolue : 0)); + $dateinvoice = empty($conf->global->MAIN_AUTOFILL_DATE) ?-1 : ''; - $datedelivery = (! empty($objectsrc->date_livraison) ? $objectsrc->date_livraison : ''); + $datedelivery = (!empty($objectsrc->date_livraison) ? $objectsrc->date_livraison : ''); if (!empty($conf->multicurrency->enabled)) { @@ -1525,11 +1525,11 @@ if ($action=='create') 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)); - $note_public = $object->getDefaultCreateValueFor('note_public', (! empty($objectsrc->note_public) ? $objectsrc->note_public : null)); + $note_private = $object->getDefaultCreateValueFor('note_private', (!empty($objectsrc->note_private) ? $objectsrc->note_private : null)); + $note_public = $object->getDefaultCreateValueFor('note_public', (!empty($objectsrc->note_public) ? $objectsrc->note_public : null)); // Object source contacts list - $srccontactslist = $objectsrc->liste_contact(- 1, 'external', 1); + $srccontactslist = $objectsrc->liste_contact(-1, 'external', 1); } else { @@ -1543,17 +1543,17 @@ if ($action=='create') } // 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 ''; print ''; print ''; - print '' . "\n"; - print ''; - print ''; - print ''; - if (!empty($currency_tx)) print ''; + print ''."\n"; + print ''; + print ''; + print ''; + if (!empty($currency_tx)) print ''; dol_fiche_head(''); @@ -1573,7 +1573,7 @@ if ($action=='create') } else { - print $form->select_company((empty($socid)?'':$socid), 'socid', 's.fournisseur=1', 'SelectThirdParty', 0, 0, null, 0, 'minwidth300'); + print $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)) { @@ -1594,13 +1594,13 @@ if ($action=='create') if ($societe->id > 0) { // Discounts for third party - print '
    ' . $langs->trans('Discounts') . ''; + print '
    '.$langs->trans('Discounts').''; $absolute_discount = $societe->getAvailableDiscounts('', '', 0, 1); $thirdparty = $societe; $discount_type = 1; - $backtopage = urlencode($_SERVER["PHP_SELF"] . '?socid=' . $thirdparty->id . '&action=' . $action . '&origin=' . GETPOST('origin') . '&originid=' . GETPOST('originid')); + $backtopage = urlencode($_SERVER["PHP_SELF"].'?socid='.$thirdparty->id.'&action='.$action.'&origin='.GETPOST('origin').'&originid='.GETPOST('originid')); include DOL_DOCUMENT_ROOT.'/core/tpl/object_discounts.tpl.php'; print '
    '.$langs->trans('RefSupplier').'
    '.$langs->trans('PaymentConditionsShort').''; - $form->select_conditions_paiements(isset($_POST['cond_reglement_id'])?$_POST['cond_reglement_id']:$cond_reglement_id, 'cond_reglement_id'); + print '
    '.$langs->trans('PaymentConditionsShort').''; + $form->select_conditions_paiements(isset($_POST['cond_reglement_id']) ? $_POST['cond_reglement_id'] : $cond_reglement_id, 'cond_reglement_id'); print '
    '.$langs->trans('PaymentMode').''; - $form->select_types_paiements(isset($_POST['mode_reglement_id'])?$_POST['mode_reglement_id']:$mode_reglement_id, 'mode_reglement_id'); + print '
    '.$langs->trans('PaymentMode').''; + $form->select_types_paiements(isset($_POST['mode_reglement_id']) ? $_POST['mode_reglement_id'] : $mode_reglement_id, 'mode_reglement_id'); print '
    '; - $usehourmin=0; - if (! empty($conf->global->SUPPLIER_ORDER_USE_HOUR_FOR_DELIVERY_DATE)) $usehourmin=1; - print $form->selectDate($datelivraison?$datelivraison:-1, 'liv_', $usehourmin, $usehourmin, '', "set"); + $usehourmin = 0; + if (!empty($conf->global->SUPPLIER_ORDER_USE_HOUR_FOR_DELIVERY_DATE)) $usehourmin = 1; + print $form->selectDate($datelivraison ? $datelivraison : -1, 'liv_', $usehourmin, $usehourmin, '', "set"); print '
    ' . $langs->trans('BankAccount') . ''; + print '
    '.$langs->trans('BankAccount').''; $form->select_comptes($fk_account, 'fk_account', 0, '', 1); print '
    ' . $langs->trans('Project') . ''; - $formproject->select_projects((empty($conf->global->PROJECT_CAN_ALWAYS_LINK_TO_ALL_SUPPLIERS)?$societe->id:-1), $projectid, 'projectid', 0, 0, 1, 1); - print '   id).'">' . $langs->trans("AddProject") . ''; - + print '
    '.$langs->trans('Project').''; + $formproject->select_projects((empty($conf->global->PROJECT_CAN_ALWAYS_LINK_TO_ALL_SUPPLIERS) ? $societe->id : -1), $projectid, 'projectid', 0, 0, 1, 1); + print '   id).'">'.$langs->trans("AddProject").''; print '
    '; - print $form->select_incoterms((!empty($object->fk_incoterms) ? $object->fk_incoterms : ''), (!empty($object->location_incoterms)?$object->location_incoterms:'')); + print ''; + print $form->select_incoterms((!empty($object->fk_incoterms) ? $object->fk_incoterms : ''), (!empty($object->location_incoterms) ? $object->location_incoterms : '')); print '
    '.$form->editfieldkey('Currency', 'multicurrency_code', '', $object, 0).''; + print ''; print $form->selectMultiCurrency($currency_code, 'multicurrency_code'); print '
    ' . $langs->trans($newclassname) . '' . $objectsrc->getNomUrl(1) . '
    ' . $langs->trans('AmountHT') . '' . price($objectsrc->total_ht) . '
    ' . $langs->trans('AmountVAT') . '' . price($objectsrc->total_tva) . "
    '.$langs->trans($newclassname).''.$objectsrc->getNomUrl(1).'
    '.$langs->trans('AmountHT').''.price($objectsrc->total_ht).'
    '.$langs->trans('AmountVAT').''.price($objectsrc->total_tva)."
    ' . $langs->transcountry("AmountLT1", $mysoc->country_code) . '' . price($objectsrc->total_localtax1) . "
    '.$langs->transcountry("AmountLT1", $mysoc->country_code).''.price($objectsrc->total_localtax1)."
    ' . $langs->transcountry("AmountLT2", $mysoc->country_code) . '' . price($objectsrc->total_localtax2) . "
    '.$langs->transcountry("AmountLT2", $mysoc->country_code).''.price($objectsrc->total_localtax2)."
    ' . $langs->trans('AmountTTC') . '' . price($objectsrc->total_ttc) . "
    '.$langs->trans('AmountTTC').''.price($objectsrc->total_ttc)."
    ' . $langs->trans('MulticurrencyAmountHT') . '' . price($objectsrc->multicurrency_total_ht) . '
    ' . $langs->trans('MulticurrencyAmountVAT') . '' . price($objectsrc->multicurrency_total_tva) . '
    ' . $langs->trans('MulticurrencyAmountTTC') . '' . price($objectsrc->multicurrency_total_ttc) . '
    '.$langs->trans('MulticurrencyAmountHT').''.price($objectsrc->multicurrency_total_ht).'
    '.$langs->trans('MulticurrencyAmountVAT').''.price($objectsrc->multicurrency_total_tva).'
    '.$langs->trans('MulticurrencyAmountTTC').''.price($objectsrc->multicurrency_total_ttc).'
    '; } } -elseif (! empty($object->id)) +elseif (!empty($object->id)) { $result = $object->fetch($id, $ref); $societe = new Fournisseur($db); - $result=$societe->fetch($object->socid); + $result = $societe->fetch($object->socid); if ($result < 0) dol_print_error($db); - $author = new User($db); + $author = new User($db); $author->fetch($object->user_author_id); - $res=$object->fetch_optionals(); + $res = $object->fetch_optionals(); $head = ordersupplier_prepare_head($object); - $title=$langs->trans("SupplierOrder"); + $title = $langs->trans("SupplierOrder"); dol_fiche_head($head, 'card', $title, -1, 'order'); - $formconfirm=''; + $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); } @@ -1791,17 +1788,17 @@ elseif (! empty($object->id)) 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)')) + $formquestion = array( + array('type' => 'other', 'name' => 'socid', 'label' => $langs->trans("SelectThirdParty"), 'value' => $form->select_company(GETPOST('socid', 'int'), 'socid', '(s.fournisseur=1)')) ); // Paiement incomplet. On demande si motif = escompte ou autre $formconfirm = $form->formconfirm($_SERVER["PHP_SELF"].'?id='.$object->id, $langs->trans('ToClone'), $langs->trans('ConfirmCloneOrder', $object->ref), 'confirm_clone', $formquestion, 'yes', 1); } // Confirmation de la validation - if ($action == 'valid') + if ($action == 'valid') { - $object->date_commande=dol_now(); + $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 @@ -1813,17 +1810,17 @@ elseif (! empty($object->id)) if ($newref < 0) { setEventMessages($object->error, $object->errors, 'errors'); - $action=''; + $action = ''; } else { - $text=$langs->trans('ConfirmValidateOrder', $newref); - if (! empty($conf->notification->enabled)) + $text = $langs->trans('ConfirmValidateOrder', $newref); + if (!empty($conf->notification->enabled)) { - require_once DOL_DOCUMENT_ROOT .'/core/class/notify.class.php'; - $notify=new Notify($db); - $text.='
    '; - $text.=$notify->confirmMessage('ORDER_SUPPLIER_VALIDATE', $object->socid, $object); + require_once DOL_DOCUMENT_ROOT.'/core/class/notify.class.php'; + $notify = new Notify($db); + $text .= '
    '; + $text .= $notify->confirmMessage('ORDER_SUPPLIER_VALIDATE', $object->socid, $object); } $formconfirm = $form->formconfirm($_SERVER["PHP_SELF"].'?id='.$object->id, $langs->trans('ValidateOrder'), $text, 'confirm_valid', '', 0, 1); @@ -1831,59 +1828,59 @@ elseif (! empty($object->id)) } // Confirm approval - if ($action == 'approve' || $action == 'approve2') + if ($action == 'approve' || $action == 'approve2') { - $qualified_for_stock_change=0; + $qualified_for_stock_change = 0; if (empty($conf->global->STOCK_SUPPORTS_SERVICES)) { - $qualified_for_stock_change=$object->hasProductsOrServices(2); + $qualified_for_stock_change = $object->hasProductsOrServices(2); } else { - $qualified_for_stock_change=$object->hasProductsOrServices(1); + $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) + $formquestion = array(); + 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 - $formquestion=array( + $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 + $formquestion = array( //'text' => $langs->trans("ConfirmClone"), //array('type' => 'checkbox', 'name' => 'clone_content', 'label' => $langs->trans("CloneMainAttributes"), 'value' => 1), //array('type' => 'checkbox', 'name' => 'update_prices', 'label' => $langs->trans("PuttingPricesUpToDate"), 'value' => 1), - array('type' => 'other', 'name' => 'idwarehouse', 'label' => $langs->trans("SelectWarehouseForStockIncrease"), 'value' => $formproduct->selectWarehouses(GETPOST('idwarehouse', 'int'), 'idwarehouse', '', 1, 0, 0, '', 0, $forcecombo)) + array('type' => 'other', 'name' => 'idwarehouse', 'label' => $langs->trans("SelectWarehouseForStockIncrease"), 'value' => $formproduct->selectWarehouses(GETPOST('idwarehouse', 'int'), 'idwarehouse', '', 1, 0, 0, '', 0, $forcecombo)) ); } - $text=$langs->trans("ConfirmApproveThisOrder", $object->ref); - if (! empty($conf->notification->enabled)) + $text = $langs->trans("ConfirmApproveThisOrder", $object->ref); + if (!empty($conf->notification->enabled)) { - require_once DOL_DOCUMENT_ROOT .'/core/class/notify.class.php'; - $notify=new Notify($db); - $text.='
    '; - $text.=$notify->confirmMessage('ORDER_SUPPLIER_APPROVE', $object->socid, $object); + require_once DOL_DOCUMENT_ROOT.'/core/class/notify.class.php'; + $notify = new Notify($db); + $text .= '
    '; + $text .= $notify->confirmMessage('ORDER_SUPPLIER_APPROVE', $object->socid, $object); } $formconfirm = $form->formconfirm($_SERVER['PHP_SELF']."?id=".$object->id, $langs->trans("ApproveThisOrder"), $text, "confirm_".$action, $formquestion, 1, 1, 240); } // 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); @@ -1897,10 +1894,10 @@ elseif (! empty($object->id)) if (!$formconfirm) { - $parameters=array('lineid'=>$lineid); + $parameters = array('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 @@ -1909,56 +1906,56 @@ elseif (! empty($object->id)) // Supplier order card - $linkback = ''.$langs->trans("BackToList").''; + $linkback = ''.$langs->trans("BackToList").''; - $morehtmlref='
    '; + $morehtmlref = '
    '; // Ref supplier - $morehtmlref.=$form->editfieldkey("RefSupplier", 'ref_supplier', $object->ref_supplier, $object, $user->rights->fournisseur->commande->creer, 'string', '', 0, 1); - $morehtmlref.=$form->editfieldval("RefSupplier", 'ref_supplier', $object->ref_supplier, $object, $user->rights->fournisseur->commande->creer, 'string', '', null, null, '', 1); + $morehtmlref .= $form->editfieldkey("RefSupplier", 'ref_supplier', $object->ref_supplier, $object, $user->rights->fournisseur->commande->creer, 'string', '', 0, 1); + $morehtmlref .= $form->editfieldval("RefSupplier", 'ref_supplier', $object->ref_supplier, $object, $user->rights->fournisseur->commande->creer, 'string', '', null, null, '', 1); // Thirdparty - $morehtmlref.='
    '.$langs->trans('ThirdParty'); - if(! empty($conf->global->MAIN_CAN_EDIT_SUPPLIER_ON_SUPPLIER_ORDER) && ! empty($user->rights->fournisseur->commande->creer) && $action == 'edit_thirdparty') { + $morehtmlref .= '
    '.$langs->trans('ThirdParty'); + if (!empty($conf->global->MAIN_CAN_EDIT_SUPPLIER_ON_SUPPLIER_ORDER) && !empty($user->rights->fournisseur->commande->creer) && $action == 'edit_thirdparty') { $morehtmlref .= ' : '; - $morehtmlref .= '
    '; + $morehtmlref .= ''; $morehtmlref .= ''; - $morehtmlref .= ''; + $morehtmlref .= ''; $morehtmlref .= $form->select_company($object->thirdparty->id, 'new_socid', 's.fournisseur=1', '', 0, 0, array(), 0, 'minwidth300'); - $morehtmlref .= ''; + $morehtmlref .= ''; $morehtmlref .= '
    '; } - if(empty($conf->global->MAIN_CAN_EDIT_SUPPLIER_ON_SUPPLIER_ORDER) || $action != 'edit_thirdparty') { - if(! empty($conf->global->MAIN_CAN_EDIT_SUPPLIER_ON_SUPPLIER_ORDER) && $object->statut == CommandeFournisseur::STATUS_DRAFT) { - $morehtmlref .= '' . img_edit($langs->transnoentitiesnoconv('SetThirdParty')) . ''; + if (empty($conf->global->MAIN_CAN_EDIT_SUPPLIER_ON_SUPPLIER_ORDER) || $action != 'edit_thirdparty') { + if (!empty($conf->global->MAIN_CAN_EDIT_SUPPLIER_ON_SUPPLIER_ORDER) && $object->statut == CommandeFournisseur::STATUS_DRAFT) { + $morehtmlref .= ''.img_edit($langs->transnoentitiesnoconv('SetThirdParty')).''; } $morehtmlref .= ' : '.$object->thirdparty->getNomUrl(1); - if(empty($conf->global->MAIN_DISABLE_OTHER_LINK) && $object->thirdparty->id > 0) $morehtmlref .= ' (' . $langs->trans("OtherOrders") . ')'; + if (empty($conf->global->MAIN_DISABLE_OTHER_LINK) && $object->thirdparty->id > 0) $morehtmlref .= ' ('.$langs->trans("OtherOrders").')'; } // Project - if(!empty($conf->projet->enabled)) { + if (!empty($conf->projet->enabled)) { $langs->load("projects"); - $morehtmlref .= '
    ' . $langs->trans('Project') . ' '; - if($user->rights->fournisseur->commande->creer) { - if($action != 'classify') - $morehtmlref .= '' . img_edit($langs->transnoentitiesnoconv('SetProject')) . ' : '; - if($action == 'classify') { + $morehtmlref .= '
    '.$langs->trans('Project').' '; + if ($user->rights->fournisseur->commande->creer) { + if ($action != 'classify') + $morehtmlref .= ''.img_edit($langs->transnoentitiesnoconv('SetProject')).' : '; + if ($action == 'classify') { //$morehtmlref.=$form->form_project($_SERVER['PHP_SELF'] . '?id=' . $object->id, $object->socid, $object->fk_project, 'projectid', 0, 0, 1, 1); - $morehtmlref .= '
    '; + $morehtmlref .= ''; $morehtmlref .= ''; - $morehtmlref .= ''; + $morehtmlref .= ''; $morehtmlref .= $formproject->select_projects((empty($conf->global->PROJECT_CAN_ALWAYS_LINK_TO_ALL_SUPPLIERS) ? $object->socid : -1), $object->fk_project, 'projectid', $maxlength, 0, 1, 0, 1, 0, 0, '', 1); - $morehtmlref .= ''; + $morehtmlref .= ''; $morehtmlref .= '
    '; } else { - $morehtmlref .= $form->form_project($_SERVER['PHP_SELF'] . '?id=' . $object->id, $object->socid, $object->fk_project, 'none', 0, 0, 0, 1); + $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)) { + if (!empty($object->fk_project)) { $proj = new Project($db); $proj->fetch($object->fk_project); - $morehtmlref .= ''; + $morehtmlref .= ''; $morehtmlref .= $proj->ref; $morehtmlref .= ''; } @@ -1967,7 +1964,7 @@ elseif (! empty($object->id)) } } } - $morehtmlref.='
    '; + $morehtmlref .= '
    '; dol_banner_tab($object, 'ref', $linkback, 1, 'ref', 'ref', $morehtmlref); @@ -2001,7 +1998,7 @@ elseif (! empty($object->id)) print '
    ' . $langs->trans('Discounts') . ''; + print '
    '.$langs->trans('Discounts').''; $thirdparty = $societe; $discount_type = 1; - $backtopage = urlencode($_SERVER["PHP_SELF"] . '?id=' . $object->id); + $backtopage = urlencode($_SERVER["PHP_SELF"].'?id='.$object->id); include DOL_DOCUMENT_ROOT.'/core/tpl/object_discounts.tpl.php'; print '
    id . '">' . img_edit($langs->transnoentitiesnoconv('SetMultiCurrencyCode'), 1) . 'id.'">'.img_edit($langs->transnoentitiesnoconv('SetMultiCurrencyCode'), 1).'
    '; print '
    '; if ($action == 'editmulticurrencycode') { - $form->form_multicurrency_code($_SERVER['PHP_SELF'] . '?id=' . $object->id, $object->multicurrency_code, 'multicurrency_code'); + $form->form_multicurrency_code($_SERVER['PHP_SELF'].'?id='.$object->id, $object->multicurrency_code, 'multicurrency_code'); } else { - $form->form_multicurrency_code($_SERVER['PHP_SELF'] . '?id=' . $object->id, $object->multicurrency_code, 'none'); + $form->form_multicurrency_code($_SERVER['PHP_SELF'].'?id='.$object->id, $object->multicurrency_code, 'none'); } print '
    id . '">' . img_edit($langs->transnoentitiesnoconv('SetMultiCurrencyCode'), 1) . 'id.'">'.img_edit($langs->transnoentitiesnoconv('SetMultiCurrencyCode'), 1).'
    '; print '
    '; if ($action == 'editmulticurrencyrate' || $action == 'actualizemulticurrencyrate') { - if($action == 'actualizemulticurrencyrate') { + if ($action == 'actualizemulticurrencyrate') { list($object->fk_multicurrency, $object->multicurrency_tx) = MultiCurrency::getIdAndTxFromCode($object->db, $object->multicurrency_code); } - $form->form_multicurrency_rate($_SERVER['PHP_SELF'] . '?id=' . $object->id, $object->multicurrency_tx, 'multicurrency_tx', $object->multicurrency_code); + $form->form_multicurrency_rate($_SERVER['PHP_SELF'].'?id='.$object->id, $object->multicurrency_tx, 'multicurrency_tx', $object->multicurrency_code); } else { - $form->form_multicurrency_rate($_SERVER['PHP_SELF'] . '?id=' . $object->id, $object->multicurrency_tx, 'none', $object->multicurrency_code); + $form->form_multicurrency_rate($_SERVER['PHP_SELF'].'?id='.$object->id, $object->multicurrency_tx, 'none', $object->multicurrency_code); if ($object->statut == $object::STATUS_DRAFT && $object->multicurrency_code && $object->multicurrency_code != $conf->currency) { print '
            '; print ''.$langs->trans("ActualizeCurrency").''; @@ -2113,7 +2110,7 @@ elseif (! empty($object->id)) } // 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 '
    '; print ''; } // Other attributes - include DOL_DOCUMENT_ROOT . '/core/tpl/extrafields_view.tpl.php'; + include DOL_DOCUMENT_ROOT.'/core/tpl/extrafields_view.tpl.php'; print '
    '; @@ -2145,18 +2142,18 @@ elseif (! empty($object->id)) print '
    '; print ''; print ''; - $usehourmin=0; - if (! empty($conf->global->SUPPLIER_ORDER_USE_HOUR_FOR_DELIVERY_DATE)) $usehourmin=1; - print $form->selectDate($object->date_livraison?$object->date_livraison:-1, 'liv_', $usehourmin, $usehourmin, '', "setdate_livraison"); + $usehourmin = 0; + if (!empty($conf->global->SUPPLIER_ORDER_USE_HOUR_FOR_DELIVERY_DATE)) $usehourmin = 1; + print $form->selectDate($object->date_livraison ? $object->date_livraison : -1, 'liv_', $usehourmin, $usehourmin, '', "setdate_livraison"); print ''; print '
    '; } else { - $usehourmin='day'; - if (! empty($conf->global->SUPPLIER_ORDER_USE_HOUR_FOR_DELIVERY_DATE)) $usehourmin='dayhour'; + $usehourmin = 'day'; + if (!empty($conf->global->SUPPLIER_ORDER_USE_HOUR_FOR_DELIVERY_DATE)) $usehourmin = 'dayhour'; print $object->date_livraison ? dol_print_date($object->date_livraison, $usehourmin) : ' '; - if ($object->hasDelay() && ! empty($object->date_livraison)) { + if ($object->hasDelay() && !empty($object->date_livraison)) { print ' '.img_picto($langs->trans("Late").' : '.$object->showDelay(), "warning"); } } @@ -2186,13 +2183,13 @@ elseif (! empty($object->id)) } 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); + print $form->select_incoterms((!empty($object->fk_incoterms) ? $object->fk_incoterms : ''), (!empty($object->location_incoterms) ? $object->location_incoterms : ''), $_SERVER['PHP_SELF'].'?id='.$object->id); } print '
    '; @@ -2206,25 +2203,25 @@ elseif (! empty($object->id)) if (!empty($conf->multicurrency->enabled)) { // Multicurrency Amount HT - 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)) . '
    '.$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)).'
    ' . $form->editfieldkey('MulticurrencyAmountVAT', 'multicurrency_total_tva', '', $object, 0) . '' . price($object->multicurrency_total_tva, '', $langs, 0, - 1, - 1, (!empty($object->multicurrency_code) ? $object->multicurrency_code : $conf->currency)) . '
    '.$form->editfieldkey('MulticurrencyAmountVAT', 'multicurrency_total_tva', '', $object, 0).''.price($object->multicurrency_total_tva, '', $langs, 0, - 1, - 1, (!empty($object->multicurrency_code) ? $object->multicurrency_code : $conf->currency)).'
    ' . $form->editfieldkey('MulticurrencyAmountTTC', 'multicurrency_total_ttc', '', $object, 0) . '' . price($object->multicurrency_total_ttc, '', $langs, 0, - 1, - 1, (!empty($object->multicurrency_code) ? $object->multicurrency_code : $conf->currency)) . '
    '.$form->editfieldkey('MulticurrencyAmountTTC', 'multicurrency_total_ttc', '', $object, 0).''.price($object->multicurrency_total_ttc, '', $langs, 0, - 1, - 1, (!empty($object->multicurrency_code) ? $object->multicurrency_code : $conf->currency)).'
    '.$langs->trans("AmountHT").''.price($object->total_ht, '', $langs, 1, -1, -1, $conf->currency).$alert.'
    '.$langs->transcountry("AmountLT1", $mysoc->country_code).''.price($object->total_localtax1, '', $langs, 1, -1, -1, $conf->currency).'
    '.$langs->transcountry("AmountLT2", $mysoc->country_code).''.price($object->total_localtax2, '', $langs, 1, -1, -1, $conf->currency).'
    '.$langs->trans("ToOrder").'
    '.$langs->trans("OrderDate").''; $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 '
    ' . $langs->trans("Date") . ''; + print '
    '.$langs->trans("Date").''; if ($object->date_commande) { - print dol_print_date($object->date_commande, "dayhour") . "\n"; + print dol_print_date($object->date_commande, "dayhour")."\n"; } print "
    ' . $langs->trans("Method") . '' . $object->getInputMethod() . '
    '.$langs->trans("Method").''.$object->getInputMethod().'
    ' . $langs->trans("AuthorRequest") . '' . $author->getNomUrl(1, '', 0, 0, 0) . '
    '.$langs->trans("AuthorRequest").''.$author->getNomUrl(1, '', 0, 0, 0).'
    '; + print '
    '; // Set $products_dispatched with qty dispatched for each product id $products_dispatched = array(); $sql = "SELECT l.rowid, cfd.fk_product, sum(cfd.qty) as qty"; - $sql .= " FROM " . MAIN_DB_PREFIX . "commande_fournisseur_dispatch as cfd"; - $sql .= " LEFT JOIN " . MAIN_DB_PREFIX . "commande_fournisseurdet as l on l.rowid = cfd.fk_commandefourndet"; - $sql .= " WHERE cfd.fk_commande = " . $object->id; + $sql .= " FROM ".MAIN_DB_PREFIX."commande_fournisseur_dispatch as cfd"; + $sql .= " LEFT JOIN ".MAIN_DB_PREFIX."commande_fournisseurdet as l on l.rowid = cfd.fk_commandefourndet"; + $sql .= " WHERE cfd.fk_commande = ".$object->id; $sql .= " GROUP BY l.rowid, cfd.fk_product"; $resql = $db->query($sql); @@ -512,7 +512,7 @@ if ($id > 0 || ! empty($ref)) { $i = 0; if ($num) { - while ( $i < $num ) { + while ($i < $num) { $objd = $db->fetch_object($resql); $products_dispatched[$objd->rowid] = price2num($objd->qty, 5); $i++; @@ -535,9 +535,9 @@ if ($id > 0 || ! empty($ref)) { 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; + $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)) $sql .= " AND l.product_type = 0"; @@ -563,8 +563,8 @@ if ($id > 0 || ! empty($ref)) { if ($num) { print ''; - print ''; - if (! empty($conf->productbatch->enabled)) + print ''; + if (!empty($conf->productbatch->enabled)) { print ''; print ''; @@ -576,21 +576,21 @@ if ($id > 0 || ! empty($ref)) { print ''; print ''; } - print ''; - print ''; - print ''; - print ''; + print ''; + print ''; + print ''; + print ''; print ''; - if (! empty($conf->global->SUPPLIER_ORDER_CAN_UPDATE_BUYINGPRICE_DURING_RECEIPT)) { + if (!empty($conf->global->SUPPLIER_ORDER_CAN_UPDATE_BUYINGPRICE_DURING_RECEIPT)) { if (empty($conf->multicurrency->enabled) && empty($conf->dynamicprices->enabled)) { - print ''; - print ''; - print ''; + print ''; + print ''; + print ''; } } - print ''; + print ''; // Enable hooks to append additional columns $parameters = array(); @@ -606,18 +606,18 @@ if ($id > 0 || ! empty($ref)) { print "\n"; } - $nbfreeproduct = 0; // Nb of lins of free products/services - $nbproduct = 0; // Nb of predefined product lines to dispatch (already done or not) if SUPPLIER_ORDER_DISABLE_STOCK_DISPATCH_WHEN_TOTAL_REACHED is off (default) + $nbfreeproduct = 0; // Nb of lins of free products/services + $nbproduct = 0; // Nb of predefined product lines to dispatch (already done or not) if SUPPLIER_ORDER_DISABLE_STOCK_DISPATCH_WHEN_TOTAL_REACHED is off (default) // or nb of line that remain to dispatch if SUPPLIER_ORDER_DISABLE_STOCK_DISPATCH_WHEN_TOTAL_REACHED is on. - while ( $i < $num ) { + while ($i < $num) { $objp = $db->fetch_object($resql); // On n'affiche pas les produits libres - if (! $objp->fk_product > 0) { + if (!$objp->fk_product > 0) { $nbfreeproduct++; } else { - $remaintodispatch = price2num($objp->qty - (( float ) $products_dispatched[$objp->rowid]), 5); // Calculation of dispatched + $remaintodispatch = price2num($objp->qty - ((float) $products_dispatched[$objp->rowid]), 5); // Calculation of dispatched if ($remaintodispatch < 0) $remaintodispatch = 0; @@ -627,19 +627,19 @@ if ($id > 0 || ! empty($ref)) { // To show detail cref and description value, we must make calculation by cref // print ($objp->cref?' ('.$objp->cref.')':''); // if ($objp->description) print '
    '.nl2br($objp->description); - $suffix = '_0_' . $i; + $suffix = '_0_'.$i; print "\n"; - print '' . "\n"; + print ''."\n"; // hidden fields for js function - print ''; - print ''; + print ''; + print ''; print ''; - $linktoprod = '' . img_object($langs->trans("ShowProduct"), 'product') . ' ' . $objp->ref . ''; - $linktoprod .= ' - ' . $objp->label . "\n"; + $linktoprod = ''.img_object($langs->trans("ShowProduct"), 'product').' '.$objp->ref.''; + $linktoprod .= ' - '.$objp->label."\n"; - if (! empty($conf->productbatch->enabled)) { + if (!empty($conf->productbatch->enabled)) { if ($objp->tobatch) { print ''; // Qty ordered - print ''; + print ''; // Already dispatched - print ''; + print ''; - if (! empty($conf->productbatch->enabled) && $objp->tobatch == 1) { + if (!empty($conf->productbatch->enabled) && $objp->tobatch == 1) { $type = 'batch'; print ''; // Qty to dispatch + print ''; // Qty to dispatch print ''; // Dispatch column + print ''; // Dispatch column print ''; // Warehouse column // Enable hooks to append additional columns @@ -704,42 +704,42 @@ if ($id > 0 || ! empty($ref)) { print ''; - print ''; + print ''; print ''; print ''; print ''; print ''; print ''; // Supplier ref + Qty ordered + qty already dispatched } else { $type = 'dispatch'; print ''; // Qty to dispatch + print ''; // Qty to dispatch print ''; // Dispatch column + print ''; // Dispatch column print ''; // Warehouse column // Enable hooks to append additional columns @@ -760,19 +760,19 @@ if ($id > 0 || ! empty($ref)) { print ''; - print ''; + print ''; print ''; @@ -780,7 +780,7 @@ if ($id > 0 || ! empty($ref)) { // Qty to dispatch print ''; print '
    ' . $langs->trans("Description") . ''.$langs->trans("Description").''.$langs->trans("batch_number").''.$langs->trans("EatByDate").'' . $langs->trans("SupplierRef") . '' . $langs->trans("QtyOrdered") . '' . $langs->trans("QtyDispatchedShort") . '' . $langs->trans("QtyToDispatchShort") . ''.$langs->trans("SupplierRef").''.$langs->trans("QtyOrdered").''.$langs->trans("QtyDispatchedShort").''.$langs->trans("QtyToDispatchShort").'' . $langs->trans("Price") . '' . $langs->trans("ReductionShort") . ' (%)' . $langs->trans("UpdatePrice") . ''.$langs->trans("Price").''.$langs->trans("ReductionShort").' (%)'.$langs->trans("UpdatePrice").'' . $langs->trans("Warehouse") . ''.$langs->trans("Warehouse").'
    '; print $linktoprod; @@ -665,25 +665,25 @@ 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 ''.$objp->sref.'' . $objp->qty . ''.$objp->qty.'' . $products_dispatched[$objp->rowid] . ''.$products_dispatched[$objp->rowid].''; - print ''; //print img_picto($langs->trans('AddDispatchBatchLine'), 'split.png', 'onClick="addDispatchLine(' . $i . ',\'' . $type . '\')"'); - print '
    '; - print ''; - print ''; + print ''; + print ''; print ''; - 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").': '; + print $langs->trans("BuyingPrice").': '; } else { - print ''; + print ''; } print ''; - print ''; + print ''; print ''; - $dlcdatesuffix = dol_mktime(0, 0, 0, GETPOST('dlc' . $suffix . 'month'), GETPOST('dlc' . $suffix . 'day'), GETPOST('dlc' . $suffix . 'year')); - print $form->selectDate($dlcdatesuffix, 'dlc' . $suffix, '', '', 1, ''); + $dlcdatesuffix = dol_mktime(0, 0, 0, GETPOST('dlc'.$suffix.'month'), GETPOST('dlc'.$suffix.'day'), GETPOST('dlc'.$suffix.'year')); + print $form->selectDate($dlcdatesuffix, 'dlc'.$suffix, '', '', 1, ''); print ''; - $dluodatesuffix = dol_mktime(0, 0, 0, GETPOST('dluo' . $suffix . 'month'), GETPOST('dluo' . $suffix . 'day'), GETPOST('dluo' . $suffix . 'year')); - print $form->selectDate($dluodatesuffix, 'dluo' . $suffix, '', '', 1, ''); + $dluodatesuffix = dol_mktime(0, 0, 0, GETPOST('dluo'.$suffix.'month'), GETPOST('dluo'.$suffix.'day'), GETPOST('dluo'.$suffix.'year')); + print $form->selectDate($dluodatesuffix, 'dluo'.$suffix, '', '', 1, ''); print ' '; - print ''; //print img_picto($langs->trans('AddStockLocationLine'), 'split.png', 'onClick="addDispatchLine(' . $i . ',\'' . $type . '\')"'); - print '
    '; - print ''; - print ''; + print ''; + print ''; print ''; - 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").': '; + print $langs->trans("BuyingPrice").': '; } else { - print ''; + print ''; } print ''; - print ''; + print ''; print ''; @@ -819,9 +819,9 @@ if ($id > 0 || ! empty($ref)) { // Warehouse print ''; if (count($listwarehouses) > 1) { - print $formproduct->selectWarehouses(GETPOST("entrepot" . $suffix)?GETPOST("entrepot" . $suffix):($objp->fk_default_warehouse?$objp->fk_default_warehouse:''), "entrepot" . $suffix, '', 1, 0, $objp->fk_product, '', 1, 0, null, 'csswarehouse'.$suffix); + print $formproduct->selectWarehouses(GETPOST("entrepot".$suffix) ?GETPOST("entrepot".$suffix) : ($objp->fk_default_warehouse ? $objp->fk_default_warehouse : ''), "entrepot".$suffix, '', 1, 0, $objp->fk_product, '', 1, 0, null, 'csswarehouse'.$suffix); } elseif (count($listwarehouses) == 1) { - print $formproduct->selectWarehouses(GETPOST("entrepot" . $suffix)?GETPOST("entrepot" . $suffix):($objp->fk_default_warehouse?$objp->fk_default_warehouse:''), "entrepot" . $suffix, '', 0, 0, $objp->fk_product, '', 1, 0, null, 'csswarehouse'.$suffix); + print $formproduct->selectWarehouses(GETPOST("entrepot".$suffix) ?GETPOST("entrepot".$suffix) : ($objp->fk_default_warehouse ? $objp->fk_default_warehouse : ''), "entrepot".$suffix, '', 0, 0, $objp->fk_product, '', 1, 0, null, 'csswarehouse'.$suffix); } else { $langs->load("errors"); print $langs->trans("ErrorNoWarehouseDefined"); @@ -864,7 +864,7 @@ if ($id > 0 || ! empty($ref)) { // modified by hook if (empty($reshook)) { - if (empty($conf->reception->enabled)){ + if (empty($conf->reception->enabled)) { print $langs->trans("Comment").' : '; print 'trans("DispatchSupplierOrder", $object->ref); @@ -873,9 +873,9 @@ if ($id > 0 || ! empty($ref)) { print ' '.$checkboxlabel; } - empty($conf->reception->enabled)?$dispatchBt=$langs->trans("DispatchVerb"):$dispatchBt=$langs->trans("Receive"); + empty($conf->reception->enabled) ? $dispatchBt = $langs->trans("DispatchVerb") : $dispatchBt = $langs->trans("Receive"); - print '
    '; @@ -884,12 +884,12 @@ if ($id > 0 || ! empty($ref)) { } // Message if nothing to dispatch - if (! $nbproduct) { + if (!$nbproduct) { print "
    \n"; if (empty($conf->global->SUPPLIER_ORDER_DISABLE_STOCK_DISPATCH_WHEN_TOTAL_REACHED)) - print '
    '.$langs->trans("NoPredefinedProductToDispatch").'
    '; // No predefined line at all + print '
    '.$langs->trans("NoPredefinedProductToDispatch").'
    '; // No predefined line at all else - print '
    '.$langs->trans("NoMorePredefinedProductToDispatch").'
    '; // No predefined line that remain to be dispatched. + print '
    '.$langs->trans("NoMorePredefinedProductToDispatch").'
    '; // No predefined line that remain to be dispatched. } print ''; @@ -902,12 +902,12 @@ if ($id > 0 || ! empty($ref)) { $sql = "SELECT p.ref, p.label,"; $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"; - 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 . "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"; - $sql .= " WHERE cfd.fk_commande = " . $object->id; + 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."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"; + $sql .= " WHERE cfd.fk_commande = ".$object->id; $sql .= " AND cfd.fk_product = p.rowid"; $sql .= " ORDER BY cfd.rowid ASC"; @@ -922,29 +922,29 @@ if ($id > 0 || ! empty($ref)) { print load_fiche_titre($langs->trans("ReceivingForSameOrder")); print '
    '; - print ''; + print '
    '; print ''; - if($conf->reception->enabled)print ''; + if ($conf->reception->enabled)print ''; - print ''; - print ''; - print ''; - if (! empty($conf->productbatch->enabled)) { - print ''; - print ''; - print ''; + print ''; + print ''; + print ''; + if (!empty($conf->productbatch->enabled)) { + print ''; + print ''; + print ''; } - print ''; + print ''; print ''; - print ''; - print ''; + print ''; + print ''; // Status - if (! empty($conf->global->SUPPLIER_ORDER_USE_DISPATCH_STATUS) && empty($reception->rowid)) { - print ''; + if (!empty($conf->global->SUPPLIER_ORDER_USE_DISPATCH_STATUS) && empty($reception->rowid)) { + print ''; } - elseif(!empty($conf->reception->enabled)) { + elseif (!empty($conf->reception->enabled)) { print ''; } @@ -952,14 +952,14 @@ if ($id > 0 || ! empty($ref)) { print "\n"; - while ( $i < $num ) { + while ($i < $num) { $objp = $db->fetch_object($resql); - print ""; + print ""; - if(!empty($conf->reception->enabled) ){ + if (!empty($conf->reception->enabled)) { print '\n"; print ''; print ''; - if (! empty($conf->productbatch->enabled)) { - print ''; - print ''; - print ''; + if (!empty($conf->productbatch->enabled)) { + print ''; + print ''; + print ''; } // Qty - print ''; + print ''; print ''; // Warehouse @@ -993,10 +993,10 @@ if ($id > 0 || ! empty($ref)) { print ''; // Comment - print ''; + print ''; // Status - if (! empty($conf->global->SUPPLIER_ORDER_USE_DISPATCH_STATUS) && empty($reception->rowid)) { + if (!empty($conf->global->SUPPLIER_ORDER_USE_DISPATCH_STATUS) && empty($reception->rowid)) { print ''; - } elseif(!empty($conf->reception->enabled)) { + } elseif (!empty($conf->reception->enabled)) { print ''; @@ -1044,7 +1044,7 @@ if ($id > 0 || ! empty($ref)) { print "\n"; - $i ++; + $i++; } $db->free($resql); diff --git a/htdocs/fourn/commande/document.php b/htdocs/fourn/commande/document.php index 8fbe54e8580..f879f077183 100644 --- a/htdocs/fourn/commande/document.php +++ b/htdocs/fourn/commande/document.php @@ -34,12 +34,12 @@ require_once DOL_DOCUMENT_ROOT.'/core/lib/images.lib.php'; require_once DOL_DOCUMENT_ROOT.'/core/lib/fourn.lib.php'; require_once DOL_DOCUMENT_ROOT.'/core/class/html.formfile.class.php'; require_once DOL_DOCUMENT_ROOT.'/fourn/class/fournisseur.commande.class.php'; -if (! empty($conf->projet->enabled)) { - require_once DOL_DOCUMENT_ROOT . '/projet/class/project.class.php'; +if (!empty($conf->projet->enabled)) { + require_once DOL_DOCUMENT_ROOT.'/projet/class/project.class.php'; } // Load translation files required by the page -$langs->loadLangs(array("bills", "orders", "sendings", "companies", "deliveries", "products", "stocks","other")); +$langs->loadLangs(array("bills", "orders", "sendings", "companies", "deliveries", "products", "stocks", "other")); $id = GETPOST('id', 'int'); $ref = GETPOST('ref', 'alpha'); @@ -58,8 +58,8 @@ if (empty($page) || $page == -1) { $page = 0; } // If $page is not defined, $offset = $conf->liste_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); @@ -77,18 +77,18 @@ $object->fetch_thirdparty(); * Actions */ -include_once DOL_DOCUMENT_ROOT . '/core/actions_linkedfiles.inc.php'; +include_once DOL_DOCUMENT_ROOT.'/core/actions_linkedfiles.inc.php'; /* * View */ -$form = new Form($db); +$form = new Form($db); if ($object->id > 0) { - $help_url='EN:Module_Suppliers_Orders|FR:CommandeFournisseur|ES:Módulo_Pedidos_a_proveedores'; + $help_url = 'EN:Module_Suppliers_Orders|FR:CommandeFournisseur|ES:Módulo_Pedidos_a_proveedores'; llxHeader('', $langs->trans("Order"), $help_url); $object->fetch_thirdparty(); @@ -174,8 +174,8 @@ if ($object->id > 0) $modulepart = 'commande_fournisseur'; $permission = $user->rights->fournisseur->commande->creer; $permtoedit = $user->rights->fournisseur->commande->creer; - $param = '&id=' . $object->id; - include_once DOL_DOCUMENT_ROOT . '/core/tpl/document_actions_post_headers.tpl.php'; + $param = '&id='.$object->id; + include_once DOL_DOCUMENT_ROOT.'/core/tpl/document_actions_post_headers.tpl.php'; } else { diff --git a/htdocs/fourn/commande/index.php b/htdocs/fourn/commande/index.php index 5a8e0446cea..2831e4590c7 100644 --- a/htdocs/fourn/commande/index.php +++ b/htdocs/fourn/commande/index.php @@ -32,7 +32,7 @@ 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); @@ -51,7 +51,7 @@ $langs->loadLangs(array("suppliers", "orders")); llxHeader('', $langs->trans("SuppliersOrdersArea")); $commandestatic = new CommandeFournisseur($db); -$userstatic=new User($db); +$userstatic = new User($db); $formfile = new FormFile($db); print load_fiche_titre($langs->trans("SuppliersOrdersArea"), '', 'commercial'); @@ -59,15 +59,16 @@ print load_fiche_titre($langs->trans("SuppliersOrdersArea"), '', 'commercial'); 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 { print '
    '; print ''; - print '
    ' . $langs->trans("Reception") . ''.$langs->trans("Reception").'' . $langs->trans("Product") . '' . $langs->trans("DateCreation") . '' . $langs->trans("DateDeliveryPlanned") . '' . $langs->trans("batch_number") . '' . $langs->trans("EatByDate") . '' . $langs->trans("SellByDate") . ''.$langs->trans("Product").''.$langs->trans("DateCreation").''.$langs->trans("DateDeliveryPlanned").''.$langs->trans("batch_number").''.$langs->trans("EatByDate").''.$langs->trans("SellByDate").'' . $langs->trans("QtyDispatched") . ''.$langs->trans("QtyDispatched").'' . $langs->trans("Warehouse") . '' . $langs->trans("Comment") . ''.$langs->trans("Warehouse").''.$langs->trans("Comment").'' . $langs->trans("Status") . ''.$langs->trans("Status").'
    '; - if (!empty($objp->fk_reception)){ + if (!empty($objp->fk_reception)) { $reception = new Reception($db); $reception->fetch($objp->fk_reception); print $reception->getNomUrl(1); @@ -969,20 +969,20 @@ if ($id > 0 || ! empty($ref)) { } print ''; - print '' . img_object($langs->trans("ShowProduct"), 'product') . ' ' . $objp->ref . ''; - print ' - ' . $objp->label; + print ''.img_object($langs->trans("ShowProduct"), 'product').' '.$objp->ref.''; + print ' - '.$objp->label; print "'.dol_print_date($db->jdate($objp->datec), 'day').''.dol_print_date($db->jdate($objp->date_delivery), 'day').'' . $objp->batch . '' . dol_print_date($db->jdate($objp->eatby), 'day') . '' . dol_print_date($db->jdate($objp->sellby), 'day') . ''.$objp->batch.''.dol_print_date($db->jdate($objp->eatby), 'day').''.dol_print_date($db->jdate($objp->sellby), 'day').'' . $objp->qty . ''.$objp->qty.' ' . $objp->comment . ''.$objp->comment.''; $supplierorderdispatch->status = (empty($objp->status) ? 0 : $objp->status); // print $supplierorderdispatch->status; @@ -1005,36 +1005,36 @@ if ($id > 0 || ! empty($ref)) { // Add button to check/uncheck disaptching print ''; - 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 '' . $langs->trans("Approve") . ''; - print '' . $langs->trans("Deny") . ''; + print ''.$langs->trans("Approve").''; + print ''.$langs->trans("Deny").''; } else { - print '' . $langs->trans("Disapprove") . ''; - print '' . $langs->trans("Deny") . ''; + print ''.$langs->trans("Disapprove").''; + print ''.$langs->trans("Deny").''; } } else { $disabled = ''; if ($object->statut == 5) $disabled = 1; if (empty($objp->status)) { - print 'dispatchlineid . '">' . $langs->trans("Approve") . ''; - print 'dispatchlineid . '">' . $langs->trans("Deny") . ''; + print 'dispatchlineid.'">'.$langs->trans("Approve").''; + print 'dispatchlineid.'">'.$langs->trans("Deny").''; } if ($objp->status == 1) { - print 'dispatchlineid . '">' . $langs->trans("Reinit") . ''; - print 'dispatchlineid . '">' . $langs->trans("Deny") . ''; + print 'dispatchlineid.'">'.$langs->trans("Reinit").''; + print 'dispatchlineid.'">'.$langs->trans("Deny").''; } if ($objp->status == 2) { - print 'dispatchlineid . '">' . $langs->trans("Reinit") . ''; - print 'dispatchlineid . '">' . $langs->trans("Approve") . ''; + print 'dispatchlineid.'">'.$langs->trans("Reinit").''; + print 'dispatchlineid.'">'.$langs->trans("Approve").''; } } print ''; - if(!empty($reception->id)){ + if (!empty($reception->id)) { print $reception->getLibStatut(5); } print '
    '; + print '
    '; + print '
    '; print ''; print ''; - print "
    '.$langs->trans("Search").'
    '; print $langs->trans("SupplierOrder").':

    \n"; + print "

    \n"; } @@ -76,14 +77,14 @@ if (! empty($conf->global->MAIN_SEARCH_FORM_ON_HOME_AREAS)) // This is usele */ $sql = "SELECT count(cf.rowid), fk_statut"; -$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"; -$sql.= " WHERE cf.fk_soc = s.rowid"; -$sql.= " AND cf.entity = ".$conf->entity; -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"; +$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"; +$sql .= " WHERE cf.fk_soc = s.rowid"; +$sql .= " AND cf.entity = ".$conf->entity; +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) @@ -91,10 +92,10 @@ if ($resql) $num = $db->num_rows($resql); $i = 0; - $total=0; - $totalinprocess=0; - $dataseries=array(); - $vals=array(); + $total = 0; + $totalinprocess = 0; + $dataseries = array(); + $vals = array(); // 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 @@ -103,28 +104,29 @@ if ($resql) $row = $db->fetch_row($resql); if ($row) { - if ($row[1]!=7 && $row[1]!=6 && $row[1]!=5) + if ($row[1] != 7 && $row[1] != 6 && $row[1] != 5) { - $vals[$row[1]]=$row[0]; - $totalinprocess+=$row[0]; + $vals[$row[1]] = $row[0]; + $totalinprocess += $row[0]; } - $total+=$row[0]; + $total += $row[0]; } $i++; } $db->free($resql); - print ''; + print '
    '; + print '
    '; print ''; print "\n"; - foreach (array(0,1,2,3,4,5,6) as $status) + foreach (array(0, 1, 2, 3, 4, 5, 6) as $status) { - $dataseries[]=array($commandestatic->LibStatut($status, 1), (isset($vals[$status])?(int) $vals[$status]:0)); - if (! $conf->use_javascript_ajax) + $dataseries[] = array($commandestatic->LibStatut($status, 1), (isset($vals[$status]) ? (int) $vals[$status] : 0)); + if (!$conf->use_javascript_ajax) { print ''; print ''; - print ''; + print ''; print "\n"; } } @@ -140,7 +142,7 @@ if ($resql) $dolgraph->SetType(array('pie')); $dolgraph->setWidth('100%'); $dolgraph->draw('idgraphstatus'); - print $dolgraph->show($total?0:1); + print $dolgraph->show($total ? 0 : 1); print ''; } @@ -148,7 +150,7 @@ if ($resql) //print ''; print ''; - print "
    '.$langs->trans("Statistics").' - '.$langs->trans("SuppliersOrders").'
    '.$commandestatic->LibStatut($status, 0).''.(isset($vals[$status])?$vals[$status]:0).''.(isset($vals[$status]) ? $vals[$status] : 0).'
    '.$langs->trans("Total").' ('.$langs->trans("SuppliersOrdersRunning").')'.$totalinprocess.'
    '.$langs->trans("Total").''.$total.'

    "; + print "

    "; } else { @@ -163,14 +165,14 @@ else */ $sql = "SELECT count(cf.rowid), fk_statut"; -$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"; -$sql.= " WHERE cf.fk_soc = s.rowid"; -$sql.= " AND s.entity = ".$conf->entity; -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"; +$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"; +$sql .= " WHERE cf.fk_soc = s.rowid"; +$sql .= " AND s.entity = ".$conf->entity; +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) @@ -178,7 +180,8 @@ if ($resql) $num = $db->num_rows($resql); $i = 0; - print ''; + print '
    '; + print '
    '; print ''; print ''; @@ -195,7 +198,7 @@ if ($resql) print "\n"; $i++; } - print "
    '.$langs->trans("Status").''.$langs->trans("Nb").'

    "; + print "

    "; $db->free($resql); } else @@ -208,22 +211,23 @@ else * 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"; - $sql.= " WHERE c.fk_soc = s.rowid"; - $sql.= " AND c.entity = ".$conf->entity; - $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; + $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"; + $sql .= " WHERE c.fk_soc = s.rowid"; + $sql .= " AND c.entity = ".$conf->entity; + $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; - $resql=$db->query($sql); + $resql = $db->query($sql); if ($resql) { - print ''; + print '
    '; + print '
    '; print ''; print ''; $langs->load("orders"); @@ -242,7 +246,7 @@ if (! empty($conf->fournisseur->enabled)) $i++; } } - print "
    '.$langs->trans("DraftOrders").'

    "; + print "

    "; } } @@ -251,16 +255,16 @@ if (! empty($conf->fournisseur->enabled)) * List of users allowed */ $sql = "SELECT u.rowid, u.lastname, u.firstname, u.email"; -$sql.= " FROM ".MAIN_DB_PREFIX."user as u,"; -$sql.= " ".MAIN_DB_PREFIX."user_rights as ur"; -$sql.= ", ".MAIN_DB_PREFIX."rights_def as rd"; -$sql.= " WHERE u.rowid = ur.fk_user"; -$sql.= " AND (u.entity IN (0,".$conf->entity.")"; -$sql.= " AND rd.entity = ".$conf->entity.")"; -$sql.= " AND ur.fk_id = rd.id"; -$sql.= " AND module = 'fournisseur'"; -$sql.= " AND perms = 'commande'"; -$sql.= " AND subperms = 'approuver'"; +$sql .= " FROM ".MAIN_DB_PREFIX."user as u,"; +$sql .= " ".MAIN_DB_PREFIX."user_rights as ur"; +$sql .= ", ".MAIN_DB_PREFIX."rights_def as rd"; +$sql .= " WHERE u.rowid = ur.fk_user"; +$sql .= " AND (u.entity IN (0,".$conf->entity.")"; +$sql .= " AND rd.entity = ".$conf->entity.")"; +$sql .= " AND ur.fk_id = rd.id"; +$sql .= " AND module = 'fournisseur'"; +$sql .= " AND perms = 'commande'"; +$sql .= " AND subperms = 'approuver'"; $resql = $db->query($sql); if ($resql) @@ -268,7 +272,8 @@ if ($resql) $num = $db->num_rows($resql); $i = 0; - print ''; + print '
    '; + print '
    '; print ''; print "\n"; @@ -278,16 +283,16 @@ if ($resql) print ''; print ''; print "\n"; $i++; } - print "
    '.$langs->trans("UserWithApproveOrderGrant").'
    '; - $userstatic->id=$obj->rowid; - $userstatic->lastname=$obj->lastname; - $userstatic->firstname=$obj->firstname; - $userstatic->email=$obj->email; + $userstatic->id = $obj->rowid; + $userstatic->lastname = $obj->lastname; + $userstatic->firstname = $obj->firstname; + $userstatic->email = $obj->email; print $userstatic->getNomUrl(1); print '

    "; + print "

    "; $db->free($resql); } else @@ -302,24 +307,25 @@ print '
    '; /* * Last modified orders */ -$max=5; +$max = 5; $sql = "SELECT c.rowid, c.ref, c.fk_statut, c.tms, 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"; -$sql.= " WHERE c.fk_soc = s.rowid"; -$sql.= " AND c.entity = ".$conf->entity; +$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"; +$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; -$sql.= " ORDER BY c.tms DESC"; -$sql.= $db->plimit($max, 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; +$sql .= " ORDER BY c.tms DESC"; +$sql .= $db->plimit($max, 0); -$resql=$db->query($sql); +$resql = $db->query($sql); if ($resql) { - print ''; + print '
    '; + print '
    '; print ''; print ''; @@ -334,8 +340,8 @@ if ($resql) print ''; print '
    '.$langs->trans("LastModifiedOrders", $max).'
    '; - $commandestatic->id=$obj->rowid; - $commandestatic->ref=$obj->ref; + $commandestatic->id = $obj->rowid; + $commandestatic->ref = $obj->ref; print ''; print ''; print '
    '; @@ -347,9 +353,9 @@ if ($resql) print ''; - $filename=dol_sanitizeFileName($obj->ref); - $filedir=$conf->commande->dir_output . '/' . dol_sanitizeFileName($obj->ref); - $urlsource=$_SERVER['PHP_SELF'].'?id='.$obj->rowid; + $filename = dol_sanitizeFileName($obj->ref); + $filedir = $conf->commande->dir_output.'/'.dol_sanitizeFileName($obj->ref); + $urlsource = $_SERVER['PHP_SELF'].'?id='.$obj->rowid; print $formfile->getDocumentsLink($commandestatic->element, $filename, $filedir); print '
    '; @@ -362,7 +368,7 @@ if ($resql) $i++; } } - print "

    "; + print "

    "; } else dol_print_error($db); @@ -387,7 +393,8 @@ if ($resql) { $num = $db->num_rows($resql); -print ''; +print '
    '; +print '
    '; print ''; print ''; @@ -431,7 +438,7 @@ $i++; } } -print "
    '.$langs->trans("OrdersToProcess").' ('.$num.')

    "; +print "

    "; } */ diff --git a/htdocs/fourn/commande/info.php b/htdocs/fourn/commande/info.php index 4f73b373589..6928ed9d055 100644 --- a/htdocs/fourn/commande/info.php +++ b/htdocs/fourn/commande/info.php @@ -65,15 +65,15 @@ if (!$user->rights->fournisseur->commande->lire) accessforbidden(); * Actions */ -$parameters=array('id'=>$id); -$reshook=$hookmanager->executeHooks('doActions', $parameters, $object, $action); // Note that $action and $object may have been modified by some hooks +$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'); // 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 { - $actioncode=''; - $search_agenda_label=''; + $actioncode = ''; + $search_agenda_label = ''; } @@ -82,22 +82,22 @@ if (GETPOST('button_removefilter_x', 'alpha') || GETPOST('button_removefilter.x' * View */ -$form = new Form($db); +$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"); -$help_url='EN:Module_Suppliers_Orders|FR:CommandeFournisseur|ES:Módulo_Pedidos_a_proveedores'; +$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"); +$help_url = 'EN:Module_Suppliers_Orders|FR:CommandeFournisseur|ES:Módulo_Pedidos_a_proveedores'; llxHeader('', $title, $help_url); -$now=dol_now(); +$now = dol_now(); $head = ordersupplier_prepare_head($object); @@ -170,19 +170,19 @@ dol_fiche_end(); // Actions buttons -$out=''; -$permok=$user->rights->agenda->myactions->create; +$out = ''; +$permok = $user->rights->agenda->myactions->create; if ($permok) { - $out.='&originid='.$object->id.'&origin=order_supplier'; + $out .= '&originid='.$object->id.'&origin=order_supplier'; } print '
    '; -if (! empty($conf->agenda->enabled)) +if (!empty($conf->agenda->enabled)) { - if (! empty($user->rights->agenda->myactions->create) || ! empty($user->rights->agenda->allactions->create)) + if (!empty($user->rights->agenda->myactions->create) || !empty($user->rights->agenda->allactions->create)) { print ''.$langs->trans("AddAction").''; } @@ -197,9 +197,9 @@ print '
    '; 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; + $param = '&id='.$object->id; + 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"), '', ''); @@ -215,8 +215,8 @@ if (!empty($object->id)) //show_actions_done($conf,$langs,$db,$object,null,0,$actioncode); // List of all actions - $filters=array(); - $filters['search_agenda_label']=$search_agenda_label; + $filters = array(); + $filters['search_agenda_label'] = $search_agenda_label; show_actions_done($conf, $langs, $db, $object, null, 0, $actioncode, '', $filters); } diff --git a/htdocs/fourn/commande/list.php b/htdocs/fourn/commande/list.php index 197d4562114..4582f76c8a6 100644 --- a/htdocs/fourn/commande/list.php +++ b/htdocs/fourn/commande/list.php @@ -42,61 +42,61 @@ require_once DOL_DOCUMENT_ROOT.'/core/class/html.formcompany.class.php'; require_once DOL_DOCUMENT_ROOT.'/product/class/product.class.php'; require_once DOL_DOCUMENT_ROOT.'/projet/class/project.class.php'; -$langs->loadLangs(array("orders","sendings",'deliveries','companies','compta','bills','projects','suppliers')); +$langs->loadLangs(array("orders", "sendings", 'deliveries', 'companies', 'compta', 'bills', 'projects', 'suppliers')); -$action=GETPOST('action', 'aZ09'); -$massaction=GETPOST('massaction', 'alpha'); -$show_files=GETPOST('show_files', 'int'); -$confirm=GETPOST('confirm', 'alpha'); +$action = GETPOST('action', 'aZ09'); +$massaction = GETPOST('massaction', 'alpha'); +$show_files = GETPOST('show_files', 'int'); +$confirm = GETPOST('confirm', 'alpha'); $toselect = GETPOST('toselect', 'array'); -$contextpage=GETPOST('contextpage', 'aZ')?GETPOST('contextpage', 'aZ'):'supplierorderlist'; +$contextpage = GETPOST('contextpage', 'aZ') ?GETPOST('contextpage', 'aZ') : 'supplierorderlist'; -$search_orderyear=GETPOST("search_orderyear", "int"); -$search_ordermonth=GETPOST("search_ordermonth", "int"); -$search_orderday=GETPOST("search_orderday", "int"); -$search_deliveryyear=GETPOST("search_deliveryyear", "int"); -$search_deliverymonth=GETPOST("search_deliverymonth", "int"); -$search_deliveryday=GETPOST("search_deliveryday", "int"); +$search_orderyear = GETPOST("search_orderyear", "int"); +$search_ordermonth = GETPOST("search_ordermonth", "int"); +$search_orderday = GETPOST("search_orderday", "int"); +$search_deliveryyear = GETPOST("search_deliveryyear", "int"); +$search_deliverymonth = GETPOST("search_deliverymonth", "int"); +$search_deliveryday = GETPOST("search_deliveryday", "int"); -$sall=trim((GETPOST('search_all', 'alphanohtml')!='')?GETPOST('search_all', 'alphanohtml'):GETPOST('sall', 'alphanohtml')); +$sall = trim((GETPOST('search_all', 'alphanohtml') != '') ?GETPOST('search_all', 'alphanohtml') : GETPOST('sall', 'alphanohtml')); -$search_product_category=GETPOST('search_product_category', 'int'); -$search_ref=GETPOST('search_ref', 'alpha'); -$search_refsupp=GETPOST('search_refsupp', 'alpha'); -$search_company=GETPOST('search_company', 'alpha'); -$search_town=GETPOST('search_town', 'alpha'); -$search_zip=GETPOST('search_zip', 'alpha'); -$search_state=trim(GETPOST("search_state", 'alpha')); -$search_country=GETPOST("search_country", 'int'); -$search_type_thirdparty=GETPOST("search_type_thirdparty", 'int'); -$search_user=GETPOST('search_user', 'int'); -$search_request_author=GETPOST('search_request_author', 'alpha'); -$search_ht=GETPOST('search_ht', 'alpha'); -$search_ttc=GETPOST('search_ttc', 'alpha'); -$search_status=(GETPOST('search_status', 'alpha')!=''?GETPOST('search_status', 'alpha'):GETPOST('statut', 'alpha')); // alpha and not intbecause it can be '6,7' +$search_product_category = GETPOST('search_product_category', 'int'); +$search_ref = GETPOST('search_ref', 'alpha'); +$search_refsupp = GETPOST('search_refsupp', 'alpha'); +$search_company = GETPOST('search_company', 'alpha'); +$search_town = GETPOST('search_town', 'alpha'); +$search_zip = GETPOST('search_zip', 'alpha'); +$search_state = trim(GETPOST("search_state", 'alpha')); +$search_country = GETPOST("search_country", 'int'); +$search_type_thirdparty = GETPOST("search_type_thirdparty", 'int'); +$search_user = GETPOST('search_user', 'int'); +$search_request_author = GETPOST('search_request_author', 'alpha'); +$search_ht = GETPOST('search_ht', 'alpha'); +$search_ttc = GETPOST('search_ttc', 'alpha'); +$search_status = (GETPOST('search_status', 'alpha') != '' ?GETPOST('search_status', 'alpha') : GETPOST('statut', 'alpha')); // alpha and not intbecause it can be '6,7' $optioncss = GETPOST('optioncss', 'alpha'); $socid = GETPOST('socid', 'int'); -$search_sale=GETPOST('search_sale', 'int'); -$search_total_ht=GETPOST('search_total_ht', 'alpha'); -$search_total_vat=GETPOST('search_total_vat', 'alpha'); -$search_total_ttc=GETPOST('search_total_ttc', 'alpha'); +$search_sale = GETPOST('search_sale', 'int'); +$search_total_ht = GETPOST('search_total_ht', 'alpha'); +$search_total_vat = GETPOST('search_total_vat', 'alpha'); +$search_total_ttc = GETPOST('search_total_ttc', 'alpha'); $optioncss = GETPOST('optioncss', 'alpha'); $search_billed = GETPOST('search_billed', 'int'); -$search_project_ref=GETPOST('search_project_ref', 'alpha'); -$search_btn=GETPOST('button_search', 'alpha'); -$search_remove_btn=GETPOST('button_removefilter', 'alpha'); +$search_project_ref = GETPOST('search_project_ref', 'alpha'); +$search_btn = GETPOST('button_search', 'alpha'); +$search_remove_btn = GETPOST('button_removefilter', 'alpha'); -$status=GETPOST('statut', 'alpha'); -$viewstatut=GETPOST('viewstatut'); +$status = GETPOST('statut', 'alpha'); +$viewstatut = GETPOST('viewstatut'); // 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; +$diroutputmassaction = $conf->fournisseur->commande->dir_output.'/temp/massgeneration/'.$user->id; -$limit = GETPOST('limit', 'int')?GETPOST('limit', 'int'):$conf->liste_limit; +$limit = GETPOST('limit', 'int') ?GETPOST('limit', 'int') : $conf->liste_limit; $sortfield = GETPOST("sortfield", 'alpha'); $sortorder = GETPOST("sortorder", 'alpha'); $page = GETPOST("page", 'int'); @@ -104,10 +104,10 @@ if (empty($page) || $page == -1 || !empty($search_btn) || !empty($search_remove_ $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); @@ -117,7 +117,7 @@ $extrafields = new ExtraFields($db); // fetch optionals attributes and labels $extrafields->fetch_name_optionals_label('commande_fournisseur'); -$search_array_options=$extrafields->getOptionalsFromPost($object->table_element, '', 'search_'); +$search_array_options = $extrafields->getOptionalsFromPost($object->table_element, '', 'search_'); // List of fields to search into when doing a "search in all" $fieldstosearchall = array( @@ -127,10 +127,10 @@ $fieldstosearchall = array( 's.nom'=>"ThirdParty", '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( +$checkedtypetiers = 0; +$arrayfields = array( 'cf.ref'=>array('label'=>$langs->trans("Ref"), 'checked'=>1), 'cf.ref_supplier'=>array('label'=>$langs->trans("RefOrderSupplierShort"), 'checked'=>1, 'enabled'=>1), 'p.project_ref'=>array('label'=>$langs->trans("ProjectRef"), 'checked'=>0, 'enabled'=>1), @@ -154,10 +154,10 @@ $arrayfields=array( // 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) + 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], 'checked'=>(($extrafields->attributes[$object->table_element]['list'][$key]<0)?0:1), 'position'=>$extrafields->attributes[$object->table_element]['pos'][$key], 'enabled'=>(abs($extrafields->attributes[$object->table_element]['list'][$key])!=3 && $extrafields->attributes[$object->table_element]['perms'][$key])); + if (!empty($extrafields->attributes[$object->table_element]['list'][$key])) + $arrayfields["ef.".$key] = array('label'=>$extrafields->attributes[$object->table_element]['label'][$key], 'checked'=>(($extrafields->attributes[$object->table_element]['list'][$key] < 0) ? 0 : 1), 'position'=>$extrafields->attributes[$object->table_element]['pos'][$key], 'enabled'=>(abs($extrafields->attributes[$object->table_element]['list'][$key]) != 3 && $extrafields->attributes[$object->table_element]['perms'][$key])); } } $object->fields = dol_sort_array($object->fields, 'position'); @@ -169,11 +169,11 @@ $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 +$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)) @@ -184,45 +184,45 @@ if (empty($reshook)) // Purge search criteria if (GETPOST('button_removefilter_x', 'alpha') || GETPOST('button_removefilter.x', 'alpha') || GETPOST('button_removefilter', 'alpha')) // All tests are required to be compatible with all browsers { - $search_categ=''; - $search_user=''; - $search_sale=''; - $search_product_category=''; - $search_ref=''; - $search_refsupp=''; - $search_company=''; - $search_town=''; - $search_zip=""; - $search_state=""; - $search_type=''; - $search_country=''; - $search_type_thirdparty=''; - $search_request_author=''; - $search_total_ht=''; - $search_total_vat=''; - $search_total_ttc=''; - $search_project_ref=''; - $search_status=-1; - $search_orderyear=''; - $search_ordermonth=''; - $search_orderday=''; - $search_deliveryday=''; - $search_deliverymonth=''; - $search_deliveryyear=''; - $billed=''; - $search_billed=''; - $toselect=''; - $search_array_options=array(); + $search_categ = ''; + $search_user = ''; + $search_sale = ''; + $search_product_category = ''; + $search_ref = ''; + $search_refsupp = ''; + $search_company = ''; + $search_town = ''; + $search_zip = ""; + $search_state = ""; + $search_type = ''; + $search_country = ''; + $search_type_thirdparty = ''; + $search_request_author = ''; + $search_total_ht = ''; + $search_total_vat = ''; + $search_total_ttc = ''; + $search_project_ref = ''; + $search_status = -1; + $search_orderyear = ''; + $search_ordermonth = ''; + $search_orderday = ''; + $search_deliveryday = ''; + $search_deliverymonth = ''; + $search_deliveryyear = ''; + $billed = ''; + $search_billed = ''; + $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')) { - $massaction=''; // Protection to avoid mass action if we force a new search during a mass action confirmation + $massaction = ''; // Protection to avoid mass action if we force a new search during a mass action confirmation } // Mass actions - $objectclass='CommandeFournisseur'; - $objectlabel='SupplierOrders'; + $objectclass = 'CommandeFournisseur'; + $objectlabel = 'SupplierOrders'; $permissiontoread = $user->rights->fournisseur->commande->lire; $permissiontodelete = $user->rights->fournisseur->commande->supprimer; $uploaddir = $conf->fournisseur->commande->dir_output; @@ -242,18 +242,18 @@ if (empty($reshook)) $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; $object = new Facture($db); - if(!empty($createbills_onebythird) && !empty($TFactThird[$cmd->socid])) $object = $TFactThird[$cmd->socid]; // If option "one bill per third" is set, we use already created order. + if (!empty($createbills_onebythird) && !empty($TFactThird[$cmd->socid])) $object = $TFactThird[$cmd->socid]; // If option "one bill per third" is set, we use already created order. else { $object->socid = $cmd->socid; $object->type = Facture::TYPE_STANDARD; $object->cond_reglement_id = $cmd->cond_reglement_id; $object->mode_reglement_id = $cmd->mode_reglement_id; - $object->fk_project = $cmd->fk_project; + $object->fk_project = $cmd->fk_project; $datefacture = dol_mktime(12, 0, 0, $_POST['remonth'], $_POST['reday'], $_POST['reyear']); if (empty($datefacture)) @@ -267,29 +267,29 @@ if (empty($reshook)) $res = $object->create($user); - if($res > 0) $nb_bills_created++; + if ($res > 0) $nb_bills_created++; } if ($object->id > 0) { $sql = "INSERT INTO ".MAIN_DB_PREFIX."element_element ("; - $sql.= "fk_source"; - $sql.= ", sourcetype"; - $sql.= ", fk_target"; - $sql.= ", targettype"; - $sql.= ") VALUES ("; - $sql.= $id_order; - $sql.= ", '".$object->origin."'"; - $sql.= ", ".$object->id; - $sql.= ", '".$object->element."'"; - $sql.= ")"; + $sql .= "fk_source"; + $sql .= ", sourcetype"; + $sql .= ", fk_target"; + $sql .= ", targettype"; + $sql .= ") VALUES ("; + $sql .= $id_order; + $sql .= ", '".$object->origin."'"; + $sql .= ", ".$object->id; + $sql .= ", '".$object->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')) @@ -298,27 +298,27 @@ if (empty($reshook)) $lines = $cmd->lines; } - $fk_parent_line=0; - $num=count($lines); + $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); + $desc = ($lines[$i]->desc ? $lines[$i]->desc : $lines[$i]->libelle); if ($lines[$i]->subprice < 0) { // Negative line, we create a discount line $discount = new DiscountAbsolute($db); - $discount->fk_soc=$object->socid; - $discount->amount_ht=abs($lines[$i]->total_ht); - $discount->amount_tva=abs($lines[$i]->total_tva); - $discount->amount_ttc=abs($lines[$i]->total_ttc); - $discount->tva_tx=$lines[$i]->tva_tx; - $discount->fk_user=$user->id; - $discount->description=$desc; - $discountid=$discount->create($user); + $discount->fk_soc = $object->socid; + $discount->amount_ht = abs($lines[$i]->total_ht); + $discount->amount_tva = abs($lines[$i]->total_tva); + $discount->amount_ttc = abs($lines[$i]->total_ttc); + $discount->tva_tx = $lines[$i]->tva_tx; + $discount->fk_user = $user->id; + $discount->description = $desc; + $discountid = $discount->create($user); if ($discountid > 0) { - $result=$object->insert_discount($discountid); + $result = $object->insert_discount($discountid); //$result=$discount->link_to_invoice($lineid,$id); } else @@ -331,17 +331,17 @@ if (empty($reshook)) else { // Positive line - $product_type=($lines[$i]->product_type?$lines[$i]->product_type:0); + $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; + $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; //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; + $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; // 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) { @@ -375,11 +375,11 @@ if (empty($reshook)) ); if ($result > 0) { - $lineid=$result; + $lineid = $result; } else { - $lineid=0; + $lineid = 0; $error++; break; } @@ -393,9 +393,9 @@ if (empty($reshook)) } } - $cmd->classifyBilled($user); // TODO Move this in workflow like done for customer orders + $cmd->classifyBilled($user); // TODO Move this in workflow like done for customer orders - if(!empty($createbills_onebythird) && empty($TFactThird[$cmd->socid])) $TFactThird[$cmd->socid] = $object; + if (!empty($createbills_onebythird) && empty($TFactThird[$cmd->socid])) $TFactThird[$cmd->socid] = $object; else $TFact[$object->id] = $object; } @@ -403,10 +403,10 @@ if (empty($reshook)) $TAllFact = empty($createbills_onebythird) ? $TFact : $TFactThird; $toselect = array(); - if (! $error && $validate_invoices) { + if (!$error && $validate_invoices) { $massaction = $action = 'builddoc'; - foreach($TAllFact as &$object) + foreach ($TAllFact as &$object) { $object->validate($user); if ($result <= 0) @@ -436,9 +436,9 @@ if (empty($reshook)) else { $db->rollback(); - $action='create'; - $_GET["origin"]=$_POST["origin"]; - $_GET["originid"]=$_POST["originid"]; + $action = 'create'; + $_GET["origin"] = $_POST["origin"]; + $_GET["originid"] = $_POST["originid"]; setEventMessages($object->error, $object->errors, 'errors'); $error++; } @@ -450,15 +450,15 @@ if (empty($reshook)) * View */ -$now=dol_now(); +$now = dol_now(); -$form=new Form($db); +$form = new Form($db); $thirdpartytmp = new Fournisseur($db); -$commandestatic=new CommandeFournisseur($db); +$commandestatic = new CommandeFournisseur($db); $formfile = new FormFile($db); $formorder = new FormOrder($db); $formother = new FormOther($db); -$formcompany=new FormCompany($db); +$formcompany = new FormCompany($db); $title = $langs->trans("SuppliersOrders"); if ($socid > 0) @@ -469,88 +469,88 @@ if ($socid > 0) } if ($status) { - if ($status == '1,2,3') $title.=' - '.$langs->trans("StatusOrderToProcessShort"); - if ($status == '6,7') $title.=' - '.$langs->trans("StatusOrderCanceled"); - else $title.=' - '.$commandestatic->LibStatut($status); + if ($status == '1,2,3') $title .= ' - '.$langs->trans("StatusOrderToProcessShort"); + if ($status == '6,7') $title .= ' - '.$langs->trans("StatusOrderCanceled"); + else $title .= ' - '.$commandestatic->LibStatut($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=''; +$help_url = ''; // llxHeader('',$title,$help_url); $sql = 'SELECT'; if ($sall || $search_product_category > 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,"; -$sql.= " cf.rowid, cf.ref, cf.ref_supplier, cf.fk_statut, cf.billed, cf.total_ht, cf.tva as total_tva, cf.total_ttc, cf.fk_user_author, cf.date_commande as date_commande, cf.date_livraison as date_delivery,"; -$sql.= ' cf.date_creation as date_creation, cf.tms as date_update,'; -$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"; +$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,"; +$sql .= " cf.rowid, cf.ref, cf.ref_supplier, cf.fk_statut, cf.billed, cf.total_ht, cf.tva as total_tva, cf.total_ttc, cf.fk_user_author, cf.date_commande as date_commande, cf.date_livraison as date_delivery,"; +$sql .= ' cf.date_creation as date_creation, cf.tms as date_update,'; +$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 : ''); +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 : ''); } // 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."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)"; -$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'; -$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"; +$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."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)"; +$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'; +$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_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 .= ", ".MAIN_DB_PREFIX."element_contact as ec"; + $sql .= ", ".MAIN_DB_PREFIX."c_type_contact as tc"; } -$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; +$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 ($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_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 ($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') !== '') $sql .= " AND cf.fk_statut IN (".$db->escape($db->escape(GETPOST('statut', 'intcomma'))).")"; if ($search_status != '' && $search_status >= 0) - $sql.=" AND cf.fk_statut IN (".$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); + $sql .= " AND cf.fk_statut IN (".$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->escape($search_country).')'; if ($search_type_thirdparty) $sql .= " AND s.fk_typent IN (".$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_vat != '') $sql.= natural_search('cf.tva', $search_total_vat, 1); -if ($search_total_ttc != '') $sql.= natural_search('cf.total_ttc', $search_total_ttc, 1); -if ($search_project_ref != '') $sql.= natural_search("p.ref", $search_project_ref); +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_vat != '') $sql .= natural_search('cf.tva', $search_total_vat, 1); +if ($search_total_ttc != '') $sql .= natural_search('cf.total_ttc', $search_total_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 -$parameters=array(); -$reshook=$hookmanager->executeHooks('printFieldListWhere', $parameters); // Note that $action and $object may have been modified by hook -$sql.=$hookmanager->resPrint; +$parameters = array(); +$reshook = $hookmanager->executeHooks('printFieldListWhere', $parameters); // Note that $action and $object may have been modified by hook +$sql .= $hookmanager->resPrint; -$sql.= $db->order($sortfield, $sortorder); +$sql .= $db->order($sortfield, $sortorder); $nbtotalofrecords = ''; if (empty($conf->global->MAIN_DISABLE_FULL_SCANLIST)) @@ -564,7 +564,7 @@ if (empty($conf->global->MAIN_DISABLE_FULL_SCANLIST)) } } -$sql.= $db->plimit($limit+1, $offset); +$sql .= $db->plimit($limit + 1, $offset); $resql = $db->query($sql); if ($resql) @@ -573,7 +573,7 @@ if ($resql) { $soc = new Societe($db); $soc->fetch($socid); - $title = $langs->trans('ListOfSupplierOrders') . ' - '.$soc->name; + $title = $langs->trans('ListOfSupplierOrders').' - '.$soc->name; } else { @@ -582,9 +582,9 @@ if ($resql) $num = $db->num_rows($resql); - $arrayofselected=is_array($toselect)?$toselect:array(); + $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; @@ -594,48 +594,48 @@ if ($resql) llxHeader('', $title, $help_url); - $param=''; - if ($socid > 0) $param.='&socid='.$socid; - if (! empty($contextpage) && $contextpage != $_SERVER["PHP_SELF"]) $param.='&contextpage='.$contextpage; - if ($limit > 0 && $limit != $conf->liste_limit) $param.='&limit='.$limit; - if ($sall) $param.="&search_all=".$sall; - if ($search_orderday) $param.='&search_orderday='.$search_orderday; - if ($search_ordermonth) $param.='&search_ordermonth='.$search_ordermonth; - if ($search_orderyear) $param.='&search_orderyear='.$search_orderyear; - if ($search_deliveryday) $param.='&search_deliveryday='.$search_deliveryday; - if ($search_deliverymonth) $param.='&search_deliverymonth='.$search_deliverymonth; - if ($search_deliveryyear) $param.='&search_deliveryyear='.$search_deliveryyear; - if ($search_ref) $param.='&search_ref='.$search_ref; - if ($search_company) $param.='&search_company='.$search_company; - if ($search_user > 0) $param.='&search_user='.$search_user; - if ($search_request_author) $param.='&search_request_author='.$search_request_author; - if ($search_sale > 0) $param.='&search_sale='.$search_sale; - if ($search_total_ht != '') $param.='&search_total_ht='.$search_total_ht; - if ($search_total_ttc != '') $param.="&search_total_ttc=".$search_total_ttc; - if ($search_refsupp) $param.="&search_refsupp=".$search_refsupp; - if ($search_status >= 0) $param.="&search_status=".$search_status; - if ($search_project_ref >= 0) $param.="&search_project_ref=".$search_project_ref; - if ($search_billed != '') $param.="&search_billed=".$search_billed; - if ($show_files) $param.='&show_files=' .$show_files; - if ($optioncss != '') $param.='&optioncss='.$optioncss; + $param = ''; + if ($socid > 0) $param .= '&socid='.$socid; + if (!empty($contextpage) && $contextpage != $_SERVER["PHP_SELF"]) $param .= '&contextpage='.$contextpage; + if ($limit > 0 && $limit != $conf->liste_limit) $param .= '&limit='.$limit; + if ($sall) $param .= "&search_all=".$sall; + if ($search_orderday) $param .= '&search_orderday='.$search_orderday; + if ($search_ordermonth) $param .= '&search_ordermonth='.$search_ordermonth; + if ($search_orderyear) $param .= '&search_orderyear='.$search_orderyear; + if ($search_deliveryday) $param .= '&search_deliveryday='.$search_deliveryday; + if ($search_deliverymonth) $param .= '&search_deliverymonth='.$search_deliverymonth; + if ($search_deliveryyear) $param .= '&search_deliveryyear='.$search_deliveryyear; + if ($search_ref) $param .= '&search_ref='.$search_ref; + if ($search_company) $param .= '&search_company='.$search_company; + if ($search_user > 0) $param .= '&search_user='.$search_user; + if ($search_request_author) $param .= '&search_request_author='.$search_request_author; + if ($search_sale > 0) $param .= '&search_sale='.$search_sale; + if ($search_total_ht != '') $param .= '&search_total_ht='.$search_total_ht; + if ($search_total_ttc != '') $param .= "&search_total_ttc=".$search_total_ttc; + if ($search_refsupp) $param .= "&search_refsupp=".$search_refsupp; + if ($search_status >= 0) $param .= "&search_status=".$search_status; + if ($search_project_ref >= 0) $param .= "&search_project_ref=".$search_project_ref; + if ($search_billed != '') $param .= "&search_billed=".$search_billed; + if ($show_files) $param .= '&show_files='.$show_files; + if ($optioncss != '') $param .= '&optioncss='.$optioncss; // Add $param from extra fields include DOL_DOCUMENT_ROOT.'/core/tpl/extrafields_list_search_param.tpl.php'; // List of mass actions available - $arrayofmassactions = array( + $arrayofmassactions = array( 'generate_doc'=>$langs->trans("ReGeneratePDF"), 'builddoc'=>$langs->trans("PDFMerge"), 'presend'=>$langs->trans("SendByMail"), ); //if($user->rights->fournisseur->facture->creer) $arrayofmassactions['createbills']=$langs->trans("CreateInvoiceForThisCustomer"); - if ($user->rights->fournisseur->commande->supprimer) $arrayofmassactions['predelete']=''.$langs->trans("Delete"); - if (in_array($massaction, array('presend','predelete','createbills'))) $arrayofmassactions=array(); - $massactionbutton=$form->selectMassAction('', $arrayofmassactions); + if ($user->rights->fournisseur->commande->supprimer) $arrayofmassactions['predelete'] = ''.$langs->trans("Delete"); + if (in_array($massaction, array('presend', 'predelete', 'createbills'))) $arrayofmassactions = array(); + $massactionbutton = $form->selectMassAction('', $arrayofmassactions); - $newcardbutton=''; - if($user->rights->fournisseur->commande->creer) + $newcardbutton = ''; + if ($user->rights->fournisseur->commande->creer) { - $newcardbutton.= dolGetButtonTitle($langs->trans('NewOrder'), '', 'fa fa-plus-circle', DOL_URL_ROOT.'/fourn/commande/card.php?action=create'); + $newcardbutton .= dolGetButtonTitle($langs->trans('NewOrder'), '', 'fa fa-plus-circle', DOL_URL_ROOT.'/fourn/commande/card.php?action=create'); } // Fields title search @@ -651,10 +651,10 @@ if ($resql) print ''; print_barre_liste($title, $page, $_SERVER["PHP_SELF"], $param, $sortfield, $sortorder, $massactionbutton, $num, $nbtotalofrecords, 'commercial', 0, $newcardbutton, '', $limit); - $topicmail="SendOrderRef"; - $modelmail="order_supplier_send"; - $objecttmp=new CommandeFournisseur($db); - $trackid='sord'.$object->id; + $topicmail = "SendOrderRef"; + $modelmail = "order_supplier_send"; + $objecttmp = new CommandeFournisseur($db); + $trackid = 'sord'.$object->id; include DOL_DOCUMENT_ROOT.'/core/tpl/massactions_pre.tpl.php'; if ($massaction == 'createbills') @@ -699,144 +699,144 @@ if ($resql) if ($sall) { - foreach($fieldstosearchall as $key => $val) $fieldstosearchall[$key]=$langs->trans($val); - print '
    '.$langs->trans("FilterOnInto", $sall) . join(', ', $fieldstosearchall).'
    '; + foreach ($fieldstosearchall as $key => $val) $fieldstosearchall[$key] = $langs->trans($val); + print '
    '.$langs->trans("FilterOnInto", $sall).join(', ', $fieldstosearchall).'
    '; } - $moreforfilter=''; + $moreforfilter = ''; // If the user can view prospects other than his' 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.='
    '; + $moreforfilter .= '
    '; + $moreforfilter .= $langs->trans('ThirdPartiesOfSaleRepresentative').': '; + $moreforfilter .= $formother->select_salesrepresentatives($search_sale, 'search_sale', $user, 0, 1, 'maxwidth200'); + $moreforfilter .= '
    '; } // If the user can view other users 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 .= '
    '; + $moreforfilter .= $langs->trans('LinkedToSpecificUsers').': '; + $moreforfilter .= $form->select_dolusers($search_user, 'search_user', 1, '', 0, '', '', 0, 0, 0, '', 0, '', 'maxwidth200'); + $moreforfilter .= '
    '; } // If the user can view prospects other than his' 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'). ': '; + $moreforfilter .= '
    '; + $moreforfilter .= $langs->trans('IncludingProductWithTag').': '; $cate_arbo = $form->select_all_categories(Categorie::TYPE_PRODUCT, null, 'parent', null, null, 1); - $moreforfilter.=$form->selectarray('search_product_category', $cate_arbo, $search_product_category, 1, 0, 0, '', 0, 0, 0, 0, 'maxwidth300', 1); - $moreforfilter.='
    '; + $moreforfilter .= $form->selectarray('search_product_category', $cate_arbo, $search_product_category, 1, 0, 0, '', 0, 0, 0, 0, 'maxwidth300', 1); + $moreforfilter .= '
    '; } - $parameters=array(); - $reshook=$hookmanager->executeHooks('printFieldPreListTitle', $parameters); // Note that $action and $object may have been modified by hook + $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($moreforfilter)) + if (!empty($moreforfilter)) { print '
    '; print $moreforfilter; print '
    '; } - $varpage=empty($contextpage)?$_SERVER["PHP_SELF"]:$contextpage; - $selectedfields=$form->multiSelectArrayWithCheckbox('selectedfields', $arrayfields, $varpage); // This also change content of $arrayfields - if ($massactionbutton) $selectedfields.=$form->showCheckAddButtons('checkforselect', 1); + $varpage = empty($contextpage) ? $_SERVER["PHP_SELF"] : $contextpage; + $selectedfields = $form->multiSelectArrayWithCheckbox('selectedfields', $arrayfields, $varpage); // This also change content of $arrayfields + if ($massactionbutton) $selectedfields .= $form->showCheckAddButtons('checkforselect', 1); print '
    '; - print ''."\n"; + print '
    '."\n"; print ''; // Ref - if (! empty($arrayfields['cf.ref']['checked'])) + if (!empty($arrayfields['cf.ref']['checked'])) { print ''; } // Ref customer - if (! empty($arrayfields['cf.ref_supplier']['checked'])) + if (!empty($arrayfields['cf.ref_supplier']['checked'])) { print ''; } // Project ref - if (! empty($arrayfields['p.project_ref']['checked'])) + if (!empty($arrayfields['p.project_ref']['checked'])) { print ''; } // Request author - if (! empty($arrayfields['u.login']['checked'])) + if (!empty($arrayfields['u.login']['checked'])) { print ''; } // Thirpdarty - if (! empty($arrayfields['s.nom']['checked'])) + if (!empty($arrayfields['s.nom']['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 ''; } // Date order - if (! empty($arrayfields['cf.date_commande']['checked'])) + if (!empty($arrayfields['cf.date_commande']['checked'])) { print ''; } // Date delivery - if (! empty($arrayfields['cf.date_delivery']['checked'])) + if (!empty($arrayfields['cf.date_delivery']['checked'])) { print ''; } - if (! empty($arrayfields['cf.total_ht']['checked'])) + if (!empty($arrayfields['cf.total_ht']['checked'])) { // Amount print ''; } - if (! empty($arrayfields['cf.total_vat']['checked'])) + if (!empty($arrayfields['cf.total_vat']['checked'])) { // Amount print ''; } - if (! empty($arrayfields['cf.total_ttc']['checked'])) + if (!empty($arrayfields['cf.total_ttc']['checked'])) { // Amount print ''; } // Date modification - if (! empty($arrayfields['cf.tms']['checked'])) + if (!empty($arrayfields['cf.tms']['checked'])) { print ''; } // Status - if (! empty($arrayfields['cf.fk_statut']['checked'])) + if (!empty($arrayfields['cf.fk_statut']['checked'])) { print ''; } // Status billed - if (! empty($arrayfields['cf.billed']['checked'])) + if (!empty($arrayfields['cf.billed']['checked'])) { print ''; print "\n"; print ''; - 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); - 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_delivery']['checked'])) print_liste_field_titre($arrayfields['cf.date_delivery']['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_vat']['checked'])) print_liste_field_titre($arrayfields['cf.total_vat']['label'], $_SERVER["PHP_SELF"], "cf.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.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); + 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_delivery']['checked'])) print_liste_field_titre($arrayfields['cf.date_delivery']['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_vat']['checked'])) print_liste_field_titre($arrayfields['cf.total_vat']['label'], $_SERVER["PHP_SELF"], "cf.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 '); // 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 + $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 "\n"; - $total=0; - $subtotal=0; - $productstat_cache=array(); + $total = 0; + $subtotal = 0; + $productstat_cache = array(); $userstatic = new User($db); - $objectstatic=new CommandeFournisseur($db); - $projectstatic=new Project($db); + $objectstatic = new CommandeFournisseur($db); + $projectstatic = new Project($db); - $i=0; - $totalarray=array(); + $i = 0; + $totalarray = array(); while ($i < min($num, $limit)) { $obj = $db->fetch_object($resql); - $objectstatic->id=$obj->rowid; - $objectstatic->ref=$obj->ref; + $objectstatic->id = $obj->rowid; + $objectstatic->ref = $obj->ref; $objectstatic->ref_supplier = $obj->ref_supplier; $objectstatic->total_ht = $obj->total_ht; $objectstatic->total_tva = $obj->total_tva; @@ -941,36 +941,36 @@ if ($resql) print ''; // Ref - if (! empty($arrayfields['cf.ref']['checked'])) + if (!empty($arrayfields['cf.ref']['checked'])) { print ''."\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 ''."\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; + $projectstatic->id = $obj->project_id; + $projectstatic->ref = $obj->project_ref; + $projectstatic->title = $obj->project_title; print ''; - if (! $i) $totalarray['nbfield']++; + if (!$i) $totalarray['nbfield']++; } // Author $userstatic->id = $obj->fk_user_author; @@ -979,15 +979,15 @@ 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 '"; - if (! $i) $totalarray['nbfield']++; + if (!$i) $totalarray['nbfield']++; } // Thirdparty - if (! empty($arrayfields['s.nom']['checked'])) + if (!empty($arrayfields['s.nom']['checked'])) { 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, 0, 0, 0, '', 0, 0, 0, (empty($conf->global->SOCIETE_SORT_ON_TYPEENT)?'ASC':$conf->global->SOCIETE_SORT_ON_TYPEENT)); + print $form->selectarray("search_type_thirdparty", $formcompany->typent_array(0), $search_type_thirdparty, 0, 0, 0, '', 0, 0, 0, (empty($conf->global->SOCIETE_SORT_ON_TYPEENT) ? 'ASC' : $conf->global->SOCIETE_SORT_ON_TYPEENT)); 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_orderyear?$search_orderyear:-1, 'search_orderyear', 1, 20, 5); + $formother->select_year($search_orderyear ? $search_orderyear : -1, 'search_orderyear', 1, 20, 5); 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_deliveryyear?$search_deliveryyear:-1, 'search_deliveryyear', 1, 20, 5); + $formother->select_year($search_deliveryyear ? $search_deliveryyear : -1, 'search_deliveryyear', 1, 20, 5); print ''; print ''; print ''; print ''; print ''; @@ -847,30 +847,30 @@ if ($resql) include DOL_DOCUMENT_ROOT.'/core/tpl/extrafields_list_search_input.tpl.php'; // Fields from hook - $parameters=array('arrayfields'=>$arrayfields); - $reshook=$hookmanager->executeHooks('printFieldListOption', $parameters); // Note that $action and $object may have been modified by hook + $parameters = array('arrayfields'=>$arrayfields); + $reshook = $hookmanager->executeHooks('printFieldListOption', $parameters); // Note that $action and $object may have been modified by hook print $hookmanager->resPrint; // Date creation - if (! empty($arrayfields['cf.datec']['checked'])) + if (!empty($arrayfields['cf.datec']['checked'])) { print ''; print ''; print ''; - $formorder->selectSupplierOrderStatus((strstr($search_status, ',')?-1:$search_status), 1, 'search_status'); + $formorder->selectSupplierOrderStatus((strstr($search_status, ',') ?-1 : $search_status), 1, 'search_status'); print ''; print $form->selectyesno('search_billed', $search_billed, 1, 0, 1); @@ -878,59 +878,59 @@ if ($resql) } // Action column print ''; - $searchpicto=$form->showFilterButtons(); + $searchpicto = $form->showFilterButtons(); print $searchpicto; print '
    '; // Picto + Ref print $objectstatic->getNomUrl(1); // Other picto tool - $filename=dol_sanitizeFileName($obj->ref); - $filedir=$conf->fournisseur->commande->dir_output.'/' . dol_sanitizeFileName($obj->ref); + $filename = dol_sanitizeFileName($obj->ref); + $filedir = $conf->fournisseur->commande->dir_output.'/'.dol_sanitizeFileName($obj->ref); print $formfile->getDocumentsLink($objectstatic->element, $filename, $filedir); print ''.$obj->ref_supplier.''; if ($obj->project_id > 0) print $projectstatic->getNomUrl(1); print ''; if ($userstatic->id) print $userstatic->getNomUrl(1); print "'; $thirdpartytmp->id = $obj->socid; @@ -1137,8 +1137,8 @@ if ($resql) include DOL_DOCUMENT_ROOT.'/core/tpl/list_print_total.tpl.php'; - $parameters=array('arrayfields'=>$arrayfields, 'sql'=>$sql); - $reshook=$hookmanager->executeHooks('printFieldListFooter', $parameters); // Note that $action and $object may have been modified by hook + $parameters = array('arrayfields'=>$arrayfields, 'sql'=>$sql); + $reshook = $hookmanager->executeHooks('printFieldListFooter', $parameters); // Note that $action and $object may have been modified by hook print $hookmanager->resPrint; print "
    \n"; @@ -1147,16 +1147,16 @@ if ($resql) $db->free($resql); - $hidegeneratedfilelistifempty=1; - if ($massaction == 'builddoc' || $action == 'remove_file' || $show_files) $hidegeneratedfilelistifempty=0; + $hidegeneratedfilelistifempty = 1; + if ($massaction == 'builddoc' || $action == 'remove_file' || $show_files) $hidegeneratedfilelistifempty = 0; // Show list of available documents - $urlsource=$_SERVER['PHP_SELF'].'?sortfield='.$sortfield.'&sortorder='.$sortorder; - $urlsource.=str_replace('&', '&', $param); + $urlsource = $_SERVER['PHP_SELF'].'?sortfield='.$sortfield.'&sortorder='.$sortorder; + $urlsource .= str_replace('&', '&', $param); - $filedir=$diroutputmassaction; - $genallowed=$user->rights->fournisseur->commande->lire; - $delallowed=$user->rights->fournisseur->commande->creer; + $filedir = $diroutputmassaction; + $genallowed = $user->rights->fournisseur->commande->lire; + $delallowed = $user->rights->fournisseur->commande->creer; print $formfile->showdocuments('massfilesarea_supplier_order', '', $filedir, $urlsource, 0, $delallowed, '', 1, 1, 0, 48, 1, $param, $title, '', '', '', null, $hidegeneratedfilelistifempty); } diff --git a/htdocs/fourn/commande/note.php b/htdocs/fourn/commande/note.php index 63629af25bb..a6697aeb098 100644 --- a/htdocs/fourn/commande/note.php +++ b/htdocs/fourn/commande/note.php @@ -70,9 +70,9 @@ $form = new Form($db); /* */ /* *************************************************************************** */ -$now=dol_now(); +$now = dol_now(); -if ($id > 0 || ! empty($ref)) +if ($id > 0 || !empty($ref)) { if ($result >= 0) { @@ -139,7 +139,7 @@ if ($id > 0 || ! empty($ref)) print '
    '; - $cssclass="titlefield"; + $cssclass = "titlefield"; include DOL_DOCUMENT_ROOT.'/core/tpl/notes.tpl.php'; print '
    '; diff --git a/htdocs/fourn/commande/orderstoinvoice.php b/htdocs/fourn/commande/orderstoinvoice.php index 7005d3029f4..098b6b93710 100644 --- a/htdocs/fourn/commande/orderstoinvoice.php +++ b/htdocs/fourn/commande/orderstoinvoice.php @@ -30,21 +30,21 @@ * \brief Page to invoice multiple supplier orders */ require '../../main.inc.php'; -require_once DOL_DOCUMENT_ROOT . '/fourn/class/fournisseur.facture.class.php'; -require_once DOL_DOCUMENT_ROOT . '/fourn/class/fournisseur.commande.class.php'; -require_once DOL_DOCUMENT_ROOT . '/core/class/html.formfile.class.php'; -require_once DOL_DOCUMENT_ROOT . '/core/class/html.formother.class.php'; -require_once DOL_DOCUMENT_ROOT . '/core/lib/date.lib.php'; -require_once DOL_DOCUMENT_ROOT . '/core/lib/report.lib.php'; -require_once DOL_DOCUMENT_ROOT . '/core/modules/supplier_invoice/modules_facturefournisseur.php'; -if (! empty($conf->projet->enabled)) { - require_once DOL_DOCUMENT_ROOT . '/core/class/html.formprojet.class.php'; +require_once DOL_DOCUMENT_ROOT.'/fourn/class/fournisseur.facture.class.php'; +require_once DOL_DOCUMENT_ROOT.'/fourn/class/fournisseur.commande.class.php'; +require_once DOL_DOCUMENT_ROOT.'/core/class/html.formfile.class.php'; +require_once DOL_DOCUMENT_ROOT.'/core/class/html.formother.class.php'; +require_once DOL_DOCUMENT_ROOT.'/core/lib/date.lib.php'; +require_once DOL_DOCUMENT_ROOT.'/core/lib/report.lib.php'; +require_once DOL_DOCUMENT_ROOT.'/core/modules/supplier_invoice/modules_facturefournisseur.php'; +if (!empty($conf->projet->enabled)) { + require_once DOL_DOCUMENT_ROOT.'/core/class/html.formprojet.class.php'; } // Load translation files required by the page $langs->loadLangs(array("orders", "companies", "deliveries")); -if (! $user->rights->fournisseur->facture->creer) +if (!$user->rights->fournisseur->facture->creer) accessforbidden(); $id = (GETPOST('id') ? GETPOST('id', 'int') : GETPOST("facid")); // For backward compatibility @@ -53,16 +53,16 @@ $action = GETPOST('action', 'alpha'); $confirm = GETPOST('confirm', 'alpha'); $sref = GETPOST('sref'); $sref_client = GETPOST('sref_client'); -$sall = trim((GETPOST('search_all', 'alphanohtml')!='')?GETPOST('search_all', 'alphanohtml'):GETPOST('sall', 'alphanohtml')); +$sall = trim((GETPOST('search_all', 'alphanohtml') != '') ?GETPOST('search_all', 'alphanohtml') : GETPOST('sall', 'alphanohtml')); $socid = GETPOST('socid', 'int'); $selected = GETPOST('orders_to_invoice'); $sortfield = GETPOST("sortfield", 'alpha'); $sortorder = GETPOST("sortorder", 'alpha'); $viewstatut = GETPOST('viewstatut'); -if (! $sortfield) +if (!$sortfield) $sortfield = 'c.rowid'; -if (! $sortorder) +if (!$sortorder) $sortorder = 'DESC'; $now = dol_now(); @@ -80,13 +80,13 @@ $extrafields->fetch_name_optionals_label($object->table_element); if ($action == 'create') { - if (! GETPOST('createbill')) + if (!GETPOST('createbill')) { $action = ''; } else { - if (! is_array($selected)) + if (!is_array($selected)) { //$error++; setEventMessages($langs->trans('Error_OrderNotChecked'), null, 'errors'); @@ -99,7 +99,7 @@ if ($action == 'create') } // Initialize technical object to manage hooks of page. Note that conf->hooks_modules contains array of hook context -include_once DOL_DOCUMENT_ROOT . '/core/class/hookmanager.class.php'; +include_once DOL_DOCUMENT_ROOT.'/core/class/hookmanager.class.php'; $hookmanager = new HookManager($db); $hookmanager->initHooks(array('orderstoinvoicesupplier')); @@ -108,10 +108,10 @@ $hookmanager->initHooks(array('orderstoinvoicesupplier')); * Actions */ -if (($action == 'create' || $action == 'add') && ! $error) { - require_once DOL_DOCUMENT_ROOT . '/core/lib/fourn.lib.php'; - if (! empty($conf->projet->enabled)) - require_once DOL_DOCUMENT_ROOT . '/projet/class/project.class.php'; +if (($action == 'create' || $action == 'add') && !$error) { + require_once DOL_DOCUMENT_ROOT.'/core/lib/fourn.lib.php'; + 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", "main", "products")); @@ -157,7 +157,7 @@ if (($action == 'create' || $action == 'add') && ! $error) { if (empty($datefacture)) { $datefacture = dol_mktime(date("h"), date("M"), 0, date("m"), date("d"), date("Y")); } - if (! $error) { + if (!$error) { $object->ref = GETPOST('ref', 'nohtml'); $object->ref_supplier = GETPOST('ref_supplier', 'alpha'); $object->socid = GETPOST('socid', 'int'); @@ -181,18 +181,18 @@ if (($action == 'create' || $action == 'add') && ! $error) { if ($ret < 0) $error++; if ($_POST['origin'] && $_POST['originid']) { - $linked_orders_ids=array(); + $linked_orders_ids = array(); foreach ($orders_id as $origin => $origin_id) { - $origin_id = (! empty($origin_id) ? $origin_id : $orders_id[$ii]); - $linked_orders_ids[]=$origin_id; + $origin_id = (!empty($origin_id) ? $origin_id : $orders_id[$ii]); + $linked_orders_ids[] = $origin_id; } $object->linked_objects = array(GETPOST('origin')=>$linked_orders_ids); $id = $object->create($user); if ($id > 0) { - while ( $ii < $nn ) { + while ($ii < $nn) { $objectsrc = new CommandeFournisseur($db); - dol_syslog("Try to find source object origin=" . $object->origin . " originid=" . $object->origin_id . " to add lines"); + dol_syslog("Try to find source object origin=".$object->origin." originid=".$object->origin_id." to add lines"); $result = $objectsrc->fetch($orders_id[$ii]); if ($result > 0) { $lines = $objectsrc->lines; @@ -202,7 +202,7 @@ if (($action == 'create' || $action == 'add') && ! $error) { } $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); $desc = ($lines[$i]->desc ? $lines[$i]->desc : $lines[$i]->libelle); @@ -232,7 +232,7 @@ if (($action == 'create' || $action == 'add') && ! $error) { $lineid = $result; } else { $lineid = 0; - $error ++; + $error++; break; } // Defined the new fk_parent_line @@ -242,22 +242,22 @@ if (($action == 'create' || $action == 'add') && ! $error) { } } else { $mesgs[] = $objectsrc->error; - $error ++; + $error++; } - $ii ++; + $ii++; } } else { $mesgs[] = $object->error; - $error ++; + $error++; } } } // End of object creation, we show it - if ($id > 0 && ! $error) { - foreach($orders_id as $fk_supplier_order) { + if ($id > 0 && !$error) { + foreach ($orders_id as $fk_supplier_order) { $supplier_order = new CommandeFournisseur($db); - if ($supplier_order->fetch($fk_supplier_order)>0 && $supplier_order->statut == 5) + if ($supplier_order->fetch($fk_supplier_order) > 0 && $supplier_order->statut == 5) { if ($supplier_order->classifyBilled($user) < 0) { @@ -265,7 +265,7 @@ if (($action == 'create' || $action == 'add') && ! $error) { $action = 'create'; $_GET["origin"] = $_POST["origin"]; $_GET["originid"] = $_POST["originid"]; - $mesgs[] = '
    ' . $object->error . '
    '; + $mesgs[] = '
    '.$object->error.'
    '; $error++; break; @@ -273,9 +273,9 @@ if (($action == 'create' || $action == 'add') && ! $error) { } } - if(!$error) { + if (!$error) { $db->commit(); - header('Location: ' . DOL_URL_ROOT . '/fourn/facture/card.php?facid=' . $id); + header('Location: '.DOL_URL_ROOT.'/fourn/facture/card.php?facid='.$id); exit(); } } else { @@ -283,7 +283,7 @@ if (($action == 'create' || $action == 'add') && ! $error) { $action = 'create'; $_GET["origin"] = $_POST["origin"]; $_GET["originid"] = $_POST["originid"]; - $mesgs[] = '
    ' . $object->error . '
    '; + $mesgs[] = '
    '.$object->error.'
    '; } } } @@ -308,7 +308,7 @@ if ($action == 'create' && !$error) { $cond_reglement_id = $soc->cond_reglement_supplier_id; $mode_reglement_id = $soc->mode_reglement_supplier_id; } - $dateinvoice = empty($conf->global->MAIN_AUTOFILL_DATE) ? - 1 : ''; + $dateinvoice = empty($conf->global->MAIN_AUTOFILL_DATE) ? -1 : ''; $objectsrc = new CommandeFournisseur($db); $listoforders = array(); @@ -322,66 +322,64 @@ if ($action == 'create' && !$error) { if (empty($mode_reglement_id)) $mode_reglement_id = $objectsrc->mode_reglement_id; } - print '
    '; - print ''; + print ''; + print ''; print ''; - print '' . "\n"; + print ''."\n"; print ''; - print ''; - print ''; - print ''; - print ''; - print ''; + print ''; + print ''; + print ''; + print ''; + print ''; - print ''; + print '
    '; // Ref - print ''; + print ''; // Ref supplier - print ''; + print ''; print ''; // Date invoice - print ''; // Payment term - print ''; // Payment mode - print ''; // Project - if (! empty($conf->projet->enabled)) { + if (!empty($conf->projet->enabled)) { $formproject = new FormProjets($db); $langs->load('projects'); - print ''; } // Other attributes - $parameters = array ( + $parameters = array( 'objectsrc' => $objectsrc, - 'idsrc' => $listoforders, - 'colspan' => ' colspan="2"', - 'cols'=>2 + 'idsrc' => $listoforders ); $reshook = $hookmanager->executeHooks('formObjectOptions', $parameters, $object, $action); // Note that $action and $object may have been modified by hook print $hookmanager->resPrint; if (empty($reshook)) { - $object=new FactureFournisseur($db); + $object = new FactureFournisseur($db); print $object->showOptionals($extrafields, 'edit'); } // Modele PDF - print ''; + print ''; print ''; - print ''; - print ''; // Private note if (empty($user->socid)) { print ''; - print ''; - print ''; } @@ -410,13 +408,13 @@ if ($action == 'create' && !$error) { print '
    ' . $langs->trans('Ref') . '' . $langs->trans('Draft') . '
    '.$langs->trans('Ref').''.$langs->trans('Draft').'
    ' . $langs->trans('RefSupplier') . '
    '.$langs->trans('RefSupplier').'
    ' . $langs->trans('Date') . ''; + print '
    '.$langs->trans('Date').''; print $html->selectDate('', '', '', '', '', "add", 1, 1); print '
    ' . $langs->trans('PaymentConditionsShort') . ''; + print '
    '.$langs->trans('PaymentConditionsShort').''; $html->select_conditions_paiements(isset($_POST['cond_reglement_id']) ? $_POST['cond_reglement_id'] : $cond_reglement_id, 'cond_reglement_id'); print '
    ' . $langs->trans('PaymentMode') . ''; + print '
    '.$langs->trans('PaymentMode').''; $html->select_types_paiements(isset($_POST['mode_reglement_id']) ? $_POST['mode_reglement_id'] : $mode_reglement_id, 'mode_reglement_id'); print '
    ' . $langs->trans('Project') . ''; + print '
    '.$langs->trans('Project').''; $formproject->select_projects($soc->id, $projectid, 'projectid'); print '
    ' . $langs->trans('Model') . '
    '.$langs->trans('Model').''; $liste = ModelePDFSuppliersInvoices::liste_modeles($db); print $html->selectarray('model', $liste, $conf->global->INVOICE_SUPPLIER_ADDON_PDF); @@ -389,20 +387,20 @@ if ($action == 'create' && !$error) { // Public note print '
    ' . $langs->trans('NotePublic') . ''; - print '
    ' . $langs->trans('NotePrivate') . ''; - print '
    '; while ($i < $n) { - print ''; + print ''; $i++; } // Button "Create Draft" - print '
    '; + print '
    '; print "
    \n"; print '
    '; + print '
    '; print ''; - print_liste_field_titre('Ref', 'orderstoinvoice.php', 'c.ref', '', '&socid=' . $socid, '', $sortfield, $sortorder); - print_liste_field_titre('RefSupplier', 'orderstoinvoice.php', 'c.ref_supplier', '', '&socid=' . $socid, '', $sortfield, $sortorder); - print_liste_field_titre('OrderDate', 'orderstoinvoice.php', 'c.date_commande', '', '&socid=' . $socid, '', $sortfield, $sortorder, 'center '); - print_liste_field_titre('DeliveryDate', 'orderstoinvoice.php', 'c.date_livraison', '', '&socid=' . $socid, '', $sortfield, $sortorder, 'center '); + print_liste_field_titre('Ref', 'orderstoinvoice.php', 'c.ref', '', '&socid='.$socid, '', $sortfield, $sortorder); + print_liste_field_titre('RefSupplier', 'orderstoinvoice.php', 'c.ref_supplier', '', '&socid='.$socid, '', $sortfield, $sortorder); + print_liste_field_titre('OrderDate', 'orderstoinvoice.php', 'c.date_commande', '', '&socid='.$socid, '', $sortfield, $sortorder, 'center '); + print_liste_field_titre('DeliveryDate', 'orderstoinvoice.php', 'c.date_livraison', '', '&socid='.$socid, '', $sortfield, $sortorder, 'center '); print_liste_field_titre('Status', '', '', '', '', '', '', '', 'right '); print_liste_field_titre('GenerateBill', '', '', '', '', '', '', '', 'center '); print "\n"; @@ -532,12 +530,12 @@ if (($action != 'create' && $action != 'add') && !$error) { print ''; // print ''; // DATE ORDER @@ -552,13 +550,13 @@ if (($action != 'create' && $action != 'add') && !$error) { // SEARCH BUTTON print ''; // ALL/NONE print ''; print ''; @@ -581,13 +579,13 @@ if (($action != 'create' && $action != 'add') && !$error) { print '
    '; // REF - print ''; + print ''; print ''; print ''; - print ''; + print ''; print ''; - print ''; + print ''; print ''; if ($conf->use_javascript_ajax) - print '' . $langs->trans("All") . ' / ' . $langs->trans("None") . ''; + print ''.$langs->trans("All").' / '.$langs->trans("None").''; print '
    '; $filename = dol_sanitizeFileName($objp->ref); - $filedir = $conf->fournisseur->commande->dir_output . '/' . dol_sanitizeFileName($objp->ref); - $urlsource = $_SERVER['PHP_SELF'] . '?id=' . $objp->rowid; + $filedir = $conf->fournisseur->commande->dir_output.'/'.dol_sanitizeFileName($objp->ref); + $urlsource = $_SERVER['PHP_SELF'].'?id='.$objp->rowid; print $formfile->getDocumentsLink($generic_commande->element, $filename, $filedir); print '
    '; print '
    ' . $objp->ref_supplier . ''.$objp->ref_supplier.''; @@ -600,18 +598,18 @@ if (($action != 'create' && $action != 'add') && !$error) { print '' . $generic_commande->LibStatut($objp->fk_statut, 5) . ''.$generic_commande->LibStatut($objp->fk_statut, 5).''; - print ''; + print ''; print '
    '; @@ -620,11 +618,11 @@ if (($action != 'create' && $action != 'add') && !$error) { */ print '
    '; print '
    '; - print ''; + print ''; print ''; print '
    '; // print ''.$langs->trans("GoBack").''; - print ''; + print ''; print '
    '; print '
    '; diff --git a/htdocs/fourn/contact.php b/htdocs/fourn/contact.php index 649c24408a1..35d21ab04f3 100644 --- a/htdocs/fourn/contact.php +++ b/htdocs/fourn/contact.php @@ -48,9 +48,9 @@ if (empty($page) || $page == -1) { $page = 0; } // If $page is not defined, $offset = $conf->liste_limit * $page; $pageprev = $page - 1; $pagenext = $page + 1; -if (! $sortorder) $sortorder="ASC"; -if (! $sortfield) $sortfield="p.name"; -$limit = GETPOST('limit', 'int')?GETPOST('limit', 'int'):$conf->liste_limit; +if (!$sortorder) $sortorder = "ASC"; +if (!$sortfield) $sortfield = "p.name"; +$limit = GETPOST('limit', 'int') ?GETPOST('limit', 'int') : $conf->liste_limit; /* @@ -58,14 +58,14 @@ $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 "; -$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"; -$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 .= ", 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"; +$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 (dol_strlen($stcomm)) { $sql .= " AND s.fk_stcomm=$stcomm"; @@ -93,10 +93,10 @@ if ($result) { $num = $db->num_rows($result); - $title = (! empty($conf->global->SOCIETE_ADDRESSES_MANAGEMENT) ? $langs->trans("ListOfContacts") : $langs->trans("ListOfContactsAddresses")); + $title = (!empty($conf->global->SOCIETE_ADDRESSES_MANAGEMENT) ? $langs->trans("ListOfContacts") : $langs->trans("ListOfContactsAddresses")); print_barre_liste($title." (".$langs->trans("Suppliers").")", $page, $_SERVER["PHP_SELF"], "", $sortfield, $sortorder, "", $num); - print ''; + print '
    '; print ''; print_liste_field_titre("Lastname", $_SERVER["PHP_SELF"], "p.name", $begin, "", "", $sortfield, $sortorder); print_liste_field_titre("Firstname", $_SERVER["PHP_SELF"], "p.firstname", $begin, "", "", $sortfield, $sortorder); diff --git a/htdocs/fourn/facture/card.php b/htdocs/fourn/facture/card.php index 6935e978c67..6a5e29892d2 100644 --- a/htdocs/fourn/facture/card.php +++ b/htdocs/fourn/facture/card.php @@ -53,82 +53,82 @@ 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')); +$langs->loadLangs(array('bills', 'compta', 'suppliers', 'companies', 'products', 'banks')); if (!empty($conf->incoterm->enabled)) $langs->load('incoterm'); -$id = (GETPOST('facid', 'int') ? GETPOST('facid', 'int') : GETPOST('id', 'int')); -$socid = GETPOST('socid', 'int'); +$id = (GETPOST('facid', 'int') ? GETPOST('facid', 'int') : GETPOST('id', 'int')); +$socid = GETPOST('socid', 'int'); $action = GETPOST('action', 'aZ09'); $confirm = GETPOST("confirm"); -$ref = GETPOST('ref', 'alpha'); +$ref = GETPOST('ref', 'alpha'); $cancel = GETPOST('cancel', 'alpha'); $lineid = GETPOST('lineid', 'int'); -$projectid = GETPOST('projectid', 'int'); +$projectid = GETPOST('projectid', 'int'); $origin = GETPOST('origin', 'alpha'); -$originid = GETPOST('originid', 'int'); +$originid = GETPOST('originid', 'int'); // PDF -$hidedetails = (GETPOST('hidedetails', 'int') ? GETPOST('hidedetails', 'int') : (! empty($conf->global->MAIN_GENERATE_DOCUMENTS_HIDE_DETAILS) ? 1 : 0)); -$hidedesc = (GETPOST('hidedesc', 'int') ? GETPOST('hidedesc', 'int') : (! empty($conf->global->MAIN_GENERATE_DOCUMENTS_HIDE_DESC) ? 1 : 0)); -$hideref = (GETPOST('hideref', 'int') ? GETPOST('hideref', 'int') : (! empty($conf->global->MAIN_GENERATE_DOCUMENTS_HIDE_REF) ? 1 : 0)); +$hidedetails = (GETPOST('hidedetails', 'int') ? GETPOST('hidedetails', 'int') : (!empty($conf->global->MAIN_GENERATE_DOCUMENTS_HIDE_DETAILS) ? 1 : 0)); +$hidedesc = (GETPOST('hidedesc', 'int') ? GETPOST('hidedesc', 'int') : (!empty($conf->global->MAIN_GENERATE_DOCUMENTS_HIDE_DESC) ? 1 : 0)); +$hideref = (GETPOST('hideref', 'int') ? GETPOST('hideref', 'int') : (!empty($conf->global->MAIN_GENERATE_DOCUMENTS_HIDE_REF) ? 1 : 0)); // Initialize technical object to manage hooks of page. Note that conf->hooks_modules contains array of hook context -$hookmanager->initHooks(array('invoicesuppliercard','globalcard')); +$hookmanager->initHooks(array('invoicesuppliercard', 'globalcard')); -$object=new FactureFournisseur($db); +$object = new FactureFournisseur($db); $extrafields = new ExtraFields($db); // fetch optionals attributes and labels $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); + $ret = $object->fetch($id, $ref); if ($ret < 0) dol_print_error($db, $object->error); - $ret=$object->fetch_thirdparty(); + $ret = $object->fetch_thirdparty(); if ($ret < 0) dol_print_error($db, $object->error); } // Security check -$socid=''; -if (! empty($user->socid)) $socid=$user->socid; +$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); -$permissionnote=$user->rights->fournisseur->facture->creer; // Used by the include of actions_setnotes.inc.php -$permissiondellink=$user->rights->fournisseur->facture->creer; // Used by the include of actions_dellink.inc.php -$permissiontoadd=$user->rights->fournisseur->facture->creer; // Used by the include of actions_addupdatedelete.inc.php and actions_lineupdown.inc.php +$permissionnote = $user->rights->fournisseur->facture->creer; // Used by the include of actions_setnotes.inc.php +$permissiondellink = $user->rights->fournisseur->facture->creer; // Used by the include of actions_dellink.inc.php +$permissiontoadd = $user->rights->fournisseur->facture->creer; // Used by the include of actions_addupdatedelete.inc.php and actions_lineupdown.inc.php /* * Actions */ -$parameters=array('socid'=>$socid); -$reshook=$hookmanager->executeHooks('doActions', $parameters, $object, $action); // Note that $action and $object may have been modified by some hooks +$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 ($cancel) { - if (! empty($backtopage)) + if (!empty($backtopage)) { header("Location: ".$backtopage); exit; } - $action=''; + $action = ''; } - include DOL_DOCUMENT_ROOT.'/core/actions_setnotes.inc.php'; // Must be include, not include_once + include DOL_DOCUMENT_ROOT.'/core/actions_setnotes.inc.php'; // Must be include, not include_once - include DOL_DOCUMENT_ROOT.'/core/actions_dellink.inc.php'; // Must be include, not include_once + include DOL_DOCUMENT_ROOT.'/core/actions_dellink.inc.php'; // Must be include, not include_once - include DOL_DOCUMENT_ROOT.'/core/actions_lineupdown.inc.php'; // Must be include, not include_once + 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) @@ -141,12 +141,12 @@ if (empty($reshook)) // Action clone object if ($action == 'confirm_clone' && $confirm == 'yes' && $permissiontoadd) { - $objectutil = dol_clone($object, 1); // To avoid to denaturate loaded object when setting some properties for clone. We use native clone to keep this->db valid. + $objectutil = dol_clone($object, 1); // To avoid to denaturate loaded object when setting some properties for clone. We use native clone to keep this->db valid. if (GETPOST('newsupplierref', 'alphanohtml')) $objectutil->ref_supplier = GETPOST('newsupplierref', 'alphanohtml'); $objectutil->date = dol_mktime(12, 0, 0, GETPOST('newdatemonth', 'int'), GETPOST('newdateday', 'int'), GETPOST('newdateyear', 'int')); - $result=$objectutil->createFromClone($user, $id); + $result = $objectutil->createFromClone($user, $id); if ($result > 0) { header("Location: ".$_SERVER['PHP_SELF'].'?id='.$result); @@ -156,49 +156,49 @@ if (empty($reshook)) { $langs->load("errors"); setEventMessages($objectutil->error, $objectutil->errors, 'errors'); - $action=''; + $action = ''; } } elseif ($action == 'confirm_valid' && $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))) + ((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))) ) { - $idwarehouse=GETPOST('idwarehouse'); + $idwarehouse = GETPOST('idwarehouse'); $object->fetch($id); $object->fetch_thirdparty(); - $qualified_for_stock_change=0; + $qualified_for_stock_change = 0; if (empty($conf->global->STOCK_SUPPORTS_SERVICES)) { - $qualified_for_stock_change=$object->hasProductsOrServices(2); + $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_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=''; + $action = ''; } } - if (! $error) + if (!$error) { $result = $object->validate($user, '', $idwarehouse); if ($result < 0) { setEventMessages($object->error, $object->errors, 'errors'); - }else{ + } else { // Define output language if (empty($conf->global->MAIN_DISABLE_PDF_AUTOUPDATE)) { @@ -206,14 +206,14 @@ if (empty($reshook)) $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 (!empty($newlang)) { $outputlangs = new Translate("", $conf); $outputlangs->setDefaultLang($newlang); } - $model=$object->modelpdf; + $model = $object->modelpdf; $ret = $object->fetch($id); // Reload to get new records - $result=$object->generateDocument($model, $outputlangs, $hidedetails, $hidedesc, $hideref); + $result = $object->generateDocument($model, $outputlangs, $hidedetails, $hidedesc, $hideref); if ($result < 0) dol_print_error($db, $result); } } @@ -225,12 +225,12 @@ if (empty($reshook)) $object->fetch($id); $object->fetch_thirdparty(); - $isErasable=$object->is_erasable(); + $isErasable = $object->is_erasable(); if (($user->rights->fournisseur->facture->supprimer && $isErasable > 0) || ($user->rights->fournisseur->facture->creer && $isErasable == 1)) { - $result=$object->delete($user); + $result = $object->delete($user); if ($result > 0) { header('Location: list.php?restore_lastsearch_values=1'); @@ -272,7 +272,7 @@ if (empty($reshook)) { setEventMessages($object->error, $object->errors, 'errors'); /* Fix bug 1485 : Reset action to avoid asking again confirmation on failure */ - $action=''; + $action = ''; } } @@ -287,8 +287,8 @@ if (empty($reshook)) elseif ($action == 'confirm_paid' && $confirm == 'yes' && $user->rights->fournisseur->facture->creer) { $object->fetch($id); - $result=$object->set_paid($user); - if ($result<0) + $result = $object->set_paid($user); + if ($result < 0) { setEventMessages($object->error, $object->errors, 'errors'); } @@ -313,7 +313,7 @@ if (empty($reshook)) 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); } @@ -327,7 +327,7 @@ if (empty($reshook)) // payments conditions if ($action == 'setconditions' && $user->rights->fournisseur->facture->creer) { - $result=$object->setPaymentTerms(GETPOST('cond_reglement_id', 'int')); + $result = $object->setPaymentTerms(GETPOST('cond_reglement_id', 'int')); } // Set incoterm @@ -354,21 +354,21 @@ if (empty($reshook)) // bank account elseif ($action == 'setbankaccount' && $user->rights->fournisseur->facture->creer) { - $result=$object->setBankAccount(GETPOST('fk_account', 'int')); + $result = $object->setBankAccount(GETPOST('fk_account', 'int')); } // Set label elseif ($action == 'setlabel' && $user->rights->fournisseur->facture->creer) { $object->fetch($id); - $object->label=GETPOST('label'); - $result=$object->update($user); + $object->label = GETPOST('label'); + $result = $object->update($user); if ($result < 0) dol_print_error($db); } elseif ($action == 'setdatef' && $user->rights->fournisseur->facture->creer) { - $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))) + $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'); @@ -376,30 +376,30 @@ if (empty($reshook)) $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) + $object->date = $newdate; + $date_echence_calc = $object->calculate_date_lim_reglement(); + 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) { - $object->date_echeance=$object->date; + $object->date_echeance = $object->date; } - $result=$object->update($user); + $result = $object->update($user); if ($result < 0) dol_print_error($db, $object->error); } elseif ($action == 'setdate_lim_reglement' && $user->rights->fournisseur->facture->creer) { $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) + $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) { - $object->date_echeance=$object->date; + $object->date_echeance = $object->date; setEventMessages($langs->trans("DatePaymentTermCantBeLowerThanObjectDate"), null, 'warnings'); } - $result=$object->update($user); + $result = $object->update($user); if ($result < 0) dol_print_error($db, $object->error); } elseif ($action == "setabsolutediscount" && $user->rights->fournisseur->facture->creer) @@ -407,7 +407,7 @@ if (empty($reshook)) // POST[remise_id] or POST[remise_id_for_payment] // We use the credit to reduce amount of invoice - if (! empty($_POST["remise_id"])) { + if (!empty($_POST["remise_id"])) { $ret = $object->fetch($id); if ($ret > 0) { $result = $object->insert_discount($_POST["remise_id"]); @@ -419,9 +419,9 @@ 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'; + require_once DOL_DOCUMENT_ROOT.'/core/class/discount.class.php'; $discount = new DiscountAbsolute($db); $discount->fetch($_POST["remise_id_for_payment"]); @@ -434,7 +434,7 @@ if (empty($reshook)) setEventMessages($langs->trans("ErrorDiscountLargerThanRemainToPaySplitItBefore"), null, 'errors'); } - if (! $error) + if (!$error) { $result = $discount->link_to_invoice(0, $id); if ($result < 0) { @@ -449,7 +449,7 @@ if (empty($reshook)) $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 (!empty($newlang)) { $outputlangs = new Translate("", $conf); $outputlangs->setDefaultLang($newlang); } @@ -467,12 +467,12 @@ if (empty($reshook)) //$object->fetch_lines(); // Already done into fetch // Check if there is already a discount (protection to avoid duplicate creation when resubmit post) - $discountcheck=new DiscountAbsolute($db); - $result=$discountcheck->fetch(0, 0, $object->id); + $discountcheck = new DiscountAbsolute($db); + $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 payed (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 payed back and not already converted and amount of payment is 0 (see real condition into condition used to show button converttoreduc) + $canconvert = 0; + if ($object->type == FactureFournisseur::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 (($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 payed back and not already converted and amount of payment is 0 (see real condition into condition used to show button converttoreduc) if ($canconvert) { $db->begin(); @@ -488,7 +488,7 @@ if (empty($reshook)) $amount_ht[$line->tva_tx] += $line->total_ht; $amount_tva[$line->tva_tx] += $line->total_tva; $amount_ttc[$line->tva_tx] += $line->total_ttc; - $i ++; + $i++; } } @@ -514,14 +514,14 @@ if (empty($reshook)) // If we're on a standard invoice, we have to get excess paid to create a discount in TTC without VAT $sql = 'SELECT SUM(pf.amount) as total_paiements'; - $sql.= ' FROM '.MAIN_DB_PREFIX.'paiementfourn_facturefourn as pf, '.MAIN_DB_PREFIX.'paiementfourn as p'; - $sql.= ' LEFT JOIN '.MAIN_DB_PREFIX.'c_paiement as c ON p.fk_paiement = c.id AND c.entity IN (' . getEntity('c_paiement') . ')'; - $sql.= ' WHERE pf.fk_facturefourn = '.$object->id; - $sql.= ' AND pf.fk_paiementfourn = p.rowid'; - $sql.= ' AND p.entity IN (' . getEntity('invoice').')'; + $sql .= ' FROM '.MAIN_DB_PREFIX.'paiementfourn_facturefourn as pf, '.MAIN_DB_PREFIX.'paiementfourn as p'; + $sql .= ' LEFT JOIN '.MAIN_DB_PREFIX.'c_paiement as c ON p.fk_paiement = c.id AND c.entity IN ('.getEntity('c_paiement').')'; + $sql .= ' WHERE pf.fk_facturefourn = '.$object->id; + $sql .= ' AND pf.fk_paiementfourn = p.rowid'; + $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; @@ -556,7 +556,7 @@ if (empty($reshook)) if (empty($error)) { - if($object->type != FactureFournisseur::TYPE_DEPOSIT) { + if ($object->type != FactureFournisseur::TYPE_DEPOSIT) { // Classe facture $result = $object->set_paid($user); if ($result >= 0) @@ -588,9 +588,9 @@ if (empty($reshook)) if ($object->statut == FactureFournisseur::STATUS_VALIDATED && $object->paye == 0) { $paiementfourn = new PaiementFourn($db); - $result=$paiementfourn->fetch(GETPOST('paiement_id')); + $result = $paiementfourn->fetch(GETPOST('paiement_id')); if ($result > 0) { - $result=$paiementfourn->delete(); // If fetch ok and found + $result = $paiementfourn->delete(); // If fetch ok and found header("Location: ".$_SERVER['PHP_SELF']."?id=".$id); } if ($result < 0) { @@ -612,8 +612,8 @@ if (empty($reshook)) $ret = $extrafields->setOptionalsFromPost(null, $object); if ($ret < 0) $error++; - $datefacture=dol_mktime(12, 0, 0, $_POST['remonth'], $_POST['reday'], $_POST['reyear']); - $datedue=dol_mktime(12, 0, 0, $_POST['echmonth'], $_POST['echday'], $_POST['echyear']); + $datefacture = dol_mktime(12, 0, 0, $_POST['remonth'], $_POST['reday'], $_POST['reyear']); + $datedue = dol_mktime(12, 0, 0, $_POST['echmonth'], $_POST['echday'], $_POST['echyear']); // Replacement invoice if ($_POST['type'] == FactureFournisseur::TYPE_REPLACEMENT) @@ -621,36 +621,36 @@ if (empty($reshook)) if ($datefacture == '') { setEventMessages($langs->trans('ErrorFieldRequired', $langs->transnoentities('DateInvoice')), null, 'errors'); - $action='create'; - $_GET['socid']=$_POST['socid']; + $action = 'create'; + $_GET['socid'] = $_POST['socid']; $error++; } - if (! ($_POST['fac_replacement'] > 0)) { - $error ++; + if (!($_POST['fac_replacement'] > 0)) { + $error++; setEventMessages($langs->trans("ErrorFieldRequired", $langs->transnoentitiesnoconv("ReplaceInvoice")), null, 'errors'); } - if (! $error) { + if (!$error) { // This is a replacement invoice $result = $object->fetch(GETPOST('fac_replacement'), 'int'); $object->fetch_thirdparty(); - $object->ref = GETPOST('ref', 'nohtml'); - $object->ref_supplier = GETPOST('ref_supplier', 'alpha'); - $object->socid = GETPOST('socid', 'int'); - $object->libelle = GETPOST('label', 'nohtml'); - $object->date = $datefacture; - $object->date_echeance = $datedue; - $object->note_public = GETPOST('note_public', 'none'); - $object->note_private = GETPOST('note_private', 'none'); + $object->ref = GETPOST('ref', 'nohtml'); + $object->ref_supplier = GETPOST('ref_supplier', 'alpha'); + $object->socid = GETPOST('socid', 'int'); + $object->libelle = GETPOST('label', 'nohtml'); + $object->date = $datefacture; + $object->date_echeance = $datedue; + $object->note_public = GETPOST('note_public', 'none'); + $object->note_private = GETPOST('note_private', 'none'); $object->cond_reglement_id = GETPOST('cond_reglement_id'); $object->mode_reglement_id = GETPOST('mode_reglement_id'); $object->fk_account = GETPOST('fk_account', 'int'); $object->fk_project = ($tmpproject > 0) ? $tmpproject : null; - $object->fk_incoterms = GETPOST('incoterm_id', 'int'); + $object->fk_incoterms = GETPOST('incoterm_id', 'int'); $object->location_incoterms = GETPOST('location_incoterms', 'alpha'); $object->multicurrency_code = GETPOST('multicurrency_code', 'alpha'); - $object->multicurrency_tx = GETPOST('originmulticurrency_tx', 'int'); + $object->multicurrency_tx = GETPOST('originmulticurrency_tx', 'int'); // Proprietes particulieres a facture de remplacement $object->fk_facture_source = GETPOST('fac_replacement'); @@ -668,73 +668,73 @@ if (empty($reshook)) if ($_POST['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 ++; + $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'; + $action = 'create'; $error++; } if ($datefacture == '') { setEventMessages($langs->trans('ErrorFieldRequired', $langs->transnoentities('DateInvoice')), null, 'errors'); - $action='create'; - $_GET['socid']=$_POST['socid']; + $action = 'create'; + $_GET['socid'] = $_POST['socid']; $error++; } - if (! GETPOST('ref_supplier')) + if (!GETPOST('ref_supplier')) { setEventMessages($langs->trans('ErrorFieldRequired', $langs->transnoentities('RefSupplier')), null, 'errors'); - $action='create'; - $_GET['socid']=$_POST['socid']; + $action = 'create'; + $_GET['socid'] = $_POST['socid']; $error++; } - if (! $error) + if (!$error) { $tmpproject = GETPOST('projectid', 'int'); // Creation facture - $object->ref = GETPOST('ref', 'nohtml'); - $object->ref_supplier = GETPOST('ref_supplier', 'nohtml'); + $object->ref = GETPOST('ref', 'nohtml'); + $object->ref_supplier = GETPOST('ref_supplier', 'nohtml'); $object->socid = GETPOST('socid', 'int'); - $object->libelle = GETPOST('label', 'nohtml'); + $object->libelle = GETPOST('label', 'nohtml'); $object->label = GETPOST('label', 'nohtml'); - $object->date = $datefacture; - $object->date_echeance = $datedue; - $object->note_public = GETPOST('note_public', 'none'); - $object->note_private = GETPOST('note_private', 'none'); + $object->date = $datefacture; + $object->date_echeance = $datedue; + $object->note_public = GETPOST('note_public', 'none'); + $object->note_private = GETPOST('note_private', 'none'); $object->cond_reglement_id = GETPOST('cond_reglement_id'); $object->mode_reglement_id = GETPOST('mode_reglement_id'); $object->fk_account = GETPOST('fk_account', 'int'); $object->fk_project = ($tmpproject > 0) ? $tmpproject : null; - $object->fk_incoterms = GETPOST('incoterm_id', 'int'); + $object->fk_incoterms = GETPOST('incoterm_id', 'int'); $object->location_incoterms = GETPOST('location_incoterms', 'alpha'); $object->multicurrency_code = GETPOST('multicurrency_code', 'alpha'); - $object->multicurrency_tx = GETPOST('originmulticurrency_tx', 'int'); + $object->multicurrency_tx = GETPOST('originmulticurrency_tx', 'int'); // Proprietes particulieres a facture avoir - $object->fk_facture_source = $sourceinvoice > 0 ? $sourceinvoice : ''; + $object->fk_facture_source = $sourceinvoice > 0 ? $sourceinvoice : ''; $object->type = FactureFournisseur::TYPE_CREDIT_NOTE; $id = $object->create($user); - if($id <= 0) { + if ($id <= 0) { $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) { @@ -744,13 +744,13 @@ if (empty($reshook)) $line->fk_facture_fourn = $object->id; $line->fk_parent_line = $fk_parent_line; - $line->subprice =-$line->subprice; // invert price for object + $line->subprice = -$line->subprice; // invert price for object $line->pa_ht = -$line->pa_ht; - $line->total_ht=-$line->total_ht; - $line->total_tva=-$line->total_tva; - $line->total_ttc=-$line->total_ttc; - $line->total_localtax1=-$line->total_localtax1; - $line->total_localtax2=-$line->total_localtax2; + $line->total_ht = -$line->total_ht; + $line->total_tva = -$line->total_tva; + $line->total_ttc = -$line->total_ttc; + $line->total_localtax1 = -$line->total_localtax1; + $line->total_localtax2 = -$line->total_localtax2; $result = $line->insert(); @@ -766,10 +766,10 @@ 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(); @@ -785,29 +785,29 @@ if (empty($reshook)) // Standard or deposit if ($_POST['type'] == FactureFournisseur::TYPE_STANDARD || $_POST['type'] == FactureFournisseur::TYPE_DEPOSIT) { - if (GETPOST('socid', 'int')<1) + if (GETPOST('socid', 'int') < 1) { setEventMessages($langs->trans('ErrorFieldRequired', $langs->transnoentities('Supplier')), null, 'errors'); - $action='create'; + $action = 'create'; $error++; } if ($datefacture == '') { setEventMessages($langs->trans('ErrorFieldRequired', $langs->transnoentities('DateInvoice')), null, 'errors'); - $action='create'; - $_GET['socid']=$_POST['socid']; + $action = 'create'; + $_GET['socid'] = $_POST['socid']; $error++; } - if (! GETPOST('ref_supplier')) + if (!GETPOST('ref_supplier')) { setEventMessages($langs->trans('ErrorFieldRequired', $langs->transnoentities('RefSupplier')), null, 'errors'); - $action='create'; - $_GET['socid']=$_POST['socid']; + $action = 'create'; + $_GET['socid'] = $_POST['socid']; $error++; } - if (! $error) + if (!$error) { $tmpproject = GETPOST('projectid', 'int'); @@ -823,19 +823,19 @@ if (empty($reshook)) $object->cond_reglement_id = GETPOST('cond_reglement_id'); $object->mode_reglement_id = GETPOST('mode_reglement_id'); $object->fk_account = GETPOST('fk_account', 'int'); - $object->fk_project = ($tmpproject > 0) ? $tmpproject : null; + $object->fk_project = ($tmpproject > 0) ? $tmpproject : null; $object->fk_incoterms = GETPOST('incoterm_id', 'int'); $object->location_incoterms = GETPOST('location_incoterms', 'alpha'); $object->multicurrency_code = GETPOST('multicurrency_code', 'alpha'); $object->multicurrency_tx = GETPOST('originmulticurrency_tx', 'int'); // 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 && $_POST['origin'] && $_POST['originid']) + if (!$error && $_POST['origin'] && $_POST['originid']) { // Parse element/subelement (ex: project_task) $element = $subelement = GETPOST('origin'); @@ -846,10 +846,10 @@ if (empty($reshook)) }*/ // For compatibility - if ($element == 'order') { + if ($element == 'order') { $element = $subelement = 'commande'; } - if ($element == 'propal') { + if ($element == 'propal') { $element = 'comm/propal'; $subelement = 'propal'; } if ($element == 'contract') { @@ -868,7 +868,7 @@ 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(); @@ -893,10 +893,10 @@ 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'; $srcobject = new $classname($db); - $result=$srcobject->fetch(GETPOST('originid', 'int')); + $result = $srcobject->fetch(GETPOST('originid', 'int')); if ($result > 0) { $lines = $srcobject->lines; @@ -906,11 +906,11 @@ if (empty($reshook)) $lines = $srcobject->lines; } - $num=count($lines); + $num = count($lines); 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); + $desc = ($lines[$i]->desc ? $lines[$i]->desc : $lines[$i]->libelle); + $product_type = ($lines[$i]->product_type ? $lines[$i]->product_type : 0); // Extrafields if (empty($conf->global->MAIN_EXTRAFIELDS_DISABLED) && method_exists($lines[$i], 'fetch_optionals')) { @@ -919,12 +919,12 @@ 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; - $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; + $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 = $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; // FIXME Missing special_code into addline and updateline methods $object->special_code = $lines[$i]->special_code; @@ -975,7 +975,7 @@ if (empty($reshook)) $error++; } } - elseif (! $error) + elseif (!$error) { $id = $object->create($user); if ($id < 0) @@ -992,8 +992,8 @@ if (empty($reshook)) $db->rollback(); setEventMessages($object->error, $object->errors, 'errors'); - $action='create'; - $_GET['socid']=$_POST['socid']; + $action = 'create'; + $_GET['socid'] = $_POST['socid']; } else { @@ -1002,7 +1002,7 @@ if (empty($reshook)) if (empty($conf->global->MAIN_DISABLE_PDF_AUTOUPDATE)) { $outputlangs = $langs; $result = $object->generateDocument($object->modelpdf, $outputlangs, $hidedetails, $hidedesc, $hideref); - if ($result < 0) + if ($result < 0) { dol_print_error($db, $object->error, $object->errors); exit; @@ -1038,9 +1038,9 @@ if (empty($reshook)) if (GETPOST('productid') > 0) { $productsupplier = new ProductFournisseur($db); - if (! empty($conf->global->SUPPLIER_INVOICE_WITH_PREDEFINED_PRICES_ONLY)) + if (!empty($conf->global->SUPPLIER_INVOICE_WITH_PREDEFINED_PRICES_ONLY)) { - if (GETPOST('productid') > 0 && $productsupplier->get_buyprice(0, price2num($_POST['qty']), GETPOST('productid'), 'none', GETPOST('socid', 'int')) < 0 ) + if (GETPOST('productid') > 0 && $productsupplier->get_buyprice(0, price2num($_POST['qty']), GETPOST('productid'), 'none', GETPOST('socid', 'int')) < 0) { setEventMessages($langs->trans("ErrorQtyTooLowForThisSupplier"), null, 'warnings'); } @@ -1049,18 +1049,18 @@ 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 { $label = $_POST['product_desc']; - $type = $_POST["type"]?$_POST["type"]:0; + $type = $_POST["type"] ? $_POST["type"] : 0; } - $date_start=dol_mktime(GETPOST('date_starthour'), GETPOST('date_startmin'), GETPOST('date_startsec'), GETPOST('date_startmonth'), GETPOST('date_startday'), GETPOST('date_startyear')); - $date_end=dol_mktime(GETPOST('date_endhour'), GETPOST('date_endmin'), GETPOST('date_endsec'), GETPOST('date_endmonth'), GETPOST('date_endday'), GETPOST('date_endyear')); + $date_start = dol_mktime(GETPOST('date_starthour'), GETPOST('date_startmin'), GETPOST('date_startsec'), GETPOST('date_startmonth'), GETPOST('date_startday'), GETPOST('date_startyear')); + $date_end = dol_mktime(GETPOST('date_endhour'), GETPOST('date_endmin'), GETPOST('date_endsec'), GETPOST('date_endmonth'), GETPOST('date_endday'), GETPOST('date_endyear')); // Define info_bits $info_bits = 0; @@ -1069,10 +1069,10 @@ if (empty($reshook)) // Define vat_rate $tva_tx = str_replace('*', '', $tva_tx); - $localtax1_tx= get_localtax($tva_tx, 1, $mysoc, $object->thirdparty); - $localtax2_tx= get_localtax($tva_tx, 2, $mysoc, $object->thirdparty); + $localtax1_tx = get_localtax($tva_tx, 1, $mysoc, $object->thirdparty); + $localtax2_tx = get_localtax($tva_tx, 2, $mysoc, $object->thirdparty); - $remise_percent=GETPOST('remise_percent'); + $remise_percent = GETPOST('remise_percent'); $pu_ht_devise = GETPOST('multicurrency_subprice'); // Extrafields Lines @@ -1081,11 +1081,11 @@ if (empty($reshook)) // Unset extrafield POST Data if (is_array($extralabelsline)) { foreach ($extralabelsline as $key => $value) { - unset($_POST["options_" . $key]); + unset($_POST["options_".$key]); } } - $result=$object->updateline(GETPOST('lineid'), $label, $up, $tva_tx, $localtax1_tx, $localtax2_tx, GETPOST('qty'), GETPOST('productid'), $price_base_type, $info_bits, $type, $remise_percent, 0, $date_start, $date_end, $array_options, $_POST['units'], $pu_ht_devise, GETPOST('fourn_ref', 'alpha')); + $result = $object->updateline(GETPOST('lineid'), $label, $up, $tva_tx, $localtax1_tx, $localtax2_tx, GETPOST('qty'), GETPOST('productid'), $price_base_type, $info_bits, $type, $remise_percent, 0, $date_start, $date_end, $array_options, $_POST['units'], $pu_ht_devise, GETPOST('fourn_ref', 'alpha')); if ($result >= 0) { unset($_POST['label']); @@ -1116,39 +1116,39 @@ if (empty($reshook)) { $db->begin(); - $ret=$object->fetch($id); + $ret = $object->fetch($id); if ($ret < 0) { dol_print_error($db, $object->error); exit; } - $ret=$object->fetch_thirdparty(); + $ret = $object->fetch_thirdparty(); $langs->load('errors'); - $error=0; + $error = 0; // Set if we used free entry or predefined product - $predef=''; - $product_desc=(GETPOST('dp_desc')?GETPOST('dp_desc'):''); - $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')); + $predef = ''; + $product_desc = (GETPOST('dp_desc') ?GETPOST('dp_desc') : ''); + $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') { - $idprod=0; + $idprod = 0; $price_ht = GETPOST('price_ht'); $tva_tx = (GETPOST('tva_tx') ? GETPOST('tva_tx') : 0); } else { - $idprod=GETPOST('idprod', 'int'); + $idprod = GETPOST('idprod', 'int'); $price_ht = ''; $tva_tx = ''; } $qty = GETPOST('qty'.$predef); - $remise_percent=GETPOST('remise_percent'.$predef); + $remise_percent = GETPOST('remise_percent'.$predef); $price_ht_devise = GETPOST('multicurrency_price_ht'); // Extrafields @@ -1158,31 +1158,31 @@ if (empty($reshook)) if (is_array($extralabelsline)) { // Get extra fields foreach ($extralabelsline as $key => $value) { - unset($_POST["options_" . $key]); + unset($_POST["options_".$key]); } } - 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++; @@ -1197,28 +1197,28 @@ if (empty($reshook)) $idprod = $res->fk_product_child; } else { setEventMessages($langs->trans('ErrorProductCombinationNotFound'), null, 'errors'); - $error ++; + $error++; } } } 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); + $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, ...) + $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 (preg_match('/^idprod_([0-9]+)$/', GETPOST('idprodfournprice', 'alpha'), $reg)) { - $idprod=$reg[1]; - $res=$productsupplier->fetch($idprod); // Load product from its id + $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 + $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 { $productsupplier->ref_supplier = ''; @@ -1227,15 +1227,15 @@ if (empty($reshook)) 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 + $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) { - $qtytosearch=$qty; // Just to see if a price exists for the quantity. Not used to found vat. + $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); + $idprod = $productsupplier->get_buyprice(GETPOST('idprodfournprice', 'alpha'), $qtytosearch); + $res = $productsupplier->fetch($idprod); } if ($idprod > 0) @@ -1243,27 +1243,27 @@ if (empty($reshook)) $label = $productsupplier->label; // if we use supplier description of the products - if(!empty($productsupplier->desc_supplier) && !empty($conf->global->PRODUIT_FOURN_TEXTS)) { + if (!empty($productsupplier->desc_supplier) && !empty($conf->global->PRODUIT_FOURN_TEXTS)) { $desc = $productsupplier->desc_supplier; } else $desc = $productsupplier->description; if (trim($product_desc) != trim($desc)) $desc = dol_concatdesc($desc, $product_desc, '', !empty($conf->global->MAIN_CHANGE_ORDER_CONCAT_DESCRIPTION)); $type = $productsupplier->type; - $price_base_type = ($productsupplier->fourn_price_base_type?$productsupplier->fourn_price_base_type:'HT'); + $price_base_type = ($productsupplier->fourn_price_base_type ? $productsupplier->fourn_price_base_type : 'HT'); $ref_supplier = $productsupplier->ref_supplier; - $tva_tx=get_default_tva($object->thirdparty, $mysoc, $productsupplier->id, GETPOST('idprodfournprice', 'alpha')); + $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; - $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($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); $pu = $productsupplier->fourn_pu; - 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( + $result = $object->addline( $desc, $pu, $tva_tx, @@ -1311,13 +1311,13 @@ if (empty($reshook)) $type = GETPOST('type'); $ref_supplier = GETPOST('fourn_ref', 'alpha'); - $fk_unit= GETPOST('units', 'alpha'); + $fk_unit = GETPOST('units', 'alpha'); - $tva_tx = price2num($tva_tx); // When vat is text input field + $tva_tx = price2num($tva_tx); // When vat is text input field // Local Taxes - $localtax1_tx= get_localtax($tva_tx, 1, $mysoc, $object->thirdparty); - $localtax2_tx= get_localtax($tva_tx, 2, $mysoc, $object->thirdparty); + $localtax1_tx = get_localtax($tva_tx, 1, $mysoc, $object->thirdparty); + $localtax2_tx = get_localtax($tva_tx, 2, $mysoc, $object->thirdparty); if ($price_ht !== '') { @@ -1335,7 +1335,7 @@ if (empty($reshook)) } //print "xx".$tva_tx; exit; - if (! $error && $result > 0) + if (!$error && $result > 0) { $db->commit(); @@ -1346,14 +1346,14 @@ if (empty($reshook)) $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 (!empty($newlang)) { $outputlangs = new Translate("", $conf); $outputlangs->setDefaultLang($newlang); } - $model=$object->modelpdf; + $model = $object->modelpdf; $ret = $object->fetch($id); // Reload to get new records - $result=$object->generateDocument($model, $outputlangs, $hidedetails, $hidedesc, $hideref); + $result = $object->generateDocument($model, $outputlangs, $hidedetails, $hidedesc, $hideref); if ($result < 0) dol_print_error($db, $result); } @@ -1402,7 +1402,7 @@ if (empty($reshook)) elseif ($action == 'classin' && $user->rights->fournisseur->facture->creer) { $object->fetch($id); - $result=$object->setProject($projectid); + $result = $object->setProject($projectid); } @@ -1417,7 +1417,7 @@ 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) @@ -1426,25 +1426,25 @@ if (empty($reshook)) $object->fetch_thirdparty(); - $qualified_for_stock_change=0; + $qualified_for_stock_change = 0; if (empty($conf->global->STOCK_SUPPORTS_SERVICES)) { - $qualified_for_stock_change=$object->hasProductsOrServices(2); + $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_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=''; + $action = ''; } } @@ -1457,18 +1457,18 @@ if (empty($reshook)) $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 (!empty($newlang)) { $outputlangs = new Translate("", $conf); $outputlangs->setDefaultLang($newlang); } - $model=$object->modelpdf; + $model = $object->modelpdf; $ret = $object->fetch($id); // Reload to get new records - $result=$object->generateDocument($model, $outputlangs, $hidedetails, $hidedesc, $hideref); + $result = $object->generateDocument($model, $outputlangs, $hidedetails, $hidedesc, $hideref); if ($result < 0) dol_print_error($db, $result); } - $action=''; + $action = ''; } } } @@ -1497,10 +1497,10 @@ if (empty($reshook)) include DOL_DOCUMENT_ROOT.'/core/actions_printing.inc.php'; // Actions to send emails - $trigger_name='BILL_SUPPLIER_SENTBYMAIL'; - $paramname='id'; - $autocopy='MAIN_MAIL_AUTOCOPY_SUPPLIER_INVOICE_TO'; - $trackid='sin'.$object->id; + $trigger_name = 'BILL_SUPPLIER_SENTBYMAIL'; + $paramname = 'id'; + $autocopy = 'MAIN_MAIL_AUTOCOPY_SUPPLIER_INVOICE_TO'; + $trackid = 'sin'.$object->id; include DOL_DOCUMENT_ROOT.'/core/actions_sendmails.inc.php'; // Actions to build doc @@ -1511,12 +1511,12 @@ if (empty($reshook)) // Make calculation according to calculationrule if ($action == 'calculate') { - $calculationrule=GETPOST('calculationrule'); + $calculationrule = GETPOST('calculationrule'); $object->fetch($id); $object->fetch_thirdparty(); - $result=$object->update_price(0, (($calculationrule=='totalofround')?'0':'1'), 0, $object->thirdparty); - if ($result <= 0) + $result = $object->update_price(0, (($calculationrule == 'totalofround') ? '0' : '1'), 0, $object->thirdparty); + if ($result <= 0) { dol_print_error($db, $result); exit; @@ -1530,12 +1530,12 @@ if (empty($reshook)) $ret = $extrafields->setOptionalsFromPost(null, $object, GETPOST('attribute', 'none')); if ($ret < 0) $error++; - if (! $error) + if (!$error) { // Actions on extra fields if (empty($conf->global->MAIN_EXTRAFIELDS_DISABLED)) // For avoid conflicts if trigger used { - $result=$object->insertExtraFields('BILL_SUPPLIER_MODIFY'); + $result = $object->insertExtraFields('BILL_SUPPLIER_MODIFY'); if ($result < 0) { $error++; @@ -1547,7 +1547,7 @@ if (empty($reshook)) $action = 'edit_extras'; } - if (! empty($conf->global->MAIN_DISABLE_CONTACTS_TAB) && $user->rights->fournisseur->facture->creer) + if (!empty($conf->global->MAIN_DISABLE_CONTACTS_TAB) && $user->rights->fournisseur->facture->creer) { if ($action == 'addcontact') { @@ -1583,7 +1583,7 @@ if (empty($reshook)) { if ($object->fetch($id)) { - $result=$object->swapContactStatus(GETPOST('ligne')); + $result = $object->swapContactStatus(GETPOST('ligne')); } else { @@ -1616,13 +1616,13 @@ if (empty($reshook)) $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); } +$bankaccountstatic = new Account($db); +$paymentstatic = new PaiementFourn($db); +if (!empty($conf->projet->enabled)) { $formproject = new FormProjets($db); } $now = dol_now(); -$title = $langs->trans('SupplierInvoice') . " - " . $langs->trans('Card'); +$title = $langs->trans('SupplierInvoice')." - ".$langs->trans('Card'); $helpurl = "EN:Module_Suppliers_Invoices|FR:Module_Fournisseurs_Factures|ES:Módulo_Facturas_de_proveedores"; llxHeader('', $title, $helpurl); @@ -1637,15 +1637,15 @@ if ($action == 'create') $currency_code = $conf->currency; - $societe=''; + $societe = ''; if (GETPOST('socid') > 0) { - $societe=new Societe($db); + $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($origin) && ! empty($originid)) + if (!empty($origin) && !empty($originid)) { // Parse element/subelement (ex: project_task) $element = $subelement = $origin; @@ -1657,10 +1657,10 @@ if ($action == 'create') } // For compatibility - if ($element == 'order') { + if ($element == 'order') { $element = $subelement = 'commande'; } - if ($element == 'propal') { + if ($element == 'propal') { $element = 'comm/propal'; $subelement = 'propal'; } if ($element == 'contract') { @@ -1672,21 +1672,21 @@ 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(); - $projectid = (!empty($objectsrc->fk_project)?$objectsrc->fk_project:''); + $projectid = (!empty($objectsrc->fk_project) ? $objectsrc->fk_project : ''); //$ref_client = (!empty($objectsrc->ref_client)?$object->ref_client:''); $soc = $objectsrc->thirdparty; - $cond_reglement_id = (!empty($objectsrc->cond_reglement_id)?$objectsrc->cond_reglement_id:(!empty($soc->cond_reglement_supplier_id)?$soc->cond_reglement_supplier_id:0)); // TODO maybe add default value option - $mode_reglement_id = (!empty($objectsrc->mode_reglement_id)?$objectsrc->mode_reglement_id:(!empty($soc->mode_reglement_supplier_id)?$soc->mode_reglement_supplier_id:0)); - $fk_account = (! empty($objectsrc->fk_account)?$objectsrc->fk_account:(! empty($soc->fk_account)?$soc->fk_account:0)); - $remise_percent = (!empty($objectsrc->remise_percent)?$objectsrc->remise_percent:(!empty($soc->remise_supplier_percent)?$soc->remise_supplier_percent:0)); - $remise_absolue = (!empty($objectsrc->remise_absolue)?$objectsrc->remise_absolue:(!empty($soc->remise_absolue)?$soc->remise_absolue:0)); - $dateinvoice = empty($conf->global->MAIN_AUTOFILL_DATE)?-1:''; + $cond_reglement_id = (!empty($objectsrc->cond_reglement_id) ? $objectsrc->cond_reglement_id : (!empty($soc->cond_reglement_supplier_id) ? $soc->cond_reglement_supplier_id : 0)); // TODO maybe add default value option + $mode_reglement_id = (!empty($objectsrc->mode_reglement_id) ? $objectsrc->mode_reglement_id : (!empty($soc->mode_reglement_supplier_id) ? $soc->mode_reglement_supplier_id : 0)); + $fk_account = (!empty($objectsrc->fk_account) ? $objectsrc->fk_account : (!empty($soc->fk_account) ? $soc->fk_account : 0)); + $remise_percent = (!empty($objectsrc->remise_percent) ? $objectsrc->remise_percent : (!empty($soc->remise_supplier_percent) ? $soc->remise_supplier_percent : 0)); + $remise_absolue = (!empty($objectsrc->remise_absolue) ? $objectsrc->remise_absolue : (!empty($soc->remise_absolue) ? $soc->remise_absolue : 0)); + $dateinvoice = empty($conf->global->MAIN_AUTOFILL_DATE) ?-1 : ''; if (!empty($conf->multicurrency->enabled)) { @@ -1694,10 +1694,10 @@ if ($action == 'create') if (!empty($conf->global->MULTICURRENCY_USE_ORIGIN_TX) && !empty($objectsrc->multicurrency_tx)) $currency_tx = $objectsrc->multicurrency_tx; } - $datetmp=dol_mktime(12, 0, 0, $_POST['remonth'], $_POST['reday'], $_POST['reyear']); - $dateinvoice=($datetmp==''?(empty($conf->global->MAIN_AUTOFILL_DATE)?-1:''):$datetmp); - $datetmp=dol_mktime(12, 0, 0, $_POST['echmonth'], $_POST['echday'], $_POST['echyear']); - $datedue=($datetmp==''?-1:$datetmp); + $datetmp = dol_mktime(12, 0, 0, $_POST['remonth'], $_POST['reday'], $_POST['reyear']); + $dateinvoice = ($datetmp == '' ? (empty($conf->global->MAIN_AUTOFILL_DATE) ?-1 : '') : $datetmp); + $datetmp = dol_mktime(12, 0, 0, $_POST['echmonth'], $_POST['echday'], $_POST['echyear']); + $datedue = ($datetmp == '' ?-1 : $datetmp); // Replicate extrafields $objectsrc->fetch_optionals($originid); @@ -1708,10 +1708,10 @@ if ($action == 'create') $cond_reglement_id = $societe->cond_reglement_supplier_id; $mode_reglement_id = $societe->mode_reglement_supplier_id; $fk_account = $societe->fk_account; - $datetmp=dol_mktime(12, 0, 0, $_POST['remonth'], $_POST['reday'], $_POST['reyear']); - $dateinvoice=($datetmp==''?(empty($conf->global->MAIN_AUTOFILL_DATE)?-1:''):$datetmp); - $datetmp=dol_mktime(12, 0, 0, $_POST['echmonth'], $_POST['echday'], $_POST['echyear']); - $datedue=($datetmp==''?-1:$datetmp); + $datetmp = dol_mktime(12, 0, 0, $_POST['remonth'], $_POST['reday'], $_POST['reyear']); + $dateinvoice = ($datetmp == '' ? (empty($conf->global->MAIN_AUTOFILL_DATE) ?-1 : '') : $datetmp); + $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; } @@ -1719,14 +1719,14 @@ if ($action == 'create') print ''; print ''; print ''; - if ($societe->id > 0) print '' . "\n"; + if ($societe->id > 0) print ''."\n"; print ''; print ''; - if (!empty($currency_tx)) print ''; + if (!empty($currency_tx)) print ''; dol_fiche_head(); - print '
    '; + print '
    '; // Ref print ''; @@ -1762,16 +1762,16 @@ if ($action == 'create') print ''; // Ref supplier - print ''; + print ''; print ''; print ''; @@ -1997,37 +1997,37 @@ if ($action == 'create') // Payment term print ''; // Payment mode print ''; // Bank Account print ''; // Multicurrency - if (! empty($conf->multicurrency->enabled)) + if (!empty($conf->multicurrency->enabled)) { print ''; print ''; print ''; } // Project - if (! empty($conf->projet->enabled)) + if (!empty($conf->projet->enabled)) { $formproject = new FormProjets($db); $langs->load('projects'); - print ''; } @@ -2037,7 +2037,7 @@ if ($action == 'create') print ''; print ''; print ''; } @@ -2045,8 +2045,8 @@ if ($action == 'create') print ''; print ''; // print ''; @@ -2056,9 +2056,9 @@ if ($action == 'create') print ''; print ''; // print ''; @@ -2079,10 +2079,10 @@ if ($action == 'create') print ''; print ''; - $txt=$langs->trans($classname); - if ($classname=='CommandeFournisseur') { + $txt = $langs->trans($classname); + if ($classname == 'CommandeFournisseur') { $langs->load('orders'); - $txt=$langs->trans("SupplierOrder"); + $txt = $langs->trans("SupplierOrder"); } print ''; print ''; print '"; - if ($mysoc->localtax1_assuj=="1" || $object->total_localtax1 != 0) //Localtax1 + if ($mysoc->localtax1_assuj == "1" || $object->total_localtax1 != 0) //Localtax1 { print '"; } - if ($mysoc->localtax2_assuj=="1" || $object->total_localtax2 != 0) //Localtax2 + if ($mysoc->localtax2_assuj == "1" || $object->total_localtax2 != 0) //Localtax2 { print '"; } @@ -2118,15 +2118,15 @@ if ($action == 'create') if (!empty($conf->multicurrency->enabled)) { - print ''; - print '"; - print '"; + print ''; + print '"; + print '"; } } // Other options - $parameters=array(); - $reshook=$hookmanager->executeHooks('formObjectOptions', $parameters, $object, $action); // Note that $action and $object may have been modified by hook + $parameters = array(); + $reshook = $hookmanager->executeHooks('formObjectOptions', $parameters, $object, $action); // Note that $action and $object may have been modified by hook print $hookmanager->resPrint; // Bouton "Create Draft" @@ -2137,7 +2137,7 @@ if ($action == 'create') print '
    '; print ''; print '     '; - print ''; + print ''; print '
    '; print "\n"; @@ -2148,10 +2148,10 @@ if ($action == 'create') { print '
    '; - $title=$langs->trans('ProductsAndServices'); + $title = $langs->trans('ProductsAndServices'); print load_fiche_titre($title); - print '
    '.$langs->trans('Ref').''.$langs->trans('Draft').'
    '.$langs->trans('RefSupplier').'
    '.$langs->trans('RefSupplier').'
    '.$langs->trans('Type').''; - print '
    ' . "\n"; + print '
    '."\n"; // Standard invoice print '
    '; - $tmp=' '; + $tmp = ' '; $desc = $form->textwithpicto($tmp.$langs->trans("InvoiceStandardAsk"), $langs->transnoentities("InvoiceStandardDesc"), 1, 'help', '', 0, 3); print $desc; print '
    '; @@ -1883,7 +1883,7 @@ if ($action == 'create') if (empty($conf->global->INVOICE_DISABLE_CREDIT_NOTE)) { // Show link for credit note - $facids=$facturestatic->list_qualified_avoir_supplier_invoices($societe->id); + $facids = $facturestatic->list_qualified_avoir_supplier_invoices($societe->id); if ($facids < 0) { dol_print_error($db, $facturestatic); @@ -1899,19 +1899,19 @@ if ($action == 'create') $newinvoice_static->type = $valarray ['type']; $newinvoice_static->paye = $valarray ['paye']; - $optionsav .= ''; } print '
    '; - $tmp=' jQuery(document).ready(function() { @@ -1927,26 +1927,26 @@ if ($action == 'create') }); }); '; - $text = $tmp.$langs->transnoentities("InvoiceAvoirAsk") . ' '; + $text = $tmp.$langs->transnoentities("InvoiceAvoirAsk").' '; // $text.=''; $text .= ''; $desc = $form->textwithpicto($text, $langs->transnoentities("InvoiceAvoirDesc"), 1, 'help', '', 0, 3); print $desc; print '
    '; - print '    0 ? 'checked':'').' /> '; + print '    0 ? 'checked' : '').' /> '; print '"; - print '
        0 ? 'checked':'').' /> '; + print '
        0 ? 'checked' : '').' /> '; print '"; print '
    '; @@ -1956,12 +1956,12 @@ if ($action == 'create') else { print '
    '; - $tmp=' '; - $text = $tmp.$langs->trans("InvoiceAvoir") . ' '; - $text.= '('.$langs->trans("YouMustCreateInvoiceFromSupplierThird").') '; + $tmp = ' '; + $text = $tmp.$langs->trans("InvoiceAvoir").' '; + $text .= '('.$langs->trans("YouMustCreateInvoiceFromSupplierThird").') '; $desc = $form->textwithpicto($text, $langs->transnoentities("InvoiceAvoirDesc"), 1, 'help', '', 0, 3); print $desc; - print '
    ' . "\n"; + print '
    '."\n"; } } @@ -1972,11 +1972,11 @@ if ($action == 'create') if ($societe->id > 0) { // Discounts for third party - print '
    ' . $langs->trans('Discounts') . ''; + print '
    '.$langs->trans('Discounts').''; $thirdparty = $societe; $discount_type = 1; - $backtopage = urlencode($_SERVER["PHP_SELF"] . '?socid=' . $societe->id . '&action=' . $action . '&origin=' . GETPOST('origin') . '&originid=' . GETPOST('originid')); + $backtopage = urlencode($_SERVER["PHP_SELF"].'?socid='.$societe->id.'&action='.$action.'&origin='.GETPOST('origin').'&originid='.GETPOST('originid')); include DOL_DOCUMENT_ROOT.'/core/tpl/object_discounts.tpl.php'; print '
    '.$langs->trans('PaymentConditionsShort').''; - $form->select_conditions_paiements(GETPOSTISSET('cond_reglement_id')?GETPOST('cond_reglement_id', 'int'):$cond_reglement_id, 'cond_reglement_id'); + $form->select_conditions_paiements(GETPOSTISSET('cond_reglement_id') ?GETPOST('cond_reglement_id', 'int') : $cond_reglement_id, 'cond_reglement_id'); print '
    '.$langs->trans('PaymentMode').''; - $form->select_types_paiements(GETPOSTISSET('mode_reglement_id')?GETPOST('mode_reglement_id', 'int'):$mode_reglement_id, 'mode_reglement_id', 'DBIT'); + $form->select_types_paiements(GETPOSTISSET('mode_reglement_id') ?GETPOST('mode_reglement_id', 'int') : $mode_reglement_id, 'mode_reglement_id', 'DBIT'); print '
    '.$langs->trans('BankAccount').''; - $form->select_comptes((GETPOSTISSET('fk_account')?GETPOST('fk_account', 'alpha'):$fk_account), 'fk_account', 0, '', 1); + $form->select_comptes((GETPOSTISSET('fk_account') ?GETPOST('fk_account', 'alpha') : $fk_account), 'fk_account', 0, '', 1); print '
    '.$form->editfieldkey('Currency', 'multicurrency_code', '', $object, 0).''; - print $form->selectMultiCurrency((GETPOSTISSET('multicurrency_code')?GETPOST('multicurrency_code', 'alpha'):$currency_code), 'multicurrency_code'); + print $form->selectMultiCurrency((GETPOSTISSET('multicurrency_code') ?GETPOST('multicurrency_code', 'alpha') : $currency_code), 'multicurrency_code'); print '
    ' . $langs->trans('Project') . ''; - $formproject->select_projects((empty($conf->global->PROJECT_CAN_ALWAYS_LINK_TO_ALL_SUPPLIERS)?$societe->id:-1), $projectid, 'projectid', 0, 0, 1, 1); + print '
    '.$langs->trans('Project').''; + $formproject->select_projects((empty($conf->global->PROJECT_CAN_ALWAYS_LINK_TO_ALL_SUPPLIERS) ? $societe->id : -1), $projectid, 'projectid', 0, 0, 1, 1); print '
    '; - print $form->select_incoterms(GETPOSTISSET('incoterm_id') ? GETPOST('incoterm_id', 'alphanohtml') : (!empty($objectsrc->fk_incoterms) ? $objectsrc->fk_incoterms : ''), GETPOSTISSET('location_incoterms') ? GETPOST('location_incoterms', 'alphanohtml') : (!empty($objectsrc->location_incoterms)?$objectsrc->location_incoterms:'')); + print $form->select_incoterms(GETPOSTISSET('incoterm_id') ? GETPOST('incoterm_id', 'alphanohtml') : (!empty($objectsrc->fk_incoterms) ? $objectsrc->fk_incoterms : ''), GETPOSTISSET('location_incoterms') ? GETPOST('location_incoterms', 'alphanohtml') : (!empty($objectsrc->location_incoterms) ? $objectsrc->location_incoterms : '')); print '
    '.$langs->trans('NotePublic').''; $note_public = $object->getDefaultCreateValueFor('note_public'); - if(empty($note_public))$note_public = $objectsrc->note_public; - $doleditor = new DolEditor('note_public', (GETPOSTISSET('note_public')?GETPOST('note_public', 'none'):$note_public), '', 80, 'dolibarr_notes', 'In', 0, false, true, ROWS_3, '90%'); + if (empty($note_public))$note_public = $objectsrc->note_public; + $doleditor = new DolEditor('note_public', (GETPOSTISSET('note_public') ?GETPOST('note_public', 'none') : $note_public), '', 80, 'dolibarr_notes', 'In', 0, false, true, ROWS_3, '90%'); print $doleditor->Create(1); print '
    '.$langs->trans('NotePrivate').''; $note_private = $object->getDefaultCreateValueFor('note_private'); - if(empty($note_private))$note_private = $objectsrc->note_private; + if (empty($note_private))$note_private = $objectsrc->note_private; - $doleditor = new DolEditor('note_private', (GETPOSTISSET('note_private')?GETPOST('note_private', 'none'):$note_private), '', 80, 'dolibarr_notes', 'In', 0, false, true, ROWS_3, '90%'); + $doleditor = new DolEditor('note_private', (GETPOSTISSET('note_private') ?GETPOST('note_private', 'none') : $note_private), '', 80, 'dolibarr_notes', 'In', 0, false, true, ROWS_3, '90%'); print $doleditor->Create(1); print '
    '.$txt.''.$objectsrc->getNomUrl(1); // We check if Origin document (id and type is known) has already at least one invoice attached to it @@ -2091,7 +2091,7 @@ 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); @@ -2105,12 +2105,12 @@ if ($action == 'create') echo '
    '.$langs->trans('AmountHT').''.price($objectsrc->total_ht).'
    '.$langs->trans('AmountVAT').''.price($objectsrc->total_tva)."
    '.$langs->transcountry("AmountLT1", $mysoc->country_code).''.price($objectsrc->total_localtax1)."
    '.$langs->transcountry("AmountLT2", $mysoc->country_code).''.price($objectsrc->total_localtax2)."
    ' . $langs->trans('MulticurrencyAmountHT') . '' . price($objectsrc->multicurrency_total_ht) . '
    ' . $langs->trans('MulticurrencyAmountVAT') . '' . price($objectsrc->multicurrency_total_tva) . "
    ' . $langs->trans('MulticurrencyAmountTTC') . '' . price($objectsrc->multicurrency_total_ttc) . "
    '.$langs->trans('MulticurrencyAmountHT').''.price($objectsrc->multicurrency_total_ht).'
    '.$langs->trans('MulticurrencyAmountVAT').''.price($objectsrc->multicurrency_total_tva)."
    '.$langs->trans('MulticurrencyAmountTTC').''.price($objectsrc->multicurrency_total_ttc)."
    '; + print '
    '; $objectsrc->printOriginLinesList(); @@ -2160,7 +2160,7 @@ if ($action == 'create') } else { - if ($id > 0 || ! empty($ref)) + if ($id > 0 || !empty($ref)) { /* *************************************************************************** */ /* */ @@ -2168,16 +2168,16 @@ else /* */ /* *************************************************************************** */ - $now=dol_now(); + $now = dol_now(); $productstatic = new Product($db); $object->fetch($id, $ref); - $result=$object->fetch_thirdparty(); + $result = $object->fetch_thirdparty(); if ($result < 0) dol_print_error($db); $societe = new Fournisseur($db); - $result=$societe->fetch($object->socid); + $result = $societe->fetch($object->socid); if ($result < 0) dol_print_error($db); $totalpaye = $object->getSommePaiement(); @@ -2198,7 +2198,7 @@ else } $resteapayeraffiche = $resteapayer; - if (! empty($conf->global->FACTURE_DEPOSITS_ARE_JUST_PAYMENTS)) { // Never use this + if (!empty($conf->global->FACTURE_DEPOSITS_ARE_JUST_PAYMENTS)) { // Never use this $filterabsolutediscount = "fk_invoice_supplier_source IS NULL"; // If we want deposit to be substracted to payments only and not to total of final invoice $filtercreditnote = "fk_invoice_supplier_source IS NOT NULL"; // If we want deposit to be substracted to payments only and not to total of final invoice } else { @@ -2215,7 +2215,7 @@ else * View card */ $head = facturefourn_prepare_head($object); - $titre=$langs->trans('SupplierInvoice'); + $titre = $langs->trans('SupplierInvoice'); dol_fiche_head($head, 'card', $titre, -1, 'bill'); @@ -2223,19 +2223,19 @@ else // 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 .= '
    '.$langs->trans('ConfirmConvertToReducSupplier2'); - $formconfirm = $form->formconfirm($_SERVER['PHP_SELF'] . '?facid=' . $object->id, $langs->trans('ConvertToReduc'), $text, 'confirm_converttoreduc', '', "yes", 2); + $formconfirm = $form->formconfirm($_SERVER['PHP_SELF'].'?facid='.$object->id, $langs->trans('ConvertToReduc'), $text, 'confirm_converttoreduc', '', "yes", 2); } // Clone confirmation if ($action == 'clone') { // Create an array for form - $formquestion=array( + $formquestion = array( array('type' => 'text', 'name' => 'newsupplierref', 'label' => $langs->trans("RefSupplier"), 'value' => $langs->trans("CopyOf").' '.$object->ref_supplier), array('type' => 'date', 'name' => 'newdate', 'label' => $langs->trans("Date"), 'value' => dol_now()) ); @@ -2250,7 +2250,7 @@ else $objectref = substr($object->ref, 1, 4); if ($objectref == 'PROV') { - $savdate=$object->date; + $savdate = $object->date; $numref = $object->getNextNumRef($societe); } else @@ -2258,7 +2258,7 @@ else $numref = $object->ref; } - $text=$langs->trans('ConfirmValidateBill', $numref); + $text = $langs->trans('ConfirmValidateBill', $numref); /*if (! empty($conf->notification->enabled)) { require_once DOL_DOCUMENT_ROOT .'/core/class/notify.class.php'; @@ -2266,34 +2266,34 @@ else $text.='
    '; $text.=$notify->confirmMessage('BILL_SUPPLIER_VALIDATE',$object->socid, $object); }*/ - $formquestion=array(); + $formquestion = array(); - $qualified_for_stock_change=0; + $qualified_for_stock_change = 0; if (empty($conf->global->STOCK_SUPPORTS_SERVICES)) { - $qualified_for_stock_change=$object->hasProductsOrServices(2); + $qualified_for_stock_change = $object->hasProductsOrServices(2); } else { - $qualified_for_stock_change=$object->hasProductsOrServices(1); + $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); + $formproduct = new FormProduct($db); $warehouse = new Entrepot($db); $warehouse_array = $warehouse->list_array(); if (count($warehouse_array) == 1) { $label = $object->type == FactureFournisseur::TYPE_CREDIT_NOTE ? $langs->trans("WarehouseForStockDecrease", current($warehouse_array)) : $langs->trans("WarehouseForStockIncrease", current($warehouse_array)); - $value = ''; + $value = ''; } else { $label = $object->type == FactureFournisseur::TYPE_CREDIT_NOTE ? $langs->trans("SelectWarehouseForStockDecrease") : $langs->trans("SelectWarehouseForStockIncrease"); - $value = $formproduct->selectWarehouses(GETPOST('idwarehouse')?GETPOST('idwarehouse'):'ifone', 'idwarehouse', '', 1); + $value = $formproduct->selectWarehouses(GETPOST('idwarehouse') ?GETPOST('idwarehouse') : 'ifone', 'idwarehouse', '', 1); } $formquestion = array( - array('type' => 'other','name' => 'idwarehouse','label' => $label,'value' => $value) + array('type' => 'other', 'name' => 'idwarehouse', 'label' => $label, 'value' => $value) ); } @@ -2314,7 +2314,7 @@ 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'; @@ -2323,13 +2323,13 @@ else $warehouse_array = $warehouse->list_array(); if (count($warehouse_array) == 1) { $label = $object->type == FactureFournisseur::TYPE_CREDIT_NOTE ? $langs->trans("WarehouseForStockIncrease", current($warehouse_array)) : $langs->trans("WarehouseForStockDecrease", current($warehouse_array)); - $value = ''; + $value = ''; } else { $label = $object->type == FactureFournisseur::TYPE_CREDIT_NOTE ? $langs->trans("SelectWarehouseForStockIncrease") : $langs->trans("SelectWarehouseForStockDecrease"); - $value = $formproduct->selectWarehouses(GETPOST('idwarehouse')?GETPOST('idwarehouse'):'ifone', 'idwarehouse', '', 1); + $value = $formproduct->selectWarehouses(GETPOST('idwarehouse') ?GETPOST('idwarehouse') : 'ifone', 'idwarehouse', '', 1); } $formquestion = array( - array('type' => 'other','name' => 'idwarehouse','label' => $label,'value' => $value) + array('type' => 'other', 'name' => 'idwarehouse', 'label' => $label, 'value' => $value) ); } $formconfirm = $form->formconfirm($_SERVER["PHP_SELF"].'?id='.$object->id, $langs->trans('UnvalidateBill'), $langs->trans('ConfirmUnvalidateBill', $object->ref), 'confirm_edit', $formquestion, 1, 1); @@ -2355,15 +2355,15 @@ else // 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); + $formconfirm = $form->formconfirm($_SERVER["PHP_SELF"].'?id='.$object->id.'&lineid='.$lineid, $langs->trans('DeleteProductLine'), $langs->trans('ConfirmDeleteProductLine'), 'confirm_deleteline', '', 0, 1); } if (!$formconfirm) { - $parameters=array('lineid'=>$lineid); + $parameters = array('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 @@ -2371,51 +2371,51 @@ else // Supplier invoice card - $linkback = ''.$langs->trans("BackToList").''; + $linkback = ''.$langs->trans("BackToList").''; - $morehtmlref='
    '; + $morehtmlref = '
    '; // Ref supplier - $morehtmlref.=$form->editfieldkey("RefSupplier", 'ref_supplier', $object->ref_supplier, $object, $user->rights->fournisseur->facture->creer, 'string', '', 0, 1); - $morehtmlref.=$form->editfieldval("RefSupplier", 'ref_supplier', $object->ref_supplier, $object, $user->rights->fournisseur->facture->creer, 'string', '', null, null, '', 1); + $morehtmlref .= $form->editfieldkey("RefSupplier", 'ref_supplier', $object->ref_supplier, $object, $user->rights->fournisseur->facture->creer, 'string', '', 0, 1); + $morehtmlref .= $form->editfieldval("RefSupplier", 'ref_supplier', $object->ref_supplier, $object, $user->rights->fournisseur->facture->creer, 'string', '', null, null, '', 1); // Thirdparty - $morehtmlref.='
    '.$langs->trans('ThirdParty') . ' : ' . $object->thirdparty->getNomUrl(1); - if (empty($conf->global->MAIN_DISABLE_OTHER_LINK) && $object->thirdparty->id > 0) $morehtmlref.=' ('.$langs->trans("OtherBills").')'; + $morehtmlref .= '
    '.$langs->trans('ThirdParty').' : '.$object->thirdparty->getNomUrl(1); + if (empty($conf->global->MAIN_DISABLE_OTHER_LINK) && $object->thirdparty->id > 0) $morehtmlref .= ' ('.$langs->trans("OtherBills").')'; // Project - if (! empty($conf->projet->enabled)) + if (!empty($conf->projet->enabled)) { $langs->load("projects"); - $morehtmlref.='
    '.$langs->trans('Project') . ' '; + $morehtmlref .= '
    '.$langs->trans('Project').' '; if ($user->rights->fournisseur->facture->creer) { if ($action != 'classify') { - $morehtmlref.='' . img_edit($langs->transnoentitiesnoconv('SetProject')) . ' : '; + $morehtmlref .= ''.img_edit($langs->transnoentitiesnoconv('SetProject')).' : '; } if ($action == 'classify') { //$morehtmlref.=$form->form_project($_SERVER['PHP_SELF'] . '?id=' . $object->id, $object->socid, $object->fk_project, 'projectid', 0, 0, 1, 1); - $morehtmlref.='
    '; - $morehtmlref.=''; - $morehtmlref.=''; - $morehtmlref.=$formproject->select_projects((empty($conf->global->PROJECT_CAN_ALWAYS_LINK_TO_ALL_SUPPLIERS)?$object->socid:-1), $object->fk_project, 'projectid', $maxlength, 0, 1, 0, 1, 0, 0, '', 1); - $morehtmlref.=''; - $morehtmlref.=''; + $morehtmlref .= '
    '; + $morehtmlref .= ''; + $morehtmlref .= ''; + $morehtmlref .= $formproject->select_projects((empty($conf->global->PROJECT_CAN_ALWAYS_LINK_TO_ALL_SUPPLIERS) ? $object->socid : -1), $object->fk_project, 'projectid', $maxlength, 0, 1, 0, 1, 0, 0, '', 1); + $morehtmlref .= ''; + $morehtmlref .= ''; } else { - $morehtmlref.=$form->form_project($_SERVER['PHP_SELF'] . '?id=' . $object->id, $object->socid, $object->fk_project, 'none', 0, 0, 0, 1); + $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)) { + if (!empty($object->fk_project)) { $proj = new Project($db); $proj->fetch($object->fk_project); - $morehtmlref.=''; - $morehtmlref.=$proj->ref; - $morehtmlref.=''; + $morehtmlref .= ''; + $morehtmlref .= $proj->ref; + $morehtmlref .= ''; } else { - $morehtmlref.=''; + $morehtmlref .= ''; } } } - $morehtmlref.='
    '; + $morehtmlref .= '
    '; - $object->totalpaye = $totalpaye; // To give a chance to dol_banner_tab to use already paid amount to show correct status + $object->totalpaye = $totalpaye; // To give a chance to dol_banner_tab to use already paid amount to show correct status dol_banner_tab($object, 'ref', $linkback, 1, 'ref', 'ref', $morehtmlref); @@ -2430,27 +2430,27 @@ else print $object->getLibType(); if ($object->type == FactureFournisseur::TYPE_REPLACEMENT) { - $facreplaced=new FactureFournisseur($db); + $facreplaced = new FactureFournisseur($db); $facreplaced->fetch($object->fk_facture_source); print ' ('.$langs->transnoentities("ReplaceInvoice", $facreplaced->getNomUrl(1)).')'; } if ($object->type == FactureFournisseur::TYPE_CREDIT_NOTE) { - $facusing=new FactureFournisseur($db); + $facusing = new FactureFournisseur($db); $facusing->fetch($object->fk_facture_source); print ' ('.$langs->transnoentities("CorrectInvoice", $facusing->getNomUrl(1)).')'; } - $facidavoir=$object->getListIdAvoirFromInvoice(); + $facidavoir = $object->getListIdAvoirFromInvoice(); if (count($facidavoir) > 0) { print ' ('.$langs->transnoentities("InvoiceHasAvoir"); - $i=0; - foreach($facidavoir as $id) + $i = 0; + foreach ($facidavoir as $id) { - if ($i==0) print ' '; + if ($i == 0) print ' '; else print ','; - $facavoir=new FactureFournisseur($db); + $facavoir = new FactureFournisseur($db); $facavoir->fetch($id); print $facavoir->getNomUrl(1); } @@ -2458,14 +2458,14 @@ else } if (isset($facidnext) && $facidnext > 0) { - $facthatreplace=new FactureFournisseur($db); + $facthatreplace = new FactureFournisseur($db); $facthatreplace->fetch($facidnext); print ' ('.$langs->transnoentities("ReplacedByInvoice", $facthatreplace->getNomUrl(1)).')'; } if ($object->type == FactureFournisseur::TYPE_CREDIT_NOTE || $object->type == FactureFournisseur::TYPE_DEPOSIT) { $discount = new DiscountAbsolute($db); $result = $discount->fetch(0, 0, $object->id); - if ($result > 0){ + if ($result > 0) { print '. '.$langs->trans("CreditNoteConvertedIntoDiscount", $object->getLibType(1), $discount->getNomUrl(1, 'discount')).'
    '; } } @@ -2473,12 +2473,12 @@ else // Relative and absolute discounts - print ''; @@ -2548,7 +2548,7 @@ else print ''; // Multicurrency - if (! empty($conf->multicurrency->enabled)) + if (!empty($conf->multicurrency->enabled)) { // Multicurrency code print ''; @@ -2557,13 +2557,13 @@ else print $form->editfieldkey('Currency', 'multicurrency_code', '', $object, 0); print ''; if ($action != 'editmulticurrencycode' && $object->statut == $object::STATUS_DRAFT) - print ''; + print ''; print '
    ' . $langs->trans('Discounts'); + print '
    '.$langs->trans('Discounts'); print ''; $thirdparty = $societe; $discount_type = 1; - $backtopage = urlencode($_SERVER["PHP_SELF"] . '?facid=' . $object->id); + $backtopage = urlencode($_SERVER["PHP_SELF"].'?facid='.$object->id); include DOL_DOCUMENT_ROOT.'/core/tpl/object_discounts.tpl.php'; print '
    id . '">' . img_edit($langs->transnoentitiesnoconv('SetMultiCurrencyCode'), 1) . 'id.'">'.img_edit($langs->transnoentitiesnoconv('SetMultiCurrencyCode'), 1).'
    '; print '
    '; if ($action == 'editmulticurrencycode') { - $form->form_multicurrency_code($_SERVER['PHP_SELF'] . '?id=' . $object->id, $object->multicurrency_code, 'multicurrency_code'); + $form->form_multicurrency_code($_SERVER['PHP_SELF'].'?id='.$object->id, $object->multicurrency_code, 'multicurrency_code'); } else { - $form->form_multicurrency_code($_SERVER['PHP_SELF'] . '?id=' . $object->id, $object->multicurrency_code, 'none'); + $form->form_multicurrency_code($_SERVER['PHP_SELF'].'?id='.$object->id, $object->multicurrency_code, 'none'); } print '
    id . '">' . img_edit($langs->transnoentitiesnoconv('SetMultiCurrencyCode'), 1) . 'id.'">'.img_edit($langs->transnoentitiesnoconv('SetMultiCurrencyCode'), 1).'
    '; print '
    '; if ($action == 'editmulticurrencyrate' || $action == 'actualizemulticurrencyrate') { if ($action == 'actualizemulticurrencyrate') { list($object->fk_multicurrency, $object->multicurrency_tx) = MultiCurrency::getIdAndTxFromCode($object->db, $object->multicurrency_code); } - $form->form_multicurrency_rate($_SERVER['PHP_SELF'] . '?id=' . $object->id, $object->multicurrency_tx, 'multicurrency_tx', $object->multicurrency_code); + $form->form_multicurrency_rate($_SERVER['PHP_SELF'].'?id='.$object->id, $object->multicurrency_tx, 'multicurrency_tx', $object->multicurrency_code); } else { - $form->form_multicurrency_rate($_SERVER['PHP_SELF'] . '?id=' . $object->id, $object->multicurrency_tx, 'none', $object->multicurrency_code); + $form->form_multicurrency_rate($_SERVER['PHP_SELF'].'?id='.$object->id, $object->multicurrency_tx, 'none', $object->multicurrency_code); if ($object->statut == $object::STATUS_DRAFT && $object->multicurrency_code && $object->multicurrency_code != $conf->currency) { print '
            '; print ''.$langs->trans("ActualizeCurrency").''; @@ -2631,14 +2631,14 @@ else } 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); + print $form->select_incoterms((!empty($object->fk_incoterms) ? $object->fk_incoterms : ''), (!empty($object->location_incoterms) ? $object->location_incoterms : ''), $_SERVER['PHP_SELF'].'?id='.$object->id); } print '
    '; @@ -2652,44 +2652,44 @@ else if (!empty($conf->multicurrency->enabled) && ($object->multicurrency_code != $conf->currency)) { // Multicurrency Amount HT - 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)) . '
    '.$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)).'
    ' . $form->editfieldkey('MulticurrencyAmountVAT', 'multicurrency_total_tva', '', $object, 0) . '' . price($object->multicurrency_total_tva, '', $langs, 0, - 1, - 1, (!empty($object->multicurrency_code) ? $object->multicurrency_code : $conf->currency)) . '
    '.$form->editfieldkey('MulticurrencyAmountVAT', 'multicurrency_total_tva', '', $object, 0).''.price($object->multicurrency_total_tva, '', $langs, 0, - 1, - 1, (!empty($object->multicurrency_code) ? $object->multicurrency_code : $conf->currency)).'
    ' . $form->editfieldkey('MulticurrencyAmountTTC', 'multicurrency_total_ttc', '', $object, 0) . '' . price($object->multicurrency_total_ttc, '', $langs, 0, - 1, - 1, (!empty($object->multicurrency_code) ? $object->multicurrency_code : $conf->currency)) . '
    '.$form->editfieldkey('MulticurrencyAmountTTC', 'multicurrency_total_ttc', '', $object, 0).''.price($object->multicurrency_total_ttc, '', $langs, 0, - 1, - 1, (!empty($object->multicurrency_code) ? $object->multicurrency_code : $conf->currency)).'
    '.$langs->trans('AmountHT').''.price($object->total_ht, 1, $langs, 0, -1, -1, $conf->currency).'
    '.$langs->trans('AmountVAT').''.price($object->total_tva, 1, $langs, 0, -1, -1, $conf->currency).'
            '; - 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; - $s=$langs->trans("ReCalculate").' '; - $s.=''.$langs->trans("Mode1").''; - $s.=' / '; - $s.=''.$langs->trans("Mode2").''; + 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; + $s = $langs->trans("ReCalculate").' '; + $s .= ''.$langs->trans("Mode1").''; + $s .= ' / '; + $s .= ''.$langs->trans("Mode2").''; print $form->textwithtooltip($s, $langs->trans("CalculationRuleDesc", $calculationrulenum).'
    '.$langs->trans("CalculationRuleDescSupplier"), 2, 1, img_picto('', 'help')); print '
    '.$langs->transcountry("AmountLT1", $societe->country_code).''.price($object->total_localtax1, 1, $langs, 0, -1, -1, $conf->currency).'
    '.$langs->transcountry("AmountLT2", $societe->country_code).''.price($object->total_localtax2, 1, $langs, 0, -1, -1, $conf->currency).'
    '; print ''; - print ''; + print ''; print ''; print ''; - if (! empty($conf->banque->enabled)) print ''; + if (!empty($conf->banque->enabled)) print ''; print ''; print ''; print ''; @@ -2753,28 +2753,28 @@ else { $objp = $db->fetch_object($result); - $paymentstatic->id=$objp->rowid; - $paymentstatic->datepaye=$db->jdate($objp->dp); - $paymentstatic->ref=($objp->ref ? $objp->ref : $objp->rowid); - $paymentstatic->num_paiement=$objp->num_paiement; - $paymentstatic->payment_code=$objp->payment_code; + $paymentstatic->id = $objp->rowid; + $paymentstatic->datepaye = $db->jdate($objp->dp); + $paymentstatic->ref = ($objp->ref ? $objp->ref : $objp->rowid); + $paymentstatic->num_paiement = $objp->num_paiement; + $paymentstatic->payment_code = $objp->payment_code; print ''; print ''; - print ''; + print ''; print ''; - if (! empty($conf->banque->enabled)) + if (!empty($conf->banque->enabled)) { - $bankaccountstatic->id=$objp->baid; - $bankaccountstatic->ref=$objp->baref; - $bankaccountstatic->label=$objp->baref; + $bankaccountstatic->id = $objp->baid; + $bankaccountstatic->ref = $objp->baref; + $bankaccountstatic->label = $objp->baref; $bankaccountstatic->number = $objp->banumber; - if (! empty($conf->accounting->enabled)) { + if (!empty($conf->accounting->enabled)) { $bankaccountstatic->account_number = $objp->account_number; $accountingjournal = new AccountingJournal($db); @@ -2786,7 +2786,7 @@ else if ($objp->baid > 0) print $bankaccountstatic->getNomUrl(1, 'transactions'); print ''; } - print ''; + print ''; print ''; + print ' :'; //$resteapayer = $object->total_ttc - $totalpaye; $resteapayeraffiche = $resteapayer; @@ -2847,8 +2847,8 @@ else $sql = "SELECT re.rowid, re.amount_ht, re.amount_tva, re.amount_ttc,"; $sql .= " re.description, re.fk_invoice_supplier_source"; - $sql .= " FROM " . MAIN_DB_PREFIX . "societe_remise_except as re"; - $sql .= " WHERE fk_invoice_supplier = " . $object->id; + $sql .= " FROM ".MAIN_DB_PREFIX."societe_remise_except as re"; + $sql .= " WHERE fk_invoice_supplier = ".$object->id; $resql = $db->query($sql); if ($resql) { $num = $db->num_rows($resql); @@ -2857,18 +2857,18 @@ else while ($i < $num) { $obj = $db->fetch_object($resql); $invoice->fetch($obj->fk_invoice_supplier_source); - print ''; - print ''; + print ''; print ''; - $i ++; + $i++; if ($invoice->type == FactureFournisseur::TYPE_CREDIT_NOTE) $creditnoteamount += $obj->amount_ttc; if ($invoice->type == FactureFournisseur::TYPE_DEPOSIT) @@ -2880,73 +2880,73 @@ else // Paye partiellement 'escompte' if (($object->statut == FactureFournisseur::STATUS_CLOSED || $object->statut == FactureFournisseur::STATUS_ABANDONED) && $object->close_code == 'discount_vat') { - print ''; + print ''; $resteapayeraffiche = 0; $cssforamountpaymentcomplete = 'amountpaymentneutral'; } // Paye partiellement ou Abandon 'badsupplier' if (($object->statut == FactureFournisseur::STATUS_CLOSED || $object->statut == FactureFournisseur::STATUS_ABANDONED) && $object->close_code == 'badsupplier') { - print ''; + print ''; // $resteapayeraffiche=0; $cssforamountpaymentcomplete = 'amountpaymentneutral'; } // Paye partiellement ou Abandon 'product_returned' if (($object->statut == FactureFournisseur::STATUS_CLOSED || $object->statut == FactureFournisseur::STATUS_ABANDONED) && $object->close_code == 'product_returned') { - print ''; + print ''; $resteapayeraffiche = 0; $cssforamountpaymentcomplete = 'amountpaymentneutral'; } // Paye partiellement ou Abandon 'abandon' if (($object->statut == FactureFournisseur::STATUS_CLOSED || $object->statut == FactureFournisseur::STATUS_ABANDONED) && $object->close_code == 'abandon') { - print ''; + $text .= '

    '.$langs->trans("Reason").':'.$object->close_note; + print $form->textwithpicto($langs->trans("Abandoned").':', $text, - 1); + print ''; $resteapayeraffiche = 0; $cssforamountpaymentcomplete = 'amountpaymentneutral'; } // Billed - print ''; + print ''; // Remainder to pay - print ''; - print ''; + print ''; print ''; } else // Credit note { - $cssforamountpaymentcomplete='amountpaymentneutral'; + $cssforamountpaymentcomplete = 'amountpaymentneutral'; // Total already paid back - print ''; + print ' :'; // Billed - print ''; + print ''; // Remainder to pay back - print ''; - print ''; + print ''; print ''; // Sold credit note @@ -2964,16 +2964,16 @@ else print '

    '; - 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; + $colwidth = 20; $blocname = 'notes'; $title = $langs->trans('Notes'); include DOL_DOCUMENT_ROOT.'/core/tpl/bloc_showhide.tpl.php'; @@ -2983,31 +2983,31 @@ else /* * Lines */ - print ''; + print ''; print ''; - print ''; + print ''; print ''; print ''; print ''; - if (! empty($conf->use_javascript_ajax) && $object->statut == FactureFournisseur::STATUS_DRAFT) { - include DOL_DOCUMENT_ROOT . '/core/tpl/ajaxrow.tpl.php'; + if (!empty($conf->use_javascript_ajax) && $object->statut == FactureFournisseur::STATUS_DRAFT) { + include DOL_DOCUMENT_ROOT.'/core/tpl/ajaxrow.tpl.php'; } print '
    '; print '
    ' . ($object->type == FactureFournisseur::TYPE_CREDIT_NOTE ? $langs->trans("PaymentsBack") : $langs->trans('Payments')) . ''.($object->type == FactureFournisseur::TYPE_CREDIT_NOTE ? $langs->trans("PaymentsBack") : $langs->trans('Payments')).''.$langs->trans('Date').''.$langs->trans('Type').''.$langs->trans('BankAccount').''.$langs->trans('BankAccount').''.$langs->trans('Amount').' 
    '; print $paymentstatic->getNomUrl(1); print ''.dol_print_date($db->jdate($objp->dp), 'day') . ''.dol_print_date($db->jdate($objp->dp), 'day').''; print $form->form_modes_reglement(null, $objp->paiement_type, 'none').' '.$objp->num_paiement; print '' . price($sign * $objp->amount) . ''.price($sign * $objp->amount).''; if ($object->statut == FactureFournisseur::STATUS_VALIDATED && $object->paye == 0 && $user->socid == 0) { @@ -2828,12 +2828,12 @@ else if ($object->type != FactureFournisseur::TYPE_CREDIT_NOTE) { // Total already paid - print '
    '; + print '
    '; if ($object->type != FactureFournisseur::TYPE_DEPOSIT) print $langs->trans('AlreadyPaidNoCreditNotesNoDeposits'); else print $langs->trans('AlreadyPaid'); - print ' : 0)?' class="amountalreadypaid"':'').'>' . price($totalpaye) . ' 
    0) ? ' class="amountalreadypaid"' : '').'>'.price($totalpaye).' 
    '; + print '
    '; if ($invoice->type == FactureFournisseur::TYPE_CREDIT_NOTE) - print $langs->trans("CreditNote") . ' '; + print $langs->trans("CreditNote").' '; if ($invoice->type == FactureFournisseur::TYPE_DEPOSIT) - print $langs->trans("Deposit") . ' '; + print $langs->trans("Deposit").' '; print $invoice->getNomUrl(0); print ' :' . price($obj->amount_ttc) . ''.price($obj->amount_ttc).''; - print 'rowid . '">' . img_delete() . ''; + print 'rowid.'">'.img_delete().''; print '
    '; - print $form->textwithpicto($langs->trans("Discount") . ':', $langs->trans("HelpEscompte"), - 1); - print '' . price($object->total_ttc - $creditnoteamount - $depositamount - $totalpaye) . ' 
    '; + print $form->textwithpicto($langs->trans("Discount").':', $langs->trans("HelpEscompte"), - 1); + print ''.price($object->total_ttc - $creditnoteamount - $depositamount - $totalpaye).' 
    '; - print $form->textwithpicto($langs->trans("Abandoned") . ':', $langs->trans("HelpAbandonBadCustomer"), - 1); - print '' . price($object->total_ttc - $creditnoteamount - $depositamount - $totalpaye) . ' 
    '; + print $form->textwithpicto($langs->trans("Abandoned").':', $langs->trans("HelpAbandonBadCustomer"), - 1); + print ''.price($object->total_ttc - $creditnoteamount - $depositamount - $totalpaye).' 
    '; - print $form->textwithpicto($langs->trans("ProductReturned") . ':', $langs->trans("HelpAbandonProductReturned"), - 1); - print '' . price($object->total_ttc - $creditnoteamount - $depositamount - $totalpaye) . ' 
    '; + print $form->textwithpicto($langs->trans("ProductReturned").':', $langs->trans("HelpAbandonProductReturned"), - 1); + print ''.price($object->total_ttc - $creditnoteamount - $depositamount - $totalpaye).' 
    '; + print '
    '; $text = $langs->trans("HelpAbandonOther"); if ($object->close_note) - $text .= '

    ' . $langs->trans("Reason") . ':' . $object->close_note; - print $form->textwithpicto($langs->trans("Abandoned") . ':', $text, - 1); - print '
    ' . price($object->total_ttc - $creditnoteamount - $depositamount - $totalpaye) . ' 
    '.price($object->total_ttc - $creditnoteamount - $depositamount - $totalpaye).' 
    ' . $langs->trans("Billed") . ' :' . price($object->total_ttc) . ' 
    '.$langs->trans("Billed").' :'.price($object->total_ttc).' 
    '; + print '
    '; if ($resteapayeraffiche >= 0) print $langs->trans('RemainderToPay'); else print $langs->trans('ExcessPaid'); print ' :' . price($resteapayeraffiche) . ''.price($resteapayeraffiche).' 
    '; + print '
    '; print $langs->trans('AlreadyPaidBack'); - print ' :' . price($sign * $totalpaye) . ' 
    '.price($sign * $totalpaye).' 
    ' . $langs->trans("Billed") . ' :' . price($sign * $object->total_ttc) . ' 
    '.$langs->trans("Billed").' :'.price($sign * $object->total_ttc).' 
    '; + print '
    '; if ($resteapayeraffiche <= 0) print $langs->trans('RemainderToPayBack'); else print $langs->trans('ExcessPaid'); print ' :' . price($sign * $resteapayeraffiche) . ''.price($sign * $resteapayeraffiche).' 
    '; 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. + $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)) + if (!empty($object->lines)) $ret = $object->printObjectLines($action, $societe, $mysoc, $lineid, 1); - $num=count($object->lines); + $num = count($object->lines); // Form to add new line if ($object->statut == FactureFournisseur::STATUS_DRAFT && $user->rights->fournisseur->facture->creer) @@ -3046,7 +3046,7 @@ else if ($object->statut == FactureFournisseur::STATUS_VALIDATED && $action != 'confirm_edit' && $object->getSommePaiement() == 0 && $user->rights->fournisseur->facture->creer) { // 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. + $ventilExportCompta = $object->getVentilExportCompta(); // Should be 0 since the sum of payments are zero. But we keep the protection. if ($ventilExportCompta == 0) { @@ -3054,7 +3054,7 @@ else } else { - print '
    ' . $langs->trans('Modify') . '
    '; + print '
    '.$langs->trans('Modify').'
    '; } } @@ -3066,7 +3066,7 @@ else || ($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' && $user->rights->fournisseur->facture->creer) // Not replaced by another invoice + if (!$facidnext && $object->close_code != 'replaced' && $user->rights->fournisseur->facture->creer) // Not replaced by another invoice { print ''; } @@ -3091,13 +3091,13 @@ else } // 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 ''; // must use facid because id is for payment id not invoice + print ''; // must use facid because id is for payment id not invoice } // Classify paid - if ($action != 'confirm_edit' && $object->statut == FactureFournisseur::STATUS_VALIDATED && $object->paye == 0 && $user->socid == 0) + if ($action != 'confirm_edit' && $object->statut == FactureFournisseur::STATUS_VALIDATED && $object->paye == 0 && $user->socid == 0) { print ''; @@ -3127,7 +3127,7 @@ else } // For credit note if ($object->type == FactureFournisseur::TYPE_CREDIT_NOTE && $object->statut == 1 && $object->paye == 0 && $user->rights->fournisseur->facture->creer && $object->getSommePaiement() == 0) { - print ''; + print ''; } // For deposit invoice if ($object->type == FactureFournisseur::TYPE_DEPOSIT && $object->paye == 1 && $resteapayer == 0 && $user->rights->fournisseur->facture->creer && empty($discount->id)) @@ -3141,8 +3141,8 @@ else { if (count($object->lines)) { - 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))) + 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))) { print ''; @@ -3170,32 +3170,32 @@ else // Create a credit note if (($object->type == FactureFournisseur::TYPE_STANDARD || $object->type == FactureFournisseur::TYPE_DEPOSIT) && $object->statut > 0 && $user->rights->fournisseur->facture->creer) { - if (! $objectidnext) + if (!$objectidnext) { - print ''; + print ''; } } // Delete - $isErasable=$object->is_erasable(); + $isErasable = $object->is_erasable(); if ($action != 'confirm_edit' && ($user->rights->fournisseur->facture->supprimer || ($user->rights->fournisseur->facture->creer && $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 ''; + print ''; } elseif ($isErasable == -3) { // Should never happen with supplier invoice - print ''; + print ''; } elseif ($isErasable == -2) { // Should never happen with supplier invoice - print ''; + print ''; } elseif ($isErasable == -1) { - print ''; + print ''; } elseif ($isErasable <= 0) // Any other cases { - print ''; + print ''; } else { @@ -3211,16 +3211,16 @@ else /* * Documents generes */ - $ref=dol_sanitizeFileName($object->ref); + $ref = dol_sanitizeFileName($object->ref); $subdir = get_exdir($object->id, 2, 0, 0, $object, 'invoice_supplier').$ref; $filedir = $conf->fournisseur->facture->dir_output.'/'.$subdir; - $urlsource=$_SERVER['PHP_SELF'].'?id='.$object->id; - $genallowed=$user->rights->fournisseur->facture->lire; - $delallowed=$user->rights->fournisseur->facture->creer; - $modelpdf=(! empty($object->modelpdf)?$object->modelpdf:(empty($conf->global->INVOICE_SUPPLIER_ADDON_PDF)?'':$conf->global->INVOICE_SUPPLIER_ADDON_PDF)); + $urlsource = $_SERVER['PHP_SELF'].'?id='.$object->id; + $genallowed = $user->rights->fournisseur->facture->lire; + $delallowed = $user->rights->fournisseur->facture->creer; + $modelpdf = (!empty($object->modelpdf) ? $object->modelpdf : (empty($conf->global->INVOICE_SUPPLIER_ADDON_PDF) ? '' : $conf->global->INVOICE_SUPPLIER_ADDON_PDF)); print $formfile->showdocuments('facture_fournisseur', $subdir, $filedir, $urlsource, $genallowed, $delallowed, $modelpdf, 1, 0, 0, 40, 0, '', '', '', $societe->default_lang); - $somethingshown=$formfile->numoffiles; + $somethingshown = $formfile->numoffiles; // Show links to link elements $linktoelem = $form->showLinkToObjectBlock($object, null, array('invoice_supplier')); @@ -3232,8 +3232,8 @@ else // List of actions on element include_once DOL_DOCUMENT_ROOT.'/core/class/html.formactions.class.php'; - $formactions=new FormActions($db); - $somethingshown = $formactions->showactions($object, 'invoice_supplier', $socid, 1, 'listaction'.($genallowed?'largetitle':'')); + $formactions = new FormActions($db); + $somethingshown = $formactions->showactions($object, 'invoice_supplier', $socid, 1, 'listaction'.($genallowed ? 'largetitle' : '')); print ''; //print '
    '; @@ -3247,10 +3247,10 @@ else } // Presend form - $modelmail='invoice_supplier_send'; - $defaulttopic='SendBillRef'; + $modelmail = 'invoice_supplier_send'; + $defaulttopic = 'SendBillRef'; $diroutput = $conf->fournisseur->facture->dir_output; - $autocopy='MAIN_MAIL_AUTOCOPY_SUPPLIER_INVOICE_TO'; + $autocopy = 'MAIN_MAIL_AUTOCOPY_SUPPLIER_INVOICE_TO'; $trackid = 'sin'.$object->id; include DOL_DOCUMENT_ROOT.'/core/tpl/card_presend.tpl.php'; diff --git a/htdocs/fourn/facture/contact.php b/htdocs/fourn/facture/contact.php index 18f64d15734..c80dcf31c61 100644 --- a/htdocs/fourn/facture/contact.php +++ b/htdocs/fourn/facture/contact.php @@ -85,7 +85,7 @@ elseif ($action == 'swapstatut' && $user->rights->fournisseur->facture->creer) { if ($object->fetch($id)) { - $result=$object->swapContactStatus(GETPOST('ligne')); + $result = $object->swapContactStatus(GETPOST('ligne')); } else { @@ -114,14 +114,14 @@ elseif ($action == 'deletecontact' && $user->rights->fournisseur->facture->creer * View */ -$title = $langs->trans('SupplierInvoice') . " - " . $langs->trans('ContactsAddresses'); +$title = $langs->trans('SupplierInvoice')." - ".$langs->trans('ContactsAddresses'); $helpurl = "EN:Module_Suppliers_Invoices|FR:Module_Fournisseurs_Factures|ES:Módulo_Facturas_de_proveedores"; llxHeader('', $title, $helpurl); $form = new Form($db); $formcompany = new FormCompany($db); -$contactstatic=new Contact($db); -$userstatic=new User($db); +$contactstatic = new Contact($db); +$userstatic = new User($db); /* *************************************************************************** */ @@ -130,97 +130,97 @@ $userstatic=new User($db); /* */ /* *************************************************************************** */ -if ($id > 0 || ! empty($ref)) +if ($id > 0 || !empty($ref)) { if ($object->fetch($id, $ref) > 0) { $object->fetch_thirdparty(); - $alreadypaid=$object->getSommePaiement(); + $alreadypaid = $object->getSommePaiement(); $head = facturefourn_prepare_head($object); dol_fiche_head($head, 'contact', $langs->trans('SupplierInvoice'), -1, 'bill'); - $linkback = '' . $langs->trans("BackToList") . ''; + $linkback = ''.$langs->trans("BackToList").''; - $morehtmlref='
    '; + $morehtmlref = '
    '; // Ref supplier - $morehtmlref.=$form->editfieldkey("RefSupplier", 'ref_supplier', $object->ref_supplier, $object, 0, 'string', '', 0, 1); - $morehtmlref.=$form->editfieldval("RefSupplier", 'ref_supplier', $object->ref_supplier, $object, 0, 'string', '', null, null, '', 1); + $morehtmlref .= $form->editfieldkey("RefSupplier", 'ref_supplier', $object->ref_supplier, $object, 0, 'string', '', 0, 1); + $morehtmlref .= $form->editfieldval("RefSupplier", 'ref_supplier', $object->ref_supplier, $object, 0, 'string', '', null, null, '', 1); // Thirdparty - $morehtmlref.='
    '.$langs->trans('ThirdParty') . ' : ' . $object->thirdparty->getNomUrl(1); - if (empty($conf->global->MAIN_DISABLE_OTHER_LINK) && $object->thirdparty->id > 0) $morehtmlref.=' ('.$langs->trans("OtherBills").')'; + $morehtmlref .= '
    '.$langs->trans('ThirdParty').' : '.$object->thirdparty->getNomUrl(1); + if (empty($conf->global->MAIN_DISABLE_OTHER_LINK) && $object->thirdparty->id > 0) $morehtmlref .= ' ('.$langs->trans("OtherBills").')'; // Project - if (! empty($conf->projet->enabled)) + if (!empty($conf->projet->enabled)) { $langs->load("projects"); - $morehtmlref.='
    '.$langs->trans('Project') . ' '; + $morehtmlref .= '
    '.$langs->trans('Project').' '; if ($user->rights->facture->creer) { if ($action != 'classify') //$morehtmlref.='' . img_edit($langs->transnoentitiesnoconv('SetProject')) . ' : '; - $morehtmlref.=' : '; + $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.=''; + $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); + $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)) { + if (!empty($object->fk_project)) { $proj = new Project($db); $proj->fetch($object->fk_project); - $morehtmlref.=''; - $morehtmlref.=$proj->ref; - $morehtmlref.=''; + $morehtmlref .= ''; + $morehtmlref .= $proj->ref; + $morehtmlref .= ''; } else { - $morehtmlref.=''; + $morehtmlref .= ''; } } } - $morehtmlref.='
    '; + $morehtmlref .= '
    '; - $object->totalpaye = $alreadypaid; // To give a chance to dol_banner_tab to use already paid amount to show correct status + $object->totalpaye = $alreadypaid; // To give a chance to dol_banner_tab to use already paid amount to show correct status dol_banner_tab($object, 'ref', $linkback, 1, 'ref', 'ref', $morehtmlref); print '
    '; print '
    '; - print ''; + print '
    '; // Type print ''; print ''; print ''; } - if ($societe->localtax2_assuj=="1") //Localtax2 + if ($societe->localtax2_assuj == "1") //Localtax2 { print ''; print ''; diff --git a/htdocs/fourn/facture/document.php b/htdocs/fourn/facture/document.php index 087325e3de0..e2f03a89a20 100644 --- a/htdocs/fourn/facture/document.php +++ b/htdocs/fourn/facture/document.php @@ -57,14 +57,14 @@ if (empty($page) || $page == -1) { $page = 0; } // If $page is not defined, $offset = $conf->liste_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)) { $object->fetch_thirdparty(); - $ref=dol_sanitizeFileName($object->ref); + $ref = dol_sanitizeFileName($object->ref); $upload_dir = $conf->fournisseur->facture->dir_output.'/'.get_exdir($object->id, 2, 0, 0, $object, 'invoice_supplier').$ref; } @@ -73,7 +73,7 @@ if ($object->fetch($id, $ref)) * Actions */ -include_once DOL_DOCUMENT_ROOT . '/core/actions_linkedfiles.inc.php'; +include_once DOL_DOCUMENT_ROOT.'/core/actions_linkedfiles.inc.php'; /* @@ -82,7 +82,7 @@ include_once DOL_DOCUMENT_ROOT . '/core/actions_linkedfiles.inc.php'; $form = new Form($db); -$title = $langs->trans('SupplierInvoice') . " - " . $langs->trans('Documents'); +$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); @@ -93,51 +93,51 @@ if ($object->id > 0) $totalpaye = $object->getSommePaiement(); - $linkback = '' . $langs->trans("BackToList") . ''; + $linkback = ''.$langs->trans("BackToList").''; - $morehtmlref='
    '; + $morehtmlref = '
    '; // Ref supplier - $morehtmlref.=$form->editfieldkey("RefSupplier", 'ref_supplier', $object->ref_supplier, $object, 0, 'string', '', 0, 1); - $morehtmlref.=$form->editfieldval("RefSupplier", 'ref_supplier', $object->ref_supplier, $object, 0, 'string', '', null, null, '', 1); + $morehtmlref .= $form->editfieldkey("RefSupplier", 'ref_supplier', $object->ref_supplier, $object, 0, 'string', '', 0, 1); + $morehtmlref .= $form->editfieldval("RefSupplier", 'ref_supplier', $object->ref_supplier, $object, 0, 'string', '', null, null, '', 1); // Thirdparty - $morehtmlref.='
    '.$langs->trans('ThirdParty') . ' : ' . $object->thirdparty->getNomUrl(1); - if (empty($conf->global->MAIN_DISABLE_OTHER_LINK) && $object->thirdparty->id > 0) $morehtmlref.=' ('.$langs->trans("OtherBills").')'; + $morehtmlref .= '
    '.$langs->trans('ThirdParty').' : '.$object->thirdparty->getNomUrl(1); + if (empty($conf->global->MAIN_DISABLE_OTHER_LINK) && $object->thirdparty->id > 0) $morehtmlref .= ' ('.$langs->trans("OtherBills").')'; // Project - if (! empty($conf->projet->enabled)) + if (!empty($conf->projet->enabled)) { $langs->load("projects"); - $morehtmlref.='
    '.$langs->trans('Project') . ' '; + $morehtmlref .= '
    '.$langs->trans('Project').' '; if ($user->rights->facture->creer) { if ($action != 'classify') //$morehtmlref.='' . img_edit($langs->transnoentitiesnoconv('SetProject')) . ' : '; - $morehtmlref.=' : '; + $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.=''; + $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); + $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)) { + if (!empty($object->fk_project)) { $proj = new Project($db); $proj->fetch($object->fk_project); - $morehtmlref.=''; - $morehtmlref.=$proj->ref; - $morehtmlref.=''; + $morehtmlref .= ''; + $morehtmlref .= $proj->ref; + $morehtmlref .= ''; } else { - $morehtmlref.=''; + $morehtmlref .= ''; } } } - $morehtmlref.='
    '; + $morehtmlref .= '
    '; - $object->totalpaye = $totalpaye; // To give a chance to dol_banner_tab to use already paid amount to show correct status + $object->totalpaye = $totalpaye; // To give a chance to dol_banner_tab to use already paid amount to show correct status dol_banner_tab($object, 'ref', $linkback, 1, 'ref', 'ref', $morehtmlref, '', 0); @@ -145,11 +145,11 @@ if ($object->id > 0) print '
    '; // 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) + $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) { - $totalsize+=$file['size']; + $totalsize += $file['size']; } /* @@ -167,27 +167,27 @@ if ($object->id > 0) print $object->getLibType(); if ($object->type == FactureFournisseur::TYPE_REPLACEMENT) { - $facreplaced=new FactureFournisseur($db); + $facreplaced = new FactureFournisseur($db); $facreplaced->fetch($object->fk_facture_source); print ' ('.$langs->transnoentities("ReplaceInvoice", $facreplaced->getNomUrl(1)).')'; } if ($object->type == FactureFournisseur::TYPE_CREDIT_NOTE) { - $facusing=new FactureFournisseur($db); + $facusing = new FactureFournisseur($db); $facusing->fetch($object->fk_facture_source); print ' ('.$langs->transnoentities("CorrectInvoice", $facusing->getNomUrl(1)).')'; } - $facidavoir=$object->getListIdAvoirFromInvoice(); + $facidavoir = $object->getListIdAvoirFromInvoice(); if (count($facidavoir) > 0) { print ' ('.$langs->transnoentities("InvoiceHasAvoir"); - $i=0; - foreach($facidavoir as $id) + $i = 0; + foreach ($facidavoir as $id) { - if ($i==0) print ' '; + if ($i == 0) print ' '; else print ','; - $facavoir=new FactureFournisseur($db); + $facavoir = new FactureFournisseur($db); $facavoir->fetch($id); print $facavoir->getNomUrl(1); } @@ -214,13 +214,13 @@ 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 ''; print ''; print ''; } - if ($societe->localtax2_assuj=="1") //Localtax2 + if ($societe->localtax2_assuj == "1") //Localtax2 { print ''; print ''; @@ -250,8 +250,8 @@ if ($object->id > 0) $modulepart = 'facture_fournisseur'; $permission = $user->rights->fournisseur->facture->creer; $permtoedit = $user->rights->fournisseur->facture->creer; - $param = '&facid=' . $object->id; - include_once DOL_DOCUMENT_ROOT . '/core/tpl/document_actions_post_headers.tpl.php'; + $param = '&facid='.$object->id; + include_once DOL_DOCUMENT_ROOT.'/core/tpl/document_actions_post_headers.tpl.php'; } else { diff --git a/htdocs/fourn/facture/impayees.php b/htdocs/fourn/facture/impayees.php index 0a10d58764a..4d6e85006c3 100644 --- a/htdocs/fourn/facture/impayees.php +++ b/htdocs/fourn/facture/impayees.php @@ -185,7 +185,7 @@ if ($user->rights->fournisseur->facture->lire) $i = 0; print ''; - print '
    '.$langs->trans('Type').''; print $object->getLibType(); if ($object->type == FactureFournisseur::TYPE_REPLACEMENT) { - $facreplaced=new FactureFournisseur($db); + $facreplaced = new FactureFournisseur($db); $facreplaced->fetch($object->fk_facture_source); print ' ('.$langs->transnoentities("ReplaceInvoice", $facreplaced->getNomUrl(1)).')'; } if ($object->type == FactureFournisseur::TYPE_CREDIT_NOTE) { - $facusing=new FactureFournisseur($db); + $facusing = new FactureFournisseur($db); $facusing->fetch($object->fk_facture_source); print ' ('.$langs->transnoentities("CorrectInvoice", $facusing->getNomUrl(1)).')'; } - $facidavoir=$object->getListIdAvoirFromInvoice(); + $facidavoir = $object->getListIdAvoirFromInvoice(); if (count($facidavoir) > 0) { print ' ('.$langs->transnoentities("InvoiceHasAvoir"); - $i=0; - foreach($facidavoir as $fid) + $i = 0; + foreach ($facidavoir as $fid) { - if ($i==0) print ' '; + if ($i == 0) print ' '; else print ','; - $facavoir=new FactureFournisseur($db); + $facavoir = new FactureFournisseur($db); $facavoir->fetch($fid); print $facavoir->getNomUrl(1); } @@ -228,7 +228,7 @@ if ($id > 0 || ! empty($ref)) } if ($facidnext > 0) { - $facthatreplace=new FactureFournisseur($db); + $facthatreplace = new FactureFournisseur($db); $facthatreplace->fetch($facidnext); print ' ('.$langs->transnoentities("ReplacedByInvoice", $facthatreplace->getNomUrl(1)).')'; } @@ -245,13 +245,13 @@ 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 '
    '.$langs->transcountry("AmountLT1", $societe->country_code).''.price($object->total_localtax1, 1, $langs, 0, -1, -1, $conf->currency).'
    '.$langs->transcountry("AmountLT2", $societe->country_code).''.price($object->total_localtax2, 1, $langs, 0, -1, -1, $conf->currency).'
    '.$langs->transcountry("AmountLT1", $societe->country_code).''.price($object->total_localtax1, 1, $langs, 0, -1, -1, $conf->currency).'
    '.$langs->transcountry("AmountLT2", $societe->country_code).''.price($object->total_localtax2, 1, $langs, 0, -1, -1, $conf->currency).'
    '; + print '
    '; print ''; print_liste_field_titre("Ref", $_SERVER["PHP_SELF"], "f.rowid", "", $param, "", $sortfield, $sortorder); print_liste_field_titre("RefSupplier", $_SERVER["PHP_SELF"], "f.ref_supplier", "", $param, "", $sortfield, $sortorder); diff --git a/htdocs/fourn/facture/info.php b/htdocs/fourn/facture/info.php index 8f10fd94dc4..4b024cef449 100644 --- a/htdocs/fourn/facture/info.php +++ b/htdocs/fourn/facture/info.php @@ -52,7 +52,7 @@ $object = new FactureFournisseur($db); $form = new Form($db); -$title = $langs->trans('SupplierInvoice') . " - " . $langs->trans('Info'); +$title = $langs->trans('SupplierInvoice')." - ".$langs->trans('Info'); $helpurl = "EN:Module_Suppliers_Invoices|FR:Module_Fournisseurs_Factures|ES:Módulo_Facturas_de_proveedores"; llxHeader('', $title, $helpurl); @@ -61,57 +61,57 @@ $object->fetch_thirdparty(); $object->info($object->id); -$alreadypaid=$object->getSommePaiement(); +$alreadypaid = $object->getSommePaiement(); $head = facturefourn_prepare_head($object); -$titre=$langs->trans('SupplierInvoice'); +$titre = $langs->trans('SupplierInvoice'); dol_fiche_head($head, 'info', $langs->trans('SupplierInvoice'), -1, 'bill'); -$linkback = '' . $langs->trans("BackToList") . ''; +$linkback = ''.$langs->trans("BackToList").''; -$morehtmlref='
    '; +$morehtmlref = '
    '; // Ref supplier -$morehtmlref.=$form->editfieldkey("RefSupplier", 'ref_supplier', $object->ref_supplier, $object, 0, 'string', '', 0, 1); -$morehtmlref.=$form->editfieldval("RefSupplier", 'ref_supplier', $object->ref_supplier, $object, 0, 'string', '', null, null, '', 1); +$morehtmlref .= $form->editfieldkey("RefSupplier", 'ref_supplier', $object->ref_supplier, $object, 0, 'string', '', 0, 1); +$morehtmlref .= $form->editfieldval("RefSupplier", 'ref_supplier', $object->ref_supplier, $object, 0, 'string', '', null, null, '', 1); // Thirdparty -$morehtmlref.='
    '.$langs->trans('ThirdParty') . ' : ' . $object->thirdparty->getNomUrl(1); -if (empty($conf->global->MAIN_DISABLE_OTHER_LINK) && $object->thirdparty->id > 0) $morehtmlref.=' ('.$langs->trans("OtherBills").')'; +$morehtmlref .= '
    '.$langs->trans('ThirdParty').' : '.$object->thirdparty->getNomUrl(1); +if (empty($conf->global->MAIN_DISABLE_OTHER_LINK) && $object->thirdparty->id > 0) $morehtmlref .= ' ('.$langs->trans("OtherBills").')'; // Project -if (! empty($conf->projet->enabled)) +if (!empty($conf->projet->enabled)) { $langs->load("projects"); - $morehtmlref.='
    '.$langs->trans('Project') . ' '; + $morehtmlref .= '
    '.$langs->trans('Project').' '; if ($user->rights->facture->creer) { if ($action != 'classify') //$morehtmlref.='' . img_edit($langs->transnoentitiesnoconv('SetProject')) . ' : '; - $morehtmlref.=' : '; + $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->thirdparty->id, $object->fk_project, 'projectid', $maxlength, 0, 1, 0, 1, 0, 0, '', 1); - $morehtmlref.=''; - $morehtmlref.=''; + $morehtmlref .= '
    '; + $morehtmlref .= ''; + $morehtmlref .= ''; + $morehtmlref .= $formproject->select_projects($object->thirdparty->id, $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->thirdparty->id, $object->fk_project, 'none', 0, 0, 0, 1); + $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)) { + if (!empty($object->fk_project)) { $proj = new Project($db); $proj->fetch($object->fk_project); - $morehtmlref.=''; - $morehtmlref.=$proj->ref; - $morehtmlref.=''; + $morehtmlref .= ''; + $morehtmlref .= $proj->ref; + $morehtmlref .= ''; } else { - $morehtmlref.=''; + $morehtmlref .= ''; } } } -$morehtmlref.='
    '; +$morehtmlref .= '
    '; -$object->totalpaye = $alreadypaid; // To give a chance to dol_banner_tab to use already paid amount to show correct status +$object->totalpaye = $alreadypaid; // To give a chance to dol_banner_tab to use already paid amount to show correct status dol_banner_tab($object, 'ref', $linkback, 1, 'ref', 'ref', $morehtmlref, '', 0); diff --git a/htdocs/fourn/facture/list.php b/htdocs/fourn/facture/list.php index db1fba3001a..05965067b55 100644 --- a/htdocs/fourn/facture/list.php +++ b/htdocs/fourn/facture/list.php @@ -49,59 +49,59 @@ if (!$user->rights->fournisseur->facture->lire) accessforbidden(); // Load translation files required by the page $langs->loadLangs(array('products', 'bills', 'companies', 'projects')); -$action=GETPOST('action', 'alpha'); -$massaction=GETPOST('massaction', 'alpha'); -$show_files=GETPOST('show_files', 'int'); -$confirm=GETPOST('confirm', 'alpha'); +$action = GETPOST('action', 'alpha'); +$massaction = GETPOST('massaction', 'alpha'); +$show_files = GETPOST('show_files', 'int'); +$confirm = GETPOST('confirm', 'alpha'); $toselect = GETPOST('toselect', 'array'); $optioncss = GETPOST('optioncss', 'alpha'); -$contextpage=GETPOST('contextpage', 'aZ')?GETPOST('contextpage', 'aZ'):'supplierinvoicelist'; +$contextpage = GETPOST('contextpage', 'aZ') ?GETPOST('contextpage', 'aZ') : 'supplierinvoicelist'; $socid = GETPOST('socid', 'int'); // Security check if ($user->socid > 0) { - $action=''; + $action = ''; $_GET["action"] = ''; $socid = $user->socid; } -$mode=GETPOST("mode"); +$mode = GETPOST("mode"); -$search_all = trim((GETPOST('search_all', 'alphanohtml')!='')?GETPOST('search_all', 'alphanohtml'):GETPOST('sall', 'alphanohtml')); +$search_all = trim((GETPOST('search_all', 'alphanohtml') != '') ?GETPOST('search_all', 'alphanohtml') : GETPOST('sall', 'alphanohtml')); $search_label = GETPOST("search_label", "alpha"); $search_amount_no_tax = GETPOST("search_amount_no_tax", "alpha"); $search_amount_all_tax = GETPOST("search_amount_all_tax", "alpha"); -$search_product_category=GETPOST('search_product_category', 'int'); -$search_ref=GETPOST('sf_ref')?GETPOST('sf_ref', 'alpha'):GETPOST('search_ref', 'alpha'); -$search_refsupplier=GETPOST('search_refsupplier', 'alpha'); -$search_type=GETPOST('search_type', 'int'); -$search_project=GETPOST('search_project', 'alpha'); -$search_company=GETPOST('search_company', 'alpha'); -$search_montant_ht=GETPOST('search_montant_ht', 'alpha'); -$search_montant_vat=GETPOST('search_montant_vat', 'alpha'); -$search_montant_localtax1=GETPOST('search_montant_localtax1', 'alpha'); -$search_montant_localtax2=GETPOST('search_montant_localtax2', 'alpha'); -$search_montant_ttc=GETPOST('search_montant_ttc', 'alpha'); -$search_status=GETPOST('search_status', 'int'); -$search_paymentmode=GETPOST('search_paymentmode', 'int'); -$search_town=GETPOST('search_town', 'alpha'); -$search_zip=GETPOST('search_zip', 'alpha'); -$search_state=trim(GETPOST("search_state")); -$search_country=GETPOST("search_country", 'int'); -$search_type_thirdparty=GETPOST("search_type_thirdparty", 'int'); +$search_product_category = GETPOST('search_product_category', 'int'); +$search_ref = GETPOST('sf_ref') ?GETPOST('sf_ref', 'alpha') : GETPOST('search_ref', 'alpha'); +$search_refsupplier = GETPOST('search_refsupplier', 'alpha'); +$search_type = GETPOST('search_type', 'int'); +$search_project = GETPOST('search_project', 'alpha'); +$search_company = GETPOST('search_company', 'alpha'); +$search_montant_ht = GETPOST('search_montant_ht', 'alpha'); +$search_montant_vat = GETPOST('search_montant_vat', 'alpha'); +$search_montant_localtax1 = GETPOST('search_montant_localtax1', 'alpha'); +$search_montant_localtax2 = GETPOST('search_montant_localtax2', 'alpha'); +$search_montant_ttc = GETPOST('search_montant_ttc', 'alpha'); +$search_status = GETPOST('search_status', 'int'); +$search_paymentmode = GETPOST('search_paymentmode', 'int'); +$search_town = GETPOST('search_town', 'alpha'); +$search_zip = GETPOST('search_zip', 'alpha'); +$search_state = trim(GETPOST("search_state")); +$search_country = GETPOST("search_country", 'int'); +$search_type_thirdparty = GETPOST("search_type_thirdparty", 'int'); $search_user = GETPOST('search_user', 'int'); $search_sale = GETPOST('search_sale', 'int'); -$day = GETPOST('day', 'int'); -$month = GETPOST('month', 'int'); -$year = GETPOST('year', 'int'); -$day_lim = GETPOST('day_lim', 'int'); +$day = GETPOST('day', 'int'); +$month = GETPOST('month', 'int'); +$year = GETPOST('year', 'int'); +$day_lim = GETPOST('day_lim', 'int'); $month_lim = GETPOST('month_lim', 'int'); $year_lim = GETPOST('year_lim', 'int'); $toselect = GETPOST('toselect', 'array'); -$search_btn=GETPOST('button_search', 'alpha'); -$search_remove_btn=GETPOST('button_removefilter', 'alpha'); +$search_btn = GETPOST('button_search', 'alpha'); +$search_remove_btn = GETPOST('button_removefilter', 'alpha'); $option = GETPOST('option'); if ($option == 'late') { @@ -109,20 +109,20 @@ if ($option == 'late') { } $filter = GETPOST('filtre', 'alpha'); -$limit = GETPOST('limit', 'int')?GETPOST('limit', 'int'):$conf->liste_limit; +$limit = GETPOST('limit', 'int') ?GETPOST('limit', 'int') : $conf->liste_limit; $sortfield = GETPOST("sortfield", 'alpha'); $sortorder = GETPOST("sortorder", 'alpha'); -$page=GETPOST("page", 'int'); -if ($page == -1 || $page == null || !empty($search_btn) || !empty($search_remove_btn) || (empty($toselect) && $massaction === '0')) { $page = 0 ; } -$offset = $limit * $page ; +$page = GETPOST("page", 'int'); +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; +$diroutputmassaction = $conf->fournisseur->facture->dir_output.'/temp/massgeneration/'.$user->id; -$now=dol_now(); +$now = dol_now(); // Initialize technical object to manage hooks of page. Note that conf->hooks_modules contains array of hook context $object = new FactureFournisseur($db); @@ -132,7 +132,7 @@ $extrafields = new ExtraFields($db); // fetch optionals attributes and labels $extrafields->fetch_name_optionals_label($object->table_element); -$search_array_options=$extrafields->getOptionalsFromPost($object->table_element, '', 'search_'); +$search_array_options = $extrafields->getOptionalsFromPost($object->table_element, '', 'search_'); // List of fields to search into when doing a "search in all" $fieldstosearchall = array( @@ -142,10 +142,10 @@ $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( +$checkedtypetiers = 0; +$arrayfields = array( 'f.ref'=>array('label'=>$langs->trans("Ref"), 'checked'=>1), 'f.ref_supplier'=>array('label'=>$langs->trans("RefSupplier"), 'checked'=>1), 'f.type'=>array('label'=>$langs->trans("Type"), 'checked'=>0), @@ -162,8 +162,8 @@ $arrayfields=array( 'f.fk_mode_reglement'=>array('label'=>$langs->trans("PaymentMode"), 'checked'=>1), 'f.total_ht'=>array('label'=>$langs->trans("AmountHT"), 'checked'=>1), 'f.total_vat'=>array('label'=>$langs->trans("AmountVAT"), 'checked'=>0), - 'f.total_localtax1'=>array('label'=>$langs->transcountry("AmountLT1", $mysoc->country_code), 'checked'=>0, 'enabled'=>$mysoc->localtax1_assuj=="1"), - 'f.total_localtax2'=>array('label'=>$langs->transcountry("AmountLT2", $mysoc->country_code), 'checked'=>0, 'enabled'=>$mysoc->localtax2_assuj=="1"), + 'f.total_localtax1'=>array('label'=>$langs->transcountry("AmountLT1", $mysoc->country_code), 'checked'=>0, 'enabled'=>$mysoc->localtax1_assuj == "1"), + 'f.total_localtax2'=>array('label'=>$langs->transcountry("AmountLT2", $mysoc->country_code), 'checked'=>0, 'enabled'=>$mysoc->localtax2_assuj == "1"), 'f.total_ttc'=>array('label'=>$langs->trans("AmountTTC"), 'checked'=>0), 'dynamount_payed'=>array('label'=>$langs->trans("Payed"), 'checked'=>0), 'rtp'=>array('label'=>$langs->trans("Rest"), 'checked'=>0), @@ -174,10 +174,10 @@ $arrayfields=array( // 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) + 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], 'checked'=>(($extrafields->attributes[$object->table_element]['list'][$key]<0)?0:1), 'position'=>$extrafields->attributes[$object->table_element]['pos'][$key], 'enabled'=>(abs($extrafields->attributes[$object->table_element]['list'][$key])!=3 && $extrafields->attributes[$object->table_element]['perms'][$key])); + if (!empty($extrafields->attributes[$object->table_element]['list'][$key])) + $arrayfields["ef.".$key] = array('label'=>$extrafields->attributes[$object->table_element]['label'][$key], 'checked'=>(($extrafields->attributes[$object->table_element]['list'][$key] < 0) ? 0 : 1), 'position'=>$extrafields->attributes[$object->table_element]['pos'][$key], 'enabled'=>(abs($extrafields->attributes[$object->table_element]['list'][$key]) != 3 && $extrafields->attributes[$object->table_element]['perms'][$key])); } } $object->fields = dol_sort_array($object->fields, 'position'); @@ -188,11 +188,11 @@ $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 +$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)) @@ -236,6 +236,7 @@ if (empty($reshook)) $search_array_options=array(); $filter=''; $option=''; + $socid=""; } // Mass actions @@ -253,58 +254,58 @@ if (empty($reshook)) * View */ -$form=new Form($db); -$formother=new FormOther($db); +$form = new Form($db); +$formother = new FormOther($db); $formfile = new FormFile($db); -$bankaccountstatic=new Account($db); -$facturestatic=new FactureFournisseur($db); -$formcompany=new FormCompany($db); -$thirdparty=new Societe($db); +$bankaccountstatic = new Account($db); +$facturestatic = new FactureFournisseur($db); +$formcompany = new FormCompany($db); +$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'; -$sql.= " f.rowid as facid, f.ref, f.ref_supplier, f.type, f.datef, f.date_lim_reglement as datelimite, f.fk_mode_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,"; -$sql.= " s.rowid as socid, s.nom as name, s.email, s.town, s.zip, s.fk_pays, s.client, s.fournisseur, s.code_client, s.code_fournisseur, s.code_compta as code_compta_client, s.code_compta_fournisseur,"; -$sql.= " typent.code as typent_code,"; -$sql.= " state.code_departement as state_code, state.nom as state_name,"; -$sql.= " country.code as country_code,"; -$sql.= " p.rowid as project_id, p.ref as project_ref, p.title as project_label"; +$sql .= " f.rowid as facid, f.ref, f.ref_supplier, f.type, f.datef, f.date_lim_reglement as datelimite, f.fk_mode_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,"; +$sql .= " s.rowid as socid, s.nom as name, s.email, s.town, s.zip, s.fk_pays, s.client, s.fournisseur, s.code_client, s.code_fournisseur, s.code_compta as code_compta_client, s.code_compta_fournisseur,"; +$sql .= " typent.code as typent_code,"; +$sql .= " state.code_departement as state_code, state.nom as state_name,"; +$sql .= " country.code as country_code,"; +$sql .= " p.rowid as project_id, p.ref as project_ref, p.title as project_label"; // 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_all) $sql .= ', SUM(pf.amount) as dynamount_payed'; // 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 : ''); +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 : ''); } // 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.'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)"; -$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'; -$sql.= " LEFT JOIN ".MAIN_DB_PREFIX."projet as p ON p.rowid = f.fk_projet"; +$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.'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)"; +$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'; +$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_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 .= ", ".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; +$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) { @@ -315,34 +316,34 @@ 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 == '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_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) $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_status != '' && $search_status >= 0) $sql.= " AND f.fk_statut = ".$db->escape($search_status); +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_status != '' && $search_status >= 0) $sql .= " AND f.fk_statut = ".$db->escape($search_status); if ($search_paymentmode > 0) $sql .= " AND f.fk_mode_reglement = ".$search_paymentmode.""; -$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)."'"; +$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_status != '' && $search_status >= 0) { - $sql.= " AND f.fk_statut = ".$search_status; + $sql .= " AND f.fk_statut = ".$search_status; } if ($filter && $filter != -1) { @@ -350,44 +351,44 @@ if ($filter && $filter != -1) foreach ($aFilter as $fil) { $filt = explode(':', $fil); - $sql .= ' AND ' . $db->escape(trim($filt[0])) . ' = ' . $db->escape(trim($filt[1])); + $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 = " .$db->escape($search_sale); +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='invoice_supplier' AND tc.source='internal' AND ec.element_id = f.rowid AND ec.fk_socpeople = ".$search_user; + $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 include DOL_DOCUMENT_ROOT.'/core/tpl/extrafields_list_search_sql.tpl.php'; // Add where from hooks -$parameters=array(); -$reshook=$hookmanager->executeHooks('printFieldListWhere', $parameters); // Note that $action and $object may have been modified by hook -$sql.=$hookmanager->resPrint; +$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,"; - $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,"; - $sql.= ' s.rowid, s.nom, s.email, s.town, s.zip, s.fk_pays, s.client, s.fournisseur, s.code_client, s.code_fournisseur, s.code_compta, s.code_compta_fournisseur,'; - $sql.= " typent.code,"; - $sql.= " state.code_departement, state.nom,"; - $sql.= ' country.code,'; - $sql.= " p.rowid, p.ref, p.title"; - if (! empty($extrafields->attributes[$object->table_element]['label'])) { + $sql .= " GROUP BY f.rowid, f.ref, f.ref_supplier, f.type, f.datef, f.date_lim_reglement, f.fk_mode_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,"; + $sql .= ' s.rowid, s.nom, s.email, s.town, s.zip, s.fk_pays, s.client, s.fournisseur, s.code_client, s.code_fournisseur, s.code_compta, s.code_compta_fournisseur,'; + $sql .= " typent.code,"; + $sql .= " state.code_departement, state.nom,"; + $sql .= ' country.code,'; + $sql .= " p.rowid, p.ref, p.title"; + if (!empty($extrafields->attributes[$object->table_element]['label'])) { foreach ($extrafields->attributes[$object->table_element]['label'] as $key => $val) { //prevent error with sql_mode=only_full_group_by - $sql.=($extrafields->attributes[$object->table_element]['type'][$key] != 'separate' ? ",ef.".$key : ''); + $sql .= ($extrafields->attributes[$object->table_element]['type'][$key] != 'separate' ? ",ef.".$key : ''); } } } else { - $sql.= natural_search(array_keys($fieldstosearchall), $search_all); + $sql .= natural_search(array_keys($fieldstosearchall), $search_all); } -$sql.= $db->order($sortfield, $sortorder); +$sql .= $db->order($sortfield, $sortorder); $nbtotalofrecords = ''; if (empty($conf->global->MAIN_DISABLE_FULL_SCANLIST)) @@ -401,7 +402,7 @@ if (empty($conf->global->MAIN_DISABLE_FULL_SCANLIST)) } } -$sql.= $db->plimit($limit+1, $offset); +$sql .= $db->plimit($limit + 1, $offset); //print $sql; $resql = $db->query($sql); @@ -409,9 +410,9 @@ if ($resql) { $num = $db->num_rows($resql); - $arrayofselected=is_array($toselect)?$toselect:array(); + $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; @@ -429,51 +430,51 @@ if ($resql) if (empty($search_company)) $search_company = $soc->name; } - $param='&socid='.$socid; - if (! empty($contextpage) && $contextpage != $_SERVER["PHP_SELF"]) $param.='&contextpage='.$contextpage; - if ($limit > 0 && $limit != $conf->liste_limit) $param.='&limit='.$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_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_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=' .$show_files; - if ($option) $param.="&option=".$option; - if ($optioncss != '') $param.='&optioncss='.$optioncss; + $param = '&socid='.$socid; + if (!empty($contextpage) && $contextpage != $_SERVER["PHP_SELF"]) $param .= '&contextpage='.$contextpage; + if ($limit > 0 && $limit != $conf->liste_limit) $param .= '&limit='.$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_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_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='.$show_files; + if ($option) $param .= "&option=".$option; + if ($optioncss != '') $param .= '&optioncss='.$optioncss; // Add $param from extra fields include DOL_DOCUMENT_ROOT.'/core/tpl/extrafields_list_search_param.tpl.php'; // List of mass actions available - $arrayofmassactions = array( + $arrayofmassactions = array( 'validate'=>$langs->trans("Validate"), 'generate_doc'=>$langs->trans("ReGeneratePDF"), //'builddoc'=>$langs->trans("PDFMerge"), //'presend'=>$langs->trans("SendByMail"), ); //if($user->rights->fournisseur->facture->creer) $arrayofmassactions['createbills']=$langs->trans("CreateInvoiceForThisCustomer"); - if ($user->rights->fournisseur->facture->supprimer) $arrayofmassactions['predelete']=''.$langs->trans("Delete"); - if (in_array($massaction, array('presend','predelete','createbills'))) $arrayofmassactions=array(); - $massactionbutton=$form->selectMassAction('', $arrayofmassactions); + if ($user->rights->fournisseur->facture->supprimer) $arrayofmassactions['predelete'] = ''.$langs->trans("Delete"); + if (in_array($massaction, array('presend', 'predelete', 'createbills'))) $arrayofmassactions = array(); + $massactionbutton = $form->selectMassAction('', $arrayofmassactions); - $newcardbutton=''; + $newcardbutton = ''; if ($user->rights->fournisseur->facture->creer) { - $newcardbutton.= dolGetButtonTitle($langs->trans('NewBill'), '', 'fa fa-plus-circle', DOL_URL_ROOT.'/fourn/facture/card.php?action=create'); + $newcardbutton .= dolGetButtonTitle($langs->trans('NewBill'), '', 'fa fa-plus-circle', DOL_URL_ROOT.'/fourn/facture/card.php?action=create'); } $i = 0; @@ -488,12 +489,12 @@ if ($resql) print ''; print ''; - print_barre_liste($langs->trans("BillsSuppliers").($socid?' '.$soc->name:''), $page, $_SERVER["PHP_SELF"], $param, $sortfield, $sortorder, $massactionbutton, $num, $nbtotalofrecords, 'invoicing', 0, $newcardbutton, '', $limit); + print_barre_liste($langs->trans("BillsSuppliers").($socid ? ' '.$soc->name : ''), $page, $_SERVER["PHP_SELF"], $param, $sortfield, $sortorder, $massactionbutton, $num, $nbtotalofrecords, 'invoicing', 0, $newcardbutton, '', $limit); - $topicmail="SendBillRef"; - $modelmail="invoice_supplier_send"; - $objecttmp=new FactureFournisseur($db); - $trackid='sinv'.$object->id; + $topicmail = "SendBillRef"; + $modelmail = "invoice_supplier_send"; + $objecttmp = new FactureFournisseur($db); + $trackid = 'sinv'.$object->id; include DOL_DOCUMENT_ROOT.'/core/tpl/massactions_pre.tpl.php'; if ($massaction == 'createbills') @@ -538,40 +539,40 @@ if ($resql) if ($search_all) { - foreach($fieldstosearchall as $key => $val) $fieldstosearchall[$key]=$langs->trans($val); - print '
    '.$langs->trans("FilterOnInto", $search_all) . join(', ', $fieldstosearchall).'
    '; + foreach ($fieldstosearchall as $key => $val) $fieldstosearchall[$key] = $langs->trans($val); + print '
    '.$langs->trans("FilterOnInto", $search_all).join(', ', $fieldstosearchall).'
    '; } // If the user can view prospects other than his' - $moreforfilter=''; + $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.='
    '; + $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 .= '
    '; + $moreforfilter .= $langs->trans('LinkedToSpecificUsers').': '; + $moreforfilter .= $form->select_dolusers($search_user, 'search_user', 1, '', 0, '', '', 0, 0, 0, '', 0, '', 'maxwidth200'); + $moreforfilter .= '
    '; } // If the user can view prospects other than his' 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'). ': '; + $moreforfilter .= '
    '; + $moreforfilter .= $langs->trans('IncludingProductWithTag').': '; $cate_arbo = $form->select_all_categories(Categorie::TYPE_PRODUCT, null, 'parent', null, null, 1); - $moreforfilter.=$form->selectarray('search_product_category', $cate_arbo, $search_product_category, 1, 0, 0, '', 0, 0, 0, 0, 'maxwidth300', 1); - $moreforfilter.='
    '; + $moreforfilter .= $form->selectarray('search_product_category', $cate_arbo, $search_product_category, 1, 0, 0, '', 0, 0, 0, 0, 'maxwidth300', 1); + $moreforfilter .= '
    '; } - $parameters=array(); - $reshook=$hookmanager->executeHooks('printFieldPreListTitle', $parameters); // Note that $action and $object may have been modified by hook + $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; @@ -582,34 +583,34 @@ if ($resql) print ''; } - $varpage=empty($contextpage)?$_SERVER["PHP_SELF"]:$contextpage; - $selectedfields=$form->multiSelectArrayWithCheckbox('selectedfields', $arrayfields, $varpage); // This also change content of $arrayfields - if ($massactionbutton) $selectedfields.=$form->showCheckAddButtons('checkforselect', 1); + $varpage = empty($contextpage) ? $_SERVER["PHP_SELF"] : $contextpage; + $selectedfields = $form->multiSelectArrayWithCheckbox('selectedfields', $arrayfields, $varpage); // This also change content of $arrayfields + if ($massactionbutton) $selectedfields .= $form->showCheckAddButtons('checkforselect', 1); print '
    '; - print '
    '."\n"; + print '
    '."\n"; // Line for filters print ''; // Ref - if (! empty($arrayfields['f.ref']['checked'])) + if (!empty($arrayfields['f.ref']['checked'])) { print ''; } // Ref supplier - if (! empty($arrayfields['f.ref_supplier']['checked'])) + if (!empty($arrayfields['f.ref_supplier']['checked'])) { print ''; } // Type - if (! empty($arrayfields['f.type']['checked'])) + if (!empty($arrayfields['f.type']['checked'])) { print ''; } // Label - if (! empty($arrayfields['f.label']['checked'])) + if (!empty($arrayfields['f.label']['checked'])) { print ''; } // Date invoice - if (! empty($arrayfields['f.datef']['checked'])) + if (!empty($arrayfields['f.datef']['checked'])) { print ''; } // Date due - if (! empty($arrayfields['f.date_lim_reglement']['checked'])) + if (!empty($arrayfields['f.date_lim_reglement']['checked'])) { print ''; } // Project - if (! empty($arrayfields['p.ref']['checked'])) + if (!empty($arrayfields['p.ref']['checked'])) { print ''; } // Thirpdarty - if (! empty($arrayfields['s.nom']['checked'])) + if (!empty($arrayfields['s.nom']['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 ''; } - if (! empty($arrayfields['f.total_ht']['checked'])) + if (!empty($arrayfields['f.total_ht']['checked'])) { // Amount without tax print ''; } - if (! empty($arrayfields['f.total_vat']['checked'])) + if (!empty($arrayfields['f.total_vat']['checked'])) { // Amount vat print ''; } - if (! empty($arrayfields['f.total_localtax1']['checked'])) + if (!empty($arrayfields['f.total_localtax1']['checked'])) { // Amount tax 1 print ''; } - if (! empty($arrayfields['f.total_localtax2']['checked'])) + if (!empty($arrayfields['f.total_localtax2']['checked'])) { // Amount tax 2 print ''; } - if (! empty($arrayfields['f.total_ttc']['checked'])) + if (!empty($arrayfields['f.total_ttc']['checked'])) { // Amount inc tac 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 ''; @@ -742,102 +743,102 @@ if ($resql) include DOL_DOCUMENT_ROOT.'/core/tpl/extrafields_list_search_input.tpl.php'; // Fields from hook - $parameters=array('arrayfields'=>$arrayfields); - $reshook=$hookmanager->executeHooks('printFieldListOption', $parameters); // Note that $action and $object may have been modified by hook + $parameters = array('arrayfields'=>$arrayfields); + $reshook = $hookmanager->executeHooks('printFieldListOption', $parameters); // Note that $action and $object may have been modified by hook print $hookmanager->resPrint; // Date creation - if (! empty($arrayfields['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['f.fk_statut']['checked'])) + if (!empty($arrayfields['f.fk_statut']['checked'])) { print ''; } // Action column print ''; print "\n"; print ''; - 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_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['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.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_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['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 '); // 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 + $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 "\n"; - $facturestatic=new FactureFournisseur($db); - $supplierstatic=new Fournisseur($db); - $projectstatic=new Project($db); + $facturestatic = new FactureFournisseur($db); + $supplierstatic = new Fournisseur($db); + $projectstatic = new Project($db); if ($num > 0) { - $i=0; - $totalarray=array(); + $i = 0; + $totalarray = array(); while ($i < min($num, $limit)) { $obj = $db->fetch_object($resql); - $datelimit=$db->jdate($obj->datelimite); - $facturestatic->id=$obj->facid; - $facturestatic->ref=$obj->ref; - $facturestatic->type=$obj->type; - $facturestatic->ref_supplier=$obj->ref_supplier; + $datelimit = $db->jdate($obj->datelimite); + $facturestatic->id = $obj->facid; + $facturestatic->ref = $obj->ref; + $facturestatic->type = $obj->type; + $facturestatic->ref_supplier = $obj->ref_supplier; $facturestatic->date_echeance = $db->jdate($obj->datelimite); $facturestatic->statut = $obj->fk_statut; - $thirdparty->id=$obj->socid; - $thirdparty->name=$obj->name; - $thirdparty->client=$obj->client; - $thirdparty->fournisseur=$obj->fournisseur; - $thirdparty->code_client=$obj->code_client; - $thirdparty->code_compta_client=$obj->code_compta_client; - $thirdparty->code_fournisseur=$obj->code_fournisseur; - $thirdparty->code_compta_fournisseur=$obj->code_compta_fournisseur; - $thirdparty->email=$obj->email; - $thirdparty->country_code=$obj->country_code; + $thirdparty->id = $obj->socid; + $thirdparty->name = $obj->name; + $thirdparty->client = $obj->client; + $thirdparty->fournisseur = $obj->fournisseur; + $thirdparty->code_client = $obj->code_client; + $thirdparty->code_compta_client = $obj->code_compta_client; + $thirdparty->code_fournisseur = $obj->code_fournisseur; + $thirdparty->code_compta_fournisseur = $obj->code_compta_fournisseur; + $thirdparty->email = $obj->email; + $thirdparty->country_code = $obj->country_code; $paiement = $facturestatic->getSommePaiement(); $totalcreditnotes = $facturestatic->getSumCreditNotesUsed(); @@ -846,14 +847,14 @@ if ($resql) $remaintopay = $obj->total_ttc - $totalpay; //If invoice has been converted and the conversion has been used, we dont have remain to pay on invoice - if($facturestatic->type == FactureFournisseur::TYPE_CREDIT_NOTE) { - if($facturestatic->isCreditNoteUsed()){ - $remaintopay=-$facturestatic->getSumFromThisCreditNotesNotUsed(); + if ($facturestatic->type == FactureFournisseur::TYPE_CREDIT_NOTE) { + if ($facturestatic->isCreditNoteUsed()) { + $remaintopay = -$facturestatic->getSumFromThisCreditNotesNotUsed(); } } print ''; - if (! empty($arrayfields['f.ref']['checked'])) + if (!empty($arrayfields['f.ref']['checked'])) { print ''; // Other picto tool print '
    '; print ''; print ''; print ''; print ''; - $listtype=array( + $listtype = array( FactureFournisseur::TYPE_STANDARD=>$langs->trans("InvoiceStandard"), FactureFournisseur::TYPE_REPLACEMENT=>$langs->trans("InvoiceReplacement"), FactureFournisseur::TYPE_CREDIT_NOTE=>$langs->trans("InvoiceAvoir"), @@ -626,114 +627,114 @@ if ($resql) 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($year?$year:-1, 'year', 1, 20, 5); + $formother->select_year($year ? $year : -1, 'year', 1, 20, 5); 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($year_lim?$year_lim:-1, 'year_lim', 1, 20, 5); - print '
    '.$langs->trans("Late"); + $formother->select_year($year_lim ? $year_lim : -1, 'year_lim', 1, 20, 5); + print '
    '.$langs->trans("Late"); 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, 0, 0, 0, '', 0, 0, 0, (empty($conf->global->SOCIETE_SORT_ON_TYPEENT)?'ASC':$conf->global->SOCIETE_SORT_ON_TYPEENT)); + print $form->selectarray("search_type_thirdparty", $formcompany->typent_array(0), $search_type_thirdparty, 0, 0, 0, '', 0, 0, 0, (empty($conf->global->SOCIETE_SORT_ON_TYPEENT) ? 'ASC' : $conf->global->SOCIETE_SORT_ON_TYPEENT)); print ''; $form->select_types_paiements($search_paymentmode, 'search_paymentmode', '', 0, 1, 1, 10); print ''; print ''; print ''; print ''; print ''; print ''; print ''; print ''; print ''; print ''; print ''; print ''; print ''; print ''; print ''; - $liststatus=array('0'=>$langs->trans("Draft"),'1'=>$langs->trans("Unpaid"), '2'=>$langs->trans("Paid")); + $liststatus = array('0'=>$langs->trans("Draft"), '1'=>$langs->trans("Unpaid"), '2'=>$langs->trans("Paid")); print $form->selectarray('search_status', $liststatus, $search_status, 1); print ''; - $searchpicto=$form->showFilterButtons(); + $searchpicto = $form->showFilterButtons(); print $searchpicto; print '
    '; @@ -867,54 +868,54 @@ if ($resql) //print ''; - $filename=dol_sanitizeFileName($obj->ref); - $filedir=$conf->fournisseur->facture->dir_output.'/'.get_exdir($obj->facid, 2, 0, 0, $facturestatic, 'invoice_supplier').dol_sanitizeFileName($obj->ref); + $filename = dol_sanitizeFileName($obj->ref); + $filedir = $conf->fournisseur->facture->dir_output.'/'.get_exdir($obj->facid, 2, 0, 0, $facturestatic, 'invoice_supplier').dol_sanitizeFileName($obj->ref); $subdir = get_exdir($obj->facid, 2, 0, 0, $facturestatic, 'invoice_supplier').dol_sanitizeFileName($obj->ref); print $formfile->getDocumentsLink('facture_fournisseur', $subdir, $filedir); print '
    '; print "
    '; print $obj->ref_supplier; print ''; print $facturestatic->getLibType(); print "'; print $obj->label; print ''; print dol_print_date($db->jdate($obj->datef), 'day'); print ''.dol_print_date($datelimit, 'day'); if ($facturestatic->hasDelay()) @@ -1059,45 +1060,45 @@ if ($resql) // Extra fields include DOL_DOCUMENT_ROOT.'/core/tpl/extrafields_list_print_fields.tpl.php'; // Fields from hook - $parameters=array('arrayfields'=>$arrayfields, 'obj'=>$obj); - $reshook=$hookmanager->executeHooks('printFieldListValue', $parameters); // Note that $action and $object may have been modified by hook + $parameters = array('arrayfields'=>$arrayfields, 'obj'=>$obj); + $reshook = $hookmanager->executeHooks('printFieldListValue', $parameters); // Note that $action and $object may have been modified by hook print $hookmanager->resPrint; // Date creation - if (! empty($arrayfields['f.datec']['checked'])) + if (!empty($arrayfields['f.datec']['checked'])) { 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 ''; // TODO $paiement is not yet defined print $facturestatic->LibStatut($obj->paye, $obj->fk_statut, 5, $paiement, $obj->type); print "'; if ($massactionbutton || $massaction) // If we are in select mode (massactionbutton defined) or if we have already selected and sent an action ($massaction) defined { - $selected=0; - if (in_array($obj->facid, $arrayofselected)) $selected=1; - print ''; + $selected = 0; + if (in_array($obj->facid, $arrayofselected)) $selected = 1; + print ''; } print '
    \n"; @@ -1119,16 +1120,16 @@ if ($resql) print "\n"; - $hidegeneratedfilelistifempty=1; - if ($massaction == 'builddoc' || $action == 'remove_file' || $show_files) $hidegeneratedfilelistifempty=0; + $hidegeneratedfilelistifempty = 1; + if ($massaction == 'builddoc' || $action == 'remove_file' || $show_files) $hidegeneratedfilelistifempty = 0; // Show list of available documents - $urlsource=$_SERVER['PHP_SELF'].'?sortfield='.$sortfield.'&sortorder='.$sortorder; - $urlsource.=str_replace('&', '&', $param); + $urlsource = $_SERVER['PHP_SELF'].'?sortfield='.$sortfield.'&sortorder='.$sortorder; + $urlsource .= str_replace('&', '&', $param); - $filedir=$diroutputmassaction; - $genallowed=$user->rights->facture->lire; - $delallowed=$user->rights->facture->creer; + $filedir = $diroutputmassaction; + $genallowed = $user->rights->facture->lire; + $delallowed = $user->rights->facture->creer; $title = ''; print $formfile->showdocuments('massfilesarea_supplier_invoice', '', $filedir, $urlsource, 0, $delallowed, '', 1, 1, 0, 48, 1, $param, $title, '', '', '', null, $hidegeneratedfilelistifempty); diff --git a/htdocs/fourn/facture/note.php b/htdocs/fourn/facture/note.php index a7200495e96..53aa47ee760 100644 --- a/htdocs/fourn/facture/note.php +++ b/htdocs/fourn/facture/note.php @@ -29,8 +29,8 @@ require '../../main.inc.php'; require_once DOL_DOCUMENT_ROOT.'/core/lib/fourn.lib.php'; require_once DOL_DOCUMENT_ROOT.'/fourn/class/fournisseur.class.php'; require_once DOL_DOCUMENT_ROOT.'/fourn/class/fournisseur.facture.class.php'; -if (! empty($conf->projet->enabled)) { - require_once DOL_DOCUMENT_ROOT . '/projet/class/project.class.php'; +if (!empty($conf->projet->enabled)) { + require_once DOL_DOCUMENT_ROOT.'/projet/class/project.class.php'; } $langs->loadLangs(array("bills", "companies")); @@ -70,7 +70,7 @@ if ($action == 'setlabel' && $user->rights->fournisseur->facture->creer) $form = new Form($db); -$title = $langs->trans('SupplierInvoice') . " - " . $langs->trans('Notes'); +$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); @@ -138,34 +138,34 @@ if ($object->id > 0) print '
    '; print '
    '; - print ''; + print '
    '; // Type print ''; print ''; print ''; } - if ($societe->localtax2_assuj=="1") //Localtax2 + if ($societe->localtax2_assuj == "1") //Localtax2 { print ''; print ''; @@ -209,7 +209,7 @@ if ($object->id > 0) print '
    '; print '
    '; - $cssclass="titlefield"; + $cssclass = "titlefield"; include DOL_DOCUMENT_ROOT.'/core/tpl/notes.tpl.php'; dol_fiche_end(); diff --git a/htdocs/fourn/facture/paiement.php b/htdocs/fourn/facture/paiement.php index eb7c8af3ef0..eb0beab54f4 100644 --- a/htdocs/fourn/facture/paiement.php +++ b/htdocs/fourn/facture/paiement.php @@ -47,19 +47,19 @@ $optioncss = GETPOST('optioncss', 'alpha'); $facid = GETPOST('facid', 'int'); $socid = GETPOST('socid', 'int'); -$accountid = GETPOST('accountid', 'int'); -$day = GETPOST('day', 'int'); +$accountid = GETPOST('accountid', 'int'); +$day = GETPOST('day', 'int'); $month = GETPOST('month', 'int'); -$year = GETPOST('year', 'int'); +$year = GETPOST('year', 'int'); -$search_ref=GETPOST("search_ref", "alpha"); -$search_account=GETPOST("search_account", "int"); -$search_paymenttype=GETPOST("search_paymenttype"); -$search_amount=GETPOST("search_amount", 'alpha'); // alpha because we must be able to search on "< x" -$search_company=GETPOST("search_company", 'alpha'); -$search_payment_num=GETPOST('search_payment_num', 'alpha'); +$search_ref = GETPOST("search_ref", "alpha"); +$search_account = GETPOST("search_account", "int"); +$search_paymenttype = GETPOST("search_paymenttype"); +$search_amount = GETPOST("search_amount", 'alpha'); // alpha because we must be able to search on "< x" +$search_company = GETPOST("search_company", 'alpha'); +$search_payment_num = GETPOST('search_payment_num', 'alpha'); -$limit = GETPOST('limit', 'int')?GETPOST('limit', 'int'):$conf->liste_limit; +$limit = GETPOST('limit', 'int') ?GETPOST('limit', 'int') : $conf->liste_limit; $sortfield = GETPOST("sortfield", 'alpha'); $sortorder = GETPOST("sortorder", 'alpha'); $page = GETPOST("page", 'int'); @@ -67,15 +67,15 @@ if (empty($page) || $page == -1) { $page = 0; } // If $page is not defined, $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(); -$addwarning=0; +$amountsresttopay = array(); +$addwarning = 0; -$multicurrency_amounts=array(); -$multicurrency_amountsresttopay=array(); +$multicurrency_amounts = array(); +$multicurrency_amountsresttopay = array(); // Security check if ($user->socid > 0) @@ -94,7 +94,7 @@ $extrafields->fetch_name_optionals_label($object->table_element); $search_array_options = $extrafields->getOptionalsFromPost($object->table_element, '', 'search_'); -$arrayfields=array(); +$arrayfields = array(); @@ -104,25 +104,25 @@ $arrayfields=array(); 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=""; - $search_paymenttype=""; - $search_payment_num=""; - $search_company=""; - $day=''; - $year=''; - $month=''; - $search_array_options=array(); + $search_ref = ""; + $search_account = ""; + $search_amount = ""; + $search_paymenttype = ""; + $search_payment_num = ""; + $search_company = ""; + $day = ''; + $year = ''; + $month = ''; + $search_array_options = array(); } -$parameters=array('socid'=>$socid); -$reshook=$hookmanager->executeHooks('doActions', $parameters, $object, $action); // Note that $action and $object may have been modified by some hooks +$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 ($action == 'add_paiement' || ($action == 'confirm_paiement' && $confirm=='yes')) + if ($action == 'add_paiement' || ($action == 'confirm_paiement' && $confirm == 'yes')) { $error = 0; @@ -132,7 +132,7 @@ if (empty($reshook)) $atleastonepaymentnotnull = 0; // Generate payment array and check if there is payment higher than invoice and payment date before invoice date - $tmpinvoice=new FactureFournisseur($db); + $tmpinvoice = new FactureFournisseur($db); foreach ($_POST as $key => $value) { if (substr($key, 0, 7) == 'amount_') @@ -140,16 +140,16 @@ if (empty($reshook)) $cursorfacid = substr($key, 7); $amounts[$cursorfacid] = price2num(trim(GETPOST($key))); $totalpayment = $totalpayment + $amounts[$cursorfacid]; - if (! empty($amounts[$cursorfacid])) $atleastonepaymentnotnull++; - $result=$tmpinvoice->fetch($cursorfacid); + if (!empty($amounts[$cursorfacid])) $atleastonepaymentnotnull++; + $result = $tmpinvoice->fetch($cursorfacid); if ($result <= 0) dol_print_error($db); - $amountsresttopay[$cursorfacid]=price2num($tmpinvoice->total_ttc - $tmpinvoice->getSommePaiement()); + $amountsresttopay[$cursorfacid] = price2num($tmpinvoice->total_ttc - $tmpinvoice->getSommePaiement()); if ($amounts[$cursorfacid]) { // Check amount if ($amounts[$cursorfacid] && (abs($amounts[$cursorfacid]) > abs($amountsresttopay[$cursorfacid]))) { - $addwarning=1; + $addwarning = 1; $formquestion['text'] = img_warning($langs->trans("PaymentHigherThanReminderToPaySupplier")).' '.$langs->trans("HelpPaymentHigherThanReminderToPaySupplier"); } // Check date @@ -161,23 +161,23 @@ if (empty($reshook)) } } - $formquestion[$i++]=array('type' => 'hidden','name' => $key, 'value' => $_POST[$key]); + $formquestion[$i++] = array('type' => 'hidden', 'name' => $key, 'value' => $_POST[$key]); } elseif (substr($key, 0, 21) == 'multicurrency_amount_') { $cursorfacid = substr($key, 21); $multicurrency_amounts[$cursorfacid] = price2num(trim(GETPOST($key))); $multicurrency_totalpayment += $multicurrency_amounts[$cursorfacid]; - if (! empty($multicurrency_amounts[$cursorfacid])) $atleastonepaymentnotnull++; - $result=$tmpinvoice->fetch($cursorfacid); + if (!empty($multicurrency_amounts[$cursorfacid])) $atleastonepaymentnotnull++; + $result = $tmpinvoice->fetch($cursorfacid); if ($result <= 0) dol_print_error($db); - $multicurrency_amountsresttopay[$cursorfacid]=price2num($tmpinvoice->total_ttc - $tmpinvoice->getSommePaiement(1)); + $multicurrency_amountsresttopay[$cursorfacid] = price2num($tmpinvoice->total_ttc - $tmpinvoice->getSommePaiement(1)); if ($multicurrency_amounts[$cursorfacid]) { // Check amount if ($multicurrency_amounts[$cursorfacid] && (abs($multicurrency_amounts[$cursorfacid]) > abs($multicurrency_amountsresttopay[$cursorfacid]))) { - $addwarning=1; + $addwarning = 1; $formquestion['text'] = img_warning($langs->trans("PaymentHigherThanReminderToPaySupplier")).' '.$langs->trans("HelpPaymentHigherThanReminderToPaySupplier"); } // Check date @@ -189,7 +189,7 @@ if (empty($reshook)) } } - $formquestion[$i++]=array('type' => 'hidden','name' => $key, 'value' => GETPOST($key, 'int')); + $formquestion[$i++] = array('type' => 'hidden', 'name' => $key, 'value' => GETPOST($key, 'int')); } } @@ -200,7 +200,7 @@ if (empty($reshook)) $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) @@ -248,7 +248,7 @@ if (empty($reshook)) */ if ($action == 'confirm_paiement' && $confirm == 'yes') { - $error=0; + $error = 0; $datepaye = dol_mktime(12, 0, 0, GETPOST('remonth', 'int'), GETPOST('reday', 'int'), GETPOST('reyear', 'int')); @@ -279,7 +279,7 @@ if (empty($reshook)) //var_dump($multicurrency_amounts); //exit; - if (! $error) + if (!$error) { $db->begin(); @@ -289,14 +289,14 @@ if (empty($reshook)) // Creation de la ligne paiement $paiement = new PaiementFourn($db); $paiement->datepaye = $datepaye; - $paiement->amounts = $amounts; // Array of amounts + $paiement->amounts = $amounts; // Array of amounts $paiement->multicurrency_amounts = $multicurrency_amounts; $paiement->paiementid = $_POST['paiementid']; $paiement->num_paiement = $_POST['num_paiement']; $paiement->note = $_POST['comment']; - if (! $error) + if (!$error) { - $paiement_id = $paiement->create($user, (GETPOST('closepaidinvoices')=='on'?1:0), $thirdparty); + $paiement_id = $paiement->create($user, (GETPOST('closepaidinvoices') == 'on' ? 1 : 0), $thirdparty); if ($paiement_id < 0) { setEventMessages($paiement->error, $paiement->errors, 'errors'); @@ -304,9 +304,9 @@ if (empty($reshook)) } } - if (! $error) + if (!$error) { - $result=$paiement->addPaymentToBank($user, 'payment_supplier', '(SupplierInvoicePayment)', $accountid, '', ''); + $result = $paiement->addPaymentToBank($user, 'payment_supplier', '(SupplierInvoicePayment)', $accountid, '', ''); if ($result < 0) { setEventMessages($paiement->error, $paiement->errors, 'errors'); @@ -314,19 +314,19 @@ if (empty($reshook)) } } - 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; + $invoiceid = 0; 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 ($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; @@ -347,10 +347,10 @@ if (empty($reshook)) * View */ -$form=new Form($db); -$formother=new FormOther($db); +$form = new Form($db); +$formother = new FormOther($db); -$supplierstatic=new Societe($db); +$supplierstatic = new Societe($db); $invoicesupplierstatic = new FactureFournisseur($db); llxHeader('', $langs->trans('ListPayment')); @@ -360,17 +360,17 @@ if ($action == 'create' || $action == 'confirm_paiement' || $action == 'add_paie $object = new FactureFournisseur($db); $result = $object->fetch($facid); - $datefacture=dol_mktime(12, 0, 0, GETPOST('remonth', 'int'), GETPOST('reday', 'int'), GETPOST('reyear', 'int')); - $dateinvoice=($datefacture==''?(empty($conf->global->MAIN_AUTOFILL_DATE)?-1:''):$datefacture); + $datefacture = dol_mktime(12, 0, 0, GETPOST('remonth', 'int'), GETPOST('reday', 'int'), GETPOST('reyear', 'int')); + $dateinvoice = ($datefacture == '' ? (empty($conf->global->MAIN_AUTOFILL_DATE) ?-1 : '') : $datefacture); $sql = 'SELECT s.nom as name, s.rowid as socid,'; - $sql.= ' f.rowid, f.ref, f.ref_supplier, f.amount, f.total_ttc as total, f.fk_mode_reglement, f.fk_account'; + $sql .= ' f.rowid, f.ref, f.ref_supplier, f.amount, 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 "; - $sql.= ' FROM '.MAIN_DB_PREFIX.'societe as s, '.MAIN_DB_PREFIX.'facture_fourn as f'; + $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"; - $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; + $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; $resql = $db->query($sql); if ($resql) { @@ -383,7 +383,7 @@ if ($action == 'create' || $action == 'confirm_paiement' || $action == 'add_paie 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".''; dolibarr_install_syslog("- check: end"); -pFooter(1); // Never display next button +pFooter(1); // Never display next button diff --git a/htdocs/install/doctemplates/contracts/index.html b/htdocs/install/doctemplates/contracts/index.html deleted file mode 100644 index e69de29bb2d..00000000000 diff --git a/htdocs/install/doctemplates/invoices/index.html b/htdocs/install/doctemplates/invoices/index.html deleted file mode 100644 index e69de29bb2d..00000000000 diff --git a/htdocs/install/doctemplates/orders/index.html b/htdocs/install/doctemplates/orders/index.html deleted file mode 100644 index e69de29bb2d..00000000000 diff --git a/htdocs/install/doctemplates/products/index.html b/htdocs/install/doctemplates/products/index.html deleted file mode 100644 index e69de29bb2d..00000000000 diff --git a/htdocs/install/doctemplates/projects/index.html b/htdocs/install/doctemplates/projects/index.html deleted file mode 100644 index e69de29bb2d..00000000000 diff --git a/htdocs/install/doctemplates/proposals/index.html b/htdocs/install/doctemplates/proposals/index.html deleted file mode 100644 index e69de29bb2d..00000000000 diff --git a/htdocs/install/doctemplates/shipments/index.html b/htdocs/install/doctemplates/shipments/index.html deleted file mode 100644 index e69de29bb2d..00000000000 diff --git a/htdocs/install/doctemplates/supplier_proposals/index.html b/htdocs/install/doctemplates/supplier_proposals/index.html deleted file mode 100644 index e69de29bb2d..00000000000 diff --git a/htdocs/install/doctemplates/tasks/index.html b/htdocs/install/doctemplates/tasks/index.html deleted file mode 100644 index e69de29bb2d..00000000000 diff --git a/htdocs/install/doctemplates/thirdparties/index.html b/htdocs/install/doctemplates/thirdparties/index.html deleted file mode 100644 index e69de29bb2d..00000000000 diff --git a/htdocs/install/doctemplates/usergroups/index.html b/htdocs/install/doctemplates/usergroups/index.html deleted file mode 100644 index e69de29bb2d..00000000000 diff --git a/htdocs/install/doctemplates/users/index.html b/htdocs/install/doctemplates/users/index.html deleted file mode 100644 index e69de29bb2d..00000000000 diff --git a/htdocs/install/doctemplates/websites/website_template-corporate.zip b/htdocs/install/doctemplates/websites/website_template-corporate.zip index e86e11df288..01d984562cc 100644 Binary files a/htdocs/install/doctemplates/websites/website_template-corporate.zip and b/htdocs/install/doctemplates/websites/website_template-corporate.zip differ diff --git a/htdocs/install/doctemplates/websites/website_template-stellar.jpg b/htdocs/install/doctemplates/websites/website_template-stellar.jpg index 66867384b58..9e8251b1deb 100644 Binary files a/htdocs/install/doctemplates/websites/website_template-stellar.jpg and b/htdocs/install/doctemplates/websites/website_template-stellar.jpg differ diff --git a/htdocs/install/doctemplates/websites/website_template-stellar.zip b/htdocs/install/doctemplates/websites/website_template-stellar.zip index b4d55a83e73..750d39d36d9 100644 Binary files a/htdocs/install/doctemplates/websites/website_template-stellar.zip and b/htdocs/install/doctemplates/websites/website_template-stellar.zip differ diff --git a/htdocs/install/mysql/data/llx_c_action_trigger.sql b/htdocs/install/mysql/data/llx_c_action_trigger.sql index 406bfe88dbc..85360478500 100644 --- a/htdocs/install/mysql/data/llx_c_action_trigger.sql +++ b/htdocs/install/mysql/data/llx_c_action_trigger.sql @@ -119,14 +119,15 @@ insert into llx_c_action_trigger (code,label,description,elementtype,rang) value insert into llx_c_action_trigger (code,label,description,elementtype,rang) values ('FICHINTER_MODIFY','Intervention modified','Executed when a intervention is modified','ficheinter',19); insert into llx_c_action_trigger (code,label,description,elementtype,rang) values ('PROJECT_CREATE','Project creation','Executed when a project is created','project',140); insert into llx_c_action_trigger (code,label,description,elementtype,rang) values ('PROJECT_MODIFY','Project modified','Executed when a project is modified','project',142); -insert into llx_c_action_trigger (code,label,description,elementtype,rang) values ('BOM_VALIDATE','BOM validated','Executed when a BOM is validated','bom',400); -insert into llx_c_action_trigger (code,label,description,elementtype,rang) values ('BOM_UNVALIDATE','BOM unvalidated','Executed when a BOM is unvalidated','bom',401); -insert into llx_c_action_trigger (code,label,description,elementtype,rang) values ('BOM_CLOSE','BOM disabled','Executed when a BOM is disabled','bom',402); -insert into llx_c_action_trigger (code,label,description,elementtype,rang) values ('BOM_REOPEN','BOM reopen','Executed when a BOM is re-open','bom',403); -insert into llx_c_action_trigger (code,label,description,elementtype,rang) values ('BOM_DELETE','BOM deleted','Executed when a BOM deleted','bom',404); -insert into llx_c_action_trigger (code,label,description,elementtype,rang) values ('MO_VALIDATE','MO validated','Executed when a MO is validated','bom',410); -insert into llx_c_action_trigger (code,label,description,elementtype,rang) values ('MO_PRODUCED','MO disabled','Executed when a MO is produced','bom',411); -insert into llx_c_action_trigger (code,label,description,elementtype,rang) values ('MO_DELETE','MO deleted','Executed when a MO is deleted','bom',412); +insert into llx_c_action_trigger (code,label,description,elementtype,rang) values ('BOM_VALIDATE','BOM validated','Executed when a BOM is validated','bom',650); +insert into llx_c_action_trigger (code,label,description,elementtype,rang) values ('BOM_UNVALIDATE','BOM unvalidated','Executed when a BOM is unvalidated','bom',651); +insert into llx_c_action_trigger (code,label,description,elementtype,rang) values ('BOM_CLOSE','BOM disabled','Executed when a BOM is disabled','bom',652); +insert into llx_c_action_trigger (code,label,description,elementtype,rang) values ('BOM_REOPEN','BOM reopen','Executed when a BOM is re-open','bom',653); +insert into llx_c_action_trigger (code,label,description,elementtype,rang) values ('BOM_DELETE','BOM deleted','Executed when a BOM deleted','bom',654); +insert into llx_c_action_trigger (code,label,description,elementtype,rang) values ('MO_VALIDATE','MO validated','Executed when a MO is validated','bom',660); +insert into llx_c_action_trigger (code,label,description,elementtype,rang) values ('MO_PRODUCED','MO produced','Executed when a MO is produced','bom',661); +insert into llx_c_action_trigger (code,label,description,elementtype,rang) values ('MO_DELETE','MO deleted','Executed when a MO is deleted','bom',662); +insert into llx_c_action_trigger (code,label,description,elementtype,rang) values ('MO_CANCEL','MO canceled','Executed when a MO is canceled','bom',663); -- actions not enabled by default : they are excluded when we enable the module Agenda (except TASK_...) insert into llx_c_action_trigger (code,label,description,elementtype,rang) values ('TASK_CREATE','Task created','Executed when a project task is created','project',150); insert into llx_c_action_trigger (code,label,description,elementtype,rang) values ('TASK_MODIFY','Task modified','Executed when a project task is modified','project',151); diff --git a/htdocs/install/mysql/data/llx_c_socialnetworks.sql b/htdocs/install/mysql/data/llx_c_socialnetworks.sql index e45179cfe89..829cbbf0294 100644 --- a/htdocs/install/mysql/data/llx_c_socialnetworks.sql +++ b/htdocs/install/mysql/data/llx_c_socialnetworks.sql @@ -30,24 +30,24 @@ INSERT INTO llx_c_socialnetworks (entity, code, label, url, icon, active) VALUES INSERT INTO llx_c_socialnetworks (entity, code, label, url, icon, active) VALUES(1, 'googleplus', 'GooglePlus', 'https://www.googleplus.com/{socialid}', 'fa-google-plus-g', 0); INSERT INTO llx_c_socialnetworks (entity, code, label, url, icon, active) VALUES(1, 'youtube', 'Youtube', 'https://www.youtube.com/{socialid}', 'fa-youtube', 1); INSERT INTO llx_c_socialnetworks (entity, code, label, url, icon, active) VALUES(1, 'whatsapp', 'Whatsapp', '{socialid}', 'fa-whatsapp', 1); -INSERT INTO llx_c_socialnetworks (entity, code, label, url, icon, active) VALUES(1, 'tumblr', 'Tumblr', 'https://www.tumblr.com/{socialid}', '', 0); +INSERT INTO llx_c_socialnetworks (entity, code, label, url, icon, active) VALUES(1, 'tumblr', 'Tumblr', 'https://www.tumblr.com/{socialid}', 'fa-tumblr', 0); INSERT INTO llx_c_socialnetworks (entity, code, label, url, icon, active) VALUES(1, 'vero', 'Vero', 'https://vero.co/{socialid}', '', 0); -INSERT INTO llx_c_socialnetworks (entity, code, label, url, icon, active) VALUES(1, 'viadeo', 'Viadeo', 'https://fr.viadeo.com/fr/{socialid}', '', 0); -INSERT INTO llx_c_socialnetworks (entity, code, label, url, icon, active) VALUES(1, 'slack', 'Slack', '{socialid}', '', 0); -INSERT INTO llx_c_socialnetworks (entity, code, label, url, icon, active) VALUES(1, 'xing', 'Xing', '{socialid}', '', 0); -INSERT INTO llx_c_socialnetworks (entity, code, label, url, icon, active) VALUES(1, 'meetup', 'Meetup', '{socialid}', '', 0); -INSERT INTO llx_c_socialnetworks (entity, code, label, url, icon, active) VALUES(1, 'pinterest', 'Pinterest', '{socialid}', '', 0); -INSERT INTO llx_c_socialnetworks (entity, code, label, url, icon, active) VALUES(1, 'flickr', 'Flickr', '{socialid}', '', 0); -INSERT INTO llx_c_socialnetworks (entity, code, label, url, icon, active) VALUES(1, '500px', '500px', '{socialid}', '', 0); +INSERT INTO llx_c_socialnetworks (entity, code, label, url, icon, active) VALUES(1, 'viadeo', 'Viadeo', 'https://fr.viadeo.com/fr/{socialid}', 'fa-viadeo', 0); +INSERT INTO llx_c_socialnetworks (entity, code, label, url, icon, active) VALUES(1, 'slack', 'Slack', '{socialid}', 'fa-slack', 0); +INSERT INTO llx_c_socialnetworks (entity, code, label, url, icon, active) VALUES(1, 'xing', 'Xing', '{socialid}', 'fa-xing', 0); +INSERT INTO llx_c_socialnetworks (entity, code, label, url, icon, active) VALUES(1, 'meetup', 'Meetup', '{socialid}', 'fa-meetup', 0); +INSERT INTO llx_c_socialnetworks (entity, code, label, url, icon, active) VALUES(1, 'pinterest', 'Pinterest', '{socialid}', 'fa-pinterest', 0); +INSERT INTO llx_c_socialnetworks (entity, code, label, url, icon, active) VALUES(1, 'flickr', 'Flickr', '{socialid}', 'fa-flickr', 0); +INSERT INTO llx_c_socialnetworks (entity, code, label, url, icon, active) VALUES(1, '500px', '500px', '{socialid}', 'fa-500px', 0); INSERT INTO llx_c_socialnetworks (entity, code, label, url, icon, active) VALUES(1, 'giphy', 'Giphy', '{socialid}', '', 0); INSERT INTO llx_c_socialnetworks (entity, code, label, url, icon, active) VALUES(1, 'gifycat', 'Gificat', '{socialid}', '', 0); INSERT INTO llx_c_socialnetworks (entity, code, label, url, icon, active) VALUES(1, 'dailymotion', 'Dailymotion', '{socialid}', '', 0); INSERT INTO llx_c_socialnetworks (entity, code, label, url, icon, active) VALUES(1, 'vimeo', 'Vimeo', '{socialid}', '', 0); INSERT INTO llx_c_socialnetworks (entity, code, label, url, icon, active) VALUES(1, 'periscope', 'Periscope', '{socialid}', '', 0); INSERT INTO llx_c_socialnetworks (entity, code, label, url, icon, active) VALUES(1, 'twitch', 'Twitch', '{socialid}', '', 0); -INSERT INTO llx_c_socialnetworks (entity, code, label, url, icon, active) VALUES(1, 'discord', 'Discord', '{socialid}', '', 0); +INSERT INTO llx_c_socialnetworks (entity, code, label, url, icon, active) VALUES(1, 'discord', 'Discord', '{socialid}', 'fa-discord', 0); INSERT INTO llx_c_socialnetworks (entity, code, label, url, icon, active) VALUES(1, 'wikipedia', 'Wikipedia', '{socialid}', '', 0); -INSERT INTO llx_c_socialnetworks (entity, code, label, url, icon, active) VALUES(1, 'reddit', 'Reddit', '{socialid}', '', 0); +INSERT INTO llx_c_socialnetworks (entity, code, label, url, icon, active) VALUES(1, 'reddit', 'Reddit', '{socialid}', 'fa-reddit', 0); INSERT INTO llx_c_socialnetworks (entity, code, label, url, icon, active) VALUES(1, 'quora', 'Quora', '{socialid}', '', 0); INSERT INTO llx_c_socialnetworks (entity, code, label, url, icon, active) VALUES(1, 'tripadvisor', 'Tripadvisor', '{socialid}', '', 0); INSERT INTO llx_c_socialnetworks (entity, code, label, url, icon, active) VALUES(1, 'mastodon', 'Mastodon', '{socialid}', '', 0); diff --git a/htdocs/install/mysql/data/llx_c_ticket_type.sql b/htdocs/install/mysql/data/llx_c_ticket_type.sql index c3c6deae58f..660f1444b43 100644 --- a/htdocs/install/mysql/data/llx_c_ticket_type.sql +++ b/htdocs/install/mysql/data/llx_c_ticket_type.sql @@ -17,8 +17,9 @@ -- Contenu de la table llx_c_ticket_type -- -INSERT INTO llx_c_ticket_type (code, pos, label, active, use_default, description) VALUES('COM', '10', 'Commercial question', 1, 1, NULL); -INSERT INTO llx_c_ticket_type (code, pos, label, active, use_default, description) VALUES('ISSUE', '20', 'Issue or problem' , 1, 0, NULL); +INSERT INTO llx_c_ticket_type (code, pos, label, active, use_default, description) VALUES('COM', '10', 'Commercial question', 1, 0, NULL); +INSERT INTO llx_c_ticket_type (code, pos, label, active, use_default, description) VALUES('HELP', '15', 'Request for functionnal help', 1, 0, NULL); +INSERT INTO llx_c_ticket_type (code, pos, label, active, use_default, description) VALUES('ISSUE', '20', 'Issue or problem', 1, 0, NULL); INSERT INTO llx_c_ticket_type (code, pos, label, active, use_default, description) VALUES('REQUEST', '25', 'Change or enhancement request', 1, 0, NULL); -INSERT INTO llx_c_ticket_type (code, pos, label, active, use_default, description) VALUES('PROJECT', '30', 'Project', 0, 0, NULL); -INSERT INTO llx_c_ticket_type (code, pos, label, active, use_default, description) VALUES('OTHER', '40', 'Other', 1, 0, NULL); +INSERT INTO llx_c_ticket_type (code, pos, label, active, use_default, description) VALUES('PROJECT', '30', 'Project', 0, 0, NULL); +INSERT INTO llx_c_ticket_type (code, pos, label, active, use_default, description) VALUES('OTHER', '40', 'Other', 1, 0, NULL); diff --git a/htdocs/install/mysql/data/llx_c_type_container.sql b/htdocs/install/mysql/data/llx_c_type_container.sql index 949f0bad687..703d8f2ac34 100644 --- a/htdocs/install/mysql/data/llx_c_type_container.sql +++ b/htdocs/install/mysql/data/llx_c_type_container.sql @@ -33,5 +33,6 @@ insert into llx_c_type_container (code,label,module,active) values ('page', 'Page', 'system', 1); insert into llx_c_type_container (code,label,module,active) values ('banner', 'Banner', 'system', 1); insert into llx_c_type_container (code,label,module,active) values ('blogpost', 'BlogPost', 'system', 1); +insert into llx_c_type_container (code,label,module,active) values ('menu', 'Menu', 'system', 1); insert into llx_c_type_container (code,label,module,active) values ('other', 'Other', 'system', 1); diff --git a/htdocs/install/mysql/migration/10.0.0-11.0.0.sql b/htdocs/install/mysql/migration/10.0.0-11.0.0.sql index fcd7ede9bcc..127091b7963 100644 --- a/htdocs/install/mysql/migration/10.0.0-11.0.0.sql +++ b/htdocs/install/mysql/migration/10.0.0-11.0.0.sql @@ -51,6 +51,10 @@ ALTER TABLE llx_adherent_type ADD UNIQUE INDEX uk_adherent_type_libelle (libelle -- For v11 +insert into llx_c_type_container (code,label,module,active) values ('menu', 'Menu', 'system', 1); + +INSERT INTO llx_c_ticket_type (code, pos, label, active, use_default, description) VALUES('HELP', '15', 'Request for functionnal help', 1, 0, NULL); + ALTER TABLE llx_don ADD COLUMN fk_user_modif integer; ALTER TABLE llx_expeditiondet ADD INDEX idx_expeditiondet_fk_origin_line (fk_origin_line); @@ -61,6 +65,7 @@ ALTER TABLE llx_rights_def ADD COLUMN family_position INTEGER NOT NULL DEFAULT 0 UPDATE llx_rights_def SET subperms = 'write' WHERE perms = 'fiscalyear' AND module = 'accounting' AND subperms IS NULL; ALTER TABLE llx_bom_bom ADD COLUMN duration double(8,4) DEFAULT NULL; +ALTER TABLE llx_bom_bom ADD COLUMN fk_warehouse integer; ALTER TABLE llx_bom_bomline ADD COLUMN position integer NOT NULL DEFAULT 0; ALTER TABLE llx_bom_bomline ADD COLUMN qty_frozen smallint DEFAULT 0; ALTER TABLE llx_bom_bomline ADD COLUMN disable_stock_change smallint DEFAULT 0; @@ -273,24 +278,24 @@ INSERT INTO llx_c_socialnetworks (entity, code, label, url, icon, active) VALUES INSERT INTO llx_c_socialnetworks (entity, code, label, url, icon, active) VALUES(1, 'googleplus', 'GooglePlus', 'https://www.googleplus.com/{socialid}', 'fa-google-plus-g', 1); INSERT INTO llx_c_socialnetworks (entity, code, label, url, icon, active) VALUES(1, 'youtube', 'Youtube', 'https://www.youtube.com/{socialid}', 'fa-youtube', 1); INSERT INTO llx_c_socialnetworks (entity, code, label, url, icon, active) VALUES(1, 'whatsapp', 'Whatsapp', '{socialid}', 'fa-whatsapp', 1); -INSERT INTO llx_c_socialnetworks (entity, code, label, url, icon, active) VALUES(1, 'tumblr', 'Tumblr', 'https://www.tumblr.com/{socialid}', '', 0); +INSERT INTO llx_c_socialnetworks (entity, code, label, url, icon, active) VALUES(1, 'tumblr', 'Tumblr', 'https://www.tumblr.com/{socialid}', 'fa-tumblr', 0); INSERT INTO llx_c_socialnetworks (entity, code, label, url, icon, active) VALUES(1, 'vero', 'Vero', 'https://vero.co/{socialid}', '', 0); -INSERT INTO llx_c_socialnetworks (entity, code, label, url, icon, active) VALUES(1, 'viadeo', 'Viadeo', 'https://fr.viadeo.com/fr/{socialid}', '', 0); -INSERT INTO llx_c_socialnetworks (entity, code, label, url, icon, active) VALUES(1, 'slack', 'Slack', '{socialid}', '', 0); -INSERT INTO llx_c_socialnetworks (entity, code, label, url, icon, active) VALUES(1, 'xing', 'Xing', '{socialid}', '', 0); -INSERT INTO llx_c_socialnetworks (entity, code, label, url, icon, active) VALUES(1, 'meetup', 'Meetup', '{socialid}', '', 0); -INSERT INTO llx_c_socialnetworks (entity, code, label, url, icon, active) VALUES(1, 'pinterest', 'Pinterest', '{socialid}', '', 0); -INSERT INTO llx_c_socialnetworks (entity, code, label, url, icon, active) VALUES(1, 'flickr', 'Flickr', '{socialid}', '', 0); -INSERT INTO llx_c_socialnetworks (entity, code, label, url, icon, active) VALUES(1, '500px', '500px', '{socialid}', '', 0); +INSERT INTO llx_c_socialnetworks (entity, code, label, url, icon, active) VALUES(1, 'viadeo', 'Viadeo', 'https://fr.viadeo.com/fr/{socialid}', 'fa-viadeo', 0); +INSERT INTO llx_c_socialnetworks (entity, code, label, url, icon, active) VALUES(1, 'slack', 'Slack', '{socialid}', 'fa-slack', 0); +INSERT INTO llx_c_socialnetworks (entity, code, label, url, icon, active) VALUES(1, 'xing', 'Xing', '{socialid}', 'fa-xing', 0); +INSERT INTO llx_c_socialnetworks (entity, code, label, url, icon, active) VALUES(1, 'meetup', 'Meetup', '{socialid}', 'fa-meetup', 0); +INSERT INTO llx_c_socialnetworks (entity, code, label, url, icon, active) VALUES(1, 'pinterest', 'Pinterest', '{socialid}', 'fa-pinterest', 0); +INSERT INTO llx_c_socialnetworks (entity, code, label, url, icon, active) VALUES(1, 'flickr', 'Flickr', '{socialid}', 'fa-flickr', 0); +INSERT INTO llx_c_socialnetworks (entity, code, label, url, icon, active) VALUES(1, '500px', '500px', '{socialid}', 'fa-500px', 0); INSERT INTO llx_c_socialnetworks (entity, code, label, url, icon, active) VALUES(1, 'giphy', 'Giphy', '{socialid}', '', 0); INSERT INTO llx_c_socialnetworks (entity, code, label, url, icon, active) VALUES(1, 'gifycat', 'Gificat', '{socialid}', '', 0); INSERT INTO llx_c_socialnetworks (entity, code, label, url, icon, active) VALUES(1, 'dailymotion', 'Dailymotion', '{socialid}', '', 0); INSERT INTO llx_c_socialnetworks (entity, code, label, url, icon, active) VALUES(1, 'vimeo', 'Vimeo', '{socialid}', '', 0); INSERT INTO llx_c_socialnetworks (entity, code, label, url, icon, active) VALUES(1, 'periscope', 'Periscope', '{socialid}', '', 0); INSERT INTO llx_c_socialnetworks (entity, code, label, url, icon, active) VALUES(1, 'twitch', 'Twitch', '{socialid}', '', 0); -INSERT INTO llx_c_socialnetworks (entity, code, label, url, icon, active) VALUES(1, 'discord', 'Discord', '{socialid}', '', 0); +INSERT INTO llx_c_socialnetworks (entity, code, label, url, icon, active) VALUES(1, 'discord', 'Discord', '{socialid}', 'fa-discord', 0); INSERT INTO llx_c_socialnetworks (entity, code, label, url, icon, active) VALUES(1, 'wikipedia', 'Wikipedia', '{socialid}', '', 0); -INSERT INTO llx_c_socialnetworks (entity, code, label, url, icon, active) VALUES(1, 'reddit', 'Reddit', '{socialid}', '', 0); +INSERT INTO llx_c_socialnetworks (entity, code, label, url, icon, active) VALUES(1, 'reddit', 'Reddit', '{socialid}', 'fa-reddit', 0); INSERT INTO llx_c_socialnetworks (entity, code, label, url, icon, active) VALUES(1, 'quora', 'Quora', '{socialid}', '', 0); INSERT INTO llx_c_socialnetworks (entity, code, label, url, icon, active) VALUES(1, 'tripadvisor', 'Tripadvisor', '{socialid}', '', 0); INSERT INTO llx_c_socialnetworks (entity, code, label, url, icon, active) VALUES(1, 'mastodon', 'Mastodon', '{socialid}', '', 0); @@ -420,6 +425,14 @@ create table llx_c_shipment_package_type entity integer DEFAULT 1 NOT NULL -- Multi company id )ENGINE=innodb; +CREATE TABLE llx_product_fournisseur_price_extrafields ( + rowid integer AUTO_INCREMENT PRIMARY KEY, + tms timestamp, + fk_object integer NOT NULL, + import_key varchar(14) -- import key +) ENGINE=innodb; + +ALTER TABLE llx_product_fournisseur_price_extrafields ADD INDEX idx_product_fournisseur_price_extrafields (fk_object); CREATE TABLE llx_mrp_mo( -- BEGIN MODULEBUILDER FIELDS @@ -473,14 +486,41 @@ create table llx_mrp_mo_extrafields ALTER TABLE llx_mrp_mo_extrafields ADD INDEX idx_fk_object(fk_object); -insert into llx_c_action_trigger (code,label,description,elementtype,rang) values ('BOM_VALIDATE','BOM validated','Executed when a BOM is validated','bom',400); -insert into llx_c_action_trigger (code,label,description,elementtype,rang) values ('BOM_UNVALIDATE','BOM unvalidated','Executed when a BOM is unvalidated','bom',401); -insert into llx_c_action_trigger (code,label,description,elementtype,rang) values ('BOM_CLOSE','BOM disabled','Executed when a BOM is disabled','bom',402); -insert into llx_c_action_trigger (code,label,description,elementtype,rang) values ('BOM_REOPEN','BOM reopen','Executed when a BOM is re-open','bom',403); -insert into llx_c_action_trigger (code,label,description,elementtype,rang) values ('BOM_DELETE','BOM deleted','Executed when a BOM deleted','bom',404); +insert into llx_c_action_trigger (code,label,description,elementtype,rang) values ('BOM_VALIDATE','BOM validated','Executed when a BOM is validated','bom',650); +insert into llx_c_action_trigger (code,label,description,elementtype,rang) values ('BOM_UNVALIDATE','BOM unvalidated','Executed when a BOM is unvalidated','bom',651); +insert into llx_c_action_trigger (code,label,description,elementtype,rang) values ('BOM_CLOSE','BOM disabled','Executed when a BOM is disabled','bom',652); +insert into llx_c_action_trigger (code,label,description,elementtype,rang) values ('BOM_REOPEN','BOM reopen','Executed when a BOM is re-open','bom',653); +insert into llx_c_action_trigger (code,label,description,elementtype,rang) values ('BOM_DELETE','BOM deleted','Executed when a BOM deleted','bom',654); -insert into llx_c_action_trigger (code,label,description,elementtype,rang) values ('MO_VALIDATE','MO validated','Executed when a MO is validated','bom',410); -insert into llx_c_action_trigger (code,label,description,elementtype,rang) values ('MO_PRODUCED','MO disabled','Executed when a MO is produced','bom',411); -insert into llx_c_action_trigger (code,label,description,elementtype,rang) values ('MO_DELETE','MO deleted','Executed when a MO is deleted','bom',412); +insert into llx_c_action_trigger (code,label,description,elementtype,rang) values ('MO_VALIDATE','MO validated','Executed when a MO is validated','bom',660); +insert into llx_c_action_trigger (code,label,description,elementtype,rang) values ('MO_PRODUCED','MO produced','Executed when a MO is produced','bom',661); +insert into llx_c_action_trigger (code,label,description,elementtype,rang) values ('MO_DELETE','MO deleted','Executed when a MO is deleted','bom',662); +insert into llx_c_action_trigger (code,label,description,elementtype,rang) values ('MO_CANCEL','MO canceled','Executed when a MO is canceled','bom',663); ALTER TABLE llx_comment ADD COLUMN fk_user_modif integer DEFAULT NULL; + + +CREATE TABLE llx_mrp_production( + rowid integer AUTO_INCREMENT PRIMARY KEY NOT NULL, + fk_mo integer NOT NULL, + position integer NOT NULL DEFAULT 0, + fk_product integer NOT NULL, + fk_warehouse integer, + qty integer NOT NULL DEFAULT 1, + batch varchar(30), + role varchar(10), -- 'toconsume' or 'toproduce' (initialized at MO creation), 'consumed' or 'produced' (added after MO validation) + fk_mrp_production integer, -- if role = 'consumed', id of line with role 'toconsume', if role = 'produced' id of line with role 'toproduce' + fk_stock_movement integer, -- id of stock movement when movements are validated + date_creation datetime NOT NULL, + tms timestamp, + fk_user_creat integer NOT NULL, + fk_user_modif integer, + import_key varchar(14) +) ENGINE=innodb; + +ALTER TABLE llx_mrp_production ADD CONSTRAINT fk_mrp_production_mo FOREIGN KEY (fk_mo) REFERENCES llx_mrp_mo (rowid); +ALTER TABLE llx_mrp_production ADD CONSTRAINT fk_mrp_production_product FOREIGN KEY (fk_product) REFERENCES llx_product (rowid); +ALTER TABLE llx_mrp_production ADD CONSTRAINT fk_mrp_production_stock_movement FOREIGN KEY (fk_stock_movement) REFERENCES llx_stock_mouvement (rowid); + +ALTER TABLE llx_mrp_production ADD INDEX idx_mrp_production_fk_mo (fk_mo); + diff --git a/htdocs/install/mysql/migration/3.5.0-3.6.0.sql b/htdocs/install/mysql/migration/3.5.0-3.6.0.sql old mode 100755 new mode 100644 diff --git a/htdocs/install/mysql/migration/3.6.0-3.7.0.sql b/htdocs/install/mysql/migration/3.6.0-3.7.0.sql old mode 100755 new mode 100644 diff --git a/htdocs/install/mysql/migration/3.7.0-3.8.0.sql b/htdocs/install/mysql/migration/3.7.0-3.8.0.sql old mode 100755 new mode 100644 diff --git a/htdocs/install/mysql/migration/repair.sql b/htdocs/install/mysql/migration/repair.sql old mode 100755 new mode 100644 index eac0d5b3bd9..69bdea770c9 --- a/htdocs/install/mysql/migration/repair.sql +++ b/htdocs/install/mysql/migration/repair.sql @@ -71,6 +71,8 @@ UPDATE llx_user set api_key = null where api_key = ''; UPDATE llx_c_email_templates SET position = 0 WHERE position IS NULL; +-- DELETE FROM llx_c_email_templates WHERE label = '(SendAnEMailToMember)'; -- Now it is '(SendingAnEMailToMemner)' + -- delete foreign key that should never exists ALTER TABLE llx_propal DROP FOREIGN KEY fk_propal_fk_currency; diff --git a/htdocs/install/mysql/tables/llx_accounting_bookkeeping.sql b/htdocs/install/mysql/tables/llx_accounting_bookkeeping.sql index f851061db63..cf1c3334092 100644 --- a/htdocs/install/mysql/tables/llx_accounting_bookkeeping.sql +++ b/htdocs/install/mysql/tables/llx_accounting_bookkeeping.sql @@ -17,7 +17,7 @@ -- -- ============================================================================ -CREATE TABLE llx_accounting_bookkeeping +CREATE TABLE llx_accounting_bookkeeping ( rowid integer NOT NULL AUTO_INCREMENT PRIMARY KEY, entity integer DEFAULT 1 NOT NULL, -- | multi company id @@ -27,7 +27,7 @@ CREATE TABLE llx_accounting_bookkeeping doc_ref varchar(300) NOT NULL, -- FEC:PieceRef | facture_client/reglement_client/... reference number fk_doc integer NOT NULL, -- | facture_client/reglement_client/... rowid fk_docdet integer NOT NULL, -- | facture_client/reglement_client/... line rowid - thirdparty_code varchar(32), -- Third party code (customer or supplier) when record is saved (may help debug) + thirdparty_code varchar(32), -- Third party code (customer or supplier) when record is saved (may help debug) subledger_account varchar(32), -- FEC:CompAuxNum | account number of subledger account subledger_label varchar(255), -- FEC:CompAuxLib | label of subledger account numero_compte varchar(32) NOT NULL, -- FEC:CompteNum | account number @@ -45,12 +45,12 @@ CREATE TABLE llx_accounting_bookkeeping fk_user_author integer NOT NULL, -- | user creating fk_user_modif integer, -- | user making last change date_creation datetime, -- FEC:EcritureDate | creation date - tms timestamp, -- | date last modification + tms timestamp, -- | date last modification fk_user integer NULL, -- The id of user that validate the accounting source document code_journal varchar(32) NOT NULL, -- FEC:JournalCode journal_label varchar(255), -- FEC:JournalLib - date_validated datetime, -- FEC:ValidDate | if empty: movement not validated / if not empty: movement validated (No deleting / No modification) - date_export datetime DEFAULT NULL, -- + date_validated datetime, -- FEC:ValidDate | if empty: movement not validated / if not empty: movement validated (No deleting / No modification) + date_export datetime DEFAULT NULL, -- import_key varchar(14), - extraparams varchar(255) -- for other parameters with json format + extraparams varchar(255) -- for other parameters with json format ) ENGINE=innodb; diff --git a/htdocs/install/mysql/tables/llx_bom_bom.sql b/htdocs/install/mysql/tables/llx_bom_bom.sql index f1e80d927f9..cc35af666d3 100644 --- a/htdocs/install/mysql/tables/llx_bom_bom.sql +++ b/htdocs/install/mysql/tables/llx_bom_bom.sql @@ -20,10 +20,11 @@ CREATE TABLE llx_bom_bom( entity integer DEFAULT 1 NOT NULL, ref varchar(128) NOT NULL, label varchar(255), + fk_product integer, description text, note_public text, note_private text, - fk_product integer, + fk_warehouse integer, qty double(24,8), efficiency double(8,4) DEFAULT 1, duration double(8,4) DEFAULT NULL, diff --git a/htdocs/install/mysql/tables/llx_c_holiday_types.sql b/htdocs/install/mysql/tables/llx_c_holiday_types.sql old mode 100755 new mode 100644 diff --git a/htdocs/install/mysql/tables/llx_c_price_expression.sql b/htdocs/install/mysql/tables/llx_c_price_expression.sql old mode 100755 new mode 100644 diff --git a/htdocs/install/mysql/tables/llx_c_ticketsup_category.key.sql b/htdocs/install/mysql/tables/llx_c_ticket_category.key.sql similarity index 100% rename from htdocs/install/mysql/tables/llx_c_ticketsup_category.key.sql rename to htdocs/install/mysql/tables/llx_c_ticket_category.key.sql diff --git a/htdocs/install/mysql/tables/llx_c_ticketsup_category.sql b/htdocs/install/mysql/tables/llx_c_ticket_category.sql old mode 100755 new mode 100644 similarity index 100% rename from htdocs/install/mysql/tables/llx_c_ticketsup_category.sql rename to htdocs/install/mysql/tables/llx_c_ticket_category.sql diff --git a/htdocs/install/mysql/tables/llx_c_ticketsup_severity.key.sql b/htdocs/install/mysql/tables/llx_c_ticket_severity.key.sql similarity index 100% rename from htdocs/install/mysql/tables/llx_c_ticketsup_severity.key.sql rename to htdocs/install/mysql/tables/llx_c_ticket_severity.key.sql diff --git a/htdocs/install/mysql/tables/llx_c_ticketsup_severity.sql b/htdocs/install/mysql/tables/llx_c_ticket_severity.sql old mode 100755 new mode 100644 similarity index 100% rename from htdocs/install/mysql/tables/llx_c_ticketsup_severity.sql rename to htdocs/install/mysql/tables/llx_c_ticket_severity.sql diff --git a/htdocs/install/mysql/tables/llx_c_ticketsup_type.key.sql b/htdocs/install/mysql/tables/llx_c_ticket_type.key.sql similarity index 100% rename from htdocs/install/mysql/tables/llx_c_ticketsup_type.key.sql rename to htdocs/install/mysql/tables/llx_c_ticket_type.key.sql diff --git a/htdocs/install/mysql/tables/llx_c_ticketsup_type.sql b/htdocs/install/mysql/tables/llx_c_ticket_type.sql old mode 100755 new mode 100644 similarity index 100% rename from htdocs/install/mysql/tables/llx_c_ticketsup_type.sql rename to htdocs/install/mysql/tables/llx_c_ticket_type.sql diff --git a/htdocs/install/mysql/tables/llx_expensereport.sql b/htdocs/install/mysql/tables/llx_expensereport.sql old mode 100755 new mode 100644 diff --git a/htdocs/install/mysql/tables/llx_mrp_production.key.sql b/htdocs/install/mysql/tables/llx_mrp_production.key.sql new file mode 100644 index 00000000000..d77ef297e82 --- /dev/null +++ b/htdocs/install/mysql/tables/llx_mrp_production.key.sql @@ -0,0 +1,21 @@ +-- Copyright (C) 2019 Laurent Destailleur +-- +-- This program is free software: you can redistribute it and/or modify +-- it under the terms of the GNU General Public License as published by +-- the Free Software Foundation, either version 3 of the License, or +-- (at your option) any later version. +-- +-- This program is distributed in the hope that it will be useful, +-- but WITHOUT ANY WARRANTY; without even the implied warranty of +-- MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +-- GNU General Public License for more details. +-- +-- You should have received a copy of the GNU General Public License +-- along with this program. If not, see http://www.gnu.org/licenses/. + +ALTER TABLE llx_mrp_production ADD CONSTRAINT fk_mrp_production_mo FOREIGN KEY (fk_mo) REFERENCES llx_mrp_mo (rowid); +ALTER TABLE llx_mrp_production ADD CONSTRAINT fk_mrp_production_product FOREIGN KEY (fk_product) REFERENCES llx_product (rowid); +ALTER TABLE llx_mrp_production ADD CONSTRAINT fk_mrp_production_stock_movement FOREIGN KEY (fk_stock_movement) REFERENCES llx_stock_mouvement (rowid); + +ALTER TABLE llx_mrp_production ADD INDEX idx_mrp_production_fk_mo (fk_mo); + diff --git a/htdocs/install/mysql/tables/llx_mrp_production.sql b/htdocs/install/mysql/tables/llx_mrp_production.sql new file mode 100644 index 00000000000..275acde6aef --- /dev/null +++ b/htdocs/install/mysql/tables/llx_mrp_production.sql @@ -0,0 +1,34 @@ +-- Copyright (C) 2019 Laurent Destailleur +-- +-- This program is free software: you can redistribute it and/or modify +-- it under the terms of the GNU General Public License as published by +-- the Free Software Foundation, either version 3 of the License, or +-- (at your option) any later version. +-- +-- This program is distributed in the hope that it will be useful, +-- but WITHOUT ANY WARRANTY; without even the implied warranty of +-- MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +-- GNU General Public License for more details. +-- +-- You should have received a copy of the GNU General Public License +-- along with this program. If not, see http://www.gnu.org/licenses/. + + +CREATE TABLE llx_mrp_production( + rowid integer AUTO_INCREMENT PRIMARY KEY NOT NULL, + fk_mo integer NOT NULL, + position integer NOT NULL DEFAULT 0, + fk_product integer NOT NULL, + fk_warehouse integer, + qty integer NOT NULL DEFAULT 1, + batch varchar(30), + role varchar(10), -- 'toconsume' or 'toproduce' (initialized at MO creation), 'consumed' or 'produced' (added after MO validation) + fk_mrp_production integer, -- if role = 'consumed', id of line with role 'toconsume', if role = 'produced' id of line with role 'toproduce' + fk_stock_movement integer, -- id of stock movement when movements are validated + date_creation datetime NOT NULL, + tms timestamp, + fk_user_creat integer NOT NULL, + fk_user_modif integer, + import_key varchar(14) +) ENGINE=innodb; + diff --git a/htdocs/install/mysql/tables/llx_product.sql b/htdocs/install/mysql/tables/llx_product.sql old mode 100755 new mode 100644 diff --git a/htdocs/install/mysql/tables/llx_product_batch.sql b/htdocs/install/mysql/tables/llx_product_batch.sql index 70b7d024398..ba8b7ff59e4 100644 --- a/htdocs/install/mysql/tables/llx_product_batch.sql +++ b/htdocs/install/mysql/tables/llx_product_batch.sql @@ -17,6 +17,7 @@ -- -- This table is dedicated to store detail (lots/serial) of a stock -- ============================================================================ + CREATE TABLE llx_product_batch ( rowid integer AUTO_INCREMENT PRIMARY KEY, tms timestamp, diff --git a/htdocs/install/mysql/tables/llx_product_fournisseur_price.sql b/htdocs/install/mysql/tables/llx_product_fournisseur_price.sql old mode 100755 new mode 100644 diff --git a/htdocs/install/mysql/tables/llx_product_price.sql b/htdocs/install/mysql/tables/llx_product_price.sql old mode 100755 new mode 100644 diff --git a/htdocs/install/mysql/tables/llx_ticket.key.sql b/htdocs/install/mysql/tables/llx_ticket.key.sql old mode 100755 new mode 100644 diff --git a/htdocs/install/upgrade2.php b/htdocs/install/upgrade2.php index 232cee40440..d4fd5a20caf 100644 --- a/htdocs/install/upgrade2.php +++ b/htdocs/install/upgrade2.php @@ -92,14 +92,14 @@ if (! is_object($conf)) dolibarr_install_syslog("upgrade2: conf file not initial * View */ -if ((! $versionfrom || preg_match('/version/', $versionfrom)) && (! $versionto || preg_match('/version/', $versionto))) +if ((!$versionfrom || preg_match('/version/', $versionfrom)) && (!$versionto || preg_match('/version/', $versionto))) { print 'Error: Parameter versionfrom or versionto missing or having a bad format.'."\n"; print 'Upgrade must be ran from command line with parameters or called from page install/index.php (like a first install)'."\n"; // Test if batch mode $sapi_type = php_sapi_name(); $script_file = basename(__FILE__); - $path=__DIR__.'/'; + $path = __DIR__.'/'; if (substr($sapi_type, 0, 3) == 'cli') { print 'Syntax from command line: '.$script_file." x.y.z a.b.c [MAIN_MODULE_NAME1_TO_ENABLE,MAIN_MODULE_NAME2_TO_ENABLE...]\n"; @@ -107,24 +107,24 @@ if ((! $versionfrom || preg_match('/version/', $versionfrom)) && (! $versionto | exit; } -pHeader('', 'step5', GETPOST('action', 'aZ09')?GETPOST('action', 'aZ09'):'upgrade', 'versionfrom='.$versionfrom.'&versionto='.$versionto); +pHeader('', 'step5', GETPOST('action', 'aZ09') ?GETPOST('action', 'aZ09') : 'upgrade', 'versionfrom='.$versionfrom.'&versionto='.$versionto); -if (! GETPOST('action', 'aZ09') || preg_match('/upgrade/i', GETPOST('action', 'aZ09'))) +if (!GETPOST('action', 'aZ09') || preg_match('/upgrade/i', GETPOST('action', 'aZ09'))) { print '

    Database '.$langs->trans('DataMigration').'

    '; print '
    '.$langs->trans('Type').''; print $object->getLibType(); if ($object->type == FactureFournisseur::TYPE_REPLACEMENT) { - $facreplaced=new FactureFournisseur($db); + $facreplaced = new FactureFournisseur($db); $facreplaced->fetch($object->fk_facture_source); print ' ('.$langs->transnoentities("ReplaceInvoice", $facreplaced->getNomUrl(1)).')'; } if ($object->type == FactureFournisseur::TYPE_CREDIT_NOTE) { - $facusing=new FactureFournisseur($db); + $facusing = new FactureFournisseur($db); $facusing->fetch($object->fk_facture_source); print ' ('.$langs->transnoentities("CorrectInvoice", $facusing->getNomUrl(1)).')'; } - $facidavoir=$object->getListIdAvoirFromInvoice(); + $facidavoir = $object->getListIdAvoirFromInvoice(); if (count($facidavoir) > 0) { print ' ('.$langs->transnoentities("InvoiceHasAvoir"); - $i=0; - foreach($facidavoir as $fid) + $i = 0; + foreach ($facidavoir as $fid) { - if ($i==0) print ' '; + if ($i == 0) print ' '; else print ','; - $facavoir=new FactureFournisseur($db); + $facavoir = new FactureFournisseur($db); $facavoir->fetch($fid); print $facavoir->getNomUrl(1); } @@ -173,7 +173,7 @@ if ($object->id > 0) } if ($facidnext > 0) { - $facthatreplace=new FactureFournisseur($db); + $facthatreplace = new FactureFournisseur($db); $facthatreplace->fetch($facidnext); print ' ('.$langs->transnoentities("ReplacedByInvoice", $facthatreplace->getNomUrl(1)).')'; } @@ -190,13 +190,13 @@ 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 '
    '.$langs->transcountry("AmountLT1", $societe->country_code).''.price($object->total_localtax1, 1, $langs, 0, -1, -1, $conf->currency).'
    '.$langs->transcountry("AmountLT2", $societe->country_code).''.price($object->total_localtax2, 1, $langs, 0, -1, -1, $conf->currency).'
    '; // If password is encoded, we decode it - if (preg_match('/crypted:/i', $dolibarr_main_db_pass) || ! empty($dolibarr_main_db_encrypted_pass)) + if (preg_match('/crypted:/i', $dolibarr_main_db_pass) || !empty($dolibarr_main_db_encrypted_pass)) { require_once $dolibarr_main_document_root.'/core/lib/security.lib.php'; if (preg_match('/crypted:/i', $dolibarr_main_db_pass)) { $dolibarr_main_db_pass = preg_replace('/crypted:/i', '', $dolibarr_main_db_pass); $dolibarr_main_db_pass = dol_decode($dolibarr_main_db_pass); - $dolibarr_main_db_encrypted_pass = $dolibarr_main_db_pass; // We need to set this as it is used to know the password was initially crypted + $dolibarr_main_db_encrypted_pass = $dolibarr_main_db_pass; // We need to set this as it is used to know the password was initially crypted } else $dolibarr_main_db_pass = dol_decode($dolibarr_main_db_encrypted_pass); } @@ -137,25 +137,25 @@ if (! GETPOST('action', 'aZ09') || preg_match('/upgrade/i', GETPOST('action', 'a $conf->db->user = $dolibarr_main_db_user; $conf->db->pass = $dolibarr_main_db_pass; - $db=getDoliDBInstance($conf->db->type, $conf->db->host, $conf->db->user, $conf->db->pass, $conf->db->name, $conf->db->port); + $db = getDoliDBInstance($conf->db->type, $conf->db->host, $conf->db->user, $conf->db->pass, $conf->db->name, $conf->db->port); // Create the global $hookmanager object include_once DOL_DOCUMENT_ROOT.'/core/class/hookmanager.class.php'; - $hookmanager=new HookManager($db); + $hookmanager = new HookManager($db); $hookmanager->initHooks(array('upgrade')); if (!$db->connected) { print ''; - dolibarr_install_syslog('upgrade2: failed to connect to database :' . $conf->db->name . ' on ' . $conf->db->host . ' for user ' . $conf->db->user, LOG_ERR); + dolibarr_install_syslog('upgrade2: failed to connect to database :'.$conf->db->name.' on '.$conf->db->host.' for user '.$conf->db->user, LOG_ERR); $error++; } - if (! $error) + if (!$error) { - if($db->database_selected) + if ($db->database_selected) { - dolibarr_install_syslog('upgrade2: database connection successful :' . $dolibarr_main_db_name); + dolibarr_install_syslog('upgrade2: database connection successful :'.$dolibarr_main_db_name); } else { @@ -163,17 +163,17 @@ if (! GETPOST('action', 'aZ09') || preg_match('/upgrade/i', GETPOST('action', 'a } } - if (empty($dolibarr_main_db_encryption)) $dolibarr_main_db_encryption=0; + if (empty($dolibarr_main_db_encryption)) $dolibarr_main_db_encryption = 0; $conf->db->dolibarr_main_db_encryption = $dolibarr_main_db_encryption; - if (empty($dolibarr_main_db_cryptkey)) $dolibarr_main_db_cryptkey=''; + if (empty($dolibarr_main_db_cryptkey)) $dolibarr_main_db_cryptkey = ''; $conf->db->dolibarr_main_db_cryptkey = $dolibarr_main_db_cryptkey; // Chargement config - if (! $error) + if (!$error) { $conf->setValues($db); // Reset forced setup after the setValues - if (defined('SYSLOG_FILE')) $conf->global->SYSLOG_FILE=constant('SYSLOG_FILE'); + if (defined('SYSLOG_FILE')) $conf->global->SYSLOG_FILE = constant('SYSLOG_FILE'); $conf->global->MAIN_ENABLE_LOG_TO_HTML = 1; } @@ -185,18 +185,18 @@ if (! GETPOST('action', 'aZ09') || preg_match('/upgrade/i', GETPOST('action', 'a ***************************************************************************************/ $db->begin(); - if (! $error) + if (!$error) { // Current version is $conf->global->MAIN_VERSION_LAST_UPGRADE // Version to install is DOL_VERSION - $dolibarrlastupgradeversionarray=preg_split('/[\.-]/', isset($conf->global->MAIN_VERSION_LAST_UPGRADE)?$conf->global->MAIN_VERSION_LAST_UPGRADE:(isset($conf->global->MAIN_VERSION_LAST_INSTALL)?$conf->global->MAIN_VERSION_LAST_INSTALL:'')); + $dolibarrlastupgradeversionarray = preg_split('/[\.-]/', isset($conf->global->MAIN_VERSION_LAST_UPGRADE) ? $conf->global->MAIN_VERSION_LAST_UPGRADE : (isset($conf->global->MAIN_VERSION_LAST_INSTALL) ? $conf->global->MAIN_VERSION_LAST_INSTALL : '')); // Chaque action de migration doit renvoyer une ligne sur 4 colonnes avec // dans la 1ere colonne, la description de l'action a faire // dans la 4eme colonne, le texte 'OK' si fait ou 'AlreadyDone' si rien n'est fait ou 'Error' - $versiontoarray=explode('.', $versionto); - $versionranarray=explode('.', DOL_VERSION); + $versiontoarray = explode('.', $versionto); + $versionranarray = explode('.', DOL_VERSION); // Force to execute this at begin to avoid the new core code into Dolibarr to be broken. @@ -224,8 +224,8 @@ if (! GETPOST('action', 'aZ09') || preg_match('/upgrade/i', GETPOST('action', 'a $db->query($sql, 1); - $afterversionarray=explode('.', '2.0.0'); - $beforeversionarray=explode('.', '2.7.9'); + $afterversionarray = explode('.', '2.0.0'); + $beforeversionarray = explode('.', '2.7.9'); if (versioncompare($versiontoarray, $afterversionarray) >= 0 && versioncompare($versiontoarray, $beforeversionarray) <= 0) { // Script pour V2 -> V2.1 @@ -287,12 +287,12 @@ if (! GETPOST('action', 'aZ09') || preg_match('/upgrade/i', GETPOST('action', 'a } // Script for 2.8 - $afterversionarray=explode('.', '2.7.9'); - $beforeversionarray=explode('.', '2.8.9'); + $afterversionarray = explode('.', '2.7.9'); + $beforeversionarray = explode('.', '2.8.9'); //print $versionto.' '.versioncompare($versiontoarray,$afterversionarray).' '.versioncompare($versiontoarray,$beforeversionarray); if (versioncompare($versiontoarray, $afterversionarray) >= 0 && versioncompare($versiontoarray, $beforeversionarray) <= 0) { - migrate_price_facture($db, $langs, $conf); // Code of this function works for 2.8+ because need a field tva_tx + migrate_price_facture($db, $langs, $conf); // Code of this function works for 2.8+ because need a field tva_tx migrate_relationship_tables($db, $langs, $conf, 'co_exp', 'fk_commande', 'commande', 'fk_expedition', 'shipping'); @@ -314,8 +314,8 @@ if (! GETPOST('action', 'aZ09') || preg_match('/upgrade/i', GETPOST('action', 'a } // Script for 2.9 - $afterversionarray=explode('.', '2.8.9'); - $beforeversionarray=explode('.', '2.9.9'); + $afterversionarray = explode('.', '2.8.9'); + $beforeversionarray = explode('.', '2.9.9'); if (versioncompare($versiontoarray, $afterversionarray) >= 0 && versioncompare($versiontoarray, $beforeversionarray) <= 0) { migrate_project_task_time($db, $langs, $conf); @@ -328,16 +328,16 @@ if (! GETPOST('action', 'aZ09') || preg_match('/upgrade/i', GETPOST('action', 'a } // Script for 3.0 - $afterversionarray=explode('.', '2.9.9'); - $beforeversionarray=explode('.', '3.0.9'); + $afterversionarray = explode('.', '2.9.9'); + $beforeversionarray = explode('.', '3.0.9'); if (versioncompare($versiontoarray, $afterversionarray) >= 0 && versioncompare($versiontoarray, $beforeversionarray) <= 0) { // No particular code } // Script for 3.1 - $afterversionarray=explode('.', '3.0.9'); - $beforeversionarray=explode('.', '3.1.9'); + $afterversionarray = explode('.', '3.0.9'); + $beforeversionarray = explode('.', '3.1.9'); if (versioncompare($versiontoarray, $afterversionarray) >= 0 && versioncompare($versiontoarray, $beforeversionarray) <= 0) { migrate_rename_directories($db, $langs, $conf, '/rss', '/externalrss'); @@ -346,8 +346,8 @@ if (! GETPOST('action', 'aZ09') || preg_match('/upgrade/i', GETPOST('action', 'a } // Script for 3.2 - $afterversionarray=explode('.', '3.1.9'); - $beforeversionarray=explode('.', '3.2.9'); + $afterversionarray = explode('.', '3.1.9'); + $beforeversionarray = explode('.', '3.2.9'); if (versioncompare($versiontoarray, $afterversionarray) >= 0 && versioncompare($versiontoarray, $beforeversionarray) <= 0) { migrate_price_contrat($db, $langs, $conf); @@ -358,8 +358,8 @@ if (! GETPOST('action', 'aZ09') || preg_match('/upgrade/i', GETPOST('action', 'a } // Script for 3.3 - $afterversionarray=explode('.', '3.2.9'); - $beforeversionarray=explode('.', '3.3.9'); + $afterversionarray = explode('.', '3.2.9'); + $beforeversionarray = explode('.', '3.3.9'); if (versioncompare($versiontoarray, $afterversionarray) >= 0 && versioncompare($versiontoarray, $beforeversionarray) <= 0) { migrate_categorie_association($db, $langs, $conf); @@ -369,32 +369,32 @@ if (! GETPOST('action', 'aZ09') || preg_match('/upgrade/i', GETPOST('action', 'a // No specific scripts // Tasks to do always and only into last targeted version - $afterversionarray=explode('.', '3.6.9'); // target is after this - $beforeversionarray=explode('.', '3.7.9'); // target is before this + $afterversionarray = explode('.', '3.6.9'); // target is after this + $beforeversionarray = explode('.', '3.7.9'); // target is before this if (versioncompare($versiontoarray, $afterversionarray) >= 0 && versioncompare($versiontoarray, $beforeversionarray) <= 0) { migrate_event_assignement($db, $langs, $conf); } // Scripts for 3.9 - $afterversionarray=explode('.', '3.7.9'); - $beforeversionarray=explode('.', '3.8.9'); + $afterversionarray = explode('.', '3.7.9'); + $beforeversionarray = explode('.', '3.8.9'); if (versioncompare($versiontoarray, $afterversionarray) >= 0 && versioncompare($versiontoarray, $beforeversionarray) <= 0) { // No particular code } // Scripts for 4.0 - $afterversionarray=explode('.', '3.9.9'); - $beforeversionarray=explode('.', '4.0.9'); + $afterversionarray = explode('.', '3.9.9'); + $beforeversionarray = explode('.', '4.0.9'); if (versioncompare($versiontoarray, $afterversionarray) >= 0 && versioncompare($versiontoarray, $beforeversionarray) <= 0) { migrate_rename_directories($db, $langs, $conf, '/fckeditor', '/medias'); } // Scripts for 5.0 - $afterversionarray=explode('.', '4.0.9'); - $beforeversionarray=explode('.', '5.0.9'); + $afterversionarray = explode('.', '4.0.9'); + $beforeversionarray = explode('.', '5.0.9'); if (versioncompare($versiontoarray, $afterversionarray) >= 0 && versioncompare($versiontoarray, $beforeversionarray) <= 0) { // Migrate to add entity value into llx_societe_remise @@ -405,11 +405,11 @@ if (! GETPOST('action', 'aZ09') || preg_match('/upgrade/i', GETPOST('action', 'a } // Scripts for 6.0 - $afterversionarray=explode('.', '5.0.9'); - $beforeversionarray=explode('.', '6.0.9'); + $afterversionarray = explode('.', '5.0.9'); + $beforeversionarray = explode('.', '6.0.9'); if (versioncompare($versiontoarray, $afterversionarray) >= 0 && versioncompare($versiontoarray, $beforeversionarray) <= 0) { - if (! empty($conf->multicompany->enabled)) + if (!empty($conf->multicompany->enabled)) { global $multicompany_transverse_mode; @@ -426,8 +426,8 @@ if (! GETPOST('action', 'aZ09') || preg_match('/upgrade/i', GETPOST('action', 'a } // Scripts for 7.0 - $afterversionarray=explode('.', '6.0.9'); - $beforeversionarray=explode('.', '7.0.9'); + $afterversionarray = explode('.', '6.0.9'); + $beforeversionarray = explode('.', '7.0.9'); if (versioncompare($versiontoarray, $afterversionarray) >= 0 && versioncompare($versiontoarray, $beforeversionarray) <= 0) { // Migrate contact association @@ -437,16 +437,16 @@ if (! GETPOST('action', 'aZ09') || preg_match('/upgrade/i', GETPOST('action', 'a } // Scripts for 8.0 - $afterversionarray=explode('.', '7.0.9'); - $beforeversionarray=explode('.', '8.0.9'); + $afterversionarray = explode('.', '7.0.9'); + $beforeversionarray = explode('.', '8.0.9'); if (versioncompare($versiontoarray, $afterversionarray) >= 0 && versioncompare($versiontoarray, $beforeversionarray) <= 0) { migrate_rename_directories($db, $langs, $conf, '/contracts', '/contract'); } // Scripts for 9.0 - $afterversionarray=explode('.', '8.0.9'); - $beforeversionarray=explode('.', '9.0.9'); + $afterversionarray = explode('.', '8.0.9'); + $beforeversionarray = explode('.', '9.0.9'); if (versioncompare($versiontoarray, $afterversionarray) >= 0 && versioncompare($versiontoarray, $beforeversionarray) <= 0) { migrate_user_photospath(); @@ -467,7 +467,7 @@ if (! GETPOST('action', 'aZ09') || preg_match('/upgrade/i', GETPOST('action', 'a if (versioncompare($versiontoarray, $versionranarray) >= 0 || versioncompare($versiontoarray, $versionranarray) <= -3) { // Reload modules (this must be always done and only into last targeted version, because code to reload module may need table structure of last version) - $listofmodule=array( + $listofmodule = array( 'MAIN_MODULE_ACCOUNTING'=>'newboxdefonly', 'MAIN_MODULE_AGENDA'=>'newboxdefonly', 'MAIN_MODULE_BARCODE'=>'newboxdefonly', @@ -488,7 +488,7 @@ if (! GETPOST('action', 'aZ09') || preg_match('/upgrade/i', GETPOST('action', 'a 'MAIN_MODULE_SYSLOG'=>'newboxdefonly', 'MAIN_MODULE_SOCIETE'=>'newboxdefonly', 'MAIN_MODULE_SERVICE'=>'newboxdefonly', - 'MAIN_MODULE_USER'=>'newboxdefonly', //This one must be always done and only into last targeted version) + 'MAIN_MODULE_USER'=>'newboxdefonly', //This one must be always done and only into last targeted version) 'MAIN_MODULE_VARIANTS'=>'newboxdefonly', 'MAIN_MODULE_WEBSITE'=>'newboxdefonly', ); @@ -500,27 +500,27 @@ if (! GETPOST('action', 'aZ09') || preg_match('/upgrade/i', GETPOST('action', 'a // Can force activation of some module during migration with parameter 'enablemodules=MAIN_MODULE_XXX,MAIN_MODULE_YYY,...' // In most cases (online install or upgrade) $enablemodules is empty. Can be forced when ran from command line. - if (! $error && $enablemodules) + if (!$error && $enablemodules) { // Reload modules (this must be always done and only into last targeted version) - $listofmodules=array(); - $enablemodules=preg_replace('/enablemodules=/', '', $enablemodules); - $tmplistofmodules=explode(',', $enablemodules); - foreach($tmplistofmodules as $value) + $listofmodules = array(); + $enablemodules = preg_replace('/enablemodules=/', '', $enablemodules); + $tmplistofmodules = explode(',', $enablemodules); + foreach ($tmplistofmodules as $value) { - $listofmodules[$value]='forceactivate'; + $listofmodules[$value] = 'forceactivate'; } migrate_reload_modules($db, $langs, $conf, $listofmodules, 1); } // Can call a dedicated external upgrade process - if (! $error) + if (!$error) { - $parameters=array('versionfrom'=>$versionfrom, 'versionto='.$versionto); - $object=new stdClass(); - $action="upgrade"; - $reshook=$hookmanager->executeHooks('doUpgrade2', $parameters, $object, $action); // Note that $action and $object may have been modified by some hooks + $parameters = array('versionfrom'=>$versionfrom, 'versionto='.$versionto); + $object = new stdClass(); + $action = "upgrade"; + $reshook = $hookmanager->executeHooks('doUpgrade2', $parameters, $object, $action); // Note that $action and $object may have been modified by some hooks if ($hookmanager->resNbOfHooks > 0) { if ($reshook < 0) @@ -542,7 +542,7 @@ if (! GETPOST('action', 'aZ09') || preg_match('/upgrade/i', GETPOST('action', 'a else { //if (! empty($conf->modules)) - if (! empty($conf->modules_parts['hooks'])) // If there is at least one module with one hook, we show message to say nothing was done + if (!empty($conf->modules_parts['hooks'])) // If there is at least one module with one hook, we show message to say nothing was done { print ''; $insert_sql = 'INSERT INTO '.MAIN_DB_PREFIX.'paiementfourn_facturefourn SET '; - $insert_sql.= ' fk_paiementfourn = \''.$select_obj->rowid.'\','; - $insert_sql.= ' fk_facturefourn = \''.$select_obj->fk_facture_fourn.'\','; - $insert_sql.= ' amount = \''.$select_obj->amount.'\''; + $insert_sql .= ' fk_paiementfourn = \''.$select_obj->rowid.'\','; + $insert_sql .= ' fk_facturefourn = \''.$select_obj->fk_facture_fourn.'\','; + $insert_sql .= ' amount = \''.$select_obj->amount.'\''; $insert_resql = $db->query($insert_sql); if ($insert_resql) @@ -1454,9 +1454,9 @@ function migrate_paiementfourn_facturefourn($db, $langs, $conf) */ function migrate_price_facture($db, $langs, $conf) { - $err=0; + $err = 0; - $tmpmysoc=new Societe($db); + $tmpmysoc = new Societe($db); $tmpmysoc->setMysoc($conf); $db->begin(); @@ -1468,14 +1468,14 @@ function migrate_price_facture($db, $langs, $conf) // List of invoice lines not up to date $sql = "SELECT fd.rowid, fd.qty, fd.subprice, fd.remise_percent, fd.tva_tx as vatrate, fd.total_ttc, fd.info_bits,"; - $sql.= " f.rowid as facid, f.remise_percent as remise_percent_global, f.total_ttc as total_ttc_f"; - $sql.= " FROM ".MAIN_DB_PREFIX."facturedet as fd, ".MAIN_DB_PREFIX."facture as f"; - $sql.= " WHERE fd.fk_facture = f.rowid"; - $sql.= " AND (((fd.total_ttc = 0 AND fd.remise_percent != 100) or fd.total_ttc IS NULL) or f.total_ttc IS NULL)"; + $sql .= " f.rowid as facid, f.remise_percent as remise_percent_global, f.total_ttc as total_ttc_f"; + $sql .= " FROM ".MAIN_DB_PREFIX."facturedet as fd, ".MAIN_DB_PREFIX."facture as f"; + $sql .= " WHERE fd.fk_facture = f.rowid"; + $sql .= " AND (((fd.total_ttc = 0 AND fd.remise_percent != 100) or fd.total_ttc IS NULL) or f.total_ttc IS NULL)"; //print $sql; dolibarr_install_syslog("upgrade2::migrate_price_facture"); - $resql=$db->query($sql); + $resql = $db->query($sql); if ($resql) { $num = $db->num_rows($resql); @@ -1496,10 +1496,10 @@ function migrate_price_facture($db, $langs, $conf) $info_bits = $obj->info_bits; // On met a jour les 3 nouveaux champs - $facligne= new FactureLigne($db); + $facligne = new FactureLigne($db); $facligne->fetch($rowid); - $result=calcul_price_total($qty, $pu, $remise_percent, $vatrate, 0, 0, $remise_percent_global, 'HT', $info_bits, $facligne->product_type, $tmpmysoc); + $result = calcul_price_total($qty, $pu, $remise_percent, $vatrate, 0, 0, $remise_percent_global, 'HT', $info_bits, $facligne->product_type, $tmpmysoc); $total_ht = $result[0]; $total_tva = $result[1]; $total_ttc = $result[2]; @@ -1508,20 +1508,20 @@ function migrate_price_facture($db, $langs, $conf) $facligne->total_tva = $total_tva; $facligne->total_ttc = $total_ttc; - dolibarr_install_syslog("upgrade2: line " . $rowid . ": facid=" . $obj->facid . " pu=" . $pu ." qty=" . $qty . " vatrate=" . $vatrate . " remise_percent=" . $remise_percent . " remise_global=" . $remise_percent_global . " -> " . $total_ht . ", " . $total_tva . ", " . $total_ttc); + dolibarr_install_syslog("upgrade2: line ".$rowid.": facid=".$obj->facid." pu=".$pu." qty=".$qty." vatrate=".$vatrate." remise_percent=".$remise_percent." remise_global=".$remise_percent_global." -> ".$total_ht.", ".$total_tva.", ".$total_ttc); print ". "; $facligne->update_total(); /* On touche a facture mere uniquement si total_ttc = 0 */ - if (! $total_ttc_f) + if (!$total_ttc_f) { $facture = new Facture($db); - $facture->id=$obj->facid; + $facture->id = $obj->facid; - if ( $facture->fetch($facture->id) >= 0) + if ($facture->fetch($facture->id) >= 0) { - if ( $facture->update_price() > 0 ) + if ($facture->update_price() > 0) { //print $facture->id; } @@ -1573,7 +1573,7 @@ function migrate_price_facture($db, $langs, $conf) */ function migrate_price_propal($db, $langs, $conf) { - $tmpmysoc=new Societe($db); + $tmpmysoc = new Societe($db); $tmpmysoc->setMysoc($conf); $db->begin(); @@ -1585,13 +1585,13 @@ function migrate_price_propal($db, $langs, $conf) // List of proposal lines not up to date $sql = "SELECT pd.rowid, pd.qty, pd.subprice, pd.remise_percent, pd.tva_tx as vatrate, pd.info_bits,"; - $sql.= " p.rowid as propalid, p.remise_percent as remise_percent_global"; - $sql.= " FROM ".MAIN_DB_PREFIX."propaldet as pd, ".MAIN_DB_PREFIX."propal as p"; - $sql.= " WHERE pd.fk_propal = p.rowid"; - $sql.= " AND ((pd.total_ttc = 0 AND pd.remise_percent != 100) or pd.total_ttc IS NULL)"; + $sql .= " p.rowid as propalid, p.remise_percent as remise_percent_global"; + $sql .= " FROM ".MAIN_DB_PREFIX."propaldet as pd, ".MAIN_DB_PREFIX."propal as p"; + $sql .= " WHERE pd.fk_propal = p.rowid"; + $sql .= " AND ((pd.total_ttc = 0 AND pd.remise_percent != 100) or pd.total_ttc IS NULL)"; dolibarr_install_syslog("upgrade2::migrate_price_propal"); - $resql=$db->query($sql); + $resql = $db->query($sql); if ($resql) { $num = $db->num_rows($resql); @@ -1611,10 +1611,10 @@ function migrate_price_propal($db, $langs, $conf) $info_bits = $obj->info_bits; // On met a jour les 3 nouveaux champs - $propalligne= new PropaleLigne($db); + $propalligne = new PropaleLigne($db); $propalligne->fetch($rowid); - $result=calcul_price_total($qty, $pu, $remise_percent, $vatrate, 0, 0, $remise_percent_global, 'HT', $info_bits, $propalligne->product_type, $tmpmysoc); + $result = calcul_price_total($qty, $pu, $remise_percent, $vatrate, 0, 0, $remise_percent_global, 'HT', $info_bits, $propalligne->product_type, $tmpmysoc); $total_ht = $result[0]; $total_tva = $result[1]; $total_ttc = $result[2]; @@ -1623,7 +1623,7 @@ function migrate_price_propal($db, $langs, $conf) $propalligne->total_tva = $total_tva; $propalligne->total_ttc = $total_ttc; - dolibarr_install_syslog("upgrade2: Line " . $rowid . ": propalid=" . $obj->rowid . " pu=" . $pu . " qty=" . $qty . " vatrate=" . $vatrate . " remise_percent=" . $remise_percent . " remise_global=" . $remise_percent_global . " -> " . $total_ht . ", " . $total_tva. ", " . $total_ttc); + dolibarr_install_syslog("upgrade2: Line ".$rowid.": propalid=".$obj->rowid." pu=".$pu." qty=".$qty." vatrate=".$vatrate." remise_percent=".$remise_percent." remise_global=".$remise_percent_global." -> ".$total_ht.", ".$total_tva.", ".$total_ttc); print ". "; $propalligne->update_total(); @@ -1683,9 +1683,9 @@ function migrate_price_contrat($db, $langs, $conf) { $db->begin(); - $tmpmysoc=new Societe($db); + $tmpmysoc = new Societe($db); $tmpmysoc->setMysoc($conf); - if (empty($tmpmysoc->country_id)) $tmpmysoc->country_id=0; // Ti not have this set to '' or will make sql syntax error. + if (empty($tmpmysoc->country_id)) $tmpmysoc->country_id = 0; // Ti not have this set to '' or will make sql syntax error. print ''; print ''; @@ -3722,7 +3722,7 @@ function migrate_categorie_association($db, $langs, $conf) $db->begin(); $sqlSelect = "SELECT fk_categorie_mere, fk_categorie_fille"; - $sqlSelect.= " FROM ".MAIN_DB_PREFIX."categorie_association"; + $sqlSelect .= " FROM ".MAIN_DB_PREFIX."categorie_association"; $resql = $db->query($sqlSelect); if ($resql) @@ -3737,11 +3737,11 @@ function migrate_categorie_association($db, $langs, $conf) $obj = $db->fetch_object($resql); $sqlUpdate = "UPDATE ".MAIN_DB_PREFIX."categorie SET "; - $sqlUpdate.= "fk_parent = ".$obj->fk_categorie_mere; - $sqlUpdate.= " WHERE rowid = ".$obj->fk_categorie_fille; + $sqlUpdate .= "fk_parent = ".$obj->fk_categorie_mere; + $sqlUpdate .= " WHERE rowid = ".$obj->fk_categorie_fille; - $result=$db->query($sqlUpdate); - if (! $result) + $result = $db->query($sqlUpdate); + if (!$result) { $error++; dol_print_error($db); @@ -3755,7 +3755,7 @@ function migrate_categorie_association($db, $langs, $conf) print $langs->trans('AlreadyDone')."
    \n"; } - if (! $error) + if (!$error) { // TODO DROP table in the next release /* @@ -3813,10 +3813,10 @@ function migrate_event_assignement($db, $langs, $conf) $db->begin(); $sqlSelect = "SELECT a.id, a.fk_user_action"; - $sqlSelect.= " FROM ".MAIN_DB_PREFIX."actioncomm as a"; - $sqlSelect.= " LEFT JOIN ".MAIN_DB_PREFIX."actioncomm_resources as ar ON ar.fk_actioncomm = a.id AND ar.element_type = 'user' AND ar.fk_element = a.fk_user_action"; - $sqlSelect.= " WHERE fk_user_action > 0 AND fk_user_action NOT IN (SELECT fk_element FROM ".MAIN_DB_PREFIX."actioncomm_resources as ar WHERE ar.fk_actioncomm = a.id AND ar.element_type = 'user')"; - $sqlSelect.= " ORDER BY a.id"; + $sqlSelect .= " FROM ".MAIN_DB_PREFIX."actioncomm as a"; + $sqlSelect .= " LEFT JOIN ".MAIN_DB_PREFIX."actioncomm_resources as ar ON ar.fk_actioncomm = a.id AND ar.element_type = 'user' AND ar.fk_element = a.fk_user_action"; + $sqlSelect .= " WHERE fk_user_action > 0 AND fk_user_action NOT IN (SELECT fk_element FROM ".MAIN_DB_PREFIX."actioncomm_resources as ar WHERE ar.fk_actioncomm = a.id AND ar.element_type = 'user')"; + $sqlSelect .= " ORDER BY a.id"; //print $sqlSelect; $resql = $db->query($sqlSelect); @@ -3832,10 +3832,10 @@ function migrate_event_assignement($db, $langs, $conf) $obj = $db->fetch_object($resql); $sqlUpdate = "INSERT INTO ".MAIN_DB_PREFIX."actioncomm_resources(fk_actioncomm, element_type, fk_element) "; - $sqlUpdate.= "VALUES(".$obj->id.", 'user', ".$obj->fk_user_action.")"; + $sqlUpdate .= "VALUES(".$obj->id.", 'user', ".$obj->fk_user_action.")"; - $result=$db->query($sqlUpdate); - if (! $result) + $result = $db->query($sqlUpdate); + if (!$result) { $error++; dol_print_error($db); @@ -3849,7 +3849,7 @@ function migrate_event_assignement($db, $langs, $conf) print $langs->trans('AlreadyDone')."
    \n"; } - if (! $error) + if (!$error) { $db->commit(); } @@ -3890,10 +3890,10 @@ function migrate_event_assignement_contact($db, $langs, $conf) $db->begin(); $sqlSelect = "SELECT a.id, a.fk_contact"; - $sqlSelect.= " FROM ".MAIN_DB_PREFIX."actioncomm as a"; - $sqlSelect.= " LEFT JOIN ".MAIN_DB_PREFIX."actioncomm_resources as ar ON ar.fk_actioncomm = a.id AND ar.element_type = 'socpeople' AND ar.fk_element = a.fk_contact"; - $sqlSelect.= " WHERE fk_contact > 0 AND fk_contact NOT IN (SELECT fk_element FROM ".MAIN_DB_PREFIX."actioncomm_resources as ar WHERE ar.fk_actioncomm = a.id AND ar.element_type = 'socpeople')"; - $sqlSelect.= " ORDER BY a.id"; + $sqlSelect .= " FROM ".MAIN_DB_PREFIX."actioncomm as a"; + $sqlSelect .= " LEFT JOIN ".MAIN_DB_PREFIX."actioncomm_resources as ar ON ar.fk_actioncomm = a.id AND ar.element_type = 'socpeople' AND ar.fk_element = a.fk_contact"; + $sqlSelect .= " WHERE fk_contact > 0 AND fk_contact NOT IN (SELECT fk_element FROM ".MAIN_DB_PREFIX."actioncomm_resources as ar WHERE ar.fk_actioncomm = a.id AND ar.element_type = 'socpeople')"; + $sqlSelect .= " ORDER BY a.id"; //print $sqlSelect; $resql = $db->query($sqlSelect); @@ -3909,10 +3909,10 @@ function migrate_event_assignement_contact($db, $langs, $conf) $obj = $db->fetch_object($resql); $sqlUpdate = "INSERT INTO ".MAIN_DB_PREFIX."actioncomm_resources(fk_actioncomm, element_type, fk_element) "; - $sqlUpdate.= "VALUES(".$obj->id.", 'socpeople', ".$obj->fk_contact.")"; + $sqlUpdate .= "VALUES(".$obj->id.", 'socpeople', ".$obj->fk_contact.")"; - $result=$db->query($sqlUpdate); - if (! $result) + $result = $db->query($sqlUpdate); + if (!$result) { $error++; dol_print_error($db); @@ -3926,7 +3926,7 @@ function migrate_event_assignement_contact($db, $langs, $conf) print $langs->trans('AlreadyDone')."
    \n"; } - if (! $error) + if (!$error) { $db->commit(); } @@ -3972,7 +3972,7 @@ function migrate_reset_blocked_log($db, $langs, $conf) $db->begin(); $sqlSelect = "SELECT DISTINCT entity"; - $sqlSelect.= " FROM ".MAIN_DB_PREFIX."blockedlog"; + $sqlSelect .= " FROM ".MAIN_DB_PREFIX."blockedlog"; //print $sqlSelect; @@ -4001,9 +4001,9 @@ function migrate_reset_blocked_log($db, $langs, $conf) print ' - Record for entity must be reset...'; $sqlUpdate = "DELETE FROM ".MAIN_DB_PREFIX."blockedlog"; - $sqlUpdate.= " WHERE entity = " . $obj->entity; - $resqlUpdate=$db->query($sqlUpdate); - if (! $resqlUpdate) + $sqlUpdate .= " WHERE entity = ".$obj->entity; + $resqlUpdate = $db->query($sqlUpdate); + if (!$resqlUpdate) { $error++; dol_print_error($db); @@ -4011,18 +4011,18 @@ function migrate_reset_blocked_log($db, $langs, $conf) else { // Add set line - $object=new stdClass(); + $object = new stdClass(); $object->id = 1; $object->element = 'module'; $object->ref = 'systemevent'; $object->entity = $obj->entity; $object->date = dol_now(); - $b=new BlockedLog($db); + $b = new BlockedLog($db); $b->setObjectData($object, 'MODULE_SET', 0); $res = $b->create($user); - if ($res<=0) { + if ($res <= 0) { $error++; } } @@ -4045,7 +4045,7 @@ function migrate_reset_blocked_log($db, $langs, $conf) print $langs->trans('NothingToDo')."
    \n"; } - if (! $error) + if (!$error) { $db->commit(); } @@ -4086,8 +4086,8 @@ function migrate_remise_entity($db, $langs, $conf) $db->begin(); $sqlSelect = "SELECT sr.rowid, s.entity"; - $sqlSelect.= " FROM ".MAIN_DB_PREFIX."societe_remise as sr, ".MAIN_DB_PREFIX."societe as s"; - $sqlSelect.= " WHERE sr.fk_soc = s.rowid and sr.entity != s.entity"; + $sqlSelect .= " FROM ".MAIN_DB_PREFIX."societe_remise as sr, ".MAIN_DB_PREFIX."societe as s"; + $sqlSelect .= " WHERE sr.fk_soc = s.rowid and sr.entity != s.entity"; //print $sqlSelect; @@ -4104,11 +4104,11 @@ function migrate_remise_entity($db, $langs, $conf) $obj = $db->fetch_object($resql); $sqlUpdate = "UPDATE ".MAIN_DB_PREFIX."societe_remise SET"; - $sqlUpdate.= " entity = " . $obj->entity; - $sqlUpdate.= " WHERE rowid = " . $obj->rowid; + $sqlUpdate .= " entity = ".$obj->entity; + $sqlUpdate .= " WHERE rowid = ".$obj->rowid; - $result=$db->query($sqlUpdate); - if (! $result) + $result = $db->query($sqlUpdate); + if (!$result) { $error++; dol_print_error($db); @@ -4123,7 +4123,7 @@ function migrate_remise_entity($db, $langs, $conf) print $langs->trans('AlreadyDone')."
    \n"; } - if (! $error) + if (!$error) { $db->commit(); } @@ -4163,7 +4163,7 @@ function migrate_remise_except_entity($db, $langs, $conf) $db->begin(); $sqlSelect = "SELECT sr.rowid, sr.fk_soc, sr.fk_facture_source, sr.fk_facture, sr.fk_facture_line"; - $sqlSelect.= " FROM ".MAIN_DB_PREFIX."societe_remise_except as sr"; + $sqlSelect .= " FROM ".MAIN_DB_PREFIX."societe_remise_except as sr"; //print $sqlSelect; $resql = $db->query($sqlSelect); @@ -4183,21 +4183,21 @@ function migrate_remise_except_entity($db, $langs, $conf) $fk_facture = (!empty($obj->fk_facture_source) ? $obj->fk_facture_source : $obj->fk_facture); $sqlSelect2 = "SELECT f.entity"; - $sqlSelect2.= " FROM ".MAIN_DB_PREFIX."facture as f"; - $sqlSelect2.= " WHERE f.rowid = " . $fk_facture; + $sqlSelect2 .= " FROM ".MAIN_DB_PREFIX."facture as f"; + $sqlSelect2 .= " WHERE f.rowid = ".$fk_facture; } elseif (!empty($obj->fk_facture_line)) { $sqlSelect2 = "SELECT f.entity"; - $sqlSelect2.= " FROM ".MAIN_DB_PREFIX."facture as f, ".MAIN_DB_PREFIX."facturedet as fd"; - $sqlSelect2.= " WHERE fd.rowid = " . $obj->fk_facture_line; - $sqlSelect2.= " AND fd.fk_facture = f.rowid"; + $sqlSelect2 .= " FROM ".MAIN_DB_PREFIX."facture as f, ".MAIN_DB_PREFIX."facturedet as fd"; + $sqlSelect2 .= " WHERE fd.rowid = ".$obj->fk_facture_line; + $sqlSelect2 .= " AND fd.fk_facture = f.rowid"; } else { $sqlSelect2 = "SELECT s.entity"; - $sqlSelect2.= " FROM ".MAIN_DB_PREFIX."societe as s"; - $sqlSelect2.= " WHERE s.rowid = " . $obj->fk_soc; + $sqlSelect2 .= " FROM ".MAIN_DB_PREFIX."societe as s"; + $sqlSelect2 .= " WHERE s.rowid = ".$obj->fk_soc; } $resql2 = $db->query($sqlSelect2); @@ -4208,11 +4208,11 @@ function migrate_remise_except_entity($db, $langs, $conf) $obj2 = $db->fetch_object($resql2); $sqlUpdate = "UPDATE ".MAIN_DB_PREFIX."societe_remise_except SET"; - $sqlUpdate.= " entity = " . $obj2->entity; - $sqlUpdate.= " WHERE rowid = " . $obj->rowid; + $sqlUpdate .= " entity = ".$obj2->entity; + $sqlUpdate .= " WHERE rowid = ".$obj->rowid; - $result=$db->query($sqlUpdate); - if (! $result) + $result = $db->query($sqlUpdate); + if (!$result) { $error++; dol_print_error($db); @@ -4234,7 +4234,7 @@ function migrate_remise_except_entity($db, $langs, $conf) print $langs->trans('AlreadyDone')."
    \n"; } - if (! $error) + if (!$error) { $db->commit(); } @@ -4274,8 +4274,8 @@ function migrate_user_rights_entity($db, $langs, $conf) $db->begin(); $sqlSelect = "SELECT u.rowid, u.entity"; - $sqlSelect.= " FROM ".MAIN_DB_PREFIX."user as u"; - $sqlSelect.= " WHERE u.entity > 1"; + $sqlSelect .= " FROM ".MAIN_DB_PREFIX."user as u"; + $sqlSelect .= " WHERE u.entity > 1"; //print $sqlSelect; $resql = $db->query($sqlSelect); @@ -4291,11 +4291,11 @@ function migrate_user_rights_entity($db, $langs, $conf) $obj = $db->fetch_object($resql); $sqlUpdate = "UPDATE ".MAIN_DB_PREFIX."user_rights SET"; - $sqlUpdate.= " entity = " . $obj->entity; - $sqlUpdate.= " WHERE fk_user = " . $obj->rowid; + $sqlUpdate .= " entity = ".$obj->entity; + $sqlUpdate .= " WHERE fk_user = ".$obj->rowid; - $result=$db->query($sqlUpdate); - if (! $result) + $result = $db->query($sqlUpdate); + if (!$result) { $error++; dol_print_error($db); @@ -4310,7 +4310,7 @@ function migrate_user_rights_entity($db, $langs, $conf) print $langs->trans('AlreadyDone')."
    \n"; } - if (! $error) + if (!$error) { $db->commit(); } @@ -4350,8 +4350,8 @@ function migrate_usergroup_rights_entity($db, $langs, $conf) $db->begin(); $sqlSelect = "SELECT u.rowid, u.entity"; - $sqlSelect.= " FROM ".MAIN_DB_PREFIX."usergroup as u"; - $sqlSelect.= " WHERE u.entity > 1"; + $sqlSelect .= " FROM ".MAIN_DB_PREFIX."usergroup as u"; + $sqlSelect .= " WHERE u.entity > 1"; //print $sqlSelect; $resql = $db->query($sqlSelect); @@ -4367,11 +4367,11 @@ function migrate_usergroup_rights_entity($db, $langs, $conf) $obj = $db->fetch_object($resql); $sqlUpdate = "UPDATE ".MAIN_DB_PREFIX."usergroup_rights SET"; - $sqlUpdate.= " entity = " . $obj->entity; - $sqlUpdate.= " WHERE fk_usergroup = " . $obj->rowid; + $sqlUpdate .= " entity = ".$obj->entity; + $sqlUpdate .= " WHERE fk_usergroup = ".$obj->rowid; - $result=$db->query($sqlUpdate); - if (! $result) + $result = $db->query($sqlUpdate); + if (!$result) { $error++; dol_print_error($db); @@ -4386,7 +4386,7 @@ function migrate_usergroup_rights_entity($db, $langs, $conf) print $langs->trans('AlreadyDone')."
    \n"; } - if (! $error) + if (!$error) { $db->commit(); } @@ -4419,9 +4419,9 @@ function migrate_rename_directories($db, $langs, $conf, $oldname, $newname) { dolibarr_install_syslog("upgrade2::migrate_rename_directories"); - if (is_dir(DOL_DATA_ROOT.$oldname) && ! file_exists(DOL_DATA_ROOT.$newname)) + if (is_dir(DOL_DATA_ROOT.$oldname) && !file_exists(DOL_DATA_ROOT.$newname)) { - dolibarr_install_syslog("upgrade2::migrate_rename_directories move " . DOL_DATA_ROOT . $oldname . ' into ' . DOL_DATA_ROOT . $newname); + dolibarr_install_syslog("upgrade2::migrate_rename_directories move ".DOL_DATA_ROOT.$oldname.' into '.DOL_DATA_ROOT.$newname); @rename(DOL_DATA_ROOT.$oldname, DOL_DATA_ROOT.$newname); } } @@ -4481,7 +4481,14 @@ function migrate_delete_old_files($db, $langs, $conf) '/societe/class/api_contact.class.php', '/societe/class/api_thirdparty.class.php', '/support/online.php', - '/takepos/class/actions_takepos.class.php' + '/takepos/class/actions_takepos.class.php', + + '/install/mysql/tables/llx_c_ticketsup_category.key.sql', + '/install/mysql/tables/llx_c_ticketsup_category.sql', + '/install/mysql/tables/llx_c_ticketsup_severity.key.sql', + '/install/mysql/tables/llx_c_ticketsup_severity.sql', + '/install/mysql/tables/llx_c_ticketsup_type.key.sql', + '/install/mysql/tables/llx_c_ticketsup_type.sql' ); foreach ($filetodeletearray as $filetodelete) { @@ -4489,9 +4496,9 @@ function migrate_delete_old_files($db, $langs, $conf) $result = 1; if (file_exists(DOL_DOCUMENT_ROOT.$filetodelete)) { $result = dol_delete_file(DOL_DOCUMENT_ROOT.$filetodelete, 0, 0, 0, null, true, false); - if (! $result) { + if (!$result) { $langs->load("errors"); - print '
    '.$langs->trans("Error").': '.$langs->trans("ErrorFailToDeleteFile", DOL_DOCUMENT_ROOT . $filetodelete); + print '
    '.$langs->trans("Error").': '.$langs->trans("ErrorFailToDeleteFile", DOL_DOCUMENT_ROOT.$filetodelete); print ' '.$langs->trans("RemoveItManuallyAndPressF5ToContinue").'
    '; } else { //print $langs->trans("FileWasRemoved", $filetodelete).'
    '; @@ -4516,7 +4523,7 @@ function migrate_delete_old_dir($db, $langs, $conf) dolibarr_install_syslog("upgrade2::migrate_delete_old_dir"); // List of files to delete - $filetodeletearray=array( + $filetodeletearray = array( DOL_DOCUMENT_ROOT.'/core/modules/facture/terre', DOL_DOCUMENT_ROOT.'/core/modules/facture/mercure', ); @@ -4526,7 +4533,7 @@ function migrate_delete_old_dir($db, $langs, $conf) if (file_exists($filetodelete)) { $result = dol_delete_dir_recursive($filetodelete); } - if (! $result) { + if (!$result) { $langs->load("errors"); print '
    '.$langs->trans("Error").': '.$langs->trans("ErrorFailToDeleteDir", $filetodelete); print ' '.$langs->trans("RemoveItManuallyAndPressF5ToContinue").'
    '; @@ -4554,18 +4561,18 @@ function migrate_reload_modules($db, $langs, $conf, $listofmodule = array(), $fo dolibarr_install_syslog("upgrade2::migrate_reload_modules force=".$force.", listofmodule=".join(',', array_keys($listofmodule))); - foreach($listofmodule as $moduletoreload => $reloadmode) // reloadmodule can be 'noboxes', 'newboxdefonly', 'forceactivate' + foreach ($listofmodule as $moduletoreload => $reloadmode) // reloadmodule can be 'noboxes', 'newboxdefonly', 'forceactivate' { - if (empty($moduletoreload) || (empty($conf->global->$moduletoreload) && ! $force)) continue; // Discard reload if module not enabled + if (empty($moduletoreload) || (empty($conf->global->$moduletoreload) && !$force)) continue; // Discard reload if module not enabled - $mod=null; + $mod = null; if ($moduletoreload == 'MAIN_MODULE_AGENDA') { dolibarr_install_syslog("upgrade2::migrate_reload_modules Reactivate Agenda module"); - $res=@include_once DOL_DOCUMENT_ROOT.'/core/modules/modAgenda.class.php'; + $res = @include_once DOL_DOCUMENT_ROOT.'/core/modules/modAgenda.class.php'; if ($res) { - $mod=new modAgenda($db); + $mod = new modAgenda($db); $mod->remove('noboxes'); $mod->init($reloadmode); } @@ -4573,9 +4580,9 @@ function migrate_reload_modules($db, $langs, $conf, $listofmodule = array(), $fo elseif ($moduletoreload == 'MAIN_MODULE_API') { dolibarr_install_syslog("upgrade2::migrate_reload_modules Reactivate Rest API module"); - $res=@include_once DOL_DOCUMENT_ROOT.'/core/modules/modApi.class.php'; + $res = @include_once DOL_DOCUMENT_ROOT.'/core/modules/modApi.class.php'; if ($res) { - $mod=new modApi($db); + $mod = new modApi($db); //$mod->remove('noboxes'); $mod->init($reloadmode); } @@ -4583,9 +4590,9 @@ function migrate_reload_modules($db, $langs, $conf, $listofmodule = array(), $fo elseif ($moduletoreload == 'MAIN_MODULE_BARCODE') { dolibarr_install_syslog("upgrade2::migrate_reload_modules Reactivate Barcode module"); - $res=@include_once DOL_DOCUMENT_ROOT.'/core/modules/modBarcode.class.php'; + $res = @include_once DOL_DOCUMENT_ROOT.'/core/modules/modBarcode.class.php'; if ($res) { - $mod=new modBarcode($db); + $mod = new modBarcode($db); $mod->remove('noboxes'); $mod->init($reloadmode); } @@ -4593,9 +4600,9 @@ function migrate_reload_modules($db, $langs, $conf, $listofmodule = array(), $fo elseif ($moduletoreload == 'MAIN_MODULE_CRON') { dolibarr_install_syslog("upgrade2::migrate_reload_modules Reactivate Cron module"); - $res=@include_once DOL_DOCUMENT_ROOT.'/core/modules/modCron.class.php'; + $res = @include_once DOL_DOCUMENT_ROOT.'/core/modules/modCron.class.php'; if ($res) { - $mod=new modCron($db); + $mod = new modCron($db); $mod->remove('noboxes'); $mod->init($reloadmode); } @@ -4603,9 +4610,9 @@ function migrate_reload_modules($db, $langs, $conf, $listofmodule = array(), $fo elseif ($moduletoreload == 'MAIN_MODULE_SOCIETE') { dolibarr_install_syslog("upgrade2::migrate_reload_modules Reactivate Societe module"); - $res=@include_once DOL_DOCUMENT_ROOT.'/core/modules/modSociete.class.php'; + $res = @include_once DOL_DOCUMENT_ROOT.'/core/modules/modSociete.class.php'; if ($res) { - $mod=new modSociete($db); + $mod = new modSociete($db); $mod->remove('noboxes'); $mod->init($reloadmode); } @@ -4613,9 +4620,9 @@ function migrate_reload_modules($db, $langs, $conf, $listofmodule = array(), $fo elseif ($moduletoreload == 'MAIN_MODULE_PRODUIT') // Permission has changed into 2.7 { dolibarr_install_syslog("upgrade2::migrate_reload_modules Reactivate Produit module"); - $res=@include_once DOL_DOCUMENT_ROOT.'/core/modules/modProduct.class.php'; + $res = @include_once DOL_DOCUMENT_ROOT.'/core/modules/modProduct.class.php'; if ($res) { - $mod=new modProduct($db); + $mod = new modProduct($db); //$mod->remove('noboxes'); $mod->init($reloadmode); } @@ -4623,9 +4630,9 @@ function migrate_reload_modules($db, $langs, $conf, $listofmodule = array(), $fo elseif ($moduletoreload == 'MAIN_MODULE_SERVICE') // Permission has changed into 2.7 { dolibarr_install_syslog("upgrade2::migrate_reload_modules Reactivate Service module"); - $res=@include_once DOL_DOCUMENT_ROOT.'/core/modules/modService.class.php'; + $res = @include_once DOL_DOCUMENT_ROOT.'/core/modules/modService.class.php'; if ($res) { - $mod=new modService($db); + $mod = new modService($db); //$mod->remove('noboxes'); $mod->init($reloadmode); } @@ -4633,9 +4640,9 @@ function migrate_reload_modules($db, $langs, $conf, $listofmodule = array(), $fo elseif ($moduletoreload == 'MAIN_MODULE_COMMANDE') // Permission has changed into 2.9 { dolibarr_install_syslog("upgrade2::migrate_reload_modules Reactivate Commande module"); - $res=@include_once DOL_DOCUMENT_ROOT.'/core/modules/modCommande.class.php'; + $res = @include_once DOL_DOCUMENT_ROOT.'/core/modules/modCommande.class.php'; if ($res) { - $mod=new modCommande($db); + $mod = new modCommande($db); //$mod->remove('noboxes'); $mod->init($reloadmode); } @@ -4643,9 +4650,9 @@ function migrate_reload_modules($db, $langs, $conf, $listofmodule = array(), $fo elseif ($moduletoreload == 'MAIN_MODULE_FACTURE') // Permission has changed into 2.9 { dolibarr_install_syslog("upgrade2::migrate_reload_modules Reactivate Facture module"); - $res=@include_once DOL_DOCUMENT_ROOT.'/core/modules/modFacture.class.php'; + $res = @include_once DOL_DOCUMENT_ROOT.'/core/modules/modFacture.class.php'; if ($res) { - $mod=new modFacture($db); + $mod = new modFacture($db); //$mod->remove('noboxes'); $mod->init($reloadmode); } @@ -4653,9 +4660,9 @@ function migrate_reload_modules($db, $langs, $conf, $listofmodule = array(), $fo elseif ($moduletoreload == 'MAIN_MODULE_FOURNISSEUR') // Permission has changed into 2.9 { dolibarr_install_syslog("upgrade2::migrate_reload_modules Reactivate Fournisseur module"); - $res=@include_once DOL_DOCUMENT_ROOT.'/core/modules/modFournisseur.class.php'; + $res = @include_once DOL_DOCUMENT_ROOT.'/core/modules/modFournisseur.class.php'; if ($res) { - $mod=new modFournisseur($db); + $mod = new modFournisseur($db); //$mod->remove('noboxes'); $mod->init($reloadmode); } @@ -4663,9 +4670,9 @@ function migrate_reload_modules($db, $langs, $conf, $listofmodule = array(), $fo elseif ($moduletoreload == 'MAIN_MODULE_HOLIDAY') // Permission and tabs has changed into 3.8 { dolibarr_install_syslog("upgrade2::migrate_reload_modules Reactivate Leave Request module"); - $res=@include_once DOL_DOCUMENT_ROOT.'/core/modules/modHoliday.class.php'; + $res = @include_once DOL_DOCUMENT_ROOT.'/core/modules/modHoliday.class.php'; if ($res) { - $mod=new modHoliday($db); + $mod = new modHoliday($db); $mod->remove('noboxes'); $mod->init($reloadmode); } @@ -4673,9 +4680,9 @@ function migrate_reload_modules($db, $langs, $conf, $listofmodule = array(), $fo elseif ($moduletoreload == 'MAIN_MODULE_DEPLACEMENT') // Permission has changed into 3.0 { dolibarr_install_syslog("upgrade2::migrate_reload_modules Reactivate Deplacement module"); - $res=@include_once DOL_DOCUMENT_ROOT.'/core/modules/modDeplacement.class.php'; + $res = @include_once DOL_DOCUMENT_ROOT.'/core/modules/modDeplacement.class.php'; if ($res) { - $mod=new modDeplacement($db); + $mod = new modDeplacement($db); //$mod->remove('noboxes'); $mod->init($reloadmode); } @@ -4683,9 +4690,9 @@ function migrate_reload_modules($db, $langs, $conf, $listofmodule = array(), $fo elseif ($moduletoreload == 'MAIN_MODULE_DON') // Permission has changed into 3.0 { dolibarr_install_syslog("upgrade2::migrate_reload_modules Reactivate Don module"); - $res=@include_once DOL_DOCUMENT_ROOT.'/core/modules/modDon.class.php'; + $res = @include_once DOL_DOCUMENT_ROOT.'/core/modules/modDon.class.php'; if ($res) { - $mod=new modDon($db); + $mod = new modDon($db); //$mod->remove('noboxes'); $mod->init($reloadmode); } @@ -4693,47 +4700,47 @@ function migrate_reload_modules($db, $langs, $conf, $listofmodule = array(), $fo elseif ($moduletoreload == 'MAIN_MODULE_ECM') // Permission has changed into 3.0 and 3.1 { dolibarr_install_syslog("upgrade2::migrate_reload_modules Reactivate ECM module"); - $res=@include_once DOL_DOCUMENT_ROOT.'/core/modules/modECM.class.php'; + $res = @include_once DOL_DOCUMENT_ROOT.'/core/modules/modECM.class.php'; if ($res) { - $mod=new modECM($db); - $mod->remove('noboxes'); // We need to remove because a permission id has been removed + $mod = new modECM($db); + $mod->remove('noboxes'); // We need to remove because a permission id has been removed $mod->init($reloadmode); } } elseif ($moduletoreload == 'MAIN_MODULE_PAYBOX') // Permission has changed into 3.0 { dolibarr_install_syslog("upgrade2::migrate_reload_modules Reactivate Paybox module"); - $res=@include_once DOL_DOCUMENT_ROOT.'/core/modules/modPaybox.class.php'; + $res = @include_once DOL_DOCUMENT_ROOT.'/core/modules/modPaybox.class.php'; if ($res) { - $mod=new modPaybox($db); - $mod->remove('noboxes'); // We need to remove because id of module has changed + $mod = new modPaybox($db); + $mod->remove('noboxes'); // We need to remove because id of module has changed $mod->init($reloadmode); } } elseif ($moduletoreload == 'MAIN_MODULE_SUPPLIERPROPOSAL') // Module after 3.5 { dolibarr_install_syslog("upgrade2::migrate_reload_modules Reactivate Supplier Proposal module"); - $res=@include_once DOL_DOCUMENT_ROOT.'/core/modules/modSupplierProposal.class.php'; + $res = @include_once DOL_DOCUMENT_ROOT.'/core/modules/modSupplierProposal.class.php'; if ($res) { - $mod=new modSupplierProposal($db); - $mod->remove('noboxes'); // We need to remove because id of module has changed + $mod = new modSupplierProposal($db); + $mod->remove('noboxes'); // We need to remove because id of module has changed $mod->init($reloadmode); } } elseif ($moduletoreload == 'MAIN_MODULE_OPENSURVEY') // Permission has changed into 3.0 { dolibarr_install_syslog("upgrade2::migrate_reload_modules Reactivate Opensurvey module"); - $res=@include_once DOL_DOCUMENT_ROOT.'/core/modules/modOpenSurvey.class.php'; + $res = @include_once DOL_DOCUMENT_ROOT.'/core/modules/modOpenSurvey.class.php'; if ($res) { - $mod=new modOpenSurvey($db); - $mod->remove('noboxes'); // We need to remove because menu entries has changed + $mod = new modOpenSurvey($db); + $mod->remove('noboxes'); // We need to remove because menu entries has changed $mod->init($reloadmode); } } else { $tmp = preg_match('/MAIN_MODULE_([a-zA-Z0-9]+)/', $moduletoreload, $reg); - if (! empty($reg[1])) + if (!empty($reg[1])) { if (strtoupper($moduletoreload) == $moduletoreload) // If key is un uppercase { @@ -4744,10 +4751,10 @@ function migrate_reload_modules($db, $langs, $conf, $listofmodule = array(), $fo $moduletoreloadshort = $reg[1]; } dolibarr_install_syslog("upgrade2::migrate_reload_modules Reactivate module ".$moduletoreloadshort." with mode ".$reloadmode); - $res=@include_once DOL_DOCUMENT_ROOT.'/core/modules/mod'.$moduletoreloadshort.'.class.php'; + $res = @include_once DOL_DOCUMENT_ROOT.'/core/modules/mod'.$moduletoreloadshort.'.class.php'; if ($res) { $classname = 'mod'.$moduletoreloadshort; - $mod=new $classname($db); + $mod = new $classname($db); //$mod->remove('noboxes'); $mod->init($reloadmode); } @@ -4755,10 +4762,10 @@ function migrate_reload_modules($db, $langs, $conf, $listofmodule = array(), $fo { dolibarr_install_syslog('Failed to include '.DOL_DOCUMENT_ROOT.'/core/modules/mod'.$moduletoreloadshort.'.class.php'); - $res=@dol_include_once(strtolower($moduletoreloadshort).'/core/modules/mod'.$moduletoreloadshort.'.class.php'); + $res = @dol_include_once(strtolower($moduletoreloadshort).'/core/modules/mod'.$moduletoreloadshort.'.class.php'); if ($res) { $classname = 'mod'.$moduletoreloadshort; - $mod=new $classname($db); + $mod = new $classname($db); //$mod->remove('noboxes'); $mod->init($reloadmode); } @@ -4775,11 +4782,11 @@ function migrate_reload_modules($db, $langs, $conf, $listofmodule = array(), $fo } } - if (! empty($mod) && is_object($mod)) + if (!empty($mod) && is_object($mod)) { print '
    '; @@ -4804,11 +4811,11 @@ function migrate_reload_menu($db, $langs, $conf, $versionto) dolibarr_install_syslog("upgrade2::migrate_reload_menu"); // Define list of menu handlers to initialize - $listofmenuhandler=array(); + $listofmenuhandler = array(); if ($conf->global->MAIN_MENU_STANDARD == 'auguria_menu' || $conf->global->MAIN_MENU_SMARTPHONE == 'auguria_menu' || $conf->global->MAIN_MENUFRONT_STANDARD == 'auguria_menu' || $conf->global->MAIN_MENUFRONT_SMARTPHONE == 'auguria_menu') { - $listofmenuhandler['auguria']=1; // We set here only dynamic menu handlers + $listofmenuhandler['auguria'] = 1; // We set here only dynamic menu handlers } foreach ($listofmenuhandler as $key => $val) @@ -4821,10 +4828,10 @@ function migrate_reload_menu($db, $langs, $conf, $versionto) // Load sql ini_menu_handler.sql file $dir = DOL_DOCUMENT_ROOT."/core/menus/"; - $file='init_menu_'.$key.'.sql'; + $file = 'init_menu_'.$key.'.sql'; if (file_exists($dir.$file)) { - $result=run_sql($dir.$file, 1, '', 1, $key); + $result = run_sql($dir.$file, 1, '', 1, $key); } print ''; @@ -4847,9 +4854,9 @@ function migrate_user_photospath() include_once DOL_DOCUMENT_ROOT.'/user/class/user.class.php'; $fuser = new User($db); - if (! is_object($user)) $user = $fuser; // To avoid error during migration + if (!is_object($user)) $user = $fuser; // To avoid error during migration - $sql = "SELECT rowid as uid from ".MAIN_DB_PREFIX."user"; // Get list of all users + $sql = "SELECT rowid as uid from ".MAIN_DB_PREFIX."user"; // Get list of all users $resql = $db->query($sql); if ($resql) { @@ -4859,25 +4866,25 @@ function migrate_user_photospath() //echo '
    '.$fuser->id.' -> '.$fuser->entity; $entity = (empty($fuser->entity) ? 1 : $fuser->entity); if ($entity > 1) { - $dir = DOL_DATA_ROOT . '/' . $entity . '/users'; + $dir = DOL_DATA_ROOT.'/'.$entity.'/users'; } else { - $dir = $conf->user->multidir_output[$entity]; // $conf->user->multidir_output[] for each entity is construct by the multicompany module + $dir = $conf->user->multidir_output[$entity]; // $conf->user->multidir_output[] for each entity is construct by the multicompany module } if ($dir) { //print "Process user id ".$fuser->id."
    \n"; - $origin = $dir .'/'. get_exdir($fuser->id, 2, 0, 1, $fuser, 'user'); // Use old behaviour to get x/y path - $destin = $dir .'/'. $fuser->id; + $origin = $dir.'/'.get_exdir($fuser->id, 2, 0, 1, $fuser, 'user'); // Use old behaviour to get x/y path + $destin = $dir.'/'.$fuser->id; - $origin_osencoded=dol_osencode($origin); + $origin_osencoded = dol_osencode($origin); dol_mkdir($destin); //echo '
    '.$origin.' -> '.$destin; if (dol_is_dir($origin)) { - $handle=opendir($origin_osencoded); + $handle = opendir($origin_osencoded); if (is_resource($handle)) { while (($file = readdir($handle)) !== false) @@ -4892,7 +4899,7 @@ function migrate_user_photospath() dol_mkdir($destin.'/'.$file); while (($thumb = readdir($thumbs)) !== false) { - if (! dol_is_file($destin.'/'.$file.'/'.$thumb)) + if (!dol_is_file($destin.'/'.$file.'/'.$thumb)) { if ($thumb == '.' || $thumb == '..') continue; @@ -4907,7 +4914,7 @@ function migrate_user_photospath() } else // it is a file { - if (! dol_is_file($destin.'/'.$file)) + if (!dol_is_file($destin.'/'.$file)) { //print $origin.'/'.$file.' -> '.$destin.'/'.$file.'
    '."\n"; print '.'; @@ -5023,7 +5030,7 @@ function migrate_users_socialnetworks() dol_print_error($db); $db->rollback(); } - print ''.$langs->trans('MigrationUsersSocialNetworks')."
    \n"; + print ''.$langs->trans('MigrationFieldsSocialNetworks', 'Users')."
    \n"; print ''; } @@ -5114,7 +5121,7 @@ function migrate_members_socialnetworks() dol_print_error($db); $db->rollback(); } - print ''.$langs->trans('MigrationMembersSocialNetworks')."
    \n"; + print ''.$langs->trans('MigrationFieldsSocialNetworks', 'Members')."
    \n"; print ''; } @@ -5209,7 +5216,7 @@ function migrate_contacts_socialnetworks() dol_print_error($db); $db->rollback(); } - print ''.$langs->trans('MigrationContactsSocialNetworks')."
    \n"; + print ''.$langs->trans('MigrationFieldsSocialNetworks', 'Contacts')."
    \n"; print ''; } @@ -5299,6 +5306,6 @@ function migrate_thirdparties_socialnetworks() dol_print_error($db); $db->rollback(); } - print ''.$langs->trans('MigrationThirdpartiesSocialNetworks')."
    \n"; + print ''.$langs->trans('MigrationFieldsSocialNetworks', 'Thirdparties')."
    \n"; print ''; } diff --git a/htdocs/langs/en_US/accountancy.lang b/htdocs/langs/en_US/accountancy.lang index 45133632481..a86c89aef09 100644 --- a/htdocs/langs/en_US/accountancy.lang +++ b/htdocs/langs/en_US/accountancy.lang @@ -167,12 +167,14 @@ ACCOUNTING_ACCOUNT_SUSPENSE=Accounting account of wait DONATION_ACCOUNTINGACCOUNT=Accounting account to register donations ADHERENT_SUBSCRIPTION_ACCOUNTINGACCOUNT=Accounting account to register subscriptions -ACCOUNTING_PRODUCT_BUY_ACCOUNT=Accounting account by default for bought products (used if not defined in the product sheet) +ACCOUNTING_PRODUCT_BUY_ACCOUNT=Accounting account by default for the bought products (used if not defined in the product sheet) ACCOUNTING_PRODUCT_SOLD_ACCOUNT=Accounting account by default for the sold products (used if not defined in the product sheet) -ACCOUNTING_PRODUCT_SOLD_INTRA_ACCOUNT=Accounting account by default for the sold products in EEC (used if not defined in the product sheet) -ACCOUNTING_PRODUCT_SOLD_EXPORT_ACCOUNT=Accounting account by default for the sold products export out of EEC (used if not defined in the product sheet) +ACCOUNTING_PRODUCT_SOLD_INTRA_ACCOUNT=Accounting account by default for the products sold in EEC (used if not defined in the product sheet) +ACCOUNTING_PRODUCT_SOLD_EXPORT_ACCOUNT=Accounting account by default for the products sold and exported out of EEC (used if not defined in the product sheet) ACCOUNTING_SERVICE_BUY_ACCOUNT=Accounting account by default for the bought services (used if not defined in the service sheet) ACCOUNTING_SERVICE_SOLD_ACCOUNT=Accounting account by default for the sold services (used if not defined in the service sheet) +ACCOUNTING_SERVICE_SOLD_INTRA_ACCOUNT=Accounting account by default for the services sold in EEC (used if not defined in the service sheet) +ACCOUNTING_SERVICE_SOLD_EXPORT_ACCOUNT=Accounting account by default for the services sold and exported out of EEC (used if not defined in the service sheet) Doctype=Type of document Docdate=Date diff --git a/htdocs/langs/en_US/admin.lang b/htdocs/langs/en_US/admin.lang index ebc8431f5e3..e7685ef25b9 100644 --- a/htdocs/langs/en_US/admin.lang +++ b/htdocs/langs/en_US/admin.lang @@ -268,6 +268,7 @@ Emails=Emails EMailsSetup=Emails setup EMailsDesc=This page allows you to override your default PHP parameters for email sending. In most cases on Unix/Linux OS, the PHP setup is correct and these parameters are unnecessary. EmailSenderProfiles=Emails sender profiles +EMailsSenderProfileDesc=You can keep this section empty. If you enter some emails here, they will be added to the list of possible senders into the combobox when your write a new email. MAIN_MAIL_SMTP_PORT=SMTP/SMTPS Port (default value in php.ini: %s) MAIN_MAIL_SMTP_SERVER=SMTP/SMTPS Host (default value in php.ini: %s) MAIN_MAIL_SMTP_PORT_NotAvailableOnLinuxLike=SMTP/SMTPS Port (Not defined into PHP on Unix-like systems) @@ -903,6 +904,7 @@ Permission20003=Delete leave requests Permission20004=Read all leave requests (even of user not subordinates) Permission20005=Create/modify leave requests for everybody (even of user not subordinates) Permission20006=Admin leave requests (setup and update balance) +Permission20007=Approve leave requests Permission23001=Read Scheduled job Permission23002=Create/update Scheduled job Permission23003=Delete Scheduled job diff --git a/htdocs/langs/en_US/agenda.lang b/htdocs/langs/en_US/agenda.lang index 465846a43db..9f141d15220 100644 --- a/htdocs/langs/en_US/agenda.lang +++ b/htdocs/langs/en_US/agenda.lang @@ -89,6 +89,7 @@ PRODUCT_MODIFYInDolibarr=Product %s modified PRODUCT_DELETEInDolibarr=Product %s deleted HOLIDAY_CREATEInDolibarr=Request for leave %s created HOLIDAY_MODIFYInDolibarr=Request for leave %s modified +HOLIDAY_APPROVEInDolibarr=Request for leave %s approved HOLIDAY_VALIDATEDInDolibarr=Request for leave %s validated HOLIDAY_DELETEInDolibarr=Request for leave %s deleted EXPENSE_REPORT_CREATEInDolibarr=Expense report %s created @@ -104,6 +105,14 @@ TICKET_MODIFYInDolibarr=Ticket %s modified TICKET_ASSIGNEDInDolibarr=Ticket %s assigned TICKET_CLOSEInDolibarr=Ticket %s closed TICKET_DELETEInDolibarr=Ticket %s deleted +BOM_VALIDATEInDolibarr=BOM validated +BOM_UNVALIDATEInDolibarr=BOM unvalidated +BOM_CLOSEInDolibarr=BOM disabled +BOM_REOPENInDolibarr=BOM reopen +BOM_DELETEInDolibarr=BOM deleted +MO_VALIDATEInDolibarr=MO validated +MO_PRODUCEDInDolibarr=MO produced +MO_DELETEInDolibarr=MO deleted ##### End agenda events ##### AgendaModelModule=Document templates for event DateActionStart=Start date diff --git a/htdocs/langs/en_US/errors.lang b/htdocs/langs/en_US/errors.lang index 96eedb296a3..53f9e57fceb 100644 --- a/htdocs/langs/en_US/errors.lang +++ b/htdocs/langs/en_US/errors.lang @@ -222,6 +222,7 @@ ErrorDeletePaymentLinkedToAClosedInvoiceNotPossible=Error, delete payment linked ErrorSearchCriteriaTooSmall=Search criteria too small. ErrorObjectMustHaveStatusActiveToBeDisabled=Objects must have status 'Active' to be disabled ErrorObjectMustHaveStatusDraftOrDisabledToBeActivated=Objects must have status 'Draft' or 'Disabled' to be enabled +ErrorNoFieldWithAttributeShowoncombobox=No fields has property 'showoncombobox' into definition of object '%s'. No way to show the combolist. # Warnings WarningParamUploadMaxFileSizeHigherThanPostMaxSize=Your PHP parameter upload_max_filesize (%s) is higher than PHP parameter post_max_size (%s). This is not a consistent setup. WarningPasswordSetWithNoAccount=A password was set for this member. However, no user account was created. So this password is stored but can't be used to login to Dolibarr. It may be used by an external module/interface but if you don't need to define any login nor password for a member, you can disable option "Manage a login for each member" from Member module setup. If you need to manage a login but don't need any password, you can keep this field empty to avoid this warning. Note: Email can also be used as a login if the member is linked to a user. @@ -246,4 +247,5 @@ WarningYourLoginWasModifiedPleaseLogin=Your login was modified. For security pur WarningAnEntryAlreadyExistForTransKey=An entry already exists for the translation key for this language WarningNumberOfRecipientIsRestrictedInMassAction=Warning, number of different recipient is limited to %s when using the mass actions on lists WarningDateOfLineMustBeInExpenseReportRange=Warning, the date of line is not in the range of the expense report -WarningProjectClosed=Project is closed. You must re-open it first. \ No newline at end of file +WarningProjectClosed=Project is closed. You must re-open it first. +WarningSomeBankTransactionByChequeWereRemovedAfter=Some bank transaction were removed after that the receipt including them were generated. So nb of cheques and total of receipt may differ from number and total in list. \ No newline at end of file diff --git a/htdocs/langs/en_US/holiday.lang b/htdocs/langs/en_US/holiday.lang index 9e31180f3ea..69b6a698e1a 100644 --- a/htdocs/langs/en_US/holiday.lang +++ b/htdocs/langs/en_US/holiday.lang @@ -127,4 +127,5 @@ HolidaysNumberingModules=Leave requests numbering models TemplatePDFHolidays=Template for leave requests PDF FreeLegalTextOnHolidays=Free text on PDF WatermarkOnDraftHolidayCards=Watermarks on draft leave requests -HolidaysToApprove=Holidays to approve \ No newline at end of file +HolidaysToApprove=Holidays to approve +NobodyHasPermissionToValidateHolidays=Nobody has permission to validate holidays diff --git a/htdocs/langs/en_US/install.lang b/htdocs/langs/en_US/install.lang index cfd95d879b7..708b3bac479 100644 --- a/htdocs/langs/en_US/install.lang +++ b/htdocs/langs/en_US/install.lang @@ -205,10 +205,7 @@ MigrationRemiseExceptEntity=Update entity field value of llx_societe_remise_exce MigrationUserRightsEntity=Update entity field value of llx_user_rights MigrationUserGroupRightsEntity=Update entity field value of llx_usergroup_rights MigrationUserPhotoPath=Migration of photo paths for users -MigrationUsersSocialNetworks=Migration of users fields social networks -MigrationMembersSocialNetworks=Migration of members fields social networks -MigrationContactsSocialNetworks=Migration of contacts fields social networks -MigrationThirdpartiesSocialNetworks=Migration of thirdparties fields social networks +MigrationFieldsSocialNetworks=Migration of users fields social networks (%s) MigrationReloadModule=Reload module %s MigrationResetBlockedLog=Reset module BlockedLog for v7 algorithm ShowNotAvailableOptions=Show unavailable options diff --git a/htdocs/langs/en_US/mrp.lang b/htdocs/langs/en_US/mrp.lang index fd89d8c8e38..2fa68d36061 100644 --- a/htdocs/langs/en_US/mrp.lang +++ b/htdocs/langs/en_US/mrp.lang @@ -48,4 +48,7 @@ DisableStockChange=Disable stock change DisableStockChangeHelp=When this flag is set, there is no stock change on this product, whatever is the quantity produced BomAndBomLines=Bills Of Material and lines BOMLine=Line of BOM -WarehouseForProduction=Warehouse for production \ No newline at end of file +WarehouseForProduction=Warehouse for production +CreateMO=Create MO +ToConsume=A consommer +Manufactured=Fabriqué diff --git a/htdocs/langs/en_US/paybox.lang b/htdocs/langs/en_US/paybox.lang index 35216661140..f70b3ee92eb 100644 --- a/htdocs/langs/en_US/paybox.lang +++ b/htdocs/langs/en_US/paybox.lang @@ -13,14 +13,6 @@ PaymentCode=Payment code PayBoxDoPayment=Pay with Paybox YouWillBeRedirectedOnPayBox=You will be redirected on secured Paybox page to input you credit card information Continue=Next -ToOfferALinkForOnlinePayment=URL for %s payment -ToOfferALinkForOnlinePaymentOnOrder=URL to offer a %s online payment user interface for a sales order -ToOfferALinkForOnlinePaymentOnInvoice=URL to offer a %s online payment user interface for a customer invoice -ToOfferALinkForOnlinePaymentOnContractLine=URL to offer a %s online payment user interface for a contract line -ToOfferALinkForOnlinePaymentOnFreeAmount=URL to offer a %s online payment user interface for a free amount -ToOfferALinkForOnlinePaymentOnMemberSubscription=URL to offer a %s online payment user interface for a member subscription -ToOfferALinkForOnlinePaymentOnDonation=URL to offer a %s online payment, user interface for payment of donation -YouCanAddTagOnUrl=You can also add url parameter &tag=value to any of those URL (required only for free payment) to add your own payment comment tag. SetupPayBoxToHavePaymentCreatedAutomatically=Setup your Paybox with url %s to have payment created automatically when validated by Paybox. YourPaymentHasBeenRecorded=This page confirms that your payment has been recorded. Thank you. YourPaymentHasNotBeenRecorded=Your payment has NOT been recorded and the transaction has been canceled. Thank you. diff --git a/htdocs/langs/en_US/stripe.lang b/htdocs/langs/en_US/stripe.lang index 6905bd41b20..92fe1051f08 100644 --- a/htdocs/langs/en_US/stripe.lang +++ b/htdocs/langs/en_US/stripe.lang @@ -16,12 +16,13 @@ StripeDoPayment=Pay with Stripe YouWillBeRedirectedOnStripe=You will be redirected on secured Stripe page to input you credit card information Continue=Next ToOfferALinkForOnlinePayment=URL for %s payment -ToOfferALinkForOnlinePaymentOnOrder=URL to offer a %s online payment user interface for a sales order -ToOfferALinkForOnlinePaymentOnInvoice=URL to offer a %s online payment user interface for a customer invoice -ToOfferALinkForOnlinePaymentOnContractLine=URL to offer a %s online payment user interface for a contract line -ToOfferALinkForOnlinePaymentOnFreeAmount=URL to offer a %s online payment user interface for a free amount -ToOfferALinkForOnlinePaymentOnMemberSubscription=URL to offer a %s online payment user interface for a member subscription -YouCanAddTagOnUrl=You can also add url parameter &tag=value to any of those URL (required only for free payment) to add your own payment comment tag. +ToOfferALinkForOnlinePaymentOnOrder=URL to offer a %s online payment page for a sales order +ToOfferALinkForOnlinePaymentOnInvoice=URL to offer a %s online payment page for a customer invoice +ToOfferALinkForOnlinePaymentOnContractLine=URL to offer a %s online payment page for a contract line +ToOfferALinkForOnlinePaymentOnFreeAmount=URL to offer a %s online payment page of any amount with no existing object +ToOfferALinkForOnlinePaymentOnMemberSubscription=URL to offer a %s online payment page for a member subscription +ToOfferALinkForOnlinePaymentOnDonation=URL to offer a %s online payment page for payment of a donation +YouCanAddTagOnUrl=You can also add url parameter &tag=value to any of those URL (mandatory only for payment not linked to an object) to add your own payment comment tag.
    For the URL of payments with no existing object, you may also add the parameter &noidempotency=1 so the same link with same tag can be used several times (some payment mode may limit the payment to 1 for each different link without this parameter) SetupStripeToHavePaymentCreatedAutomatically=Setup your Stripe with url %s to have payment created automatically when validated by Stripe. AccountParameter=Account parameters UsageParameter=Usage parameters diff --git a/htdocs/langs/en_US/ticket.lang b/htdocs/langs/en_US/ticket.lang index 14f06f8831f..53758677770 100644 --- a/htdocs/langs/en_US/ticket.lang +++ b/htdocs/langs/en_US/ticket.lang @@ -33,7 +33,9 @@ TicketDictSeverity=Ticket - Severities TicketTypeShortBUGSOFT=Dysfonctionnement logiciel TicketTypeShortBUGHARD=Dysfonctionnement matériel TicketTypeShortCOM=Commercial question -TicketTypeShortINCIDENT=Request for assistance +TicketTypeShortHELP=Request for functionnal help +TicketTypeShortISSUE=Issue, bug or problem +TicketTypeShortREQUEST=Change or enhancement request TicketTypeShortPROJET=Project TicketTypeShortOTHER=Other @@ -228,6 +230,7 @@ TicketNotNotifyTiersAtCreate=Not notify company at create Unread=Unread TicketNotCreatedFromPublicInterface=Not available. Ticket was not created from public interface. PublicInterfaceNotEnabled=Public interface was not enabled +ErrorTicketRefRequired=Ticket reference name is required # # Logs diff --git a/htdocs/langs/en_US/website.lang b/htdocs/langs/en_US/website.lang index 62ce5a23531..116b500fb7d 100644 --- a/htdocs/langs/en_US/website.lang +++ b/htdocs/langs/en_US/website.lang @@ -118,4 +118,5 @@ EditInLineOnOff=Mode 'Edit inline' is %s ShowSubContainersOnOff=Mode to execute 'dynamic content' is %s GlobalCSSorJS=Global CSS/JS/Header file of web site BackToHomePage=Back to home page... -TranslationLinks=Translation links \ No newline at end of file +TranslationLinks=Translation links +YouTryToAccessToAFileThatIsNotAWebsitePage=You try to access to a page that is not a website page \ No newline at end of file diff --git a/htdocs/langs/fr_FR/ticket.lang b/htdocs/langs/fr_FR/ticket.lang index 9154449ab20..0170e12c4c9 100644 --- a/htdocs/langs/fr_FR/ticket.lang +++ b/htdocs/langs/fr_FR/ticket.lang @@ -33,7 +33,7 @@ TicketDictSeverity=Ticket - Sévérités TicketTypeShortBUGSOFT=Dysfonctionnement logiciel TicketTypeShortBUGHARD=Dysfonctionnement matériel TicketTypeShortCOM=Question commerciale -TicketTypeShortINCIDENT=Demande d'assistance +TicketTypeShortISSUE=Incident ou problem TicketTypeShortPROJET=Projet TicketTypeShortOTHER=Autre diff --git a/htdocs/livraison/card.php b/htdocs/livraison/card.php index 8ac7494b8ab..e72dcb08fae 100644 --- a/htdocs/livraison/card.php +++ b/htdocs/livraison/card.php @@ -69,18 +69,18 @@ $extrafields->fetch_name_optionals_label($object->table_element); $extrafields->fetch_name_optionals_label($object->table_element_line); // Load object. Make an object->fetch -include DOL_DOCUMENT_ROOT.'/core/actions_fetchobject.inc.php'; // Must be include, not include_once +include DOL_DOCUMENT_ROOT.'/core/actions_fetchobject.inc.php'; // Must be include, not include_once // Initialize technical object to manage hooks of page. Note that conf->hooks_modules contains array of hook context -$hookmanager->initHooks(array('deliverycard','globalcard')); +$hookmanager->initHooks(array('deliverycard', 'globalcard')); /* * Actions */ -$parameters=array(); -$reshook=$hookmanager->executeHooks('doActions', $parameters, $object, $action); // Note that $action and $object may have been modified by some hooks +$parameters = array(); +$reshook = $hookmanager->executeHooks('doActions', $parameters, $object, $action); // Note that $action and $object may have been modified by some hooks if ($action == 'add') { @@ -91,9 +91,9 @@ if ($action == 'add') $object->commande_id = $_POST["commande_id"]; $object->fk_incoterms = GETPOST('incoterm_id', 'int'); - if (!$conf->expedition_bon->enabled && ! empty($conf->stock->enabled)) + if (!$conf->expedition_bon->enabled && !empty($conf->stock->enabled)) { - $expedition->entrepot_id = $_POST["entrepot_id"]; + $expedition->entrepot_id = $_POST["entrepot_id"]; } // On boucle sur chaque ligne de commande pour completer objet livraison @@ -101,7 +101,7 @@ if ($action == 'add') $commande = new Commande($db); $commande->fetch($object->commande_id); $commande->fetch_lines(); - $num=count($commande->lines); + $num = count($commande->lines); for ($i = 0; $i < $num; $i++) { $qty = "qtyl".$i; @@ -112,7 +112,7 @@ if ($action == 'add') } } - $ret=$object->create($user); + $ret = $object->create($user); if ($ret > 0) { $db->commit(); @@ -124,14 +124,14 @@ if ($action == 'add') setEventMessages($object->error, $object->errors, 'errors'); $db->rollback(); - $_GET["commande_id"]=$_POST["commande_id"]; - $action='create'; + $_GET["commande_id"] = $_POST["commande_id"]; + $action = 'create'; } } elseif ($action == 'confirm_valid' && $confirm == 'yes' && - ((empty($conf->global->MAIN_USE_ADVANCED_PERMS) && ! empty($user->rights->expedition->livraison->creer)) - || (! empty($conf->global->MAIN_USE_ADVANCED_PERMS) && ! empty($user->rights->expedition->livraison_advance->validate))) + ((empty($conf->global->MAIN_USE_ADVANCED_PERMS) && !empty($user->rights->expedition->livraison->creer)) + || (!empty($conf->global->MAIN_USE_ADVANCED_PERMS) && !empty($user->rights->expedition->livraison_advance->validate))) ) { $result = $object->valid($user); @@ -143,14 +143,14 @@ elseif ($action == 'confirm_valid' && $confirm == 'yes' && $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 (!empty($newlang)) { $outputlangs = new Translate("", $conf); $outputlangs->setDefaultLang($newlang); } - $model=$object->modelpdf; + $model = $object->modelpdf; $ret = $object->fetch($id); // Reload to get new records - $result=$object->generateDocument($model, $outputlangs, $hidedetails, $hidedesc, $hideref); + $result = $object->generateDocument($model, $outputlangs, $hidedetails, $hidedesc, $hideref); if ($result < 0) dol_print_error($db, $result); } } @@ -158,12 +158,12 @@ elseif ($action == 'confirm_valid' && $confirm == 'yes' && if ($action == 'confirm_delete' && $confirm == 'yes' && $user->rights->expedition->livraison->supprimer) { $db->begin(); - $result=$object->delete(); + $result = $object->delete(); if ($result > 0) { $db->commit(); - if (! empty($backtopage)) header("Location: ".$backtopage); + if (!empty($backtopage)) header("Location: ".$backtopage); else header("Location: ".DOL_URL_ROOT.'/expedition/list.php?restore_lastsearch_values=1'); exit; } @@ -175,11 +175,11 @@ if ($action == 'confirm_delete' && $confirm == 'yes' && $user->rights->expeditio if ($action == 'setdate_livraison' && $user->rights->expedition->livraison->creer) { - $datedelivery=dol_mktime(GETPOST('liv_hour', 'int'), GETPOST('liv_min', 'int'), 0, GETPOST('liv_month', 'int'), GETPOST('liv_day', 'int'), GETPOST('liv_year', 'int')); - $result=$object->set_date_livraison($user, $datedelivery); + $datedelivery = dol_mktime(GETPOST('liv_hour', 'int'), GETPOST('liv_min', 'int'), 0, GETPOST('liv_month', 'int'), GETPOST('liv_day', 'int'), GETPOST('liv_year', 'int')); + $result = $object->set_date_livraison($user, $datedelivery); if ($result < 0) { - $mesg='
    '.$object->error.'
    '; + $mesg = '
    '.$object->error.'
    '; } } @@ -198,7 +198,7 @@ if ($action == 'update_extras') $ret = $extrafields->setOptionalsFromPost(null, $object, GETPOST('attribute', 'none')); if ($ret < 0) $error++; - if (! $error) + if (!$error) { // Actions on extra fields $result = $object->insertExtraFields('DELIVERY_MODIFY'); @@ -216,8 +216,8 @@ if ($action == 'update_extras') // Extrafields line if ($action == 'update_extras_line') { - $array_options=array(); - $num=count($object->lines); + $array_options = array(); + $num = count($object->lines); for ($i = 0; $i < $num; $i++) { @@ -228,14 +228,14 @@ if ($action == 'update_extras_line') if (is_array($extralabelsline)) { // Get extra fields foreach ($extralabelsline as $key => $value) { - unset($_POST["options_" . $key]); + unset($_POST["options_".$key]); } } - $ret = $object->update_line($object->lines[$i]->id, $array_options[$i]); // extrafields update + $ret = $object->update_line($object->lines[$i]->id, $array_options[$i]); // extrafields update if ($ret < 0) { - $mesg='
    '.$object->error.'
    '; + $mesg = '
    '.$object->error.'
    '; $error++; } } @@ -319,9 +319,9 @@ else { // Origin of a 'livraison' (delivery receipt) is ALWAYS 'expedition' (shipment). // However, origin of shipment in future may differs (commande, proposal, ...) - $expedition=new Expedition($db); + $expedition = new Expedition($db); $result = $expedition->fetch($object->origin_id); - $typeobject = $expedition->origin; // example: commande + $typeobject = $expedition->origin; // example: commande if ($object->origin_id > 0) { $object->fetch_origin(); @@ -332,7 +332,7 @@ else $soc = new Societe($db); $soc->fetch($object->socid); - $head=delivery_prepare_head($object); + $head = delivery_prepare_head($object); print ''; @@ -367,52 +367,52 @@ else * Livraison */ - if ($typeobject == 'commande' && $expedition->origin_id > 0 && ! empty($conf->commande->enabled)) + if ($typeobject == 'commande' && $expedition->origin_id > 0 && !empty($conf->commande->enabled)) { - $objectsrc=new Commande($db); + $objectsrc = new Commande($db); $objectsrc->fetch($expedition->origin_id); } - if ($typeobject == 'propal' && $expedition->origin_id > 0 && ! empty($conf->propal->enabled)) + if ($typeobject == 'propal' && $expedition->origin_id > 0 && !empty($conf->propal->enabled)) { - $objectsrc=new Propal($db); + $objectsrc = new Propal($db); $objectsrc->fetch($expedition->origin_id); } // Shipment card - $linkback = ''.$langs->trans("BackToList").''; + $linkback = ''.$langs->trans("BackToList").''; - $morehtmlref='
    '; + $morehtmlref = '
    '; // Ref customer shipment - $morehtmlref.=$form->editfieldkey("RefCustomer", '', $expedition->ref_customer, $expedition, $user->rights->expedition->creer, 'string', '', 0, 1); - $morehtmlref.=$form->editfieldval("RefCustomer", '', $expedition->ref_customer, $expedition, $user->rights->expedition->creer, 'string', '', null, null, '', 1); - $morehtmlref.='
    '.$langs->trans("RefDeliveryReceipt").' : '.$object->ref; + $morehtmlref .= $form->editfieldkey("RefCustomer", '', $expedition->ref_customer, $expedition, $user->rights->expedition->creer, 'string', '', 0, 1); + $morehtmlref .= $form->editfieldval("RefCustomer", '', $expedition->ref_customer, $expedition, $user->rights->expedition->creer, 'string', '', null, null, '', 1); + $morehtmlref .= '
    '.$langs->trans("RefDeliveryReceipt").' : '.$object->ref; // Thirdparty - $morehtmlref.='
    '.$langs->trans('ThirdParty') . ' : ' . $expedition->thirdparty->getNomUrl(1); + $morehtmlref .= '
    '.$langs->trans('ThirdParty').' : '.$expedition->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').' '; if (0) { // Do not change on shipment if ($action != 'classify') { - $morehtmlref .= '' . img_edit($langs->transnoentitiesnoconv('SetProject')) . ' : '; + $morehtmlref .= ''.img_edit($langs->transnoentitiesnoconv('SetProject')).' : '; } if ($action == 'classify') { // $morehtmlref.=$form->form_project($_SERVER['PHP_SELF'] . '?id=' . $expedition->id, $expedition->socid, $expedition->fk_project, 'projectid', 0, 0, 1, 1); - $morehtmlref .= ''; + $morehtmlref .= ''; $morehtmlref .= ''; - $morehtmlref .= ''; + $morehtmlref .= ''; $morehtmlref .= $formproject->select_projects($expedition->socid, $expedition->fk_project, 'projectid', $maxlength, 0, 1, 0, 1, 0, 0, '', 1); - $morehtmlref .= ''; + $morehtmlref .= ''; $morehtmlref .= ''; } else { - $morehtmlref .= $form->form_project($_SERVER['PHP_SELF'] . '?id=' . $expedition->id, $expedition->socid, $expedition->fk_project, 'none', 0, 0, 0, 1); + $morehtmlref .= $form->form_project($_SERVER['PHP_SELF'].'?id='.$expedition->id, $expedition->socid, $expedition->fk_project, 'none', 0, 0, 0, 1); } } else { $morehtmlref .= ' : '; - if (! empty($objectsrc->fk_project)) { + if (!empty($objectsrc->fk_project)) { $proj = new Project($db); $proj->fetch($objectsrc->fk_project); - $morehtmlref .= ''; + $morehtmlref .= ''; $morehtmlref .= $proj->ref; $morehtmlref .= ''; } else { @@ -420,7 +420,7 @@ else } } } - $morehtmlref.='
    '; + $morehtmlref .= '
    '; $morehtmlright = $langs->trans("StatusReceipt").' : '.$object->getLibStatut(6).'
    '; @@ -460,19 +460,19 @@ else */ // Document origine - if ($typeobject == 'commande' && $expedition->origin_id && ! empty($conf->commande->enabled)) + if ($typeobject == 'commande' && $expedition->origin_id && !empty($conf->commande->enabled)) { print ''; - $order=new Commande($db); + $order = new Commande($db); $order->fetch($expedition->origin_id); print '\n"; print ''; } - if ($typeobject == 'propal' && $expedition->origin_id && ! empty($conf->propal->enabled)) + if ($typeobject == 'propal' && $expedition->origin_id && !empty($conf->propal->enabled)) { - $propal=new Propal($db); + $propal = new Propal($db); $propal->fetch($expedition->origin_id); print ''; print ''; } @@ -553,7 +553,7 @@ else print '\n"; print '';*/ - if (!$conf->expedition_bon->enabled && ! empty($conf->stock->enabled)) + if (!$conf->expedition_bon->enabled && !empty($conf->stock->enabled)) { // Entrepot $entrepot = new Entrepot($db); @@ -573,7 +573,7 @@ else } } $cols = 2; - include DOL_DOCUMENT_ROOT . '/core/tpl/extrafields_view.tpl.php'; + include DOL_DOCUMENT_ROOT.'/core/tpl/extrafields_view.tpl.php'; print "
    '.$langs->trans("ErrorFailedToConnectToDatabase", $conf->db->name).''.$langs->trans('Error').'
    '; print ''.$langs->trans('UpgradeExternalModule').': '.$langs->trans("None"); @@ -560,8 +560,8 @@ if (! GETPOST('action', 'aZ09') || preg_match('/upgrade/i', GETPOST('action', 'a // Copy directory medias - $srcroot=DOL_DOCUMENT_ROOT.'/install/medias'; - $destroot=DOL_DATA_ROOT.'/medias'; + $srcroot = DOL_DOCUMENT_ROOT.'/install/medias'; + $destroot = DOL_DATA_ROOT.'/medias'; dolCopyDir($srcroot, $destroot, 0, 0); @@ -581,12 +581,12 @@ else $error++; } -$ret=0; -if ($error && isset($argv[1])) $ret=1; +$ret = 0; +if ($error && isset($argv[1])) $ret = 1; dolibarr_install_syslog("Exit ".$ret); dolibarr_install_syslog("--- upgrade2: end"); -pFooter($error?2:0, $setuplang); +pFooter($error ? 2 : 0, $setuplang); if ($db->connected) $db->close(); @@ -630,7 +630,7 @@ function migrate_paiements($db, $langs, $conf) while ($i < $num) { $obj = $db->fetch_object($resql); - $row[$i][0] = $obj->rowid ; + $row[$i][0] = $obj->rowid; $row[$i][1] = $obj->fk_facture; $row[$i][2] = $obj->amount; $i++; @@ -647,11 +647,11 @@ function migrate_paiements($db, $langs, $conf) if ($db->begin()) { $res = 0; - $num=count($row); + $num = count($row); for ($i = 0; $i < $num; $i++) { $sql = "INSERT INTO ".MAIN_DB_PREFIX."paiement_facture (fk_facture, fk_paiement, amount)"; - $sql.= " VALUES (".$row[$i][1].",".$row[$i][0].",".$row[$i][2].")"; + $sql .= " VALUES (".$row[$i][1].",".$row[$i][0].",".$row[$i][2].")"; $res += $db->query($sql); @@ -710,13 +710,13 @@ function migrate_paiements_orphelins_1($db, $langs, $conf) { // Tous les enregistrements qui sortent de cette requete devrait avoir un pere dans llx_paiement_facture $sql = "SELECT distinct p.rowid, p.datec, p.amount as pamount, bu.fk_bank, b.amount as bamount,"; - $sql.= " bu2.url_id as socid"; - $sql.= " FROM (".MAIN_DB_PREFIX."paiement as p, ".MAIN_DB_PREFIX."bank_url as bu, ".MAIN_DB_PREFIX."bank as b)"; - $sql.= " LEFT JOIN ".MAIN_DB_PREFIX."paiement_facture as pf ON pf.fk_paiement = p.rowid"; - $sql.= " LEFT JOIN ".MAIN_DB_PREFIX."bank_url as bu2 ON (bu.fk_bank=bu2.fk_bank AND bu2.type = 'company')"; - $sql.= " WHERE pf.rowid IS NULL AND (p.rowid=bu.url_id AND bu.type='payment') AND bu.fk_bank = b.rowid"; - $sql.= " AND b.rappro = 1"; - $sql.= " AND (p.fk_facture = 0 OR p.fk_facture IS NULL)"; + $sql .= " bu2.url_id as socid"; + $sql .= " FROM (".MAIN_DB_PREFIX."paiement as p, ".MAIN_DB_PREFIX."bank_url as bu, ".MAIN_DB_PREFIX."bank as b)"; + $sql .= " LEFT JOIN ".MAIN_DB_PREFIX."paiement_facture as pf ON pf.fk_paiement = p.rowid"; + $sql .= " LEFT JOIN ".MAIN_DB_PREFIX."bank_url as bu2 ON (bu.fk_bank=bu2.fk_bank AND bu2.type = 'company')"; + $sql .= " WHERE pf.rowid IS NULL AND (p.rowid=bu.url_id AND bu.type='payment') AND bu.fk_bank = b.rowid"; + $sql .= " AND b.rappro = 1"; + $sql .= " AND (p.fk_facture = 0 OR p.fk_facture IS NULL)"; $resql = $db->query($sql); @@ -732,7 +732,7 @@ function migrate_paiements_orphelins_1($db, $langs, $conf) $obj = $db->fetch_object($resql); if ($obj->pamount == $obj->bamount && $obj->socid) // Pour etre sur d'avoir bon cas { - $row[$j]['paymentid'] = $obj->rowid ; // paymentid + $row[$j]['paymentid'] = $obj->rowid; // paymentid $row[$j]['pamount'] = $obj->pamount; $row[$j]['fk_bank'] = $obj->fk_bank; $row[$j]['bamount'] = $obj->bamount; @@ -754,30 +754,30 @@ function migrate_paiements_orphelins_1($db, $langs, $conf) $db->begin(); $res = 0; - $num=count($row); + $num = count($row); for ($i = 0; $i < $num; $i++) { if ($conf->global->MAIN_FEATURES_LEVEL == 2) print '* '.$row[$i]['datec'].' paymentid='.$row[$i]['paymentid'].' pamount='.$row[$i]['pamount'].' fk_bank='.$row[$i]['fk_bank'].' bamount='.$row[$i]['bamount'].' socid='.$row[$i]['socid'].'
    '; // On cherche facture sans lien paiement et du meme montant et pour meme societe. - $sql=" SELECT distinct f.rowid from ".MAIN_DB_PREFIX."facture as f"; - $sql.=" LEFT JOIN ".MAIN_DB_PREFIX."paiement_facture as pf ON f.rowid = pf.fk_facture"; - $sql.=" WHERE f.fk_statut in (2,3) AND fk_soc = ".$row[$i]['socid']." AND total_ttc = ".$row[$i]['pamount']; - $sql.=" AND pf.fk_facture IS NULL"; - $sql.=" ORDER BY f.fk_statut"; + $sql = " SELECT distinct f.rowid from ".MAIN_DB_PREFIX."facture as f"; + $sql .= " LEFT JOIN ".MAIN_DB_PREFIX."paiement_facture as pf ON f.rowid = pf.fk_facture"; + $sql .= " WHERE f.fk_statut in (2,3) AND fk_soc = ".$row[$i]['socid']." AND total_ttc = ".$row[$i]['pamount']; + $sql .= " AND pf.fk_facture IS NULL"; + $sql .= " ORDER BY f.fk_statut"; //print $sql.'
    '; - $resql=$db->query($sql); + $resql = $db->query($sql); if ($resql) { $num = $db->num_rows($resql); //print 'Nb of invoice found for this amount and company :'.$num.'
    '; if ($num >= 1) { - $obj=$db->fetch_object($resql); - $facid=$obj->rowid; + $obj = $db->fetch_object($resql); + $facid = $obj->rowid; $sql = "INSERT INTO ".MAIN_DB_PREFIX."paiement_facture (fk_facture, fk_paiement, amount)"; - $sql.= " VALUES (".$facid.",".$row[$i]['paymentid'].",".$row[$i]['pamount'].")"; + $sql .= " VALUES (".$facid.",".$row[$i]['paymentid'].",".$row[$i]['pamount'].")"; $res += $db->query($sql); @@ -837,12 +837,12 @@ function migrate_paiements_orphelins_2($db, $langs, $conf) { // Tous les enregistrements qui sortent de cette requete devrait avoir un pere dans llx_paiement_facture $sql = "SELECT distinct p.rowid, p.datec, p.amount as pamount, bu.fk_bank, b.amount as bamount,"; - $sql.= " bu2.url_id as socid"; - $sql.= " FROM (".MAIN_DB_PREFIX."paiement as p, ".MAIN_DB_PREFIX."bank_url as bu, ".MAIN_DB_PREFIX."bank as b)"; - $sql.= " LEFT JOIN ".MAIN_DB_PREFIX."paiement_facture as pf ON pf.fk_paiement = p.rowid"; - $sql.= " LEFT JOIN ".MAIN_DB_PREFIX."bank_url as bu2 ON (bu.fk_bank = bu2.fk_bank AND bu2.type = 'company')"; - $sql.= " WHERE pf.rowid IS NULL AND (p.fk_bank = bu.fk_bank AND bu.type = 'payment') AND bu.fk_bank = b.rowid"; - $sql.= " AND (p.fk_facture = 0 OR p.fk_facture IS NULL)"; + $sql .= " bu2.url_id as socid"; + $sql .= " FROM (".MAIN_DB_PREFIX."paiement as p, ".MAIN_DB_PREFIX."bank_url as bu, ".MAIN_DB_PREFIX."bank as b)"; + $sql .= " LEFT JOIN ".MAIN_DB_PREFIX."paiement_facture as pf ON pf.fk_paiement = p.rowid"; + $sql .= " LEFT JOIN ".MAIN_DB_PREFIX."bank_url as bu2 ON (bu.fk_bank = bu2.fk_bank AND bu2.type = 'company')"; + $sql .= " WHERE pf.rowid IS NULL AND (p.fk_bank = bu.fk_bank AND bu.type = 'payment') AND bu.fk_bank = b.rowid"; + $sql .= " AND (p.fk_facture = 0 OR p.fk_facture IS NULL)"; $resql = $db->query($sql); @@ -858,7 +858,7 @@ function migrate_paiements_orphelins_2($db, $langs, $conf) $obj = $db->fetch_object($resql); if ($obj->pamount == $obj->bamount && $obj->socid) // Pour etre sur d'avoir bon cas { - $row[$j]['paymentid'] = $obj->rowid ; // paymentid + $row[$j]['paymentid'] = $obj->rowid; // paymentid $row[$j]['pamount'] = $obj->pamount; $row[$j]['fk_bank'] = $obj->fk_bank; $row[$j]['bamount'] = $obj->bamount; @@ -874,9 +874,9 @@ function migrate_paiements_orphelins_2($db, $langs, $conf) dol_print_error($db); } - $nberr=0; + $nberr = 0; - $num=count($row); + $num = count($row); if ($num) { print $langs->trans('OrphelinsPaymentsDetectedByMethod', 2).': '.count($row)."
    \n"; @@ -888,24 +888,24 @@ function migrate_paiements_orphelins_2($db, $langs, $conf) if ($conf->global->MAIN_FEATURES_LEVEL == 2) print '* '.$row[$i]['datec'].' paymentid='.$row[$i]['paymentid'].' '.$row[$i]['pamount'].' fk_bank='.$row[$i]['fk_bank'].' '.$row[$i]['bamount'].' socid='.$row[$i]['socid'].'
    '; // On cherche facture sans lien paiement et du meme montant et pour meme societe. - $sql=" SELECT distinct f.rowid from ".MAIN_DB_PREFIX."facture as f"; - $sql.=" LEFT JOIN ".MAIN_DB_PREFIX."paiement_facture as pf ON f.rowid = pf.fk_facture"; - $sql.=" WHERE f.fk_statut in (2,3) AND fk_soc = ".$row[$i]['socid']." AND total_ttc = ".$row[$i]['pamount']; - $sql.=" AND pf.fk_facture IS NULL"; - $sql.=" ORDER BY f.fk_statut"; + $sql = " SELECT distinct f.rowid from ".MAIN_DB_PREFIX."facture as f"; + $sql .= " LEFT JOIN ".MAIN_DB_PREFIX."paiement_facture as pf ON f.rowid = pf.fk_facture"; + $sql .= " WHERE f.fk_statut in (2,3) AND fk_soc = ".$row[$i]['socid']." AND total_ttc = ".$row[$i]['pamount']; + $sql .= " AND pf.fk_facture IS NULL"; + $sql .= " ORDER BY f.fk_statut"; //print $sql.'
    '; - $resql=$db->query($sql); + $resql = $db->query($sql); if ($resql) { $num = $db->num_rows($resql); //print 'Nb of invoice found for this amount and company :'.$num.'
    '; if ($num >= 1) { - $obj=$db->fetch_object($resql); - $facid=$obj->rowid; + $obj = $db->fetch_object($resql); + $facid = $obj->rowid; $sql = "INSERT INTO ".MAIN_DB_PREFIX."paiement_facture (fk_facture, fk_paiement, amount)"; - $sql.= " VALUES (".$facid.",".$row[$i]['paymentid'].",".$row[$i]['pamount'].")"; + $sql .= " VALUES (".$facid.",".$row[$i]['paymentid'].",".$row[$i]['pamount'].")"; $res += $db->query($sql); print $langs->trans('MigrationProcessPaymentUpdate', 'facid='.$facid.'-paymentid='.$row[$i]['paymentid'].'-amount='.$row[$i]['pamount'])."
    \n"; @@ -971,19 +971,19 @@ function migrate_contracts_det($db, $langs, $conf) { print '
    '; - $nberr=0; + $nberr = 0; print '
    '; print ''.$langs->trans('MigrationContractsUpdate')."
    \n"; $sql = "SELECT c.rowid as cref, c.date_contrat, c.statut, c.mise_en_service, c.fin_validite, c.date_cloture, c.fk_product, c.fk_facture, c.fk_user_author,"; - $sql.= " p.ref, p.label, p.description, p.price, p.tva_tx, p.duration, cd.rowid"; - $sql.= " FROM ".MAIN_DB_PREFIX."contrat as c"; - $sql.= " LEFT JOIN ".MAIN_DB_PREFIX."product as p"; - $sql.= " ON c.fk_product = p.rowid"; - $sql.= " LEFT JOIN ".MAIN_DB_PREFIX."contratdet as cd"; - $sql.= " ON c.rowid=cd.fk_contrat"; - $sql.= " WHERE cd.rowid IS NULL AND p.rowid IS NOT NULL"; + $sql .= " p.ref, p.label, p.description, p.price, p.tva_tx, p.duration, cd.rowid"; + $sql .= " FROM ".MAIN_DB_PREFIX."contrat as c"; + $sql .= " LEFT JOIN ".MAIN_DB_PREFIX."product as p"; + $sql .= " ON c.fk_product = p.rowid"; + $sql .= " LEFT JOIN ".MAIN_DB_PREFIX."contratdet as cd"; + $sql .= " ON c.rowid=cd.fk_contrat"; + $sql .= " WHERE cd.rowid IS NULL AND p.rowid IS NOT NULL"; $resql = $db->query($sql); dolibarr_install_syslog("upgrade2::migrate_contracts_det"); @@ -1003,20 +1003,20 @@ function migrate_contracts_det($db, $langs, $conf) $obj = $db->fetch_object($resql); $sql = "INSERT INTO ".MAIN_DB_PREFIX."contratdet ("; - $sql.= "fk_contrat, fk_product, statut, label, description,"; - $sql.= "date_ouverture_prevue, date_ouverture, date_fin_validite, tva_tx, qty,"; - $sql.= "subprice, price_ht, fk_user_author, fk_user_ouverture)"; - $sql.= " VALUES ("; - $sql.= $obj->cref.",".($obj->fk_product?$obj->fk_product:0).","; - $sql.= ($obj->mise_en_service?"4":"0").","; - $sql.= "'".$db->escape($obj->label)."', null,"; - $sql.= ($obj->mise_en_service?"'".$obj->mise_en_service."'":($obj->date_contrat?"'".$obj->date_contrat."'":"null")).","; - $sql.= ($obj->mise_en_service?"'".$obj->mise_en_service."'":"null").","; - $sql.= ($obj->fin_validite?"'".$obj->fin_validite."'":"null").","; - $sql.= "'".$obj->tva_tx."', 1,"; - $sql.= "'".$obj->price."', '".$obj->price."',".$obj->fk_user_author.","; - $sql.= ($obj->mise_en_service?$obj->fk_user_author:"null"); - $sql.= ")"; + $sql .= "fk_contrat, fk_product, statut, label, description,"; + $sql .= "date_ouverture_prevue, date_ouverture, date_fin_validite, tva_tx, qty,"; + $sql .= "subprice, price_ht, fk_user_author, fk_user_ouverture)"; + $sql .= " VALUES ("; + $sql .= $obj->cref.",".($obj->fk_product ? $obj->fk_product : 0).","; + $sql .= ($obj->mise_en_service ? "4" : "0").","; + $sql .= "'".$db->escape($obj->label)."', null,"; + $sql .= ($obj->mise_en_service ? "'".$obj->mise_en_service."'" : ($obj->date_contrat ? "'".$obj->date_contrat."'" : "null")).","; + $sql .= ($obj->mise_en_service ? "'".$obj->mise_en_service."'" : "null").","; + $sql .= ($obj->fin_validite ? "'".$obj->fin_validite."'" : "null").","; + $sql .= "'".$obj->tva_tx."', 1,"; + $sql .= "'".$obj->price."', '".$obj->price."',".$obj->fk_user_author.","; + $sql .= ($obj->mise_en_service ? $obj->fk_user_author : "null"); + $sql .= ")"; if ($db->query($sql)) { @@ -1031,7 +1031,7 @@ function migrate_contracts_det($db, $langs, $conf) $i++; } - if (! $nberr) + if (!$nberr) { // $db->rollback(); $db->commit(); @@ -1069,17 +1069,17 @@ function migrate_links_transfert($db, $langs, $conf) { print '
    '; - $nberr=0; + $nberr = 0; print '
    '; print ''.$langs->trans('MigrationBankTransfertsUpdate')."
    \n"; $sql = "SELECT ba.rowid as barowid, bb.rowid as bbrowid"; - $sql.= " FROM ".MAIN_DB_PREFIX."bank as bb, ".MAIN_DB_PREFIX."bank as ba"; - $sql.= " LEFT JOIN ".MAIN_DB_PREFIX."bank_url as bu ON bu.fk_bank = ba.rowid"; - $sql.= " WHERE ba.amount = -bb.amount AND ba.fk_account <> bb.fk_account"; - $sql.= " AND ba.datev = bb.datev AND ba.datec = bb.datec"; - $sql.= " AND bu.fk_bank IS NULL"; + $sql .= " FROM ".MAIN_DB_PREFIX."bank as bb, ".MAIN_DB_PREFIX."bank as ba"; + $sql .= " LEFT JOIN ".MAIN_DB_PREFIX."bank_url as bu ON bu.fk_bank = ba.rowid"; + $sql .= " WHERE ba.amount = -bb.amount AND ba.fk_account <> bb.fk_account"; + $sql .= " AND ba.datev = bb.datev AND ba.datec = bb.datec"; + $sql .= " AND bu.fk_bank IS NULL"; $resql = $db->query($sql); dolibarr_install_syslog("upgrade2::migrate_links_transfert"); @@ -1099,16 +1099,16 @@ function migrate_links_transfert($db, $langs, $conf) $obj = $db->fetch_object($resql); $sql = "INSERT INTO ".MAIN_DB_PREFIX."bank_url ("; - $sql.= "fk_bank, url_id, url, label, type"; - $sql.= ")"; - $sql.= " VALUES ("; - $sql.= $obj->barowid.",".$obj->bbrowid.", '/compta/bank/line.php?rowid=', '(banktransfert)', 'banktransfert'"; - $sql.= ")"; + $sql .= "fk_bank, url_id, url, label, type"; + $sql .= ")"; + $sql .= " VALUES ("; + $sql .= $obj->barowid.",".$obj->bbrowid.", '/compta/bank/line.php?rowid=', '(banktransfert)', 'banktransfert'"; + $sql .= ")"; print $sql.'
    '; dolibarr_install_syslog("migrate_links_transfert"); - if (! $db->query($sql)) + if (!$db->query($sql)) { dol_print_error($db); $nberr++; @@ -1117,7 +1117,7 @@ function migrate_links_transfert($db, $langs, $conf) $i++; } - if (! $nberr) + if (!$nberr) { // $db->rollback(); $db->commit(); @@ -1156,19 +1156,19 @@ function migrate_contracts_date1($db, $langs, $conf) print '
    '; print ''.$langs->trans('MigrationContractsEmptyDatesUpdate')."
    \n"; - $sql="update ".MAIN_DB_PREFIX."contrat set date_contrat=tms where date_contrat is null"; + $sql = "update ".MAIN_DB_PREFIX."contrat set date_contrat=tms where date_contrat is null"; dolibarr_install_syslog("upgrade2::migrate_contracts_date1"); $resql = $db->query($sql); - if (! $resql) dol_print_error($db); + if (!$resql) dol_print_error($db); if ($db->affected_rows($resql) > 0) print $langs->trans('MigrationContractsEmptyDatesUpdateSuccess')."
    \n"; else print $langs->trans('MigrationContractsEmptyDatesNothingToUpdate')."
    \n"; - $sql="update ".MAIN_DB_PREFIX."contrat set datec=tms where datec is null"; + $sql = "update ".MAIN_DB_PREFIX."contrat set datec=tms where datec is null"; dolibarr_install_syslog("upgrade2::migrate_contracts_date1"); $resql = $db->query($sql); - if (! $resql) dol_print_error($db); + if (!$resql) dol_print_error($db); if ($db->affected_rows($resql) > 0) print $langs->trans('MigrationContractsEmptyCreationDatesUpdateSuccess')."
    \n"; else @@ -1184,16 +1184,16 @@ function migrate_contracts_date2($db, $langs, $conf) { print '
    '; - $nberr=0; + $nberr = 0; print '
    '; print ''.$langs->trans('MigrationContractsInvalidDatesUpdate')."
    \n"; $sql = "SELECT c.rowid as cref, c.datec, c.date_contrat, MIN(cd.date_ouverture) as datemin"; - $sql.= " FROM ".MAIN_DB_PREFIX."contrat as c,"; - $sql.= " ".MAIN_DB_PREFIX."contratdet as cd"; - $sql.= " WHERE c.rowid=cd.fk_contrat AND cd.date_ouverture IS NOT NULL"; - $sql.= " GROUP BY c.rowid, c.date_contrat"; + $sql .= " FROM ".MAIN_DB_PREFIX."contrat as c,"; + $sql .= " ".MAIN_DB_PREFIX."contratdet as cd"; + $sql .= " WHERE c.rowid=cd.fk_contrat AND cd.date_ouverture IS NOT NULL"; + $sql .= " GROUP BY c.rowid, c.date_contrat"; $resql = $db->query($sql); dolibarr_install_syslog("upgrade2::migrate_contracts_date2"); @@ -1205,7 +1205,7 @@ function migrate_contracts_date2($db, $langs, $conf) if ($num) { - $nbcontratsmodifie=0; + $nbcontratsmodifie = 0; $db->begin(); while ($i < $num) @@ -1214,11 +1214,11 @@ function migrate_contracts_date2($db, $langs, $conf) if ($obj->date_contrat > $obj->datemin) { print $langs->trans('MigrationContractsInvalidDateFix', $obj->cref, $obj->date_contrat, $obj->datemin)."
    \n"; - $sql ="UPDATE ".MAIN_DB_PREFIX."contrat"; - $sql.=" SET date_contrat='".$obj->datemin."'"; - $sql.=" WHERE rowid=".$obj->cref; - $resql2=$db->query($sql); - if (! $resql2) dol_print_error($db); + $sql = "UPDATE ".MAIN_DB_PREFIX."contrat"; + $sql .= " SET date_contrat='".$obj->datemin."'"; + $sql .= " WHERE rowid=".$obj->cref; + $resql2 = $db->query($sql); + if (!$resql2) dol_print_error($db); $nbcontratsmodifie++; } @@ -1256,10 +1256,10 @@ function migrate_contracts_date3($db, $langs, $conf) print '
    '; print ''.$langs->trans('MigrationContractsIncoherentCreationDateUpdate')."
    \n"; - $sql="update ".MAIN_DB_PREFIX."contrat set datec=date_contrat where datec is null or datec > date_contrat"; + $sql = "update ".MAIN_DB_PREFIX."contrat set datec=date_contrat where datec is null or datec > date_contrat"; dolibarr_install_syslog("upgrade2::migrate_contracts_date3"); $resql = $db->query($sql); - if (! $resql) dol_print_error($db); + if (!$resql) dol_print_error($db); if ($db->affected_rows($resql) > 0) print $langs->trans('MigrationContractsIncoherentCreationDateUpdateSuccess')."
    \n"; else @@ -1284,10 +1284,10 @@ function migrate_contracts_open($db, $langs, $conf) print ''.$langs->trans('MigrationReopeningContracts')."
    \n"; $sql = "SELECT c.rowid as cref FROM ".MAIN_DB_PREFIX."contrat as c, ".MAIN_DB_PREFIX."contratdet as cd"; - $sql.= " WHERE cd.statut = 4 AND c.statut=2 AND c.rowid=cd.fk_contrat"; + $sql .= " WHERE cd.statut = 4 AND c.statut=2 AND c.rowid=cd.fk_contrat"; dolibarr_install_syslog("upgrade2::migrate_contracts_open"); $resql = $db->query($sql); - if (! $resql) dol_print_error($db); + if (!$resql) dol_print_error($db); if ($db->affected_rows($resql) > 0) { $i = 0; $row = array(); @@ -1295,7 +1295,7 @@ function migrate_contracts_open($db, $langs, $conf) if ($num) { - $nbcontratsmodifie=0; + $nbcontratsmodifie = 0; $db->begin(); while ($i < $num) @@ -1303,11 +1303,11 @@ function migrate_contracts_open($db, $langs, $conf) $obj = $db->fetch_object($resql); print $langs->trans('MigrationReopenThisContract', $obj->cref)."
    \n"; - $sql ="UPDATE ".MAIN_DB_PREFIX."contrat"; - $sql.=" SET statut=1"; - $sql.=" WHERE rowid=".$obj->cref; - $resql2=$db->query($sql); - if (! $resql2) dol_print_error($db); + $sql = "UPDATE ".MAIN_DB_PREFIX."contrat"; + $sql .= " SET statut=1"; + $sql .= " WHERE rowid=".$obj->cref; + $resql2 = $db->query($sql); + if (!$resql2) dol_print_error($db); $nbcontratsmodifie++; @@ -1348,31 +1348,31 @@ function migrate_paiementfourn_facturefourn($db, $langs, $conf) $obj = $db->fetch_object($result); if ($obj) { - $error=0; - $nb=0; + $error = 0; + $nb = 0; $select_sql = 'SELECT rowid, fk_facture_fourn, amount'; - $select_sql.= ' FROM '.MAIN_DB_PREFIX.'paiementfourn'; - $select_sql.= ' WHERE fk_facture_fourn IS NOT NULL'; + $select_sql .= ' FROM '.MAIN_DB_PREFIX.'paiementfourn'; + $select_sql .= ' WHERE fk_facture_fourn IS NOT NULL'; dolibarr_install_syslog("upgrade2::migrate_paiementfourn_facturefourn"); $select_resql = $db->query($select_sql); if ($select_resql) { $select_num = $db->num_rows($select_resql); - $i=0; + $i = 0; $var = true; // Pour chaque paiement fournisseur, on insere une ligne dans paiementfourn_facturefourn - while (($i < $select_num) && (! $error)) + while (($i < $select_num) && (!$error)) { $var = !$var; $select_obj = $db->fetch_object($select_resql); // Verifier si la ligne est deja dans la nouvelle table. On ne veut pas inserer de doublons. $check_sql = 'SELECT fk_paiementfourn, fk_facturefourn'; - $check_sql.= ' FROM '.MAIN_DB_PREFIX.'paiementfourn_facturefourn'; - $check_sql.= ' WHERE fk_paiementfourn = '.$select_obj->rowid.' AND fk_facturefourn = '.$select_obj->fk_facture_fourn; + $check_sql .= ' FROM '.MAIN_DB_PREFIX.'paiementfourn_facturefourn'; + $check_sql .= ' WHERE fk_paiementfourn = '.$select_obj->rowid.' AND fk_facturefourn = '.$select_obj->fk_facture_fourn; $check_resql = $db->query($check_sql); if ($check_resql) { @@ -1391,9 +1391,9 @@ function migrate_paiementfourn_facturefourn($db, $langs, $conf) print '
    '.$select_obj->rowid.''.$select_obj->fk_facture_fourn.''.$select_obj->amount.'
    '; @@ -1694,13 +1694,13 @@ function migrate_price_contrat($db, $langs, $conf) // List of contract lines not up to date $sql = "SELECT cd.rowid, cd.qty, cd.subprice, cd.remise_percent, cd.tva_tx as vatrate, cd.info_bits,"; - $sql.= " c.rowid as contratid"; - $sql.= " FROM ".MAIN_DB_PREFIX."contratdet as cd, ".MAIN_DB_PREFIX."contrat as c"; - $sql.= " WHERE cd.fk_contrat = c.rowid"; - $sql.= " AND ((cd.total_ttc = 0 AND cd.remise_percent != 100 AND cd.subprice > 0) or cd.total_ttc IS NULL)"; + $sql .= " c.rowid as contratid"; + $sql .= " FROM ".MAIN_DB_PREFIX."contratdet as cd, ".MAIN_DB_PREFIX."contrat as c"; + $sql .= " WHERE cd.fk_contrat = c.rowid"; + $sql .= " AND ((cd.total_ttc = 0 AND cd.remise_percent != 100 AND cd.subprice > 0) or cd.total_ttc IS NULL)"; dolibarr_install_syslog("upgrade2::migrate_price_contrat"); - $resql=$db->query($sql); + $resql = $db->query($sql); if ($resql) { $num = $db->num_rows($resql); @@ -1719,11 +1719,11 @@ function migrate_price_contrat($db, $langs, $conf) $info_bits = $obj->info_bits; // On met a jour les 3 nouveaux champs - $contratligne= new ContratLigne($db); + $contratligne = new ContratLigne($db); //$contratligne->fetch($rowid); Non requis car le update_total ne met a jour que chp redefinis $contratligne->fetch($rowid); - $result=calcul_price_total($qty, $pu, $remise_percent, $vatrate, 0, 0, 0, 'HT', $info_bits, $contratligne->product_type, $tmpmysoc); + $result = calcul_price_total($qty, $pu, $remise_percent, $vatrate, 0, 0, 0, 'HT', $info_bits, $contratligne->product_type, $tmpmysoc); $total_ht = $result[0]; $total_tva = $result[1]; $total_ttc = $result[2]; @@ -1732,7 +1732,7 @@ function migrate_price_contrat($db, $langs, $conf) $contratligne->total_tva = $total_tva; $contratligne->total_ttc = $total_ttc; - dolibarr_install_syslog("upgrade2: Line " . $rowid . ": contratdetid=" . $obj->rowid . " pu=" . $pu . " qty=" . $qty . " vatrate=" . $vatrate . " remise_percent=" . $remise_percent. " -> " . $total_ht . ", " . $total_tva. " , " . $total_ttc); + dolibarr_install_syslog("upgrade2: Line ".$rowid.": contratdetid=".$obj->rowid." pu=".$pu." qty=".$qty." vatrate=".$vatrate." remise_percent=".$remise_percent." -> ".$total_ht.", ".$total_tva." , ".$total_ttc); print ". "; $contratligne->update_total(); @@ -1772,7 +1772,7 @@ function migrate_price_commande($db, $langs, $conf) { $db->begin(); - $tmpmysoc=new Societe($db); + $tmpmysoc = new Societe($db); $tmpmysoc->setMysoc($conf); print '
    '; @@ -1782,13 +1782,13 @@ function migrate_price_commande($db, $langs, $conf) // List of sales orders lines not up to date $sql = "SELECT cd.rowid, cd.qty, cd.subprice, cd.remise_percent, cd.tva_tx as vatrate, cd.info_bits,"; - $sql.= " c.rowid as commandeid, c.remise_percent as remise_percent_global"; - $sql.= " FROM ".MAIN_DB_PREFIX."commandedet as cd, ".MAIN_DB_PREFIX."commande as c"; - $sql.= " WHERE cd.fk_commande = c.rowid"; - $sql.= " AND ((cd.total_ttc = 0 AND cd.remise_percent != 100) or cd.total_ttc IS NULL)"; + $sql .= " c.rowid as commandeid, c.remise_percent as remise_percent_global"; + $sql .= " FROM ".MAIN_DB_PREFIX."commandedet as cd, ".MAIN_DB_PREFIX."commande as c"; + $sql .= " WHERE cd.fk_commande = c.rowid"; + $sql .= " AND ((cd.total_ttc = 0 AND cd.remise_percent != 100) or cd.total_ttc IS NULL)"; dolibarr_install_syslog("upgrade2::migrate_price_commande"); - $resql=$db->query($sql); + $resql = $db->query($sql); if ($resql) { $num = $db->num_rows($resql); @@ -1808,10 +1808,10 @@ function migrate_price_commande($db, $langs, $conf) $info_bits = $obj->info_bits; // On met a jour les 3 nouveaux champs - $commandeligne= new OrderLine($db); + $commandeligne = new OrderLine($db); $commandeligne->fetch($rowid); - $result=calcul_price_total($qty, $pu, $remise_percent, $vatrate, 0, 0, $remise_percent_global, 'HT', $info_bits, $commandeligne->product_type, $tmpmysoc); + $result = calcul_price_total($qty, $pu, $remise_percent, $vatrate, 0, 0, $remise_percent_global, 'HT', $info_bits, $commandeligne->product_type, $tmpmysoc); $total_ht = $result[0]; $total_tva = $result[1]; $total_ttc = $result[2]; @@ -1820,7 +1820,7 @@ function migrate_price_commande($db, $langs, $conf) $commandeligne->total_tva = $total_tva; $commandeligne->total_ttc = $total_ttc; - dolibarr_install_syslog("upgrade2: Line " . $rowid . " : commandeid=" . $obj->rowid . " pu=" . $pu . " qty=" . $qty . " vatrate=" . $vatrate . " remise_percent=" . $remise_percent . " remise_global=" . $remise_percent_global. " -> " . $total_ht . ", " . $total_tva . ", " . $total_ttc); + dolibarr_install_syslog("upgrade2: Line ".$rowid." : commandeid=".$obj->rowid." pu=".$pu." qty=".$qty." vatrate=".$vatrate." remise_percent=".$remise_percent." remise_global=".$remise_percent_global." -> ".$total_ht.", ".$total_tva.", ".$total_ttc); print ". "; $commandeligne->update_total(); @@ -1889,7 +1889,7 @@ function migrate_price_commande_fournisseur($db, $langs, $conf) { $db->begin(); - $tmpmysoc=new Societe($db); + $tmpmysoc = new Societe($db); $tmpmysoc->setMysoc($conf); print '
    '; @@ -1899,13 +1899,13 @@ function migrate_price_commande_fournisseur($db, $langs, $conf) // List of purchase order lines not up to date $sql = "SELECT cd.rowid, cd.qty, cd.subprice, cd.remise_percent, cd.tva_tx as vatrate, cd.info_bits,"; - $sql.= " c.rowid as commandeid, c.remise_percent as remise_percent_global"; - $sql.= " FROM ".MAIN_DB_PREFIX."commande_fournisseurdet as cd, ".MAIN_DB_PREFIX."commande_fournisseur as c"; - $sql.= " WHERE cd.fk_commande = c.rowid"; - $sql.= " AND ((cd.total_ttc = 0 AND cd.remise_percent != 100) or cd.total_ttc IS NULL)"; + $sql .= " c.rowid as commandeid, c.remise_percent as remise_percent_global"; + $sql .= " FROM ".MAIN_DB_PREFIX."commande_fournisseurdet as cd, ".MAIN_DB_PREFIX."commande_fournisseur as c"; + $sql .= " WHERE cd.fk_commande = c.rowid"; + $sql .= " AND ((cd.total_ttc = 0 AND cd.remise_percent != 100) or cd.total_ttc IS NULL)"; dolibarr_install_syslog("upgrade2::migrate_price_commande_fournisseur"); - $resql=$db->query($sql); + $resql = $db->query($sql); if ($resql) { $num = $db->num_rows($resql); @@ -1925,10 +1925,10 @@ function migrate_price_commande_fournisseur($db, $langs, $conf) $info_bits = $obj->info_bits; // On met a jour les 3 nouveaux champs - $commandeligne= new CommandeFournisseurLigne($db); + $commandeligne = new CommandeFournisseurLigne($db); $commandeligne->fetch($rowid); - $result=calcul_price_total($qty, $pu, $remise_percent, $vatrate, 0, 0, $remise_percent_global, 'HT', $info_bits, $commandeligne->product_type, $tmpsoc); + $result = calcul_price_total($qty, $pu, $remise_percent, $vatrate, 0, 0, $remise_percent_global, 'HT', $info_bits, $commandeligne->product_type, $tmpsoc); $total_ht = $result[0]; $total_tva = $result[1]; $total_ttc = $result[2]; @@ -1937,7 +1937,7 @@ function migrate_price_commande_fournisseur($db, $langs, $conf) $commandeligne->total_tva = $total_tva; $commandeligne->total_ttc = $total_ttc; - dolibarr_install_syslog("upgrade2: Line " . $rowid . ": commandeid=" . $obj->rowid . " pu=" . $pu . " qty=" . $qty . " vatrate=" . $vatrate . " remise_percent=" . $remise_percent . " remise_global=" . $remise_percent_global . " -> " . $total_ht . ", " . $total_tva . ", " . $total_ttc); + dolibarr_install_syslog("upgrade2: Line ".$rowid.": commandeid=".$obj->rowid." pu=".$pu." qty=".$qty." vatrate=".$vatrate." remise_percent=".$remise_percent." remise_global=".$remise_percent_global." -> ".$total_ht.", ".$total_tva.", ".$total_ttc); print ". "; $commandeligne->update_total(); @@ -2009,42 +2009,42 @@ function migrate_modeles($db, $langs, $conf) dolibarr_install_syslog("upgrade2::migrate_modeles"); - if (! empty($conf->facture->enabled)) + if (!empty($conf->facture->enabled)) { include_once DOL_DOCUMENT_ROOT.'/core/modules/facture/modules_facture.php'; - $modellist=ModelePDFFactures::liste_modeles($db); - if (count($modellist)==0) + $modellist = ModelePDFFactures::liste_modeles($db); + if (count($modellist) == 0) { // Aucun model par defaut. - $sql=" insert into ".MAIN_DB_PREFIX."document_model(nom,type) values('crabe','invoice')"; + $sql = " insert into ".MAIN_DB_PREFIX."document_model(nom,type) values('crabe','invoice')"; $resql = $db->query($sql); - if (! $resql) dol_print_error($db); + if (!$resql) dol_print_error($db); } } - if (! empty($conf->commande->enabled)) + if (!empty($conf->commande->enabled)) { include_once DOL_DOCUMENT_ROOT.'/core/modules/commande/modules_commande.php'; - $modellist=ModelePDFCommandes::liste_modeles($db); - if (count($modellist)==0) + $modellist = ModelePDFCommandes::liste_modeles($db); + if (count($modellist) == 0) { // Aucun model par defaut. - $sql=" insert into ".MAIN_DB_PREFIX."document_model(nom,type) values('einstein','order')"; + $sql = " insert into ".MAIN_DB_PREFIX."document_model(nom,type) values('einstein','order')"; $resql = $db->query($sql); - if (! $resql) dol_print_error($db); + if (!$resql) dol_print_error($db); } } - if (! empty($conf->expedition->enabled)) + if (!empty($conf->expedition->enabled)) { include_once DOL_DOCUMENT_ROOT.'/core/modules/expedition/modules_expedition.php'; - $modellist=ModelePDFExpedition::liste_modeles($db); - if (count($modellist)==0) + $modellist = ModelePDFExpedition::liste_modeles($db); + if (count($modellist) == 0) { // Aucun model par defaut. - $sql=" insert into ".MAIN_DB_PREFIX."document_model(nom,type) values('rouget','shipping')"; + $sql = " insert into ".MAIN_DB_PREFIX."document_model(nom,type) values('rouget','shipping')"; $resql = $db->query($sql); - if (! $resql) dol_print_error($db); + if (!$resql) dol_print_error($db); } } @@ -2091,8 +2091,8 @@ function migrate_commande_expedition($db, $langs, $conf) $obj = $db->fetch_object($resql); $sql = "INSERT INTO ".MAIN_DB_PREFIX."co_exp (fk_expedition,fk_commande)"; - $sql.= " VALUES (".$obj->rowid.",".$obj->fk_commande.")"; - $resql2=$db->query($sql); + $sql .= " VALUES (".$obj->rowid.",".$obj->fk_commande.")"; + $resql2 = $db->query($sql); if (!$resql2) { @@ -2155,9 +2155,9 @@ function migrate_commande_livraison($db, $langs, $conf) $db->begin(); $sql = "SELECT l.rowid, l.fk_commande"; - $sql.= ", c.ref_client, c.date_livraison"; - $sql.= " FROM ".MAIN_DB_PREFIX."livraison as l, ".MAIN_DB_PREFIX."commande as c"; - $sql.= " WHERE c.rowid = l.fk_commande"; + $sql .= ", c.ref_client, c.date_livraison"; + $sql .= " FROM ".MAIN_DB_PREFIX."livraison as l, ".MAIN_DB_PREFIX."commande as c"; + $sql .= " WHERE c.rowid = l.fk_commande"; $resql = $db->query($sql); if ($resql) { @@ -2171,16 +2171,16 @@ function migrate_commande_livraison($db, $langs, $conf) $obj = $db->fetch_object($resql); $sql = "INSERT INTO ".MAIN_DB_PREFIX."co_liv (fk_livraison,fk_commande)"; - $sql.= " VALUES (".$obj->rowid.",".$obj->fk_commande.")"; - $resql2=$db->query($sql); + $sql .= " VALUES (".$obj->rowid.",".$obj->fk_commande.")"; + $resql2 = $db->query($sql); if ($resql2) { $sqlu = "UPDATE ".MAIN_DB_PREFIX."livraison SET"; - $sqlu.= " ref_client='".$obj->ref_client."'"; - $sqlu.= ", date_livraison='".$obj->date_livraison."'"; - $sqlu.= " WHERE rowid = ".$obj->rowid; - $resql3=$db->query($sqlu); + $sqlu .= " ref_client='".$obj->ref_client."'"; + $sqlu .= ", date_livraison='".$obj->date_livraison."'"; + $sqlu .= " WHERE rowid = ".$obj->rowid; + $resql3 = $db->query($sqlu); if (!$resql3) { $error++; @@ -2250,9 +2250,9 @@ function migrate_detail_livraison($db, $langs, $conf) $db->begin(); $sql = "SELECT cd.rowid, cd.fk_product, cd.description, cd.subprice, cd.total_ht"; - $sql.= ", ld.fk_livraison"; - $sql.= " FROM ".MAIN_DB_PREFIX."commandedet as cd, ".MAIN_DB_PREFIX."livraisondet as ld"; - $sql.= " WHERE ld.fk_commande_ligne = cd.rowid"; + $sql .= ", ld.fk_livraison"; + $sql .= " FROM ".MAIN_DB_PREFIX."commandedet as cd, ".MAIN_DB_PREFIX."livraisondet as ld"; + $sql .= " WHERE ld.fk_commande_ligne = cd.rowid"; $resql = $db->query($sql); if ($resql) { @@ -2266,19 +2266,19 @@ function migrate_detail_livraison($db, $langs, $conf) $obj = $db->fetch_object($resql); $sql = "UPDATE ".MAIN_DB_PREFIX."livraisondet SET"; - $sql.= " fk_product=".$obj->fk_product; - $sql.= ",description='".$db->escape($obj->description)."'"; - $sql.= ",subprice='".$obj->subprice."'"; - $sql.= ",total_ht='".$obj->total_ht."'"; - $sql.= " WHERE fk_commande_ligne = ".$obj->rowid; - $resql2=$db->query($sql); + $sql .= " fk_product=".$obj->fk_product; + $sql .= ",description='".$db->escape($obj->description)."'"; + $sql .= ",subprice='".$obj->subprice."'"; + $sql .= ",total_ht='".$obj->total_ht."'"; + $sql .= " WHERE fk_commande_ligne = ".$obj->rowid; + $resql2 = $db->query($sql); if ($resql2) { $sql = "SELECT total_ht"; - $sql.= " FROM ".MAIN_DB_PREFIX."livraison"; - $sql.= " WHERE rowid = ".$obj->fk_livraison; - $resql3=$db->query($sql); + $sql .= " FROM ".MAIN_DB_PREFIX."livraison"; + $sql .= " WHERE rowid = ".$obj->fk_livraison; + $resql3 = $db->query($sql); if ($resql3) { @@ -2286,9 +2286,9 @@ function migrate_detail_livraison($db, $langs, $conf) $total_ht = $obju->total_ht + $obj->total_ht; $sqlu = "UPDATE ".MAIN_DB_PREFIX."livraison SET"; - $sqlu.= " total_ht='".$total_ht."'"; - $sqlu.= " WHERE rowid=".$obj->fk_livraison; - $resql4=$db->query($sqlu); + $sqlu .= " total_ht='".$total_ht."'"; + $sqlu .= " WHERE rowid=".$obj->fk_livraison; + $resql4 = $db->query($sqlu); if (!$resql4) { $error++; @@ -2365,8 +2365,8 @@ function migrate_stocks($db, $langs, $conf) $db->begin(); $sql = "SELECT SUM(reel) as total, fk_product"; - $sql.= " FROM ".MAIN_DB_PREFIX."product_stock as ps"; - $sql.= " GROUP BY fk_product"; + $sql .= " FROM ".MAIN_DB_PREFIX."product_stock as ps"; + $sql .= " GROUP BY fk_product"; $resql = $db->query($sql); if ($resql) { @@ -2380,10 +2380,10 @@ function migrate_stocks($db, $langs, $conf) $obj = $db->fetch_object($resql); $sql = "UPDATE ".MAIN_DB_PREFIX."product SET"; - $sql.= " stock = '".$obj->total."'"; - $sql.= " WHERE rowid=".$obj->fk_product; + $sql .= " stock = '".$obj->total."'"; + $sql .= " WHERE rowid=".$obj->fk_product; - $resql2=$db->query($sql); + $resql2 = $db->query($sql); if ($resql2) { } @@ -2440,9 +2440,9 @@ function migrate_menus($db, $langs, $conf) $db->begin(); $sql = "SELECT m.rowid, mc.action"; - $sql.= " FROM ".MAIN_DB_PREFIX."menu_constraint as mc, ".MAIN_DB_PREFIX."menu_const as md, ".MAIN_DB_PREFIX."menu as m"; - $sql.= " WHERE md.fk_menu = m.rowid AND md.fk_constraint = mc.rowid"; - $sql.= " AND m.enabled = '1'"; + $sql .= " FROM ".MAIN_DB_PREFIX."menu_constraint as mc, ".MAIN_DB_PREFIX."menu_const as md, ".MAIN_DB_PREFIX."menu as m"; + $sql .= " WHERE md.fk_menu = m.rowid AND md.fk_constraint = mc.rowid"; + $sql .= " AND m.enabled = '1'"; $resql = $db->query($sql); if ($resql) { @@ -2455,11 +2455,11 @@ function migrate_menus($db, $langs, $conf) $obj = $db->fetch_object($resql); $sql = "UPDATE ".MAIN_DB_PREFIX."menu SET"; - $sql.= " enabled = '".$obj->action."'"; - $sql.= " WHERE rowid=".$obj->rowid; - $sql.= " AND enabled = '1'"; + $sql .= " enabled = '".$obj->action."'"; + $sql .= " WHERE rowid=".$obj->rowid; + $sql .= " AND enabled = '1'"; - $resql2=$db->query($sql); + $resql2 = $db->query($sql); if ($resql2) { } @@ -2521,10 +2521,10 @@ function migrate_commande_deliveryaddress($db, $langs, $conf) $db->begin(); $sql = "SELECT c.fk_adresse_livraison, ce.fk_expedition"; - $sql.= " FROM ".MAIN_DB_PREFIX."commande as c"; - $sql.= ", ".MAIN_DB_PREFIX."co_exp as ce"; - $sql.= " WHERE c.rowid = ce.fk_commande"; - $sql.= " AND c.fk_adresse_livraison IS NOT NULL AND c.fk_adresse_livraison != 0"; + $sql .= " FROM ".MAIN_DB_PREFIX."commande as c"; + $sql .= ", ".MAIN_DB_PREFIX."co_exp as ce"; + $sql .= " WHERE c.rowid = ce.fk_commande"; + $sql .= " AND c.fk_adresse_livraison IS NOT NULL AND c.fk_adresse_livraison != 0"; $resql = $db->query($sql); if ($resql) @@ -2539,10 +2539,10 @@ function migrate_commande_deliveryaddress($db, $langs, $conf) $obj = $db->fetch_object($resql); $sql = "UPDATE ".MAIN_DB_PREFIX."expedition SET"; - $sql.= " fk_adresse_livraison = '".$obj->fk_adresse_livraison."'"; - $sql.= " WHERE rowid=".$obj->fk_expedition; + $sql .= " fk_adresse_livraison = '".$obj->fk_adresse_livraison."'"; + $sql .= " WHERE rowid=".$obj->fk_expedition; - $resql2=$db->query($sql); + $resql2 = $db->query($sql); if (!$resql2) { $error++; @@ -2595,7 +2595,7 @@ function migrate_restore_missing_links($db, $langs, $conf) if (($db->type == 'mysql' || $db->type == 'mysqli')) { - if (versioncompare($db->getVersionArray(), array(4,0)) < 0) + if (versioncompare($db->getVersionArray(), array(4, 0)) < 0) { dolibarr_install_syslog("upgrade2::migrate_restore_missing_links Version of database too old to make this migrate action"); return 0; @@ -2610,16 +2610,16 @@ function migrate_restore_missing_links($db, $langs, $conf) // Restore missing link for this cross foreign key (link 1 <=> 1). Direction 1. - $table1='facturedet'; $field1='fk_remise_except'; - $table2='societe_remise_except'; $field2='fk_facture_line'; + $table1 = 'facturedet'; $field1 = 'fk_remise_except'; + $table2 = 'societe_remise_except'; $field2 = 'fk_facture_line'; $db->begin(); $sql = "SELECT t1.rowid, t1.".$field1." as field"; - $sql.= " FROM ".MAIN_DB_PREFIX.$table1." as t1"; - $sql.= " WHERE t1.".$field1." IS NOT NULL AND t1.".$field1." NOT IN"; - $sql.= " (SELECT t2.rowid FROM ".MAIN_DB_PREFIX.$table2." as t2"; - $sql.= " WHERE t1.rowid = t2.".$field2.")"; + $sql .= " FROM ".MAIN_DB_PREFIX.$table1." as t1"; + $sql .= " WHERE t1.".$field1." IS NOT NULL AND t1.".$field1." NOT IN"; + $sql .= " (SELECT t2.rowid FROM ".MAIN_DB_PREFIX.$table2." as t2"; + $sql .= " WHERE t1.rowid = t2.".$field2.")"; dolibarr_install_syslog("upgrade2::migrate_restore_missing_links DIRECTION 1"); $resql = $db->query($sql); @@ -2636,11 +2636,11 @@ function migrate_restore_missing_links($db, $langs, $conf) print 'Line '.$obj->rowid.' in '.$table1.' is linked to record '.$obj->field.' in '.$table2.' that has no link to '.$table1.'. We fix this.
    '; $sql = "UPDATE ".MAIN_DB_PREFIX.$table2." SET"; - $sql.= " ".$field2." = '".$obj->rowid."'"; - $sql.= " WHERE rowid=".$obj->field; + $sql .= " ".$field2." = '".$obj->rowid."'"; + $sql .= " WHERE rowid=".$obj->field; - $resql2=$db->query($sql); - if (! $resql2) + $resql2 = $db->query($sql); + if (!$resql2) { $error++; dol_print_error($db); @@ -2675,16 +2675,16 @@ function migrate_restore_missing_links($db, $langs, $conf) print ''.$langs->trans('MigrationFixData')." (2)
    \n"; // Restore missing link for this cross foreign key (link 1 <=> 1). Direction 2. - $table2='facturedet'; $field2='fk_remise_except'; - $table1='societe_remise_except'; $field1='fk_facture_line'; + $table2 = 'facturedet'; $field2 = 'fk_remise_except'; + $table1 = 'societe_remise_except'; $field1 = 'fk_facture_line'; $db->begin(); $sql = "SELECT t1.rowid, t1.".$field1." as field"; - $sql.= " FROM ".MAIN_DB_PREFIX.$table1." as t1"; - $sql.= " WHERE t1.".$field1." IS NOT NULL AND t1.".$field1." NOT IN"; - $sql.= " (SELECT t2.rowid FROM ".MAIN_DB_PREFIX.$table2." as t2"; - $sql.= " WHERE t1.rowid = t2.".$field2.")"; + $sql .= " FROM ".MAIN_DB_PREFIX.$table1." as t1"; + $sql .= " WHERE t1.".$field1." IS NOT NULL AND t1.".$field1." NOT IN"; + $sql .= " (SELECT t2.rowid FROM ".MAIN_DB_PREFIX.$table2." as t2"; + $sql .= " WHERE t1.rowid = t2.".$field2.")"; dolibarr_install_syslog("upgrade2::migrate_restore_missing_links DIRECTION 2"); $resql = $db->query($sql); @@ -2701,11 +2701,11 @@ function migrate_restore_missing_links($db, $langs, $conf) print 'Line '.$obj->rowid.' in '.$table1.' is linked to record '.$obj->field.' in '.$table2.' that has no link to '.$table1.'. We fix this.
    '; $sql = "UPDATE ".MAIN_DB_PREFIX.$table2." SET"; - $sql.= " ".$field2." = '".$obj->rowid."'"; - $sql.= " WHERE rowid=".$obj->field; + $sql .= " ".$field2." = '".$obj->rowid."'"; + $sql .= " WHERE rowid=".$obj->field; - $resql2=$db->query($sql); - if (! $resql2) + $resql2 = $db->query($sql); + if (!$resql2) { $error++; dol_print_error($db); @@ -2776,22 +2776,22 @@ function migrate_project_user_resp($db, $langs, $conf) $obj = $db->fetch_object($resql); $sql2 = "INSERT INTO ".MAIN_DB_PREFIX."element_contact ("; - $sql2.= "datecreate"; - $sql2.= ", statut"; - $sql2.= ", element_id"; - $sql2.= ", fk_c_type_contact"; - $sql2.= ", fk_socpeople"; - $sql2.= ") VALUES ("; - $sql2.= "'".$db->idate(dol_now())."'"; - $sql2.= ", '4'"; - $sql2.= ", ".$obj->rowid; - $sql2.= ", '160'"; - $sql2.= ", ".$obj->fk_user_resp; - $sql2.= ")"; + $sql2 .= "datecreate"; + $sql2 .= ", statut"; + $sql2 .= ", element_id"; + $sql2 .= ", fk_c_type_contact"; + $sql2 .= ", fk_socpeople"; + $sql2 .= ") VALUES ("; + $sql2 .= "'".$db->idate(dol_now())."'"; + $sql2 .= ", '4'"; + $sql2 .= ", ".$obj->rowid; + $sql2 .= ", '160'"; + $sql2 .= ", ".$obj->fk_user_resp; + $sql2 .= ")"; if ($obj->fk_user_resp > 0) { - $resql2=$db->query($sql2); + $resql2 = $db->query($sql2); if (!$resql2) { $error++; @@ -2871,20 +2871,20 @@ function migrate_project_task_actors($db, $langs, $conf) $obj = $db->fetch_object($resql); $sql2 = "INSERT INTO ".MAIN_DB_PREFIX."element_contact ("; - $sql2.= "datecreate"; - $sql2.= ", statut"; - $sql2.= ", element_id"; - $sql2.= ", fk_c_type_contact"; - $sql2.= ", fk_socpeople"; - $sql2.= ") VALUES ("; - $sql2.= "'".$db->idate(dol_now())."'"; - $sql2.= ", '4'"; - $sql2.= ", ".$obj->fk_project_task; - $sql2.= ", '180'"; - $sql2.= ", ".$obj->fk_user; - $sql2.= ")"; + $sql2 .= "datecreate"; + $sql2 .= ", statut"; + $sql2 .= ", element_id"; + $sql2 .= ", fk_c_type_contact"; + $sql2 .= ", fk_socpeople"; + $sql2 .= ") VALUES ("; + $sql2 .= "'".$db->idate(dol_now())."'"; + $sql2 .= ", '4'"; + $sql2 .= ", ".$obj->fk_project_task; + $sql2 .= ", '180'"; + $sql2 .= ", ".$obj->fk_user; + $sql2 .= ")"; - $resql2=$db->query($sql2); + $resql2 = $db->query($sql2); if (!$resql2) { @@ -2950,12 +2950,12 @@ function migrate_relationship_tables($db, $langs, $conf, $table, $fk_source, $so if ($db->DDLInfoTable(MAIN_DB_PREFIX.$table)) { - dolibarr_install_syslog("upgrade2::migrate_relationship_tables table = " . MAIN_DB_PREFIX . $table); + dolibarr_install_syslog("upgrade2::migrate_relationship_tables table = ".MAIN_DB_PREFIX.$table); $db->begin(); $sqlSelect = "SELECT ".$fk_source.", ".$fk_target; - $sqlSelect.= " FROM ".MAIN_DB_PREFIX.$table; + $sqlSelect .= " FROM ".MAIN_DB_PREFIX.$table; $resql = $db->query($sqlSelect); if ($resql) @@ -2970,19 +2970,19 @@ function migrate_relationship_tables($db, $langs, $conf, $table, $fk_source, $so $obj = $db->fetch_object($resql); $sqlInsert = "INSERT INTO ".MAIN_DB_PREFIX."element_element ("; - $sqlInsert.= "fk_source"; - $sqlInsert.= ", sourcetype"; - $sqlInsert.= ", fk_target"; - $sqlInsert.= ", targettype"; - $sqlInsert.= ") VALUES ("; - $sqlInsert.= $obj->$fk_source; - $sqlInsert.= ", '".$sourcetype."'"; - $sqlInsert.= ", ".$obj->$fk_target; - $sqlInsert.= ", '".$targettype."'"; - $sqlInsert.= ")"; + $sqlInsert .= "fk_source"; + $sqlInsert .= ", sourcetype"; + $sqlInsert .= ", fk_target"; + $sqlInsert .= ", targettype"; + $sqlInsert .= ") VALUES ("; + $sqlInsert .= $obj->$fk_source; + $sqlInsert .= ", '".$sourcetype."'"; + $sqlInsert .= ", ".$obj->$fk_target; + $sqlInsert .= ", '".$targettype."'"; + $sqlInsert .= ")"; - $result=$db->query($sqlInsert); - if (! $result) + $result = $db->query($sqlInsert); + if (!$result) { $error++; dol_print_error($db); @@ -3049,7 +3049,7 @@ function migrate_project_task_time($db, $langs, $conf) $db->begin(); $sql = "SELECT rowid, fk_task, task_duration"; - $sql.= " FROM ".MAIN_DB_PREFIX."projet_task_time"; + $sql .= " FROM ".MAIN_DB_PREFIX."projet_task_time"; $resql = $db->query($sql); if ($resql) { @@ -3069,16 +3069,16 @@ function migrate_project_task_time($db, $langs, $conf) { // convert to second // only for int time and float time ex: 1,75 for 1h45 - list($hour,$min) = explode('.', $obj->task_duration); - $hour = $hour*60*60; - $min = ($min/100)*60*60; - $newtime = $hour+$min; + list($hour, $min) = explode('.', $obj->task_duration); + $hour = $hour * 60 * 60; + $min = ($min / 100) * 60 * 60; + $newtime = $hour + $min; $sql2 = "UPDATE ".MAIN_DB_PREFIX."projet_task_time SET"; - $sql2.= " task_duration = ".$newtime; - $sql2.= " WHERE rowid = ".$obj->rowid; + $sql2 .= " task_duration = ".$newtime; + $sql2 .= " WHERE rowid = ".$obj->rowid; - $resql2=$db->query($sql2); + $resql2 = $db->query($sql2); if (!$resql2) { $error++; @@ -3086,12 +3086,12 @@ function migrate_project_task_time($db, $langs, $conf) } print ". "; $oldtime++; - if (! empty($totaltime[$obj->fk_task])) $totaltime[$obj->fk_task] += $newtime; + if (!empty($totaltime[$obj->fk_task])) $totaltime[$obj->fk_task] += $newtime; else $totaltime[$obj->fk_task] = $newtime; } else { - if (! empty($totaltime[$obj->fk_task])) $totaltime[$obj->fk_task] += $obj->task_duration; + if (!empty($totaltime[$obj->fk_task])) $totaltime[$obj->fk_task] += $obj->task_duration; else $totaltime[$obj->fk_task] = $obj->task_duration; } @@ -3102,13 +3102,13 @@ function migrate_project_task_time($db, $langs, $conf) { if ($oldtime > 0) { - foreach($totaltime as $taskid => $total_duration) + foreach ($totaltime as $taskid => $total_duration) { $sql = "UPDATE ".MAIN_DB_PREFIX."projet_task SET"; - $sql.= " duration_effective = ".$total_duration; - $sql.= " WHERE rowid = ".$taskid; + $sql .= " duration_effective = ".$total_duration; + $sql .= " WHERE rowid = ".$taskid; - $resql=$db->query($sql); + $resql = $db->query($sql); if (!$resql) { $error++; @@ -3181,11 +3181,11 @@ function migrate_customerorder_shipping($db, $langs, $conf) if ($db->query($sqlAdd1) && $db->query($sqlAdd2)) { $sqlSelect = "SELECT e.rowid as shipping_id, c.ref_client, c.date_livraison"; - $sqlSelect.= " FROM ".MAIN_DB_PREFIX."expedition as e"; - $sqlSelect.= ", ".MAIN_DB_PREFIX."element_element as el"; - $sqlSelect.= " LEFT JOIN ".MAIN_DB_PREFIX."commande as c ON c.rowid = el.fk_source AND el.sourcetype = 'commande'"; - $sqlSelect.= " WHERE e.rowid = el.fk_target"; - $sqlSelect.= " AND el.targettype = 'shipping'"; + $sqlSelect .= " FROM ".MAIN_DB_PREFIX."expedition as e"; + $sqlSelect .= ", ".MAIN_DB_PREFIX."element_element as el"; + $sqlSelect .= " LEFT JOIN ".MAIN_DB_PREFIX."commande as c ON c.rowid = el.fk_source AND el.sourcetype = 'commande'"; + $sqlSelect .= " WHERE e.rowid = el.fk_target"; + $sqlSelect .= " AND el.targettype = 'shipping'"; $resql = $db->query($sqlSelect); if ($resql) @@ -3200,12 +3200,12 @@ function migrate_customerorder_shipping($db, $langs, $conf) $obj = $db->fetch_object($resql); $sqlUpdate = "UPDATE ".MAIN_DB_PREFIX."expedition SET"; - $sqlUpdate.= " ref_customer = '".$obj->ref_client."'"; - $sqlUpdate.= ", date_delivery = '".($obj->date_livraison?$obj->date_livraison:'null')."'"; - $sqlUpdate.= " WHERE rowid = ".$obj->shipping_id; + $sqlUpdate .= " ref_customer = '".$obj->ref_client."'"; + $sqlUpdate .= ", date_delivery = '".($obj->date_livraison ? $obj->date_livraison : 'null')."'"; + $sqlUpdate .= " WHERE rowid = ".$obj->shipping_id; - $result=$db->query($sqlUpdate); - if (! $result) + $result = $db->query($sqlUpdate); + if (!$result) { $error++; dol_print_error($db); @@ -3275,8 +3275,8 @@ function migrate_shipping_delivery($db, $langs, $conf) $db->begin(); $sqlSelect = "SELECT rowid, fk_expedition"; - $sqlSelect.= " FROM ".MAIN_DB_PREFIX."livraison"; - $sqlSelect.= " WHERE fk_expedition is not null"; + $sqlSelect .= " FROM ".MAIN_DB_PREFIX."livraison"; + $sqlSelect .= " WHERE fk_expedition is not null"; $resql = $db->query($sqlSelect); if ($resql) @@ -3291,25 +3291,25 @@ function migrate_shipping_delivery($db, $langs, $conf) $obj = $db->fetch_object($resql); $sqlInsert = "INSERT INTO ".MAIN_DB_PREFIX."element_element ("; - $sqlInsert.= "fk_source"; - $sqlInsert.= ", sourcetype"; - $sqlInsert.= ", fk_target"; - $sqlInsert.= ", targettype"; - $sqlInsert.= ") VALUES ("; - $sqlInsert.= $obj->fk_expedition; - $sqlInsert.= ", 'shipping'"; - $sqlInsert.= ", ".$obj->rowid; - $sqlInsert.= ", 'delivery'"; - $sqlInsert.= ")"; + $sqlInsert .= "fk_source"; + $sqlInsert .= ", sourcetype"; + $sqlInsert .= ", fk_target"; + $sqlInsert .= ", targettype"; + $sqlInsert .= ") VALUES ("; + $sqlInsert .= $obj->fk_expedition; + $sqlInsert .= ", 'shipping'"; + $sqlInsert .= ", ".$obj->rowid; + $sqlInsert .= ", 'delivery'"; + $sqlInsert .= ")"; - $result=$db->query($sqlInsert); + $result = $db->query($sqlInsert); if ($result) { $sqlUpdate = "UPDATE ".MAIN_DB_PREFIX."livraison SET fk_expedition = NULL"; - $sqlUpdate.= " WHERE rowid = ".$obj->rowid; + $sqlUpdate .= " WHERE rowid = ".$obj->rowid; - $result=$db->query($sqlUpdate); - if (! $result) + $result = $db->query($sqlUpdate); + if (!$result) { $error++; dol_print_error($db); @@ -3383,16 +3383,16 @@ function migrate_shipping_delivery2($db, $langs, $conf) $db->begin(); $sqlSelect = "SELECT l.rowid as delivery_id, e.ref_customer, e.date_delivery"; - $sqlSelect.= " FROM ".MAIN_DB_PREFIX."livraison as l,"; - $sqlSelect.= " ".MAIN_DB_PREFIX."element_element as el,"; - $sqlSelect.= " ".MAIN_DB_PREFIX."expedition as e"; - $sqlSelect.= " WHERE l.rowid = el.fk_target"; - $sqlSelect.= " AND el.targettype = 'delivery'"; - $sqlSelect.= " AND e.rowid = el.fk_source AND el.sourcetype = 'shipping'"; - $sqlSelect.= " AND (e.ref_customer IS NOT NULL OR e.date_delivery IS NOT NULL)"; // Useless to process this record if both are null + $sqlSelect .= " FROM ".MAIN_DB_PREFIX."livraison as l,"; + $sqlSelect .= " ".MAIN_DB_PREFIX."element_element as el,"; + $sqlSelect .= " ".MAIN_DB_PREFIX."expedition as e"; + $sqlSelect .= " WHERE l.rowid = el.fk_target"; + $sqlSelect .= " AND el.targettype = 'delivery'"; + $sqlSelect .= " AND e.rowid = el.fk_source AND el.sourcetype = 'shipping'"; + $sqlSelect .= " AND (e.ref_customer IS NOT NULL OR e.date_delivery IS NOT NULL)"; // Useless to process this record if both are null // Add condition to know if we never migrate this record - $sqlSelect.= " AND (l.ref_customer IS NULL".($db->type!='pgsql'?" or l.ref_customer = ''":"").")"; - $sqlSelect.= " AND (l.date_delivery IS NULL".($db->type!='pgsql'?" or l.date_delivery = ''":"").")"; + $sqlSelect .= " AND (l.ref_customer IS NULL".($db->type != 'pgsql' ? " or l.ref_customer = ''" : "").")"; + $sqlSelect .= " AND (l.date_delivery IS NULL".($db->type != 'pgsql' ? " or l.date_delivery = ''" : "").")"; $resql = $db->query($sqlSelect); if ($resql) @@ -3407,12 +3407,12 @@ function migrate_shipping_delivery2($db, $langs, $conf) $obj = $db->fetch_object($resql); $sqlUpdate = "UPDATE ".MAIN_DB_PREFIX."livraison SET"; - $sqlUpdate.= " ref_customer = '".$obj->ref_customer."',"; - $sqlUpdate.= " date_delivery = ".($obj->date_delivery?"'".$obj->date_delivery."'":'null'); - $sqlUpdate.= " WHERE rowid = ".$obj->delivery_id; + $sqlUpdate .= " ref_customer = '".$obj->ref_customer."',"; + $sqlUpdate .= " date_delivery = ".($obj->date_delivery ? "'".$obj->date_delivery."'" : 'null'); + $sqlUpdate .= " WHERE rowid = ".$obj->delivery_id; - $result=$db->query($sqlUpdate); - if (! $result) + $result = $db->query($sqlUpdate); + if (!$result) { $error++; dol_print_error($db); @@ -3469,21 +3469,21 @@ function migrate_actioncomm_element($db, $langs, $conf) 'invoice_supplier' => 'fk_supplier_invoice' ); - foreach($elements as $type => $field) + foreach ($elements as $type => $field) { $result = $db->DDLDescTable(MAIN_DB_PREFIX."actioncomm", $field); $obj = $db->fetch_object($result); if ($obj) { - dolibarr_install_syslog("upgrade2::migrate_actioncomm_element field=" . $field); + dolibarr_install_syslog("upgrade2::migrate_actioncomm_element field=".$field); $db->begin(); $sql = "UPDATE ".MAIN_DB_PREFIX."actioncomm SET "; - $sql.= "fk_element = ".$field.", elementtype = '".$type."'"; - $sql.= " WHERE ".$field." IS NOT NULL"; - $sql.= " AND fk_element IS NULL"; - $sql.= " AND elementtype IS NULL"; + $sql .= "fk_element = ".$field.", elementtype = '".$type."'"; + $sql .= " WHERE ".$field." IS NOT NULL"; + $sql .= " AND fk_element IS NULL"; + $sql .= " AND elementtype IS NULL"; $resql = $db->query($sql); if ($resql) @@ -3527,23 +3527,23 @@ function migrate_mode_reglement($db, $langs, $conf) print ''.$langs->trans('MigrationPaymentMode')."
    \n"; $elements = array( - 'old_id' => array(5,8,9,10,11), - 'new_id' => array(50,51,52,53,54), - 'code' => array('VAD','TRA','LCR','FAC','PRO'), - 'tables' => array('commande_fournisseur','commande','facture_rec','facture','propal') + 'old_id' => array(5, 8, 9, 10, 11), + 'new_id' => array(50, 51, 52, 53, 54), + 'code' => array('VAD', 'TRA', 'LCR', 'FAC', 'PRO'), + 'tables' => array('commande_fournisseur', 'commande', 'facture_rec', 'facture', 'propal') ); - $count=0; + $count = 0; - foreach($elements['old_id'] as $key => $old_id) + foreach ($elements['old_id'] as $key => $old_id) { - $error=0; + $error = 0; - dolibarr_install_syslog("upgrade2::migrate_mode_reglement code=" . $elements['code'][$key]); + dolibarr_install_syslog("upgrade2::migrate_mode_reglement code=".$elements['code'][$key]); $sqlSelect = "SELECT id"; - $sqlSelect.= " FROM ".MAIN_DB_PREFIX."c_paiement"; - $sqlSelect.= " WHERE id = ".$old_id; - $sqlSelect.= " AND code = '".$elements['code'][$key]."'"; + $sqlSelect .= " FROM ".MAIN_DB_PREFIX."c_paiement"; + $sqlSelect .= " WHERE id = ".$old_id; + $sqlSelect .= " AND code = '".$elements['code'][$key]."'"; $resql = $db->query($sqlSelect); if ($resql) @@ -3556,27 +3556,27 @@ function migrate_mode_reglement($db, $langs, $conf) $db->begin(); $sqla = "UPDATE ".MAIN_DB_PREFIX."paiement SET "; - $sqla.= "fk_paiement = ".$elements['new_id'][$key]; - $sqla.= " WHERE fk_paiement = ".$old_id; - $sqla.= " AND fk_paiement IN (SELECT id FROM ".MAIN_DB_PREFIX."c_paiement WHERE id = ".$old_id." AND code = '".$elements['code'][$key]."')"; + $sqla .= "fk_paiement = ".$elements['new_id'][$key]; + $sqla .= " WHERE fk_paiement = ".$old_id; + $sqla .= " AND fk_paiement IN (SELECT id FROM ".MAIN_DB_PREFIX."c_paiement WHERE id = ".$old_id." AND code = '".$elements['code'][$key]."')"; $resqla = $db->query($sqla); $sql = "UPDATE ".MAIN_DB_PREFIX."c_paiement SET "; - $sql.= "id = ".$elements['new_id'][$key]; - $sql.= " WHERE id = ".$old_id; - $sql.= " AND code = '".$elements['code'][$key]."'"; + $sql .= "id = ".$elements['new_id'][$key]; + $sql .= " WHERE id = ".$old_id; + $sql .= " AND code = '".$elements['code'][$key]."'"; $resql = $db->query($sql); if ($resqla && $resql) { - foreach($elements['tables'] as $table) + foreach ($elements['tables'] as $table) { $sql = "UPDATE ".MAIN_DB_PREFIX.$table." SET "; - $sql.= "fk_mode_reglement = ".$elements['new_id'][$key]; - $sql.= " WHERE fk_mode_reglement = ".$old_id; + $sql .= "fk_mode_reglement = ".$elements['new_id'][$key]; + $sql .= " WHERE fk_mode_reglement = ".$old_id; $resql = $db->query($sql); - if (! $resql) + if (!$resql) { dol_print_error($db); $error++; @@ -3584,7 +3584,7 @@ function migrate_mode_reglement($db, $langs, $conf) print ". "; } - if (! $error) + if (!$error) { $db->commit(); } @@ -3627,54 +3627,54 @@ function migrate_clean_association($db, $langs, $conf, $versionto) $obj = $db->fetch_object($result); if ($obj) // It table categorie_association exists { - $couples=array(); - $filles=array(); + $couples = array(); + $filles = array(); $sql = "SELECT fk_categorie_mere, fk_categorie_fille"; - $sql.= " FROM ".MAIN_DB_PREFIX."categorie_association"; + $sql .= " FROM ".MAIN_DB_PREFIX."categorie_association"; dolibarr_install_syslog("upgrade: search duplicate"); $resql = $db->query($sql); if ($resql) { - $num=$db->num_rows($resql); - while ($obj=$db->fetch_object($resql)) + $num = $db->num_rows($resql); + while ($obj = $db->fetch_object($resql)) { - if (! isset($filles[$obj->fk_categorie_fille])) // Only one record as child (a child has only on parent). + if (!isset($filles[$obj->fk_categorie_fille])) // Only one record as child (a child has only on parent). { if ($obj->fk_categorie_mere != $obj->fk_categorie_fille) { - $filles[$obj->fk_categorie_fille]=1; // Set record for this child - $couples[$obj->fk_categorie_mere.'_'.$obj->fk_categorie_fille]=array('mere'=>$obj->fk_categorie_mere, 'fille'=>$obj->fk_categorie_fille); + $filles[$obj->fk_categorie_fille] = 1; // Set record for this child + $couples[$obj->fk_categorie_mere.'_'.$obj->fk_categorie_fille] = array('mere'=>$obj->fk_categorie_mere, 'fille'=>$obj->fk_categorie_fille); } } } - dolibarr_install_syslog("upgrade: result is num=" . $num . " count(couples)=" . count($couples)); + dolibarr_install_syslog("upgrade: result is num=".$num." count(couples)=".count($couples)); // If there is duplicates couples or child with two parents if (count($couples) > 0 && $num > count($couples)) { - $error=0; + $error = 0; $db->begin(); // We delete all - $sql="DELETE FROM ".MAIN_DB_PREFIX."categorie_association"; + $sql = "DELETE FROM ".MAIN_DB_PREFIX."categorie_association"; dolibarr_install_syslog("upgrade: delete association"); - $resqld=$db->query($sql); + $resqld = $db->query($sql); if ($resqld) { // And we insert only each record once - foreach($couples as $key => $val) + foreach ($couples as $key => $val) { - $sql ="INSERT INTO ".MAIN_DB_PREFIX."categorie_association(fk_categorie_mere,fk_categorie_fille)"; - $sql.=" VALUES(".$val['mere'].", ".$val['fille'].")"; + $sql = "INSERT INTO ".MAIN_DB_PREFIX."categorie_association(fk_categorie_mere,fk_categorie_fille)"; + $sql .= " VALUES(".$val['mere'].", ".$val['fille'].")"; dolibarr_install_syslog("upgrade: insert association"); - $resqli=$db->query($sql); - if (! $resqli) $error++; + $resqli = $db->query($sql); + if (!$resqli) $error++; } } - if (! $error) + if (!$error) { print '
    '.$langs->trans("MigrationCategorieAssociation").''.$langs->trans("RemoveDuplicates").' '.$langs->trans("Success").' ('.$num.'=>'.count($couples).')
    '; print ''.$langs->trans('Upgrade').': '; - print $langs->trans('MigrationReloadModule').' '.$mod->getName(); // We keep getName outside of trans because getName is already encoded/translated + print $langs->trans('MigrationReloadModule').' '.$mod->getName(); // We keep getName outside of trans because getName is already encoded/translated print ""; print "
    \n"; print '
    '.$langs->trans("RefOrder").''; print $order->getNomUrl(1, 'commande'); print "
    '.$langs->trans("RefProposal").''; @@ -500,7 +500,7 @@ else print '
    '; print ''; print ''; - print $form->selectDate($object->date_delivery?$object->date_delivery:-1, 'liv_', 1, 1, '', "setdate_livraison", 1, 1); + print $form->selectDate($object->date_delivery ? $object->date_delivery : -1, 'liv_', 1, 1, '', "setdate_livraison", 1, 1); print ''; print '
    '; } @@ -529,7 +529,7 @@ else } 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); + print $form->select_incoterms((!empty($object->fk_incoterms) ? $object->fk_incoterms : ''), (!empty($object->location_incoterms) ? $object->location_incoterms : ''), $_SERVER['PHP_SELF'].'?id='.$object->id); } print '
    '.$object->getLibStatut(4)."

    \n"; @@ -586,7 +586,7 @@ else $num_prod = count($object->lines); $i = 0; $total = 0; - print ''; + print '
    '; if ($num_prod) { @@ -613,13 +613,13 @@ else $product->fetch($object->lines[$i]->fk_product); // 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)) { $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)) { $outputlangs = new Translate("", $conf); $outputlangs->setDefaultLang($newlang); @@ -635,18 +635,18 @@ else print '\n"; } - print ''; - print ''; + print ''; + print ''; print ""; // Display lines extrafields - if (! empty($extrafields)) { + if (!empty($extrafields)) { $colspan = 2; $mode = ($object->statut == 0) ? 'edit' : 'view'; @@ -712,8 +712,8 @@ else if ($object->statut == 0 && $num_prod > 0) { - if ((empty($conf->global->MAIN_USE_ADVANCED_PERMS) && ! empty($user->rights->expedition->livraison->creer)) - || (! empty($conf->global->MAIN_USE_ADVANCED_PERMS) && ! empty($user->rights->expedition->livraison_advance->validate))) + if ((empty($conf->global->MAIN_USE_ADVANCED_PERMS) && !empty($user->rights->expedition->livraison->creer)) + || (!empty($conf->global->MAIN_USE_ADVANCED_PERMS) && !empty($user->rights->expedition->livraison_advance->validate))) { print ''.$langs->trans("Validate").''; } @@ -742,11 +742,11 @@ else */ $objectref = dol_sanitizeFileName($object->ref); - $filedir = $conf->expedition->dir_output . "/receipt/" . $objectref; + $filedir = $conf->expedition->dir_output."/receipt/".$objectref; $urlsource = $_SERVER["PHP_SELF"]."?id=".$object->id; - $genallowed=$user->rights->expedition->livraison->lire; - $delallowed=$user->rights->expedition->livraison->creer; + $genallowed = $user->rights->expedition->livraison->lire; + $delallowed = $user->rights->expedition->livraison->creer; print $formfile->showdocuments('livraison', $objectref, $filedir, $urlsource, $genallowed, $delallowed, $object->modelpdf, 1, 0, 0, 28, 0, '', '', '', $soc->default_lang); diff --git a/htdocs/livraison/class/livraison.class.php b/htdocs/livraison/class/livraison.class.php index c962d1d352e..0011ea3b7a7 100644 --- a/htdocs/livraison/class/livraison.class.php +++ b/htdocs/livraison/class/livraison.class.php @@ -63,14 +63,22 @@ class Livraison extends CommonObject public $socid; public $ref_customer; - public $date_delivery; // Date really received + /** + * @var integer|string Date really received + */ + public $date_delivery; /** - * @var integer|string date_creation - */ + * @var integer|string date_creation + */ public $date_creation; + /** + * @var integer|string date_valid + */ public $date_valid; + + public $model_pdf; diff --git a/htdocs/loan/calcmens.php b/htdocs/loan/calcmens.php index 5cde353105f..9a95ec9d438 100644 --- a/htdocs/loan/calcmens.php +++ b/htdocs/loan/calcmens.php @@ -22,42 +22,42 @@ * \brief File to return datables output */ -if (! defined('NOTOKENRENEWAL')) define('NOTOKENRENEWAL', '1'); // Disables token renewal -if (! defined('NOREQUIREMENU')) define('NOREQUIREMENU', '1'); -if (! defined('NOREQUIREAJAX')) define('NOREQUIREAJAX', '1'); +if (!defined('NOTOKENRENEWAL')) define('NOTOKENRENEWAL', '1'); // Disables token renewal +if (!defined('NOREQUIREMENU')) define('NOREQUIREMENU', '1'); +if (!defined('NOREQUIREAJAX')) define('NOREQUIREAJAX', '1'); require '../main.inc.php'; require DOL_DOCUMENT_ROOT.'/loan/class/loanschedule.class.php'; -$mens=GETPOST('mens'); -$capital=GETPOST('capital'); -$rate=GETPOST('rate'); -$echance=GETPOST('echeance'); -$nbterm=GETPOST('nbterm'); +$mens = GETPOST('mens'); +$capital = GETPOST('capital'); +$rate = GETPOST('rate'); +$echance = GETPOST('echeance'); +$nbterm = GETPOST('nbterm'); top_httphead(); -$output=array(); +$output = array(); $object = new LoanSchedule($db); -$int = ($capital*($rate/12)); +$int = ($capital * ($rate / 12)); $int = round($int, 2, PHP_ROUND_HALF_UP); -$cap_rest = round($capital - ($mens-$int), 2, PHP_ROUND_HALF_UP); -$output[$echance]=array('cap_rest'=>$cap_rest,'cap_rest_str'=>price($cap_rest),'interet'=>$int,'interet_str'=>price($int, 0, '', 1),'mens'=>$mens); +$cap_rest = round($capital - ($mens - $int), 2, PHP_ROUND_HALF_UP); +$output[$echance] = array('cap_rest'=>$cap_rest, 'cap_rest_str'=>price($cap_rest), 'interet'=>$int, 'interet_str'=>price($int, 0, '', 1), 'mens'=>$mens); $echance++; -$capital=$cap_rest; -while ($echance<=$nbterm) { - $mens = round($object->calcMonthlyPayments($capital, $rate, $nbterm-$echance+1), 2, PHP_ROUND_HALF_UP); +$capital = $cap_rest; +while ($echance <= $nbterm) { + $mens = round($object->calcMonthlyPayments($capital, $rate, $nbterm - $echance + 1), 2, PHP_ROUND_HALF_UP); - $int = ($capital*($rate/12)); + $int = ($capital * ($rate / 12)); $int = round($int, 2, PHP_ROUND_HALF_UP); - $cap_rest = round($capital - ($mens-$int), 2, PHP_ROUND_HALF_UP); + $cap_rest = round($capital - ($mens - $int), 2, PHP_ROUND_HALF_UP); - $output[$echance]=array('cap_rest'=>$cap_rest,'cap_rest_str'=>price($cap_rest),'interet'=>$int,'interet_str'=>price($int, 0, '', 1),'mens'=>$mens); + $output[$echance] = array('cap_rest'=>$cap_rest, 'cap_rest_str'=>price($cap_rest), 'interet'=>$int, 'interet_str'=>price($int, 0, '', 1), 'mens'=>$mens); - $capital=$cap_rest; + $capital = $cap_rest; $echance++; } diff --git a/htdocs/loan/card.php b/htdocs/loan/card.php index 7cf592a354c..29b70e50f2c 100644 --- a/htdocs/loan/card.php +++ b/htdocs/loan/card.php @@ -79,7 +79,7 @@ if (empty($reshook)) if ($action == 'confirm_delete' && $confirm == 'yes') { $object->fetch($id); - $result=$object->delete($user); + $result = $object->delete($user); if ($result > 0) { setEventMessages($langs->trans('LoanDeleted'), null, 'mesgs'); @@ -95,24 +95,24 @@ if (empty($reshook)) // Add loan if ($action == 'add' && $user->rights->loan->write) { - if (! $cancel) + if (!$cancel) { - $datestart = dol_mktime(12, 0, 0, GETPOST('startmonth', 'int'), GETPOST('startday', 'int'), GETPOST('startyear', 'int')); + $datestart = dol_mktime(12, 0, 0, GETPOST('startmonth', 'int'), GETPOST('startday', 'int'), GETPOST('startyear', 'int')); $dateend = dol_mktime(12, 0, 0, GETPOST('endmonth', 'int'), GETPOST('endday', 'int'), GETPOST('endyear', 'int')); - $capital = price2num(GETPOST('capital')); + $capital = price2num(GETPOST('capital')); $rate = GETPOST('rate'); - if (! $capital) + if (!$capital) { $error++; $action = 'create'; setEventMessages($langs->trans("ErrorFieldRequired", $langs->transnoentities("LoanCapital")), null, 'errors'); } - if (! $datestart) + if (!$datestart) { $error++; $action = 'create'; setEventMessages($langs->trans("ErrorFieldRequired", $langs->transnoentities("DateStart")), null, 'errors'); } - if (! $dateend) + if (!$dateend) { $error++; $action = 'create'; setEventMessages($langs->trans("ErrorFieldRequired", $langs->transnoentities("DateEnd")), null, 'errors'); @@ -123,29 +123,29 @@ if (empty($reshook)) setEventMessages($langs->trans("ErrorFieldRequired", $langs->transnoentities("Rate")), null, 'errors'); } - if (! $error) + if (!$error) { - $object->label = GETPOST('label'); + $object->label = GETPOST('label'); $object->fk_bank = GETPOST('accountid'); $object->capital = $capital; - $object->datestart = $datestart; + $object->datestart = $datestart; $object->dateend = $dateend; $object->nbterm = GETPOST('nbterm'); - $object->rate = $rate; - $object->note_private = GETPOST('note_private', 'none'); - $object->note_public = GETPOST('note_public', 'none'); - $object->fk_project = GETPOST('projectid', 'int'); - $object->insurance_amount = GETPOST('insurance_amount', 'int'); + $object->rate = $rate; + $object->note_private = GETPOST('note_private', 'none'); + $object->note_public = GETPOST('note_public', 'none'); + $object->fk_project = GETPOST('projectid', 'int'); + $object->insurance_amount = GETPOST('insurance_amount', 'int'); - $accountancy_account_capital = GETPOST('accountancy_account_capital'); - $accountancy_account_insurance = GETPOST('accountancy_account_insurance'); - $accountancy_account_interest = GETPOST('accountancy_account_interest'); + $accountancy_account_capital = GETPOST('accountancy_account_capital'); + $accountancy_account_insurance = GETPOST('accountancy_account_insurance'); + $accountancy_account_interest = GETPOST('accountancy_account_interest'); if ($accountancy_account_capital <= 0) { $object->account_capital = ''; } else { $object->account_capital = $accountancy_account_capital; } if ($accountancy_account_insurance <= 0) { $object->account_insurance = ''; } else { $object->account_insurance = $accountancy_account_insurance; } if ($accountancy_account_interest <= 0) { $object->account_interest = ''; } else { $object->account_interest = $accountancy_account_interest; } - $id=$object->create($user); + $id = $object->create($user); if ($id <= 0) { $error++; @@ -164,31 +164,31 @@ if (empty($reshook)) // Update record elseif ($action == 'update' && $user->rights->loan->write) { - if (! $cancel) + if (!$cancel) { $result = $object->fetch($id); - $datestart = dol_mktime(12, 0, 0, GETPOST('startmonth', 'int'), GETPOST('startday', 'int'), GETPOST('startyear', 'int')); + $datestart = dol_mktime(12, 0, 0, GETPOST('startmonth', 'int'), GETPOST('startday', 'int'), GETPOST('startyear', 'int')); $dateend = dol_mktime(12, 0, 0, GETPOST('endmonth', 'int'), GETPOST('endday', 'int'), GETPOST('endyear', 'int')); $capital = price2num(GETPOST('capital')); - if (! $capital) + if (!$capital) { setEventMessages($langs->trans("ErrorFieldRequired", $langs->transnoentities("LoanCapital")), null, 'errors'); $action = 'edit'; } else { - $object->datestart = $datestart; + $object->datestart = $datestart; $object->dateend = $dateend; $object->capital = $capital; $object->nbterm = GETPOST("nbterm", 'int'); - $object->rate = price2num(GETPOST("rate", 'alpha')); - $object->insurance_amount = price2num(GETPOST('insurance_amount', 'int')); + $object->rate = price2num(GETPOST("rate", 'alpha')); + $object->insurance_amount = price2num(GETPOST('insurance_amount', 'int')); - $accountancy_account_capital = GETPOST('accountancy_account_capital'); - $accountancy_account_insurance = GETPOST('accountancy_account_insurance'); - $accountancy_account_interest = GETPOST('accountancy_account_interest'); + $accountancy_account_capital = GETPOST('accountancy_account_capital'); + $accountancy_account_insurance = GETPOST('accountancy_account_insurance'); + $accountancy_account_interest = GETPOST('accountancy_account_interest'); if ($accountancy_account_capital <= 0) { $object->account_capital = ''; } else { $object->account_capital = $accountancy_account_capital; } if ($accountancy_account_insurance <= 0) { $object->account_insurance = ''; } else { $object->account_insurance = $accountancy_account_insurance; } @@ -199,7 +199,7 @@ if (empty($reshook)) if ($result > 0) { - header("Location: " . $_SERVER["PHP_SELF"] . "?id=" . $id); + header("Location: ".$_SERVER["PHP_SELF"]."?id=".$id); exit; } else @@ -210,7 +210,7 @@ if (empty($reshook)) } else { - header("Location: " . $_SERVER["PHP_SELF"] . "?id=" . $id); + header("Location: ".$_SERVER["PHP_SELF"]."?id=".$id); exit; } } @@ -240,9 +240,9 @@ if (empty($reshook)) $form = new Form($db); $formproject = new FormProjets($db); -if (! empty($conf->accounting->enabled)) $formaccounting = new FormAccounting($db); +if (!empty($conf->accounting->enabled)) $formaccounting = new FormAccounting($db); -$title = $langs->trans("Loan") . ' - ' . $langs->trans("Card"); +$title = $langs->trans("Loan").' - '.$langs->trans("Card"); $help_url = 'EN:Module_Loan|FR:Module_Emprunt'; llxHeader("", $title, $help_url); @@ -257,22 +257,22 @@ if ($action == 'create') $datec = dol_mktime(12, 0, 0, GETPOST('remonth', 'int'), GETPOST('reday', 'int'), GETPOST('reyear', 'int')); - print '' . "\n"; + print ''."\n"; print ''; print ''; dol_fiche_head(); - print '
    '; // Affiche ligne produit - $text = ''; + $text = ''; if ($object->lines[$i]->fk_product_type == 1) $text .= img_object($langs->trans('ShowService'), 'service'); else $text .= img_object($langs->trans('ShowProduct'), 'product'); - $text .= ' ' . $object->lines[$i]->product_ref . ''; - $text .= ' - ' . $label; + $text .= ' '.$object->lines[$i]->product_ref.''; + $text .= ' - '.$label; $description = (!empty($conf->global->PRODUIT_DESC_IN_FORM) ? '' : dol_htmlentitiesbr($object->lines[$i]->description)); //print $description; print $form->textwithtooltip($text, $description, 3, '', '', $i); print_date_range($object->lines[$i]->date_start, $object->lines[$i]->date_end); if (!empty($conf->global->PRODUIT_DESC_IN_FORM)) { - print (!empty($object->lines[$i]->description) && $object->lines[$i]->description != $object->lines[$i]->product_label) ? '
    ' . dol_htmlentitiesbr($object->lines[$i]->description) : ''; + print (!empty($object->lines[$i]->description) && $object->lines[$i]->description != $object->lines[$i]->product_label) ? '
    '.dol_htmlentitiesbr($object->lines[$i]->description) : ''; } } else @@ -656,23 +656,23 @@ else else $text = img_object($langs->trans('Product'), 'product'); if (!empty($object->lines[$i]->label)) { - $text .= ' ' . $object->lines[$i]->label . ''; + $text .= ' '.$object->lines[$i]->label.''; print $form->textwithtooltip($text, $object->lines[$i]->description, 3, '', '', $i); } else { - print $text . ' ' . nl2br($object->lines[$i]->description); + print $text.' '.nl2br($object->lines[$i]->description); } print_date_range($objp->date_start, $objp->date_end); print "
    ' . $object->lines[$i]->qty_asked . '' . $object->lines[$i]->qty_shipped . ''.$object->lines[$i]->qty_asked.''.$object->lines[$i]->qty_shipped.'
    '; + print '
    '; // Label print ''; // Bank account - if (! empty($conf->banque->enabled)) + if (!empty($conf->banque->enabled)) { print ''; } else @@ -283,40 +283,40 @@ if ($action == 'create') } // Capital - print ''; + print ''; // Date Start print ""; print ''; // Date End print ""; print ''; // Number of terms - print ''; + print ''; // Rate - print ''; + print ''; // Insurance amount - print ''; + print ''; // Project - if (! empty($conf->projet->enabled)) + if (!empty($conf->projet->enabled)) { - $formproject=new FormProjets($db); + $formproject = new FormProjets($db); // Projet associe $langs->loadLangs(array("projects")); print ''; } @@ -340,24 +340,24 @@ if ($action == 'create') print ''; // Accountancy - if (! empty($conf->accounting->enabled)) + if (!empty($conf->accounting->enabled)) { // Accountancy_account_capital print ''; print ''; // Accountancy_account_insurance print ''; print ''; // Accountancy_account_interest print ''; print ''; } else // For external software @@ -384,7 +384,7 @@ if ($action == 'create') print '
    '; print ''; print '     '; - print ''; + print ''; print '
    '; print ''; @@ -398,26 +398,26 @@ if ($id > 0) if ($result > 0) { - $head=loan_prepare_head($object); + $head = loan_prepare_head($object); $totalpaid = $object->getSumPayment(); // Confirm for loan if ($action == 'paid') { - $text=$langs->trans('ConfirmPayLoan'); + $text = $langs->trans('ConfirmPayLoan'); print $form->formconfirm($_SERVER["PHP_SELF"]."?id=".$object->id, $langs->trans('PayLoan'), $text, "confirm_paid", '', '', 2); } if ($action == 'delete') { - $text=$langs->trans('ConfirmDeleteLoan'); + $text = $langs->trans('ConfirmDeleteLoan'); print $form->formconfirm($_SERVER['PHP_SELF'].'?id='.$object->id, $langs->trans('DeleteLoan'), $text, 'confirm_delete', '', '', 2); } if ($action == 'edit') { - print '' . "\n"; + print ''."\n"; print ''; print ''; print ''; @@ -425,61 +425,61 @@ if ($id > 0) dol_fiche_head($head, 'card', $langs->trans("Loan"), -1, 'bill'); - print ''; // Loan card - $linkback = '' . $langs->trans("BackToList") . ''; + $linkback = ''.$langs->trans("BackToList").''; - $morehtmlref='
    '; + $morehtmlref = '
    '; // Ref loan - $morehtmlref.=$form->editfieldkey("Label", 'label', $object->label, $object, $user->rights->loan->write, 'string', '', 0, 1); - $morehtmlref.=$form->editfieldval("Label", 'label', $object->label, $object, $user->rights->loan->write, 'string', '', null, null, '', 1); + $morehtmlref .= $form->editfieldkey("Label", 'label', $object->label, $object, $user->rights->loan->write, 'string', '', 0, 1); + $morehtmlref .= $form->editfieldval("Label", 'label', $object->label, $object, $user->rights->loan->write, 'string', '', null, null, '', 1); // Project - if (! empty($conf->projet->enabled)) + if (!empty($conf->projet->enabled)) { $langs->loadLangs(array("projects")); - $morehtmlref.='
    '.$langs->trans('Project') . ' '; + $morehtmlref .= '
    '.$langs->trans('Project').' '; if ($user->rights->loan->write) { if ($action != 'classify') - $morehtmlref.='' . img_edit($langs->transnoentitiesnoconv('SetProject')) . ' : '; + $morehtmlref .= ''.img_edit($langs->transnoentitiesnoconv('SetProject')).' : '; if ($action == 'classify') { //$morehtmlref.=$form->form_project($_SERVER['PHP_SELF'] . '?id=' . $object->id, $object->socid, $object->fk_project, 'projectid', 0, 0, 1, 1); - $morehtmlref.=''; - $morehtmlref.=''; - $morehtmlref.=''; - $morehtmlref.=$formproject->select_projects($object->socid, $object->fk_project, 'projectid', $maxlength, 0, 1, 0, 1, 0, 0, '', 1); - $morehtmlref.=''; - $morehtmlref.=''; + $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); + $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)) { + if (!empty($object->fk_project)) { $proj = new Project($db); $proj->fetch($object->fk_project); - $morehtmlref.=''; - $morehtmlref.=$proj->ref; - $morehtmlref.=''; + $morehtmlref .= ''; + $morehtmlref .= $proj->ref; + $morehtmlref .= ''; } else { - $morehtmlref.=''; + $morehtmlref .= ''; } } } - $morehtmlref.='
    '; + $morehtmlref .= '
    '; - $object->totalpaid = $totalpaid; // To give a chance to dol_banner_tab to use already paid amount to show correct status + $object->totalpaid = $totalpaid; // To give a chance to dol_banner_tab to use already paid amount to show correct status dol_banner_tab($object, 'id', $linkback, 1, 'rowid', 'ref', $morehtmlref, '', 0, '', $morehtmlright); @@ -487,13 +487,13 @@ if ($id > 0) print '
    '; print '
    '; - print '
    '.$langs->trans("Label").'
    '.$langs->trans("Account").''; - $form->select_comptes(GETPOST("accountid"), "accountid", 0, "courant=1", 1); // Show list of bank account with courant + $form->select_comptes(GETPOST("accountid"), "accountid", 0, "courant=1", 1); // Show list of bank account with courant print '
    '.$langs->trans("LoanCapital").'
    '.$langs->trans("LoanCapital").'
    '.$langs->trans("DateStart").''; - print $form->selectDate($datestart?$datestart:-1, 'start', '', '', '', 'add', 1, 1); + print $form->selectDate($datestart ? $datestart : -1, 'start', '', '', '', 'add', 1, 1); print '
    '.$langs->trans("DateEnd").''; - print $form->selectDate($dateend?$dateend:-1, 'end', '', '', '', 'add', 1, 1); + print $form->selectDate($dateend ? $dateend : -1, 'end', '', '', '', 'add', 1, 1); print '
    '.$langs->trans("Nbterms").'
    '.$langs->trans("Nbterms").'
    '.$langs->trans("Rate").' %
    '.$langs->trans("Rate").' %
    '.$langs->trans("Insurance").'
    '.$langs->trans("Insurance").'
    '.$langs->trans("Project").''; - $numproject=$formproject->select_projects(-1, $projectid, 'projectid', 16, 0, 1, 1); + $numproject = $formproject->select_projects(-1, $projectid, 'projectid', 16, 0, 1, 1); print '
    '.$langs->trans("LoanAccountancyCapitalCode").''; - print $formaccounting->select_account(GETPOST('accountancy_account_capital')?GETPOST('accountancy_account_capital'):$conf->global->LOAN_ACCOUNTING_ACCOUNT_CAPITAL, 'accountancy_account_capital', 1, '', 1, 1); + print $formaccounting->select_account(GETPOST('accountancy_account_capital') ?GETPOST('accountancy_account_capital') : $conf->global->LOAN_ACCOUNTING_ACCOUNT_CAPITAL, 'accountancy_account_capital', 1, '', 1, 1); print '
    '.$langs->trans("LoanAccountancyInsuranceCode").''; - print $formaccounting->select_account(GETPOST('accountancy_account_insurance')?GETPOST('accountancy_account_insurance'):$conf->global->LOAN_ACCOUNTING_ACCOUNT_INSURANCE, 'accountancy_account_insurance', 1, '', 1, 1); + print $formaccounting->select_account(GETPOST('accountancy_account_insurance') ?GETPOST('accountancy_account_insurance') : $conf->global->LOAN_ACCOUNTING_ACCOUNT_INSURANCE, 'accountancy_account_insurance', 1, '', 1, 1); print '
    '.$langs->trans("LoanAccountancyInterestCode").''; - print $formaccounting->select_account(GETPOST('accountancy_account_interest')?GETPOST('accountancy_account_interest'):$conf->global->LOAN_ACCOUNTING_ACCOUNT_INTEREST, 'accountancy_account_interest', 1, '', 1, 1); + print $formaccounting->select_account(GETPOST('accountancy_account_interest') ?GETPOST('accountancy_account_interest') : $conf->global->LOAN_ACCOUNTING_ACCOUNT_INTEREST, 'accountancy_account_interest', 1, '', 1, 1); print '
    '; + print '
    '; // Capital if ($action == 'edit') { print ''; + print ''; print ''; } else @@ -505,7 +505,7 @@ if ($id > 0) if ($action == 'edit') { print ''; + print ''; print ''; } else @@ -544,7 +544,7 @@ if ($id > 0) print ''; @@ -573,7 +573,7 @@ if ($id > 0) print $langs->trans("LoanAccountancyCapitalCode"); print '
    '.$langs->trans("LoanCapital").''; - print '
    '.$langs->trans("Insurance").''; - print '
    '; if ($action == 'edit') { - print ''; + print ''; } else { @@ -557,11 +557,11 @@ if ($id > 0) print ''; if ($action == 'edit') { - print '%'; + print '%'; } else { - print $object->rate . '%'; + print $object->rate.'%'; } print '
    '; - if (! empty($conf->accounting->enabled)) + if (!empty($conf->accounting->enabled)) { print $formaccounting->select_account($object->account_capital, 'accountancy_account_capital', 1, '', 1, 1); } @@ -589,7 +589,7 @@ if ($id > 0) print $langs->trans("LoanAccountancyCapitalCode"); print ''; - if (! empty($conf->accounting->enabled)) + if (!empty($conf->accounting->enabled)) { $accountingaccount = new AccountingAccount($db); $accountingaccount->fetch('', $object->account_capital, 1); @@ -611,7 +611,7 @@ if ($id > 0) print $langs->trans("LoanAccountancyInsuranceCode"); print ''; - if (! empty($conf->accounting->enabled)) + if (!empty($conf->accounting->enabled)) { print $formaccounting->select_account($object->account_insurance, 'accountancy_account_insurance', 1, '', 1, 1); } @@ -627,7 +627,7 @@ if ($id > 0) print $langs->trans("LoanAccountancyCapitalCode"); print ''; - if (! empty($conf->accounting->enabled)) + if (!empty($conf->accounting->enabled)) { $accountingaccount = new AccountingAccount($db); $accountingaccount->fetch('', $object->account_insurance, 1); @@ -649,7 +649,7 @@ if ($id > 0) print $langs->trans("LoanAccountancyInterestCode"); print ''; - if (! empty($conf->accounting->enabled)) + if (!empty($conf->accounting->enabled)) { print $formaccounting->select_account($object->account_interest, 'accountancy_account_interest', 1, '', 1, 1); } @@ -665,7 +665,7 @@ if ($id > 0) print $langs->trans("LoanAccountancyInterestCode"); print ''; - if (! empty($conf->accounting->enabled)) + if (!empty($conf->accounting->enabled)) { $accountingaccount = new AccountingAccount($db); $accountingaccount->fetch('', $object->account_interest, 1); @@ -689,15 +689,15 @@ if ($id > 0) * Payments */ $sql = "SELECT p.rowid, p.num_payment, datep as dp,"; - $sql.= " p.amount_capital, p.amount_insurance, p.amount_interest,"; - $sql.= " c.libelle as paiement_type"; - $sql.= " FROM ".MAIN_DB_PREFIX."payment_loan as p"; - $sql.= " LEFT JOIN ".MAIN_DB_PREFIX."c_paiement as c ON p.fk_typepayment = c.id"; - $sql.= ", ".MAIN_DB_PREFIX."loan as l"; - $sql.= " WHERE p.fk_loan = ".$id; - $sql.= " AND p.fk_loan = l.rowid"; - $sql.= " AND l.entity IN ( ".getEntity('loan').")"; - $sql.= " ORDER BY dp DESC"; + $sql .= " p.amount_capital, p.amount_insurance, p.amount_interest,"; + $sql .= " c.libelle as paiement_type"; + $sql .= " FROM ".MAIN_DB_PREFIX."payment_loan as p"; + $sql .= " LEFT JOIN ".MAIN_DB_PREFIX."c_paiement as c ON p.fk_typepayment = c.id"; + $sql .= ", ".MAIN_DB_PREFIX."loan as l"; + $sql .= " WHERE p.fk_loan = ".$id; + $sql .= " AND p.fk_loan = l.rowid"; + $sql .= " AND l.entity IN ( ".getEntity('loan').")"; + $sql .= " ORDER BY dp DESC"; //print $sql; $resql = $db->query($sql); @@ -709,7 +709,7 @@ if ($id > 0) $total_interest = 0; $total_capital = 0; - print '
    '; // You can use div-table-responsive-no-min if you dont need reserved height for your table + print '
    '; // You can use div-table-responsive-no-min if you dont need reserved height for your table print ''; print ''; print ''; @@ -746,7 +746,7 @@ if ($id > 0) $staytopay = $object->capital - $totalpaid; print ''; - print ''; } @@ -804,7 +804,7 @@ if ($id > 0) } // Classify 'paid' - if ($object->paid == 0 && round($staytopay) <=0 && $user->rights->loan->write) + if ($object->paid == 0 && round($staytopay) <= 0 && $user->rights->loan->write) { print ''; } diff --git a/htdocs/loan/class/loan.class.php b/htdocs/loan/class/loan.class.php index 66fdfbc25a2..165756e621f 100644 --- a/htdocs/loan/class/loan.class.php +++ b/htdocs/loan/class/loan.class.php @@ -72,8 +72,14 @@ class Loan extends CommonObject */ public $date_creation; - + /** + * @var integer|string date_modification + */ public $date_modification; + + /** + * @var integer|string date_validation + */ public $date_validation; public $insurance_amount; diff --git a/htdocs/loan/class/loanschedule.class.php b/htdocs/loan/class/loanschedule.class.php index c5335496313..2d4ae196bb6 100644 --- a/htdocs/loan/class/loanschedule.class.php +++ b/htdocs/loan/class/loanschedule.class.php @@ -33,12 +33,12 @@ class LoanSchedule extends CommonObject /** * @var string ID to identify managed object */ - public $element='loan_schedule'; + public $element = 'loan_schedule'; /** * @var string Name of table without prefix where object is stored */ - public $table_element='loan_schedule'; + public $table_element = 'loan_schedule'; /** * @var int Loan ID @@ -86,7 +86,7 @@ class LoanSchedule extends CommonObject */ public $fk_user_modif; - public $lines=array(); + public $lines = array(); /** * @deprecated @@ -119,22 +119,22 @@ class LoanSchedule extends CommonObject { global $conf, $langs; - $error=0; + $error = 0; - $now=dol_now(); + $now = dol_now(); // Validate parameters - if (! $this->datep) + if (!$this->datep) { - $this->error='ErrorBadValueForParameter'; + $this->error = 'ErrorBadValueForParameter'; return -1; } // Clean parameters if (isset($this->fk_loan)) $this->fk_loan = (int) $this->fk_loan; - if (isset($this->amount_capital)) $this->amount_capital = trim($this->amount_capital?$this->amount_capital:0); - if (isset($this->amount_insurance)) $this->amount_insurance = trim($this->amount_insurance?$this->amount_insurance:0); - if (isset($this->amount_interest)) $this->amount_interest = trim($this->amount_interest?$this->amount_interest:0); + if (isset($this->amount_capital)) $this->amount_capital = trim($this->amount_capital ? $this->amount_capital : 0); + if (isset($this->amount_insurance)) $this->amount_insurance = trim($this->amount_insurance ? $this->amount_insurance : 0); + if (isset($this->amount_interest)) $this->amount_interest = trim($this->amount_interest ? $this->amount_interest : 0); if (isset($this->fk_typepayment)) $this->fk_typepayment = (int) $this->fk_typepayment; 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; @@ -145,7 +145,7 @@ class LoanSchedule extends CommonObject // Check parameters if ($totalamount == 0) { - $this->errors[]='step1'; + $this->errors[] = 'step1'; return -1; // Negative amounts are accepted for reject prelevement but not null } @@ -155,38 +155,38 @@ class LoanSchedule extends CommonObject if ($totalamount != 0) { $sql = "INSERT INTO ".MAIN_DB_PREFIX.$this->table_element." (fk_loan, datec, datep, amount_capital, amount_insurance, amount_interest,"; - $sql.= " fk_typepayment, fk_user_creat, fk_bank)"; - $sql.= " VALUES (".$this->fk_loan.", '".$this->db->idate($now)."',"; - $sql.= " '".$this->db->idate($this->datep)."',"; - $sql.= " ".$this->amount_capital.","; - $sql.= " ".$this->amount_insurance.","; - $sql.= " ".$this->amount_interest.","; - $sql.= " ".$this->fk_typepayment.", "; - $sql.= " ".$user->id.","; - $sql.= " ".$this->fk_bank . ")"; + $sql .= " fk_typepayment, fk_user_creat, fk_bank)"; + $sql .= " VALUES (".$this->fk_loan.", '".$this->db->idate($now)."',"; + $sql .= " '".$this->db->idate($this->datep)."',"; + $sql .= " ".$this->amount_capital.","; + $sql .= " ".$this->amount_insurance.","; + $sql .= " ".$this->amount_interest.","; + $sql .= " ".$this->fk_typepayment.", "; + $sql .= " ".$user->id.","; + $sql .= " ".$this->fk_bank.")"; dol_syslog(get_class($this)."::create", LOG_DEBUG); - $resql=$this->db->query($sql); + $resql = $this->db->query($sql); if ($resql) { $this->id = $this->db->last_insert_id(MAIN_DB_PREFIX."payment_loan"); } else { - $this->error=$this->db->lasterror(); + $this->error = $this->db->lasterror(); $error++; } } - if ($totalamount != 0 && ! $error) + if ($totalamount != 0 && !$error) { - $this->amount_capital=$totalamount; + $this->amount_capital = $totalamount; $this->db->commit(); return $this->id; } else { - $this->errors[]=$this->db->lasterror(); + $this->errors[] = $this->db->lasterror(); $this->db->rollback(); return -1; } @@ -260,7 +260,7 @@ class LoanSchedule extends CommonObject } else { - $this->error="Error ".$this->db->lasterror(); + $this->error = "Error ".$this->db->lasterror(); return -1; } } @@ -293,32 +293,32 @@ class LoanSchedule extends CommonObject // Update request $sql = "UPDATE ".MAIN_DB_PREFIX.$this->table_element." SET"; - $sql.= " fk_loan=".(isset($this->fk_loan)?$this->fk_loan:"null").","; - $sql.= " datec=".(dol_strlen($this->datec)!=0 ? "'".$this->db->idate($this->datec)."'" : 'null').","; - $sql.= " tms=".(dol_strlen($this->tms)!=0 ? "'".$this->db->idate($this->tms)."'" : 'null').","; - $sql.= " datep=".(dol_strlen($this->datep)!=0 ? "'".$this->db->idate($this->datep)."'" : 'null').","; - $sql.= " amount_capital=".(isset($this->amount_capital)?$this->amount_capital:"null").","; - $sql.= " amount_insurance=".(isset($this->amount_insurance)?$this->amount_insurance:"null").","; - $sql.= " amount_interest=".(isset($this->amount_interest)?$this->amount_interest:"null").","; - $sql.= " fk_typepayment=".(isset($this->fk_typepayment)?$this->fk_typepayment:"null").","; - $sql.= " num_payment=".(isset($this->num_payment)?"'".$this->db->escape($this->num_payment)."'":"null").","; - $sql.= " note_private=".(isset($this->note_private)?"'".$this->db->escape($this->note_private)."'":"null").","; - $sql.= " note_public=".(isset($this->note_public)?"'".$this->db->escape($this->note_public)."'":"null").","; - $sql.= " fk_bank=".(isset($this->fk_bank)?$this->fk_bank:"null").","; - $sql.= " fk_user_creat=".(isset($this->fk_user_creat)?$this->fk_user_creat:"null").","; - $sql.= " fk_user_modif=".(isset($this->fk_user_modif)?$this->fk_user_modif:"null").""; + $sql .= " fk_loan=".(isset($this->fk_loan) ? $this->fk_loan : "null").","; + $sql .= " datec=".(dol_strlen($this->datec) != 0 ? "'".$this->db->idate($this->datec)."'" : 'null').","; + $sql .= " tms=".(dol_strlen($this->tms) != 0 ? "'".$this->db->idate($this->tms)."'" : 'null').","; + $sql .= " datep=".(dol_strlen($this->datep) != 0 ? "'".$this->db->idate($this->datep)."'" : 'null').","; + $sql .= " amount_capital=".(isset($this->amount_capital) ? $this->amount_capital : "null").","; + $sql .= " amount_insurance=".(isset($this->amount_insurance) ? $this->amount_insurance : "null").","; + $sql .= " amount_interest=".(isset($this->amount_interest) ? $this->amount_interest : "null").","; + $sql .= " fk_typepayment=".(isset($this->fk_typepayment) ? $this->fk_typepayment : "null").","; + $sql .= " num_payment=".(isset($this->num_payment) ? "'".$this->db->escape($this->num_payment)."'" : "null").","; + $sql .= " note_private=".(isset($this->note_private) ? "'".$this->db->escape($this->note_private)."'" : "null").","; + $sql .= " note_public=".(isset($this->note_public) ? "'".$this->db->escape($this->note_public)."'" : "null").","; + $sql .= " fk_bank=".(isset($this->fk_bank) ? $this->fk_bank : "null").","; + $sql .= " fk_user_creat=".(isset($this->fk_user_creat) ? $this->fk_user_creat : "null").","; + $sql .= " fk_user_modif=".(isset($this->fk_user_modif) ? $this->fk_user_modif : "null").""; - $sql.= " WHERE rowid=".$this->id; + $sql .= " WHERE rowid=".$this->id; $this->db->begin(); dol_syslog(get_class($this)."::update", LOG_DEBUG); $resql = $this->db->query($sql); - if (! $resql) { $error++; $this->errors[]="Error ".$this->db->lasterror(); } + if (!$resql) { $error++; $this->errors[] = "Error ".$this->db->lasterror(); } - if (! $error) + if (!$error) { - if (! $notrigger) + if (!$notrigger) { // Uncomment this and change MYOBJECT to your own tag if you // want this action call a trigger. @@ -336,7 +336,7 @@ class LoanSchedule extends CommonObject if ($error) { $this->db->rollback(); - return -1*$error; + return -1 * $error; } else { @@ -356,22 +356,22 @@ class LoanSchedule extends CommonObject public function delete($user, $notrigger = 0) { global $conf, $langs; - $error=0; + $error = 0; $this->db->begin(); - if (! $error) { + if (!$error) { $sql = "DELETE FROM ".MAIN_DB_PREFIX.$this->table_element; - $sql.= " WHERE rowid=".$this->id; + $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(); } } - if (! $error) + if (!$error) { - if (! $notrigger) + if (!$notrigger) { // Uncomment this and change MYOBJECT to your own tag if you // want this action call a trigger. @@ -388,13 +388,13 @@ class LoanSchedule extends CommonObject // Commit or rollback if ($error) { - 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); + $this->error .= ($this->error ? ', '.$errmsg : $errmsg); } $this->db->rollback(); - return -1*$error; + return -1 * $error; } else { @@ -413,10 +413,10 @@ class LoanSchedule extends CommonObject */ public function calcMonthlyPayments($capital, $rate, $nbterm) { - $result=''; + $result = ''; if (!empty($capital) && !empty($rate) && !empty($nbterm)) { - $result = ($capital*($rate/12))/(1-pow((1+($rate/12)), ($nbterm*-1))); + $result = ($capital * ($rate / 12)) / (1 - pow((1 + ($rate / 12)), ($nbterm * -1))); } return $result; @@ -434,30 +434,30 @@ class LoanSchedule extends CommonObject global $langs; $sql = "SELECT"; - $sql.= " t.rowid,"; - $sql.= " t.fk_loan,"; - $sql.= " t.datec,"; - $sql.= " t.tms,"; - $sql.= " t.datep,"; - $sql.= " t.amount_capital,"; - $sql.= " t.amount_insurance,"; - $sql.= " t.amount_interest,"; - $sql.= " t.fk_typepayment,"; - $sql.= " t.num_payment,"; - $sql.= " t.note_private,"; - $sql.= " t.note_public,"; - $sql.= " t.fk_bank,"; - $sql.= " t.fk_user_creat,"; - $sql.= " t.fk_user_modif"; - $sql.= " FROM ".MAIN_DB_PREFIX.$this->table_element." as t"; - $sql.= " WHERE t.fk_loan = ".$loanid; + $sql .= " t.rowid,"; + $sql .= " t.fk_loan,"; + $sql .= " t.datec,"; + $sql .= " t.tms,"; + $sql .= " t.datep,"; + $sql .= " t.amount_capital,"; + $sql .= " t.amount_insurance,"; + $sql .= " t.amount_interest,"; + $sql .= " t.fk_typepayment,"; + $sql .= " t.num_payment,"; + $sql .= " t.note_private,"; + $sql .= " t.note_public,"; + $sql .= " t.fk_bank,"; + $sql .= " t.fk_user_creat,"; + $sql .= " t.fk_user_modif"; + $sql .= " FROM ".MAIN_DB_PREFIX.$this->table_element." as t"; + $sql .= " WHERE t.fk_loan = ".$loanid; dol_syslog(get_class($this)."::fetchAll", LOG_DEBUG); - $resql=$this->db->query($sql); + $resql = $this->db->query($sql); if ($resql) { - while($obj = $this->db->fetch_object($resql)) + while ($obj = $this->db->fetch_object($resql)) { $line = new LoanSchedule($this->db); $line->id = $obj->rowid; @@ -485,7 +485,7 @@ class LoanSchedule extends CommonObject } else { - $this->error="Error ".$this->db->lasterror(); + $this->error = "Error ".$this->db->lasterror(); return -1; } } @@ -504,24 +504,24 @@ class LoanSchedule extends CommonObject $toinsert = array(); $sql = "SELECT l.rowid"; - $sql.= " FROM ".MAIN_DB_PREFIX."loan as l "; - $sql.= " WHERE l.paid = 0"; - $resql=$this->db->query($sql); + $sql .= " FROM ".MAIN_DB_PREFIX."loan as l "; + $sql .= " WHERE l.paid = 0"; + $resql = $this->db->query($sql); - if($resql){ - while($obj = $this->db->fetch_object($resql)){ + if ($resql) { + while ($obj = $this->db->fetch_object($resql)) { $lastrecorded = $this->lastPayment($obj->rowid); $toinsert = $this->paimenttorecord($obj->rowid, $lastrecorded); - if(count($toinsert)>0){ - foreach ($toinsert as $echid){ + if (count($toinsert) > 0) { + foreach ($toinsert as $echid) { $this->db->begin(); - $sql = "INSERT INTO " .MAIN_DB_PREFIX . "payment_loan "; - $sql.= "(fk_loan,datec,tms,datep,amount_capital,amount_insurance,amount_interest,fk_typepayment,num_payment,note_private,note_public,fk_bank,fk_user_creat,fk_user_modif) "; - $sql.= "SELECT fk_loan,datec,tms,datep,amount_capital,amount_insurance,amount_interest,fk_typepayment,num_payment,note_private,note_public,fk_bank,fk_user_creat,fk_user_modif FROM " . MAIN_DB_PREFIX . "loan_schedule WHERE rowid =" .$echid; - $res=$this->db->query($sql); - if($res){ + $sql = "INSERT INTO ".MAIN_DB_PREFIX."payment_loan "; + $sql .= "(fk_loan,datec,tms,datep,amount_capital,amount_insurance,amount_interest,fk_typepayment,num_payment,note_private,note_public,fk_bank,fk_user_creat,fk_user_modif) "; + $sql .= "SELECT fk_loan,datec,tms,datep,amount_capital,amount_insurance,amount_interest,fk_typepayment,num_payment,note_private,note_public,fk_bank,fk_user_creat,fk_user_modif FROM ".MAIN_DB_PREFIX."loan_schedule WHERE rowid =".$echid; + $res = $this->db->query($sql); + if ($res) { $this->db->commit(); - }else { + } else { $this->db->rollback(); } } @@ -540,17 +540,17 @@ class LoanSchedule extends CommonObject private function lastPayment($loanid) { $sql = "SELECT p.datep"; - $sql.= " FROM ".MAIN_DB_PREFIX."payment_loan as p "; - $sql.= " WHERE p.fk_loan = " . $loanid; - $sql.= " ORDER BY p.datep DESC "; - $sql.= " LIMIT 1 "; + $sql .= " FROM ".MAIN_DB_PREFIX."payment_loan as p "; + $sql .= " WHERE p.fk_loan = ".$loanid; + $sql .= " ORDER BY p.datep DESC "; + $sql .= " LIMIT 1 "; - $resql=$this->db->query($sql); + $resql = $this->db->query($sql); - if($resql){ + if ($resql) { $obj = $this->db->fetch_object($resql); return $this->db->jdate($obj->datep); - }else{ + } else { return -1; } } @@ -568,15 +568,15 @@ class LoanSchedule extends CommonObject $result=array(); $sql = "SELECT p.rowid"; - $sql.= " FROM ".MAIN_DB_PREFIX.$this->table_element." as p "; - $sql.= " WHERE p.fk_loan = " . $loanid; - if (!empty($datemax)) { $sql.= " AND p.datep > '" . $this->db->idate($datemax) ."'";} - $sql.= " AND p.datep <= '" . $this->db->idate(dol_now()). "'"; + $sql .= " FROM ".MAIN_DB_PREFIX.$this->table_element." as p "; + $sql .= " WHERE p.fk_loan = ".$loanid; + if (!empty($datemax)) { $sql .= " AND p.datep > '".$this->db->idate($datemax)."'"; } + $sql .= " AND p.datep <= '".$this->db->idate(dol_now())."'"; - $resql=$this->db->query($sql); + $resql = $this->db->query($sql); - if($resql){ - while($obj = $this->db->fetch_object($resql)) + if ($resql) { + while ($obj = $this->db->fetch_object($resql)) { $result[] = $obj->rowid; } diff --git a/htdocs/loan/class/paymentloan.class.php b/htdocs/loan/class/paymentloan.class.php index eb0508c3768..9dd4a9ac284 100644 --- a/htdocs/loan/class/paymentloan.class.php +++ b/htdocs/loan/class/paymentloan.class.php @@ -33,12 +33,12 @@ class PaymentLoan extends CommonObject /** * @var string ID to identify managed object */ - public $element='payment_loan'; + public $element = 'payment_loan'; /** * @var string Name of table without prefix where object is stored */ - public $table_element='payment_loan'; + public $table_element = 'payment_loan'; /** * @var int Loan ID @@ -48,18 +48,18 @@ class PaymentLoan extends CommonObject /** * @var string Create date */ - public $datec=''; + public $datec = ''; - public $tms=''; + public $tms = ''; /** * @var string Payment date */ - public $datep=''; + public $datep = ''; - public $amounts=array(); // Array of amounts + public $amounts = array(); // Array of amounts - public $amount_capital; // Total amount of payment + public $amount_capital; // Total amount of payment public $amount_insurance; @@ -115,22 +115,22 @@ class PaymentLoan extends CommonObject { global $conf, $langs; - $error=0; + $error = 0; - $now=dol_now(); + $now = dol_now(); // Validate parameters - if (! $this->datep) + if (!$this->datep) { - $this->error='ErrorBadValueForParameter'; + $this->error = 'ErrorBadValueForParameter'; return -1; } // Clean parameters if (isset($this->fk_loan)) $this->fk_loan = (int) $this->fk_loan; - if (isset($this->amount_capital)) $this->amount_capital = price2num($this->amount_capital?$this->amount_capital:0); - if (isset($this->amount_insurance)) $this->amount_insurance = price2num($this->amount_insurance?$this->amount_insurance:0); - if (isset($this->amount_interest)) $this->amount_interest = price2num($this->amount_interest?$this->amount_interest:0); + if (isset($this->amount_capital)) $this->amount_capital = price2num($this->amount_capital ? $this->amount_capital : 0); + if (isset($this->amount_insurance)) $this->amount_insurance = price2num($this->amount_insurance ? $this->amount_insurance : 0); + if (isset($this->amount_interest)) $this->amount_interest = price2num($this->amount_interest ? $this->amount_interest : 0); if (isset($this->fk_typepayment)) $this->fk_typepayment = (int) $this->fk_typepayment; if (isset($this->num_payment)) $this->num_payment = (int) $this->num_payment; if (isset($this->note_private)) $this->note_private = trim($this->note_private); @@ -151,37 +151,37 @@ class PaymentLoan extends CommonObject if ($totalamount != 0) { $sql = "INSERT INTO ".MAIN_DB_PREFIX."payment_loan (fk_loan, datec, datep, amount_capital, amount_insurance, amount_interest,"; - $sql.= " fk_typepayment, num_payment, note_private, note_public, fk_user_creat, fk_bank)"; - $sql.= " VALUES (".$this->chid.", '".$this->db->idate($now)."',"; - $sql.= " '".$this->db->idate($this->datep)."',"; - $sql.= " ".$this->amount_capital.","; - $sql.= " ".$this->amount_insurance.","; - $sql.= " ".$this->amount_interest.","; - $sql.= " ".$this->paymenttype.", '".$this->db->escape($this->num_payment)."', '".$this->db->escape($this->note_private)."', '".$this->db->escape($this->note_public)."', ".$user->id.","; - $sql.= " 0)"; + $sql .= " fk_typepayment, num_payment, note_private, note_public, fk_user_creat, fk_bank)"; + $sql .= " VALUES (".$this->chid.", '".$this->db->idate($now)."',"; + $sql .= " '".$this->db->idate($this->datep)."',"; + $sql .= " ".$this->amount_capital.","; + $sql .= " ".$this->amount_insurance.","; + $sql .= " ".$this->amount_interest.","; + $sql .= " ".$this->paymenttype.", '".$this->db->escape($this->num_payment)."', '".$this->db->escape($this->note_private)."', '".$this->db->escape($this->note_public)."', ".$user->id.","; + $sql .= " 0)"; dol_syslog(get_class($this)."::create", LOG_DEBUG); - $resql=$this->db->query($sql); + $resql = $this->db->query($sql); if ($resql) { $this->id = $this->db->last_insert_id(MAIN_DB_PREFIX."payment_loan"); } else { - $this->error=$this->db->lasterror(); + $this->error = $this->db->lasterror(); $error++; } } - if ($totalamount != 0 && ! $error) + if ($totalamount != 0 && !$error) { - $this->amount_capital=$totalamount; + $this->amount_capital = $totalamount; $this->db->commit(); return $this->id; } else { - $this->error=$this->db->lasterror(); + $this->error = $this->db->lasterror(); $this->db->rollback(); return -1; } @@ -257,7 +257,7 @@ class PaymentLoan extends CommonObject } else { - $this->error="Error ".$this->db->lasterror(); + $this->error = "Error ".$this->db->lasterror(); return -1; } } @@ -273,17 +273,17 @@ class PaymentLoan extends CommonObject public function update($user = 0, $notrigger = 0) { global $conf, $langs; - $error=0; + $error = 0; // Clean parameters if (isset($this->fk_loan)) $this->fk_loan = (int) $this->fk_loan; - if (isset($this->amount_capital)) $this->amount_capital=trim($this->amount_capital); - if (isset($this->amount_insurance)) $this->amount_insurance=trim($this->amount_insurance); - if (isset($this->amount_interest)) $this->amount_interest=trim($this->amount_interest); + if (isset($this->amount_capital)) $this->amount_capital = trim($this->amount_capital); + if (isset($this->amount_insurance)) $this->amount_insurance = trim($this->amount_insurance); + if (isset($this->amount_interest)) $this->amount_interest = trim($this->amount_interest); if (isset($this->fk_typepayment)) $this->fk_typepayment = (int) $this->fk_typepayment; if (isset($this->num_payment)) $this->num_payment = (int) $this->num_payment; - if (isset($this->note_private)) $this->note=trim($this->note_private); - if (isset($this->note_public)) $this->note=trim($this->note_public); + if (isset($this->note_private)) $this->note = trim($this->note_private); + if (isset($this->note_public)) $this->note = trim($this->note_public); 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; @@ -293,32 +293,32 @@ class PaymentLoan extends CommonObject // Update request $sql = "UPDATE ".MAIN_DB_PREFIX."payment_loan SET"; - $sql.= " fk_loan=".(isset($this->fk_loan)?$this->fk_loan:"null").","; - $sql.= " datec=".(dol_strlen($this->datec)!=0 ? "'".$this->db->idate($this->datec)."'" : 'null').","; - $sql.= " tms=".(dol_strlen($this->tms)!=0 ? "'".$this->db->idate($this->tms)."'" : 'null').","; - $sql.= " datep=".(dol_strlen($this->datep)!=0 ? "'".$this->db->idate($this->datep)."'" : 'null').","; - $sql.= " amount_capital=".(isset($this->amount_capital)?$this->amount_capital:"null").","; - $sql.= " amount_insurance=".(isset($this->amount_insurance)?$this->amount_insurance:"null").","; - $sql.= " amount_interest=".(isset($this->amount_interest)?$this->amount_interest:"null").","; - $sql.= " fk_typepayment=".(isset($this->fk_typepayment)?$this->fk_typepayment:"null").","; - $sql.= " num_payment=".(isset($this->num_payment)?"'".$this->db->escape($this->num_payment)."'":"null").","; - $sql.= " note_private=".(isset($this->note_private)?"'".$this->db->escape($this->note_private)."'":"null").","; - $sql.= " note_public=".(isset($this->note_public)?"'".$this->db->escape($this->note_public)."'":"null").","; - $sql.= " fk_bank=".(isset($this->fk_bank)?$this->fk_bank:"null").","; - $sql.= " fk_user_creat=".(isset($this->fk_user_creat)?$this->fk_user_creat:"null").","; - $sql.= " fk_user_modif=".(isset($this->fk_user_modif)?$this->fk_user_modif:"null").""; + $sql .= " fk_loan=".(isset($this->fk_loan) ? $this->fk_loan : "null").","; + $sql .= " datec=".(dol_strlen($this->datec) != 0 ? "'".$this->db->idate($this->datec)."'" : 'null').","; + $sql .= " tms=".(dol_strlen($this->tms) != 0 ? "'".$this->db->idate($this->tms)."'" : 'null').","; + $sql .= " datep=".(dol_strlen($this->datep) != 0 ? "'".$this->db->idate($this->datep)."'" : 'null').","; + $sql .= " amount_capital=".(isset($this->amount_capital) ? $this->amount_capital : "null").","; + $sql .= " amount_insurance=".(isset($this->amount_insurance) ? $this->amount_insurance : "null").","; + $sql .= " amount_interest=".(isset($this->amount_interest) ? $this->amount_interest : "null").","; + $sql .= " fk_typepayment=".(isset($this->fk_typepayment) ? $this->fk_typepayment : "null").","; + $sql .= " num_payment=".(isset($this->num_payment) ? "'".$this->db->escape($this->num_payment)."'" : "null").","; + $sql .= " note_private=".(isset($this->note_private) ? "'".$this->db->escape($this->note_private)."'" : "null").","; + $sql .= " note_public=".(isset($this->note_public) ? "'".$this->db->escape($this->note_public)."'" : "null").","; + $sql .= " fk_bank=".(isset($this->fk_bank) ? $this->fk_bank : "null").","; + $sql .= " fk_user_creat=".(isset($this->fk_user_creat) ? $this->fk_user_creat : "null").","; + $sql .= " fk_user_modif=".(isset($this->fk_user_modif) ? $this->fk_user_modif : "null").""; - $sql.= " WHERE rowid=".$this->id; + $sql .= " WHERE rowid=".$this->id; $this->db->begin(); dol_syslog(get_class($this)."::update", LOG_DEBUG); $resql = $this->db->query($sql); - if (! $resql) { $error++; $this->errors[]="Error ".$this->db->lasterror(); } + if (!$resql) { $error++; $this->errors[] = "Error ".$this->db->lasterror(); } - if (! $error) + if (!$error) { - if (! $notrigger) + if (!$notrigger) { // Uncomment this and change MYOBJECT to your own tag if you // want this action call a trigger. @@ -335,13 +335,13 @@ class PaymentLoan extends CommonObject // Commit or rollback if ($error) { - foreach($this->errors as $errmsg) + foreach ($this->errors as $errmsg) { dol_syslog(get_class($this)."::update ".$errmsg, LOG_ERR); - $this->error.=($this->error?', '.$errmsg:$errmsg); + $this->error .= ($this->error ? ', '.$errmsg : $errmsg); } $this->db->rollback(); - return -1*$error; + return -1 * $error; } else { @@ -361,28 +361,28 @@ class PaymentLoan extends CommonObject public function delete($user, $notrigger = 0) { global $conf, $langs; - $error=0; + $error = 0; $this->db->begin(); - if (! $error) + if (!$error) { $sql = "DELETE FROM ".MAIN_DB_PREFIX."bank_url"; - $sql.= " WHERE type='payment_loan' AND url_id=".$this->id; + $sql .= " WHERE type='payment_loan' 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_loan"; - $sql.= " WHERE rowid=".$this->id; + $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(); } } //if (! $error) @@ -404,13 +404,13 @@ class PaymentLoan extends CommonObject // Commit or rollback if ($error) { - 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); + $this->error .= ($this->error ? ', '.$errmsg : $errmsg); } $this->db->rollback(); - return -1*$error; + return -1 * $error; } else { @@ -436,22 +436,22 @@ class PaymentLoan extends CommonObject { global $conf; - $error=0; + $error = 0; - if (! empty($conf->banque->enabled)) + if (!empty($conf->banque->enabled)) { require_once DOL_DOCUMENT_ROOT.'/compta/bank/class/account.class.php'; $acc = new Account($this->db); $acc->fetch($accountid); - $total=$this->amount_capital; - if ($mode == 'payment_loan') $total=-$total; + $total = $this->amount_capital; + if ($mode == 'payment_loan') $total = -$total; // Insert payment into llx_bank $bank_line_id = $acc->addline( $this->datep, - $this->paymenttype, // Payment mode id or code ("CHQ or VIR for example") + $this->paymenttype, // Payment mode id or code ("CHQ or VIR for example") $label, $total, $this->num_payment, @@ -465,7 +465,7 @@ class PaymentLoan extends CommonObject // We know the payment who generated the account write if ($bank_line_id > 0) { - $result=$this->update_fk_bank($bank_line_id); + $result = $this->update_fk_bank($bank_line_id); if ($result <= 0) { $error++; @@ -473,11 +473,11 @@ class PaymentLoan extends CommonObject } // Add link 'payment_loan' in bank_url between payment and bank transaction - $url=''; - if ($mode == 'payment_loan') $url=DOL_URL_ROOT.'/loan/payment/card.php?id='; + $url = ''; + if ($mode == 'payment_loan') $url = DOL_URL_ROOT.'/loan/payment/card.php?id='; if ($url) { - $result=$acc->add_url_line($bank_line_id, $this->id, $url, '(payment)', $mode); + $result = $acc->add_url_line($bank_line_id, $this->id, $url, '(payment)', $mode); if ($result <= 0) { $error++; @@ -488,18 +488,18 @@ class PaymentLoan extends CommonObject // Add link 'loan' in bank_url between invoice and bank transaction (for each invoice concerned by payment) if ($mode == 'payment_loan') { - $result=$acc->add_url_line($bank_line_id, $fk_loan, DOL_URL_ROOT.'/loan/card.php?id=', ($this->label?$this->label:''), 'loan'); + $result = $acc->add_url_line($bank_line_id, $fk_loan, DOL_URL_ROOT.'/loan/card.php?id=', ($this->label ? $this->label : ''), 'loan'); if ($result <= 0) dol_print_error($this->db); } } else { - $this->error=$acc->error; + $this->error = $acc->error; $error++; } } - if (! $error) + if (!$error) { return 1; } @@ -531,7 +531,7 @@ class PaymentLoan extends CommonObject } else { - $this->error=$this->db->error(); + $this->error = $this->db->error(); return 0; } } diff --git a/htdocs/loan/createschedule.php b/htdocs/loan/createschedule.php index e1b7652ef63..65b8bc1a244 100644 --- a/htdocs/loan/createschedule.php +++ b/htdocs/loan/createschedule.php @@ -35,12 +35,12 @@ $object = new Loan($db); $object->fetch($loanid); // Load translation files required by the page -$langs->loadLangs(array("compta","bills","loan")); +$langs->loadLangs(array("compta", "bills", "loan")); if ($action == 'createecheancier') { - $i=1; - while($i <$object->nbterm+1){ - $date = GETPOST('hi_date'.$i, 'int'); + $i = 1; + while ($i < $object->nbterm + 1) { + $date = GETPOST('hi_date'.$i, 'int'); $mens = GETPOST('mens'.$i); $int = GETPOST('hi_interets'.$i); $insurance = GETPOST('hi_insurance'.$i); @@ -51,15 +51,15 @@ if ($action == 'createecheancier') { $echeance->datec = dol_now(); $echeance->tms = dol_now(); $echeance->datep = $date; - $echeance->amount_capital = $mens-$int; + $echeance->amount_capital = $mens - $int; $echeance->amount_insurance = $insurance; $echeance->amount_interest = $int; $echeance->fk_typepayment = 3; $echeance->fk_bank = 0; $echeance->fk_user_creat = $user->id; $echeance->fk_user_modif = $user->id; - $result=$echeance->create($user); - if ($result<0) { + $result = $echeance->create($user); + if ($result < 0) { setEventMessages($echeance->error, $echeance->errors, 'errors'); } $i++; @@ -67,8 +67,8 @@ if ($action == 'createecheancier') { } if ($action == 'updateecheancier') { - $i=1; - while($i <$object->nbterm+1){ + $i = 1; + while ($i < $object->nbterm + 1) { $mens = GETPOST('mens'.$i); $int = GETPOST('hi_interets'.$i); $id = GETPOST('hi_rowid'.$i); @@ -77,12 +77,12 @@ if ($action == 'updateecheancier') { $echeance = new LoanSchedule($db); $echeance->fetch($id); $echeance->tms = dol_now(); - $echeance->amount_capital = $mens-$int; + $echeance->amount_capital = $mens - $int; $echeance->amount_insurance = $insurance; $echeance->amount_interest = $int; $echeance->fk_user_modif = $user->id; - $result= $echeance->update($user, 0); - if ($result<0) { + $result = $echeance->update($user, 0); + if ($result < 0) { setEventMessages(null, $echeance->errors, 'errors'); } $i++; @@ -93,7 +93,7 @@ $echeance = new LoanSchedule($db); $echeance->fetchAll($object->id); top_htmlhead('', ''); -$var = ! $var; +$var = !$var; ?> @@ -109,7 +109,7 @@ $(document).ready(function() { $.ajax({ dataType: 'json', url: 'calcmens.php', - data: { echeance: echeance, mens: mens, capital:capital, rate:rate/100;?> , nbterm : nbterm;?>}, + data: { echeance: echeance, mens: mens, capital:capital, rate:rate / 100; ?> , nbterm : nbterm; ?>}, success: function(data) { $.each(data, function(index, element) { var idcap_res='#hi_capital'+index; @@ -131,19 +131,19 @@ $(document).ready(function() { '; -print ''; -print ''; -if(count($echeance->lines)>0) +print ''; +print ''; +print ''; +if (count($echeance->lines) > 0) { print ''; -}else{ +} else { print ''; } -print '
    '.$langs->trans("RefPayment").'
    '.$langs->trans("RemainderToPay").' :'; + print ''; print price($staytopay, 0, $langs, 0, 0, -1, $conf->currency); print '
    '; +print '
    '; print ''; $colspan = 6; -if (count($echeance->lines)>0) $colspan++; +if (count($echeance->lines) > 0) $colspan++; print ''; @@ -159,57 +159,57 @@ print ''; -if (count($echeance->lines)>0) print ''; +if (count($echeance->lines) > 0) print ''; print ''."\n"; -if ($object->nbterm > 0 && count($echeance->lines)==0) +if ($object->nbterm > 0 && count($echeance->lines) == 0) { - $i=1; + $i = 1; $capital = $object->capital; - $insurance = $object->insurance_amount/$object->nbterm; + $insurance = $object->insurance_amount / $object->nbterm; $insurance = price2num($insurance, 'MT'); $regulInsurance = price2num($object->insurance_amount - ($insurance * $object->nbterm)); - while($i <$object->nbterm+1) + while ($i < $object->nbterm + 1) { - $mens = price2num($echeance->calcMonthlyPayments($capital, $object->rate/100, $object->nbterm-$i+1), 'MT'); - $int = ($capital*($object->rate/12))/100; + $mens = price2num($echeance->calcMonthlyPayments($capital, $object->rate / 100, $object->nbterm - $i + 1), 'MT'); + $int = ($capital * ($object->rate / 12)) / 100; $int = price2num($int, 'MT'); - $cap_rest = price2num($capital - ($mens-$int), 'MT'); + $cap_rest = price2num($capital - ($mens - $int), 'MT'); print ''; - print ''; - print ''; - print ''; - print ''; + print ''; + print ''; + print ''; + print ''; print ''; - print ''; + print ''; print ''."\n"; $i++; $capital = $cap_rest; } } -elseif(count($echeance->lines)>0) +elseif (count($echeance->lines) > 0) { - $i=1; + $i = 1; $capital = $object->capital; - $insurance = $object->insurance_amount/$object->nbterm; + $insurance = $object->insurance_amount / $object->nbterm; $insurance = price2num($insurance, 'MT'); $regulInsurance = price2num($object->insurance_amount - ($insurance * $object->nbterm)); - foreach ($echeance->lines as $line){ - $mens = $line->amount_capital+$line->amount_insurance+$line->amount_interest; + foreach ($echeance->lines as $line) { + $mens = $line->amount_capital + $line->amount_insurance + $line->amount_interest; $int = $line->amount_interest; - $cap_rest = price2num($capital - ($mens-$int), 'MT'); + $cap_rest = price2num($capital - ($mens - $int), 'MT'); print ''; - print ''; - print ''; - print ''; - print ''; - if($line->datep > dol_now()){ + print ''; + print ''; + print ''; + print ''; + if ($line->datep > dol_now()) { print ''; - }else{ - print ''; + } else { + print ''; } - print ''; + print ''; print ''; print ''."\n"; $i++; diff --git a/htdocs/loan/document.php b/htdocs/loan/document.php index a4bed07949e..a4328bec863 100644 --- a/htdocs/loan/document.php +++ b/htdocs/loan/document.php @@ -53,21 +53,21 @@ if (empty($page) || $page == -1) { $offset = $conf->liste_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 Loan($db); if ($id > 0) $object->fetch($id); $upload_dir = $conf->loan->dir_output.'/'.dol_sanitizeFileName($object->ref); -$modulepart='loan'; +$modulepart = 'loan'; /* * Actions */ -include_once DOL_DOCUMENT_ROOT . '/core/actions_linkedfiles.inc.php'; +include_once DOL_DOCUMENT_ROOT.'/core/actions_linkedfiles.inc.php'; /* @@ -76,45 +76,45 @@ include_once DOL_DOCUMENT_ROOT . '/core/actions_linkedfiles.inc.php'; $form = new Form($db); -$title = $langs->trans("Loan") . ' - ' . $langs->trans("Documents"); +$title = $langs->trans("Loan").' - '.$langs->trans("Documents"); $help_url = 'EN:Module_Loan|FR:Module_Emprunt'; llxHeader("", $title, $help_url); if ($object->id) { - $totalpaid=$object->getSumPayment(); + $totalpaid = $object->getSumPayment(); $head = loan_prepare_head($object); dol_fiche_head($head, 'documents', $langs->trans("Loan"), -1, 'bill'); - $morehtmlref='
    '; + $morehtmlref = '
    '; // Ref loan - $morehtmlref.=$form->editfieldkey("Label", 'label', $object->label, $object, 0, 'string', '', 0, 1); - $morehtmlref.=$form->editfieldval("Label", 'label', $object->label, $object, 0, 'string', '', null, null, '', 1); + $morehtmlref .= $form->editfieldkey("Label", 'label', $object->label, $object, 0, 'string', '', 0, 1); + $morehtmlref .= $form->editfieldval("Label", 'label', $object->label, $object, 0, 'string', '', null, null, '', 1); // Project - if (! empty($conf->projet->enabled)) { + if (!empty($conf->projet->enabled)) { $langs->load("projects"); - $morehtmlref .= '
    ' . $langs->trans('Project') . ' : '; + $morehtmlref .= '
    '.$langs->trans('Project').' : '; if ($user->rights->loan->write) { //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 .= ''; + $morehtmlref .= ''; $morehtmlref .= $formproject->select_projects($object->socid, $object->fk_project, 'projectid', $maxlength, 0, 1, 0, 1, 0, 0, '', 1); - $morehtmlref .= ''; + $morehtmlref .= ''; $morehtmlref .= ''; } else { - $morehtmlref .= $form->form_project($_SERVER['PHP_SELF'] . '?id=' . $object->id, $object->socid, $object->fk_project, 'none', 0, 0, 0, 1); + $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)) { + if (!empty($object->fk_project)) { $proj = new Project($db); $proj->fetch($object->fk_project); - $morehtmlref .= ''; + $morehtmlref .= ''; $morehtmlref .= $proj->ref; $morehtmlref .= ''; } else { @@ -122,11 +122,11 @@ if ($object->id) } } } - $morehtmlref.='
    '; + $morehtmlref .= '
    '; - $linkback = '' . $langs->trans("BackToList") . ''; + $linkback = ''.$langs->trans("BackToList").''; - $object->totalpaid = $totalpaid; // To give a chance to dol_banner_tab to use already paid amount to show correct status + $object->totalpaid = $totalpaid; // To give a chance to dol_banner_tab to use already paid amount to show correct status dol_banner_tab($object, 'id', $linkback, 1, 'rowid', 'ref', $morehtmlref, '', 0, '', $morehtmlright); @@ -135,11 +135,11 @@ 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) + $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) { - $totalsize+=$file['size']; + $totalsize += $file['size']; } @@ -155,8 +155,8 @@ if ($object->id) $modulepart = 'loan'; $permission = $user->rights->loan->write; $permtoedit = $user->rights->loan->write; - $param = '&id=' . $object->id; - include_once DOL_DOCUMENT_ROOT . '/core/tpl/document_actions_post_headers.tpl.php'; + $param = '&id='.$object->id; + include_once DOL_DOCUMENT_ROOT.'/core/tpl/document_actions_post_headers.tpl.php'; } else { diff --git a/htdocs/loan/info.php b/htdocs/loan/info.php index 618345518ed..1a26a8a12da 100644 --- a/htdocs/loan/info.php +++ b/htdocs/loan/info.php @@ -48,7 +48,7 @@ $result = restrictedArea($user, 'loan', $id, '', ''); $form = new Form($db); -$title = $langs->trans("Loan") . ' - ' . $langs->trans("Info"); +$title = $langs->trans("Loan").' - '.$langs->trans("Info"); $help_url = 'EN:Module_Loan|FR:Module_Emprunt'; llxHeader("", $title, $help_url); @@ -60,33 +60,33 @@ $head = loan_prepare_head($object); dol_fiche_head($head, 'info', $langs->trans("Loan"), -1, 'bill'); -$morehtmlref='
    '; +$morehtmlref = '
    '; // Ref loan -$morehtmlref.=$form->editfieldkey("Label", 'label', $object->label, $object, 0, 'string', '', 0, 1); -$morehtmlref.=$form->editfieldval("Label", 'label', $object->label, $object, 0, 'string', '', null, null, '', 1); +$morehtmlref .= $form->editfieldkey("Label", 'label', $object->label, $object, 0, 'string', '', 0, 1); +$morehtmlref .= $form->editfieldval("Label", 'label', $object->label, $object, 0, 'string', '', null, null, '', 1); // Project -if (! empty($conf->projet->enabled)) { +if (!empty($conf->projet->enabled)) { $langs->load("projects"); - $morehtmlref .= '
    ' . $langs->trans('Project') . ' : '; + $morehtmlref .= '
    '.$langs->trans('Project').' : '; if ($user->rights->loan->write) { //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 .= ''; + $morehtmlref .= ''; $morehtmlref .= $formproject->select_projects($object->socid, $object->fk_project, 'projectid', $maxlength, 0, 1, 0, 1, 0, 0, '', 1); - $morehtmlref .= ''; + $morehtmlref .= ''; $morehtmlref .= ''; } else { - $morehtmlref .= $form->form_project($_SERVER['PHP_SELF'] . '?id=' . $object->id, $object->socid, $object->fk_project, 'none', 0, 0, 0, 1); + $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)) { + if (!empty($object->fk_project)) { $proj = new Project($db); $proj->fetch($object->fk_project); - $morehtmlref .= ''; + $morehtmlref .= ''; $morehtmlref .= $proj->ref; $morehtmlref .= ''; } else { @@ -94,11 +94,11 @@ if (! empty($conf->projet->enabled)) { } } } -$morehtmlref.='
    '; +$morehtmlref .= '
    '; -$linkback = '' . $langs->trans("BackToList") . ''; +$linkback = ''.$langs->trans("BackToList").''; -$object->totalpaid = $totalpaid; // To give a chance to dol_banner_tab to use already paid amount to show correct status +$object->totalpaid = $totalpaid; // To give a chance to dol_banner_tab to use already paid amount to show correct status dol_banner_tab($object, 'id', $linkback, 1, 'rowid', 'ref', $morehtmlref, '', 0, '', $morehtmlright); diff --git a/htdocs/loan/list.php b/htdocs/loan/list.php index c77d6b1c855..bd280aacab5 100644 --- a/htdocs/loan/list.php +++ b/htdocs/loan/list.php @@ -43,21 +43,21 @@ if (empty($page) || $page == -1) { $page = 0; } // If $page is not defined, $offset = $limit * $page; $pageprev = $page - 1; $pagenext = $page + 1; -if (! $sortfield) $sortfield="l.rowid"; -if (! $sortorder) $sortorder="DESC"; +if (!$sortfield) $sortfield = "l.rowid"; +if (!$sortorder) $sortorder = "DESC"; -$search_ref=GETPOST('search_ref', 'int'); -$search_label=GETPOST('search_label', 'alpha'); -$search_amount=GETPOST('search_amount', 'alpha'); -$filtre=GETPOST("filtre"); +$search_ref = GETPOST('search_ref', 'int'); +$search_label = GETPOST('search_label', 'alpha'); +$search_amount = GETPOST('search_amount', 'alpha'); +$filtre = GETPOST("filtre"); $optioncss = GETPOST('optioncss', 'alpha'); // Purge search criteria if (GETPOST('button_removefilter_x', 'alpha') || GETPOST('button_removefilter', 'alpha')) // Both test are required to be compatible with all browsers { - $search_ref=""; - $search_label=""; - $search_amount=""; + $search_ref = ""; + $search_label = ""; + $search_amount = ""; } @@ -70,19 +70,19 @@ $loan_static = new Loan($db); llxHeader(); $sql = "SELECT l.rowid, l.label, l.capital, l.datestart, l.dateend, l.paid,"; -$sql.= " SUM(pl.amount_capital) as alreadypayed"; -$sql.= " FROM ".MAIN_DB_PREFIX."loan as l LEFT JOIN ".MAIN_DB_PREFIX."payment_loan AS pl"; -$sql.= " ON l.rowid = pl.fk_loan"; -$sql.= " WHERE l.entity = ".$conf->entity; -if ($search_amount) $sql.= natural_search("l.capital", $search_amount, 1); -if ($search_ref) $sql.= " AND l.rowid = ".$db->escape($search_ref); -if ($search_label) $sql.= natural_search("l.label", $search_label); +$sql .= " SUM(pl.amount_capital) as alreadypayed"; +$sql .= " FROM ".MAIN_DB_PREFIX."loan as l LEFT JOIN ".MAIN_DB_PREFIX."payment_loan AS pl"; +$sql .= " ON l.rowid = pl.fk_loan"; +$sql .= " WHERE l.entity = ".$conf->entity; +if ($search_amount) $sql .= natural_search("l.capital", $search_amount, 1); +if ($search_ref) $sql .= " AND l.rowid = ".$db->escape($search_ref); +if ($search_label) $sql .= natural_search("l.label", $search_label); if ($filtre) { - $filtre=str_replace(":", "=", $filtre); + $filtre = str_replace(":", "=", $filtre); $sql .= " AND ".$filtre; } -$sql.= " GROUP BY l.rowid, l.label, l.capital, l.paid, l.datestart, l.dateend"; -$sql.= $db->order($sortfield, $sortorder); +$sql .= " GROUP BY l.rowid, l.label, l.capital, l.paid, l.datestart, l.dateend"; +$sql .= $db->order($sortfield, $sortorder); $nbtotalofrecords = ''; if (empty($conf->global->MAIN_DISABLE_FULL_SCANLIST)) @@ -131,7 +131,7 @@ if ($resql) print_barre_liste($langs->trans("Loans"), $page, $_SERVER["PHP_SELF"], $param, $sortfield, $sortorder, '', $num, $nbtotalofrecords, 'title_accountancy.png', 0, $newcardbutton, '', $limit); print '
    '; - print '
    '; print $langs->trans("FinancialCommitment"); print ''.$langs->trans("CapitalRemain"); print ' ('.price2num($object->capital).')'; print ''; print ''.$langs->trans('DoPayment').''.$langs->trans('DoPayment').'
    ' . $i .'' . dol_print_date(dol_time_plus_duree($object->datestart, $i-1, 'm'), 'day') . ''.price($insurance+(($i == 1) ? $regulInsurance : 0), 0, '', 1).' €'.price($int, 0, '', 1).' €'.$i.''.dol_print_date(dol_time_plus_duree($object->datestart, $i - 1, 'm'), 'day').''.price($insurance + (($i == 1) ? $regulInsurance : 0), 0, '', 1).' €'.price($int, 0, '', 1).' € €'.price($cap_rest).' €'.price($cap_rest).' €
    ' . $i .'' . dol_print_date($line->datep, 'day') . ''.price($insurance+(($i == 1) ? $regulInsurance : 0), 0, '', 1).' €'.price($int, 0, '', 1).' €'.$i.''.dol_print_date($line->datep, 'day').''.price($insurance + (($i == 1) ? $regulInsurance : 0), 0, '', 1).' €'.price($int, 0, '', 1).' € €' . price($mens) . ' €'.price($mens).' €'.price($cap_rest).' €'.price($cap_rest).' €'.$langs->trans('DoPayment').'
    '."\n"; + print '
    '."\n"; // Filters lines print ''; diff --git a/htdocs/loan/note.php b/htdocs/loan/note.php index 4ddd7bdccee..ebe0b9d876c 100644 --- a/htdocs/loan/note.php +++ b/htdocs/loan/note.php @@ -30,8 +30,8 @@ require '../main.inc.php'; require_once DOL_DOCUMENT_ROOT.'/loan/class/loan.class.php'; require_once DOL_DOCUMENT_ROOT.'/core/lib/loan.lib.php'; -if (! empty($conf->projet->enabled)) { - require_once DOL_DOCUMENT_ROOT . '/projet/class/project.class.php'; +if (!empty($conf->projet->enabled)) { + require_once DOL_DOCUMENT_ROOT.'/projet/class/project.class.php'; } $action = GETPOST('action', 'aZ09'); @@ -46,7 +46,7 @@ $result = restrictedArea($user, 'loan', $id, '&loan'); $object = new Loan($db); if ($id > 0) $object->fetch($id); -$permissionnote=$user->rights->loan->write; // Used by the include of actions_setnotes.inc.php +$permissionnote = $user->rights->loan->write; // Used by the include of actions_setnotes.inc.php /* @@ -62,7 +62,7 @@ include DOL_DOCUMENT_ROOT.'/core/actions_setnotes.inc.php'; // Must be include, $form = new Form($db); -$title = $langs->trans("Loan") . ' - ' . $langs->trans("Notes"); +$title = $langs->trans("Loan").' - '.$langs->trans("Notes"); $help_url = 'EN:Module_Loan|FR:Module_Emprunt'; llxHeader("", $title, $help_url); @@ -71,39 +71,39 @@ if ($id > 0) /* * Affichage onglets */ - $totalpaid=$object->getSumPayment(); + $totalpaid = $object->getSumPayment(); $head = loan_prepare_head($object); dol_fiche_head($head, 'note', $langs->trans("Loan"), -1, 'bill'); - $morehtmlref='
    '; + $morehtmlref = '
    '; // Ref loan - $morehtmlref.=$form->editfieldkey("Label", 'label', $object->label, $object, 0, 'string', '', 0, 1); - $morehtmlref.=$form->editfieldval("Label", 'label', $object->label, $object, 0, 'string', '', null, null, '', 1); + $morehtmlref .= $form->editfieldkey("Label", 'label', $object->label, $object, 0, 'string', '', 0, 1); + $morehtmlref .= $form->editfieldval("Label", 'label', $object->label, $object, 0, 'string', '', null, null, '', 1); // Project - if (! empty($conf->projet->enabled)) { + if (!empty($conf->projet->enabled)) { $langs->loadLangs(array("projects")); - $morehtmlref .= '
    ' . $langs->trans('Project') . ' : '; + $morehtmlref .= '
    '.$langs->trans('Project').' : '; if ($user->rights->loan->write) { //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 .= ''; + $morehtmlref .= ''; $morehtmlref .= $formproject->select_projects($object->socid, $object->fk_project, 'projectid', $maxlength, 0, 1, 0, 1, 0, 0, '', 1); - $morehtmlref .= ''; + $morehtmlref .= ''; $morehtmlref .= ''; } else { - $morehtmlref .= $form->form_project($_SERVER['PHP_SELF'] . '?id=' . $object->id, $object->socid, $object->fk_project, 'none', 0, 0, 0, 1); + $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)) { + if (!empty($object->fk_project)) { $proj = new Project($db); $proj->fetch($object->fk_project); - $morehtmlref .= ''; + $morehtmlref .= ''; $morehtmlref .= $proj->ref; $morehtmlref .= ''; } else { @@ -111,19 +111,19 @@ if ($id > 0) } } } - $morehtmlref.='
    '; + $morehtmlref .= '
    '; - $linkback = '' . $langs->trans("BackToList") . ''; + $linkback = ''.$langs->trans("BackToList").''; - $object->totalpaid = $totalpaid; // To give a chance to dol_banner_tab to use already paid amount to show correct status + $object->totalpaid = $totalpaid; // To give a chance to dol_banner_tab to use already paid amount to show correct status dol_banner_tab($object, 'id', $linkback, 1, 'rowid', 'ref', $morehtmlref, '', 0, '', $morehtmlright); print '
    '; print '
    '; - $cssclass='titlefield'; - $permission = $user->rights->loan->write; // Used by the include of notes.tpl.php + $cssclass = 'titlefield'; + $permission = $user->rights->loan->write; // Used by the include of notes.tpl.php include DOL_DOCUMENT_ROOT.'/core/tpl/notes.tpl.php'; dol_fiche_end(); diff --git a/htdocs/loan/payment/card.php b/htdocs/loan/payment/card.php index 1f937e6fe77..f2a3aa3a877 100644 --- a/htdocs/loan/payment/card.php +++ b/htdocs/loan/payment/card.php @@ -146,7 +146,7 @@ if ($action == 'valide') } -print '
    '; +print '
    '; // Ref print ''; @@ -210,7 +210,7 @@ if ($resql) $i = 0; $total = 0; - print '
    '.$langs->trans('Ref').'
    '; + print '
    '; print ''; print ''; print ''; diff --git a/htdocs/loan/payment/payment.php b/htdocs/loan/payment/payment.php index 742cf5ea5cf..b3b08c365f7 100644 --- a/htdocs/loan/payment/payment.php +++ b/htdocs/loan/payment/payment.php @@ -276,7 +276,7 @@ if ($action == 'create') dol_fiche_end(); - print '
    '.$langs->trans('Loan').''.$langs->trans('Label').'
    '; + print '
    '; print ''; print ''; print ''; diff --git a/htdocs/loan/schedule.php b/htdocs/loan/schedule.php index d743c11273b..7ba240a7c14 100644 --- a/htdocs/loan/schedule.php +++ b/htdocs/loan/schedule.php @@ -35,19 +35,19 @@ $object = new Loan($db); $object->fetch($loanid); // Load translation files required by the page -$langs->loadLangs(array("compta","bills","loan")); +$langs->loadLangs(array("compta", "bills", "loan")); -$title = $langs->trans("Loan") . ' - ' . $langs->trans("Card"); +$title = $langs->trans("Loan").' - '.$langs->trans("Card"); $help_url = 'EN:Module_Loan|FR:Module_Emprunt'; llxHeader("", $title, $help_url); -$head=loan_prepare_head($object); +$head = loan_prepare_head($object); dol_fiche_head($head, 'FinancialCommitment', $langs->trans("Loan"), -1, 'bill'); if ($action == 'createecheancier') { - $i=1; - while($i <$object->nbterm+1){ - $date = GETPOST('hi_date'.$i, 'int'); + $i = 1; + while ($i < $object->nbterm + 1) { + $date = GETPOST('hi_date'.$i, 'int'); $mens = GETPOST('mens'.$i); $int = GETPOST('hi_interets'.$i); $insurance = GETPOST('hi_insurance'.$i); @@ -58,15 +58,15 @@ if ($action == 'createecheancier') { $echeance->datec = dol_now(); $echeance->tms = dol_now(); $echeance->datep = $date; - $echeance->amount_capital = $mens-$int; + $echeance->amount_capital = $mens - $int; $echeance->amount_insurance = $insurance; $echeance->amount_interest = $int; $echeance->fk_typepayment = 3; $echeance->fk_bank = 0; $echeance->fk_user_creat = $user->id; $echeance->fk_user_modif = $user->id; - $result=$echeance->create($user); - if ($result<0) { + $result = $echeance->create($user); + if ($result < 0) { setEventMessages($echeance->error, $echeance->errors, 'errors'); } $i++; @@ -74,8 +74,8 @@ if ($action == 'createecheancier') { } if ($action == 'updateecheancier') { - $i=1; - while($i <$object->nbterm+1){ + $i = 1; + while ($i < $object->nbterm + 1) { $mens = GETPOST('mens'.$i); $int = GETPOST('hi_interets'.$i); $id = GETPOST('hi_rowid'.$i); @@ -84,12 +84,12 @@ if ($action == 'updateecheancier') { $echeance = new LoanSchedule($db); $echeance->fetch($id); $echeance->tms = dol_now(); - $echeance->amount_capital = $mens-$int; + $echeance->amount_capital = $mens - $int; $echeance->amount_insurance = $insurance; $echeance->amount_interest = $int; $echeance->fk_user_modif = $user->id; - $result= $echeance->update($user, 0); - if ($result<0) { + $result = $echeance->update($user, 0); + if ($result < 0) { setEventMessages(null, $echeance->errors, 'errors'); } $i++; @@ -99,7 +99,7 @@ if ($action == 'updateecheancier') { $echeance = new LoanSchedule($db); $echeance->fetchAll($object->id); -$var = ! $var; +$var = !$var; ?> @@ -115,7 +115,7 @@ $(document).ready(function() { $.ajax({ dataType: 'json', url: 'calcmens.php', - data: { echeance: echeance, mens: mens, capital:capital, rate:rate/100;?> , nbterm : nbterm;?>}, + data: { echeance: echeance, mens: mens, capital:capital, rate:rate / 100; ?> , nbterm : nbterm; ?>}, success: function(data) { $.each(data, function(index, element) { var idcap_res='#hi_capital'+index; @@ -137,19 +137,19 @@ $(document).ready(function() { '; -print ''; -print ''; -if(count($echeance->lines)>0) +print ''; +print ''; +print ''; +if (count($echeance->lines) > 0) { print ''; -}else{ +} else { print ''; } -print '
    '.$langs->trans("DateDue").''.$langs->trans("LoanCapital").'
    '; +print '
    '; print ''; $colspan = 6; -if (count($echeance->lines)>0) $colspan++; +if (count($echeance->lines) > 0) $colspan++; print ''; @@ -165,61 +165,61 @@ print ''; -if (count($echeance->lines)>0) print ''; +if (count($echeance->lines) > 0) print ''; print ''."\n"; -if ($object->nbterm > 0 && count($echeance->lines)==0) +if ($object->nbterm > 0 && count($echeance->lines) == 0) { - $i=1; + $i = 1; $capital = $object->capital; - $insurance = $object->insurance_amount/$object->nbterm; + $insurance = $object->insurance_amount / $object->nbterm; $insurance = price2num($insurance, 'MT'); $regulInsurance = price2num($object->insurance_amount - ($insurance * $object->nbterm)); - while($i <$object->nbterm+1) + while ($i < $object->nbterm + 1) { - $mens = price2num($echeance->calcMonthlyPayments($capital, $object->rate/100, $object->nbterm-$i+1), 'MT'); - $int = ($capital*($object->rate/12))/100; + $mens = price2num($echeance->calcMonthlyPayments($capital, $object->rate / 100, $object->nbterm - $i + 1), 'MT'); + $int = ($capital * ($object->rate / 12)) / 100; $int = price2num($int, 'MT'); - $insu = ($insurance+(($i == 1) ? $regulInsurance : 0)); - $cap_rest = price2num($capital - ($mens-$int), 'MT'); + $insu = ($insurance + (($i == 1) ? $regulInsurance : 0)); + $cap_rest = price2num($capital - ($mens - $int), 'MT'); print ''; - print ''; - print ''; - print ''; - print ''; + print ''; + print ''; + print ''; + print ''; print ''; - print ''; + print ''; print ''."\n"; $i++; $capital = $cap_rest; } } -elseif(count($echeance->lines)>0) +elseif (count($echeance->lines) > 0) { - $i=1; + $i = 1; $capital = $object->capital; - $insurance = $object->insurance_amount/$object->nbterm; + $insurance = $object->insurance_amount / $object->nbterm; $insurance = price2num($insurance, 'MT'); $regulInsurance = price2num($object->insurance_amount - ($insurance * $object->nbterm)); $printed = false; - foreach ($echeance->lines as $line){ - $mens = $line->amount_capital+$line->amount_interest; + foreach ($echeance->lines as $line) { + $mens = $line->amount_capital + $line->amount_interest; $int = $line->amount_interest; - $insu = ($insurance+(($i == 1) ? $regulInsurance : 0)); - $cap_rest = price2num($capital - ($mens-$int), 'MT'); + $insu = ($insurance + (($i == 1) ? $regulInsurance : 0)); + $cap_rest = price2num($capital - ($mens - $int), 'MT'); print ''; - print ''; - print ''; - print ''; - print ''; - if($line->datep > dol_now() && empty($line->fk_bank)){ + print ''; + print ''; + print ''; + print ''; + if ($line->datep > dol_now() && empty($line->fk_bank)) { print ''; - }else{ - print ''; + } else { + print ''; } - print ''; + print ''; print '
    '; print $langs->trans("FinancialCommitment"); print ''.$langs->trans("CapitalRemain"); print ' ('.price2num($object->capital).')'; print ''; print ''.$langs->trans('DoPayment').''.$langs->trans('DoPayment').'
    ' . $i .'' . dol_print_date(dol_time_plus_duree($object->datestart, $i-1, 'm'), 'day') . ''.price($insurance+(($i == 1) ? $regulInsurance : 0), 0, '', 1).' €'.price($int, 0, '', 1).' €'.$i.''.dol_print_date(dol_time_plus_duree($object->datestart, $i - 1, 'm'), 'day').''.price($insurance + (($i == 1) ? $regulInsurance : 0), 0, '', 1).' €'.price($int, 0, '', 1).' € €'.price($cap_rest).' €'.price($cap_rest).' €
    ' . $i .'' . dol_print_date($line->datep, 'day') . ''.price($insu, 0, '', 1).' €'.price($int, 0, '', 1).' €'.$i.''.dol_print_date($line->datep, 'day').''.price($insu, 0, '', 1).' €'.price($int, 0, '', 1).' € €' . price($mens) . ' €'.price($mens).' €'.price($cap_rest).' €'.price($cap_rest).' €'; if (!empty($line->fk_bank)) print $langs->trans('Paid'); elseif (!$printed) @@ -237,7 +237,7 @@ elseif(count($echeance->lines)>0) print '
    '; print '
    '; print '
    '; -if (count($echeance->lines)==0) $label = $langs->trans("Create"); +if (count($echeance->lines) == 0) $label = $langs->trans("Create"); else $label = $langs->trans("Save"); print '
    '; print ''; diff --git a/htdocs/main.inc.php b/htdocs/main.inc.php index 858f73afa05..3e623433db8 100644 --- a/htdocs/main.inc.php +++ b/htdocs/main.inc.php @@ -35,11 +35,11 @@ //@ini_set('memory_limit', '128M'); // This may be useless if memory is hard limited by your PHP // For optional tuning. Enabled if environment variable MAIN_SHOW_TUNING_INFO is defined. -$micro_start_time=0; -if (! empty($_SERVER['MAIN_SHOW_TUNING_INFO'])) +$micro_start_time = 0; +if (!empty($_SERVER['MAIN_SHOW_TUNING_INFO'])) { list($usec, $sec) = explode(" ", microtime()); - $micro_start_time=((float) $usec + (float) $sec); + $micro_start_time = ((float) $usec + (float) $sec); // Add Xdebug code coverage //define('XDEBUGCOVERAGE',1); if (defined('XDEBUGCOVERAGE')) { @@ -65,8 +65,8 @@ function testSqlAndScriptInject($val, $type) $inj += preg_match('/insert\s+into/i', $val); $inj += preg_match('/select\s+from/i', $val); $inj += preg_match('/into\s+(outfile|dumpfile)/i', $val); - $inj += preg_match('/user\s*\(/i', $val); // avoid to use function user() that return current database login - $inj += preg_match('/information_schema/i', $val); // avoid to use request that read information_schema database + $inj += preg_match('/user\s*\(/i', $val); // avoid to use function user() that return current database login + $inj += preg_match('/information_schema/i', $val); // avoid to use request that read information_schema database } if ($type == 3) { @@ -147,34 +147,34 @@ function analyseVarsForSqlAndScriptsInjection(&$var, $type) // Check consistency of NOREQUIREXXX DEFINES -if ((defined('NOREQUIREDB') || defined('NOREQUIRETRAN')) && ! defined('NOREQUIREMENU')) +if ((defined('NOREQUIREDB') || defined('NOREQUIRETRAN')) && !defined('NOREQUIREMENU')) { print 'If define NOREQUIREDB or NOREQUIRETRAN are set, you must also set NOREQUIREMENU or not set them'; exit; } // Sanity check on URL -if (! empty($_SERVER["PHP_SELF"])) +if (!empty($_SERVER["PHP_SELF"])) { - $morevaltochecklikepost=array($_SERVER["PHP_SELF"]); + $morevaltochecklikepost = array($_SERVER["PHP_SELF"]); analyseVarsForSqlAndScriptsInjection($morevaltochecklikepost, 2); } // Sanity check on GET parameters -if (! defined('NOSCANGETFORINJECTION') && ! empty($_SERVER["QUERY_STRING"])) +if (!defined('NOSCANGETFORINJECTION') && !empty($_SERVER["QUERY_STRING"])) { - $morevaltochecklikeget=array($_SERVER["QUERY_STRING"]); + $morevaltochecklikeget = array($_SERVER["QUERY_STRING"]); analyseVarsForSqlAndScriptsInjection($morevaltochecklikeget, 1); } // Sanity check on POST -if (! defined('NOSCANPOSTFORINJECTION')) +if (!defined('NOSCANPOSTFORINJECTION')) { analyseVarsForSqlAndScriptsInjection($_POST, 0); } // This is to make Dolibarr working with Plesk -if (! empty($_SERVER['DOCUMENT_ROOT']) && substr($_SERVER['DOCUMENT_ROOT'], -6) !== 'htdocs') +if (!empty($_SERVER['DOCUMENT_ROOT']) && substr($_SERVER['DOCUMENT_ROOT'], -6) !== 'htdocs') { - set_include_path($_SERVER['DOCUMENT_ROOT'] . '/htdocs'); + set_include_path($_SERVER['DOCUMENT_ROOT'].'/htdocs'); } // Include the conf.php and functions.lib.php. This defined the constants like DOL_DOCUMENT_ROOT, DOL_DATA_ROOT, DOL_URL_ROOT... @@ -183,37 +183,37 @@ require_once 'filefunc.inc.php'; // If there is a POST parameter to tell to save automatically some POST parameters into cookies, we do it. // This is used for example by form of boxes to save personalization of some options. // DOL_AUTOSET_COOKIE=cookiename:val1,val2 and cookiename_val1=aaa cookiename_val2=bbb will set cookie_name with value json_encode(array('val1'=> , )) -if (! empty($_POST["DOL_AUTOSET_COOKIE"])) +if (!empty($_POST["DOL_AUTOSET_COOKIE"])) { - $tmpautoset=explode(':', $_POST["DOL_AUTOSET_COOKIE"], 2); - $tmplist=explode(',', $tmpautoset[1]); - $cookiearrayvalue=array(); + $tmpautoset = explode(':', $_POST["DOL_AUTOSET_COOKIE"], 2); + $tmplist = explode(',', $tmpautoset[1]); + $cookiearrayvalue = array(); foreach ($tmplist as $tmpkey) { - $postkey=$tmpautoset[0].'_'.$tmpkey; + $postkey = $tmpautoset[0].'_'.$tmpkey; //var_dump('tmpkey='.$tmpkey.' postkey='.$postkey.' value='.$_POST[$postkey]); - if (! empty($_POST[$postkey])) $cookiearrayvalue[$tmpkey]=$_POST[$postkey]; + if (!empty($_POST[$postkey])) $cookiearrayvalue[$tmpkey] = $_POST[$postkey]; } - $cookiename=$tmpautoset[0]; - $cookievalue=json_encode($cookiearrayvalue); + $cookiename = $tmpautoset[0]; + $cookievalue = json_encode($cookiearrayvalue); //var_dump('setcookie cookiename='.$cookiename.' cookievalue='.$cookievalue); - setcookie($cookiename, empty($cookievalue)?'':$cookievalue, empty($cookievalue)?0:(time()+(86400*354)), '/', null, false, true); // keep cookie 1 year and add tag httponly + setcookie($cookiename, empty($cookievalue) ? '' : $cookievalue, empty($cookievalue) ? 0 : (time() + (86400 * 354)), '/', null, false, true); // keep cookie 1 year and add tag httponly if (empty($cookievalue)) unset($_COOKIE[$cookiename]); } // Init session. Name of session is specific to Dolibarr instance. // Note: the function dol_getprefix may have been redefined to return a different key to manage another area to protect. -$prefix=dol_getprefix(''); +$prefix = dol_getprefix(''); -$sessionname='DOLSESSID_'.$prefix; -$sessiontimeout='DOLSESSTIMEOUT_'.$prefix; -if (! empty($_COOKIE[$sessiontimeout])) ini_set('session.gc_maxlifetime', $_COOKIE[$sessiontimeout]); +$sessionname = 'DOLSESSID_'.$prefix; +$sessiontimeout = 'DOLSESSTIMEOUT_'.$prefix; +if (!empty($_COOKIE[$sessiontimeout])) ini_set('session.gc_maxlifetime', $_COOKIE[$sessiontimeout]); session_name($sessionname); -session_set_cookie_params(0, '/', null, false, true); // Add tag httponly on session cookie (same as setting session.cookie_httponly into php.ini). Must be called before the session_start. +session_set_cookie_params(0, '/', null, false, true); // Add tag httponly on session cookie (same as setting session.cookie_httponly into php.ini). Must be called before the session_start. // This create lock, released when session_write_close() or end of page. // We need this lock as long as we read/write $_SESSION ['vars']. We can remove lock when finished. -if (! defined('NOSESSION')) +if (!defined('NOSESSION')) { session_start(); /*if (ini_get('register_globals')) // Deprecated in 5.3 and removed in 5.4. To solve bug in using $_SESSION @@ -232,7 +232,7 @@ require_once 'master.inc.php'; register_shutdown_function('dol_shutdown'); // Load debugbar -if (! empty($conf->debugbar->enabled)) +if (!empty($conf->debugbar->enabled)) { global $debugbar; include_once DOL_DOCUMENT_ROOT.'/debugbar/class/DebugBar.php'; @@ -294,20 +294,20 @@ if (! empty($conf->file->main_force_https) && (empty($_SERVER["HTTPS"]) || $_SER } } -if (! defined('NOLOGIN') && ! defined('NOIPCHECK') && ! empty($dolibarr_main_restrict_ip)) +if (!defined('NOLOGIN') && !defined('NOIPCHECK') && !empty($dolibarr_main_restrict_ip)) { - $listofip=explode(',', $dolibarr_main_restrict_ip); + $listofip = explode(',', $dolibarr_main_restrict_ip); $found = false; - foreach($listofip as $ip) + foreach ($listofip as $ip) { - $ip=trim($ip); + $ip = trim($ip); if ($ip == $_SERVER['REMOTE_ADDR']) { $found = true; break; } } - if (! $found) + if (!$found) { print 'Access refused by IP protection'; exit; @@ -315,25 +315,25 @@ if (! defined('NOLOGIN') && ! defined('NOIPCHECK') && ! empty($dolibarr_main_res } // Loading of additional presentation includes -if (! defined('NOREQUIREHTML')) require_once DOL_DOCUMENT_ROOT .'/core/class/html.form.class.php'; // Need 660ko memory (800ko in 2.2) -if (! defined('NOREQUIREAJAX') && $conf->use_javascript_ajax) require_once DOL_DOCUMENT_ROOT.'/core/lib/ajax.lib.php'; // Need 22ko memory +if (!defined('NOREQUIREHTML')) require_once DOL_DOCUMENT_ROOT.'/core/class/html.form.class.php'; // Need 660ko memory (800ko in 2.2) +if (!defined('NOREQUIREAJAX') && $conf->use_javascript_ajax) require_once DOL_DOCUMENT_ROOT.'/core/lib/ajax.lib.php'; // Need 22ko memory // If install or upgrade process not done or not completely finished, we call the install page. -if (! empty($conf->global->MAIN_NOT_INSTALLED) || ! empty($conf->global->MAIN_NOT_UPGRADED)) +if (!empty($conf->global->MAIN_NOT_INSTALLED) || !empty($conf->global->MAIN_NOT_UPGRADED)) { dol_syslog("main.inc: A previous install or upgrade was not complete. Redirect to install page.", LOG_WARNING); header("Location: ".DOL_URL_ROOT."/install/index.php"); exit; } // If an upgrade process is required, we call the install page. -if ((! empty($conf->global->MAIN_VERSION_LAST_UPGRADE) && ($conf->global->MAIN_VERSION_LAST_UPGRADE != DOL_VERSION)) -|| (empty($conf->global->MAIN_VERSION_LAST_UPGRADE) && ! empty($conf->global->MAIN_VERSION_LAST_INSTALL) && ($conf->global->MAIN_VERSION_LAST_INSTALL != DOL_VERSION))) +if ((!empty($conf->global->MAIN_VERSION_LAST_UPGRADE) && ($conf->global->MAIN_VERSION_LAST_UPGRADE != DOL_VERSION)) +|| (empty($conf->global->MAIN_VERSION_LAST_UPGRADE) && !empty($conf->global->MAIN_VERSION_LAST_INSTALL) && ($conf->global->MAIN_VERSION_LAST_INSTALL != DOL_VERSION))) { - $versiontocompare=empty($conf->global->MAIN_VERSION_LAST_UPGRADE)?$conf->global->MAIN_VERSION_LAST_INSTALL:$conf->global->MAIN_VERSION_LAST_UPGRADE; - require_once DOL_DOCUMENT_ROOT .'/core/lib/admin.lib.php'; - $dolibarrversionlastupgrade=preg_split('/[.-]/', $versiontocompare); - $dolibarrversionprogram=preg_split('/[.-]/', DOL_VERSION); - $rescomp=versioncompare($dolibarrversionprogram, $dolibarrversionlastupgrade); + $versiontocompare = empty($conf->global->MAIN_VERSION_LAST_UPGRADE) ? $conf->global->MAIN_VERSION_LAST_INSTALL : $conf->global->MAIN_VERSION_LAST_UPGRADE; + require_once DOL_DOCUMENT_ROOT.'/core/lib/admin.lib.php'; + $dolibarrversionlastupgrade = preg_split('/[.-]/', $versiontocompare); + $dolibarrversionprogram = preg_split('/[.-]/', DOL_VERSION); + $rescomp = versioncompare($dolibarrversionprogram, $dolibarrversionlastupgrade); if ($rescomp > 0) // Programs have a version higher than database. We did not add "&& $rescomp < 3" because we want upgrade process for build upgrades { dol_syslog("main.inc: database version ".$versiontocompare." is lower than programs version ".DOL_VERSION.". Redirect to install page.", LOG_WARNING); @@ -345,7 +345,7 @@ if ((! empty($conf->global->MAIN_VERSION_LAST_UPGRADE) && ($conf->global->MAIN_V //var_dump(GETPOST('token').' '.$_SESSION['token'].' - '.$_SESSION['newtoken'].' '.$_SERVER['SCRIPT_FILENAME']); // Creation of a token against CSRF vulnerabilities -if (! defined('NOTOKENRENEWAL')) +if (!defined('NOTOKENRENEWAL')) { // Rolling token at each call ($_SESSION['token'] contains token of previous page) if (isset($_SESSION['newtoken'])) $_SESSION['token'] = $_SESSION['newtoken']; @@ -408,11 +408,11 @@ if (! empty($_SESSION["disablemodules"])) // Set current modulepart $modulepart = explode("/", $_SERVER["PHP_SELF"]); -if(is_array($modulepart) && count($modulepart)>0) +if (is_array($modulepart) && count($modulepart) > 0) { - foreach($conf->modules as $module) + foreach ($conf->modules as $module) { - if(in_array($module, $modulepart)) + if (in_array($module, $modulepart)) { $conf->modulepart = $module; break; @@ -423,8 +423,8 @@ if(is_array($modulepart) && count($modulepart)>0) /* * Phase authentication / login */ -$login=''; -if (! defined('NOLOGIN')) +$login = ''; +if (!defined('NOLOGIN')) { // $authmode lists the different method of identification to be tested in order of preference. // Example: 'http', 'dolibarr', 'ldap', 'http,forceuser', '...' @@ -436,15 +436,15 @@ if (! defined('NOLOGIN')) else { // Authentication mode - if (empty($dolibarr_main_authentication)) $dolibarr_main_authentication='http,dolibarr'; + if (empty($dolibarr_main_authentication)) $dolibarr_main_authentication = 'http,dolibarr'; // Authentication mode: forceuser - if ($dolibarr_main_authentication == 'forceuser' && empty($dolibarr_auto_user)) $dolibarr_auto_user='auto'; + if ($dolibarr_main_authentication == 'forceuser' && empty($dolibarr_auto_user)) $dolibarr_auto_user = 'auto'; } // Set authmode - $authmode=explode(',', $dolibarr_main_authentication); + $authmode = explode(',', $dolibarr_main_authentication); // No authentication mode - if (! count($authmode)) + if (!count($authmode)) { $langs->load('main'); dol_print_error('', $langs->trans("ErrorConfigParameterNotDefined", 'dolibarr_main_authentication')); @@ -531,52 +531,52 @@ if (! defined('NOLOGIN')) $allowedmethodtopostusername = 2; if (defined('MAIN_AUTHENTICATION_POST_METHOD')) $allowedmethodtopostusername = constant('MAIN_AUTHENTICATION_POST_METHOD'); - $usertotest = (! empty($_COOKIE['login_dolibarr']) ? $_COOKIE['login_dolibarr'] : GETPOST("username", "alpha", $allowedmethodtopostusername)); - $passwordtotest = GETPOST('password', 'none', $allowedmethodtopostusername); - $entitytotest = (GETPOST('entity', 'int') ? GETPOST('entity', 'int') : (!empty($conf->entity) ? $conf->entity : 1)); + $usertotest = (!empty($_COOKIE['login_dolibarr']) ? $_COOKIE['login_dolibarr'] : GETPOST("username", "alpha", $allowedmethodtopostusername)); + $passwordtotest = GETPOST('password', 'none', $allowedmethodtopostusername); + $entitytotest = (GETPOST('entity', 'int') ? GETPOST('entity', 'int') : (!empty($conf->entity) ? $conf->entity : 1)); // Define if we received data to test the login. - $goontestloop=false; - if (isset($_SERVER["REMOTE_USER"]) && in_array('http', $authmode)) $goontestloop=true; - if ($dolibarr_main_authentication == 'forceuser' && ! empty($dolibarr_auto_user)) $goontestloop=true; - if (GETPOST("username", "alpha", $allowedmethodtopostusername) || ! empty($_COOKIE['login_dolibarr']) || GETPOST('openid_mode', 'alpha', 1)) $goontestloop=true; + $goontestloop = false; + if (isset($_SERVER["REMOTE_USER"]) && in_array('http', $authmode)) $goontestloop = true; + if ($dolibarr_main_authentication == 'forceuser' && !empty($dolibarr_auto_user)) $goontestloop = true; + if (GETPOST("username", "alpha", $allowedmethodtopostusername) || !empty($_COOKIE['login_dolibarr']) || GETPOST('openid_mode', 'alpha', 1)) $goontestloop = true; - if (! is_object($langs)) // This can occurs when calling page with NOREQUIRETRAN defined, however we need langs for error messages. + if (!is_object($langs)) // This can occurs when calling page with NOREQUIRETRAN defined, however we need langs for error messages. { include_once DOL_DOCUMENT_ROOT.'/core/class/translate.class.php'; - $langs=new Translate("", $conf); - $langcode=(GETPOST('lang', 'aZ09', 1)?GETPOST('lang', 'aZ09', 1):(empty($conf->global->MAIN_LANG_DEFAULT)?'auto':$conf->global->MAIN_LANG_DEFAULT)); - if (defined('MAIN_LANG_DEFAULT')) $langcode=constant('MAIN_LANG_DEFAULT'); + $langs = new Translate("", $conf); + $langcode = (GETPOST('lang', 'aZ09', 1) ?GETPOST('lang', 'aZ09', 1) : (empty($conf->global->MAIN_LANG_DEFAULT) ? 'auto' : $conf->global->MAIN_LANG_DEFAULT)); + if (defined('MAIN_LANG_DEFAULT')) $langcode = constant('MAIN_LANG_DEFAULT'); $langs->setDefaultLang($langcode); } // Validation of login/pass/entity // If ok, the variable login will be returned // If error, we will put error message in session under the name dol_loginmesg - if ($test && $goontestloop) + if ($test && $goontestloop && GETPOST('action', 'aZ09') == 'login') { $login = checkLoginPassEntity($usertotest, $passwordtotest, $entitytotest, $authmode); if ($login) { - $dol_authmode=$conf->authmode; // This properties is defined only when logged, to say what mode was successfully used - $dol_tz=$_POST["tz"]; - $dol_tz_string=$_POST["tz_string"]; - $dol_tz_string=preg_replace('/\s*\(.+\)$/', '', $dol_tz_string); - $dol_tz_string=preg_replace('/,/', '/', $dol_tz_string); - $dol_tz_string=preg_replace('/\s/', '_', $dol_tz_string); - $dol_dst=0; + $dol_authmode = $conf->authmode; // This properties is defined only when logged, to say what mode was successfully used + $dol_tz = $_POST["tz"]; + $dol_tz_string = $_POST["tz_string"]; + $dol_tz_string = preg_replace('/\s*\(.+\)$/', '', $dol_tz_string); + $dol_tz_string = preg_replace('/,/', '/', $dol_tz_string); + $dol_tz_string = preg_replace('/\s/', '_', $dol_tz_string); + $dol_dst = 0; if (isset($_POST["dst_first"]) && isset($_POST["dst_second"])) { include_once DOL_DOCUMENT_ROOT.'/core/lib/date.lib.php'; - $datenow=dol_now(); - $datefirst=dol_stringtotime($_POST["dst_first"]); - $datesecond=dol_stringtotime($_POST["dst_second"]); - if ($datenow >= $datefirst && $datenow < $datesecond) $dol_dst=1; + $datenow = dol_now(); + $datefirst = dol_stringtotime($_POST["dst_first"]); + $datesecond = dol_stringtotime($_POST["dst_second"]); + if ($datenow >= $datefirst && $datenow < $datesecond) $dol_dst = 1; } //print $datefirst.'-'.$datesecond.'-'.$datenow.'-'.$dol_tz.'-'.$dol_tzstring.'-'.$dol_dst; exit; } - if (! $login) + if (!$login) { dol_syslog('Bad password, connexion refused', LOG_DEBUG); // Load translation files required by page @@ -584,24 +584,24 @@ if (! defined('NOLOGIN')) // Bad password. No authmode has found a good password. // We set a generic message if not defined inside function checkLoginPassEntity or subfunctions - if (empty($_SESSION["dol_loginmesg"])) $_SESSION["dol_loginmesg"]=$langs->trans("ErrorBadLoginPassword"); + if (empty($_SESSION["dol_loginmesg"])) $_SESSION["dol_loginmesg"] = $langs->trans("ErrorBadLoginPassword"); // Call trigger for the "security events" log - $user->trigger_mesg=$langs->trans("ErrorBadLoginPassword").' - login='.GETPOST("username", "alpha", 2); + $user->trigger_mesg = $langs->trans("ErrorBadLoginPassword").' - login='.GETPOST("username", "alpha", 2); // Call of triggers include_once DOL_DOCUMENT_ROOT.'/core/class/interfaces.class.php'; - $interface=new Interfaces($db); - $result=$interface->run_triggers('USER_LOGIN_FAILED', $user, $user, $langs, $conf, GETPOST("username", "alpha", 2)); + $interface = new Interfaces($db); + $result = $interface->run_triggers('USER_LOGIN_FAILED', $user, $user, $langs, $conf, GETPOST("username", "alpha", 2)); if ($result < 0) { $error++; } // End Call of triggers // Hooks on failed login - $action=''; + $action = ''; $hookmanager->initHooks(array('login')); - $parameters=array('dol_authmode'=>$dol_authmode, 'dol_loginmesg'=>$_SESSION["dol_loginmesg"]); - $reshook=$hookmanager->executeHooks('afterLoginFailed', $parameters, $user, $action); // Note that $action and $object may have been modified by some hooks + $parameters = array('dol_authmode'=>$dol_authmode, 'dol_loginmesg'=>$_SESSION["dol_loginmesg"]); + $reshook = $hookmanager->executeHooks('afterLoginFailed', $parameters, $user, $action); // Note that $action and $object may have been modified by some hooks if ($reshook < 0) $error++; // Note: exit is done in next chapter @@ -612,7 +612,7 @@ if (! defined('NOLOGIN')) 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 - dol_syslog("--- Access to ".$_SERVER["PHP_SELF"]." showing the login form and exit"); + dol_syslog("--- Access to ".$_SERVER["PHP_SELF"]." - action=".GETPOST('action', 'aZ09').", showing the login form and exit"); if (defined('NOREDIRECTBYMAINTOLOGIN')) return 'ERROR_NOT_LOGGED'; else dol_loginfunction($langs, $conf, (! empty($mysoc)?$mysoc:'')); exit; @@ -729,10 +729,10 @@ if (! defined('NOLOGIN')) $hookmanager->initHooks(array('main')); // Code for search criteria persistence. - if (! empty($_GET['save_lastsearch_values'])) // We must use $_GET here + if (!empty($_GET['save_lastsearch_values'])) // We must use $_GET here { $relativepathstring = preg_replace('/\?.*$/', '', $_SERVER["HTTP_REFERER"]); - $relativepathstring = preg_replace('/^https?:\/\/[^\/]*/', '', $relativepathstring); // Get full path except host server + $relativepathstring = preg_replace('/^https?:\/\/[^\/]*/', '', $relativepathstring); // Get full path except host server // Clean $relativepathstring if (constant('DOL_URL_ROOT')) $relativepathstring = preg_replace('/^'.preg_quote(constant('DOL_URL_ROOT'), '/').'/', '', $relativepathstring); $relativepathstring = preg_replace('/^\//', '', $relativepathstring); @@ -772,30 +772,30 @@ if (! defined('NOLOGIN')) // Is it a new session that has started ? // If we are here, this means authentication was successfull. - if (! isset($_SESSION["dol_login"])) + if (!isset($_SESSION["dol_login"])) { // New session for this login has started. - $error=0; + $error = 0; // Store value into session (values always stored) - $_SESSION["dol_login"]=$user->login; - $_SESSION["dol_authmode"]=isset($dol_authmode)?$dol_authmode:''; - $_SESSION["dol_tz"]=isset($dol_tz)?$dol_tz:''; - $_SESSION["dol_tz_string"]=isset($dol_tz_string)?$dol_tz_string:''; - $_SESSION["dol_dst"]=isset($dol_dst)?$dol_dst:''; - $_SESSION["dol_dst_observed"]=isset($dol_dst_observed)?$dol_dst_observed:''; - $_SESSION["dol_dst_first"]=isset($dol_dst_first)?$dol_dst_first:''; - $_SESSION["dol_dst_second"]=isset($dol_dst_second)?$dol_dst_second:''; - $_SESSION["dol_screenwidth"]=isset($dol_screenwidth)?$dol_screenwidth:''; - $_SESSION["dol_screenheight"]=isset($dol_screenheight)?$dol_screenheight:''; - $_SESSION["dol_company"]=$conf->global->MAIN_INFO_SOCIETE_NOM; - $_SESSION["dol_entity"]=$conf->entity; + $_SESSION["dol_login"] = $user->login; + $_SESSION["dol_authmode"] = isset($dol_authmode) ? $dol_authmode : ''; + $_SESSION["dol_tz"] = isset($dol_tz) ? $dol_tz : ''; + $_SESSION["dol_tz_string"] = isset($dol_tz_string) ? $dol_tz_string : ''; + $_SESSION["dol_dst"] = isset($dol_dst) ? $dol_dst : ''; + $_SESSION["dol_dst_observed"] = isset($dol_dst_observed) ? $dol_dst_observed : ''; + $_SESSION["dol_dst_first"] = isset($dol_dst_first) ? $dol_dst_first : ''; + $_SESSION["dol_dst_second"] = isset($dol_dst_second) ? $dol_dst_second : ''; + $_SESSION["dol_screenwidth"] = isset($dol_screenwidth) ? $dol_screenwidth : ''; + $_SESSION["dol_screenheight"] = isset($dol_screenheight) ? $dol_screenheight : ''; + $_SESSION["dol_company"] = $conf->global->MAIN_INFO_SOCIETE_NOM; + $_SESSION["dol_entity"] = $conf->entity; // Store value into session (values stored only if defined) - if (! empty($dol_hide_topmenu)) $_SESSION['dol_hide_topmenu']=$dol_hide_topmenu; - if (! empty($dol_hide_leftmenu)) $_SESSION['dol_hide_leftmenu']=$dol_hide_leftmenu; - if (! empty($dol_optimize_smallscreen)) $_SESSION['dol_optimize_smallscreen']=$dol_optimize_smallscreen; - if (! empty($dol_no_mouse_hover)) $_SESSION['dol_no_mouse_hover']=$dol_no_mouse_hover; - if (! empty($dol_use_jmobile)) $_SESSION['dol_use_jmobile']=$dol_use_jmobile; + if (!empty($dol_hide_topmenu)) $_SESSION['dol_hide_topmenu'] = $dol_hide_topmenu; + if (!empty($dol_hide_leftmenu)) $_SESSION['dol_hide_leftmenu'] = $dol_hide_leftmenu; + if (!empty($dol_optimize_smallscreen)) $_SESSION['dol_optimize_smallscreen'] = $dol_optimize_smallscreen; + if (!empty($dol_no_mouse_hover)) $_SESSION['dol_no_mouse_hover'] = $dol_no_mouse_hover; + if (!empty($dol_use_jmobile)) $_SESSION['dol_use_jmobile'] = $dol_use_jmobile; dol_syslog("This is a new started user session. _SESSION['dol_login']=".$_SESSION["dol_login"]." Session id=".session_id()); @@ -808,19 +808,19 @@ if (! defined('NOLOGIN')) // Call triggers for the "security events" log $user->trigger_mesg = $loginfo; // Call triggers - include_once DOL_DOCUMENT_ROOT . '/core/class/interfaces.class.php'; - $interface=new Interfaces($db); - $result=$interface->run_triggers('USER_LOGIN', $user, $user, $langs, $conf); + include_once DOL_DOCUMENT_ROOT.'/core/class/interfaces.class.php'; + $interface = new Interfaces($db); + $result = $interface->run_triggers('USER_LOGIN', $user, $user, $langs, $conf); if ($result < 0) { $error++; } // End call triggers // Hooks on successfull login - $action=''; + $action = ''; $hookmanager->initHooks(array('login')); - $parameters=array('dol_authmode'=>$dol_authmode, 'dol_loginfo'=>$loginfo); - $reshook=$hookmanager->executeHooks('afterLogin', $parameters, $user, $action); // Note that $action and $object may have been modified by some hooks + $parameters = array('dol_authmode'=>$dol_authmode, 'dol_loginfo'=>$loginfo); + $reshook = $hookmanager->executeHooks('afterLogin', $parameters, $user, $action); // Note that $action and $object may have been modified by some hooks if ($reshook < 0) $error++; if ($error) @@ -836,10 +836,10 @@ if (! defined('NOLOGIN')) } // Change landing page if defined. - $landingpage=(empty($user->conf->MAIN_LANDING_PAGE)?(empty($conf->global->MAIN_LANDING_PAGE)?'':$conf->global->MAIN_LANDING_PAGE):$user->conf->MAIN_LANDING_PAGE); - if (! empty($landingpage)) // Example: /index.php + $landingpage = (empty($user->conf->MAIN_LANDING_PAGE) ? (empty($conf->global->MAIN_LANDING_PAGE) ? '' : $conf->global->MAIN_LANDING_PAGE) : $user->conf->MAIN_LANDING_PAGE); + if (!empty($landingpage)) // Example: /index.php { - $newpath=dol_buildpath($landingpage, 1); + $newpath = dol_buildpath($landingpage, 1); if ($_SERVER["PHP_SELF"] != $newpath) // not already on landing page (avoid infinite loop) { header('Location: '.$newpath); @@ -852,12 +852,12 @@ if (! defined('NOLOGIN')) // If user admin, we force the rights-based modules if ($user->admin) { - $user->rights->user->user->lire=1; - $user->rights->user->user->creer=1; - $user->rights->user->user->password=1; - $user->rights->user->user->supprimer=1; - $user->rights->user->self->creer=1; - $user->rights->user->self->password=1; + $user->rights->user->user->lire = 1; + $user->rights->user->user->creer = 1; + $user->rights->user->user->password = 1; + $user->rights->user->user->supprimer = 1; + $user->rights->user->self->creer = 1; + $user->rights->user->self->password = 1; } /* @@ -865,13 +865,13 @@ if (! defined('NOLOGIN')) */ // Set liste_limit - if (isset($user->conf->MAIN_SIZE_LISTE_LIMIT)) $conf->liste_limit = $user->conf->MAIN_SIZE_LISTE_LIMIT; // Can be 0 - if (isset($user->conf->PRODUIT_LIMIT_SIZE)) $conf->product->limit_size = $user->conf->PRODUIT_LIMIT_SIZE; // Can be 0 + if (isset($user->conf->MAIN_SIZE_LISTE_LIMIT)) $conf->liste_limit = $user->conf->MAIN_SIZE_LISTE_LIMIT; // Can be 0 + if (isset($user->conf->PRODUIT_LIMIT_SIZE)) $conf->product->limit_size = $user->conf->PRODUIT_LIMIT_SIZE; // Can be 0 // Replace conf->css by personalized value if theme not forced - if (empty($conf->global->MAIN_FORCETHEME) && ! empty($user->conf->MAIN_THEME)) + if (empty($conf->global->MAIN_FORCETHEME) && !empty($user->conf->MAIN_THEME)) { - $conf->theme=$user->conf->MAIN_THEME; + $conf->theme = $user->conf->MAIN_THEME; $conf->css = "/theme/".$conf->theme."/style.css.php"; } } @@ -946,11 +946,11 @@ if (! defined('NOREQUIRETRAN')) } } -if (! defined('NOLOGIN')) +if (!defined('NOLOGIN')) { // If the login is not recovered, it is identified with an account that does not exist. // Hacking attempt? - if (! $user->login) accessforbidden(); + if (!$user->login) accessforbidden(); // Check if user is active if ($user->statut < 1) @@ -972,22 +972,22 @@ dol_syslog("--- Access to ".$_SERVER["PHP_SELF"].' - action='.GETPOST('action', //dol_syslog("Access to ".$_SERVER["PHP_SELF"].' GET='.join(',',array_keys($_GET)).'->'.join(',',$_GET).' POST:'.join(',',array_keys($_POST)).'->'.join(',',$_POST)); // Load main languages files -if (! defined('NOREQUIRETRAN')) +if (!defined('NOREQUIRETRAN')) { // Load translation files required by page $langs->loadLangs(array('main', 'dict')); } // Define some constants used for style of arrays -$bc=array(0=>'class="impair"',1=>'class="pair"'); -$bcdd=array(0=>'class="drag drop oddeven"',1=>'class="drag drop oddeven"'); -$bcnd=array(0=>'class="nodrag nodrop nohover"',1=>'class="nodrag nodrop nohoverpair"'); // Used for tr to add new lines -$bctag=array(0=>'class="impair tagtr"',1=>'class="pair tagtr"'); +$bc = array(0=>'class="impair"', 1=>'class="pair"'); +$bcdd = array(0=>'class="drag drop oddeven"', 1=>'class="drag drop oddeven"'); +$bcnd = array(0=>'class="nodrag nodrop nohover"', 1=>'class="nodrag nodrop nohoverpair"'); // Used for tr to add new lines +$bctag = array(0=>'class="impair tagtr"', 1=>'class="pair tagtr"'); // Define messages variables -$mesg=''; $warning=''; $error=0; +$mesg = ''; $warning = ''; $error = 0; // deprecated, see setEventMessages() and dol_htmloutput_events() -$mesgs=array(); $warnings=array(); $errors=array(); +$mesgs = array(); $warnings = array(); $errors = array(); // Constants used to defined number of lines in textarea if (empty($conf->browser->firefox)) @@ -1056,7 +1056,7 @@ if (! defined('NOREQUIREMENU')) // Functions -if (! function_exists("llxHeader")) +if (!function_exists("llxHeader")) { /** * Show HTML header HTML + BODY + Top menu + left menu + DIV @@ -1105,7 +1105,7 @@ if (! function_exists("llxHeader")) if (empty($conf->dol_hide_leftmenu)) { - left_menu('', $help_url, '', '', 1, $title, 1); // $menumanager is retreived with a global $menumanager inside this function + left_menu('', $help_url, '', '', 1, $title, 1); // $menumanager is retreived with a global $menumanager inside this function } // main area @@ -1320,20 +1320,20 @@ function top_htmlhead($head, $title = '', $disablejs = 0, $disablehead = 0, $arr //print 'themepath='.$themepath.' themeparam='.$themeparam;exit; print ''."\n"; - if (! empty($conf->global->MAIN_FIX_FLASH_ON_CHROME)) print ''."\n".''."\n"; + if (!empty($conf->global->MAIN_FIX_FLASH_ON_CHROME)) print ''."\n".''."\n"; // CSS forced by modules (relative url starting with /) - if (! empty($conf->modules_parts['css'])) + if (!empty($conf->modules_parts['css'])) { - $arraycss=(array) $conf->modules_parts['css']; - foreach($arraycss as $modcss => $filescss) + $arraycss = (array) $conf->modules_parts['css']; + foreach ($arraycss as $modcss => $filescss) { - $filescss=(array) $filescss; // To be sure filecss is an array - foreach($filescss as $cssfile) + $filescss = (array) $filescss; // To be sure filecss is an array + foreach ($filescss as $cssfile) { if (empty($cssfile)) dol_syslog("Warning: module ".$modcss." declared a css path file into its descriptor that is empty.", LOG_WARNING); // cssfile is a relative path - print ''."\n".''."\n"; @@ -1343,15 +1343,15 @@ function top_htmlhead($head, $title = '', $disablejs = 0, $disablehead = 0, $arr // CSS forced by page in top_htmlhead call (relative url starting with /) if (is_array($arrayofcss)) { - foreach($arrayofcss as $cssfile) + foreach ($arrayofcss as $cssfile) { if (preg_match('/^http/i', $cssfile)) { - $urltofile=$cssfile; + $urltofile = $cssfile; } else { - $urltofile=dol_buildpath($cssfile, 1); + $urltofile = dol_buildpath($cssfile, 1); } print ''."\n".'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 - print $hookmanager->resPrint; // Replace Title to show + $parameters = array(); + $result = $hookmanager->executeHooks('addHtmlHeader', $parameters); // Note that $action and $object may have been modified by some hooks + print $hookmanager->resPrint; // Replace Title to show print "\n\n"; } - $conf->headerdone=1; // To tell header was output + $conf->headerdone = 1; // To tell header was output } @@ -1547,15 +1547,15 @@ function top_menu($head, $title = '', $target = '', $disablejs = 0, $disablehead { global $user, $conf, $langs, $db; global $dolibarr_main_authentication, $dolibarr_main_demo; - global $hookmanager,$menumanager; + global $hookmanager, $menumanager; - $searchform=''; - $bookmarks=''; + $searchform = ''; + $bookmarks = ''; // Instantiate hooks of thirdparty module $hookmanager->initHooks(array('toprightmenu')); - $toprightmenu=''; + $toprightmenu = ''; // For backward compatibility with old modules if (empty($conf->headerdone)) @@ -1567,48 +1567,48 @@ function top_menu($head, $title = '', $target = '', $disablejs = 0, $disablehead /* * Top menu */ - if ((empty($conf->dol_hide_topmenu) || GETPOST('dol_invisible_topmenu', 'int')) && (! defined('NOREQUIREMENU') || ! constant('NOREQUIREMENU'))) + if ((empty($conf->dol_hide_topmenu) || GETPOST('dol_invisible_topmenu', 'int')) && (!defined('NOREQUIREMENU') || !constant('NOREQUIREMENU'))) { print "\n".''."\n"; - print '
    '; // dol_invisible_topmenu differs from dol_hide_topmenu: dol_invisible_topmenu means we output menu but we make it invisible. + print '
    '; // dol_invisible_topmenu differs from dol_hide_topmenu: dol_invisible_topmenu means we output menu but we make it invisible. // Show menu entries - print '
    '."\n"; - $menumanager->atarget=$target; - $menumanager->showmenu('top', array('searchform'=>$searchform, 'bookmarks'=>$bookmarks)); // This contains a \n + print '
    '."\n"; + $menumanager->atarget = $target; + $menumanager->showmenu('top', array('searchform'=>$searchform, 'bookmarks'=>$bookmarks)); // This contains a \n print "
    \n"; // Define link to login card - $appli=constant('DOL_APPLICATION_TITLE'); - if (! empty($conf->global->MAIN_APPLICATION_TITLE)) + $appli = constant('DOL_APPLICATION_TITLE'); + if (!empty($conf->global->MAIN_APPLICATION_TITLE)) { - $appli=$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 + 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; } - 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=''; + $logouttext = ''; if (empty($conf->global->MAIN_OPTIMIZEFORTEXTBROWSER)) { //$logouthtmltext=$appli.'
    '; if ($_SESSION["dol_authmode"] != 'forceuser' && $_SESSION["dol_authmode"] != 'http') { - $logouthtmltext.=$langs->trans("Logout").'
    '; + $logouthtmltext .= $langs->trans("Logout").'
    '; - $logouttext .=''; - $logouttext .=img_picto($langs->trans('Logout'), 'sign-out', '', false, 0, 0, '', 'atoplogin'); - $logouttext .=''; + $logouttext .= ''; + $logouttext .= img_picto($langs->trans('Logout'), 'sign-out', '', false, 0, 0, '', 'atoplogin'); + $logouttext .= ''; } else { - $logouthtmltext.=$langs->trans("NoLogoutProcessWithAuthMode", $_SESSION["dol_authmode"]); + $logouthtmltext .= $langs->trans("NoLogoutProcessWithAuthMode", $_SESSION["dol_authmode"]); $logouttext .= img_picto($langs->trans('Logout'), 'sign-out', '', false, 0, 0, '', 'atoplogin opacitymedium'); } } @@ -1740,7 +1740,7 @@ 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 '
    '; } @@ -2200,27 +2200,27 @@ function left_menu($menu_array_before, $helppagename = '', $notused = '', $menu_ print '
    '."\n"; // Version - if (! empty($conf->global->MAIN_SHOW_VERSION)) // Version is already on help picto and on login page. + if (!empty($conf->global->MAIN_SHOW_VERSION)) // Version is already on help picto and on login page. { - $doliurl='https://www.dolibarr.org'; + $doliurl = 'https://www.dolibarr.org'; //local communities - if (preg_match('/fr/i', $langs->defaultlang)) $doliurl='https://www.dolibarr.fr'; - if (preg_match('/es/i', $langs->defaultlang)) $doliurl='https://www.dolibarr.es'; - if (preg_match('/de/i', $langs->defaultlang)) $doliurl='https://www.dolibarr.de'; - if (preg_match('/it/i', $langs->defaultlang)) $doliurl='https://www.dolibarr.it'; - if (preg_match('/gr/i', $langs->defaultlang)) $doliurl='https://www.dolibarr.gr'; + if (preg_match('/fr/i', $langs->defaultlang)) $doliurl = 'https://www.dolibarr.fr'; + if (preg_match('/es/i', $langs->defaultlang)) $doliurl = 'https://www.dolibarr.es'; + if (preg_match('/de/i', $langs->defaultlang)) $doliurl = 'https://www.dolibarr.de'; + if (preg_match('/it/i', $langs->defaultlang)) $doliurl = 'https://www.dolibarr.it'; + if (preg_match('/gr/i', $langs->defaultlang)) $doliurl = 'https://www.dolibarr.gr'; - $appli=constant('DOL_APPLICATION_TITLE'); - if (! empty($conf->global->MAIN_APPLICATION_TITLE)) + $appli = constant('DOL_APPLICATION_TITLE'); + if (!empty($conf->global->MAIN_APPLICATION_TITLE)) { - $appli=$conf->global->MAIN_APPLICATION_TITLE; $doliurl=''; + $appli = $conf->global->MAIN_APPLICATION_TITLE; $doliurl = ''; 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 + 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; } - else $appli.=" ".DOL_VERSION; + else $appli .= " ".DOL_VERSION; print '
    '; // End div id="side-nav" div id="id-left" + print '
    '; // End div id="side-nav" div id="id-left" } print "\n"; @@ -2323,7 +2323,7 @@ function main_area($title = '') print ''."\n".'
    '."\n"; - if (! empty($conf->global->MAIN_ONLY_LOGIN_ALLOWED)) print info_admin($langs->trans("WarningYouAreInMaintenanceMode", $conf->global->MAIN_ONLY_LOGIN_ALLOWED)); + if (!empty($conf->global->MAIN_ONLY_LOGIN_ALLOWED)) print info_admin($langs->trans("WarningYouAreInMaintenanceMode", $conf->global->MAIN_ONLY_LOGIN_ALLOWED)); } @@ -2336,38 +2336,38 @@ function main_area($title = '') */ function getHelpParamFor($helppagename, $langs) { - $helpbaseurl=''; - $helppage=''; - $mode=''; + $helpbaseurl = ''; + $helppage = ''; + $mode = ''; if (preg_match('/^http/i', $helppagename)) { // If complete URL - $helpbaseurl='%s'; - $helppage=$helppagename; - $mode='local'; + $helpbaseurl = '%s'; + $helppage = $helppagename; + $mode = 'local'; } else { // If WIKI URL if (preg_match('/^es/i', $langs->defaultlang)) { - $helpbaseurl='http://wiki.dolibarr.org/index.php/%s'; - if (preg_match('/ES:([^|]+)/i', $helppagename, $reg)) $helppage=$reg[1]; + $helpbaseurl = 'http://wiki.dolibarr.org/index.php/%s'; + if (preg_match('/ES:([^|]+)/i', $helppagename, $reg)) $helppage = $reg[1]; } if (preg_match('/^fr/i', $langs->defaultlang)) { - $helpbaseurl='http://wiki.dolibarr.org/index.php/%s'; - if (preg_match('/FR:([^|]+)/i', $helppagename, $reg)) $helppage=$reg[1]; + $helpbaseurl = 'http://wiki.dolibarr.org/index.php/%s'; + if (preg_match('/FR:([^|]+)/i', $helppagename, $reg)) $helppage = $reg[1]; } if (empty($helppage)) // If help page not already found { - $helpbaseurl='http://wiki.dolibarr.org/index.php/%s'; - if (preg_match('/EN:([^|]+)/i', $helppagename, $reg)) $helppage=$reg[1]; + $helpbaseurl = 'http://wiki.dolibarr.org/index.php/%s'; + if (preg_match('/EN:([^|]+)/i', $helppagename, $reg)) $helppage = $reg[1]; } - $mode='wiki'; + $mode = 'wiki'; } - return array('helpbaseurl'=>$helpbaseurl,'helppage'=>$helppage,'mode'=>$mode); + return array('helpbaseurl'=>$helpbaseurl, 'helppage'=>$helppage, 'mode'=>$mode); } @@ -2428,29 +2428,29 @@ if (! function_exists("llxFooter")) */ function llxFooter($comment = '', $zone = 'private', $disabledoutputofmessages = 0) { - global $conf, $db, $langs, $user, $object; + global $conf, $db, $langs, $user, $mysoc, $object; global $delayedhtmlcontent; global $contextpage, $page, $limit; - $ext='layout='.$conf->browser->layout.'&version='.urlencode(DOL_VERSION); + $ext = 'layout='.$conf->browser->layout.'&version='.urlencode(DOL_VERSION); // Global html output events ($mesgs, $errors, $warnings) dol_htmloutput_events($disabledoutputofmessages); // Code for search criteria persistence. // $user->lastsearch_values was set by the GETPOST when form field search_xxx exists - if (is_object($user) && ! empty($user->lastsearch_values_tmp) && is_array($user->lastsearch_values_tmp)) + if (is_object($user) && !empty($user->lastsearch_values_tmp) && is_array($user->lastsearch_values_tmp)) { // Clean and save data - foreach($user->lastsearch_values_tmp as $key => $val) + foreach ($user->lastsearch_values_tmp as $key => $val) { - unset($_SESSION['lastsearch_values_tmp_'.$key]); // Clean array to rebuild it just after + unset($_SESSION['lastsearch_values_tmp_'.$key]); // Clean array to rebuild it just after if (count($val) && empty($_POST['button_removefilter'])) // If there is search criteria to save and we did not click on 'Clear filter' button { if (empty($val['sortfield'])) unset($val['sortfield']); if (empty($val['sortorder'])) unset($val['sortorder']); dol_syslog('Save lastsearch_values_tmp_'.$key.'='.json_encode($val, 0)." (systematic recording of last search criterias)"); - $_SESSION['lastsearch_values_tmp_'.$key]=json_encode($val); + $_SESSION['lastsearch_values_tmp_'.$key] = json_encode($val); unset($_SESSION['lastsearch_values_'.$key]); } } @@ -2478,7 +2478,7 @@ if (! function_exists("llxFooter")) } // Core error message - if (! empty($conf->global->MAIN_CORE_ERROR)) + if (!empty($conf->global->MAIN_CORE_ERROR)) { // Ajax version if ($conf->use_javascript_ajax) @@ -2502,23 +2502,23 @@ if (! function_exists("llxFooter")) if (empty($conf->dol_hide_leftmenu)) print '
    '."\n"; // End div id-right - if (empty($conf->dol_hide_leftmenu) && empty($conf->dol_use_jmobile)) print '
    '."\n"; // End div container + if (empty($conf->dol_hide_leftmenu) && empty($conf->dol_use_jmobile)) print '
    '."\n"; // End div container print "\n"; if ($comment) print ''."\n"; printCommonFooter($zone); - if (! empty($delayedhtmlcontent)) print $delayedhtmlcontent; + if (!empty($delayedhtmlcontent)) print $delayedhtmlcontent; - if (! empty($conf->use_javascript_ajax)) + if (!empty($conf->use_javascript_ajax)) { print "\n".''."\n"; - print ''."\n"; + print ''."\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 (!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' { @@ -2567,7 +2567,7 @@ if (! function_exists("llxFooter")) print "\n".''."\n"; print "\n\n"; $hash_unique_id = md5('dolibarr'.$conf->file->instance_unique_id); - $url_for_ping = "https://ping.dolibarr.org/"; + $url_for_ping = (empty($conf->global->MAIN_URL_FOR_PING) ? "https://ping.dolibarr.org/" : $conf->global->MAIN_URL_FOR_PING); ?> '; diff --git a/htdocs/margin/productMargins.php b/htdocs/margin/productMargins.php index cbc134c0b66..66077dc8708 100644 --- a/htdocs/margin/productMargins.php +++ b/htdocs/margin/productMargins.php @@ -100,7 +100,7 @@ print '
    '; dol_fiche_head($head, 'productMargins', $titre, 0, $picto); -print ''; +print '
    '; if ($id > 0) { print ''; @@ -146,7 +146,7 @@ print "
    '.$langs->trans('ChooseProduct/Service').'
    "; print '
    '; -print ''; +print '
    '; // Total Margin print ''; +print ''; +print ''; +print ''; +//print ''; + +$selected=1; +if (!empty($selectedLines) && !in_array($this->tpl['id'], $selectedLines)) $selected=0; +print ''; +print ''."\n"; +?> + diff --git a/htdocs/opensurvey/card.php b/htdocs/opensurvey/card.php index cdd8db1a0bd..302ecf5f1ff 100644 --- a/htdocs/opensurvey/card.php +++ b/htdocs/opensurvey/card.php @@ -35,8 +35,8 @@ require_once DOL_DOCUMENT_ROOT."/opensurvey/fonctions.php"; if (!$user->rights->opensurvey->read) accessforbidden(); // Initialisation des variables -$action=GETPOST('action', 'aZ09'); -$cancel=GETPOST('cancel', 'alpha'); +$action = GETPOST('action', 'aZ09'); +$cancel = GETPOST('cancel', 'alpha'); $numsondage = ''; @@ -44,16 +44,16 @@ if (GETPOST('id')) { $numsondage = GETPOST('id', 'alpha'); } -$object=new Opensurveysondage($db); +$object = new Opensurveysondage($db); -$result=$object->fetch(0, $numsondage); +$result = $object->fetch(0, $numsondage); if ($result <= 0) { dol_print_error($db, $object->error); exit; } -$expiredate=dol_mktime(0, 0, 0, GETPOST('expiremonth'), GETPOST('expireday'), GETPOST('expireyear')); +$expiredate = dol_mktime(0, 0, 0, GETPOST('expiremonth'), GETPOST('expireday'), GETPOST('expireyear')); @@ -67,7 +67,7 @@ if ($reshook < 0) setEventMessages($hookmanager->error, $hookmanager->errors, 'e if (empty($reshook)) { - if ($cancel) $action=''; + if ($cancel) $action = ''; // Delete if ($action == 'delete_confirm') @@ -75,7 +75,7 @@ if (empty($reshook)) // Security check if (!$user->rights->opensurvey->write) accessforbidden(); - $result=$object->delete($user, '', $numsondage); + $result = $object->delete($user, '', $numsondage); header('Location: '.dol_buildpath('/opensurvey/list.php', 1)); exit(); @@ -101,16 +101,16 @@ if (empty($reshook)) // Security check if (!$user->rights->opensurvey->write) accessforbidden(); - $error=0; + $error = 0; - if (! GETPOST('nouveautitre')) + if (!GETPOST('nouveautitre')) { setEventMessages($langs->trans("ErrorFieldRequired", $langs->transnoentitiesnoconv("Title")), null, 'errors'); $error++; $action = 'edit'; } - if (! $error) + if (!$error) { $object->titre = GETPOST('nouveautitre', 'nohtml'); $object->commentaires = GETPOST('nouveauxcommentaires', 'nohtml'); @@ -121,11 +121,11 @@ if (empty($reshook)) $object->allow_spy = GETPOST('canseeothersvote', 'alpha') == 'on' ? true : false; $object->mailsonde = GETPOST('mailsonde', 'alpha') == 'on' ? true : false; - $res=$object->update($user); + $res = $object->update($user); if ($res < 0) { setEventMessages($object->error, $object->errors, 'errors'); - $action='edit'; + $action = 'edit'; } } } @@ -133,27 +133,27 @@ if (empty($reshook)) // Add comment if (GETPOST('ajoutcomment')) { - $error=0; + $error = 0; - if (! GETPOST('comment')) + if (!GETPOST('comment')) { $error++; setEventMessages($langs->trans("ErrorFieldRequired", $langs->transnoentitiesnoconv("Comment")), null, 'errors'); } - if (! GETPOST('commentuser')) + if (!GETPOST('commentuser')) { $error++; setEventMessages($langs->trans("ErrorFieldRequired", $langs->transnoentitiesnoconv("User")), null, 'errors'); } - if (! $error) + if (!$error) { $comment = GETPOST("comment"); $comment_user = GETPOST('commentuser'); $resql = $object->addComment($comment, $comment_user); - if (! $resql) + if (!$resql) { setEventMessages($langs->trans('ErrorInsertingComment'), null, 'errors'); } @@ -161,7 +161,7 @@ if (empty($reshook)) } // Delete comment - $idcomment=GETPOST('deletecomment', 'int'); + $idcomment = GETPOST('deletecomment', 'int'); if ($idcomment) { // Security check @@ -181,7 +181,7 @@ if (empty($reshook)) * View */ -$form=new Form($db); +$form = new Form($db); if ($object->fk_user_creat) { @@ -191,21 +191,21 @@ if ($object->fk_user_creat) $title = $object->titre." - ".$langs->trans('Card'); $helpurl = ''; -$arrayofjs=array(); -$arrayofcss=array('/opensurvey/css/style.css'); +$arrayofjs = array(); +$arrayofcss = array('/opensurvey/css/style.css'); llxHeader('', $title, $helpurl, 0, 0, 0, $arrayofjs, $arrayofcss); // Define format of choices -$toutsujet=explode(",", $object->sujet); -$listofanswers=array(); +$toutsujet = explode(",", $object->sujet); +$listofanswers = array(); foreach ($toutsujet as $value) { - $tmp=explode('@', $value); - $listofanswers[]=array('label'=>$tmp[0],'format'=>($tmp[1]?$tmp[1]:'checkbox')); + $tmp = explode('@', $value); + $listofanswers[] = array('label'=>$tmp[0], 'format'=>($tmp[1] ? $tmp[1] : 'checkbox')); } -$toutsujet=str_replace("@", "
    ", $toutsujet); -$toutsujet=str_replace("°", "'", $toutsujet); +$toutsujet = str_replace("@", "
    ", $toutsujet); +$toutsujet = str_replace("°", "'", $toutsujet); print ''."\n"; print ''; @@ -228,15 +228,15 @@ print '
    '; print '
    '.$langs->trans("TotalMargin").''; diff --git a/htdocs/margin/tabs/productMargins.php b/htdocs/margin/tabs/productMargins.php index d9677ffa4da..0056c869fa1 100644 --- a/htdocs/margin/tabs/productMargins.php +++ b/htdocs/margin/tabs/productMargins.php @@ -166,7 +166,7 @@ if ($id > 0 || ! empty($ref)) $i = 0; print '
    '; - print ''; + print '
    '; print ''; print_liste_field_titre("Invoice", $_SERVER["PHP_SELF"], "f.ref", "", "&id=".$object->id, '', $sortfield, $sortorder); diff --git a/htdocs/master.inc.php b/htdocs/master.inc.php index b0138b65cbf..41150e913d5 100644 --- a/htdocs/master.inc.php +++ b/htdocs/master.inc.php @@ -32,7 +32,7 @@ * This script reads the conf file, init $lang, $db and and empty $user */ -require_once 'filefunc.inc.php'; // May have been already require by main.inc.php. But may not by scripts. +require_once 'filefunc.inc.php'; // May have been already require by main.inc.php. But may not by scripts. @@ -51,32 +51,32 @@ $conf->db->name = $dolibarr_main_db_name; $conf->db->user = $dolibarr_main_db_user; $conf->db->pass = $dolibarr_main_db_pass; $conf->db->type = $dolibarr_main_db_type; -$conf->db->prefix = $dolibarr_main_db_prefix; -$conf->db->character_set = $dolibarr_main_db_character_set; -$conf->db->dolibarr_main_db_collation = $dolibarr_main_db_collation; -$conf->db->dolibarr_main_db_encryption = $dolibarr_main_db_encryption; -$conf->db->dolibarr_main_db_cryptkey = $dolibarr_main_db_cryptkey; -if (defined('TEST_DB_FORCE_TYPE')) $conf->db->type=constant('TEST_DB_FORCE_TYPE'); // Force db type (for test purpose, by PHP unit for example) +$conf->db->prefix = $dolibarr_main_db_prefix; +$conf->db->character_set = $dolibarr_main_db_character_set; +$conf->db->dolibarr_main_db_collation = $dolibarr_main_db_collation; +$conf->db->dolibarr_main_db_encryption = $dolibarr_main_db_encryption; +$conf->db->dolibarr_main_db_cryptkey = $dolibarr_main_db_cryptkey; +if (defined('TEST_DB_FORCE_TYPE')) $conf->db->type = constant('TEST_DB_FORCE_TYPE'); // Force db type (for test purpose, by PHP unit for example) // Set properties specific to conf file -$conf->file->main_limit_users = $dolibarr_main_limit_users; +$conf->file->main_limit_users = $dolibarr_main_limit_users; $conf->file->mailing_limit_sendbyweb = $dolibarr_mailing_limit_sendbyweb; $conf->file->mailing_limit_sendbycli = $dolibarr_mailing_limit_sendbycli; -$conf->file->main_authentication = empty($dolibarr_main_authentication)?'':$dolibarr_main_authentication; // Identification mode -$conf->file->main_force_https = empty($dolibarr_main_force_https)?'':$dolibarr_main_force_https; // Force https -$conf->file->strict_mode = empty($dolibarr_strict_mode)?'':$dolibarr_strict_mode; // Force php strict mode (for debug) -$conf->file->instance_unique_id = empty($dolibarr_main_instance_unique_id)?(empty($dolibarr_main_cookie_cryptkey)?'':$dolibarr_main_cookie_cryptkey):$dolibarr_main_instance_unique_id; // Unique id of instance -$conf->file->dol_document_root = array('main' => (string) DOL_DOCUMENT_ROOT); // Define array of document root directories ('/home/htdocs') -$conf->file->dol_url_root = array('main' => (string) DOL_URL_ROOT); // Define array of url root path ('' or '/dolibarr') -if (! empty($dolibarr_main_document_root_alt)) +$conf->file->main_authentication = empty($dolibarr_main_authentication) ? '' : $dolibarr_main_authentication; // Identification mode +$conf->file->main_force_https = empty($dolibarr_main_force_https) ? '' : $dolibarr_main_force_https; // Force https +$conf->file->strict_mode = empty($dolibarr_strict_mode) ? '' : $dolibarr_strict_mode; // Force php strict mode (for debug) +$conf->file->instance_unique_id = empty($dolibarr_main_instance_unique_id) ? (empty($dolibarr_main_cookie_cryptkey) ? '' : $dolibarr_main_cookie_cryptkey) : $dolibarr_main_instance_unique_id; // Unique id of instance +$conf->file->dol_document_root = array('main' => (string) DOL_DOCUMENT_ROOT); // Define array of document root directories ('/home/htdocs') +$conf->file->dol_url_root = array('main' => (string) DOL_URL_ROOT); // Define array of url root path ('' or '/dolibarr') +if (!empty($dolibarr_main_document_root_alt)) { // dolibarr_main_document_root_alt can contains several directories - $values=preg_split('/[;,]/', $dolibarr_main_document_root_alt); - $i=0; - foreach($values as $value) $conf->file->dol_document_root['alt'.($i++)]=(string) $value; - $values=preg_split('/[;,]/', $dolibarr_main_url_root_alt); - $i=0; - foreach($values as $value) + $values = preg_split('/[;,]/', $dolibarr_main_document_root_alt); + $i = 0; + foreach ($values as $value) $conf->file->dol_document_root['alt'.($i++)] = (string) $value; + $values = preg_split('/[;,]/', $dolibarr_main_url_root_alt); + $i = 0; + foreach ($values as $value) { if (preg_match('/^http(s)?:/', $value)) { @@ -94,30 +94,30 @@ if (! empty($dolibarr_main_document_root_alt)) print "\"/custom\"
    \n"; exit; } - $conf->file->dol_url_root['alt'.($i++)]=(string) $value; + $conf->file->dol_url_root['alt'.($i++)] = (string) $value; } } // Chargement des includes principaux de librairies communes -if (! defined('NOREQUIREUSER')) require_once DOL_DOCUMENT_ROOT .'/user/class/user.class.php'; // Need 500ko memory -if (! defined('NOREQUIRETRAN')) require_once DOL_DOCUMENT_ROOT .'/core/class/translate.class.php'; -if (! defined('NOREQUIRESOC')) require_once DOL_DOCUMENT_ROOT .'/societe/class/societe.class.php'; +if (!defined('NOREQUIREUSER')) require_once DOL_DOCUMENT_ROOT.'/user/class/user.class.php'; // Need 500ko memory +if (!defined('NOREQUIRETRAN')) require_once DOL_DOCUMENT_ROOT.'/core/class/translate.class.php'; +if (!defined('NOREQUIRESOC')) require_once DOL_DOCUMENT_ROOT.'/societe/class/societe.class.php'; /* * Creation objet $langs (must be before all other code) */ -if (! defined('NOREQUIRETRAN')) +if (!defined('NOREQUIRETRAN')) { - $langs = new Translate('', $conf); // Must be after reading conf + $langs = new Translate('', $conf); // Must be after reading conf } /* * Object $db */ -if (! defined('NOREQUIREDB')) +if (!defined('NOREQUIREDB')) { - $db=getDoliDBInstance($conf->db->type, $conf->db->host, $conf->db->user, $conf->db->pass, $conf->db->name, $conf->db->port); + $db = getDoliDBInstance($conf->db->type, $conf->db->host, $conf->db->user, $conf->db->pass, $conf->db->name, $conf->db->port); if ($db->error) { @@ -147,12 +147,12 @@ if (! defined('NOREQUIREDB')) // Now database connexion is known, so we can forget password //unset($dolibarr_main_db_pass); // We comment this because this constant is used in a lot of pages -unset($conf->db->pass); // This is to avoid password to be shown in memory/swap dump +unset($conf->db->pass); // This is to avoid password to be shown in memory/swap dump /* * Object $user */ -if (! defined('NOREQUIREUSER')) { +if (!defined('NOREQUIREUSER')) { $user = new User($db); } @@ -162,11 +162,11 @@ if (! defined('NOREQUIREUSER')) { */ // By default conf->entity is 1, but we change this if we ask another value. -if (session_id() && ! empty($_SESSION["dol_entity"])) // Entity inside an opened session +if (session_id() && !empty($_SESSION["dol_entity"])) // Entity inside an opened session { $conf->entity = $_SESSION["dol_entity"]; } -elseif (! empty($_ENV["dol_entity"])) // Entity inside a CLI script +elseif (!empty($_ENV["dol_entity"])) // Entity inside a CLI script { $conf->entity = $_ENV["dol_entity"]; } @@ -180,9 +180,9 @@ elseif (defined('DOLENTITY') && is_numeric(DOLENTITY)) // For public page with } // Sanitize entity -if (! is_numeric($conf->entity)) $conf->entity=1; +if (!is_numeric($conf->entity)) $conf->entity = 1; -if (! defined('NOREQUIREDB')) +if (!defined('NOREQUIREDB')) { //print "Will work with data into entity instance number '".$conf->entity."'"; @@ -191,7 +191,7 @@ if (! defined('NOREQUIREDB')) } // Overwrite database value -if (! empty($conf->file->mailing_limit_sendbyweb)) +if (!empty($conf->file->mailing_limit_sendbyweb)) { $conf->global->MAILING_LIMIT_SENDBYWEB = $conf->file->mailing_limit_sendbyweb; } @@ -199,7 +199,7 @@ if (empty($conf->global->MAILING_LIMIT_SENDBYWEB)) { $conf->global->MAILING_LIMIT_SENDBYWEB = 25; } -if (! empty($conf->file->mailing_limit_sendbycli)) +if (!empty($conf->file->mailing_limit_sendbycli)) { $conf->global->MAILING_LIMIT_SENDBYCLI = $conf->file->mailing_limit_sendbycli; } @@ -209,27 +209,27 @@ if (empty($conf->global->MAILING_LIMIT_SENDBYCLI)) } // If software has been locked. Only login $conf->global->MAIN_ONLY_LOGIN_ALLOWED is allowed. -if (! empty($conf->global->MAIN_ONLY_LOGIN_ALLOWED)) +if (!empty($conf->global->MAIN_ONLY_LOGIN_ALLOWED)) { - $ok=0; - if ((! session_id() || ! isset($_SESSION["dol_login"])) && ! isset($_POST["username"]) && ! empty($_SERVER["GATEWAY_INTERFACE"])) $ok=1; // We let working pages if not logged and inside a web browser (login form, to allow login by admin) - elseif (isset($_POST["username"]) && $_POST["username"] == $conf->global->MAIN_ONLY_LOGIN_ALLOWED) $ok=1; // We let working pages that is a login submission (login submit, to allow login by admin) - elseif (defined('NOREQUIREDB')) $ok=1; // We let working pages that don't need database access (xxx.css.php) - elseif (defined('EVEN_IF_ONLY_LOGIN_ALLOWED')) $ok=1; // We let working pages that ask to work even if only login enabled (logout.php) - elseif (session_id() && isset($_SESSION["dol_login"]) && $_SESSION["dol_login"] == $conf->global->MAIN_ONLY_LOGIN_ALLOWED) $ok=1; // We let working if user is allowed admin - if (! $ok) + $ok = 0; + if ((!session_id() || !isset($_SESSION["dol_login"])) && !isset($_POST["username"]) && !empty($_SERVER["GATEWAY_INTERFACE"])) $ok = 1; // We let working pages if not logged and inside a web browser (login form, to allow login by admin) + elseif (isset($_POST["username"]) && $_POST["username"] == $conf->global->MAIN_ONLY_LOGIN_ALLOWED) $ok = 1; // We let working pages that is a login submission (login submit, to allow login by admin) + elseif (defined('NOREQUIREDB')) $ok = 1; // We let working pages that don't need database access (xxx.css.php) + elseif (defined('EVEN_IF_ONLY_LOGIN_ALLOWED')) $ok = 1; // We let working pages that ask to work even if only login enabled (logout.php) + elseif (session_id() && isset($_SESSION["dol_login"]) && $_SESSION["dol_login"] == $conf->global->MAIN_ONLY_LOGIN_ALLOWED) $ok = 1; // We let working if user is allowed admin + if (!$ok) { if (session_id() && isset($_SESSION["dol_login"]) && $_SESSION["dol_login"] != $conf->global->MAIN_ONLY_LOGIN_ALLOWED) { print 'Sorry, your application is offline.'."\n"; print 'You are logged with user "'.$_SESSION["dol_login"].'" and only administrator user "'.$conf->global->MAIN_ONLY_LOGIN_ALLOWED.'" is allowed to connect for the moment.'."\n"; - $nexturl=DOL_URL_ROOT.'/user/logout.php'; + $nexturl = DOL_URL_ROOT.'/user/logout.php'; print 'Please try later or click here to disconnect and change login user...'."\n"; } else { print 'Sorry, your application is offline. Only administrator user "'.$conf->global->MAIN_ONLY_LOGIN_ALLOWED.'" is allowed to connect for the moment.'."\n"; - $nexturl=DOL_URL_ROOT.'/'; + $nexturl = DOL_URL_ROOT.'/'; print 'Please try later or click here to change login user...'."\n"; } exit; diff --git a/htdocs/modulebuilder/admin/setup.php b/htdocs/modulebuilder/admin/setup.php index 673783bc06a..5c5274aba16 100644 --- a/htdocs/modulebuilder/admin/setup.php +++ b/htdocs/modulebuilder/admin/setup.php @@ -21,9 +21,9 @@ * \brief Page setup for modulebuilder module */ require '../../main.inc.php'; -require_once DOL_DOCUMENT_ROOT . '/core/lib/admin.lib.php'; +require_once DOL_DOCUMENT_ROOT.'/core/lib/admin.lib.php'; -global $conf,$langs,$user, $db; +global $conf, $langs, $user, $db; $langs->loadLangs(array("admin", "other", "modulebuilder")); if (!$user->admin || empty($conf->modulebuilder->enabled)) @@ -35,16 +35,16 @@ $backtopage = GETPOST('backtopage', 'alpha'); /* * Actions */ -if ($action=="update") +if ($action == "update") { - $res1=dolibarr_set_const($db, 'MODULEBUILDER_SPECIFIC_README', GETPOST('MODULEBUILDER_SPECIFIC_README', 'none'), 'chaine', 0, '', $conf->entity); - $res2=dolibarr_set_const($db, 'MODULEBUILDER_ASCIIDOCTOR', GETPOST('MODULEBUILDER_ASCIIDOCTOR', 'nohtml'), 'chaine', 0, '', $conf->entity); - $res3=dolibarr_set_const($db, 'MODULEBUILDER_ASCIIDOCTORPDF', GETPOST('MODULEBUILDER_ASCIIDOCTORPDF', 'nohtml'), 'chaine', 0, '', $conf->entity); - $res4=dolibarr_set_const($db, 'MODULEBUILDER_SPECIFIC_EDITOR_NAME', GETPOST('MODULEBUILDER_SPECIFIC_EDITOR_NAME', 'nohtml'), 'chaine', 0, '', $conf->entity); - $res5=dolibarr_set_const($db, 'MODULEBUILDER_SPECIFIC_EDITOR_URL', GETPOST('MODULEBUILDER_SPECIFIC_EDITOR_URL', 'nohtml'), 'chaine', 0, '', $conf->entity); - $res6=dolibarr_set_const($db, 'MODULEBUILDER_SPECIFIC_FAMILY', GETPOST('MODULEBUILDER_SPECIFIC_FAMILY', 'nohtml'), 'chaine', 0, '', $conf->entity); - $res7=dolibarr_set_const($db, 'MODULEBUILDER_SPECIFIC_AUTHOR', GETPOST('MODULEBUILDER_SPECIFIC_AUTHOR', 'html'), 'chaine', 0, '', $conf->entity); - $res8=dolibarr_set_const($db, 'MODULEBUILDER_SPECIFIC_VERSION', GETPOST('MODULEBUILDER_SPECIFIC_VERSION', 'nohtml'), 'chaine', 0, '', $conf->entity); + $res1 = dolibarr_set_const($db, 'MODULEBUILDER_SPECIFIC_README', GETPOST('MODULEBUILDER_SPECIFIC_README', 'none'), 'chaine', 0, '', $conf->entity); + $res2 = dolibarr_set_const($db, 'MODULEBUILDER_ASCIIDOCTOR', GETPOST('MODULEBUILDER_ASCIIDOCTOR', 'nohtml'), 'chaine', 0, '', $conf->entity); + $res3 = dolibarr_set_const($db, 'MODULEBUILDER_ASCIIDOCTORPDF', GETPOST('MODULEBUILDER_ASCIIDOCTORPDF', 'nohtml'), 'chaine', 0, '', $conf->entity); + $res4 = dolibarr_set_const($db, 'MODULEBUILDER_SPECIFIC_EDITOR_NAME', GETPOST('MODULEBUILDER_SPECIFIC_EDITOR_NAME', 'nohtml'), 'chaine', 0, '', $conf->entity); + $res5 = dolibarr_set_const($db, 'MODULEBUILDER_SPECIFIC_EDITOR_URL', GETPOST('MODULEBUILDER_SPECIFIC_EDITOR_URL', 'nohtml'), 'chaine', 0, '', $conf->entity); + $res6 = dolibarr_set_const($db, 'MODULEBUILDER_SPECIFIC_FAMILY', GETPOST('MODULEBUILDER_SPECIFIC_FAMILY', 'nohtml'), 'chaine', 0, '', $conf->entity); + $res7 = dolibarr_set_const($db, 'MODULEBUILDER_SPECIFIC_AUTHOR', GETPOST('MODULEBUILDER_SPECIFIC_AUTHOR', 'html'), 'chaine', 0, '', $conf->entity); + $res8 = dolibarr_set_const($db, 'MODULEBUILDER_SPECIFIC_VERSION', GETPOST('MODULEBUILDER_SPECIFIC_VERSION', 'nohtml'), 'chaine', 0, '', $conf->entity); if ($res1 < 0 || $res2 < 0 || $res3 < 0 || $res4 < 0 || $res5 < 0 || $res6 < 0 || $res7 < 0 || $res8 < 0) { setEventMessages('ErrorFailedToSaveDate', null, 'errors'); $db->rollback(); @@ -63,7 +63,7 @@ if (preg_match('/set_(.*)/', $action, $reg)) { $values = implode(',', $values); if (dolibarr_set_const($db, $code, $values, 'chaine', 0, '', $conf->entity) > 0) { - header("Location: " . $_SERVER["PHP_SELF"]); + header("Location: ".$_SERVER["PHP_SELF"]); exit; } else { dol_print_error($db); @@ -73,7 +73,7 @@ if (preg_match('/set_(.*)/', $action, $reg)) { if (preg_match('/del_(.*)/', $action, $reg)) { $code = $reg[1]; if (dolibarr_del_const($db, $code, 0) > 0) { - Header("Location: " . $_SERVER["PHP_SELF"]); + Header("Location: ".$_SERVER["PHP_SELF"]); exit; } else { dol_print_error($db); @@ -89,27 +89,27 @@ $form = new Form($db); llxHeader('', $langs->trans("ModulebuilderSetup")); -$linkback = '' . $langs->trans("BackToModuleList") . ''; +$linkback = ''.$langs->trans("BackToModuleList").''; print ''; print ''; print ''; -print load_fiche_titre($langs->trans("ModuleSetup") . ' ' . $langs->trans('Modulebuilder'), $linkback); +print load_fiche_titre($langs->trans("ModuleSetup").' '.$langs->trans('Modulebuilder'), $linkback); if (GETPOST('withtab', 'alpha')) { dol_fiche_head($head, 'modulebuilder', '', -1); } -print '' . $langs->trans("ModuleBuilderDesc") . "
    \n"; +print ''.$langs->trans("ModuleBuilderDesc")."
    \n"; print '
    '; -print '
    '; +print '
    '; print ''; -print ''; -print ''; +print ''; +print ''; print "\n"; @@ -118,49 +118,49 @@ if ($conf->global->MAIN_FEATURES_LEVEL >= 2) // What is use cas of this 2 options ? print ''; - print ''; + print ''; print ''; print ''; - print ''; + print ''; print ''; print ''; print ''; - print ''; + print ''; print ''; print ''; print ''; - print ''; + print ''; print ''; print ''; print ''; - print ''; + print ''; print ''; print ''; print ''; - print ''; + print ''; print ''; @@ -168,14 +168,14 @@ if ($conf->global->MAIN_FEATURES_LEVEL >= 2) } print ''; -print ''; +print ''; print ''; print ''; print ''; -print ''; +print ''; print ''; print ''; print ''; -print ''; +print ''; print ''; + print ''; + print ''; + print ''; + print ''; + //print ''; + //print ''; + print ''; + print ''; + $i = 0; + + if (! empty($this->lines)) + { + foreach ($this->lines as $line) + { + if (is_object($hookmanager) && (($line->product_type == 9 && ! empty($line->special_code)) || ! empty($line->fk_parent_line))) + { + if (empty($line->fk_parent_line)) + { + $parameters=array('line'=>$line, 'i'=>$i); + $action=''; + $hookmanager->executeHooks('printOriginObjectLine', $parameters, $this, $action); // Note that $action and $object may have been modified by some hooks + } + } + else + { + $this->printOriginLine($line, '', $restrictlist, '/core/tpl', $selectedLines); + } + + $i++; + } + } + } + + + /** + * Return HTML with a line of table array of source object lines + * TODO Move this and previous function into output html class file (htmlline.class.php). + * If lines are into a template, title must also be into a template + * But for the moment we don't know if it's possible as we keep a method available on overloaded objects. + * + * @param CommonObjectLine $line Line + * @param string $var Var + * @param string $restrictlist ''=All lines, 'services'=Restrict to services only (strike line if not) + * @param string $defaulttpldir Directory where to find the template + * @param array $selectedLines Array of lines id for selected lines + * @return void + */ + public function printOriginLine($line, $var, $restrictlist = '', $defaulttpldir = '/core/tpl', $selectedLines = array()) + { + global $langs, $conf; + + $this->tpl['id'] = $line->id; + + $this->tpl['label']=''; + if (! empty($line->fk_product)) + { + $productstatic = new Product($this->db); + $productstatic->fetch($line->fk_product); + $this->tpl['label'].= $productstatic->getNomUrl(1); + //$this->tpl['label'].= ' - '.$productstatic->label; + } + else + { + // If origin BOM line is not a product, but another BOM + // TODO + } + + $this->tpl['qty'] = $line->qty; + $this->tpl['qty_frozen'] = $line->qty_frozen; + $this->tpl['disable_stock_change'] = $line->disable_stock_change; + //$this->tpl['efficiency'] = $line->efficiency; + + $tpl = DOL_DOCUMENT_ROOT.'/mrp/tpl/originproductline.tpl.php'; + $res = include $tpl; + } } /** diff --git a/htdocs/mrp/index.php b/htdocs/mrp/index.php index 36847b71035..8f893f832bf 100644 --- a/htdocs/mrp/index.php +++ b/htdocs/mrp/index.php @@ -36,10 +36,10 @@ $hookmanager = new HookManager($db); $hookmanager->initHooks(array('mrpindex')); // Load translation files required by the page -$langs->loadLangs(array("companies","mrp")); +$langs->loadLangs(array("companies", "mrp")); // Security check -$result=restrictedArea($user, 'bom|mrp'); +$result = restrictedArea($user, 'bom|mrp'); /* @@ -92,7 +92,7 @@ if ($conf->use_javascript_ajax) $db->free($resql); print '
    '; - print '
    ' . $langs->trans("Key") . '' . $langs->trans("Value") . ''.$langs->trans("Key").''.$langs->trans("Value").'
    ' . $langs->trans("UseAboutPage") . ''.$langs->trans("UseAboutPage").''; if ($conf->use_javascript_ajax) { print ajax_constantonoff('MODULEBUILDER_USE_ABOUT'); } else { if (empty($conf->global->MODULEBUILDER_USE_ABOUT)) { - print '' . img_picto($langs->trans("Disabled"), 'off') . ''; + print ''.img_picto($langs->trans("Disabled"), 'off').''; } else { - print '' . img_picto($langs->trans("Enabled"), 'on') . ''; + print ''.img_picto($langs->trans("Enabled"), 'on').''; } } print '
    ' . $langs->trans("UseSpecificEditorName") . ''.$langs->trans("UseSpecificEditorName").''; print ''; print '
    ' . $langs->trans("UseSpecificEditorURL") . ''.$langs->trans("UseSpecificEditorURL").''; print ''; print '
    ' . $langs->trans("UseSpecificFamily") . ''.$langs->trans("UseSpecificFamily").''; print ''; print '
    ' . $langs->trans("UseSpecificAuthor") . ''.$langs->trans("UseSpecificAuthor").''; print ''; print '
    ' . $langs->trans("UseSpecificVersion") . ''.$langs->trans("UseSpecificVersion").''; print ''; print '
    ' . $langs->trans("UseSpecificReadme") . ''.$langs->trans("UseSpecificReadme").''; print ''; print '
    ' . $langs->trans("AsciiToHtmlConverter") . ''.$langs->trans("AsciiToHtmlConverter").''; print ''; print ' '.$langs->trans("Example").': asciidoc, asciidoctor'; @@ -183,7 +183,7 @@ print '
    ' . $langs->trans("AsciiToPdfConverter") . ''.$langs->trans("AsciiToPdfConverter").''; print ''; print ' '.$langs->trans("Example").': asciidoctor-pdf'; diff --git a/htdocs/modulebuilder/index.php b/htdocs/modulebuilder/index.php index 3879efa2030..a3a503e702b 100644 --- a/htdocs/modulebuilder/index.php +++ b/htdocs/modulebuilder/index.php @@ -27,7 +27,7 @@ * into the dirins directory. */ -if (! defined('NOSCANPOSTFORINJECTION')) define('NOSCANPOSTFORINJECTION', '1'); // Do not check anti SQL+XSS injection attack test +if (!defined('NOSCANPOSTFORINJECTION')) define('NOSCANPOSTFORINJECTION', '1'); // Do not check anti SQL+XSS injection attack test require '../main.inc.php'; require_once DOL_DOCUMENT_ROOT.'/core/lib/files.lib.php'; @@ -40,54 +40,54 @@ require_once DOL_DOCUMENT_ROOT.'/core/class/utils.class.php'; // Load translation files required by the page $langs->loadLangs(array("admin", "modulebuilder", "other", "cron", "errors")); -$action=GETPOST('action', 'aZ09'); -$confirm=GETPOST('confirm', 'alpha'); -$cancel=GETPOST('cancel', 'alpha'); +$action = GETPOST('action', 'aZ09'); +$confirm = GETPOST('confirm', 'alpha'); +$cancel = GETPOST('cancel', 'alpha'); -$module=GETPOST('module', 'alpha'); -$tab=GETPOST('tab', 'aZ09'); -$tabobj=GETPOST('tabobj', 'alpha'); -$propertykey=GETPOST('propertykey', 'alpha'); -if (empty($module)) $module='initmodule'; -if (empty($tab)) $tab='description'; -if (empty($tabobj)) $tabobj='newobjectifnoobj'; -$file=GETPOST('file', 'alpha'); +$module = GETPOST('module', 'alpha'); +$tab = GETPOST('tab', 'aZ09'); +$tabobj = GETPOST('tabobj', 'alpha'); +$propertykey = GETPOST('propertykey', 'alpha'); +if (empty($module)) $module = 'initmodule'; +if (empty($tab)) $tab = 'description'; +if (empty($tabobj)) $tabobj = 'newobjectifnoobj'; +$file = GETPOST('file', 'alpha'); -$modulename=dol_sanitizeFileName(GETPOST('modulename', 'alpha')); -$objectname=dol_sanitizeFileName(GETPOST('objectname', 'alpha')); +$modulename = dol_sanitizeFileName(GETPOST('modulename', 'alpha')); +$objectname = dol_sanitizeFileName(GETPOST('objectname', 'alpha')); // Security check if (empty($conf->modulebuilder->enabled)) accessforbidden('ModuleBuilderNotAllowed'); -if (! $user->admin && empty($conf->global->MODULEBUILDER_FOREVERYONE)) accessforbidden('ModuleBuilderNotAllowed'); +if (!$user->admin && empty($conf->global->MODULEBUILDER_FOREVERYONE)) accessforbidden('ModuleBuilderNotAllowed'); // Dir for custom dirs -$tmp=explode(',', $dolibarr_main_document_root_alt); +$tmp = explode(',', $dolibarr_main_document_root_alt); $dirins = $tmp[0]; $dirread = $dirins; $forceddirread = 0; $tmpdir = explode('@', $module); -if (! empty($tmpdir[1])) +if (!empty($tmpdir[1])) { - $module=$tmpdir[0]; - $dirread=$tmpdir[1]; - $forceddirread=1; + $module = $tmpdir[0]; + $dirread = $tmpdir[1]; + $forceddirread = 1; } if (GETPOST('dirins', 'alpha')) { $dirread = $dirins = GETPOST('dirins', 'alpha'); - $forceddirread=1; + $forceddirread = 1; } -$FILEFLAG='modulebuilder.txt'; +$FILEFLAG = 'modulebuilder.txt'; -$now=dol_now(); +$now = dol_now(); $newmask = 0; -if (empty($newmask) && ! empty($conf->global->MAIN_UMASK)) $newmask=$conf->global->MAIN_UMASK; +if (empty($newmask) && !empty($conf->global->MAIN_UMASK)) $newmask = $conf->global->MAIN_UMASK; if (empty($newmask)) // This should no happen { - $newmask='0664'; + $newmask = '0664'; } @@ -97,7 +97,7 @@ if (empty($newmask)) // This should no happen if ($dirins && $action == 'initmodule' && $modulename) { - $modulename = ucfirst($modulename); // Force first letter in uppercase + $modulename = ucfirst($modulename); // Force first letter in uppercase if (preg_match('/[^a-z0-9_]/i', $modulename)) { @@ -105,12 +105,12 @@ if ($dirins && $action == 'initmodule' && $modulename) setEventMessages($langs->trans("SpaceOrSpecialCharAreNotAllowed"), null, 'errors'); } - if (! $error) + if (!$error) { $srcdir = DOL_DOCUMENT_ROOT.'/modulebuilder/template'; $destdir = $dirins.'/'.strtolower($modulename); - $arrayreplacement=array( + $arrayreplacement = array( 'mymodule'=>strtolower($modulename), 'MyModule'=>$modulename ); @@ -131,7 +131,7 @@ if ($dirins && $action == 'initmodule' && $modulename) } } - if (! empty($conf->global->MODULEBUILDER_USE_ABOUT)) + if (!empty($conf->global->MODULEBUILDER_USE_ABOUT)) { dol_delete_file($destdir.'/admin/about.php'); } @@ -182,13 +182,13 @@ if ($dirins && $action == 'initmodule' && $modulename) } // Edit PHP files - if (! $error) + if (!$error) { $listofphpfilestoedit = dol_dir_list($destdir, 'files', 1, '\.(php|MD|js|sql|txt|xml|lang)$', '', 'fullname', SORT_ASC, 0, 1); - foreach($listofphpfilestoedit as $phpfileval) + foreach ($listofphpfilestoedit as $phpfileval) { //var_dump($phpfileval['fullname']); - $arrayreplacement=array( + $arrayreplacement = array( 'mymodule'=>strtolower($modulename), 'MyModule'=>$modulename, 'MYMODULE'=>strtoupper($modulename), @@ -225,10 +225,10 @@ if ($dirins && $action == 'initmodule' && $modulename) } } - if (! $error) + if (!$error) { setEventMessages('ModuleInitialized', null); - $module=$modulename; + $module = $modulename; $modulename = ''; } } @@ -366,10 +366,10 @@ if ($dirins && $action == 'inithook' && !empty($module)) if ($result > 0) { - $modulename = ucfirst($module); // Force first letter in uppercase + $modulename = ucfirst($module); // Force first letter in uppercase //var_dump($phpfileval['fullname']); - $arrayreplacement=array( + $arrayreplacement = array( 'mymodule'=>strtolower($modulename), 'MyModule'=>$modulename, 'MYMODULE'=>strtoupper($modulename), @@ -378,7 +378,7 @@ if ($dirins && $action == 'inithook' && !empty($module)) 'Mon module'=>$modulename, 'mon module'=>$modulename, 'htdocs/modulebuilder/template'=>strtolower($modulename), - '---Put here your own copyright and developer email---'=>dol_print_date($now, '%Y').' '.$user->getFullName($langs).($user->email?' <'.$user->email.'>':'') + '---Put here your own copyright and developer email---'=>dol_print_date($now, '%Y').' '.$user->getFullName($langs).($user->email ? ' <'.$user->email.'>' : '') ); dolReplaceInFile($destfile, $arrayreplacement); @@ -400,10 +400,10 @@ if ($dirins && $action == 'inittrigger' && !empty($module)) if ($result > 0) { - $modulename = ucfirst($module); // Force first letter in uppercase + $modulename = ucfirst($module); // Force first letter in uppercase //var_dump($phpfileval['fullname']); - $arrayreplacement=array( + $arrayreplacement = array( 'mymodule'=>strtolower($modulename), 'MyModule'=>$modulename, 'MYMODULE'=>strtoupper($modulename), @@ -412,7 +412,7 @@ if ($dirins && $action == 'inittrigger' && !empty($module)) 'Mon module'=>$modulename, 'mon module'=>$modulename, 'htdocs/modulebuilder/template'=>strtolower($modulename), - '---Put here your own copyright and developer email---'=>dol_print_date($now, '%Y').' '.$user->getFullName($langs).($user->email?' <'.$user->email.'>':'') + '---Put here your own copyright and developer email---'=>dol_print_date($now, '%Y').' '.$user->getFullName($langs).($user->email ? ' <'.$user->email.'>' : '') ); dolReplaceInFile($destfile, $arrayreplacement); @@ -434,10 +434,10 @@ if ($dirins && $action == 'initwidget' && !empty($module)) if ($result > 0) { - $modulename = ucfirst($module); // Force first letter in uppercase + $modulename = ucfirst($module); // Force first letter in uppercase //var_dump($phpfileval['fullname']); - $arrayreplacement=array( + $arrayreplacement = array( 'mymodule'=>strtolower($modulename), 'MyModule'=>$modulename, 'MYMODULE'=>strtoupper($modulename), @@ -563,7 +563,7 @@ if ($dirins && $action == 'initcli' && !empty($module)) '__USER_FULLNAME__'=>$user->getFullName($langs), '__USER_EMAIL__'=>$user->email, '__YYYY-MM-DD__'=>dol_print_date($now, 'dayrfc'), - '---Put here your own copyright and developer email---'=>dol_print_date($now, 'dayrfc').' '.$user->getFullName($langs).($user->email?' <'.$user->email.'>':'') + '---Put here your own copyright and developer email---'=>dol_print_date($now, 'dayrfc').' '.$user->getFullName($langs).($user->email ? ' <'.$user->email.'>' : '') ); dolReplaceInFile($destfile, $arrayreplacement); @@ -585,11 +585,11 @@ if ($dirins && $action == 'initdoc' && !empty($module)) if ($result > 0) { - $modulename = ucfirst($module); // Force first letter in uppercase + $modulename = ucfirst($module); // Force first letter in uppercase $modulelowercase = strtolower($module); //var_dump($phpfileval['fullname']); - $arrayreplacement=array( + $arrayreplacement = array( 'mymodule'=>strtolower($modulename), 'MyModule'=>$modulename, 'MYMODULE'=>strtoupper($modulename), @@ -603,14 +603,14 @@ if ($dirins && $action == 'initdoc' && !empty($module)) '__USER_FULLNAME__'=>$user->getFullName($langs), '__USER_EMAIL__'=>$user->email, '__YYYY-MM-DD__'=>dol_print_date($now, 'dayrfc'), - '---Put here your own copyright and developer email---'=>dol_print_date($now, 'dayrfc').' '.$user->getFullName($langs).($user->email?' <'.$user->email.'>':'') + '---Put here your own copyright and developer email---'=>dol_print_date($now, 'dayrfc').' '.$user->getFullName($langs).($user->email ? ' <'.$user->email.'>' : '') ); dolReplaceInFile($destfile, $arrayreplacement); // Delete old documentation files - $FILENAMEDOC=$modulelowercase.'.html'; - $FILENAMEDOCPDF=$modulelowercase.'.pdf'; + $FILENAMEDOC = $modulelowercase.'.html'; + $FILENAMEDOCPDF = $modulelowercase.'.pdf'; $outputfiledoc = dol_buildpath($modulelowercase, 0).'/doc/'.$FILENAMEDOC; $outputfiledocurl = dol_buildpath($modulelowercase, 1).'/doc/'.$FILENAMEDOC; $outputfiledocpdf = dol_buildpath($modulelowercase, 0).'/doc/'.$FILENAMEDOCPDF; @@ -628,7 +628,7 @@ if ($dirins && $action == 'initdoc' && !empty($module)) if ($dirins && $action == 'addlanguage' && !empty($module)) { - $newlangcode=GETPOST('newlangcode', 'aZ09'); + $newlangcode = GETPOST('newlangcode', 'aZ09'); $srcfile = $dirins.'/'.strtolower($module).'/langs/en_US'; $destfile = $dirins.'/'.strtolower($module).'/langs/'.$newlangcode; $result = dolCopyDir($srcfile, $destfile, 0, 0); @@ -636,7 +636,7 @@ if ($dirins && $action == 'addlanguage' && !empty($module)) if ($dirins && $action == 'confirm_removefile' && !empty($module)) { - $relativefilename=dol_sanitizePathName(GETPOST('file', 'none')); + $relativefilename = dol_sanitizePathName(GETPOST('file', 'none')); if ($relativefilename) { $dirnametodelete = dirname($relativefilename); @@ -758,7 +758,7 @@ if ($dirins && $action == 'initobject' && $module && $objectname) { $error++; setEventMessages($langs->trans("SpaceOrSpecialCharAreNotAllowed"), null, 'errors'); - $tabobj='newobject'; + $tabobj = 'newobject'; } $srcdir = DOL_DOCUMENT_ROOT.'/modulebuilder/template'; @@ -772,16 +772,16 @@ if ($dirins && $action == 'initobject' && $module && $objectname) dol_mkdir($destdir.'/sql'); // Scan dir class to find if an object with same name already exists. - if (! $error) + if (!$error) { - $dirlist=dol_dir_list($destdir.'/class', 'files', 0, '\.txt$'); - $alreadyfound=false; - foreach($dirlist as $key => $val) + $dirlist = dol_dir_list($destdir.'/class', 'files', 0, '\.txt$'); + $alreadyfound = false; + foreach ($dirlist as $key => $val) { - $filefound=preg_replace('/\.txt$/', '', $val['name']); + $filefound = preg_replace('/\.txt$/', '', $val['name']); if (strtolower($objectname) == strtolower($filefound) && $objectname != $filefound) { - $alreadyfound=true; + $alreadyfound = true; $error++; setEventMessages($langs->trans("AnObjectAlreadyExistWithThisNameAndDiffCase"), null, 'errors'); break; @@ -789,7 +789,7 @@ if ($dirins && $action == 'initobject' && $module && $objectname) } } - if (! $error) + if (!$error) { // Copy some files $filetogenerate = array( @@ -830,7 +830,7 @@ if ($dirins && $action == 'initobject' && $module && $objectname) ); } - foreach($filetogenerate as $srcfile => $destfile) + foreach ($filetogenerate as $srcfile => $destfile) { $result = dol_copy($srcdir.'/'.$srcfile, $destdir.'/'.$destfile, $newmask, 0); if ($result <= 0) @@ -960,7 +960,7 @@ if ($dirins && $action == 'initobject' && $module && $objectname) 'MYOBJECT'=>strtoupper($objectname) ); - $result=dolReplaceInFile($phpfileval['fullname'], $arrayreplacement); + $result = dolReplaceInFile($phpfileval['fullname'], $arrayreplacement); //var_dump($result); if ($result < 0) { @@ -1023,7 +1023,7 @@ if ($dirins && ($action == 'droptable' || $action == 'droptableextrafields') && } if ($nb == 0) { - $resql=$db->DDLDropTable($tabletodrop); + $resql = $db->DDLDropTable($tabletodrop); //var_dump($resql); setEventMessages($langs->trans("TableDropped", $tabletodrop), null, 'mesgs'); } @@ -1034,7 +1034,7 @@ if ($dirins && ($action == 'droptable' || $action == 'droptableextrafields') && } } -if ($dirins && $action == 'addproperty' && !empty($module) && ! empty($tabobj)) +if ($dirins && $action == 'addproperty' && !empty($module) && !empty($tabobj)) { $error = 0; @@ -1128,20 +1128,20 @@ if ($dirins && $action == 'confirm_deleteproperty' && $propertykey) dol_mkdir($destdir); // Edit the class file to write properties - if (! $error) + if (!$error) { - $object=rebuildObjectClass($destdir, $module, $objectname, $newmask, $srcdir, array(), $propertykey); + $object = rebuildObjectClass($destdir, $module, $objectname, $newmask, $srcdir, array(), $propertykey); if (is_numeric($object) && $object <= 0) $error++; } // Edit sql with new properties - if (! $error) + if (!$error) { - $result=rebuildObjectSql($destdir, $module, $objectname, $newmask, $srcdir, $object); + $result = rebuildObjectSql($destdir, $module, $objectname, $newmask, $srcdir, $object); if ($result <= 0) $error++; } - if (! $error) + if (!$error) { setEventMessages($langs->trans('FilesForObjectUpdated', $objectname), null); @@ -1162,9 +1162,9 @@ if ($dirins && $action == 'confirm_deletemodule') setEventMessages($langs->trans("SpaceOrSpecialCharAreNotAllowed"), null, 'errors'); } - if (! $error) + if (!$error) { - $modulelowercase=strtolower($module); + $modulelowercase = strtolower($module); // Dir for module $dir = $dirins.'/'.$modulelowercase; @@ -1193,10 +1193,10 @@ if ($dirins && $action == 'confirm_deleteobject' && $objectname) setEventMessages($langs->trans("SpaceOrSpecialCharAreNotAllowed"), null, 'errors'); } - if (! $error) + if (!$error) { - $modulelowercase=strtolower($module); - $objectlowercase=strtolower($objectname); + $modulelowercase = strtolower($module); + $objectlowercase = strtolower($objectname); // Dir for module $dir = $dirins.'/'.$modulelowercase; @@ -1248,23 +1248,23 @@ if ($dirins && $action == 'confirm_deleteobject' && $objectname) if ($dirins && $action == 'generatepackage') { - $modulelowercase=strtolower($module); + $modulelowercase = strtolower($module); // Dir for module $dir = $dirins.'/'.$modulelowercase; // Zip file to build - $FILENAMEZIP=''; + $FILENAMEZIP = ''; // Load module dol_include_once($modulelowercase.'/core/modules/mod'.$module.'.class.php'); - $class='mod'.$module; + $class = 'mod'.$module; if (class_exists($class)) { try { $moduleobj = new $class($db); } - catch(Exception $e) + catch (Exception $e) { $error++; dol_print_error($e->getMessage()); @@ -1278,16 +1278,16 @@ if ($dirins && $action == 'generatepackage') exit; } - $arrayversion=explode('.', $moduleobj->version, 3); + $arrayversion = explode('.', $moduleobj->version, 3); if (count($arrayversion)) { - $FILENAMEZIP="module_".$modulelowercase.'-'.$arrayversion[0].'.'.$arrayversion[1].($arrayversion[2]?".".$arrayversion[2]:"").".zip"; + $FILENAMEZIP = "module_".$modulelowercase.'-'.$arrayversion[0].'.'.$arrayversion[1].($arrayversion[2] ? ".".$arrayversion[2] : "").".zip"; $dirofmodule = dol_buildpath($modulelowercase, 0).'/bin'; $outputfilezip = $dirofmodule.'/'.$FILENAMEZIP; if ($dirofmodule) { - if (! dol_is_dir($dirofmodule)) dol_mkdir($dirofmodule); + if (!dol_is_dir($dirofmodule)) dol_mkdir($dirofmodule); $result = dol_compress_dir($dir, $outputfilezip, 'zip'); } else @@ -1316,7 +1316,7 @@ if ($dirins && $action == 'generatepackage') if ($dirins && $action == 'generatedoc') { - $FILENAMEDOC=strtolower($module).'.html'; + $FILENAMEDOC = strtolower($module).'.html'; $dirofmodule = dol_buildpath(strtolower($module), 0).'/doc'; $util = new Utils($db); @@ -1341,10 +1341,10 @@ if ($action == 'savefile' && empty($cancel)) if ($relofcustom) { // Check that relative path ($file) start with name 'custom' - if (! preg_match('/^'.$relofcustom.'/', $file)) $file=$relofcustom.'/'.$file; + if (!preg_match('/^'.$relofcustom.'/', $file)) $file = $relofcustom.'/'.$file; - $pathoffile=dol_buildpath($file, 0); - $pathoffilebackup=dol_buildpath($file.'.back', 0); + $pathoffile = dol_buildpath($file, 0); + $pathoffilebackup = dol_buildpath($file.'.back', 0); // Save old version if (dol_is_file($pathoffile)) @@ -1439,11 +1439,11 @@ $form = new Form($db); $formadmin = new FormAdmin($db); // Set dir where external modules are installed -if (! dol_is_dir($dirins)) +if (!dol_is_dir($dirins)) { dol_mkdir($dirins); } -$dirins_ok=(dol_is_dir($dirins)); +$dirins_ok = (dol_is_dir($dirins)); llxHeader('', $langs->trans("ModuleBuilder"), '', '', 0, 0, array( @@ -1566,24 +1566,24 @@ $infomodulesfound = '
    '.$form->textwithpicto( // Load module descriptor -$error=0; +$error = 0; $moduleobj = null; -if (! empty($module) && $module != 'initmodule' && $module != 'deletemodule') +if (!empty($module) && $module != 'initmodule' && $module != 'deletemodule') { - $modulelowercase=strtolower($module); + $modulelowercase = strtolower($module); // Load module $fullpathdirtodescriptor = $listofmodules[strtolower($module)]['moduledescriptorrelpath']; dol_include_once($fullpathdirtodescriptor); - $class='mod'.$module; + $class = 'mod'.$module; if (class_exists($class)) { try { $moduleobj = new $class($db); } - catch(Exception $e) + catch (Exception $e) { $error++; print $e->getMessage(); @@ -1602,16 +1602,16 @@ print '
    '; // Tabs for all modules $head = array(); -$h=0; +$h = 0; $head[$h][0] = $_SERVER["PHP_SELF"].'?module=initmodule'; $head[$h][1] = ''.$langs->trans("NewModule").''; $head[$h][2] = 'initmodule'; $h++; -foreach($listofmodules as $tmpmodule => $tmpmodulearray) +foreach ($listofmodules as $tmpmodule => $tmpmodulearray) { - $head[$h][0] = $_SERVER["PHP_SELF"].'?module='.$tmpmodulearray['modulenamewithcase'].($forceddirread?'@'.$dirread:''); + $head[$h][0] = $_SERVER["PHP_SELF"].'?module='.$tmpmodulearray['modulenamewithcase'].($forceddirread ? '@'.$dirread : ''); $head[$h][1] = $tmpmodulearray['modulenamewithcase']; $head[$h][2] = $tmpmodulearray['modulenamewithcase']; $h++; @@ -1623,7 +1623,7 @@ $head[$h][2] = 'deletemodule'; $h++; -dol_fiche_head($head, $module, $langs->trans("Modules"), -1, 'generic', 0, $infomodulesfound); // Modules +dol_fiche_head($head, $module, $langs->trans("Modules"), -1, 'generic', 0, $infomodulesfound); // Modules if ($module == 'initmodule') { @@ -1786,7 +1786,7 @@ elseif (! empty($module)) if ($action != 'editfile' || empty($file)) { - dol_fiche_head($head2, $tab, '', -1, ''); // Description - level 2 + dol_fiche_head($head2, $tab, '', -1, ''); // Description - level 2 print ''.$langs->trans("ModuleBuilderDesc".$tab).''; $infoonmodulepath = ''; @@ -1817,7 +1817,7 @@ elseif (! empty($module)) print load_fiche_titre($langs->trans("DescriptorFile"), '', ''); - if (! empty($moduleobj)) + if (!empty($moduleobj)) { print '
    '; print '
    '; @@ -1906,7 +1906,7 @@ elseif (! empty($module)) } else { - $fullpathoffile=dol_buildpath($file, 0, 1); // Description - level 2 + $fullpathoffile = dol_buildpath($file, 0, 1); // Description - level 2 if ($fullpathoffile) { @@ -1923,8 +1923,8 @@ elseif (! empty($module)) dol_fiche_head($head2, $tab, '', -1, ''); - $doleditor=new DolEditor('editfilecontent', $content, '', '300', 'Full', 'In', true, false, 'ace', 0, '99%', ''); - print $doleditor->Create(1, '', false, $langs->trans("File").' : '.$file, (GETPOST('format', 'aZ09')?GETPOST('format', 'aZ09'):'html')); + $doleditor = new DolEditor('editfilecontent', $content, '', '300', 'Full', 'In', true, false, 'ace', 0, '99%', ''); + print $doleditor->Create(1, '', false, $langs->trans("File").' : '.$file, (GETPOST('format', 'aZ09') ?GETPOST('format', 'aZ09') : 'html')); dol_fiche_end(); @@ -1939,7 +1939,7 @@ elseif (! empty($module)) } else { - dol_fiche_head($head2, $tab, '', -1, ''); // Level 2 + dol_fiche_head($head2, $tab, '', -1, ''); // Level 2 } if ($tab == 'languages') @@ -1963,7 +1963,7 @@ elseif (! empty($module)) print '
    '; print '
    '; - $langfiles=dol_dir_list(dol_buildpath($modulelowercase.'/langs', 0), 'files', 1, '\.lang$'); + $langfiles = dol_dir_list(dol_buildpath($modulelowercase.'/langs', 0), 'files', 1, '\.lang$'); print ''; foreach ($langfiles as $langfile) @@ -1982,7 +1982,7 @@ elseif (! empty($module)) //print $langs->trans("UseAsciiDocFormat").'
    '; - $fullpathoffile=dol_buildpath($file, 0); + $fullpathoffile = dol_buildpath($file, 0); $content = file_get_contents($fullpathoffile); @@ -1994,8 +1994,8 @@ elseif (! empty($module)) print ''; print ''; - $doleditor=new DolEditor('editfilecontent', $content, '', '300', 'Full', 'In', true, false, 'ace', 0, '99%'); - print $doleditor->Create(1, '', false, $langs->trans("File").' : '.$file, (GETPOST('format', 'aZ09')?GETPOST('format', 'aZ09'):'text')); + $doleditor = new DolEditor('editfilecontent', $content, '', '300', 'Full', 'In', true, false, 'ace', 0, '99%'); + print $doleditor->Create(1, '', false, $langs->trans("File").' : '.$file, (GETPOST('format', 'aZ09') ?GETPOST('format', 'aZ09') : 'text')); print '
    '; print '
    '; print ''; @@ -2159,27 +2159,27 @@ elseif (! empty($module)) // Scan for object class files $listofobject = dol_dir_list($dir, 'files', 0, '\.class\.php$'); - $firstobjectname=''; - foreach($listofobject as $fileobj) + $firstobjectname = ''; + foreach ($listofobject as $fileobj) { if (preg_match('/^api_/', $fileobj['name'])) continue; if (preg_match('/^actions_/', $fileobj['name'])) continue; - $tmpcontent=file_get_contents($fileobj['fullname']); + $tmpcontent = file_get_contents($fileobj['fullname']); if (preg_match('/class\s+([^\s]*)\s+extends\s+CommonObject/ims', $tmpcontent, $reg)) { //$objectname = preg_replace('/\.txt$/', '', $fileobj['name']); $objectname = $reg[1]; if (empty($firstobjectname)) $firstobjectname = $objectname; - $head3[$h][0] = $_SERVER["PHP_SELF"].'?tab=objects&module='.$module.($forceddirread?'@'.$dirread:'').'&tabobj='.$objectname; + $head3[$h][0] = $_SERVER["PHP_SELF"].'?tab=objects&module='.$module.($forceddirread ? '@'.$dirread : '').'&tabobj='.$objectname; $head3[$h][1] = $objectname; $head3[$h][2] = $objectname; $h++; } } - $head3[$h][0] = $_SERVER["PHP_SELF"].'?tab=objects&module='.$module.($forceddirread?'@'.$dirread:'').'&tabobj=deleteobject'; + $head3[$h][0] = $_SERVER["PHP_SELF"].'?tab=objects&module='.$module.($forceddirread ? '@'.$dirread : '').'&tabobj=deleteobject'; $head3[$h][1] = $langs->trans("DangerZone"); $head3[$h][2] = 'deleteobject'; $h++; @@ -2187,11 +2187,11 @@ elseif (! empty($module)) // If tabobj was not defined, then we check if there is one obj. If yes, we force on it, if no, we will show tab to create new objects. if ($tabobj == 'newobjectifnoobj') { - if ($firstobjectname) $tabobj=$firstobjectname; + if ($firstobjectname) $tabobj = $firstobjectname; else $tabobj = 'newobject'; } - dol_fiche_head($head3, $tabobj, '', -1, ''); // Level 3 + dol_fiche_head($head3, $tabobj, '', -1, ''); // Level 3 if ($tabobj == 'newobject') { @@ -2217,7 +2217,7 @@ elseif (! empty($module)) //print ' '; print $langs->trans("InitStructureFromExistingTable"); print ''; - print ''; + print ''; print '
    '; print ''; @@ -2234,7 +2234,7 @@ elseif (! empty($module)) print $langs->trans("EnterNameOfObjectToDeleteDesc").'

    '; print ''; - print ''; + print ''; print ''; } else @@ -2434,7 +2434,7 @@ elseif (! empty($module)) print '


    '; - if(function_exists('opcache_invalidate')) opcache_invalidate($dirread.'/'.$pathtoclass, true); // remove the include cache hell ! + if (function_exists('opcache_invalidate')) opcache_invalidate($dirread.'/'.$pathtoclass, true); // remove the include cache hell ! if (empty($forceddirread)) { @@ -2449,17 +2449,17 @@ elseif (! empty($module)) try { $tmpobjet = @new $tabobj($db); } - catch(Exception $e) + catch (Exception $e) { dol_syslog('Failed to load Constructor of class: '.$e->getMessage(), LOG_WARNING); } } - if (! empty($tmpobjet)) + if (!empty($tmpobjet)) { $reflector = new ReflectionClass($tabobj); - $reflectorproperties = $reflector->getProperties(); // Can also use get_object_vars - $reflectorpropdefault = $reflector->getDefaultProperties(); // Can also use get_object_vars + $reflectorproperties = $reflector->getProperties(); // Can also use get_object_vars + $reflectorpropdefault = $reflector->getDefaultProperties(); // Can also use get_object_vars //$propstat = $reflector->getStaticProperties(); //var_dump($reflectorpropdefault); @@ -2467,7 +2467,7 @@ elseif (! empty($module)) print ''; print ''; print ''; - print ''; + print ''; print ''; print ''; @@ -2480,7 +2480,7 @@ elseif (! empty($module)) print '
    '; print '
    '; print ''; - print ''; print ''; @@ -2538,7 +2538,7 @@ elseif (! empty($module)) print ''; print ''; - foreach($properties as $propkey => $propval) + foreach ($properties as $propkey => $propval) { /* If from Reflection if ($propval->class == $tabobj) @@ -2654,13 +2654,13 @@ elseif (! empty($module)) print ''.$langs->trans("SpecDefDesc").'
    '; print '
    '; - $specs=dol_dir_list(dol_buildpath($modulelowercase.'/doc', 0), 'files', 1, '(\.md|\.asciidoc)$', array('\/temp\/')); + $specs = dol_dir_list(dol_buildpath($modulelowercase.'/doc', 0), 'files', 1, '(\.md|\.asciidoc)$', array('\/temp\/')); foreach ($specs as $spec) { $pathtofile = $modulelowercase.'/doc/'.$spec['relativename']; - $format='asciidoc'; - if (preg_match('/\.md$/i', $spec['name'])) $format='markdown'; + $format = 'asciidoc'; + if (preg_match('/\.md$/i', $spec['name'])) $format = 'markdown'; print ' '.$langs->trans("SpecificationFile").' : '.$pathtofile.''; print ' '.img_picto($langs->trans("Edit"), 'edit').''; print '
    '; @@ -2672,7 +2672,7 @@ elseif (! empty($module)) //print $langs->trans("UseAsciiDocFormat").'
    '; - $fullpathoffile=dol_buildpath($file, 0); + $fullpathoffile = dol_buildpath($file, 0); $content = file_get_contents($fullpathoffile); @@ -2684,8 +2684,8 @@ elseif (! empty($module)) print ''; print ''; - $doleditor=new DolEditor('editfilecontent', $content, '', '300', 'Full', 'In', true, false, 'ace', 0, '99%'); - print $doleditor->Create(1, '', false, $langs->trans("File").' : '.$file, (GETPOST('format', 'aZ09')?GETPOST('format', 'aZ09'):'html')); + $doleditor = new DolEditor('editfilecontent', $content, '', '300', 'Full', 'In', true, false, 'ace', 0, '99%'); + print $doleditor->Create(1, '', false, $langs->trans("File").' : '.$file, (GETPOST('format', 'aZ09') ?GETPOST('format', 'aZ09') : 'html')); print '
    '; print '
    '; print ''; @@ -2708,7 +2708,7 @@ elseif (! empty($module)) print '
    '; } } - catch(Exception $e) + catch (Exception $e) { print $e->getMessage(); } @@ -2717,11 +2717,11 @@ elseif (! empty($module)) { if (empty($forceddirread)) { - $fullpathoffile=dol_buildpath($file, 0); + $fullpathoffile = dol_buildpath($file, 0); } else { - $fullpathoffile=$dirread.'/'.$file; + $fullpathoffile = $dirread.'/'.$file; } $content = file_get_contents($fullpathoffile); @@ -2733,10 +2733,10 @@ elseif (! empty($module)) print ''; print ''; print ''; - print ''; + print ''; - $doleditor=new DolEditor('editfilecontent', $content, '', '300', 'Full', 'In', true, false, 'ace', 0, '99%'); - print $doleditor->Create(1, '', false, $langs->trans("File").' : '.$file, (GETPOST('format', 'aZ09')?GETPOST('format', 'aZ09'):'html')); + $doleditor = new DolEditor('editfilecontent', $content, '', '300', 'Full', 'In', true, false, 'ace', 0, '99%'); + print $doleditor->Create(1, '', false, $langs->trans("File").' : '.$file, (GETPOST('format', 'aZ09') ?GETPOST('format', 'aZ09') : 'html')); print '
    '; print '
    '; print ''; @@ -2748,7 +2748,7 @@ elseif (! empty($module)) } } - dol_fiche_end(); // Level 3 + dol_fiche_end(); // Level 3 } if ($tab == 'menus') @@ -2866,7 +2866,7 @@ elseif (! empty($module)) } else { - $fullpathoffile=dol_buildpath($file, 0); + $fullpathoffile = dol_buildpath($file, 0); $content = file_get_contents($fullpathoffile); @@ -2878,8 +2878,8 @@ elseif (! empty($module)) print ''; print ''; - $doleditor=new DolEditor('editfilecontent', $content, '', '300', 'Full', 'In', true, false, 'ace', 0, '99%'); - print $doleditor->Create(1, '', false, $langs->trans("File").' : '.$file, (GETPOST('format', 'aZ09')?GETPOST('format', 'aZ09'):'html')); + $doleditor = new DolEditor('editfilecontent', $content, '', '300', 'Full', 'In', true, false, 'ace', 0, '99%'); + print $doleditor->Create(1, '', false, $langs->trans("File").' : '.$file, (GETPOST('format', 'aZ09') ?GETPOST('format', 'aZ09') : 'html')); print '
    '; print '
    '; print ''; @@ -2966,7 +2966,7 @@ elseif (! empty($module)) } else { - $fullpathoffile=dol_buildpath($file, 0); + $fullpathoffile = dol_buildpath($file, 0); $content = file_get_contents($fullpathoffile); @@ -2978,8 +2978,8 @@ elseif (! empty($module)) print ''; print ''; - $doleditor=new DolEditor('editfilecontent', $content, '', '300', 'Full', 'In', true, false, 'ace', 0, '99%'); - print $doleditor->Create(1, '', false, $langs->trans("File").' : '.$file, (GETPOST('format', 'aZ09')?GETPOST('format', 'aZ09'):'html')); + $doleditor = new DolEditor('editfilecontent', $content, '', '300', 'Full', 'In', true, false, 'ace', 0, '99%'); + print $doleditor->Create(1, '', false, $langs->trans("File").' : '.$file, (GETPOST('format', 'aZ09') ?GETPOST('format', 'aZ09') : 'html')); print '
    '; print '
    '; print ''; @@ -3024,7 +3024,7 @@ elseif (! empty($module)) } else { - $fullpathoffile=dol_buildpath($file, 0); + $fullpathoffile = dol_buildpath($file, 0); $content = file_get_contents($fullpathoffile); @@ -3036,8 +3036,8 @@ elseif (! empty($module)) print ''; print ''; - $doleditor=new DolEditor('editfilecontent', $content, '', '300', 'Full', 'In', true, false, 'ace', 0, '99%'); - print $doleditor->Create(1, '', false, $langs->trans("File").' : '.$file, (GETPOST('format', 'aZ09')?GETPOST('format', 'aZ09'):'html')); + $doleditor = new DolEditor('editfilecontent', $content, '', '300', 'Full', 'In', true, false, 'ace', 0, '99%'); + print $doleditor->Create(1, '', false, $langs->trans("File").' : '.$file, (GETPOST('format', 'aZ09') ?GETPOST('format', 'aZ09') : 'html')); print '
    '; print '
    '; print ''; @@ -3062,7 +3062,7 @@ elseif (! empty($module)) print '
    '; print '
    '.$langs->trans("Property"); + print ''.$langs->trans("Property"); print ' ('.$langs->trans("SeeExamples").')'; print ''; @@ -2511,7 +2511,7 @@ elseif (! empty($module)) //$properties = dol_sort_array($tmpobjet->fields, 'position'); $properties = dol_sort_array($reflectorpropdefault['fields'], 'position'); - if (! empty($properties)) + if (!empty($properties)) { // Line to add a property print '
    '.$langs->trans('Failed to init the object with the new.').'
    '; - if (! empty($triggers)) + if (!empty($triggers)) { foreach ($triggers as $trigger) { @@ -3086,7 +3086,7 @@ elseif (! empty($module)) } else { - $fullpathoffile=dol_buildpath($file, 0); + $fullpathoffile = dol_buildpath($file, 0); $content = file_get_contents($fullpathoffile); @@ -3098,8 +3098,8 @@ elseif (! empty($module)) print ''; print ''; - $doleditor=new DolEditor('editfilecontent', $content, '', '300', 'Full', 'In', true, false, 'ace', 0, '99%'); - print $doleditor->Create(1, '', false, $langs->trans("File").' : '.$file, (GETPOST('format', 'aZ09')?GETPOST('format', 'aZ09'):'html')); + $doleditor = new DolEditor('editfilecontent', $content, '', '300', 'Full', 'In', true, false, 'ace', 0, '99%'); + print $doleditor->Create(1, '', false, $langs->trans("File").' : '.$file, (GETPOST('format', 'aZ09') ?GETPOST('format', 'aZ09') : 'html')); print '
    '; print '
    '; print ''; @@ -3227,7 +3227,7 @@ elseif (! empty($module)) print '
    '; print '
    '; - if (! empty($widgets)) + if (!empty($widgets)) { foreach ($widgets as $widget) { @@ -3249,7 +3249,7 @@ elseif (! empty($module)) } else { - $fullpathoffile=dol_buildpath($file, 0); + $fullpathoffile = dol_buildpath($file, 0); $content = file_get_contents($fullpathoffile); @@ -3261,8 +3261,8 @@ elseif (! empty($module)) print ''; print ''; - $doleditor=new DolEditor('editfilecontent', $content, '', '300', 'Full', 'In', true, false, 'ace', 0, '99%'); - print $doleditor->Create(1, '', false, $langs->trans("File").' : '.$file, (GETPOST('format', 'aZ09')?GETPOST('format', 'aZ09'):'html')); + $doleditor = new DolEditor('editfilecontent', $content, '', '300', 'Full', 'In', true, false, 'ace', 0, '99%'); + print $doleditor->Create(1, '', false, $langs->trans("File").' : '.$file, (GETPOST('format', 'aZ09') ?GETPOST('format', 'aZ09') : 'html')); print '
    '; print '
    '; print ''; @@ -3279,20 +3279,20 @@ elseif (! empty($module)) $clifiles = array(); $i = 0; - $dircli=array('/'.strtolower($module).'/scripts'); + $dircli = array('/'.strtolower($module).'/scripts'); - foreach($dircli as $reldir) + foreach ($dircli as $reldir) { - $dir=dol_buildpath($reldir, 0); - $newdir=dol_osencode($dir); + $dir = dol_buildpath($reldir, 0); + $newdir = dol_osencode($dir); // Check if directory exists (we do not use dol_is_dir to avoid loading files.lib.php at each call) - if (! is_dir($newdir)) continue; + if (!is_dir($newdir)) continue; - $handle=opendir($newdir); + $handle = opendir($newdir); if (is_resource($handle)) { - while (($tmpfile = readdir($handle))!==false) + while (($tmpfile = readdir($handle)) !== false) { if (is_readable($newdir.'/'.$file) && preg_match('/^(.+)\.php/', $tmpfile, $reg)) { @@ -3313,7 +3313,7 @@ elseif (! empty($module)) print '
    '; print '
    '; - if (! empty($clifiles)) + if (!empty($clifiles)) { foreach ($clifiles as $clifile) { @@ -3335,7 +3335,7 @@ elseif (! empty($module)) } else { - $fullpathoffile=dol_buildpath($file, 0); + $fullpathoffile = dol_buildpath($file, 0); $content = file_get_contents($fullpathoffile); @@ -3347,8 +3347,8 @@ elseif (! empty($module)) print ''; print ''; - $doleditor=new DolEditor('editfilecontent', $content, '', '300', 'Full', 'In', true, false, 'ace', 0, '99%'); - print $doleditor->Create(1, '', false, $langs->trans("File").' : '.$file, (GETPOST('format', 'aZ09')?GETPOST('format', 'aZ09'):'html')); + $doleditor = new DolEditor('editfilecontent', $content, '', '300', 'Full', 'In', true, false, 'ace', 0, '99%'); + print $doleditor->Create(1, '', false, $langs->trans("File").' : '.$file, (GETPOST('format', 'aZ09') ?GETPOST('format', 'aZ09') : 'html')); print '
    '; print '
    '; print ''; @@ -3407,31 +3407,31 @@ elseif (! empty($module)) print ''; print '
    '; print ''; print ''; print ''; print ''; @@ -3457,7 +3457,7 @@ elseif (! empty($module)) } else { - $fullpathoffile=dol_buildpath($file, 0); + $fullpathoffile = dol_buildpath($file, 0); $content = file_get_contents($fullpathoffile); @@ -3469,8 +3469,8 @@ elseif (! empty($module)) print ''; print ''; - $doleditor=new DolEditor('editfilecontent', $content, '', '300', 'Full', 'In', true, false, 'ace', 0, '99%'); - print $doleditor->Create(1, '', false, $langs->trans("File").' : '.$file, (GETPOST('format', 'aZ09')?GETPOST('format', 'aZ09'):'html')); + $doleditor = new DolEditor('editfilecontent', $content, '', '300', 'Full', 'In', true, false, 'ace', 0, '99%'); + print $doleditor->Create(1, '', false, $langs->trans("File").' : '.$file, (GETPOST('format', 'aZ09') ?GETPOST('format', 'aZ09') : 'html')); print '
    '; print '
    '; print ''; @@ -3484,7 +3484,7 @@ elseif (! empty($module)) if ($tab == 'specifications') { - $specs=dol_dir_list(dol_buildpath($modulelowercase.'/doc', 0), 'files', 1, '(\.md|\.asciidoc)$', array('\/temp\/')); + $specs = dol_dir_list(dol_buildpath($modulelowercase.'/doc', 0), 'files', 1, '(\.md|\.asciidoc)$', array('\/temp\/')); if ($action != 'editfile' || empty($file)) { @@ -3492,13 +3492,13 @@ elseif (! empty($module)) print '
    '; print '
    '; - if ($cron['jobtype']=='method') + if ($cron['jobtype'] == 'method') { - $text=$langs->trans("CronClass"); - $texttoshow=$langs->trans('CronModule').': '.$module.'
    '; - $texttoshow.=$langs->trans('CronClass').': '. $cron['class'].'
    '; - $texttoshow.=$langs->trans('CronObject').': '. $cron['objectname'].'
    '; - $texttoshow.=$langs->trans('CronMethod').': '. $cron['method']; - $texttoshow.='
    '.$langs->trans('CronArgs').': '. $cron['parameters']; - $texttoshow.='
    '.$langs->trans('Comment').': '. $langs->trans($cron['comment']); + $text = $langs->trans("CronClass"); + $texttoshow = $langs->trans('CronModule').': '.$module.'
    '; + $texttoshow .= $langs->trans('CronClass').': '.$cron['class'].'
    '; + $texttoshow .= $langs->trans('CronObject').': '.$cron['objectname'].'
    '; + $texttoshow .= $langs->trans('CronMethod').': '.$cron['method']; + $texttoshow .= '
    '.$langs->trans('CronArgs').': '.$cron['parameters']; + $texttoshow .= '
    '.$langs->trans('Comment').': '.$langs->trans($cron['comment']); } - elseif ($cron['jobtype']=='command') + elseif ($cron['jobtype'] == 'command') { - $text=$langs->trans('CronCommand'); - $texttoshow=$langs->trans('CronCommand').': '.dol_trunc($cron['command']); - $texttoshow.='
    '.$langs->trans('CronArgs').': '. $cron['parameters']; - $texttoshow.='
    '.$langs->trans('Comment').': '. $langs->trans($cron['comment']); + $text = $langs->trans('CronCommand'); + $texttoshow = $langs->trans('CronCommand').': '.dol_trunc($cron['command']); + $texttoshow .= '
    '.$langs->trans('CronArgs').': '.$cron['parameters']; + $texttoshow .= '
    '.$langs->trans('Comment').': '.$langs->trans($cron['comment']); } print $form->textwithpicto($text, $texttoshow, 1); print '
    '; - if($cron['unitfrequency'] == "60") print $langs->trans('CronEach')." ".($cron['frequency'])." ".$langs->trans('Minutes'); - if($cron['unitfrequency'] == "3600") print $langs->trans('CronEach')." ".($cron['frequency'])." ".$langs->trans('Hours'); - if($cron['unitfrequency'] == "86400") print $langs->trans('CronEach')." ".($cron['frequency'])." ".$langs->trans('Days'); - if($cron['unitfrequency'] == "604800") print $langs->trans('CronEach')." ".($cron['frequency'])." ".$langs->trans('Weeks'); + if ($cron['unitfrequency'] == "60") print $langs->trans('CronEach')." ".($cron['frequency'])." ".$langs->trans('Minutes'); + if ($cron['unitfrequency'] == "3600") print $langs->trans('CronEach')." ".($cron['frequency'])." ".$langs->trans('Hours'); + if ($cron['unitfrequency'] == "86400") print $langs->trans('CronEach')." ".($cron['frequency'])." ".$langs->trans('Days'); + if ($cron['unitfrequency'] == "604800") print $langs->trans('CronEach')." ".($cron['frequency'])." ".$langs->trans('Weeks'); print ''; @@ -3439,7 +3439,7 @@ elseif (! empty($module)) print ''; - if (!empty($cron['comment'])) {print $cron['comment'];} + if (!empty($cron['comment'])) {print $cron['comment']; } print '
    '; - if (is_array($specs) && ! empty($specs)) + if (is_array($specs) && !empty($specs)) { foreach ($specs as $spec) { $pathtofile = $modulelowercase.'/doc/'.$spec['relativename']; - $format='asciidoc'; - if (preg_match('/\.md$/i', $spec['name'])) $format='markdown'; + $format = 'asciidoc'; + if (preg_match('/\.md$/i', $spec['name'])) $format = 'markdown'; print ''; @@ -3521,7 +3521,7 @@ elseif (! empty($module)) //print $langs->trans("UseAsciiDocFormat").'
    '; - $fullpathoffile=dol_buildpath($file, 0); + $fullpathoffile = dol_buildpath($file, 0); $content = file_get_contents($fullpathoffile); @@ -3533,8 +3533,8 @@ elseif (! empty($module)) print ''; print ''; - $doleditor=new DolEditor('editfilecontent', $content, '', '300', 'Full', 'In', true, false, 'ace', 0, '99%'); - print $doleditor->Create(1, '', false, $langs->trans("File").' : '.$file, (GETPOST('format', 'aZ09')?GETPOST('format', 'aZ09'):'html')); + $doleditor = new DolEditor('editfilecontent', $content, '', '300', 'Full', 'In', true, false, 'ace', 0, '99%'); + print $doleditor->Create(1, '', false, $langs->trans("File").' : '.$file, (GETPOST('format', 'aZ09') ?GETPOST('format', 'aZ09') : 'html')); print '
    '; print '
    '; print ''; @@ -3547,16 +3547,16 @@ elseif (! empty($module)) print '


    '; - $FILENAMEDOC=$modulelowercase.'.html'; - $FILENAMEDOCPDF=$modulelowercase.'.pdf'; + $FILENAMEDOC = $modulelowercase.'.html'; + $FILENAMEDOCPDF = $modulelowercase.'.pdf'; $outputfiledoc = dol_buildpath($modulelowercase, 0).'/doc/'.$FILENAMEDOC; $outputfiledocurl = dol_buildpath($modulelowercase, 1).'/doc/'.$FILENAMEDOC; $outputfiledocpdf = dol_buildpath($modulelowercase, 0).'/doc/'.$FILENAMEDOCPDF; $outputfiledocurlpdf = dol_buildpath($modulelowercase, 1).'/doc/'.$FILENAMEDOCPDF; // HTML - print ' '. $langs->trans("PathToModuleDocumentation", "HTML") . ' : '; - if (! dol_is_file($outputfiledoc)) print ''.$langs->trans("FileNotYetGenerated").''; + print ' '.$langs->trans("PathToModuleDocumentation", "HTML").' : '; + if (!dol_is_file($outputfiledoc)) print ''.$langs->trans("FileNotYetGenerated").''; else { print ''; print ''; @@ -3568,8 +3568,8 @@ elseif (! empty($module)) print '
    '; // PDF - print ' '. $langs->trans("PathToModuleDocumentation", "PDF") . ' : '; - if (! dol_is_file($outputfiledocpdf)) print ''.$langs->trans("FileNotYetGenerated").''; + print ' '.$langs->trans("PathToModuleDocumentation", "PDF").' : '; + if (!dol_is_file($outputfiledocpdf)) print ''.$langs->trans("FileNotYetGenerated").''; else { print ''; print '
    '; @@ -3633,17 +3633,17 @@ elseif (! empty($module)) exit; } - $arrayversion=explode('.', $moduleobj->version, 3); + $arrayversion = explode('.', $moduleobj->version, 3); if (count($arrayversion)) { - $FILENAMEZIP="module_".$modulelowercase.'-'.$arrayversion[0].'.'.$arrayversion[1].($arrayversion[2]?".".$arrayversion[2]:"").".zip"; + $FILENAMEZIP = "module_".$modulelowercase.'-'.$arrayversion[0].'.'.$arrayversion[1].($arrayversion[2] ? ".".$arrayversion[2] : "").".zip"; $outputfilezip = dol_buildpath($modulelowercase, 0).'/bin/'.$FILENAMEZIP; } print '
    '; - print ' '. $langs->trans("PathToModulePackage") . ' : '; - if (! dol_is_file($outputfilezip)) print ''.$langs->trans("FileNotYetGenerated").''; + print ' '.$langs->trans("PathToModulePackage").' : '; + if (!dol_is_file($outputfilezip)) print ''.$langs->trans("FileNotYetGenerated").''; else { $relativepath = $modulelowercase.'/bin/'.$FILENAMEZIP; print '
    '.$outputfilezip.''; diff --git a/htdocs/modulebuilder/template/admin/setup.php b/htdocs/modulebuilder/template/admin/setup.php index 8534e6e5cbd..56e7865a346 100644 --- a/htdocs/modulebuilder/template/admin/setup.php +++ b/htdocs/modulebuilder/template/admin/setup.php @@ -23,23 +23,23 @@ */ // Load Dolibarr environment -$res=0; +$res = 0; // Try main.inc.php into web root known defined into CONTEXT_DOCUMENT_ROOT (not always defined) -if (! $res && ! empty($_SERVER["CONTEXT_DOCUMENT_ROOT"])) $res=@include $_SERVER["CONTEXT_DOCUMENT_ROOT"]."/main.inc.php"; +if (!$res && !empty($_SERVER["CONTEXT_DOCUMENT_ROOT"])) $res = @include $_SERVER["CONTEXT_DOCUMENT_ROOT"]."/main.inc.php"; // Try main.inc.php into web root detected using web root calculated from SCRIPT_FILENAME -$tmp=empty($_SERVER['SCRIPT_FILENAME'])?'':$_SERVER['SCRIPT_FILENAME'];$tmp2=realpath(__FILE__); $i=strlen($tmp)-1; $j=strlen($tmp2)-1; -while($i > 0 && $j > 0 && isset($tmp[$i]) && isset($tmp2[$j]) && $tmp[$i]==$tmp2[$j]) { $i--; $j--; } -if (! $res && $i > 0 && file_exists(substr($tmp, 0, ($i+1))."/main.inc.php")) $res=@include substr($tmp, 0, ($i+1))."/main.inc.php"; -if (! $res && $i > 0 && file_exists(dirname(substr($tmp, 0, ($i+1)))."/main.inc.php")) $res=@include dirname(substr($tmp, 0, ($i+1)))."/main.inc.php"; +$tmp = empty($_SERVER['SCRIPT_FILENAME']) ? '' : $_SERVER['SCRIPT_FILENAME']; $tmp2 = realpath(__FILE__); $i = strlen($tmp) - 1; $j = strlen($tmp2) - 1; +while ($i > 0 && $j > 0 && isset($tmp[$i]) && isset($tmp2[$j]) && $tmp[$i] == $tmp2[$j]) { $i--; $j--; } +if (!$res && $i > 0 && file_exists(substr($tmp, 0, ($i + 1))."/main.inc.php")) $res = @include substr($tmp, 0, ($i + 1))."/main.inc.php"; +if (!$res && $i > 0 && file_exists(dirname(substr($tmp, 0, ($i + 1)))."/main.inc.php")) $res = @include dirname(substr($tmp, 0, ($i + 1)))."/main.inc.php"; // Try main.inc.php using relative path -if (! $res && file_exists("../../main.inc.php")) $res=@include "../../main.inc.php"; -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 && file_exists("../../../main.inc.php")) $res = @include "../../../main.inc.php"; +if (!$res) die("Include of main fails"); global $langs, $user; // Libraries -require_once DOL_DOCUMENT_ROOT . "/core/lib/admin.lib.php"; +require_once DOL_DOCUMENT_ROOT."/core/lib/admin.lib.php"; require_once '../lib/mymodule.lib.php'; //require_once "../class/myclass.class.php"; @@ -47,15 +47,15 @@ require_once '../lib/mymodule.lib.php'; $langs->loadLangs(array("admin", "mymodule@mymodule")); // Access control -if (! $user->admin) accessforbidden(); +if (!$user->admin) accessforbidden(); // Parameters $action = GETPOST('action', 'alpha'); $backtopage = GETPOST('backtopage', 'alpha'); -$arrayofparameters=array( - 'MYMODULE_MYPARAM1'=>array('css'=>'minwidth200','enabled'=>1), - 'MYMODULE_MYPARAM2'=>array('css'=>'minwidth500','enabled'=>1) +$arrayofparameters = array( + 'MYMODULE_MYPARAM1'=>array('css'=>'minwidth200', 'enabled'=>1), + 'MYMODULE_MYPARAM2'=>array('css'=>'minwidth500', 'enabled'=>1) ); @@ -79,7 +79,7 @@ $page_name = "MyModuleSetup"; llxHeader('', $langs->trans($page_name)); // Subheader -$linkback = ''.$langs->trans("BackToModuleList").''; +$linkback = ''.$langs->trans("BackToModuleList").''; print load_fiche_titre($langs->trans($page_name), $linkback, 'object_mymodule@mymodule'); @@ -97,15 +97,15 @@ if ($action == 'edit') print ''; print ''; - print '
    '; print ' '.$langs->trans("SpecificationFile").' : '.$pathtofile.''; print ''.img_picto($langs->trans("Edit"), 'edit').'
    '; + print '
    '; print ''; - foreach($arrayofparameters as $key => $val) + foreach ($arrayofparameters as $key => $val) { print ''; + print ''; } print '
    '.$langs->trans("Parameter").''.$langs->trans("Value").'
    '; $tooltiphelp = (($langs->trans($key.'Tooltip') != $key.'Tooltip') ? $langs->trans($key.'Tooltip') : ''); print $form->textwithpicto($langs->trans($key), $tooltiphelp); - print '
    '; @@ -118,17 +118,17 @@ if ($action == 'edit') } else { - if (! empty($arrayofparameters)) + if (!empty($arrayofparameters)) { print ''; print ''; - foreach($arrayofparameters as $key => $val) + foreach ($arrayofparameters as $key => $val) { print ''; + print ''; } print '
    '.$langs->trans("Parameter").''.$langs->trans("Value").'
    '; $tooltiphelp = (($langs->trans($key.'Tooltip') != $key.'Tooltip') ? $langs->trans($key.'Tooltip') : ''); print $form->textwithpicto($langs->trans($key), $tooltiphelp); - print '' . $conf->global->$key . '
    '.$conf->global->$key.'
    '; diff --git a/htdocs/modulebuilder/template/class/myobject.class.php b/htdocs/modulebuilder/template/class/myobject.class.php index 3c3858a7a84..bb9f8eda4e0 100644 --- a/htdocs/modulebuilder/template/class/myobject.class.php +++ b/htdocs/modulebuilder/template/class/myobject.class.php @@ -23,7 +23,7 @@ */ // Put here all includes required by your class file -require_once DOL_DOCUMENT_ROOT . '/core/class/commonobject.class.php'; +require_once DOL_DOCUMENT_ROOT.'/core/class/commonobject.class.php'; //require_once DOL_DOCUMENT_ROOT . '/societe/class/societe.class.php'; //require_once DOL_DOCUMENT_ROOT . '/product/class/product.class.php'; @@ -64,7 +64,7 @@ class MyObject extends CommonObject /** - * 'type' if the field format ('integer', 'integer:ObjectClass:PathToClass[:AddCreateButtonOrNot[:Filter]]', 'varchar(x)', 'double(24,8)', 'text', 'html', 'datetime', 'timestamp', 'float') + * 'type' if the field format ('integer', 'integer:ObjectClass:PathToClass[:AddCreateButtonOrNot[:Filter]]', 'varchar(x)', 'double(24,8)', 'real', 'price', 'text', 'html', 'date', 'datetime', 'timestamp', 'duration', 'mail', 'phone', 'url', 'password') * Note: Filter can be a string like "(t.ref:like:'SO-%') or (t.date_creation:<:'20160101') or (t.nature:is:NULL)" * 'label' the translation key. * 'enabled' is a condition when the field must be managed. @@ -89,27 +89,27 @@ class MyObject extends CommonObject /** * @var array Array with all fields and their property. Do not use it as a static var. It may be modified by constructor. */ - public $fields=array( - 'rowid' =>array('type'=>'integer', 'label'=>'TechnicalID', 'enabled'=>1, 'visible'=>-2, 'noteditable'=>1, 'notnull'=> 1, 'index'=>1, 'position'=>1, 'comment'=>'Id'), - 'ref' =>array('type'=>'varchar(128)', 'label'=>'Ref', 'enabled'=>1, 'visible'=>1, 'noteditable'=>0, 'default'=>'', 'notnull'=> 1, 'showoncombobox'=>1, 'index'=>1, 'position'=>10, 'searchall'=>1, 'comment'=>'Reference of object'), - 'entity' =>array('type'=>'integer', 'label'=>'Entity', 'enabled'=>1, 'visible'=>0, 'notnull'=> 1, 'default'=>1, 'index'=>1, 'position'=>20), - 'label' =>array('type'=>'varchar(255)', 'label'=>'Label', 'enabled'=>1, 'visible'=>1, 'position'=>30, 'searchall'=>1, 'css'=>'minwidth200', 'help'=>'Help text', 'showoncombobox'=>1), - 'amount' =>array('type'=>'double(24,8)', 'label'=>'Amount', 'enabled'=>1, 'visible'=>1, 'default'=>'null', 'position'=>40, 'searchall'=>0, 'isameasure'=>1, 'help'=>'Help text for amount'), - 'qty' =>array('type'=>'real', 'label'=>'Qty', 'enabled'=>1, 'visible'=>1, 'default'=>'0', 'position'=>45, 'searchall'=>0, 'isameasure'=>1, 'help'=>'Help text for quantity', 'css'=>'maxwidth75imp'), + public $fields = array( + 'rowid' =>array('type'=>'integer', 'label'=>'TechnicalID', 'enabled'=>1, 'visible'=>-2, 'noteditable'=>1, 'notnull'=> 1, 'index'=>1, 'position'=>1, 'comment'=>'Id'), + 'ref' =>array('type'=>'varchar(128)', 'label'=>'Ref', 'enabled'=>1, 'visible'=>1, 'noteditable'=>0, 'default'=>'', 'notnull'=> 1, 'showoncombobox'=>1, 'index'=>1, 'position'=>10, 'searchall'=>1, 'comment'=>'Reference of object'), + 'entity' =>array('type'=>'integer', 'label'=>'Entity', 'enabled'=>1, 'visible'=>0, 'notnull'=> 1, 'default'=>1, 'index'=>1, 'position'=>20), + 'label' =>array('type'=>'varchar(255)', 'label'=>'Label', 'enabled'=>1, 'visible'=>1, 'position'=>30, 'searchall'=>1, 'css'=>'minwidth200', 'help'=>'Help text', 'showoncombobox'=>1), + 'amount' =>array('type'=>'price', 'label'=>'Amount', 'enabled'=>1, 'visible'=>1, 'default'=>'null', 'position'=>40, 'searchall'=>0, 'isameasure'=>1, 'help'=>'Help text for amount'), + 'qty' =>array('type'=>'real', 'label'=>'Qty', 'enabled'=>1, 'visible'=>1, 'default'=>'0', 'position'=>45, 'searchall'=>0, 'isameasure'=>1, 'help'=>'Help text for quantity', 'css'=>'maxwidth75imp'), 'fk_soc' =>array('type'=>'integer:Societe:societe/class/societe.class.php:1:status=1 AND entity IN (__SHARED_ENTITIES__)', 'label'=>'ThirdParty', 'visible'=> 1, 'enabled'=>1, 'position'=>50, 'notnull'=>-1, 'index'=>1, 'help'=>'LinkToThirparty'), 'fk_project' =>array('type'=>'integer:Project:projet/class/project.class.php:1', 'label'=>'Project', 'enabled'=>1, 'visible'=>-1, 'position'=>52, 'notnull'=>-1, 'index'=>1), - 'description' =>array('type'=>'text', 'label'=>'Description', 'enabled'=>1, 'visible'=>3, 'position'=>60), - 'note_public' =>array('type'=>'html', 'label'=>'NotePublic', 'enabled'=>1, 'visible'=>0, 'position'=>61), - 'note_private' =>array('type'=>'html', 'label'=>'NotePrivate', 'enabled'=>1, 'visible'=>0, 'position'=>62), - 'date_creation' =>array('type'=>'datetime', 'label'=>'DateCreation', 'enabled'=>1, 'visible'=>-2, 'notnull'=> 1, 'position'=>500), - 'tms' =>array('type'=>'timestamp', 'label'=>'DateModification', 'enabled'=>1, 'visible'=>-2, 'notnull'=> 0, 'position'=>501), + 'description' =>array('type'=>'text', 'label'=>'Description', 'enabled'=>1, 'visible'=>3, 'position'=>60), + 'note_public' =>array('type'=>'html', 'label'=>'NotePublic', 'enabled'=>1, 'visible'=>0, 'position'=>61), + 'note_private' =>array('type'=>'html', 'label'=>'NotePrivate', 'enabled'=>1, 'visible'=>0, 'position'=>62), + 'date_creation' =>array('type'=>'datetime', 'label'=>'DateCreation', 'enabled'=>1, 'visible'=>-2, 'notnull'=> 1, 'position'=>500), + 'tms' =>array('type'=>'timestamp', 'label'=>'DateModification', 'enabled'=>1, 'visible'=>-2, 'notnull'=> 0, 'position'=>501), //'date_validation' =>array('type'=>'datetime', 'label'=>'DateCreation', 'enabled'=>1, 'visible'=>-2, 'position'=>502), - 'fk_user_creat' =>array('type'=>'integer:User:user/class/user.class.php', 'label'=>'UserAuthor', 'enabled'=>1, 'visible'=>-2, 'notnull'=> 1, 'position'=>510, 'foreignkey'=>'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_creat' =>array('type'=>'integer:User:user/class/user.class.php', 'label'=>'UserAuthor', 'enabled'=>1, 'visible'=>-2, 'notnull'=> 1, 'position'=>510, 'foreignkey'=>'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_valid' =>array('type'=>'integer:User:user/class/user.class.php', 'label'=>'UserValidation', 'enabled'=>1, 'visible'=>-1, 'position'=>512), - 'import_key' =>array('type'=>'varchar(14)', 'label'=>'ImportId', 'enabled'=>1, 'visible'=>-2, 'notnull'=>-1, 'index'=>0, 'position'=>1000), - 'model_pdf' =>array('type'=>'varchar(255)', 'label'=>'Model pdf', 'enabled'=>1, 'visible'=>0, 'notnull'=>-1, 'position'=>1010), - 'status' =>array('type'=>'smallint', 'label'=>'Status', 'enabled'=>1, 'visible'=>1, 'notnull'=> 1, 'default'=>0, 'index'=>1, 'position'=>1000, 'arrayofkeyval'=>array(0=>'Draft', 1=>'Validated', 9=>'Canceled')), + 'import_key' =>array('type'=>'varchar(14)', 'label'=>'ImportId', 'enabled'=>1, 'visible'=>-2, 'notnull'=>-1, 'index'=>0, 'position'=>1000), + 'model_pdf' =>array('type'=>'varchar(255)', 'label'=>'Model pdf', 'enabled'=>1, 'visible'=>0, 'notnull'=>-1, 'position'=>1010), + 'status' =>array('type'=>'smallint', 'label'=>'Status', 'enabled'=>1, 'visible'=>1, 'notnull'=> 1, 'default'=>0, 'index'=>1, 'position'=>1000, 'arrayofkeyval'=>array(0=>'Draft', 1=>'Validated', 9=>'Canceled')), ); /** @@ -214,11 +214,11 @@ class MyObject 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) + foreach ($this->fields as $key => $val) { if (isset($val['enabled']) && empty($val['enabled'])) { @@ -227,13 +227,16 @@ class MyObject extends CommonObject } // Translate some data of arrayofkeyval - foreach($this->fields as $key => $val) + if (is_object($langs)) { - if (is_array($val['arrayofkeyval'])) + foreach($this->fields as $key => $val) { - foreach($val['arrayofkeyval'] as $key2 => $val2) + if (is_array($val['arrayofkeyval'])) { - $this->fields[$key]['arrayofkeyval'][$key2]=$langs->trans($val2); + foreach($val['arrayofkeyval'] as $key2 => $val2) + { + $this->fields[$key]['arrayofkeyval'][$key2]=$langs->trans($val2); + } } } } @@ -271,7 +274,7 @@ class MyObject 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($this->lines as $line) @@ -284,18 +287,18 @@ class MyObject extends CommonObject // Clear fields - $object->ref = empty($this->fields['ref']['default']) ? "copy_of_".$object->ref: $this->fields['ref']['default']; - $object->label = empty($this->fields['label']['default']) ? $langs->trans("CopyOf")." ".$object->label: $this->fields['label']['default']; + $object->ref = empty($this->fields['ref']['default']) ? "copy_of_".$object->ref : $this->fields['ref']['default']; + $object->label = empty($this->fields['label']['default']) ? $langs->trans("CopyOf")." ".$object->label : $this->fields['label']['default']; $object->status = self::STATUS_DRAFT; // ... // Clear extrafields that are unique if (is_array($object->array_options) && count($object->array_options) > 0) { $extrafields->fetch_name_optionals_label($this->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]); @@ -312,7 +315,7 @@ class MyObject extends CommonObject $this->errors = $object->errors; } - if (! $error) + if (!$error) { // copy internal contacts if ($this->copy_linked_contact($object, 'internal') < 0) @@ -321,7 +324,7 @@ class MyObject extends CommonObject } } - if (! $error) + if (!$error) { // copy external contacts if same company if (property_exists($this, 'socid') && $this->socid == $object->socid) @@ -353,7 +356,7 @@ class MyObject extends CommonObject public function fetch($id, $ref = null) { $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(); return $result; } @@ -364,7 +367,7 @@ class MyObject extends CommonObject */ public function fetchLines() { - $this->lines=array(); + $this->lines = array(); $result = $this->fetchLinesCommon(); return $result; @@ -388,40 +391,40 @@ class MyObject extends CommonObject dol_syslog(__METHOD__, LOG_DEBUG); - $records=array(); + $records = array(); $sql = 'SELECT '; $sql .= $this->getFieldList(); - $sql .= ' FROM ' . MAIN_DB_PREFIX . $this->table_element. ' as t'; + $sql .= ' FROM '.MAIN_DB_PREFIX.$this->table_element.' as t'; if (isset($this->ismultientitymanaged) && $this->ismultientitymanaged == 1) $sql .= ' WHERE t.entity IN ('.getEntity($this->table_element).')'; else $sql .= ' WHERE 1 = 1'; // Manage filter $sqlwhere = array(); if (count($filter) > 0) { foreach ($filter as $key => $value) { - if ($key=='t.rowid') { - $sqlwhere[] = $key . '='. $value; + if ($key == 't.rowid') { + $sqlwhere[] = $key.'='.$value; } elseif (strpos($key, 'date') !== false) { $sqlwhere[] = $key.' = \''.$this->db->idate($value).'\''; } - elseif ($key=='customsql') { + elseif ($key == 'customsql') { $sqlwhere[] = $value; } else { - $sqlwhere[] = $key . ' LIKE \'%' . $this->db->escape($value) . '%\''; + $sqlwhere[] = $key.' LIKE \'%'.$this->db->escape($value).'%\''; } } } if (count($sqlwhere) > 0) { - $sql .= ' AND (' . implode(' '.$filtermode.' ', $sqlwhere).')'; + $sql .= ' AND ('.implode(' '.$filtermode.' ', $sqlwhere).')'; } if (!empty($sortfield)) { $sql .= $this->db->order($sortfield, $sortorder); } if (!empty($limit)) { - $sql .= ' ' . $this->db->plimit($limit, $offset); + $sql .= ' '.$this->db->plimit($limit, $offset); } $resql = $this->db->query($sql); @@ -443,8 +446,8 @@ class MyObject extends CommonObject return $records; } else { - $this->errors[] = 'Error ' . $this->db->lasterror(); - dol_syslog(__METHOD__ . ' ' . join(',', $this->errors), LOG_ERR); + $this->errors[] = 'Error '.$this->db->lasterror(); + dol_syslog(__METHOD__.' '.join(',', $this->errors), LOG_ERR); return -1; } @@ -584,51 +587,51 @@ class MyObject extends CommonObject { global $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 = ''; - $label = '' . $langs->trans("MyObject") . ''; - $label.= '
    '; - $label.= '' . $langs->trans('Ref') . ': ' . $this->ref; + $label = ''.$langs->trans("MyObject").''; + $label .= '
    '; + $label .= ''.$langs->trans('Ref').': '.$this->ref; $url = dol_buildpath('/mymodule/myobject_card.php', 1).'?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'; + $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=''; + $linkclose = ''; if (empty($notooltip)) { - if (! empty($conf->global->MAIN_OPTIMIZEFORTEXTBROWSER)) + if (!empty($conf->global->MAIN_OPTIMIZEFORTEXTBROWSER)) { - $label=$langs->trans("ShowMyObject"); - $linkclose.=' alt="'.dol_escape_htmltag($label, 1).'"'; + $label = $langs->trans("ShowMyObject"); + $linkclose .= ' alt="'.dol_escape_htmltag($label, 1).'"'; } - $linkclose.=' title="'.dol_escape_htmltag($label, 1).'"'; - $linkclose.=' class="classfortooltip'.($morecss?' '.$morecss:'').'"'; + $linkclose .= ' title="'.dol_escape_htmltag($label, 1).'"'; + $linkclose .= ' class="classfortooltip'.($morecss ? ' '.$morecss : '').'"'; } - else $linkclose = ($morecss?' class="'.$morecss.'"':''); + else $linkclose = ($morecss ? ' class="'.$morecss.'"' : ''); $linkstart = ''; - $linkend=''; + $linkstart .= $linkclose.'>'; + $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)) : ''); - global $action,$hookmanager; + global $action, $hookmanager; $hookmanager->initHooks(array('myobjectdao')); - $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 + $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; @@ -684,10 +687,10 @@ class MyObject extends CommonObject public function info($id) { $sql = 'SELECT rowid, date_creation as datec, tms as datem,'; - $sql.= ' fk_user_creat, fk_user_modif'; - $sql.= ' FROM '.MAIN_DB_PREFIX.$this->table_element.' as t'; - $sql.= ' WHERE t.rowid = '.$id; - $result=$this->db->query($sql); + $sql .= ' fk_user_creat, fk_user_modif'; + $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)) @@ -698,7 +701,7 @@ class MyObject extends CommonObject { $cuser = new User($this->db); $cuser->fetch($obj->fk_user_author); - $this->user_creation = $cuser; + $this->user_creation = $cuser; } if ($obj->fk_user_valid) @@ -712,7 +715,7 @@ class MyObject extends CommonObject { $cluser = new User($this->db); $cluser->fetch($obj->fk_user_cloture); - $this->user_cloture = $cluser; + $this->user_cloture = $cluser; } $this->date_creation = $this->db->jdate($obj->datec); @@ -746,7 +749,7 @@ class MyObject extends CommonObject */ public function getLinesArray() { - $this->lines=array(); + $this->lines = array(); $objectline = new MyObjectLine($this->db); $result = $objectline->fetchAll('ASC', 'position', 0, 0, array('customsql'=>'fk_myobject = '.$this->id)); @@ -777,16 +780,16 @@ class MyObject extends CommonObject */ public function generateDocument($modele, $outputlangs, $hidedetails = 0, $hidedesc = 0, $hideref = 0, $moreparams = null) { - global $conf,$langs; + global $conf, $langs; $langs->load("mymodule@mymodule"); - if (! dol_strlen($modele)) { + if (!dol_strlen($modele)) { $modele = 'standard'; if ($this->modelpdf) { $modele = $this->modelpdf; - } elseif (! empty($conf->global->MYOBJECT_ADDON_PDF)) { + } elseif (!empty($conf->global->MYOBJECT_ADDON_PDF)) { $modele = $conf->global->MYOBJECT_ADDON_PDF; } } @@ -811,7 +814,7 @@ class MyObject extends CommonObject $error = 0; $this->output = ''; - $this->error=''; + $this->error = ''; dol_syslog(__METHOD__, LOG_DEBUG); diff --git a/htdocs/modulebuilder/template/core/modules/modMyModule.class.php b/htdocs/modulebuilder/template/core/modules/modMyModule.class.php index 86eb50aff9e..7cabc1415ef 100644 --- a/htdocs/modulebuilder/template/core/modules/modMyModule.class.php +++ b/htdocs/modulebuilder/template/core/modules/modMyModule.class.php @@ -26,7 +26,7 @@ * \ingroup mymodule * \brief Description and activation file for module MyModule */ -include_once DOL_DOCUMENT_ROOT .'/core/modules/DolibarrModules.class.php'; +include_once DOL_DOCUMENT_ROOT.'/core/modules/DolibarrModules.class.php'; /** * Description and activation class for module MyModule @@ -40,7 +40,7 @@ class modMyModule extends DolibarrModules */ public function __construct($db) { - global $langs,$conf; + global $langs, $conf; $this->db = $db; // Id for module (must be unique). @@ -73,7 +73,7 @@ class modMyModule extends DolibarrModules // Name of image file used for this module. // If file is in theme/yourtheme/img directory under name object_pictovalue.png, use this->picto='pictovalue' // If file is in module/img directory under name object_pictovalue.png, use this->picto='pictovalue@module' - $this->picto='generic'; + $this->picto = 'generic'; // Define some features supported by module (triggers, login, substitutions, menus, css, etc...) $this->module_parts = array( // Set this to 1 if module has its own trigger directory (core/triggers) @@ -121,13 +121,13 @@ class modMyModule extends DolibarrModules $this->hidden = false; // List of module class names as string that must be enabled if this module is enabled. Example: array('always1'=>'modModuleToEnable1','always2'=>'modModuleToEnable2', 'FR1'=>'modModuleToEnableFR'...) $this->depends = array(); - $this->requiredby = array(); // List of module class names as string to disable if this one is disabled. Example: array('modModuleToDisable1', ...) - $this->conflictwith = array(); // List of module class names as string this module is in conflict with. Example: array('modModuleToDisable1', ...) + $this->requiredby = array(); // List of module class names as string to disable if this one is disabled. Example: array('modModuleToDisable1', ...) + $this->conflictwith = array(); // List of module class names as string this module is in conflict with. Example: array('modModuleToDisable1', ...) $this->langfiles = array("mymodule@mymodule"); - $this->phpmin = array(5,5); // Minimum version of PHP required by module - $this->need_dolibarr_version = array(11,-3); // Minimum version of Dolibarr required by module - $this->warnings_activation = array(); // Warning to show when we activate module. array('always'='text') or array('FR'='textfr','ES'='textes'...) - $this->warnings_activation_ext = array(); // Warning to show when we activate an external module. array('always'='text') or array('FR'='textfr','ES'='textes'...) + $this->phpmin = array(5, 5); // Minimum version of PHP required by module + $this->need_dolibarr_version = array(11, -3); // Minimum version of Dolibarr required by module + $this->warnings_activation = array(); // Warning to show when we activate module. array('always'='text') or array('FR'='textfr','ES'='textes'...) + $this->warnings_activation_ext = array(); // Warning to show when we activate an external module. array('always'='text') or array('FR'='textfr','ES'='textes'...) //$this->automatic_activation = array('FR'=>'MyModuleWasAutomaticallyActivatedBecauseOfYourCountryChoice'); //$this->always_enabled = true; // If true, can't be disabled @@ -146,9 +146,9 @@ class modMyModule extends DolibarrModules 'fr_FR:ParentCompany'=>'Maison mère ou revendeur' )*/ - if (! isset($conf->mymodule) || ! isset($conf->mymodule->enabled)) { - $conf->mymodule=new stdClass(); - $conf->mymodule->enabled=0; + if (!isset($conf->mymodule) || !isset($conf->mymodule->enabled)) { + $conf->mymodule = new stdClass(); + $conf->mymodule->enabled = 0; } // Array to add new pages in new tabs @@ -180,7 +180,7 @@ class modMyModule extends DolibarrModules // 'user' to add a tab in user view // Dictionaries - $this->dictionaries=array(); + $this->dictionaries = array(); /* Example: $this->dictionaries=array( 'langs'=>'mymodule@mymodule', @@ -241,44 +241,44 @@ class modMyModule extends DolibarrModules // Permissions provided by this module $this->rights = array(); - $r=0; + $r = 0; // Add here entries to declare new permissions /* BEGIN MODULEBUILDER PERMISSIONS */ - $this->rights[$r][0] = $this->numero + $r; // Permission id (must not be already used) - $this->rights[$r][1] = 'Read objects of MyModule'; // Permission label - $this->rights[$r][4] = 'myobject'; // In php code, permission will be checked by test if ($user->rights->mymodule->level1->level2) - $this->rights[$r][5] = 'read'; // In php code, permission will be checked by test if ($user->rights->mymodule->level1->level2) + $this->rights[$r][0] = $this->numero + $r; // Permission id (must not be already used) + $this->rights[$r][1] = 'Read objects of MyModule'; // Permission label + $this->rights[$r][4] = 'myobject'; // In php code, permission will be checked by test if ($user->rights->mymodule->level1->level2) + $this->rights[$r][5] = 'read'; // In php code, permission will be checked by test if ($user->rights->mymodule->level1->level2) $r++; - $this->rights[$r][0] = $this->numero + $r; // Permission id (must not be already used) - $this->rights[$r][1] = 'Create/Update objects of MyModule'; // Permission label - $this->rights[$r][4] = 'myobject'; // In php code, permission will be checked by test if ($user->rights->mymodule->level1->level2) - $this->rights[$r][5] = 'write'; // In php code, permission will be checked by test if ($user->rights->mymodule->level1->level2) + $this->rights[$r][0] = $this->numero + $r; // Permission id (must not be already used) + $this->rights[$r][1] = 'Create/Update objects of MyModule'; // Permission label + $this->rights[$r][4] = 'myobject'; // In php code, permission will be checked by test if ($user->rights->mymodule->level1->level2) + $this->rights[$r][5] = 'write'; // In php code, permission will be checked by test if ($user->rights->mymodule->level1->level2) $r++; - $this->rights[$r][0] = $this->numero + $r; // Permission id (must not be already used) - $this->rights[$r][1] = 'Delete objects of MyModule'; // Permission label - $this->rights[$r][4] = 'myobject'; // In php code, permission will be checked by test if ($user->rights->mymodule->level1->level2) - $this->rights[$r][5] = 'delete'; // In php code, permission will be checked by test if ($user->rights->mymodule->level1->level2) + $this->rights[$r][0] = $this->numero + $r; // Permission id (must not be already used) + $this->rights[$r][1] = 'Delete objects of MyModule'; // Permission label + $this->rights[$r][4] = 'myobject'; // In php code, permission will be checked by test if ($user->rights->mymodule->level1->level2) + $this->rights[$r][5] = 'delete'; // In php code, permission will be checked by test if ($user->rights->mymodule->level1->level2) $r++; /* END MODULEBUILDER PERMISSIONS */ // Main menu entries to add $this->menu = array(); - $r=0; + $r = 0; // Add here entries to declare new menus /* BEGIN MODULEBUILDER TOPMENU */ - $this->menu[$r++]=array( - 'fk_menu'=>'', // '' if this is a top menu. For left menu, use 'fk_mainmenu=xxx' or 'fk_mainmenu=xxx,fk_leftmenu=yyy' where xxx is mainmenucode and yyy is a leftmenucode - 'type'=>'top', // This is a Top menu entry + $this->menu[$r++] = array( + 'fk_menu'=>'', // '' if this is a top menu. For left menu, use 'fk_mainmenu=xxx' or 'fk_mainmenu=xxx,fk_leftmenu=yyy' where xxx is mainmenucode and yyy is a leftmenucode + 'type'=>'top', // This is a Top menu entry 'titre'=>'MyModule', 'mainmenu'=>'mymodule', 'leftmenu'=>'', 'url'=>'/mymodule/mymoduleindex.php', - 'langs'=>'mymodule@mymodule', // Lang file to use (without .lang) by module. File must be in langs/code_CODE/ directory. - 'position'=>1000+$r, - 'enabled'=>'$conf->mymodule->enabled', // Define condition to show or hide menu entry. Use '$conf->mymodule->enabled' if entry must be visible if module is enabled. - 'perms'=>'$user->rights->mymodule->myobject->read', // Use 'perms'=>'$user->rights->mymodule->level1->level2' if you want your menu with a permission rules + 'langs'=>'mymodule@mymodule', // Lang file to use (without .lang) by module. File must be in langs/code_CODE/ directory. + 'position'=>1000 + $r, + 'enabled'=>'$conf->mymodule->enabled', // Define condition to show or hide menu entry. Use '$conf->mymodule->enabled' if entry must be visible if module is enabled. + 'perms'=>'$user->rights->mymodule->myobject->read', // Use 'perms'=>'$user->rights->mymodule->level1->level2' if you want your menu with a permission rules 'target'=>'', - 'user'=>2, // 0=Menu for internal users, 1=external users, 2=both + 'user'=>2, // 0=Menu for internal users, 1=external users, 2=both ); /* END MODULEBUILDER TOPMENU */ /* BEGIN MODULEBUILDER LEFTMENU MYOBJECT @@ -327,7 +327,7 @@ class modMyModule extends DolibarrModules END MODULEBUILDER LEFTMENU MYOBJECT */ // Exports profiles provided by this module - $r=1; + $r = 1; /* BEGIN MODULEBUILDER EXPORT MYOBJECT */ /* $langs->load("mymodule@mymodule"); @@ -352,7 +352,7 @@ class modMyModule extends DolibarrModules /* END MODULEBUILDER EXPORT MYOBJECT */ // Imports profiles provided by this module - $r=1; + $r = 1; /* BEGIN MODULEBUILDER IMPORT MYOBJECT */ /* $langs->load("mymodule@mymodule"); @@ -384,7 +384,7 @@ class modMyModule extends DolibarrModules { global $conf, $langs; - $result=$this->_load_tables('/mymodule/sql/'); + $result = $this->_load_tables('/mymodule/sql/'); if ($result < 0) return -1; // Do not activate module if error 'not allowed' returned when loading module SQL queries (the _load_table run sql with run_sql with the error allowed parameter set to 'default') // Create extrafields during init diff --git a/htdocs/modulebuilder/template/core/modules/mymodule/doc/doc_generic_myobject_odt.modules.php b/htdocs/modulebuilder/template/core/modules/mymodule/doc/doc_generic_myobject_odt.modules.php index 822d6110c4b..69583f8c555 100644 --- a/htdocs/modulebuilder/template/core/modules/mymodule/doc/doc_generic_myobject_odt.modules.php +++ b/htdocs/modulebuilder/template/core/modules/mymodule/doc/doc_generic_myobject_odt.modules.php @@ -244,7 +244,7 @@ class doc_generic_myobject_odt extends ModelePDFMyObject } } - $dir = $conf->commande->multidir_output[$object->entity]; + $dir = $conf->commande->multidir_output[isset($object->entity)?$object->entity:1]; $objectref = dol_sanitizeFileName($object->ref); if (! preg_match('/specimen/i', $objectref)) $dir.= "/" . $objectref; $file = $dir . "/" . $objectref . ".odt"; diff --git a/htdocs/modulebuilder/template/mymoduleindex.php b/htdocs/modulebuilder/template/mymoduleindex.php index af7272d5954..99ed522e273 100644 --- a/htdocs/modulebuilder/template/mymoduleindex.php +++ b/htdocs/modulebuilder/template/mymoduleindex.php @@ -104,7 +104,7 @@ if (! empty($conf->mymodule->enabled) && $user->rights->mymodule->read) $total = 0; $num = $db->num_rows($resql); - print ''; + print '
    '; print ''; print ''; @@ -188,7 +188,7 @@ if (! empty($conf->mymodule->enabled) && $user->rights->mymodule->read) $num = $db->num_rows($resql); $i = 0; - print '
    '.$langs->trans("DraftOrders").($num?''.$num.'':'').'
    '; + print '
    '; print ''; print '
    '; if (empty($conf->global->SOCIETE_DISABLE_PROSPECTS) && empty($conf->global->SOCIETE_DISABLE_CUSTOMERS)) print $langs->trans("BoxTitleLastCustomersOrProspects",$max); diff --git a/htdocs/modulebuilder/template/myobject_agenda.php b/htdocs/modulebuilder/template/myobject_agenda.php index f75e7d352f1..4a077e35b5b 100644 --- a/htdocs/modulebuilder/template/myobject_agenda.php +++ b/htdocs/modulebuilder/template/myobject_agenda.php @@ -23,19 +23,19 @@ */ // Load Dolibarr environment -$res=0; +$res = 0; // Try main.inc.php into web root known defined into CONTEXT_DOCUMENT_ROOT (not always defined) -if (! $res && ! empty($_SERVER["CONTEXT_DOCUMENT_ROOT"])) $res=@include $_SERVER["CONTEXT_DOCUMENT_ROOT"]."/main.inc.php"; +if (!$res && !empty($_SERVER["CONTEXT_DOCUMENT_ROOT"])) $res = @include $_SERVER["CONTEXT_DOCUMENT_ROOT"]."/main.inc.php"; // Try main.inc.php into web root detected using web root calculated from SCRIPT_FILENAME -$tmp=empty($_SERVER['SCRIPT_FILENAME'])?'':$_SERVER['SCRIPT_FILENAME'];$tmp2=realpath(__FILE__); $i=strlen($tmp)-1; $j=strlen($tmp2)-1; -while($i > 0 && $j > 0 && isset($tmp[$i]) && isset($tmp2[$j]) && $tmp[$i]==$tmp2[$j]) { $i--; $j--; } -if (! $res && $i > 0 && file_exists(substr($tmp, 0, ($i+1))."/main.inc.php")) $res=@include substr($tmp, 0, ($i+1))."/main.inc.php"; -if (! $res && $i > 0 && file_exists(dirname(substr($tmp, 0, ($i+1)))."/main.inc.php")) $res=@include dirname(substr($tmp, 0, ($i+1)))."/main.inc.php"; +$tmp = empty($_SERVER['SCRIPT_FILENAME']) ? '' : $_SERVER['SCRIPT_FILENAME']; $tmp2 = realpath(__FILE__); $i = strlen($tmp) - 1; $j = strlen($tmp2) - 1; +while ($i > 0 && $j > 0 && isset($tmp[$i]) && isset($tmp2[$j]) && $tmp[$i] == $tmp2[$j]) { $i--; $j--; } +if (!$res && $i > 0 && file_exists(substr($tmp, 0, ($i + 1))."/main.inc.php")) $res = @include substr($tmp, 0, ($i + 1))."/main.inc.php"; +if (!$res && $i > 0 && file_exists(dirname(substr($tmp, 0, ($i + 1)))."/main.inc.php")) $res = @include dirname(substr($tmp, 0, ($i + 1)))."/main.inc.php"; // Try main.inc.php using relative path -if (! $res && file_exists("../main.inc.php")) $res=@include "../main.inc.php"; -if (! $res && file_exists("../../main.inc.php")) $res=@include "../../main.inc.php"; -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 && file_exists("../../main.inc.php")) $res = @include "../../main.inc.php"; +if (!$res && file_exists("../../../main.inc.php")) $res = @include "../../../main.inc.php"; +if (!$res) die("Include of main fails"); require_once DOL_DOCUMENT_ROOT.'/contact/class/contact.class.php'; require_once DOL_DOCUMENT_ROOT.'/core/lib/company.lib.php'; @@ -45,27 +45,27 @@ dol_include_once('/mymodule/lib/mymodule_myobject.lib.php'); // Load translation files required by the page -$langs->loadLangs(array("mymodule@mymodule","other")); +$langs->loadLangs(array("mymodule@mymodule", "other")); // Get parameters -$id = GETPOST('id', 'int'); +$id = GETPOST('id', 'int'); $ref = GETPOST('ref', 'alpha'); -$action = GETPOST('action', 'alpha'); +$action = GETPOST('action', 'alpha'); $cancel = GETPOST('cancel', 'aZ09'); $backtopage = GETPOST('backtopage', 'alpha'); if (GETPOST('actioncode', 'array')) { - $actioncode=GETPOST('actioncode', 'array', 3); - if (! count($actioncode)) $actioncode='0'; + $actioncode = GETPOST('actioncode', 'array', 3); + 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)); + $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'); -$limit = GETPOST('limit', 'int')?GETPOST('limit', 'int'):$conf->liste_limit; +$limit = GETPOST('limit', 'int') ?GETPOST('limit', 'int') : $conf->liste_limit; $sortfield = GETPOST("sortfield", 'alpha'); $sortorder = GETPOST("sortorder", 'alpha'); $page = GETPOST("page", 'int'); @@ -73,41 +73,41 @@ if (empty($page) || $page == -1) { $page = 0; } // If $page is not defined, $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 objects $object = new MyObject($db); $extrafields = new ExtraFields($db); -$diroutputmassaction=$conf->mymodule->dir_output . '/temp/massgeneration/'.$user->id; -$hookmanager->initHooks(array('myobjectagenda','globalcard')); // Note that conf->hooks_modules contains array +$diroutputmassaction = $conf->mymodule->dir_output.'/temp/massgeneration/'.$user->id; +$hookmanager->initHooks(array('myobjectagenda', 'globalcard')); // Note that conf->hooks_modules contains array // 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 // Must be include, not include_once. Include fetch and fetch_thirdparty but not fetch_optionals -if ($id > 0 || ! empty($ref)) $upload_dir = $conf->mymodule->multidir_output[$object->entity] . "/" . $object->id; +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->mymodule->multidir_output[$object->entity]."/".$object->id; // Security check - Protection if external user //if ($user->socid > 0) access_forbidden(); //if ($user->socid > 0) $socid = $user->socid; //$result = restrictedArea($user, 'mymodule', $object->id); -$permissiontoadd = $user->rights->mymodule->myobject->write; // Used by the include of actions_addupdatedelete.inc.php +$permissiontoadd = $user->rights->mymodule->myobject->write; // Used by the include of actions_addupdatedelete.inc.php /* * Actions */ -$parameters=array('id'=>$id); -$reshook=$hookmanager->executeHooks('doActions', $parameters, $object, $action); // Note that $action and $object may have been modified by some hooks +$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 (empty($reshook)) { // Cancel - if (GETPOST('cancel', 'alpha') && ! empty($backtopage)) + if (GETPOST('cancel', 'alpha') && !empty($backtopage)) { header("Location: ".$backtopage); exit; @@ -116,8 +116,8 @@ if (empty($reshook)) // Purge search criteria if (GETPOST('button_removefilter_x', 'alpha') || GETPOST('button_removefilter.x', 'alpha') || GETPOST('button_removefilter', 'alpha')) // All tests are required to be compatible with all browsers { - $actioncode=''; - $search_agenda_label=''; + $actioncode = ''; + $search_agenda_label = ''; } } @@ -131,12 +131,12 @@ $form = new Form($db); if ($object->id > 0) { - $title=$langs->trans("Agenda"); + $title = $langs->trans("Agenda"); //if (! empty($conf->global->MAIN_HTML_TITLE) && preg_match('/thirdpartynameonly/',$conf->global->MAIN_HTML_TITLE) && $object->name) $title=$object->name." - ".$title; $help_url = ''; llxHeader('', $title, $help_url); - if (! empty($conf->notification->enabled)) $langs->load("mails"); + if (!empty($conf->notification->enabled)) $langs->load("mails"); $head = myobjectPrepareHead($object); @@ -144,9 +144,9 @@ if ($object->id > 0) // Object card // ------------------------------------------------------------ - $linkback = '' . $langs->trans("BackToList") . ''; + $linkback = ''.$langs->trans("BackToList").''; - $morehtmlref='
    '; + $morehtmlref = '
    '; /* // Ref customer $morehtmlref.=$form->editfieldkey("RefCustomer", 'ref_client', $object->ref_client, $object, 0, 'string', '', 0, 1); @@ -186,7 +186,7 @@ if ($object->id > 0) } } }*/ - $morehtmlref.='
    '; + $morehtmlref .= '
    '; dol_banner_tab($object, 'ref', $linkback, 1, 'ref', 'ref', $morehtmlref); @@ -205,16 +205,16 @@ if ($object->id > 0) // Actions buttons - $objthirdparty=$object; - $objcon=new stdClass(); + $objthirdparty = $object; + $objcon = new stdClass(); - $out='&origin='.$object->element.'&originid='.$object->id; - $permok=$user->rights->agenda->myactions->create; - if ((! empty($objthirdparty->id) || ! empty($objcon->id)) && $permok) + $out = '&origin='.$object->element.'&originid='.$object->id; + $permok = $user->rights->agenda->myactions->create; + if ((!empty($objthirdparty->id) || !empty($objcon->id)) && $permok) { //$out.='trans("AddAnAction"),'filenew'); //$out.=""; @@ -223,9 +223,9 @@ if ($object->id > 0) print '
    '; - if (! empty($conf->agenda->enabled)) + if (!empty($conf->agenda->enabled)) { - if (! empty($user->rights->agenda->myactions->create) || ! empty($user->rights->agenda->allactions->create)) + if (!empty($user->rights->agenda->myactions->create) || !empty($user->rights->agenda->allactions->create)) { print ''.$langs->trans("AddAction").''; } @@ -237,18 +237,18 @@ 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); + $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); //print load_fiche_titre($langs->trans("ActionsOnMyObject"), '', ''); // List of all actions - $filters=array(); - $filters['search_agenda_label']=$search_agenda_label; + $filters = array(); + $filters['search_agenda_label'] = $search_agenda_label; // TODO Replace this with same code than into list.php //show_actions_done($conf, $langs, $db, $object, null, 0, $actioncode, '', $filters, $sortfield, $sortorder); diff --git a/htdocs/modulebuilder/template/myobject_card.php b/htdocs/modulebuilder/template/myobject_card.php index 16323790e97..7c4fa1ebbdc 100644 --- a/htdocs/modulebuilder/template/myobject_card.php +++ b/htdocs/modulebuilder/template/myobject_card.php @@ -43,19 +43,19 @@ // Load Dolibarr environment -$res=0; +$res = 0; // Try main.inc.php into web root known defined into CONTEXT_DOCUMENT_ROOT (not always defined) -if (! $res && ! empty($_SERVER["CONTEXT_DOCUMENT_ROOT"])) $res=@include $_SERVER["CONTEXT_DOCUMENT_ROOT"]."/main.inc.php"; +if (!$res && !empty($_SERVER["CONTEXT_DOCUMENT_ROOT"])) $res = @include $_SERVER["CONTEXT_DOCUMENT_ROOT"]."/main.inc.php"; // Try main.inc.php into web root detected using web root calculated from SCRIPT_FILENAME -$tmp=empty($_SERVER['SCRIPT_FILENAME'])?'':$_SERVER['SCRIPT_FILENAME'];$tmp2=realpath(__FILE__); $i=strlen($tmp)-1; $j=strlen($tmp2)-1; -while($i > 0 && $j > 0 && isset($tmp[$i]) && isset($tmp2[$j]) && $tmp[$i]==$tmp2[$j]) { $i--; $j--; } -if (! $res && $i > 0 && file_exists(substr($tmp, 0, ($i+1))."/main.inc.php")) $res=@include substr($tmp, 0, ($i+1))."/main.inc.php"; -if (! $res && $i > 0 && file_exists(dirname(substr($tmp, 0, ($i+1)))."/main.inc.php")) $res=@include dirname(substr($tmp, 0, ($i+1)))."/main.inc.php"; +$tmp = empty($_SERVER['SCRIPT_FILENAME']) ? '' : $_SERVER['SCRIPT_FILENAME']; $tmp2 = realpath(__FILE__); $i = strlen($tmp) - 1; $j = strlen($tmp2) - 1; +while ($i > 0 && $j > 0 && isset($tmp[$i]) && isset($tmp2[$j]) && $tmp[$i] == $tmp2[$j]) { $i--; $j--; } +if (!$res && $i > 0 && file_exists(substr($tmp, 0, ($i + 1))."/main.inc.php")) $res = @include substr($tmp, 0, ($i + 1))."/main.inc.php"; +if (!$res && $i > 0 && file_exists(dirname(substr($tmp, 0, ($i + 1)))."/main.inc.php")) $res = @include dirname(substr($tmp, 0, ($i + 1)))."/main.inc.php"; // Try main.inc.php using relative path -if (! $res && file_exists("../main.inc.php")) $res=@include "../main.inc.php"; -if (! $res && file_exists("../../main.inc.php")) $res=@include "../../main.inc.php"; -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 && file_exists("../../main.inc.php")) $res = @include "../../main.inc.php"; +if (!$res && file_exists("../../../main.inc.php")) $res = @include "../../../main.inc.php"; +if (!$res) die("Include of main fails"); require_once DOL_DOCUMENT_ROOT.'/core/class/html.formcompany.class.php'; require_once DOL_DOCUMENT_ROOT.'/core/class/html.formfile.class.php'; @@ -63,41 +63,41 @@ dol_include_once('/mymodule/class/myobject.class.php'); dol_include_once('/mymodule/lib/mymodule_myobject.lib.php'); // Load translation files required by the page -$langs->loadLangs(array("mymodule@mymodule","other")); +$langs->loadLangs(array("mymodule@mymodule", "other")); // Get parameters -$id = GETPOST('id', 'int'); +$id = GETPOST('id', 'int'); $ref = GETPOST('ref', 'alpha'); -$action = GETPOST('action', 'aZ09'); +$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 +$contextpage = GETPOST('contextpage', 'aZ') ?GETPOST('contextpage', 'aZ') : 'myobjectcard'; // To manage different context of search $backtopage = GETPOST('backtopage', 'alpha'); //$lineid = GETPOST('lineid', 'int'); // Initialize technical objects -$object=new MyObject($db); +$object = new MyObject($db); $extrafields = new ExtraFields($db); -$diroutputmassaction=$conf->mymodule->dir_output . '/temp/massgeneration/'.$user->id; -$hookmanager->initHooks(array('myobjectcard','globalcard')); // Note that conf->hooks_modules contains array +$diroutputmassaction = $conf->mymodule->dir_output.'/temp/massgeneration/'.$user->id; +$hookmanager->initHooks(array('myobjectcard', '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_'); +$search_array_options = $extrafields->getOptionalsFromPost($object->table_element, '', 'search_'); // Initialize array of search criterias -$search_all=trim(GETPOST("search_all", 'alpha')); -$search=array(); -foreach($object->fields as $key => $val) +$search_all = trim(GETPOST("search_all", 'alpha')); +$search = array(); +foreach ($object->fields as $key => $val) { - if (GETPOST('search_'.$key, 'alpha')) $search[$key]=GETPOST('search_'.$key, 'alpha'); + 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. +include DOL_DOCUMENT_ROOT.'/core/actions_fetchobject.inc.php'; // Must be include, not include_once. // Security check - Protection if external user //if ($user->socid > 0) access_forbidden(); @@ -110,28 +110,30 @@ $permissiontoadd = $user->rights->mymodule->myobject->write; // Used by the inc $permissiontodelete = $user->rights->mymodule->myobject->delete || ($permissiontoadd && isset($object->status) && $object->status == $object::STATUS_DRAFT); $permissionnote = $user->rights->mymodule->myobject->write; // Used by the include of actions_setnotes.inc.php $permissiondellink = $user->rights->mymodule->myobject->write; // Used by the include of actions_dellink.inc.php - +$upload_dir = $conf->mymodule->multidir_output[isset($object->entity)?$object->entity:1]; /* * Actions */ -$parameters=array(); -$reshook=$hookmanager->executeHooks('doActions', $parameters, $object, $action); // Note that $action and $object may have been modified by some hooks +$parameters = array(); +$reshook = $hookmanager->executeHooks('doActions', $parameters, $object, $action); // Note that $action and $object may have been modified by some hooks if ($reshook < 0) setEventMessages($hookmanager->error, $hookmanager->errors, 'errors'); if (empty($reshook)) { - $error=0; + $error = 0; $backurlforlist = dol_buildpath('/mymodule/myobject_list.php', 1); if (empty($backtopage) || ($cancel && empty($id))) { - if (empty($id) && (($action != 'add' && $action != 'create') || $cancel)) $backtopage = $backurlforlist; - else $backtopage = dol_buildpath('/mymodule/myobject_card.php', 1).'?id='.($id > 0 ? $id : '__ID__'); + if (empty($backtopage) || ($cancel && strpos($backtopage, '__ID__'))) { + if (empty($id) && (($action != 'add' && $action != 'create') || $cancel)) $backtopage = $backurlforlist; + else $backtopage = dol_buildpath('/mymodule/myobject_card.php', 1).'?id='.($id > 0 ? $id : '__ID__'); + } } - $triggermodname = 'MYMODULE_MYOBJECT_MODIFY'; // Name of trigger action code to execute when we modify record + $triggermodname = 'MYMODULE_MYOBJECT_MODIFY'; // Name of trigger action code to execute when we modify record // Actions cancel, add, update, delete or clone include DOL_DOCUMENT_ROOT.'/core/actions_addupdatedelete.inc.php'; @@ -158,9 +160,9 @@ if (empty($reshook)) } // Actions to send emails - $trigger_name='MYOBJECT_SENTBYMAIL'; - $autocopy='MAIN_MAIL_AUTOCOPY_MYOBJECT_TO'; - $trackid='myobject'.$object->id; + $trigger_name = 'MYOBJECT_SENTBYMAIL'; + $autocopy = 'MAIN_MAIL_AUTOCOPY_MYOBJECT_TO'; + $trackid = 'myobject'.$object->id; include DOL_DOCUMENT_ROOT.'/core/actions_sendmails.inc.php'; } @@ -173,8 +175,8 @@ if (empty($reshook)) * Put here all code to build page */ -$form=new Form($db); -$formfile=new FormFile($db); +$form = new Form($db); +$formfile = new FormFile($db); llxHeader('', $langs->trans('MyObject'), ''); @@ -209,10 +211,10 @@ if ($action == 'create') print ''."\n"; // Common attributes - include DOL_DOCUMENT_ROOT . '/core/tpl/commonfields_add.tpl.php'; + include DOL_DOCUMENT_ROOT.'/core/tpl/commonfields_add.tpl.php'; // Other attributes - include DOL_DOCUMENT_ROOT . '/core/tpl/extrafields_add.tpl.php'; + include DOL_DOCUMENT_ROOT.'/core/tpl/extrafields_add.tpl.php'; print '
    '."\n"; @@ -221,7 +223,7 @@ if ($action == 'create') print '
    '; print ''; print '  '; - print ''; // Cancel for create does not post form if we don't know the backtopage + print ''; // Cancel for create does not post form if we don't know the backtopage print '
    '; print ''; @@ -245,10 +247,10 @@ if (($id || $ref) && $action == 'edit') print ''."\n"; // Common attributes - include DOL_DOCUMENT_ROOT . '/core/tpl/commonfields_edit.tpl.php'; + include DOL_DOCUMENT_ROOT.'/core/tpl/commonfields_edit.tpl.php'; // Other attributes - include DOL_DOCUMENT_ROOT . '/core/tpl/extrafields_edit.tpl.php'; + include DOL_DOCUMENT_ROOT.'/core/tpl/extrafields_edit.tpl.php'; print '
    '; @@ -274,7 +276,7 @@ if ($object->id > 0 && (empty($action) || ($action != 'edit' && $action != 'crea // Confirmation to delete if ($action == 'delete') { - $formconfirm = $form->formconfirm($_SERVER["PHP_SELF"] . '?id=' . $object->id, $langs->trans('DeleteMyObject'), $langs->trans('ConfirmDeleteObject'), 'confirm_delete', '', 0, 1); + $formconfirm = $form->formconfirm($_SERVER["PHP_SELF"].'?id='.$object->id, $langs->trans('DeleteMyObject'), $langs->trans('ConfirmDeleteObject'), 'confirm_delete', '', 0, 1); } // Confirmation to delete line if ($action == 'deleteline') @@ -285,13 +287,13 @@ if ($object->id > 0 && (empty($action) || ($action != 'edit' && $action != 'crea if ($action == 'clone') { // Create an array for form $formquestion = array(); - $formconfirm = $form->formconfirm($_SERVER["PHP_SELF"] . '?id=' . $object->id, $langs->trans('ToClone'), $langs->trans('ConfirmCloneMyObject', $object->ref), 'confirm_clone', $formquestion, 'yes', 1); + $formconfirm = $form->formconfirm($_SERVER["PHP_SELF"].'?id='.$object->id, $langs->trans('ToClone'), $langs->trans('ConfirmCloneMyObject', $object->ref), 'confirm_clone', $formquestion, 'yes', 1); } // Confirmation of action xxxx if ($action == 'xxx') { - $formquestion=array(); + $formquestion = array(); /* $forcecombo=0; if ($conf->browser->name == 'ie') $forcecombo = 1; // There is a bug in IE10 that make combo inside popup crazy @@ -302,14 +304,14 @@ if ($object->id > 0 && (empty($action) || ($action != 'edit' && $action != 'crea // array('type' => 'other', 'name' => 'idwarehouse', 'label' => $langs->trans("SelectWarehouseForStockDecrease"), 'value' => $formproduct->selectWarehouses(GETPOST('idwarehouse')?GETPOST('idwarehouse'):'ifone', 'idwarehouse', '', 1, 0, 0, '', 0, $forcecombo)) ); */ - $formconfirm = $form->formconfirm($_SERVER["PHP_SELF"] . '?id=' . $object->id, $langs->trans('XXX'), $text, 'confirm_xxx', $formquestion, 0, 1, 220); + $formconfirm = $form->formconfirm($_SERVER["PHP_SELF"].'?id='.$object->id, $langs->trans('XXX'), $text, 'confirm_xxx', $formquestion, 0, 1, 220); } // Call Hook formConfirm $parameters = array('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; @@ -317,9 +319,9 @@ if ($object->id > 0 && (empty($action) || ($action != 'edit' && $action != 'crea // Object card // ------------------------------------------------------------ - $linkback = '' . $langs->trans("BackToList") . ''; + $linkback = ''.$langs->trans("BackToList").''; - $morehtmlref='
    '; + $morehtmlref = '
    '; /* // Ref bis $morehtmlref.=$form->editfieldkey("RefBis", 'ref_client', $object->ref_client, $object, $user->rights->mymodule->myobject->creer, 'string', '', 0, 1); @@ -357,7 +359,7 @@ if ($object->id > 0 && (empty($action) || ($action != 'edit' && $action != 'crea } } */ - $morehtmlref.='
    '; + $morehtmlref .= '
    '; dol_banner_tab($object, 'ref', $linkback, 1, 'ref', 'ref', $morehtmlref); @@ -372,10 +374,10 @@ if ($object->id > 0 && (empty($action) || ($action != 'edit' && $action != 'crea //$keyforbreak='fieldkeytoswitchonsecondcolumn'; //unset($object->fields['fk_project']); // Hide field already shown in banner //unset($object->fields['fk_soc']); // Hide field already shown in banner - include DOL_DOCUMENT_ROOT . '/core/tpl/commonfields_view.tpl.php'; + include DOL_DOCUMENT_ROOT.'/core/tpl/commonfields_view.tpl.php'; // Other attributes. Fields from hook formObjectOptions and Extrafields. - include DOL_DOCUMENT_ROOT . '/core/tpl/extrafields_view.tpl.php'; + include DOL_DOCUMENT_ROOT.'/core/tpl/extrafields_view.tpl.php'; print '
    '; print '
    '; @@ -454,9 +456,12 @@ if ($object->id > 0 && (empty($action) || ($action != 'edit' && $action != 'crea print '' . $langs->trans('SendMail') . ''."\n"; // Back to draft - if (! empty($user->rights->mymodule->myobject->write) && $object->status == BOM::STATUS_VALIDATED) + if ($object->status == $object::STATUS_VALIDATED) { - print '' . $langs->trans("SetToDraft") . ''; + if ($permissiontoadd) + { + print '' . $langs->trans("SetToDraft") . ''; + } } // Modify @@ -469,6 +474,22 @@ if ($object->id > 0 && (empty($action) || ($action != 'edit' && $action != 'crea print ''.$langs->trans('Modify').''."\n"; } + // Validate + if ($object->status == $object::STATUS_DRAFT) + { + if ($permissiontoadd) + { + if (is_array($object->lines) && count($object->lines) > 0) + { + print ''.$langs->trans("Validate").''; + } + else + { + print ''.$langs->trans("Validate").''; + } + } + } + // Clone if ($permissiontoadd) { @@ -533,13 +554,13 @@ if ($object->id > 0 && (empty($action) || ($action != 'edit' && $action != 'crea $MAXEVENT = 10; $morehtmlright = ''; - $morehtmlright.= $langs->trans("SeeAll"); - $morehtmlright.= ''; + $morehtmlright .= $langs->trans("SeeAll"); + $morehtmlright .= ''; // List of actions on element - include_once DOL_DOCUMENT_ROOT . '/core/class/html.formactions.class.php'; + include_once DOL_DOCUMENT_ROOT.'/core/class/html.formactions.class.php'; $formactions = new FormActions($db); - $somethingshown = $formactions->showactions($object, 'myobject', (is_object($object->thirdparty)?$object->thirdparty->id:0), 1, '', $MAXEVENT, '', $morehtmlright); + $somethingshown = $formactions->showactions($object, 'myobject', (is_object($object->thirdparty) ? $object->thirdparty->id : 0), 1, '', $MAXEVENT, '', $morehtmlright); print '
    '; } diff --git a/htdocs/modulebuilder/template/myobject_document.php b/htdocs/modulebuilder/template/myobject_document.php index 9d0954d277e..5a58a068a64 100644 --- a/htdocs/modulebuilder/template/myobject_document.php +++ b/htdocs/modulebuilder/template/myobject_document.php @@ -23,19 +23,19 @@ */ // Load Dolibarr environment -$res=0; +$res = 0; // Try main.inc.php into web root known defined into CONTEXT_DOCUMENT_ROOT (not always defined) -if (! $res && ! empty($_SERVER["CONTEXT_DOCUMENT_ROOT"])) $res=@include $_SERVER["CONTEXT_DOCUMENT_ROOT"]."/main.inc.php"; +if (!$res && !empty($_SERVER["CONTEXT_DOCUMENT_ROOT"])) $res = @include $_SERVER["CONTEXT_DOCUMENT_ROOT"]."/main.inc.php"; // Try main.inc.php into web root detected using web root calculated from SCRIPT_FILENAME -$tmp=empty($_SERVER['SCRIPT_FILENAME'])?'':$_SERVER['SCRIPT_FILENAME'];$tmp2=realpath(__FILE__); $i=strlen($tmp)-1; $j=strlen($tmp2)-1; -while($i > 0 && $j > 0 && isset($tmp[$i]) && isset($tmp2[$j]) && $tmp[$i]==$tmp2[$j]) { $i--; $j--; } -if (! $res && $i > 0 && file_exists(substr($tmp, 0, ($i+1))."/main.inc.php")) $res=@include substr($tmp, 0, ($i+1))."/main.inc.php"; -if (! $res && $i > 0 && file_exists(dirname(substr($tmp, 0, ($i+1)))."/main.inc.php")) $res=@include dirname(substr($tmp, 0, ($i+1)))."/main.inc.php"; +$tmp = empty($_SERVER['SCRIPT_FILENAME']) ? '' : $_SERVER['SCRIPT_FILENAME']; $tmp2 = realpath(__FILE__); $i = strlen($tmp) - 1; $j = strlen($tmp2) - 1; +while ($i > 0 && $j > 0 && isset($tmp[$i]) && isset($tmp2[$j]) && $tmp[$i] == $tmp2[$j]) { $i--; $j--; } +if (!$res && $i > 0 && file_exists(substr($tmp, 0, ($i + 1))."/main.inc.php")) $res = @include substr($tmp, 0, ($i + 1))."/main.inc.php"; +if (!$res && $i > 0 && file_exists(dirname(substr($tmp, 0, ($i + 1)))."/main.inc.php")) $res = @include dirname(substr($tmp, 0, ($i + 1)))."/main.inc.php"; // Try main.inc.php using relative path -if (! $res && file_exists("../main.inc.php")) $res=@include "../main.inc.php"; -if (! $res && file_exists("../../main.inc.php")) $res=@include "../../main.inc.php"; -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 && file_exists("../../main.inc.php")) $res = @include "../../main.inc.php"; +if (!$res && file_exists("../../../main.inc.php")) $res = @include "../../../main.inc.php"; +if (!$res) die("Include of main fails"); require_once DOL_DOCUMENT_ROOT.'/core/lib/company.lib.php'; require_once DOL_DOCUMENT_ROOT.'/core/lib/files.lib.php'; @@ -45,12 +45,12 @@ dol_include_once('/mymodule/class/myobject.class.php'); dol_include_once('/mymodule/lib/mymodule_myobject.lib.php'); // Load translation files required by the page -$langs->loadLangs(array("mymodule@mymodule","companies","other","mails")); +$langs->loadLangs(array("mymodule@mymodule", "companies", "other", "mails")); -$action=GETPOST('action', 'aZ09'); -$confirm=GETPOST('confirm'); -$id=(GETPOST('socid', 'int') ? GETPOST('socid', 'int') : GETPOST('id', 'int')); +$action = GETPOST('action', 'aZ09'); +$confirm = GETPOST('confirm'); +$id = (GETPOST('socid', 'int') ? GETPOST('socid', 'int') : GETPOST('id', 'int')); $ref = GETPOST('ref', 'alpha'); // Get parameters @@ -61,30 +61,30 @@ if (empty($page) || $page == -1) { $page = 0; } // If $page is not defined, $offset = $conf->liste_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 -$object=new MyObject($db); +$object = new MyObject($db); $extrafields = new ExtraFields($db); -$diroutputmassaction=$conf->mymodule->dir_output . '/temp/massgeneration/'.$user->id; -$hookmanager->initHooks(array('myobjectdocument','globalcard')); // Note that conf->hooks_modules contains array +$diroutputmassaction = $conf->mymodule->dir_output.'/temp/massgeneration/'.$user->id; +$hookmanager->initHooks(array('myobjectdocument', 'globalcard')); // Note that conf->hooks_modules contains array // 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 // Must be include, not include_once. Include fetch and fetch_thirdparty but not fetch_optionals +include DOL_DOCUMENT_ROOT.'/core/actions_fetchobject.inc.php'; // Must be include, not include_once // Must be include, not include_once. Include fetch and fetch_thirdparty but not fetch_optionals //if ($id > 0 || ! empty($ref)) $upload_dir = $conf->mymodule->multidir_output[$object->entity?$object->entity:$conf->entity] . "/myobject/" . dol_sanitizeFileName($object->id); -if ($id > 0 || ! empty($ref)) $upload_dir = $conf->mymodule->multidir_output[$object->entity?$object->entity:$conf->entity] . "/myobject/" . dol_sanitizeFileName($object->ref); +if ($id > 0 || !empty($ref)) $upload_dir = $conf->mymodule->multidir_output[$object->entity ? $object->entity : $conf->entity]."/myobject/".dol_sanitizeFileName($object->ref); // Security check - Protection if external user //if ($user->socid > 0) access_forbidden(); //if ($user->socid > 0) $socid = $user->socid; //$result = restrictedArea($user, 'mymodule', $object->id); -$permissiontoadd = $user->rights->mymodule->myobject->write; // Used by the include of actions_addupdatedelete.inc.php +$permissiontoadd = $user->rights->mymodule->myobject->write; // Used by the include of actions_addupdatedelete.inc.php @@ -92,7 +92,7 @@ $permissiontoadd = $user->rights->mymodule->myobject->write; // Used by the in * Actions */ -include_once DOL_DOCUMENT_ROOT . '/core/actions_linkedfiles.inc.php'; +include_once DOL_DOCUMENT_ROOT.'/core/actions_linkedfiles.inc.php'; /* @@ -101,8 +101,8 @@ include_once DOL_DOCUMENT_ROOT . '/core/actions_linkedfiles.inc.php'; $form = new Form($db); -$title=$langs->trans("MyObject").' - '.$langs->trans("Files"); -$help_url=''; +$title = $langs->trans("MyObject").' - '.$langs->trans("Files"); +$help_url = ''; //$help_url='EN:Module_Third_Parties|FR:Module_Tiers|ES:Empresas'; llxHeader('', $title, $help_url); @@ -117,16 +117,16 @@ 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) + $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) { - $totalsize+=$file['size']; + $totalsize += $file['size']; } // Object card // ------------------------------------------------------------ - $linkback = '' . $langs->trans("BackToList") . ''; + $linkback = ''.$langs->trans("BackToList").''; dol_banner_tab($object, 'ref', $linkback, 1, 'ref', 'ref', $morehtmlref); @@ -152,12 +152,12 @@ if ($object->id) $permission = 1; //$permtoedit = $user->rights->mymodule->myobject->write; $permtoedit = 1; - $param = '&id=' . $object->id; + $param = '&id='.$object->id; //$relativepathwithnofile='myobject/' . dol_sanitizeFileName($object->id).'/'; - $relativepathwithnofile='myobject/' . dol_sanitizeFileName($object->ref).'/'; + $relativepathwithnofile = 'myobject/'.dol_sanitizeFileName($object->ref).'/'; - include_once DOL_DOCUMENT_ROOT . '/core/tpl/document_actions_post_headers.tpl.php'; + include_once DOL_DOCUMENT_ROOT.'/core/tpl/document_actions_post_headers.tpl.php'; } else { diff --git a/htdocs/modulebuilder/template/myobject_list.php b/htdocs/modulebuilder/template/myobject_list.php index 6fd3f2b3705..804b3d1f8ab 100644 --- a/htdocs/modulebuilder/template/myobject_list.php +++ b/htdocs/modulebuilder/template/myobject_list.php @@ -42,47 +42,47 @@ //if (! defined("XFRAMEOPTIONS_ALLOWALL")) define('XFRAMEOPTIONS_ALLOWALL', '1'); // Do not add the HTTP header 'X-Frame-Options: SAMEORIGIN' but 'X-Frame-Options: ALLOWALL' // Load Dolibarr environment -$res=0; +$res = 0; // Try main.inc.php into web root known defined into CONTEXT_DOCUMENT_ROOT (not always defined) -if (! $res && ! empty($_SERVER["CONTEXT_DOCUMENT_ROOT"])) $res=@include $_SERVER["CONTEXT_DOCUMENT_ROOT"]."/main.inc.php"; +if (!$res && !empty($_SERVER["CONTEXT_DOCUMENT_ROOT"])) $res = @include $_SERVER["CONTEXT_DOCUMENT_ROOT"]."/main.inc.php"; // Try main.inc.php into web root detected using web root calculated from SCRIPT_FILENAME -$tmp=empty($_SERVER['SCRIPT_FILENAME'])?'':$_SERVER['SCRIPT_FILENAME'];$tmp2=realpath(__FILE__); $i=strlen($tmp)-1; $j=strlen($tmp2)-1; -while($i > 0 && $j > 0 && isset($tmp[$i]) && isset($tmp2[$j]) && $tmp[$i]==$tmp2[$j]) { $i--; $j--; } -if (! $res && $i > 0 && file_exists(substr($tmp, 0, ($i+1))."/main.inc.php")) $res=@include substr($tmp, 0, ($i+1))."/main.inc.php"; -if (! $res && $i > 0 && file_exists(dirname(substr($tmp, 0, ($i+1)))."/main.inc.php")) $res=@include dirname(substr($tmp, 0, ($i+1)))."/main.inc.php"; +$tmp = empty($_SERVER['SCRIPT_FILENAME']) ? '' : $_SERVER['SCRIPT_FILENAME']; $tmp2 = realpath(__FILE__); $i = strlen($tmp) - 1; $j = strlen($tmp2) - 1; +while ($i > 0 && $j > 0 && isset($tmp[$i]) && isset($tmp2[$j]) && $tmp[$i] == $tmp2[$j]) { $i--; $j--; } +if (!$res && $i > 0 && file_exists(substr($tmp, 0, ($i + 1))."/main.inc.php")) $res = @include substr($tmp, 0, ($i + 1))."/main.inc.php"; +if (!$res && $i > 0 && file_exists(dirname(substr($tmp, 0, ($i + 1)))."/main.inc.php")) $res = @include dirname(substr($tmp, 0, ($i + 1)))."/main.inc.php"; // Try main.inc.php using relative path -if (! $res && file_exists("../main.inc.php")) $res=@include "../main.inc.php"; -if (! $res && file_exists("../../main.inc.php")) $res=@include "../../main.inc.php"; -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 && file_exists("../../main.inc.php")) $res = @include "../../main.inc.php"; +if (!$res && file_exists("../../../main.inc.php")) $res = @include "../../../main.inc.php"; +if (!$res) die("Include of main fails"); require_once DOL_DOCUMENT_ROOT.'/core/class/html.formcompany.class.php'; require_once DOL_DOCUMENT_ROOT.'/core/lib/date.lib.php'; require_once DOL_DOCUMENT_ROOT.'/core/lib/company.lib.php'; // load mymodule libraries -require_once __DIR__ . '/class/myobject.class.php'; +require_once __DIR__.'/class/myobject.class.php'; // for other modules //dol_include_once('/othermodule/class/otherobject.class.php'); // Load translation files required by the page -$langs->loadLangs(array("mymodule@mymodule","other")); +$langs->loadLangs(array("mymodule@mymodule", "other")); -$action = GETPOST('action', 'aZ09')?GETPOST('action', 'aZ09'):'view'; // The action 'add', 'create', 'edit', 'update', 'view', ... -$massaction = GETPOST('massaction', 'alpha'); // The bulk action (combo box choice into lists) -$show_files = GETPOST('show_files', 'int'); // Show files area generated by bulk actions ? -$confirm = GETPOST('confirm', 'alpha'); // Result of a confirmation -$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'):'myobjectlist'; // 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') +$action = GETPOST('action', 'aZ09') ?GETPOST('action', 'aZ09') : 'view'; // The action 'add', 'create', 'edit', 'update', 'view', ... +$massaction = GETPOST('massaction', 'alpha'); // The bulk action (combo box choice into lists) +$show_files = GETPOST('show_files', 'int'); // Show files area generated by bulk actions ? +$confirm = GETPOST('confirm', 'alpha'); // Result of a confirmation +$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') : 'myobjectlist'; // 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') -$id = GETPOST('id', 'int'); +$id = GETPOST('id', 'int'); // Load variable for pagination -$limit = GETPOST('limit', 'int')?GETPOST('limit', 'int'):$conf->liste_limit; +$limit = GETPOST('limit', 'int') ?GETPOST('limit', 'int') : $conf->liste_limit; $sortfield = GETPOST('sortfield', 'alpha'); $sortorder = GETPOST('sortorder', 'alpha'); $page = GETPOST('page', 'int'); @@ -90,14 +90,12 @@ if (empty($page) || $page == -1 || GETPOST('button_search', 'alpha') || GETPOST( $offset = $limit * $page; $pageprev = $page - 1; $pagenext = $page + 1; -//if (! $sortfield) $sortfield="p.date_fin"; -//if (! $sortorder) $sortorder="DESC"; // Initialize technical objects $object = new MyObject($db); $extrafields = new ExtraFields($db); -$diroutputmassaction = $conf->mymodule->dir_output . '/temp/massgeneration/'.$user->id; -$hookmanager->initHooks(array('myobjectlist')); // Note that conf->hooks_modules contains array +$diroutputmassaction = $conf->mymodule->dir_output.'/temp/massgeneration/'.$user->id; +$hookmanager->initHooks(array('myobjectlist')); // Note that conf->hooks_modules contains array // Fetch optionals attributes and labels $extrafields->fetch_name_optionals_label($object->table_element); @@ -106,12 +104,12 @@ $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->mymodule->enabled)) accessforbidden('Module not enabled'); -$socid=0; +$socid = 0; if ($user->socid > 0) // Protection if external user { //$socid = $user->socid; @@ -139,15 +137,21 @@ $arrayfields=array(); 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 (! empty($extrafields->attributes[$object->table_element]['list'][$key])) - $arrayfields["ef.".$key]=array('label'=>$extrafields->attributes[$object->table_element]['label'][$key], 'checked'=>(($extrafields->attributes[$object->table_element]['list'][$key]<0)?0:1), 'position'=>$extrafields->attributes[$object->table_element]['pos'][$key], 'enabled'=>(abs($extrafields->attributes[$object->table_element]['list'][$key])!=3 && $extrafields->attributes[$object->table_element]['perms'][$key])); + if (!empty($extrafields->attributes[$object->table_element]['list'][$key])) { + $arrayfields["ef.".$key] = array( + 'label'=>$extrafields->attributes[$object->table_element]['label'][$key], + 'checked'=>(($extrafields->attributes[$object->table_element]['list'][$key]<0)?0:1), + 'position'=>$extrafields->attributes[$object->table_element]['pos'][$key], + 'enabled'=>(abs($extrafields->attributes[$object->table_element]['list'][$key])!=3 && $extrafields->attributes[$object->table_element]['perms'][$key]) + ); + } } } $object->fields = dol_sort_array($object->fields, 'position'); @@ -162,11 +166,11 @@ $permissiontodelete = $user->rights->mymodule->myobject->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 +$parameters = array(); +$reshook = $hookmanager->executeHooks('doActions', $parameters, $object, $action); // Note that $action and $object may have been modified by some hooks if ($reshook < 0) setEventMessages($hookmanager->error, $hookmanager->errors, 'errors'); if (empty($reshook)) @@ -175,24 +179,24 @@ if (empty($reshook)) 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 { - foreach($object->fields as $key => $val) + foreach ($object->fields as $key => $val) { - $search[$key]=''; + $search[$key] = ''; } - $toselect=''; - $search_array_options=array(); + $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')) { - $massaction=''; // Protection to avoid mass action if we force a new search during a mass action confirmation + $massaction = ''; // Protection to avoid mass action if we force a new search during a mass action confirmation } // Mass actions - $objectclass='MyObject'; - $objectlabel='MyObject'; + $objectclass = 'MyObject'; + $objectlabel = 'MyObject'; $uploaddir = $conf->mymodule->dir_output; include DOL_DOCUMENT_ROOT.'/core/actions_massactions.inc.php'; } @@ -203,49 +207,49 @@ if (empty($reshook)) * View */ -$form=new Form($db); +$form = new Form($db); -$now=dol_now(); +$now = dol_now(); //$help_url="EN:Module_MyObject|FR:Module_MyObject_FR|ES:Módulo_MyObject"; -$help_url=''; +$help_url = ''; $title = $langs->trans('ListOf', $langs->transnoentitiesnoconv("MyObjects")); // Build and execute select // -------------------------------------------------------------------- $sql = 'SELECT '; -foreach($object->fields as $key => $val) +foreach ($object->fields as $key => $val) { - $sql.='t.'.$key.', '; + $sql .= 't.'.$key.', '; } // Add fields from extrafields -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.', ' : ''); +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.', ' : ''); } // Add fields from hooks -$parameters=array(); -$reshook=$hookmanager->executeHooks('printFieldListSelect', $parameters, $object); // Note that $action and $object may have been modified by hook -$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) +$parameters = array(); +$reshook = $hookmanager->executeHooks('printFieldListSelect', $parameters, $object); // Note that $action and $object may have been modified by hook +$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; - $mode_search=(($object->isInt($object->fields[$key]) || $object->isFloat($object->fields[$key])) ? 1 : 0); - if ($search[$key] != '') $sql.=natural_search($key, $search[$key], (($key == 'status')?2:$mode_search)); + $mode_search = (($object->isInt($object->fields[$key]) || $object->isFloat($object->fields[$key])) ? 1 : 0); + 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); //$sql.= dolSqlDateFilter("t.field", $search_xxxday, $search_xxxmonth, $search_xxxyear); // Add where from extra fields include DOL_DOCUMENT_ROOT.'/core/tpl/extrafields_list_search_sql.tpl.php'; // Add where from hooks -$parameters=array(); -$reshook=$hookmanager->executeHooks('printFieldListWhere', $parameters, $object); // Note that $action and $object may have been modified by hook -$sql.=$hookmanager->resPrint; +$parameters = array(); +$reshook = $hookmanager->executeHooks('printFieldListWhere', $parameters, $object); // Note that $action and $object may have been modified by hook +$sql .= $hookmanager->resPrint; /* If a group by is required $sql.= " GROUP BY " @@ -263,7 +267,7 @@ $sql.=$hookmanager->resPrint; $sql=preg_replace('/,\s*$/','', $sql); */ -$sql.=$db->order($sortfield, $sortorder); +$sql .= $db->order($sortfield, $sortorder); // Count total nb of records $nbtotalofrecords = ''; @@ -278,16 +282,16 @@ if (empty($conf->global->MAIN_DISABLE_FULL_SCANLIST)) } } // 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) +if (is_numeric($nbtotalofrecords) && ($limit > $nbtotalofrecords || empty($limit))) { $num = $nbtotalofrecords; } else { - $sql.= $db->plimit($limit+1, $offset); + if ($limit) $sql .= $db->plimit($limit + 1, $offset); - $resql=$db->query($sql); - if (! $resql) + $resql = $db->query($sql); + if (!$resql) { dol_print_error($db); exit; @@ -297,7 +301,7 @@ else } // 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; @@ -326,30 +330,30 @@ jQuery(document).ready(function() { }); '; -$arrayofselected=is_array($toselect)?$toselect:array(); +$arrayofselected = is_array($toselect) ? $toselect : array(); -$param=''; -if (! empty($contextpage) && $contextpage != $_SERVER["PHP_SELF"]) $param.='&contextpage='.urlencode($contextpage); -if ($limit > 0 && $limit != $conf->liste_limit) $param.='&limit='.urlencode($limit); -foreach($search as $key => $val) +$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 (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'; // List of mass actions available -$arrayofmassactions = array( +$arrayofmassactions = array( //'validate'=>$langs->trans("Validate"), //'generate_doc'=>$langs->trans("ReGeneratePDF"), //'builddoc'=>$langs->trans("PDFMerge"), //'presend'=>$langs->trans("SendByMail"), ); -if ($permissiontodelete) $arrayofmassactions['predelete']=''.$langs->trans("Delete"); -if (GETPOST('nomassaction', 'int') || in_array($massaction, array('presend','predelete'))) $arrayofmassactions=array(); -$massactionbutton=$form->selectMassAction('', $arrayofmassactions); +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 ''; @@ -366,16 +370,16 @@ $newcardbutton = dolGetButtonTitle($langs->trans('New'), '', 'fa fa-plus-circle' print_barre_liste($title, $page, $_SERVER["PHP_SELF"], $param, $sortfield, $sortorder, $massactionbutton, $num, $nbtotalofrecords, 'title_companies', 0, $newcardbutton, '', $limit); // Add code for pre mass action (confirmation or email presend form) -$topicmail="SendMyObjectRef"; -$modelmail="myobject"; -$objecttmp=new MyObject($db); -$trackid='xxxx'.$object->id; +$topicmail = "SendMyObjectRef"; +$modelmail = "myobject"; +$objecttmp = new MyObject($db); +$trackid = 'xxxx'.$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); - print '
    '.$langs->trans("FilterOnInto", $search_all) . join(', ', $fieldstosearchall).'
    '; + foreach ($fieldstosearchall as $key => $val) $fieldstosearchall[$key] = $langs->trans($val); + print '
    '.$langs->trans("FilterOnInto", $search_all).join(', ', $fieldstosearchall).'
    '; } $moreforfilter = ''; @@ -383,39 +387,39 @@ $moreforfilter = ''; $moreforfilter.= $langs->trans('MyFilter') . ': '; $moreforfilter.= '';*/ -$parameters=array(); -$reshook=$hookmanager->executeHooks('printFieldPreListTitle', $parameters, $object); // Note that $action and $object may have been modified by hook +$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($moreforfilter)) +if (!empty($moreforfilter)) { print '
    '; print $moreforfilter; print '
    '; } -$varpage=empty($contextpage)?$_SERVER["PHP_SELF"]:$contextpage; -$selectedfields=$form->multiSelectArrayWithCheckbox('selectedfields', $arrayfields, $varpage); // This also change content of $arrayfields -$selectedfields.=(count($arrayofmassactions) ? $form->showCheckAddButtons('checkforselect', 1) : ''); +$varpage = empty($contextpage) ? $_SERVER["PHP_SELF"] : $contextpage; +$selectedfields = $form->multiSelectArrayWithCheckbox('selectedfields', $arrayfields, $varpage); // This also change content of $arrayfields +$selectedfields .= (count($arrayofmassactions) ? $form->showCheckAddButtons('checkforselect', 1) : ''); -print '
    '; // You can use div-table-responsive-no-min if you dont need reserved height for your table -print ''."\n"; +print '
    '; // You can use div-table-responsive-no-min if you dont need reserved height for your table +print '
    '."\n"; // Fields title search // -------------------------------------------------------------------- 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'])) + $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'])) { - print ''; @@ -425,12 +429,12 @@ foreach($object->fields as $key => $val) include DOL_DOCUMENT_ROOT.'/core/tpl/extrafields_list_search_input.tpl.php'; // Fields from hook -$parameters=array('arrayfields'=>$arrayfields); -$reshook=$hookmanager->executeHooks('printFieldListOption', $parameters, $object); // Note that $action and $object may have been modified by hook +$parameters = array('arrayfields'=>$arrayfields); +$reshook = $hookmanager->executeHooks('printFieldListOption', $parameters, $object); // Note that $action and $object may have been modified by hook print $hookmanager->resPrint; // Action column print ''; print ''."\n"; @@ -439,23 +443,23 @@ 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'])) + $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'])) { - print getTitleFieldOfList($arrayfields['t.'.$key]['label'], 0, $_SERVER['PHP_SELF'], 't.'.$key, '', $param, ($cssforfield?'class="'.$cssforfield.'"':''), $sortfield, $sortorder, ($cssforfield?$cssforfield.' ':''))."\n"; + print getTitleFieldOfList($arrayfields['t.'.$key]['label'], 0, $_SERVER['PHP_SELF'], 't.'.$key, '', $param, ($cssforfield ? 'class="'.$cssforfield.'"' : ''), $sortfield, $sortorder, ($cssforfield ? $cssforfield.' ' : ''))."\n"; } } // 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, $object); // Note that $action and $object may have been modified by hook +$parameters = array('arrayfields'=>$arrayfields, 'param'=>$param, 'sortfield'=>$sortfield, 'sortorder'=>$sortorder); +$reshook = $hookmanager->executeHooks('printFieldListTitle', $parameters, $object); // Note that $action and $object may have been modified by hook print $hookmanager->resPrint; // Action column print getTitleFieldOfList($selectedfields, 0, $_SERVER["PHP_SELF"], '', '', '', '', $sortfield, $sortorder, 'center maxwidthsearch ')."\n"; @@ -463,56 +467,56 @@ print ''."\n"; // Detect if we need a fetch on each output line -$needToFetchEachLine=0; +$needToFetchEachLine = 0; if (is_array($extrafields->attributes[$object->table_element]['computed']) && count($extrafields->attributes[$object->table_element]['computed']) > 0) { foreach ($extrafields->attributes[$object->table_element]['computed'] as $key => $val) { - if (preg_match('/\$object/', $val)) $needToFetchEachLine++; // There is at least one compute field that use $object + if (preg_match('/\$object/', $val)) $needToFetchEachLine++; // There is at least one compute field that use $object } } // Loop on record // -------------------------------------------------------------------- -$i=0; -$totalarray=array(); -while ($i < min($num, $limit)) +$i = 0; +$totalarray = array(); +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->id = $obj->rowid; - foreach($object->fields as $key => $val) + foreach ($object->fields as $key => $val) { if (property_exists($obj, $key)) $object->$key = $obj->$key; } // 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'; + $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('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($val['type'], array('double(24,8)', 'double(6,3)', 'integer', 'real', 'price')) && $key != 'status') $cssforfield .= ($cssforfield ? ' ' : '').'right'; - if (! empty($arrayfields['t.'.$key]['checked'])) + if (!empty($arrayfields['t.'.$key]['checked'])) { print ''; if ($key == 'status') print $object->getLibStatut(5); - elseif (in_array($val['type'], array('date','datetime','timestamp'))) print $object->showOutputField($val, $key, $db->jdate($obj->$key), ''); + elseif (in_array($val['type'], array('date', 'datetime', 'timestamp'))) print $object->showOutputField($val, $key, $db->jdate($obj->$key), ''); else print $object->showOutputField($val, $key, $obj->$key, ''); print ''; - if (! $i) $totalarray['nbfield']++; - if (! empty($val['isameasure'])) + if (!$i) $totalarray['nbfield']++; + if (!empty($val['isameasure'])) { - if (! $i) $totalarray['pos'][$totalarray['nbfield']]='t.'.$key; + if (!$i) $totalarray['pos'][$totalarray['nbfield']] = 't.'.$key; $totalarray['val']['t.'.$key] += $obj->$key; } } @@ -520,21 +524,21 @@ while ($i < min($num, $limit)) // Extra fields include DOL_DOCUMENT_ROOT.'/core/tpl/extrafields_list_print_fields.tpl.php'; // Fields from hook - $parameters=array('arrayfields'=>$arrayfields, 'obj'=>$obj, 'i'=>$i, 'totalarray'=>&$totalarray); - $reshook=$hookmanager->executeHooks('printFieldListValue', $parameters, $object); // Note that $action and $object may have been modified by hook + $parameters = array('arrayfields'=>$arrayfields, 'obj'=>$obj, 'i'=>$i, 'totalarray'=>&$totalarray); + $reshook = $hookmanager->executeHooks('printFieldListValue', $parameters, $object); // Note that $action and $object may have been modified by hook print $hookmanager->resPrint; // Action column print ''; - if (! $i) $totalarray['nbfield']++; + if (!$i) $totalarray['nbfield']++; - print ''; + print ''."\n"; $i++; } @@ -545,16 +549,16 @@ include DOL_DOCUMENT_ROOT.'/core/tpl/list_print_total.tpl.php'; // If no record found if ($num == 0) { - $colspan=1; - foreach($arrayfields as $key => $val) { if (! empty($val['checked'])) $colspan++; } + $colspan = 1; + foreach ($arrayfields as $key => $val) { if (!empty($val['checked'])) $colspan++; } print ''; } $db->free($resql); -$parameters=array('arrayfields'=>$arrayfields, 'sql'=>$sql); -$reshook=$hookmanager->executeHooks('printFieldListFooter', $parameters, $object); // Note that $action and $object may have been modified by hook +$parameters = array('arrayfields'=>$arrayfields, 'sql'=>$sql); +$reshook = $hookmanager->executeHooks('printFieldListFooter', $parameters, $object); // Note that $action and $object may have been modified by hook print $hookmanager->resPrint; print '
    '; + print ''; if (is_array($val['arrayofkeyval'])) print $form->selectarray('search_'.$key, $val['arrayofkeyval'], $search[$key], $val['notnull'], 0, 0, '', 1, 0, 0, '', 'maxwidth75'); else print ''; print ''; -$searchpicto=$form->showFilterButtons(); +$searchpicto = $form->showFilterButtons(); print $searchpicto; print '
    '; if ($massactionbutton || $massaction) // If we are in select mode (massactionbutton defined) or if we have already selected and sent an action ($massaction) defined { - $selected=0; - if (in_array($obj->rowid, $arrayofselected)) $selected=1; - print ''; + $selected = 0; + if (in_array($obj->rowid, $arrayofselected)) $selected = 1; + print ''; } print '
    '.$langs->trans("NoRecordFound").'
    '."\n"; @@ -564,19 +568,19 @@ print ''."\n"; if (in_array('builddoc', $arrayofmassactions) && ($nbtotalofrecords === '' || $nbtotalofrecords)) { - $hidegeneratedfilelistifempty=1; - if ($massaction == 'builddoc' || $action == 'remove_file' || $show_files) $hidegeneratedfilelistifempty=0; + $hidegeneratedfilelistifempty = 1; + 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); // Show list of available documents - $urlsource=$_SERVER['PHP_SELF'].'?sortfield='.$sortfield.'&sortorder='.$sortorder; - $urlsource.=str_replace('&', '&', $param); + $urlsource = $_SERVER['PHP_SELF'].'?sortfield='.$sortfield.'&sortorder='.$sortorder; + $urlsource .= str_replace('&', '&', $param); - $filedir=$diroutputmassaction; - $genallowed=$permissiontoread; - $delallowed=$permissiontoadd; + $filedir = $diroutputmassaction; + $genallowed = $permissiontoread; + $delallowed = $permissiontoadd; print $formfile->showdocuments('massfilesarea_mymodule', '', $filedir, $urlsource, 0, $delallowed, '', 1, 1, 0, 48, 1, $param, $title, '', '', '', null, $hidegeneratedfilelistifempty); } diff --git a/htdocs/modulebuilder/template/myobject_note.php b/htdocs/modulebuilder/template/myobject_note.php index 89a8ed5513b..f7440c71cf8 100644 --- a/htdocs/modulebuilder/template/myobject_note.php +++ b/htdocs/modulebuilder/template/myobject_note.php @@ -23,38 +23,38 @@ */ // Load Dolibarr environment -$res=0; +$res = 0; // Try main.inc.php into web root known defined into CONTEXT_DOCUMENT_ROOT (not always defined) -if (! $res && ! empty($_SERVER["CONTEXT_DOCUMENT_ROOT"])) $res=@include $_SERVER["CONTEXT_DOCUMENT_ROOT"]."/main.inc.php"; +if (!$res && !empty($_SERVER["CONTEXT_DOCUMENT_ROOT"])) $res = @include $_SERVER["CONTEXT_DOCUMENT_ROOT"]."/main.inc.php"; // Try main.inc.php into web root detected using web root calculated from SCRIPT_FILENAME -$tmp=empty($_SERVER['SCRIPT_FILENAME'])?'':$_SERVER['SCRIPT_FILENAME'];$tmp2=realpath(__FILE__); $i=strlen($tmp)-1; $j=strlen($tmp2)-1; -while($i > 0 && $j > 0 && isset($tmp[$i]) && isset($tmp2[$j]) && $tmp[$i]==$tmp2[$j]) { $i--; $j--; } -if (! $res && $i > 0 && file_exists(substr($tmp, 0, ($i+1))."/main.inc.php")) $res=@include substr($tmp, 0, ($i+1))."/main.inc.php"; -if (! $res && $i > 0 && file_exists(dirname(substr($tmp, 0, ($i+1)))."/main.inc.php")) $res=@include dirname(substr($tmp, 0, ($i+1)))."/main.inc.php"; +$tmp = empty($_SERVER['SCRIPT_FILENAME']) ? '' : $_SERVER['SCRIPT_FILENAME']; $tmp2 = realpath(__FILE__); $i = strlen($tmp) - 1; $j = strlen($tmp2) - 1; +while ($i > 0 && $j > 0 && isset($tmp[$i]) && isset($tmp2[$j]) && $tmp[$i] == $tmp2[$j]) { $i--; $j--; } +if (!$res && $i > 0 && file_exists(substr($tmp, 0, ($i + 1))."/main.inc.php")) $res = @include substr($tmp, 0, ($i + 1))."/main.inc.php"; +if (!$res && $i > 0 && file_exists(dirname(substr($tmp, 0, ($i + 1)))."/main.inc.php")) $res = @include dirname(substr($tmp, 0, ($i + 1)))."/main.inc.php"; // Try main.inc.php using relative path -if (! $res && file_exists("../main.inc.php")) $res=@include "../main.inc.php"; -if (! $res && file_exists("../../main.inc.php")) $res=@include "../../main.inc.php"; -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 && file_exists("../../main.inc.php")) $res = @include "../../main.inc.php"; +if (!$res && file_exists("../../../main.inc.php")) $res = @include "../../../main.inc.php"; +if (!$res) die("Include of main fails"); dol_include_once('/mymodule/class/myobject.class.php'); dol_include_once('/mymodule/lib/mymodule_myobject.lib.php'); // Load translation files required by the page -$langs->loadLangs(array("mymodule@mymodule","companies")); +$langs->loadLangs(array("mymodule@mymodule", "companies")); // Get parameters -$id = GETPOST('id', 'int'); +$id = GETPOST('id', 'int'); $ref = GETPOST('ref', 'alpha'); -$action = GETPOST('action', 'alpha'); +$action = GETPOST('action', 'alpha'); $cancel = GETPOST('cancel', 'aZ09'); $backtopage = GETPOST('backtopage', 'alpha'); // Initialize technical objects -$object=new MyObject($db); +$object = new MyObject($db); $extrafields = new ExtraFields($db); -$diroutputmassaction=$conf->mymodule->dir_output . '/temp/massgeneration/'.$user->id; -$hookmanager->initHooks(array('myobjectnote','globalcard')); // Note that conf->hooks_modules contains array +$diroutputmassaction = $conf->mymodule->dir_output.'/temp/massgeneration/'.$user->id; +$hookmanager->initHooks(array('myobjectnote', 'globalcard')); // Note that conf->hooks_modules contains array // Fetch optionals attributes and labels $extrafields->fetch_name_optionals_label($object->table_element); @@ -64,11 +64,11 @@ $extrafields->fetch_name_optionals_label($object->table_element); //$result = restrictedArea($user, 'mymodule', $id); // 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->mymodule->multidir_output[$object->entity] . "/" . $object->id; +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->mymodule->multidir_output[$object->entity]."/".$object->id; -$permissionnote=$user->rights->mymodule->myobject->write; // Used by the include of actions_setnotes.inc.php -$permissiontoadd = $user->rights->mymodule->myobject->write; // Used by the include of actions_addupdatedelete.inc.php +$permissionnote = $user->rights->mymodule->myobject->write; // Used by the include of actions_setnotes.inc.php +$permissiontoadd = $user->rights->mymodule->myobject->write; // Used by the include of actions_addupdatedelete.inc.php @@ -76,7 +76,7 @@ $permissiontoadd = $user->rights->mymodule->myobject->write; // Used by the in * Actions */ -include DOL_DOCUMENT_ROOT.'/core/actions_setnotes.inc.php'; // Must be include, not include_once +include DOL_DOCUMENT_ROOT.'/core/actions_setnotes.inc.php'; // Must be include, not include_once /* @@ -86,10 +86,10 @@ include DOL_DOCUMENT_ROOT.'/core/actions_setnotes.inc.php'; // Must be include, $form = new Form($db); //$help_url='EN:Customers_Orders|FR:Commandes_Clients|ES:Pedidos de clientes'; -$help_url=''; +$help_url = ''; llxHeader('', $langs->trans('MyObject'), $help_url); -if ($id > 0 || ! empty($ref)) +if ($id > 0 || !empty($ref)) { $object->fetch_thirdparty(); @@ -99,9 +99,9 @@ if ($id > 0 || ! empty($ref)) // Object card // ------------------------------------------------------------ - $linkback = '' . $langs->trans("BackToList") . ''; + $linkback = ''.$langs->trans("BackToList").''; - $morehtmlref='
    '; + $morehtmlref = '
    '; /* // Ref customer $morehtmlref.=$form->editfieldkey("RefCustomer", 'ref_client', $object->ref_client, $object, 0, 'string', '', 0, 1); @@ -141,7 +141,7 @@ if ($id > 0 || ! empty($ref)) } } }*/ - $morehtmlref.='
    '; + $morehtmlref .= '
    '; dol_banner_tab($object, 'ref', $linkback, 1, 'ref', 'ref', $morehtmlref); @@ -151,7 +151,7 @@ if ($id > 0 || ! empty($ref)) print '
    '; - $cssclass="titlefield"; + $cssclass = "titlefield"; include DOL_DOCUMENT_ROOT.'/core/tpl/notes.tpl.php'; print '
    '; diff --git a/htdocs/mrp/ajax/ajax_bom.php b/htdocs/mrp/ajax/ajax_bom.php index 76f1572353b..15b70ae17c9 100644 --- a/htdocs/mrp/ajax/ajax_bom.php +++ b/htdocs/mrp/ajax/ajax_bom.php @@ -22,15 +22,15 @@ //if (! defined('NOREQUIREUSER')) define('NOREQUIREUSER','1'); // Not disabled cause need to load personalized language //if (! defined('NOREQUIREDB')) define('NOREQUIREDB','1'); // Not disabled cause need to load personalized language -if (! defined('NOREQUIRESOC')) define('NOREQUIRESOC', '1'); +if (!defined('NOREQUIRESOC')) define('NOREQUIRESOC', '1'); //if (! defined('NOREQUIRETRAN')) define('NOREQUIRETRAN','1'); -if (! defined('NOCSRFCHECK')) define('NOCSRFCHECK', '1'); -if (! defined('NOTOKENRENEWAL')) define('NOTOKENRENEWAL', '1'); -if (! defined('NOREQUIREMENU')) define('NOREQUIREMENU', '1'); -if (! defined('NOREQUIREHTML')) define('NOREQUIREHTML', '1'); -if (! defined('NOREQUIREAJAX')) define('NOREQUIREAJAX', '1'); +if (!defined('NOCSRFCHECK')) define('NOCSRFCHECK', '1'); +if (!defined('NOTOKENRENEWAL')) define('NOTOKENRENEWAL', '1'); +if (!defined('NOREQUIREMENU')) define('NOREQUIREMENU', '1'); +if (!defined('NOREQUIREHTML')) define('NOREQUIREHTML', '1'); +if (!defined('NOREQUIREAJAX')) define('NOREQUIREAJAX', '1'); -require '../../main.inc.php'; // Load $user and permissions +require '../../main.inc.php'; // Load $user and permissions require_once DOL_DOCUMENT_ROOT.'/bom/class/bom.class.php'; $idbom = GETPOST('idbom', 'alpha'); @@ -42,7 +42,7 @@ $action = GETPOST('action', 'alpha'); */ $object = new BOM($db); -$result=$object->fetch($idbom); +$result = $object->fetch($idbom); if ($result > 0) { // We remove properties we don't need in answer diff --git a/htdocs/mrp/class/mo.class.php b/htdocs/mrp/class/mo.class.php index 0858ec44c6d..725427e249f 100644 --- a/htdocs/mrp/class/mo.class.php +++ b/htdocs/mrp/class/mo.class.php @@ -23,7 +23,7 @@ */ // Put here all includes required by your class file -require_once DOL_DOCUMENT_ROOT . '/core/class/commonobject.class.php'; +require_once DOL_DOCUMENT_ROOT.'/core/class/commonobject.class.php'; //require_once DOL_DOCUMENT_ROOT . '/societe/class/societe.class.php'; //require_once DOL_DOCUMENT_ROOT . '/product/class/product.class.php'; @@ -59,7 +59,7 @@ class Mo extends CommonObject const STATUS_DRAFT = 0; - const STATUS_VALIDATED = 1; // To produce + const STATUS_VALIDATED = 1; // To produce const STATUS_INPROGRESS = 2; const STATUS_PRODUCED = 3; const STATUS_CANCELED = -1; @@ -90,12 +90,12 @@ class Mo extends CommonObject /** * @var array Array with all fields and their property. Do not use it as a static var. It may be modified by constructor. */ - public $fields=array( + public $fields = array( 'rowid' => array('type'=>'integer', 'label'=>'TechnicalID', 'enabled'=>1, 'visible'=>-1, 'position'=>1, 'notnull'=>1, 'index'=>1, 'comment'=>"Id",), + 'entity' => array('type'=>'integer', 'label'=>'Entity', 'enabled'=>1, 'visible'=>0, 'position'=>5, 'notnull'=>1, 'default'=>'1', 'index'=>1,), 'ref' => array('type'=>'varchar(128)', 'label'=>'Ref', 'enabled'=>1, 'visible'=>4, 'position'=>10, 'notnull'=>1, 'default'=>'(PROV)', 'index'=>1, 'searchall'=>1, 'comment'=>"Reference of object", 'showoncombobox'=>'1',), - 'entity' => array('type'=>'integer', 'label'=>'Entity', 'enabled'=>1, 'visible'=>0, 'position'=>20, 'notnull'=>1, 'default'=>'1', 'index'=>1,), 'fk_bom' => array('type'=>'integer:Bom:bom/class/bom.class.php:0:t.status=1', 'filter'=>'active=1', 'label'=>'BOM', 'enabled'=>1, 'visible'=>1, 'position'=>33, 'notnull'=>-1, 'index'=>1, 'comment'=>"Original BOM",), - 'fk_product' => array('type'=>'integer:Product:product/class/product.class.php:1', 'label'=>'Product', 'enabled'=>1, 'visible'=>1, 'position'=>35, 'notnull'=>1, 'index'=>1, 'comment'=>"Product to produce",), + 'fk_product' => array('type'=>'integer:Product:product/class/product.class.php:0', 'label'=>'Product', 'enabled'=>1, 'visible'=>1, 'position'=>35, 'notnull'=>1, 'index'=>1, 'comment'=>"Product to produce",), 'qty' => array('type'=>'real', 'label'=>'QtyToProduce', 'enabled'=>1, 'visible'=>1, 'position'=>40, 'notnull'=>1, 'comment'=>"Qty to produce",), 'label' => array('type'=>'varchar(255)', 'label'=>'Label', 'enabled'=>1, 'visible'=>1, 'position'=>42, 'notnull'=>-1, 'searchall'=>1, 'showoncombobox'=>'1',), 'fk_soc' => array('type'=>'integer:Societe:societe/class/societe.class.php:1', 'label'=>'ThirdParty', 'enabled'=>1, 'visible'=>-1, 'position'=>50, 'notnull'=>-1, 'index'=>1), @@ -108,7 +108,7 @@ class Mo extends CommonObject 'fk_user_modif' => array('type'=>'integer', 'label'=>'UserModif', 'enabled'=>1, 'visible'=>-2, 'position'=>511, 'notnull'=>-1,), 'date_start_planned' => array('type'=>'datetime', 'label'=>'DateStartPlannedMo', 'enabled'=>1, 'visible'=>1, 'position'=>55, 'notnull'=>-1, 'index'=>1, 'help'=>'KeepEmptyForAsap'), 'date_end_planned' => array('type'=>'datetime', 'label'=>'DateEndPlannedMo', 'enabled'=>1, 'visible'=>1, 'position'=>56, 'notnull'=>-1, 'index'=>1,), - 'fk_project' => array('type'=>'integer:Project:projet/class/project.class.php:1', 'label'=>'Project', 'enabled'=>1, 'visible'=>-1, 'position'=>52, 'notnull'=>-1, 'index'=>1,), + 'fk_project' => array('type'=>'integer:Project:projet/class/project.class.php:1:fk_statut=1', 'label'=>'Project', 'enabled'=>1, 'visible'=>-1, 'position'=>52, 'notnull'=>-1, 'index'=>1,), 'import_key' => array('type'=>'varchar(14)', 'label'=>'ImportId', 'enabled'=>1, 'visible'=>-2, 'position'=>1000, 'notnull'=>-1,), 'model_pdf' =>array('type'=>'varchar(255)', 'label'=>'Model pdf', 'enabled'=>1, 'visible'=>0, 'position'=>1010), 'status' => array('type'=>'integer', 'label'=>'Status', 'enabled'=>1, 'visible'=>2, 'position'=>1000, 'default'=>0, 'notnull'=>1, 'index'=>1, 'arrayofkeyval'=>array('0'=>'Brouillon', '1'=>'Validated', '2'=>'InProgress', '3'=>'StatusMOProduced', '-1'=>'Canceled')), @@ -135,8 +135,18 @@ class Mo extends CommonObject public $import_key; public $status; public $fk_product; + + /** + * @var integer|string date_start_planned + */ public $date_start_planned; + + /** + * @var integer|string date_end_planned + */ public $date_end_planned; + + public $fk_bom; public $fk_project; // END MODULEBUILDER PROPERTIES @@ -187,11 +197,11 @@ class Mo 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) + foreach ($this->fields as $key => $val) { if (isset($val['enabled']) && empty($val['enabled'])) { @@ -200,13 +210,13 @@ class Mo extends CommonObject } // Translate some data of arrayofkeyval - foreach($this->fields as $key => $val) + foreach ($this->fields as $key => $val) { if (is_array($val['arrayofkeyval'])) { - foreach($val['arrayofkeyval'] as $key2 => $val2) + foreach ($val['arrayofkeyval'] as $key2 => $val2) { - $this->fields[$key]['arrayofkeyval'][$key2]=$langs->trans($val2); + $this->fields[$key]['arrayofkeyval'][$key2] = $langs->trans($val2); } } } @@ -244,7 +254,7 @@ class Mo 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($this->lines as $line) @@ -256,18 +266,18 @@ class Mo extends CommonObject unset($object->import_key); // Clear fields - $object->ref = empty($this->fields['ref']['default']) ? "copy_of_".$object->ref: $this->fields['ref']['default']; - $object->label = empty($this->fields['label']['default']) ? $langs->trans("CopyOf")." ".$object->label: $this->fields['label']['default']; + $object->ref = empty($this->fields['ref']['default']) ? "copy_of_".$object->ref : $this->fields['ref']['default']; + $object->label = empty($this->fields['label']['default']) ? $langs->trans("CopyOf")." ".$object->label : $this->fields['label']['default']; $object->status = self::STATUS_DRAFT; // ... // Clear extrafields that are unique if (is_array($object->array_options) && count($object->array_options) > 0) { $extrafields->fetch_name_optionals_label($this->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]); @@ -284,7 +294,7 @@ class Mo extends CommonObject $this->errors = $object->errors; } - if (! $error) + if (!$error) { // copy internal contacts if ($this->copy_linked_contact($object, 'internal') < 0) @@ -293,7 +303,7 @@ class Mo extends CommonObject } } - if (! $error) + if (!$error) { // copy external contacts if same company if (property_exists($this, 'socid') && $this->socid == $object->socid) @@ -325,7 +335,7 @@ class Mo extends CommonObject public function fetch($id, $ref = null) { $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(); return $result; } @@ -336,7 +346,7 @@ class Mo extends CommonObject */ public function fetchLines() { - $this->lines=array(); + $this->lines = array(); $result = $this->fetchLinesCommon(); return $result; @@ -360,40 +370,40 @@ class Mo extends CommonObject dol_syslog(__METHOD__, LOG_DEBUG); - $records=array(); + $records = array(); $sql = 'SELECT '; $sql .= $this->getFieldList(); - $sql .= ' FROM ' . MAIN_DB_PREFIX . $this->table_element. ' as t'; + $sql .= ' FROM '.MAIN_DB_PREFIX.$this->table_element.' as t'; if (isset($this->ismultientitymanaged) && $this->ismultientitymanaged == 1) $sql .= ' WHERE t.entity IN ('.getEntity($this->table_element).')'; else $sql .= ' WHERE 1 = 1'; // Manage filter $sqlwhere = array(); if (count($filter) > 0) { foreach ($filter as $key => $value) { - if ($key=='t.rowid') { - $sqlwhere[] = $key . '='. $value; + if ($key == 't.rowid') { + $sqlwhere[] = $key.'='.$value; } elseif (strpos($key, 'date') !== false) { $sqlwhere[] = $key.' = \''.$this->db->idate($value).'\''; } - elseif ($key=='customsql') { + elseif ($key == 'customsql') { $sqlwhere[] = $value; } else { - $sqlwhere[] = $key . ' LIKE \'%' . $this->db->escape($value) . '%\''; + $sqlwhere[] = $key.' LIKE \'%'.$this->db->escape($value).'%\''; } } } if (count($sqlwhere) > 0) { - $sql .= ' AND (' . implode(' '.$filtermode.' ', $sqlwhere).')'; + $sql .= ' AND ('.implode(' '.$filtermode.' ', $sqlwhere).')'; } if (!empty($sortfield)) { $sql .= $this->db->order($sortfield, $sortorder); } if (!empty($limit)) { - $sql .= ' ' . $this->db->plimit($limit, $offset); + $sql .= ' '.$this->db->plimit($limit, $offset); } $resql = $this->db->query($sql); @@ -415,8 +425,8 @@ class Mo extends CommonObject return $records; } else { - $this->errors[] = 'Error ' . $this->db->lasterror(); - dol_syslog(__METHOD__ . ' ' . join(',', $this->errors), LOG_ERR); + $this->errors[] = 'Error '.$this->db->lasterror(); + dol_syslog(__METHOD__.' '.join(',', $this->errors), LOG_ERR); return -1; } @@ -480,51 +490,51 @@ class Mo extends CommonObject { global $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 = ''; - $label = '' . $langs->trans("MO") . ''; - $label.= '
    '; - $label.= '' . $langs->trans('Ref') . ': ' . $this->ref; + $label = ''.$langs->trans("MO").''; + $label .= '
    '; + $label .= ''.$langs->trans('Ref').': '.$this->ref; $url = dol_buildpath('/mrp/mo_card.php', 1).'?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'; + $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=''; + $linkclose = ''; if (empty($notooltip)) { - if (! empty($conf->global->MAIN_OPTIMIZEFORTEXTBROWSER)) + if (!empty($conf->global->MAIN_OPTIMIZEFORTEXTBROWSER)) { - $label=$langs->trans("ShowMo"); - $linkclose.=' alt="'.dol_escape_htmltag($label, 1).'"'; + $label = $langs->trans("ShowMo"); + $linkclose .= ' alt="'.dol_escape_htmltag($label, 1).'"'; } - $linkclose.=' title="'.dol_escape_htmltag($label, 1).'"'; - $linkclose.=' class="classfortooltip'.($morecss?' '.$morecss:'').'"'; + $linkclose .= ' title="'.dol_escape_htmltag($label, 1).'"'; + $linkclose .= ' class="classfortooltip'.($morecss ? ' '.$morecss : '').'"'; } - else $linkclose = ($morecss?' class="'.$morecss.'"':''); + else $linkclose = ($morecss ? ' class="'.$morecss.'"' : ''); $linkstart = ''; - $linkend=''; + $linkstart .= $linkclose.'>'; + $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)) : ''); - global $action,$hookmanager; + global $action, $hookmanager; $hookmanager->initHooks(array('modao')); - $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 + $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; @@ -579,10 +589,10 @@ class Mo extends CommonObject public function info($id) { $sql = 'SELECT rowid, date_creation as datec, tms as datem,'; - $sql.= ' fk_user_creat, fk_user_modif'; - $sql.= ' FROM '.MAIN_DB_PREFIX.$this->table_element.' as t'; - $sql.= ' WHERE t.rowid = '.$id; - $result=$this->db->query($sql); + $sql .= ' fk_user_creat, fk_user_modif'; + $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)) @@ -593,7 +603,7 @@ class Mo extends CommonObject { $cuser = new User($this->db); $cuser->fetch($obj->fk_user_author); - $this->user_creation = $cuser; + $this->user_creation = $cuser; } if ($obj->fk_user_valid) @@ -607,7 +617,7 @@ class Mo extends CommonObject { $cluser = new User($this->db); $cluser->fetch($obj->fk_user_cloture); - $this->user_cloture = $cluser; + $this->user_cloture = $cluser; } $this->date_creation = $this->db->jdate($obj->datec); @@ -641,7 +651,7 @@ class Mo extends CommonObject */ public function getLinesArray() { - $this->lines=array(); + $this->lines = array(); $objectline = new MoLine($this->db); $result = $objectline->fetchAll('ASC', 'position', 0, 0, array('customsql'=>'fk_mo = '.$this->id)); @@ -672,16 +682,16 @@ class Mo extends CommonObject */ public function generateDocument($modele, $outputlangs, $hidedetails = 0, $hidedesc = 0, $hideref = 0, $moreparams = null) { - global $conf,$langs; + global $conf, $langs; $langs->load("mrp"); - if (! dol_strlen($modele)) { + if (!dol_strlen($modele)) { $modele = 'standard'; if ($this->modelpdf) { $modele = $this->modelpdf; - } elseif (! empty($conf->global->MO_ADDON_PDF)) { + } elseif (!empty($conf->global->MO_ADDON_PDF)) { $modele = $conf->global->MO_ADDON_PDF; } } @@ -706,7 +716,7 @@ class Mo extends CommonObject $error = 0; $this->output = ''; - $this->error=''; + $this->error = ''; dol_syslog(__METHOD__, LOG_DEBUG); @@ -720,6 +730,97 @@ class Mo extends CommonObject return $error; } + + /** + * Return HTML table table of source object lines + * TODO Move this and previous function into output html class file (htmlline.class.php). + * If lines are into a template, title must also be into a template + * But for the moment we don't know if it's possible, so we keep the method available on overloaded objects. + * + * @param string $restrictlist ''=All lines, 'services'=Restrict to services only + * @param array $selectedLines Array of lines id for selected lines + * @return void + */ + public function printOriginLinesList($restrictlist = '', $selectedLines = array()) + { + global $langs, $hookmanager, $conf, $form; + + print '
    '.$langs->trans('Ref').''.$langs->trans('Qty').''.$langs->trans('QtyFrozen').''.$langs->trans('DisableStockChange').''.$langs->trans('Efficiency').''.$form->showCheckAddButtons('checkforselect', 1).'
    '; + print '
    '; print ''."\n"; if ($conf->use_javascript_ajax) { @@ -143,7 +143,7 @@ $resql=$db->query($sql); if ($resql) { print '
    '; - print '
    '.$langs->trans("Statistics").'
    '; + print '
    '; print ''; print ''; @@ -196,7 +196,7 @@ $resql=$db->query($sql); if ($resql) { print '
    '; - print '
    '.$langs->trans("LatestBOMModified", $max).'
    '; + print '
    '; print ''; print ''; diff --git a/htdocs/mrp/mo_card.php b/htdocs/mrp/mo_card.php index bbf4340196b..7cbb7256b5f 100644 --- a/htdocs/mrp/mo_card.php +++ b/htdocs/mrp/mo_card.php @@ -47,45 +47,57 @@ require '../main.inc.php'; require_once DOL_DOCUMENT_ROOT.'/core/class/html.formcompany.class.php'; require_once DOL_DOCUMENT_ROOT.'/core/class/html.formfile.class.php'; require_once DOL_DOCUMENT_ROOT.'/core/class/html.formprojet.class.php'; -dol_include_once('/mrp/class/mo.class.php'); -dol_include_once('/mrp/lib/mrp_mo.lib.php'); +require_once DOL_DOCUMENT_ROOT.'/mrp/class/mo.class.php'; +require_once DOL_DOCUMENT_ROOT.'/mrp/lib/mrp_mo.lib.php'; +require_once DOL_DOCUMENT_ROOT.'/bom/class/bom.class.php'; // Load translation files required by the page $langs->loadLangs(array("mrp", "other")); // Get parameters -$id = GETPOST('id', 'int'); +$id = GETPOST('id', 'int'); $ref = GETPOST('ref', 'alpha'); -$action = GETPOST('action', 'aZ09'); +$action = GETPOST('action', 'aZ09'); $confirm = GETPOST('confirm', 'alpha'); $cancel = GETPOST('cancel', 'aZ09'); -$contextpage= GETPOST('contextpage', 'aZ')?GETPOST('contextpage', 'aZ'):'mocard'; // To manage different context of search +$contextpage = GETPOST('contextpage', 'aZ') ?GETPOST('contextpage', 'aZ') : 'mocard'; // To manage different context of search $backtopage = GETPOST('backtopage', 'alpha'); //$lineid = GETPOST('lineid', 'int'); // Initialize technical objects -$object=new Mo($db); +$object = new Mo($db); +$objectbom = new BOM($db); $extrafields = new ExtraFields($db); -$diroutputmassaction=$conf->mrp->dir_output . '/temp/massgeneration/'.$user->id; -$hookmanager->initHooks(array('mocard','globalcard')); // Note that conf->hooks_modules contains array +$diroutputmassaction = $conf->mrp->dir_output.'/temp/massgeneration/'.$user->id; +$hookmanager->initHooks(array('mocard', '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_'); +$search_array_options = $extrafields->getOptionalsFromPost($object->table_element, '', 'search_'); // Initialize array of search criterias -$search_all=trim(GETPOST("search_all", 'alpha')); -$search=array(); -foreach($object->fields as $key => $val) +$search_all = trim(GETPOST("search_all", 'alpha')); +$search = array(); +foreach ($object->fields as $key => $val) { - if (GETPOST('search_'.$key, 'alpha')) $search[$key]=GETPOST('search_'.$key, 'alpha'); + 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. +include DOL_DOCUMENT_ROOT.'/core/actions_fetchobject.inc.php'; // Must be include, not include_once. + +if (GETPOST('fk_bom', 'int')) +{ + $objectbom->fetch(GETPOST('fk_bom', 'int')); + + $_POST['fk_product'] = $objectbom->fk_product; + $_POST['qty'] = $objectbom->qty; + $_POST['fk_warehouse'] = $objectbom->fk_warehouse; + $_POST['note_private'] = $objectbom->note_private; +} // Security check - Protection if external user //if ($user->socid > 0) access_forbidden(); @@ -93,10 +105,11 @@ include DOL_DOCUMENT_ROOT.'/core/actions_fetchobject.inc.php'; // Must be inclu //$isdraft = (($object->statut == $object::STATUS_DRAFT) ? 1 : 0); //$result = restrictedArea($user, 'mrp', $object->id, '', '', 'fk_soc', 'rowid', $isdraft); -$permissionnote=$user->rights->mrp->write; // Used by the include of actions_setnotes.inc.php -$permissiondellink=$user->rights->mrp->write; // Used by the include of actions_dellink.inc.php -$permissiontoadd=$user->rights->mrp->write; // Used by the include of actions_addupdatedelete.inc.php and actions_lineupdown.inc.php +$permissionnote = $user->rights->mrp->write; // Used by the include of actions_setnotes.inc.php +$permissiondellink = $user->rights->mrp->write; // Used by the include of actions_dellink.inc.php +$permissiontoadd = $user->rights->mrp->write; // Used by the include of actions_addupdatedelete.inc.php and actions_lineupdown.inc.php $permissiontodelete = $user->rights->mrp->delete || ($permissiontoadd && isset($object->status) && $object->status == $object::STATUS_DRAFT); +$upload_dir = $conf->mrp->multidir_output[isset($object->entity)?$object->entity:1]; /* @@ -105,22 +118,23 @@ $permissiontodelete = $user->rights->mrp->delete || ($permissiontoadd && isset($ * Put here all code to do according to value of "action" parameter */ -$parameters=array(); -$reshook=$hookmanager->executeHooks('doActions', $parameters, $object, $action); // Note that $action and $object may have been modified by some hooks +$parameters = array(); +$reshook = $hookmanager->executeHooks('doActions', $parameters, $object, $action); // Note that $action and $object may have been modified by some hooks if ($reshook < 0) setEventMessages($hookmanager->error, $hookmanager->errors, 'errors'); if (empty($reshook)) { - $error=0; + $error = 0; $backurlforlist = dol_buildpath('/mrp/mo_list.php', 1); if (empty($backtopage) || ($cancel && empty($id))) { - //var_dump($backurlforlist);exit; - if (empty($id) && (($action != 'add' && $action != 'create') || $cancel)) $backtopage = $backurlforlist; - else $backtopage = DOL_URL_ROOT.'/mrp/mo_card.php?id='.($id > 0 ? $id : '__ID__'); + if (empty($backtopage) || ($cancel && strpos($backtopage, '__ID__'))) { + if (empty($id) && (($action != 'add' && $action != 'create') || $cancel)) $backtopage = $backurlforlist; + else $backtopage = DOL_URL_ROOT.'/mrp/mo_card.php?id='.($id > 0 ? $id : '__ID__'); + } } - $triggermodname = 'MRP_MO_MODIFY'; // Name of trigger action code to execute when we modify record + $triggermodname = 'MRP_MO_MODIFY'; // Name of trigger action code to execute when we modify record // Actions cancel, add, update, delete or clone include DOL_DOCUMENT_ROOT.'/core/actions_addupdatedelete.inc.php'; @@ -132,9 +146,9 @@ if (empty($reshook)) include DOL_DOCUMENT_ROOT.'/core/actions_printing.inc.php'; // Actions to send emails - $trigger_name='MO_SENTBYMAIL'; - $autocopy='MAIN_MAIL_AUTOCOPY_MO_TO'; - $trackid='mo'.$object->id; + $trigger_name = 'MO_SENTBYMAIL'; + $autocopy = 'MAIN_MAIL_AUTOCOPY_MO_TO'; + $trackid = 'mo'.$object->id; include DOL_DOCUMENT_ROOT.'/core/actions_sendmails.inc.php'; // Action to move up and down lines of object @@ -157,9 +171,9 @@ if (empty($reshook)) * View */ -$form=new Form($db); -$formfile=new FormFile($db); -$formproject=new FormProjets($db); +$form = new Form($db); +$formfile = new FormFile($db); +$formproject = new FormProjets($db); llxHeader('', $langs->trans('Mo'), ''); @@ -194,10 +208,10 @@ if ($action == 'create') print '
    '.$langs->trans("LatestMOModified", $max).'
    '."\n"; // Common attributes - include DOL_DOCUMENT_ROOT . '/core/tpl/commonfields_add.tpl.php'; + include DOL_DOCUMENT_ROOT.'/core/tpl/commonfields_add.tpl.php'; // Other attributes - include DOL_DOCUMENT_ROOT . '/core/tpl/extrafields_add.tpl.php'; + include DOL_DOCUMENT_ROOT.'/core/tpl/extrafields_add.tpl.php'; print '
    '."\n"; @@ -208,29 +222,52 @@ if ($action == 'create') $(document).ready(function () { jQuery('#fk_bom').change(function() { console.log('We change value of BOM with BOM of id '+jQuery('#fk_bom').val()); - - $.getJSON('/mrp/ajax/ajax_bom.php?action=getBoms&idbom='+jQuery('#fk_bom').val(), function(data) { - console.log(data); - if (typeof data.rowid != "undefined") { - console.log("New BOM loaded, we set values in form"); - $('#qty').val(data.qty); - $("#fk_product").val(data.fk_product); - $('#fk_product').trigger('change'); // Notify any JS components that the value changed - $('#note_private').val(data.description); - $('#note_private').trigger('change'); // Notify any JS components that the value changed - if (typeof CKEDITOR != "undefined") { - if (typeof CKEDITOR.instances != "undefined") { - if (typeof CKEDITOR.instances.note_private != "undefined") { - console.log(CKEDITOR.instances.note_private); - CKEDITOR.instances.note_private.setData(data.description); + if (jQuery('#fk_bom').val() > 0) + { + // Redirect to page with fk_bom set + window.location.href = '?action=create&fk_bom='+jQuery('#fk_bom').val(); + /* + $.getJSON('/mrp/ajax/ajax_bom.php?action=getBoms&idbom='+jQuery('#fk_bom').val(), function(data) { + console.log(data); + if (typeof data.rowid != "undefined") { + console.log("New BOM loaded, we set values in form"); + $('#qty').val(data.qty); + $("#fk_product").val(data.fk_product); + $('#fk_product').trigger('change'); // Notify any JS components that the value changed + $('#note_private').val(data.description); + $('#note_private').trigger('change'); // Notify any JS components that the value changed + $('#fk_warehouse').val(data.fk_warehouse); + $('#fk_warehouse').trigger('change'); // Notify any JS components that the value changed + if (typeof CKEDITOR != "undefined") { + if (typeof CKEDITOR.instances != "undefined") { + if (typeof CKEDITOR.instances.note_private != "undefined") { + console.log(CKEDITOR.instances.note_private); + CKEDITOR.instances.note_private.setData(data.description); + } } } + } else { + console.log("Failed to get BOM"); } - } else { - console.log("Failed to get BOM"); - } - }); + });*/ + } + else if (jQuery('#fk_bom').val() < 0) { + // Redirect to page with all fields defined except fk_bom set + console.log(jQuery('#fk_product').val()); + window.location.href = '?action=create&qty='+jQuery('#qty').val()+'&fk_product='+jQuery('#fk_product').val()+'&label='+jQuery('#label').val()+'&fk_project='+jQuery('#fk_project').val()+'&fk_warehouse='+jQuery('#fk_warehouse').val(); + /* + $('#qty').val(''); + $("#fk_product").val(''); + $('#fk_product').trigger('change'); // Notify any JS components that the value changed + $('#note_private').val(''); + $('#note_private').trigger('change'); // Notify any JS components that the value changed + $('#fk_warehouse').val(''); + $('#fk_warehouse').trigger('change'); // Notify any JS components that the value changed + */ + } }); + + //jQuery('#fk_bom').trigger('change'); }) '; print ''; print '  '; - print ''; // Cancel for create does not post form if we don't know the backtopage + print ''; // Cancel for create does not post form if we don't know the backtopage print '
    '; + if (GETPOST('fk_bom', 'int') > 0) { + print load_fiche_titre($langs->trans("ToConsume")); + + print '
    '; + print ''; + + $object->lines = $objectbom->lines; + + $object->printOriginLinesList('', array()); + + print '
    '; + print '
    '; + } + print ''; } @@ -262,10 +313,10 @@ if (($id || $ref) && $action == 'edit') print ''."\n"; // Common attributes - include DOL_DOCUMENT_ROOT . '/core/tpl/commonfields_edit.tpl.php'; + include DOL_DOCUMENT_ROOT.'/core/tpl/commonfields_edit.tpl.php'; // Other attributes - include DOL_DOCUMENT_ROOT . '/core/tpl/extrafields_edit.tpl.php'; + include DOL_DOCUMENT_ROOT.'/core/tpl/extrafields_edit.tpl.php'; print '
    '; @@ -292,7 +343,7 @@ if ($object->id > 0 && (empty($action) || ($action != 'edit' && $action != 'crea // Confirmation to delete if ($action == 'delete') { - $formconfirm = $form->formconfirm($_SERVER["PHP_SELF"] . '?id=' . $object->id, $langs->trans('DeleteMo'), $langs->trans('ConfirmDeleteMo'), 'confirm_delete', '', 0, 1); + $formconfirm = $form->formconfirm($_SERVER["PHP_SELF"].'?id='.$object->id, $langs->trans('DeleteMo'), $langs->trans('ConfirmDeleteMo'), 'confirm_delete', '', 0, 1); } // Confirmation to delete line if ($action == 'deleteline') @@ -321,14 +372,14 @@ if ($object->id > 0 && (empty($action) || ($action != 'edit' && $action != 'crea $text .= $notify->confirmMessage('BOM_VALIDATE', $object->socid, $object); }*/ - $formquestion=array(); - if (! empty($conf->bom->enabled)) + $formquestion = array(); + if (!empty($conf->mrp->enabled)) { $langs->load("mrp"); - require_once DOL_DOCUMENT_ROOT . '/product/class/html.formproduct.class.php'; + require_once DOL_DOCUMENT_ROOT.'/product/class/html.formproduct.class.php'; $formproduct = new FormProduct($db); - $forcecombo=0; - if ($conf->browser->name == 'ie') $forcecombo = 1; // There is a bug in IE10 that make combo inside popup crazy + $forcecombo = 0; + 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), @@ -336,21 +387,21 @@ if ($object->id > 0 && (empty($action) || ($action != 'edit' && $action != 'crea ); } - $formconfirm = $form->formconfirm($_SERVER["PHP_SELF"] . '?id=' . $object->id, $langs->trans('Validate'), $text, 'confirm_validate', $formquestion, 0, 1, 220); + $formconfirm = $form->formconfirm($_SERVER["PHP_SELF"].'?id='.$object->id, $langs->trans('Validate'), $text, 'confirm_validate', $formquestion, 0, 1, 220); } // Clone confirmation if ($action == 'clone') { // Create an array for form $formquestion = array(); - $formconfirm = $form->formconfirm($_SERVER["PHP_SELF"] . '?id=' . $object->id, $langs->trans('ToClone'), $langs->trans('ConfirmCloneMo', $object->ref), 'confirm_clone', $formquestion, 'yes', 1); + $formconfirm = $form->formconfirm($_SERVER["PHP_SELF"].'?id='.$object->id, $langs->trans('ToClone'), $langs->trans('ConfirmCloneMo', $object->ref), 'confirm_clone', $formquestion, 'yes', 1); } // Call Hook formConfirm $parameters = array('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; @@ -358,46 +409,46 @@ if ($object->id > 0 && (empty($action) || ($action != 'edit' && $action != 'crea // Object card // ------------------------------------------------------------ - $linkback = '' . $langs->trans("BackToList") . ''; + $linkback = ''.$langs->trans("BackToList").''; - $morehtmlref='
    '; + $morehtmlref = '
    '; /* // Ref bis $morehtmlref.=$form->editfieldkey("RefBis", 'ref_client', $object->ref_client, $object, $user->rights->mrp->creer, 'string', '', 0, 1); $morehtmlref.=$form->editfieldval("RefBis", 'ref_client', $object->ref_client, $object, $user->rights->mrp->creer, 'string', '', null, null, '', 1);*/ // Thirdparty - $morehtmlref.=$langs->trans('ThirdParty') . ' : ' . (is_object($object->thirdparty) ? $object->thirdparty->getNomUrl(1) : ''); + $morehtmlref .= $langs->trans('ThirdParty').' : '.(is_object($object->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').' '; if ($permissiontoadd) { if ($action != 'classify') - $morehtmlref.='' . img_edit($langs->transnoentitiesnoconv('SetProject')) . ' : '; + $morehtmlref .= ''.img_edit($langs->transnoentitiesnoconv('SetProject')).' : '; if ($action == 'classify') { //$morehtmlref.=$form->form_project($_SERVER['PHP_SELF'] . '?id=' . $object->id, $object->fk_soc, $object->fk_project, 'projectid', 0, 0, 1, 1); - $morehtmlref.='
    '; - $morehtmlref.=''; - $morehtmlref.=''; - $morehtmlref.=$formproject->select_projects($object->fk_soc, $object->fk_project, 'projectid', 0, 0, 1, 0, 1, 0, 0, '', 1); - $morehtmlref.=''; - $morehtmlref.='
    '; + $morehtmlref .= '
    '; + $morehtmlref .= ''; + $morehtmlref .= ''; + $morehtmlref .= $formproject->select_projects($object->fk_soc, $object->fk_project, 'projectid', 0, 0, 1, 0, 1, 0, 0, '', 1); + $morehtmlref .= ''; + $morehtmlref .= '
    '; } else { - $morehtmlref.=$form->form_project($_SERVER['PHP_SELF'] . '?id=' . $object->id, $object->fk_soc, $object->fk_project, 'none', 0, 0, 0, 1); + $morehtmlref .= $form->form_project($_SERVER['PHP_SELF'].'?id='.$object->id, $object->fk_soc, $object->fk_project, 'none', 0, 0, 0, 1); } } else { - if (! empty($object->fk_project)) { + if (!empty($object->fk_project)) { $proj = new Project($db); $proj->fetch($object->fk_project); - $morehtmlref.=$proj->getNomUrl(); + $morehtmlref .= $proj->getNomUrl(); } else { - $morehtmlref.=''; + $morehtmlref .= ''; } } } - $morehtmlref.='
    '; + $morehtmlref .= '
    '; dol_banner_tab($object, 'ref', $linkback, 1, 'ref', 'ref', $morehtmlref); @@ -409,13 +460,13 @@ if ($object->id > 0 && (empty($action) || ($action != 'edit' && $action != 'crea print ''."\n"; // Common attributes - $keyforbreak='fk_warehouse'; + $keyforbreak = 'fk_warehouse'; unset($object->fields['fk_project']); unset($object->fields['fk_soc']); - include DOL_DOCUMENT_ROOT . '/core/tpl/commonfields_view.tpl.php'; + include DOL_DOCUMENT_ROOT.'/core/tpl/commonfields_view.tpl.php'; // Other attributes - include DOL_DOCUMENT_ROOT . '/core/tpl/extrafields_view.tpl.php'; + include DOL_DOCUMENT_ROOT.'/core/tpl/extrafields_view.tpl.php'; print '
    '; print ''; @@ -430,29 +481,29 @@ if ($object->id > 0 && (empty($action) || ($action != 'edit' && $action != 'crea * Lines */ - if (! empty($object->table_element_line)) + if (!empty($object->table_element_line)) { // Show object lines $result = $object->getLinesArray(); - print '
    - - + print ' + + - + '; - if (! empty($conf->use_javascript_ajax) && $object->status == 0) { - include DOL_DOCUMENT_ROOT . '/core/tpl/ajaxrow.tpl.php'; + if (!empty($conf->use_javascript_ajax) && $object->status == 0) { + include DOL_DOCUMENT_ROOT.'/core/tpl/ajaxrow.tpl.php'; } 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, '/mrp/tpl'); } @@ -470,7 +521,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 '
    '; } @@ -484,8 +535,8 @@ if ($object->id > 0 && (empty($action) || ($action != 'edit' && $action != 'crea if ($action != 'presend' && $action != 'editline') { print '
    '."\n"; - $parameters=array(); - $reshook=$hookmanager->executeHooks('addMoreActionsButtons', $parameters, $object, $action); // Note that $action and $object may have been modified by hook + $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)) @@ -493,9 +544,13 @@ if ($object->id > 0 && (empty($action) || ($action != 'edit' && $action != 'crea // Send //print '' . $langs->trans('SendMail') . ''."\n"; - if ($user->rights->bom->write && $object->status == MO::STATUS_VALIDATED) + // Back to draft + if ($object->status == $object::STATUS_VALIDATED) { - print '' . $langs->trans("SetToDraft") . ''; + if ($permissiontoadd) + { + print ''.$langs->trans("SetToDraft").''; + } } // Modify @@ -509,22 +564,25 @@ if ($object->id > 0 && (empty($action) || ($action != 'edit' && $action != 'crea } // Validate - if ($user->rights->mrp->write && $object->status == MO::STATUS_DRAFT) + if ($object->status == $object::STATUS_DRAFT) { - if (is_array($object->lines) && count($object->lines) > 0) - { - print '' . $langs->trans("Validate") . ''; - } - else - { - print '' . $langs->trans("Validate") . ''; - } + if ($permissiontoadd) + { + if (is_array($object->lines) && count($object->lines) > 0) + { + print ''.$langs->trans("Validate").''; + } + else + { + print ''.$langs->trans("Validate").''; + } + } } // Clone if ($permissiontoadd) { - print '' . $langs->trans("ToClone") . ''; + print ''.$langs->trans("ToClone").''; } // Delete (need delete permission, or if draft, just need create/modify permission) @@ -553,11 +611,11 @@ if ($object->id > 0 && (empty($action) || ($action != 'edit' && $action != 'crea // Documents $objref = dol_sanitizeFileName($object->ref); - $relativepath = $objref . '/' . $objref . '.pdf'; - $filedir = $conf->mrp->dir_output . '/' . $objref; - $urlsource = $_SERVER["PHP_SELF"] . "?id=" . $object->id; - $genallowed = $user->rights->mrp->read; // If you can read, you can build the PDF to read content - $delallowed = $user->rights->mrp->create; // If you can create/edit, you can remove a file on card + $relativepath = $objref.'/'.$objref.'.pdf'; + $filedir = $conf->mrp->dir_output.'/'.$objref; + $urlsource = $_SERVER["PHP_SELF"]."?id=".$object->id; + $genallowed = $user->rights->mrp->read; // If you can read, you can build the PDF to read content + $delallowed = $user->rights->mrp->create; // If you can create/edit, you can remove a file on card print $formfile->showdocuments('mrp:mo', $objref, $filedir, $urlsource, $genallowed, $delallowed, $object->modelpdf, 1, 0, 0, 28, 0, '', '', '', $mysoc->default_lang); // Show links to link elements @@ -570,11 +628,11 @@ if ($object->id > 0 && (empty($action) || ($action != 'edit' && $action != 'crea $MAXEVENT = 10; $morehtmlright = ''; - $morehtmlright.= $langs->trans("SeeAll"); - $morehtmlright.= ''; + $morehtmlright .= $langs->trans("SeeAll"); + $morehtmlright .= ''; // List of actions on element - include_once DOL_DOCUMENT_ROOT . '/core/class/html.formactions.class.php'; + include_once DOL_DOCUMENT_ROOT.'/core/class/html.formactions.class.php'; $formactions = new FormActions($db); $somethingshown = $formactions->showactions($object, 'mo', $socid, 1, '', $MAXEVENT, '', $morehtmlright); @@ -585,8 +643,8 @@ if ($object->id > 0 && (empty($action) || ($action != 'edit' && $action != 'crea if (GETPOST('modelselected')) $action = 'presend'; // Presend form - $modelmail='mo'; - $defaulttopic='InformationMessage'; + $modelmail = 'mo'; + $defaulttopic = 'InformationMessage'; $diroutput = $conf->mrp->dir_output; $trackid = 'mo'.$object->id; diff --git a/htdocs/mrp/mo_document.php b/htdocs/mrp/mo_document.php index 2c4d1b36c99..72fab7c3517 100644 --- a/htdocs/mrp/mo_document.php +++ b/htdocs/mrp/mo_document.php @@ -133,10 +133,8 @@ if ($object->id) dol_fiche_end(); $modulepart = 'mrp'; - //$permission = $user->rights->mrp->create; - $permission = 1; - //$permtoedit = $user->rights->mrp->create; - $permtoedit = 1; + $permission = $user->rights->mrp->write; + $permtoedit = $user->rights->mrp->write; $param = '&id=' . $object->id; //$relativepathwithnofile='mo/' . dol_sanitizeFileName($object->id).'/'; diff --git a/htdocs/mrp/mo_list.php b/htdocs/mrp/mo_list.php index 6124101cffa..4d3bb9cd313 100644 --- a/htdocs/mrp/mo_list.php +++ b/htdocs/mrp/mo_list.php @@ -48,28 +48,28 @@ require_once DOL_DOCUMENT_ROOT.'/core/lib/date.lib.php'; require_once DOL_DOCUMENT_ROOT.'/core/lib/company.lib.php'; // load mrp libraries -require_once __DIR__ . '/class/mo.class.php'; +require_once __DIR__.'/class/mo.class.php'; // for other modules //dol_include_once('/othermodule/class/otherobject.class.php'); // Load translation files required by the page -$langs->loadLangs(array("mrp","other")); +$langs->loadLangs(array("mrp", "other")); -$action = GETPOST('action', 'aZ09')?GETPOST('action', 'aZ09'):'view'; // The action 'add', 'create', 'edit', 'update', 'view', ... -$massaction = GETPOST('massaction', 'alpha'); // The bulk action (combo box choice into lists) -$show_files = GETPOST('show_files', 'int'); // Show files area generated by bulk actions ? -$confirm = GETPOST('confirm', 'alpha'); // Result of a confirmation -$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'):'molist'; // 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') +$action = GETPOST('action', 'aZ09') ?GETPOST('action', 'aZ09') : 'view'; // The action 'add', 'create', 'edit', 'update', 'view', ... +$massaction = GETPOST('massaction', 'alpha'); // The bulk action (combo box choice into lists) +$show_files = GETPOST('show_files', 'int'); // Show files area generated by bulk actions ? +$confirm = GETPOST('confirm', 'alpha'); // Result of a confirmation +$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') : 'molist'; // 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') -$id = GETPOST('id', 'int'); +$id = GETPOST('id', 'int'); // Load variable for pagination -$limit = GETPOST('limit', 'int')?GETPOST('limit', 'int'):$conf->liste_limit; +$limit = GETPOST('limit', 'int') ?GETPOST('limit', 'int') : $conf->liste_limit; $sortfield = GETPOST('sortfield', 'alpha'); $sortorder = GETPOST('sortorder', 'alpha'); $page = GETPOST('page', 'int'); @@ -83,8 +83,8 @@ $pagenext = $page + 1; // Initialize technical objects $object = new Mo($db); $extrafields = new ExtraFields($db); -$diroutputmassaction = $conf->mrp->dir_output . '/temp/massgeneration/'.$user->id; -$hookmanager->initHooks(array('molist')); // Note that conf->hooks_modules contains array +$diroutputmassaction = $conf->mrp->dir_output.'/temp/massgeneration/'.$user->id; +$hookmanager->initHooks(array('molist')); // Note that conf->hooks_modules contains array // Fetch optionals attributes and labels $extrafields->fetch_name_optionals_label($object->table_element); @@ -92,12 +92,12 @@ $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->mrp->enabled)) accessforbidden('Module not enabled'); -$socid=0; +$socid = 0; if ($user->socid > 0) // Protection if external user { //$socid = $user->socid; @@ -107,34 +107,34 @@ if ($user->socid > 0) // Protection if external user // Initialize array of search criterias -$search_all=trim(GETPOST("search_all", 'alpha')); -$search=array(); -foreach($object->fields as $key => $val) +$search_all = trim(GETPOST("search_all", 'alpha')); +$search = array(); +foreach ($object->fields as $key => $val) { - if (GETPOST('search_'.$key, 'alpha')) $search[$key]=GETPOST('search_'.$key, 'alpha'); + 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) +foreach ($object->fields as $key => $val) { - if ($val['searchall']) $fieldstosearchall['t.'.$key]=$val['label']; + if ($val['searchall']) $fieldstosearchall['t.'.$key] = $val['label']; } // Definition of fields for list -$arrayfields=array(); -foreach($object->fields as $key => $val) +$arrayfields = array(); +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) + 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], 'checked'=>(($extrafields->attributes[$object->table_element]['list'][$key]<0)?0:1), 'position'=>$extrafields->attributes[$object->table_element]['pos'][$key], 'enabled'=>(abs($extrafields->attributes[$object->table_element]['list'][$key])!=3 && $extrafields->attributes[$object->table_element]['perms'][$key])); + if (!empty($extrafields->attributes[$object->table_element]['list'][$key])) + $arrayfields["ef.".$key] = array('label'=>$extrafields->attributes[$object->table_element]['label'][$key], 'checked'=>(($extrafields->attributes[$object->table_element]['list'][$key] < 0) ? 0 : 1), 'position'=>$extrafields->attributes[$object->table_element]['pos'][$key], 'enabled'=>(abs($extrafields->attributes[$object->table_element]['list'][$key]) != 3 && $extrafields->attributes[$object->table_element]['perms'][$key])); } } $object->fields = dol_sort_array($object->fields, 'position'); @@ -146,11 +146,11 @@ $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(); -$reshook=$hookmanager->executeHooks('doActions', $parameters, $object, $action); // Note that $action and $object may have been modified by some hooks +$parameters = array(); +$reshook = $hookmanager->executeHooks('doActions', $parameters, $object, $action); // Note that $action and $object may have been modified by some hooks if ($reshook < 0) setEventMessages($hookmanager->error, $hookmanager->errors, 'errors'); if (empty($reshook)) @@ -159,24 +159,24 @@ if (empty($reshook)) 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 { - foreach($object->fields as $key => $val) + foreach ($object->fields as $key => $val) { - $search[$key]=''; + $search[$key] = ''; } - $toselect=''; - $search_array_options=array(); + $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')) { - $massaction=''; // Protection to avoid mass action if we force a new search during a mass action confirmation + $massaction = ''; // Protection to avoid mass action if we force a new search during a mass action confirmation } // Mass actions - $objectclass='Mo'; - $objectlabel='Mo'; + $objectclass = 'Mo'; + $objectlabel = 'Mo'; $permissiontoread = $user->rights->mrp->read; $permissiontodelete = $user->rights->mrp->delete; $uploaddir = $conf->mrp->dir_output; @@ -189,47 +189,47 @@ if (empty($reshook)) * View */ -$form=new Form($db); +$form = new Form($db); -$now=dol_now(); +$now = dol_now(); //$help_url="EN:Module_Mo|FR:Module_Mo_FR|ES:Módulo_Mo"; -$help_url=''; +$help_url = ''; $title = $langs->trans('ListOfManufacturingOrders'); // Build and execute select // -------------------------------------------------------------------- $sql = 'SELECT '; -foreach($object->fields as $key => $val) +foreach ($object->fields as $key => $val) { - $sql.='t.'.$key.', '; + $sql .= 't.'.$key.', '; } // Add fields from extrafields -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.', ' : ''); +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.', ' : ''); // Add fields from hooks -$parameters=array(); -$reshook=$hookmanager->executeHooks('printFieldListSelect', $parameters, $object); // Note that $action and $object may have been modified by hook -$sql.=$hookmanager->resPrint; -$sql=preg_replace('/, $/', '', $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) +$parameters = array(); +$reshook = $hookmanager->executeHooks('printFieldListSelect', $parameters, $object); // Note that $action and $object may have been modified by hook +$sql .= $hookmanager->resPrint; +$sql = preg_replace('/, $/', '', $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; - $mode_search=(($object->isInt($object->fields[$key]) || $object->isFloat($object->fields[$key])) ? 1 : 0); - if ($search[$key] != '') $sql.=natural_search($key, $search[$key], (($key == 'status')?2:$mode_search)); + $mode_search = (($object->isInt($object->fields[$key]) || $object->isFloat($object->fields[$key])) ? 1 : 0); + 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 -$parameters=array(); -$reshook=$hookmanager->executeHooks('printFieldListWhere', $parameters, $object); // Note that $action and $object may have been modified by hook -$sql.=$hookmanager->resPrint; +$parameters = array(); +$reshook = $hookmanager->executeHooks('printFieldListWhere', $parameters, $object); // Note that $action and $object may have been modified by hook +$sql .= $hookmanager->resPrint; /* If a group by is required $sql.= " GROUP BY " @@ -247,7 +247,7 @@ $sql.=$hookmanager->resPrint; $sql=preg_replace('/, $/','', $sql); */ -$sql.=$db->order($sortfield, $sortorder); +$sql .= $db->order($sortfield, $sortorder); // Count total nb of records $nbtotalofrecords = ''; @@ -268,10 +268,10 @@ if (is_numeric($nbtotalofrecords) && $limit > $nbtotalofrecords) } else { - $sql.= $db->plimit($limit+1, $offset); + $sql .= $db->plimit($limit + 1, $offset); - $resql=$db->query($sql); - if (! $resql) + $resql = $db->query($sql); + if (!$resql) { dol_print_error($db); exit; @@ -281,7 +281,7 @@ else } // Direct jump if only one record found -if ($num == 1 && ! empty($conf->global->MAIN_SEARCH_DIRECT_OPEN_IF_ONLY_ONE) && $search_all) +if ($num == 1 && !empty($conf->global->MAIN_SEARCH_DIRECT_OPEN_IF_ONLY_ONE) && $search_all) { $obj = $db->fetch_object($resql); $id = $obj->rowid; @@ -310,30 +310,30 @@ jQuery(document).ready(function() { }); '; -$arrayofselected=is_array($toselect)?$toselect:array(); +$arrayofselected = is_array($toselect) ? $toselect : array(); -$param=''; -if (! empty($contextpage) && $contextpage != $_SERVER["PHP_SELF"]) $param.='&contextpage='.urlencode($contextpage); -if ($limit > 0 && $limit != $conf->liste_limit) $param.='&limit='.urlencode($limit); -foreach($search as $key => $val) +$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 (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'; // List of mass actions available -$arrayofmassactions = array( +$arrayofmassactions = array( //'validate'=>$langs->trans("Validate"), //'generate_doc'=>$langs->trans("ReGeneratePDF"), //'builddoc'=>$langs->trans("PDFMerge"), //'presend'=>$langs->trans("SendByMail"), ); -if ($user->rights->mrp->delete) $arrayofmassactions['predelete']=''.$langs->trans("Delete"); -if (GETPOST('nomassaction', 'int') || in_array($massaction, array('presend','predelete'))) $arrayofmassactions=array(); -$massactionbutton=$form->selectMassAction('', $arrayofmassactions); +if ($user->rights->mrp->delete) $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 ''; @@ -350,16 +350,16 @@ $newcardbutton = dolGetButtonTitle($langs->trans('New'), '', 'fa fa-plus-circle' print_barre_liste($title, $page, $_SERVER["PHP_SELF"], $param, $sortfield, $sortorder, $massactionbutton, $num, $nbtotalofrecords, 'cubes', 0, $newcardbutton, '', $limit); // Add code for pre mass action (confirmation or email presend form) -$topicmail="SendMoRef"; -$modelmail="mo"; -$objecttmp=new Mo($db); -$trackid='xxxx'.$object->id; +$topicmail = "SendMoRef"; +$modelmail = "mo"; +$objecttmp = new Mo($db); +$trackid = 'xxxx'.$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); - print '
    '.$langs->trans("FilterOnInto", $search_all) . join(', ', $fieldstosearchall).'
    '; + foreach ($fieldstosearchall as $key => $val) $fieldstosearchall[$key] = $langs->trans($val); + print '
    '.$langs->trans("FilterOnInto", $search_all).join(', ', $fieldstosearchall).'
    '; } $moreforfilter = ''; @@ -367,39 +367,39 @@ $moreforfilter = ''; $moreforfilter.= $langs->trans('MyFilter') . ': '; $moreforfilter.= '
    ';*/ -$parameters=array(); -$reshook=$hookmanager->executeHooks('printFieldPreListTitle', $parameters, $object); // Note that $action and $object may have been modified by hook +$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($moreforfilter)) +if (!empty($moreforfilter)) { print '
    '; print $moreforfilter; print '
    '; } -$varpage=empty($contextpage)?$_SERVER["PHP_SELF"]:$contextpage; -$selectedfields=$form->multiSelectArrayWithCheckbox('selectedfields', $arrayfields, $varpage); // This also change content of $arrayfields -$selectedfields.=(count($arrayofmassactions) ? $form->showCheckAddButtons('checkforselect', 1) : ''); +$varpage = empty($contextpage) ? $_SERVER["PHP_SELF"] : $contextpage; +$selectedfields = $form->multiSelectArrayWithCheckbox('selectedfields', $arrayfields, $varpage); // This also change content of $arrayfields +$selectedfields .= (count($arrayofmassactions) ? $form->showCheckAddButtons('checkforselect', 1) : ''); -print '
    '; // You can use div-table-responsive-no-min if you dont need reserved height for your table -print ''."\n"; +print '
    '; // You can use div-table-responsive-no-min if you dont need reserved height for your table +print '
    '."\n"; // Fields title search // -------------------------------------------------------------------- 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'])) + $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'])) { - print ''; @@ -409,12 +409,12 @@ foreach($object->fields as $key => $val) include DOL_DOCUMENT_ROOT.'/core/tpl/extrafields_list_search_input.tpl.php'; // Fields from hook -$parameters=array('arrayfields'=>$arrayfields); -$reshook=$hookmanager->executeHooks('printFieldListOption', $parameters, $object); // Note that $action and $object may have been modified by hook +$parameters = array('arrayfields'=>$arrayfields); +$reshook = $hookmanager->executeHooks('printFieldListOption', $parameters, $object); // Note that $action and $object may have been modified by hook print $hookmanager->resPrint; // Action column print ''; print ''."\n"; @@ -423,23 +423,23 @@ 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'])) + $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'])) { - print getTitleFieldOfList($arrayfields['t.'.$key]['label'], 0, $_SERVER['PHP_SELF'], 't.'.$key, '', $param, ($cssforfield?'class="'.$cssforfield.'"':''), $sortfield, $sortorder, ($cssforfield?$cssforfield.' ':''))."\n"; + print getTitleFieldOfList($arrayfields['t.'.$key]['label'], 0, $_SERVER['PHP_SELF'], 't.'.$key, '', $param, ($cssforfield ? 'class="'.$cssforfield.'"' : ''), $sortfield, $sortorder, ($cssforfield ? $cssforfield.' ' : ''))."\n"; } } // 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, $object); // Note that $action and $object may have been modified by hook +$parameters = array('arrayfields'=>$arrayfields, 'param'=>$param, 'sortfield'=>$sortfield, 'sortorder'=>$sortorder); +$reshook = $hookmanager->executeHooks('printFieldListTitle', $parameters, $object); // Note that $action and $object may have been modified by hook print $hookmanager->resPrint; // Action column print getTitleFieldOfList($selectedfields, 0, $_SERVER["PHP_SELF"], '', '', '', '', $sortfield, $sortorder, 'center maxwidthsearch ')."\n"; @@ -447,56 +447,56 @@ print ''."\n"; // Detect if we need a fetch on each output line -$needToFetchEachLine=0; +$needToFetchEachLine = 0; if (is_array($extrafields->attributes[$object->table_element]['computed']) && count($extrafields->attributes[$object->table_element]['computed']) > 0) { foreach ($extrafields->attributes[$object->table_element]['computed'] as $key => $val) { - if (preg_match('/\$object/', $val)) $needToFetchEachLine++; // There is at least one compute field that use $object + if (preg_match('/\$object/', $val)) $needToFetchEachLine++; // There is at least one compute field that use $object } } // Loop on record // -------------------------------------------------------------------- -$i=0; -$totalarray=array(); +$i = 0; +$totalarray = array(); while ($i < min($num, $limit)) { $obj = $db->fetch_object($resql); - if (empty($obj)) break; // Should not happen + if (empty($obj)) break; // Should not happen // Store properties in $object $object->id = $obj->rowid; - foreach($object->fields as $key => $val) + foreach ($object->fields as $key => $val) { if (property_exists($obj, $key)) $object->$key = $obj->$key; } // 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'; + $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('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($val['type'], array('double(24,8)', 'double(6,3)', 'integer', 'real', 'price')) && $key != 'status') $cssforfield .= ($cssforfield ? ' ' : '').'right'; - if (! empty($arrayfields['t.'.$key]['checked'])) + if (!empty($arrayfields['t.'.$key]['checked'])) { print ''; if ($key == 'status') print $object->getLibStatut(5); - elseif (in_array($val['type'], array('date','datetime','timestamp'))) print $object->showOutputField($val, $key, $db->jdate($obj->$key), ''); + elseif (in_array($val['type'], array('date', 'datetime', 'timestamp'))) print $object->showOutputField($val, $key, $db->jdate($obj->$key), ''); else print $object->showOutputField($val, $key, $obj->$key, ''); print ''; - if (! $i) $totalarray['nbfield']++; - if (! empty($val['isameasure'])) + if (!$i) $totalarray['nbfield']++; + if (!empty($val['isameasure'])) { - if (! $i) $totalarray['pos'][$totalarray['nbfield']]='t.'.$key; + if (!$i) $totalarray['pos'][$totalarray['nbfield']] = 't.'.$key; $totalarray['val']['t.'.$key] += $obj->$key; } } @@ -504,19 +504,19 @@ while ($i < min($num, $limit)) // Extra fields include DOL_DOCUMENT_ROOT.'/core/tpl/extrafields_list_print_fields.tpl.php'; // Fields from hook - $parameters=array('arrayfields'=>$arrayfields, 'obj'=>$obj); - $reshook=$hookmanager->executeHooks('printFieldListValue', $parameters, $object); // Note that $action and $object may have been modified by hook + $parameters = array('arrayfields'=>$arrayfields, 'obj'=>$obj); + $reshook = $hookmanager->executeHooks('printFieldListValue', $parameters, $object); // Note that $action and $object may have been modified by hook print $hookmanager->resPrint; // Action column print ''; - if (! $i) $totalarray['nbfield']++; + if (!$i) $totalarray['nbfield']++; print ''; @@ -530,16 +530,16 @@ include DOL_DOCUMENT_ROOT.'/core/tpl/list_print_total.tpl.php'; // If no record found if ($num == 0) { - $colspan=1; - foreach($arrayfields as $key => $val) { if (! empty($val['checked'])) $colspan++; } + $colspan = 1; + foreach ($arrayfields as $key => $val) { if (!empty($val['checked'])) $colspan++; } print ''; } $db->free($resql); -$parameters=array('arrayfields'=>$arrayfields, 'sql'=>$sql); -$reshook=$hookmanager->executeHooks('printFieldListFooter', $parameters, $object); // Note that $action and $object may have been modified by hook +$parameters = array('arrayfields'=>$arrayfields, 'sql'=>$sql); +$reshook = $hookmanager->executeHooks('printFieldListFooter', $parameters, $object); // Note that $action and $object may have been modified by hook print $hookmanager->resPrint; print '
    '; + print ''; if (is_array($val['arrayofkeyval'])) print $form->selectarray('search_'.$key, $val['arrayofkeyval'], $search[$key], $val['notnull'], 0, 0, '', 1, 0, 0, '', 'maxwidth75'); else print ''; print ''; -$searchpicto=$form->showFilterButtons(); +$searchpicto = $form->showFilterButtons(); print $searchpicto; print '
    '; if ($massactionbutton || $massaction) // If we are in select mode (massactionbutton defined) or if we have already selected and sent an action ($massaction) defined { - $selected=0; - if (in_array($obj->rowid, $arrayofselected)) $selected=1; - print ''; + $selected = 0; + if (in_array($obj->rowid, $arrayofselected)) $selected = 1; + print ''; } print '
    '.$langs->trans("NoRecordFound").'
    '."\n"; @@ -549,19 +549,19 @@ print ''."\n"; if (in_array('builddoc', $arrayofmassactions) && ($nbtotalofrecords === '' || $nbtotalofrecords)) { - $hidegeneratedfilelistifempty=1; - if ($massaction == 'builddoc' || $action == 'remove_file' || $show_files) $hidegeneratedfilelistifempty=0; + $hidegeneratedfilelistifempty = 1; + 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); // Show list of available documents - $urlsource=$_SERVER['PHP_SELF'].'?sortfield='.$sortfield.'&sortorder='.$sortorder; - $urlsource.=str_replace('&', '&', $param); + $urlsource = $_SERVER['PHP_SELF'].'?sortfield='.$sortfield.'&sortorder='.$sortorder; + $urlsource .= str_replace('&', '&', $param); - $filedir=$diroutputmassaction; - $genallowed=$user->rights->mrp->read; - $delallowed=$user->rights->mrp->write; + $filedir = $diroutputmassaction; + $genallowed = $user->rights->mrp->read; + $delallowed = $user->rights->mrp->write; print $formfile->showdocuments('massfilesarea_mrp', '', $filedir, $urlsource, 0, $delallowed, '', 1, 1, 0, 48, 1, $param, $title, '', '', '', null, $hidegeneratedfilelistifempty); } diff --git a/htdocs/mrp/mo_production.php b/htdocs/mrp/mo_production.php index 8dc7ee4c625..2b63065f72c 100644 --- a/htdocs/mrp/mo_production.php +++ b/htdocs/mrp/mo_production.php @@ -54,49 +54,50 @@ dol_include_once('/mrp/lib/mrp_mo.lib.php'); $langs->loadLangs(array("mrp", "other")); // Get parameters -$id = GETPOST('id', 'int'); +$id = GETPOST('id', 'int'); $ref = GETPOST('ref', 'alpha'); -$action = GETPOST('action', 'aZ09'); +$action = GETPOST('action', 'aZ09'); $confirm = GETPOST('confirm', 'alpha'); $cancel = GETPOST('cancel', 'aZ09'); -$contextpage= GETPOST('contextpage', 'aZ')?GETPOST('contextpage', 'aZ'):'mocard'; // To manage different context of search +$contextpage = GETPOST('contextpage', 'aZ') ?GETPOST('contextpage', 'aZ') : 'mocard'; // To manage different context of search $backtopage = GETPOST('backtopage', 'alpha'); //$lineid = GETPOST('lineid', 'int'); // Initialize technical objects -$object=new Mo($db); +$object = new Mo($db); $extrafields = new ExtraFields($db); -$diroutputmassaction=$conf->mrp->dir_output . '/temp/massgeneration/'.$user->id; -$hookmanager->initHooks(array('mocard','globalcard')); // Note that conf->hooks_modules contains array +$diroutputmassaction = $conf->mrp->dir_output.'/temp/massgeneration/'.$user->id; +$hookmanager->initHooks(array('mocard', '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_'); +$search_array_options = $extrafields->getOptionalsFromPost($object->table_element, '', 'search_'); // Initialize array of search criterias -$search_all=trim(GETPOST("search_all", 'alpha')); -$search=array(); -foreach($object->fields as $key => $val) +$search_all = trim(GETPOST("search_all", 'alpha')); +$search = array(); +foreach ($object->fields as $key => $val) { - if (GETPOST('search_'.$key, 'alpha')) $search[$key]=GETPOST('search_'.$key, 'alpha'); + 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. +include DOL_DOCUMENT_ROOT.'/core/actions_fetchobject.inc.php'; // Must be include, not include_once. // Security check - Protection if external user //if ($user->socid > 0) access_forbidden(); //if ($user->socid > 0) $socid = $user->socid; -//$isdraft = (($object->statut == Mo::STATUS_DRAFT) ? 1 : 0); +//$isdraft = (($object->statut == $object::STATUS_DRAFT) ? 1 : 0); //$result = restrictedArea($user, 'mrp', $object->id, '', '', 'fk_soc', 'rowid', $isdraft); -$permissionnote=$user->rights->mrp->write; // Used by the include of actions_setnotes.inc.php -$permissiondellink=$user->rights->mrp->write; // Used by the include of actions_dellink.inc.php -$permissiontoadd=$user->rights->mrp->write; // Used by the include of actions_addupdatedelete.inc.php and actions_lineupdown.inc.php -$permissiontodelete = $user->rights->mrp->delete || ($permissiontoadd && $object->status == 0); +$permissionnote = $user->rights->mrp->write; // Used by the include of actions_setnotes.inc.php +$permissiondellink = $user->rights->mrp->write; // Used by the include of actions_dellink.inc.php +$permissiontoadd = $user->rights->mrp->write; // Used by the include of actions_addupdatedelete.inc.php and actions_lineupdown.inc.php +$permissiontodelete = $user->rights->mrp->delete || ($permissiontoadd && isset($object->status) && $object->status == $object::STATUS_DRAFT); +$upload_dir = $conf->mrp->multidir_output[isset($object->entity)?$object->entity:1]; /* @@ -105,13 +106,13 @@ $permissiontodelete = $user->rights->mrp->delete || ($permissiontoadd && $object * Put here all code to do according to value of "action" parameter */ -$parameters=array(); -$reshook=$hookmanager->executeHooks('doActions', $parameters, $object, $action); // Note that $action and $object may have been modified by some hooks +$parameters = array(); +$reshook = $hookmanager->executeHooks('doActions', $parameters, $object, $action); // Note that $action and $object may have been modified by some hooks if ($reshook < 0) setEventMessages($hookmanager->error, $hookmanager->errors, 'errors'); if (empty($reshook)) { - $error=0; + $error = 0; $backurlforlist = dol_buildpath('/mrp/mo_list.php', 1); @@ -120,7 +121,7 @@ if (empty($reshook)) if (empty($id) && (($action != 'add' && $action != 'create') || $cancel)) $backtopage = $backurlforlist; else $backtopage = DOL_URL_ROOT.'/mrp/mo_card.php?id='.($id > 0 ? $id : '__ID__'); } - $triggermodname = 'MRP_MO_MODIFY'; // Name of trigger action code to execute when we modify record + $triggermodname = 'MRP_MO_MODIFY'; // Name of trigger action code to execute when we modify record // Actions cancel, add, update, delete or clone include DOL_DOCUMENT_ROOT.'/core/actions_addupdatedelete.inc.php'; @@ -131,6 +132,12 @@ if (empty($reshook)) // Actions when printing a doc from card include DOL_DOCUMENT_ROOT.'/core/actions_printing.inc.php'; + // Actions to send emails + $trigger_name = 'MO_SENTBYMAIL'; + $autocopy = 'MAIN_MAIL_AUTOCOPY_MO_TO'; + $trackid = 'mo'.$object->id; + include DOL_DOCUMENT_ROOT.'/core/actions_sendmails.inc.php'; + // Action to move up and down lines of object //include DOL_DOCUMENT_ROOT.'/core/actions_lineupdown.inc.php'; // Must be include, not include_once @@ -142,12 +149,6 @@ if (empty($reshook)) { $object->setProject(GETPOST('projectid', 'int')); } - - // Actions to send emails - $trigger_name='MO_SENTBYMAIL'; - $autocopy='MAIN_MAIL_AUTOCOPY_MO_TO'; - $trackid='mo'.$object->id; - include DOL_DOCUMENT_ROOT.'/core/actions_sendmails.inc.php'; } @@ -157,8 +158,9 @@ if (empty($reshook)) * View */ -$form=new Form($db); -$formproject=new FormProjets($db); +$form = new Form($db); +$formfile = new FormFile($db); +$formproject = new FormProjets($db); llxHeader('', $langs->trans('Mo'), ''); @@ -182,7 +184,8 @@ jQuery(document).ready(function() { // Part to show record if ($object->id > 0 && (empty($action) || ($action != 'edit' && $action != 'create'))) { - $res = $object->fetch_optionals(); + $res = $object->fetch_thirdparty(); + $res = $object->fetch_optionals(); $head = moPrepareHead($object); dol_fiche_head($head, 'production', $langs->trans("MO"), -1, $object->picto); @@ -192,7 +195,7 @@ if ($object->id > 0 && (empty($action) || ($action != 'edit' && $action != 'crea // Confirmation to delete if ($action == 'delete') { - $formconfirm = $form->formconfirm($_SERVER["PHP_SELF"] . '?id=' . $object->id, $langs->trans('DeleteMo'), $langs->trans('ConfirmDeleteMo'), 'confirm_delete', '', 0, 1); + $formconfirm = $form->formconfirm($_SERVER["PHP_SELF"].'?id='.$object->id, $langs->trans('DeleteMo'), $langs->trans('ConfirmDeleteMo'), 'confirm_delete', '', 0, 1); } // Confirmation to delete line if ($action == 'deleteline') @@ -203,13 +206,13 @@ if ($object->id > 0 && (empty($action) || ($action != 'edit' && $action != 'crea if ($action == 'clone') { // Create an array for form $formquestion = array(); - $formconfirm = $form->formconfirm($_SERVER["PHP_SELF"] . '?id=' . $object->id, $langs->trans('ToClone'), $langs->trans('ConfirmCloneMo', $object->ref), 'confirm_clone', $formquestion, 'yes', 1); + $formconfirm = $form->formconfirm($_SERVER["PHP_SELF"].'?id='.$object->id, $langs->trans('ToClone'), $langs->trans('ConfirmCloneMo', $object->ref), 'confirm_clone', $formquestion, 'yes', 1); } // Confirmation of action xxxx if ($action == 'xxx') { - $formquestion=array(); + $formquestion = array(); /* $forcecombo=0; if ($conf->browser->name == 'ie') $forcecombo = 1; // There is a bug in IE10 that make combo inside popup crazy @@ -220,14 +223,14 @@ if ($object->id > 0 && (empty($action) || ($action != 'edit' && $action != 'crea // array('type' => 'other', 'name' => 'idwarehouse', 'label' => $langs->trans("SelectWarehouseForStockDecrease"), 'value' => $formproduct->selectWarehouses(GETPOST('idwarehouse')?GETPOST('idwarehouse'):'ifone', 'idwarehouse', '', 1, 0, 0, '', 0, $forcecombo)) ); */ - $formconfirm = $form->formconfirm($_SERVER["PHP_SELF"] . '?id=' . $object->id, $langs->trans('XXX'), $text, 'confirm_xxx', $formquestion, 0, 1, 220); + $formconfirm = $form->formconfirm($_SERVER["PHP_SELF"].'?id='.$object->id, $langs->trans('XXX'), $text, 'confirm_xxx', $formquestion, 0, 1, 220); } // Call Hook formConfirm $parameters = array('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; @@ -235,46 +238,46 @@ if ($object->id > 0 && (empty($action) || ($action != 'edit' && $action != 'crea // Object card // ------------------------------------------------------------ - $linkback = '' . $langs->trans("BackToList") . ''; + $linkback = ''.$langs->trans("BackToList").''; - $morehtmlref='
    '; + $morehtmlref = '
    '; /* // Ref bis $morehtmlref.=$form->editfieldkey("RefBis", 'ref_client', $object->ref_client, $object, $user->rights->mrp->creer, 'string', '', 0, 1); $morehtmlref.=$form->editfieldval("RefBis", 'ref_client', $object->ref_client, $object, $user->rights->mrp->creer, 'string', '', null, null, '', 1);*/ // Thirdparty - $morehtmlref.=$langs->trans('ThirdParty') . ' : ' . $object->thirdparty->getNomUrl(1); + $morehtmlref .= $langs->trans('ThirdParty').' : '.(is_object($object->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->mrp->write) + $morehtmlref .= '
    '.$langs->trans('Project').' '; + if ($permissiontoadd) { if ($action != 'classify') - $morehtmlref.='' . img_edit($langs->transnoentitiesnoconv('SetProject')) . ' : '; + $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.='
    '; + //$morehtmlref.=$form->form_project($_SERVER['PHP_SELF'] . '?id=' . $object->id, $object->fk_soc, $object->fk_project, 'projectid', 0, 0, 1, 1); + $morehtmlref .= '
    '; + $morehtmlref .= ''; + $morehtmlref .= ''; + $morehtmlref .= $formproject->select_projects($object->fk_soc, $object->fk_project, 'projectid', 0, 0, 1, 0, 1, 0, 0, '', 1); + $morehtmlref .= ''; + $morehtmlref .= '
    '; } else { - $morehtmlref.=$form->form_project($_SERVER['PHP_SELF'] . '?id=' . $object->id, $object->socid, $object->fk_project, 'none', 0, 0, 0, 1); + $morehtmlref .= $form->form_project($_SERVER['PHP_SELF'].'?id='.$object->id, $object->fk_soc, $object->fk_project, 'none', 0, 0, 0, 1); } } else { - if (! empty($object->fk_project)) { + if (!empty($object->fk_project)) { $proj = new Project($db); $proj->fetch($object->fk_project); - $morehtmlref.=$proj->getNomUrl(); + $morehtmlref .= $proj->getNomUrl(); } else { - $morehtmlref.=''; + $morehtmlref .= ''; } } } - $morehtmlref.='
    '; + $morehtmlref .= '
    '; dol_banner_tab($object, 'ref', $linkback, 1, 'ref', 'ref', $morehtmlref); @@ -283,16 +286,16 @@ if ($object->id > 0 && (empty($action) || ($action != 'edit' && $action != 'crea print '
    '; print '
    '; print '
    '; - print ''."\n"; + print '
    '."\n"; // Common attributes - $keyforbreak='qty'; + $keyforbreak = 'fk_warehouse'; unset($object->fields['fk_project']); unset($object->fields['fk_soc']); - include DOL_DOCUMENT_ROOT . '/core/tpl/commonfields_view.tpl.php'; + include DOL_DOCUMENT_ROOT.'/core/tpl/commonfields_view.tpl.php'; // Other attributes - include DOL_DOCUMENT_ROOT . '/core/tpl/extrafields_view.tpl.php'; + include DOL_DOCUMENT_ROOT.'/core/tpl/extrafields_view.tpl.php'; print '
    '; print '
    '; @@ -307,31 +310,31 @@ if ($object->id > 0 && (empty($action) || ($action != 'edit' && $action != 'crea * Lines */ - if (! empty($object->table_element_line)) + if (!empty($object->table_element_line)) { // Show object lines $result = $object->getLinesArray(); - print '
    - - + print ' + + - + '; - if (! empty($conf->use_javascript_ajax) && $object->status == 0) { - include DOL_DOCUMENT_ROOT . '/core/tpl/ajaxrow.tpl.php'; + if (!empty($conf->use_javascript_ajax) && $object->status == 0) { + include DOL_DOCUMENT_ROOT.'/core/tpl/ajaxrow.tpl.php'; } print '
    '; - if (! empty($object->lines) && $object->status == 0 && $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); + $object->printObjectLines($action, $mysoc, null, GETPOST('lineid', 'int'), 1, '/mrp/tpl'); } // Form to add new line @@ -340,14 +343,14 @@ if ($object->id > 0 && (empty($action) || ($action != 'edit' && $action != 'crea if ($action != 'editline') { // Add products/services form - $object->formAddObjectLine(1, $mysoc, $soc); + $object->formAddObjectLine(1, $mysoc, $soc, '/mrp/tpl'); $parameters = array(); $reshook = $hookmanager->executeHooks('formAddObjectLine', $parameters, $object, $action); // Note that $action and $object may have been modified by hook } } - if (! empty($object->lines) && $object->status == 0 && $permissiontoadd && $action != 'selectlines' && $action != 'editline') + if (!empty($object->lines) || ($object->status == $object::STATUS_DRAFT && $permissiontoadd && $action != 'selectlines' && $action != 'editline')) { print '
    '; } diff --git a/htdocs/mrp/tpl/originproductline.tpl.php b/htdocs/mrp/tpl/originproductline.tpl.php new file mode 100644 index 00000000000..67032eea7fe --- /dev/null +++ b/htdocs/mrp/tpl/originproductline.tpl.php @@ -0,0 +1,44 @@ + +/* Copyright (C) 2017 Charlie Benke + * + * This program is free software; you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation; either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + */ + +// Protection to avoid direct call of template +if (empty($conf) || ! is_object($conf)) +{ + print "Error, template page can't be called as URL"; + exit; +} + +?> + + +tpl['strike'])?'':' strikefordisabled').'">'; +print '
    '.$this->tpl['label'].''.$this->tpl['qty'].''.yn($this->tpl['qty_frozen']).''.yn($this->tpl['disable_stock_change']).''.$this->tpl['efficiency'].''; +//print ''; +print '
    '; // Type -$type=($object->format=="A")?'classic':'date'; +$type = ($object->format == "A") ? 'classic' : 'date'; print ''; +print img_picto('', dol_buildpath('/opensurvey/img/'.($type == 'classic' ? 'chart-32.png' : 'calendar-32.png'), 1), 'width="16"', 1); +print ' '.$langs->trans($type == 'classic' ? "TypeClassic" : "TypeDate").''; // Title print ''; // Description -print ''; // EMail //If linked user, then emails are going to be sent to users' email if (!$object->fk_user_creat) { - print ''; print ''; @@ -300,14 +300,14 @@ print ''; print ''; // Expire date print ''; // Author print ''; print '
    '.$langs->trans("Type").''; -print img_picto('', dol_buildpath('/opensurvey/img/'.($type == 'classic'?'chart-32.png':'calendar-32.png'), 1), 'width="16"', 1); -print ' '.$langs->trans($type=='classic'?"TypeClassic":"TypeDate").'
    '; -$adresseadmin=$object->mail_admin; -print $langs->trans("Title") .''; +$adresseadmin = $object->mail_admin; +print $langs->trans("Title").''; if ($action == 'edit') { print ''; @@ -245,22 +245,22 @@ else print dol_htmlentities($object->titre); print '
    '.$langs->trans("Description") .''; +print '
    '.$langs->trans("Description").''; if ($action == 'edit') { - $doleditor=new DolEditor('nouveauxcommentaires', dol_htmlentities($object->commentaires), '', 120, 'dolibarr_notes', 'In', 1, 1, 1, ROWS_7, '90%'); + $doleditor = new DolEditor('nouveauxcommentaires', dol_htmlentities($object->commentaires), '', 120, 'dolibarr_notes', 'In', 1, 1, 1, ROWS_7, '90%'); $doleditor->Create(0, ''); } else { - print (dol_textishtml($object->commentaires)?$object->commentaires:dol_nl2br($object->commentaires, 1, true)); + print (dol_textishtml($object->commentaires) ? $object->commentaires : dol_nl2br($object->commentaires, 1, true)); } print '
    '.$langs->trans("EMail") .''; + print '
    '.$langs->trans("EMail").''; if ($action == 'edit') { print ''; @@ -273,7 +273,7 @@ if (!$object->fk_user_creat) { print '
    '.$langs->trans('ToReceiveEMailForEachVote').''; if ($action == 'edit') { - print 'mailsonde?'checked="checked"':'').'">'; + print 'mailsonde ? 'checked="checked"' : '').'">'; } else { print yn($object->mailsonde); @@ -291,7 +291,7 @@ print '
    '.$langs->trans('CanComment').''; if ($action == 'edit') { - print 'allow_comments?'checked="checked"':'').'">'; + print 'allow_comments ? 'checked="checked"' : '').'">'; } else print yn($object->allow_comments); print '
    '.$langs->trans('CanSeeOthersVote').''; if ($action == 'edit') { - print 'allow_spy?'checked="checked"':'').'">'; + print 'allow_spy ? 'checked="checked"' : '').'">'; } else print yn($object->allow_spy); print '
    '.$langs->trans('ExpireDate').''; -if ($action == 'edit') print $form->selectDate($expiredate?$expiredate:$object->date_fin, 'expire', 0, 0, 0, '', 1, 0); +if ($action == 'edit') print $form->selectDate($expiredate ? $expiredate : $object->date_fin, 'expire', 0, 0, 0, '', 1, 0); else { print dol_print_date($object->date_fin, 'day'); @@ -317,7 +317,7 @@ print '
    '; -print $langs->trans("Author") .''; +print $langs->trans("Author").''; if ($object->fk_user_creat) { print $userstatic->getLoginUrl(1); } else { @@ -329,11 +329,11 @@ print '
    '.img_picto('', 'globe').' '.$langs->trans("UrlForSurvey", '').''; // Define $urlwithroot -$urlwithouturlroot=preg_replace('/'.preg_quote(DOL_URL_ROOT, '/').'$/i', '', trim($dolibarr_main_url_root)); -$urlwithroot=$urlwithouturlroot.DOL_URL_ROOT; // This is to use external domain name found into config file +$urlwithouturlroot = preg_replace('/'.preg_quote(DOL_URL_ROOT, '/').'$/i', '', trim($dolibarr_main_url_root)); +$urlwithroot = $urlwithouturlroot.DOL_URL_ROOT; // This is to use external domain name found into config file //$urlwithroot=DOL_MAIN_URL_ROOT; // This is to use same domain name than current -$url=$urlwithroot.'/public/opensurvey/studs.php?sondage='.$object->id_sondage; +$url = $urlwithroot.'/public/opensurvey/studs.php?sondage='.$object->id_sondage; print ''; if ($action != 'edit') print ajax_autoselect("opensurveyurl", $url); @@ -365,17 +365,17 @@ print '
    '; if ($action != 'edit' && $user->rights->opensurvey->write) { //Modify button - print ''.$langs->trans("Modify") . ''; + print ''.$langs->trans("Modify").''; if ($object->status == Opensurveysondage::STATUS_VALIDATED) { //Close button - print ''.$langs->trans("Close") . ''; + print ''.$langs->trans("Close").''; } if ($object->status == Opensurveysondage::STATUS_CLOSED) { //Opened button - print ''.$langs->trans("ReOpen") . ''; + print ''.$langs->trans("ReOpen").''; } //Delete button @@ -419,12 +419,12 @@ print '
    '; // Add comment if ($object->allow_comments) { - print $langs->trans("AddACommentForPoll") . '
    '; + print $langs->trans("AddACommentForPoll").'
    '; print '
    '."\n"; - print $langs->trans("Name") .':
    '."\n"; + print $langs->trans("Name").':
    '."\n"; print '
    '."\n"; - if (isset($erreur_commentaire_vide) && $erreur_commentaire_vide=="yes") { - print "" . $langs->trans("ErrorFieldRequired", $langs->transnoentitiesnoconv("Name")) . ""; + if (isset($erreur_commentaire_vide) && $erreur_commentaire_vide == "yes") { + print "".$langs->trans("ErrorFieldRequired", $langs->transnoentitiesnoconv("Name")).""; } } diff --git a/htdocs/opensurvey/index.php b/htdocs/opensurvey/index.php index ad7f78938c6..92bcd788ad6 100644 --- a/htdocs/opensurvey/index.php +++ b/htdocs/opensurvey/index.php @@ -1,6 +1,7 @@ * Copyright (C) 2019 Nicolas ZABOURI + * Copyright (C) 2019 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 @@ -63,7 +64,8 @@ print load_fiche_titre($title, '', 'wrench'); print '
    '; -print ''; +print '
    '; +print '
    '; print ''; print ''; print ''; @@ -72,6 +74,7 @@ print ""; //print $total; //print ''; print '
    '.$langs->trans("OpenSurveyArea").'
    '.$langs->trans("NbOfSurveys").''.$nbsondages.'
    '; +print '
    '; print '
    '; diff --git a/htdocs/opensurvey/list.php b/htdocs/opensurvey/list.php index aa01088744f..6f5fd824b06 100644 --- a/htdocs/opensurvey/list.php +++ b/htdocs/opensurvey/list.php @@ -30,23 +30,23 @@ require_once DOL_DOCUMENT_ROOT."/opensurvey/class/opensurveysondage.class.php"; // Load translation files required by the page $langs->load("opensurvey"); -$action = GETPOST('action', 'aZ09')?GETPOST('action', 'aZ09'):'view'; // The action 'add', 'create', 'edit', 'update', 'view', ... -$massaction = GETPOST('massaction', 'alpha'); // The bulk action (combo box choice into lists) -$show_files = GETPOST('show_files', 'int'); // Show files area generated by bulk actions ? -$confirm = GETPOST('confirm', 'alpha'); // Result of a confirmation -$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'):'myobjectlist'; // 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') +$action = GETPOST('action', 'aZ09') ?GETPOST('action', 'aZ09') : 'view'; // The action 'add', 'create', 'edit', 'update', 'view', ... +$massaction = GETPOST('massaction', 'alpha'); // The bulk action (combo box choice into lists) +$show_files = GETPOST('show_files', 'int'); // Show files area generated by bulk actions ? +$confirm = GETPOST('confirm', 'alpha'); // Result of a confirmation +$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') : 'myobjectlist'; // 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') -$id=GETPOST('id', 'alpha'); +$id = GETPOST('id', 'alpha'); $search_ref = GETPOST('search_ref', 'alpha'); $search_title = GETPOST('search_title', 'alpha'); $search_status = GETPOST('search_status', 'alpha'); // Load variable for pagination -$limit = GETPOST('limit', 'int')?GETPOST('limit', 'int'):$conf->liste_limit; +$limit = GETPOST('limit', 'int') ?GETPOST('limit', 'int') : $conf->liste_limit; $sortfield = GETPOST('sortfield', 'alpha'); $sortorder = GETPOST('sortorder', 'alpha'); $page = GETPOST('page', 'int'); @@ -75,7 +75,7 @@ if (!$user->rights->opensurvey->read) accessforbidden(); // Definition of fields for list $arrayfields=array(); -foreach($object->fields as $key => $val) +foreach($arrayfields 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'], 'position'=>$val['position']); @@ -98,16 +98,20 @@ 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->opensurvey->read; +$permissiontoadd = $user->rights->opensurvey->write; +$permissiontodelete = $user->rights->opensurvey->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 +$parameters = array(); +$reshook = $hookmanager->executeHooks('doActions', $parameters, $object, $action); // Note that $action and $object may have been modified by some hooks if ($reshook < 0) setEventMessages($hookmanager->error, $hookmanager->errors, 'errors'); if (empty($reshook)) @@ -133,8 +137,6 @@ if (empty($reshook)) // Mass actions $objectclass='Opensurveysondage'; $objectlabel='Opensurveysondage'; - $permissiontoread = $user->rights->opensurvey->read; - $permissiontodelete = $user->rights->opensurvey->write; $uploaddir = $conf->opensurvey->dir_output; include DOL_DOCUMENT_ROOT.'/core/actions_massactions.inc.php'; } @@ -144,33 +146,33 @@ if (empty($reshook)) * View */ -$form=new Form($db); +$form = new Form($db); $now = dol_now(); //$help_url="EN:Module_MyObject|FR:Module_MyObject_FR|ES:Módulo_MyObject"; -$help_url=''; +$help_url = ''; $title = $langs->trans('OpenSurveyArea'); $sql = "SELECT p.id_sondage as rowid, p.fk_user_creat, p.format, p.date_fin, p.status, p.titre, p.nom_admin,"; -$sql.= " u.login, u.firstname, u.lastname"; -$sql.= " FROM ".MAIN_DB_PREFIX."opensurvey_sondage as p"; -$sql.= " LEFT JOIN ".MAIN_DB_PREFIX."user u ON u.rowid = p.fk_user_creat"; -$sql.= " WHERE p.entity IN (".getEntity('survey').")"; -if ($search_status != '-1' && $search_status != '') $sql.=natural_search("p.status", $search_status, 2); -if ($search_expired == 'expired') $sql.=" AND p.date_fin < '".$db->idate($now)."'"; -if ($search_expired == 'opened') $sql.=" AND p.date_fin >= '".$db->idate($now)."'"; -if ($search_ref) $sql.=natural_search("p.id_sondage", $search_ref); -if ($search_title) $sql.=natural_search("p.titre", $search_title); +$sql .= " u.login, u.firstname, u.lastname"; +$sql .= " FROM ".MAIN_DB_PREFIX."opensurvey_sondage as p"; +$sql .= " LEFT JOIN ".MAIN_DB_PREFIX."user u ON u.rowid = p.fk_user_creat"; +$sql .= " WHERE p.entity IN (".getEntity('survey').")"; +if ($search_status != '-1' && $search_status != '') $sql .= natural_search("p.status", $search_status, 2); +if ($search_expired == 'expired') $sql .= " AND p.date_fin < '".$db->idate($now)."'"; +if ($search_expired == 'opened') $sql .= " AND p.date_fin >= '".$db->idate($now)."'"; +if ($search_ref) $sql .= natural_search("p.id_sondage", $search_ref); +if ($search_title) $sql .= natural_search("p.titre", $search_title); // Add where from extra fields include DOL_DOCUMENT_ROOT.'/core/tpl/extrafields_list_search_sql.tpl.php'; // Add where from hooks -$parameters=array(); -$reshook=$hookmanager->executeHooks('printFieldListWhere', $parameters, $object); // Note that $action and $object may have been modified by hook -$sql.=$hookmanager->resPrint; +$parameters = array(); +$reshook = $hookmanager->executeHooks('printFieldListWhere', $parameters, $object); // Note that $action and $object may have been modified by hook +$sql .= $hookmanager->resPrint; -$sql.=$db->order($sortfield, $sortorder); +$sql .= $db->order($sortfield, $sortorder); // Count total nb of records $nbtotalofrecords = ''; @@ -191,10 +193,10 @@ if (is_numeric($nbtotalofrecords) && $limit > $nbtotalofrecords) } else { - $sql.= $db->plimit($limit+1, $offset); + $sql .= $db->plimit($limit + 1, $offset); - $resql=$db->query($sql); - if (! $resql) + $resql = $db->query($sql); + if (!$resql) { dol_print_error($db); exit; @@ -204,7 +206,7 @@ else } // Direct jump if only one record found -if ($num == 1 && ! empty($conf->global->MAIN_SEARCH_DIRECT_OPEN_IF_ONLY_ONE) && $search_all) +if ($num == 1 && !empty($conf->global->MAIN_SEARCH_DIRECT_OPEN_IF_ONLY_ONE) && $search_all) { $obj = $db->fetch_object($resql); $id = $obj->rowid; @@ -213,6 +215,9 @@ if ($num == 1 && ! empty($conf->global->MAIN_SEARCH_DIRECT_OPEN_IF_ONLY_ONE) && } +// Output page +// -------------------------------------------------------------------- + llxHeader('', $title, $help_url); $arrayofselected=is_array($toselect)?$toselect:array(); @@ -231,7 +236,7 @@ $arrayofmassactions = array( //'presend'=>$langs->trans("SendByMail"), //'builddoc'=>$langs->trans("PDFMerge"), ); -if ($user->rights->opensurvey->write) $arrayofmassactions['predelete']=''.$langs->trans("Delete"); +if ($permissiontodelete) $arrayofmassactions['predelete']=''.$langs->trans("Delete"); if (GETPOST('nomassaction', 'int') || in_array($massaction, array('presend','predelete'))) $arrayofmassactions=array(); $massactionbutton=$form->selectMassAction('', $arrayofmassactions); @@ -248,8 +253,7 @@ print ''; print ''; print ''; -$newcardbutton=''; -$newcardbutton.= dolGetButtonTitle($langs->trans('NewSurvey'), '', 'fa fa-plus-circle', DOL_URL_ROOT.'/opensurvey/wizard/index.php', '', $user->rights->opensurvey->write); +$newcardbutton = dolGetButtonTitle($langs->trans('NewSurvey'), '', 'fa fa-plus-circle', DOL_URL_ROOT.'/opensurvey/wizard/index.php', '', $user->rights->opensurvey->write); print_barre_liste($title, $page, $_SERVER["PHP_SELF"], $param, $sortfield, $sortorder, $massactionbutton, $num, $nbtotalofrecords, 'generic', 0, $newcardbutton, '', $limit); @@ -271,25 +275,25 @@ $moreforfilter = ''; $moreforfilter.= $langs->trans('MyFilter') . ': '; $moreforfilter.= '';*/ -$parameters=array(); -$reshook=$hookmanager->executeHooks('printFieldPreListTitle', $parameters, $object); // Note that $action and $object may have been modified by hook +$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($moreforfilter)) +if (!empty($moreforfilter)) { print '
    '; print $moreforfilter; print '
    '; } -$varpage=empty($contextpage)?$_SERVER["PHP_SELF"]:$contextpage; +$varpage = empty($contextpage) ? $_SERVER["PHP_SELF"] : $contextpage; //$selectedfields=$form->multiSelectArrayWithCheckbox('selectedfields', $arrayfields, $varpage); // This also change content of $arrayfields -$selectedfields=''; -$selectedfields.=(count($arrayofmassactions) ? $form->showCheckAddButtons('checkforselect', 1) : ''); +$selectedfields = ''; +$selectedfields .= (count($arrayofmassactions) ? $form->showCheckAddButtons('checkforselect', 1) : ''); print '
    '; -print ''."\n"; +print '
    '."\n"; // Fields title search // -------------------------------------------------------------------- @@ -310,7 +314,7 @@ $parameters=array('arrayfields'=>$arrayfields); $reshook=$hookmanager->executeHooks('printFieldListOption', $parameters, $object); // Note that $action and $object may have been modified by hook print $hookmanager->resPrint; // Action column -print ''; @@ -330,9 +334,10 @@ print_liste_field_titre("Status", $_SERVER["PHP_SELF"], "p.status", $param, "", // 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, $object); // Note that $action and $object may have been modified by hook +$parameters = array('arrayfields'=>$arrayfields, 'param'=>$param, 'sortfield'=>$sortfield, 'sortorder'=>$sortorder); +$reshook = $hookmanager->executeHooks('printFieldListTitle', $parameters, $object); // Note that $action and $object may have been modified by hook print $hookmanager->resPrint; +// Action column print getTitleFieldOfList($selectedfields, 0, $_SERVER["PHP_SELF"], '', '', '', 'align="center"', $sortfield, $sortorder, 'maxwidthsearch ')."\n"; print ''."\n"; @@ -340,27 +345,27 @@ print ''."\n"; // Loop on record // -------------------------------------------------------------------- -$i=0; -$totalarray=array(); +$i = 0; +$totalarray = array(); while ($i < min($num, $limit)) { $obj = $db->fetch_object($resql); - if (empty($obj)) break; // Should not happen + if (empty($obj)) break; // Should not happen - $sql2='select COUNT(*) as nb from '.MAIN_DB_PREFIX."opensurvey_user_studs where id_sondage='".$db->escape($obj->id_sondage)."'"; - $resql2=$db->query($sql2); + $sql2 = 'select COUNT(*) as nb from '.MAIN_DB_PREFIX."opensurvey_user_studs where id_sondage='".$db->escape($obj->id_sondage)."'"; + $resql2 = $db->query($sql2); if ($resql2) { - $obj2=$db->fetch_object($resql2); - $nbuser=$obj2->nb; + $obj2 = $db->fetch_object($resql2); + $nbuser = $obj2->nb; } else dol_print_error($db); - $opensurvey_static->id=$obj->rowid; - $opensurvey_static->ref=$obj->rowid; - $opensurvey_static->title=$obj->titre; - $opensurvey_static->status=$obj->status; - $opensurvey_static->date_fin=$db->jdate($obj->date_fin); + $opensurvey_static->id = $obj->rowid; + $opensurvey_static->ref = $obj->rowid; + $opensurvey_static->title = $obj->titre; + $opensurvey_static->status = $obj->status; + $opensurvey_static->date_fin = $db->jdate($obj->date_fin); // Show here line of result print ''; @@ -369,17 +374,21 @@ while ($i < min($num, $limit)) print ''; + if (! $i) $totalarray['nbfield']++; // Title print ''; + if (! $i) $totalarray['nbfield']++; // Type print ''; + if (! $i) $totalarray['nbfield']++; + print ''; + if (! $i) $totalarray['nbfield']++; // Nb of voters print''."\n"; + if (! $i) $totalarray['nbfield']++; print ''; + if (! $i) $totalarray['nbfield']++; print''."\n"; + if (! $i) $totalarray['nbfield']++; // Extra fields include DOL_DOCUMENT_ROOT.'/core/tpl/extrafields_list_print_fields.tpl.php'; // Fields from hook - $parameters=array('arrayfields'=>$arrayfields, 'obj'=>$obj); + $parameters=array('arrayfields'=>$arrayfields, 'obj'=>$obj, 'i'=>$i, 'totalarray'=>&$totalarray); $reshook=$hookmanager->executeHooks('printFieldListValue', $parameters, $object); // Note that $action and $object may have been modified by hook print $hookmanager->resPrint; // Action column @@ -419,6 +431,7 @@ while ($i < min($num, $limit)) print ''; } print ''; + if (! $i) $totalarray['nbfield']++; print ''."\n"; $i++; @@ -431,7 +444,7 @@ include DOL_DOCUMENT_ROOT.'/core/tpl/list_print_total.tpl.php'; // If no record found if ($num == 0) { - $colspan=1; + $colspan = 8; foreach($arrayfields as $key => $val) { if (! empty($val['checked'])) $colspan++; } print ''; } @@ -461,8 +474,8 @@ if (in_array('builddoc', $arrayofmassactions) && ($nbtotalofrecords === '' || $n $urlsource.=str_replace('&', '&', $param); $filedir=$diroutputmassaction; - $genallowed=$user->rights->mymodule->read; - $delallowed=$user->rights->mymodule->create; + $genallowed=$permissiontoread; + $delallowed=$permissiontoadd; print $formfile->showdocuments('massfilesarea_mymodule', '', $filedir, $urlsource, 0, $delallowed, '', 1, 1, 0, 48, 1, $param, $title, '', '', '', null, $hidegeneratedfilelistifempty); } diff --git a/htdocs/opensurvey/results.php b/htdocs/opensurvey/results.php index 017779b74f7..7bb775e790e 100644 --- a/htdocs/opensurvey/results.php +++ b/htdocs/opensurvey/results.php @@ -35,14 +35,14 @@ if (!$user->rights->opensurvey->read) accessforbidden(); // Init vars -$action=GETPOST('action', 'aZ09'); -$numsondage= GETPOST("id"); +$action = GETPOST('action', 'aZ09'); +$numsondage = GETPOST("id"); -$object=new Opensurveysondage($db); -$result=$object->fetch(0, $numsondage); +$object = new Opensurveysondage($db); +$result = $object->fetch(0, $numsondage); if ($result <= 0) dol_print_error('', 'Failed to get survey id '.$numsondage); -$nblines=$object->fetch_lines(); +$nblines = $object->fetch_lines(); /* @@ -65,28 +65,28 @@ if (GETPOST("boutonp") || GETPOST("boutonp.x") || GETPOST("boutonp_x")) // bout $erreur_prenom = false; $nouveauchoix = ''; - for ($i=0;$i<$nbcolonnes;$i++) + for ($i = 0; $i < $nbcolonnes; $i++) { if (isset($_POST["choix$i"]) && $_POST["choix$i"] == '1') { - $nouveauchoix.="1"; + $nouveauchoix .= "1"; } elseif (isset($_POST["choix$i"]) && $_POST["choix$i"] == '2') { - $nouveauchoix.="2"; + $nouveauchoix .= "2"; } else { // sinon c'est 0 - $nouveauchoix.="0"; + $nouveauchoix .= "0"; } } - $nom=substr(GETPOST("nom", 'nohtml'), 0, 64); + $nom = substr(GETPOST("nom", 'nohtml'), 0, 64); // Check if vote already exists $sql = 'SELECT id_users, nom as name'; - $sql.= ' FROM '.MAIN_DB_PREFIX.'opensurvey_user_studs'; - $sql.= " WHERE id_sondage='".$db->escape($numsondage)."' AND nom = '".$db->escape($nom)."'"; - $sql.= ' ORDER BY id_users'; + $sql .= ' FROM '.MAIN_DB_PREFIX.'opensurvey_user_studs'; + $sql .= " WHERE id_sondage='".$db->escape($numsondage)."' AND nom = '".$db->escape($nom)."'"; + $sql .= ' ORDER BY id_users'; $resql = $db->query($sql); $num_rows = $db->num_rows($resql); if ($num_rows > 0) @@ -97,9 +97,9 @@ if (GETPOST("boutonp") || GETPOST("boutonp.x") || GETPOST("boutonp_x")) // bout else { $sql = 'INSERT INTO '.MAIN_DB_PREFIX.'opensurvey_user_studs (nom, id_sondage, reponses)'; - $sql.= " VALUES ('".$db->escape($nom)."', '".$db->escape($numsondage)."','".$db->escape($nouveauchoix)."')"; - $resql=$db->query($sql); - if (! $resql) dol_print_error($db); + $sql .= " VALUES ('".$db->escape($nom)."', '".$db->escape($numsondage)."','".$db->escape($nouveauchoix)."')"; + $resql = $db->query($sql); + if (!$resql) dol_print_error($db); } } } @@ -108,19 +108,19 @@ if (GETPOST("boutonp") || GETPOST("boutonp.x") || GETPOST("boutonp_x")) // bout $testmodifier = false; $testligneamodifier = false; $ligneamodifier = -1; -for ($i=0; $i<$nblines; $i++) +for ($i = 0; $i < $nblines; $i++) { if (isset($_POST['modifierligne'.$i])) { - $ligneamodifier=$i; - $testligneamodifier=true; + $ligneamodifier = $i; + $testligneamodifier = true; } //test pour voir si une ligne est a modifier if (isset($_POST['validermodifier'.$i])) { - $modifier=$i; - $testmodifier=true; + $modifier = $i; + $testmodifier = true; } } if ($testmodifier) @@ -134,24 +134,24 @@ if ($testmodifier) //var_dump($_POST["choix$i"]); if (isset($_POST["choix$i"]) && $_POST["choix$i"] == '1') { - $nouveauchoix.="1"; + $nouveauchoix .= "1"; } elseif (isset($_POST["choix$i"]) && $_POST["choix$i"] == '2') { - $nouveauchoix.="2"; + $nouveauchoix .= "2"; } else { // sinon c'est 0 - $nouveauchoix.="0"; + $nouveauchoix .= "0"; } } - $idtomodify=$_POST["idtomodify".$modifier]; + $idtomodify = $_POST["idtomodify".$modifier]; $sql = 'UPDATE '.MAIN_DB_PREFIX."opensurvey_user_studs"; - $sql.= " SET reponses = '".$db->escape($nouveauchoix)."'"; - $sql.= " WHERE id_users = '".$db->escape($idtomodify)."'"; + $sql .= " SET reponses = '".$db->escape($nouveauchoix)."'"; + $sql .= " WHERE id_users = '".$db->escape($idtomodify)."'"; $resql = $db->query($sql); - if (! $resql) dol_print_error($db); + if (!$resql) dol_print_error($db); } // Add column (not for date) @@ -160,18 +160,18 @@ if (GETPOST("ajoutercolonne") && GETPOST('nouvellecolonne') && $object->format = // Security check if (!$user->rights->opensurvey->write) accessforbidden(); - $nouveauxsujets=$object->sujet; + $nouveauxsujets = $object->sujet; //on rajoute la valeur a la fin de tous les sujets deja entrés - $nouveauxsujets.=','; - $nouveauxsujets.=str_replace(array(",","@"), " ", $_POST["nouvellecolonne"]).(empty($_POST["typecolonne"])?'':'@'.$_POST["typecolonne"]); + $nouveauxsujets .= ','; + $nouveauxsujets .= str_replace(array(",", "@"), " ", $_POST["nouvellecolonne"]).(empty($_POST["typecolonne"]) ? '' : '@'.$_POST["typecolonne"]); //mise a jour avec les nouveaux sujets dans la base $sql = 'UPDATE '.MAIN_DB_PREFIX."opensurvey_sondage"; - $sql.= " SET sujet = '".$db->escape($nouveauxsujets)."'"; - $sql.= " WHERE id_sondage = '".$db->escape($numsondage)."'"; + $sql .= " SET sujet = '".$db->escape($nouveauxsujets)."'"; + $sql .= " WHERE id_sondage = '".$db->escape($numsondage)."'"; $resql = $db->query($sql); - if (! $resql) dol_print_error($db); + if (!$resql) dol_print_error($db); else { header('Location: results.php?id='.$object->id_sondage); } @@ -223,10 +223,10 @@ if (isset($_POST["ajoutercolonne"]) && $object->format == "D") //recherche de l'endroit de l'insertion de la nouvelle date dans les dates deja entrées dans le tableau if ($nouvelledate < $datesbase[0]) { $cleinsertion = 0; - } elseif ($nouvelledate > $datesbase[$taillebase-1]) { + } elseif ($nouvelledate > $datesbase[$taillebase - 1]) { $cleinsertion = count($datesbase); } else { - $nbdatesbase=count($datesbase); + $nbdatesbase = count($datesbase); for ($i = 0; $i < $nbdatesbase; $i++) { $j = $i + 1; @@ -239,10 +239,10 @@ if (isset($_POST["ajoutercolonne"]) && $object->format == "D") array_splice($datesbase, $cleinsertion, 0, $nouvelledate); $cle = array_search($nouvelledate, $datesbase); $dateinsertion = ''; - $nbofdates=count($datesbase); + $nbofdates = count($datesbase); for ($i = 0; $i < $nbofdates; $i++) { - $dateinsertion.=","; - $dateinsertion.=$datesbase[$i]; + $dateinsertion .= ","; + $dateinsertion .= $datesbase[$i]; } $dateinsertion = substr("$dateinsertion", 1); @@ -251,10 +251,10 @@ if (isset($_POST["ajoutercolonne"]) && $object->format == "D") if (isset($erreur_ajout_date) && empty($erreur_ajout_date)) { $sql = 'UPDATE '.MAIN_DB_PREFIX."opensurvey_sondage"; - $sql.= " SET sujet = '".$db->escape($dateinsertion)."'"; - $sql.= " WHERE id_sondage = '".$db->escape($numsondage)."'"; + $sql .= " SET sujet = '".$db->escape($dateinsertion)."'"; + $sql .= " WHERE id_sondage = '".$db->escape($numsondage)."'"; $resql = $db->query($sql); - if (! $resql) dol_print_error($db); + if (!$resql) dol_print_error($db); else { header('Location: results.php?id='.$object->id_sondage); } @@ -264,7 +264,7 @@ if (isset($_POST["ajoutercolonne"]) && $object->format == "D") } else { - $erreur_ajout_date="yes"; + $erreur_ajout_date = "yes"; } } @@ -276,24 +276,24 @@ for ($i = 0; $i < $nblines; $i++) // Security check if (!$user->rights->opensurvey->write) accessforbidden(); - $compteur=0; + $compteur = 0; // Loop on each answer $compteur = 0; - $sql ="SELECT id_users, nom as name, id_sondage, reponses"; - $sql.=" FROM ".MAIN_DB_PREFIX."opensurvey_user_studs"; - $sql.=" WHERE id_sondage = '".$db->escape($numsondage)."'"; - $resql=$db->query($sql); - if (! $resql) dol_print_error($db); - $num=$db->num_rows($resql); + $sql = "SELECT id_users, nom as name, id_sondage, reponses"; + $sql .= " FROM ".MAIN_DB_PREFIX."opensurvey_user_studs"; + $sql .= " WHERE id_sondage = '".$db->escape($numsondage)."'"; + $resql = $db->query($sql); + if (!$resql) dol_print_error($db); + $num = $db->num_rows($resql); while ($compteur < $num) { - $obj=$db->fetch_object($resql); + $obj = $db->fetch_object($resql); - if ($compteur==$i) + if ($compteur == $i) { $sql2 = 'DELETE FROM '.MAIN_DB_PREFIX.'opensurvey_user_studs'; - $sql2.= ' WHERE id_users = '.$db->escape($obj->id_users); + $sql2 .= ' WHERE id_users = '.$db->escape($obj->id_users); $resql2 = $db->query($sql2); } @@ -323,7 +323,7 @@ for ($i = 0; $i < $nbcolonnes; $i++) //si le sujet n'est pas celui qui a été effacé alors on concatene if ($i != $j) { - if (! empty($nouveauxsujets)) $nouveauxsujets .= ','; + if (!empty($nouveauxsujets)) $nouveauxsujets .= ','; $nouveauxsujets .= $toutsujet[$j]; } @@ -332,26 +332,26 @@ for ($i = 0; $i < $nbcolonnes; $i++) // Mise a jour des sujets dans la base $sql = 'UPDATE '.MAIN_DB_PREFIX."opensurvey_sondage"; - $sql.= " SET sujet = '".$db->escape($nouveauxsujets)."' WHERE id_sondage = '".$db->escape($numsondage)."'"; + $sql .= " SET sujet = '".$db->escape($nouveauxsujets)."' WHERE id_sondage = '".$db->escape($numsondage)."'"; $resql = $db->query($sql); - if (! $resql) dol_print_error($db); + if (!$resql) dol_print_error($db); // Clean current answer to remove deleted columns $compteur = 0; - $sql ="SELECT id_users, nom as name, id_sondage, reponses"; - $sql.=" FROM ".MAIN_DB_PREFIX."opensurvey_user_studs"; - $sql.=" WHERE id_sondage = '".$db->escape($numsondage)."'"; + $sql = "SELECT id_users, nom as name, id_sondage, reponses"; + $sql .= " FROM ".MAIN_DB_PREFIX."opensurvey_user_studs"; + $sql .= " WHERE id_sondage = '".$db->escape($numsondage)."'"; dol_syslog('sql='.$sql); - $resql=$db->query($sql); - if (! $resql) + $resql = $db->query($sql); + if (!$resql) { dol_print_error($db); exit; } - $num=$db->num_rows($resql); + $num = $db->num_rows($resql); while ($compteur < $num) { - $obj=$db->fetch_object($resql); + $obj = $db->fetch_object($resql); $newcar = ''; $ensemblereponses = $obj->reponses; @@ -359,7 +359,7 @@ for ($i = 0; $i < $nbcolonnes; $i++) // parcours de toutes les réponses actuelles for ($j = 0; $j < $nbcolonnes; $j++) { - $car=substr($ensemblereponses, $j, 1); + $car = substr($ensemblereponses, $j, 1); //si les reponses ne concerne pas la colonne effacée, on concatene if ($i != $j) { $newcar .= $car; @@ -368,8 +368,8 @@ for ($i = 0; $i < $nbcolonnes; $i++) // mise a jour des reponses utilisateurs dans la base $sql2 = 'UPDATE '.MAIN_DB_PREFIX.'opensurvey_user_studs'; - $sql2.= " SET reponses = '".$db->escape($newcar)."'"; - $sql2.= " WHERE id_users = '".$db->escape($obj->id_users)."'"; + $sql2 .= " SET reponses = '".$db->escape($newcar)."'"; + $sql2 .= " WHERE id_users = '".$db->escape($obj->id_users)."'"; //print $sql2; dol_syslog('sql='.$sql2); $resql2 = $db->query($sql2); @@ -387,14 +387,14 @@ for ($i = 0; $i < $nbcolonnes; $i++) * View */ -$form=new Form($db); +$form = new Form($db); if ($object->fk_user_creat) { $userstatic = new User($db); $userstatic->fetch($object->fk_user_creat); } -$result=$object->fetch(0, $numsondage); +$result = $object->fetch(0, $numsondage); if ($result <= 0) { dol_print_error($db, $object->error); @@ -403,21 +403,21 @@ if ($result <= 0) $title = $object->titre." - ".$langs->trans('Card'); $helpurl = ''; -$arrayofjs=array(); -$arrayofcss=array('/opensurvey/css/style.css'); +$arrayofjs = array(); +$arrayofcss = array('/opensurvey/css/style.css'); llxHeader('', $title, $helpurl, 0, 0, 0, $arrayofjs, $arrayofcss); // Define format of choices -$toutsujet=explode(",", $object->sujet); -$listofanswers=array(); +$toutsujet = explode(",", $object->sujet); +$listofanswers = array(); foreach ($toutsujet as $value) { - $tmp=explode('@', $value); - $listofanswers[]=array('label'=>$tmp[0],'format'=>($tmp[1]?$tmp[1]:'checkbox')); + $tmp = explode('@', $value); + $listofanswers[] = array('label'=>$tmp[0], 'format'=>($tmp[1] ? $tmp[1] : 'checkbox')); } -$toutsujet=str_replace("@", "
    ", $toutsujet); -$toutsujet=str_replace("°", "'", $toutsujet); +$toutsujet = str_replace("@", "
    ", $toutsujet); +$toutsujet = str_replace("°", "'", $toutsujet); print ''."\n"; @@ -439,15 +439,15 @@ print '
    '; print '
    '; +print ''; $searchpicto=$form->showFilterButtons(); print $searchpicto; print '
    '; print $opensurvey_static->getNomUrl(1); print ''.dol_htmlentities($obj->titre).''; $type=($obj->format=='A')?'classic':'date'; print img_picto('', dol_buildpath('/opensurvey/img/'.($type == 'classic'?'chart-32.png':'calendar-32.png'), 1), 'width="16"', 1); print ' '.$langs->trans($type=='classic'?"TypeClassic":"TypeDate"); - print ''; + print ''; // Author if ($obj->fk_user_creat) { $userstatic = new User($db); @@ -392,22 +401,25 @@ while ($i < min($num, $limit)) } else { print dol_htmlentities($obj->nom_admin); } - print ''.$nbuser.''.dol_print_date($db->jdate($obj->date_fin), 'day'); if ($db->jdate($obj->date_fin) < $now && $obj->status == Opensurveysondage::STATUS_VALIDATED) { print img_warning($langs->trans("Expired")); } print ''.$opensurvey_static->getLibStatut(5).'
    '.$langs->trans("NoRecordFound").'
    '; // Type -$type=($object->format=="A")?'classic':'date'; +$type = ($object->format == "A") ? 'classic' : 'date'; print ''; +print img_picto('', dol_buildpath('/opensurvey/img/'.($type == 'classic' ? 'chart-32.png' : 'calendar-32.png'), 1), 'width="16"', 1); +print ' '.$langs->trans($type == 'classic' ? "TypeClassic" : "TypeDate").''; // Title print ''; // Expire date print ''; // Author print ''; print '
    '.$langs->trans("Type").''; -print img_picto('', dol_buildpath('/opensurvey/img/'.($type == 'classic'?'chart-32.png':'calendar-32.png'), 1), 'width="16"', 1); -print ' '.$langs->trans($type=='classic'?"TypeClassic":"TypeDate").'
    '; -$adresseadmin=$object->mail_admin; -print $langs->trans("Title") .''; +$adresseadmin = $object->mail_admin; +print $langs->trans("Title").''; if ($action == 'edit') { print ''; @@ -457,13 +457,13 @@ print '
    '.$langs->trans('ExpireDate').''; -if ($action == 'edit') print $form->selectDate($expiredate?$expiredate:$object->date_fin, 'expire', 0, 0, 0, '', 1, 0); +if ($action == 'edit') print $form->selectDate($expiredate ? $expiredate : $object->date_fin, 'expire', 0, 0, 0, '', 1, 0); else print dol_print_date($object->date_fin, 'day'); print '
    '; -print $langs->trans("Author") .''; +print $langs->trans("Author").''; if ($object->fk_user_creat) { print $userstatic->getLoginUrl(1); } else { @@ -475,12 +475,12 @@ print '
    '.img_picto('', 'globe').' '.$langs->trans("UrlForSurvey", '').''; // Define $urlwithroot -$urlwithouturlroot=preg_replace('/'.preg_quote(DOL_URL_ROOT, '/').'$/i', '', trim($dolibarr_main_url_root)); -$urlwithroot=$urlwithouturlroot.DOL_URL_ROOT; // This is to use external domain name found into config file +$urlwithouturlroot = preg_replace('/'.preg_quote(DOL_URL_ROOT, '/').'$/i', '', trim($dolibarr_main_url_root)); +$urlwithroot = $urlwithouturlroot.DOL_URL_ROOT; // This is to use external domain name found into config file //$urlwithroot=DOL_MAIN_URL_ROOT; // This is to use same domain name than current -$url=$urlwithouturlroot.dol_buildpath('/public/opensurvey/studs.php', 1).'?sondage='.$object->id_sondage; -$urllink=''; +$url = $urlwithouturlroot.dol_buildpath('/public/opensurvey/studs.php', 1).'?sondage='.$object->id_sondage; +$urllink = ''; print $urllink; if ($action != 'edit') { @@ -505,7 +505,7 @@ print ''."\n"; print ''; @@ -523,11 +523,11 @@ if (GETPOST('ajoutsujet')) print "

    "."\n"; // Add new column - if ($object->format=="A") + if ($object->format == "A") { - print $langs->trans("AddNewColumn") .':

    '; + print $langs->trans("AddNewColumn").':

    '; print $langs->trans("Title").'
    '; - $tmparray=array('checkbox'=>$langs->trans("CheckBox"),'yesno'=>$langs->trans("YesNoList"),'foragainst'=>$langs->trans("PourContreList")); + $tmparray = array('checkbox'=>$langs->trans("CheckBox"), 'yesno'=>$langs->trans("YesNoList"), 'foragainst'=>$langs->trans("PourContreList")); print $langs->trans("Type").' '.$form->selectarray("typecolonne", $tmparray, GETPOST('typecolonne')).'

    '; print ''; print '     '; @@ -538,12 +538,12 @@ if (GETPOST('ajoutsujet')) { require_once DOL_DOCUMENT_ROOT.'/core/class/html.formother.class.php'; - $formother=new FormOther($db); + $formother = new FormOther($db); //ajout d'une date avec creneau horaire - print $langs->trans("AddADate") .':

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

    '."\n"; print ''."\n"; @@ -554,7 +554,7 @@ if (GETPOST('ajoutsujet')) print $formother->select_year('', 'nouvelleannee', 1, 0, 5, 0, 1); - print '

    '. $langs->trans("AddStartHour") .':

    '."\n"; + print '

    '.$langs->trans("AddStartHour").':

    '."\n"; print ''."\n"; - print '

    '. $langs->trans("AddEndHour") .':

    '."\n"; + print '

    '.$langs->trans("AddEndHour").':

    '."\n"; print ''."\n"; //reformatage des données des sujets du sondage -$toutsujet=explode(",", $object->sujet); -$toutsujet=str_replace("°", "'", $toutsujet); +$toutsujet = explode(",", $object->sujet); +$toutsujet = str_replace("°", "'", $toutsujet); print ''."\n"; print ''."\n"; @@ -628,7 +628,7 @@ print ''."\n"; // Show choice titles -if ($object->format=="D") +if ($object->format == "D") { //affichage des sujets du sondage print ''."\n"; @@ -636,9 +636,9 @@ if ($object->format=="D") print ''."\n"; //affichage des années - $colspan=1; - $nbofsujet=count($toutsujet); - for ($i=0;$i<$nbofsujet;$i++) + $colspan = 1; + $nbofsujet = count($toutsujet); + for ($i = 0; $i < $nbofsujet; $i++) { $current = $toutsujet[$i]; @@ -646,24 +646,24 @@ if ($object->format=="D") $current = substr($toutsujet[$i], 0, strpos($toutsujet[$i], '@')); } - if (isset($toutsujet[$i+1]) && strpos($toutsujet[$i+1], '@') !== false) { - $next = substr($toutsujet[$i+1], 0, strpos($toutsujet[$i+1], '@')); - } elseif (isset($toutsujet[$i+1])) { - $next = $toutsujet[$i+1]; + if (isset($toutsujet[$i + 1]) && strpos($toutsujet[$i + 1], '@') !== false) { + $next = substr($toutsujet[$i + 1], 0, strpos($toutsujet[$i + 1], '@')); + } elseif (isset($toutsujet[$i + 1])) { + $next = $toutsujet[$i + 1]; } $currenty = 0; - if ($current) $currenty=strftime("%Y", $current); + if ($current) $currenty = strftime("%Y", $current); $next = 0; - if ($next) $nexty=strftime("%Y", $next); - if (isset($toutsujet[$i+1]) && ($currenty == $nexty)) + if ($next) $nexty = strftime("%Y", $next); + if (isset($toutsujet[$i + 1]) && ($currenty == $nexty)) { $colspan++; } else { print ''."\n"; - $colspan=1; + $colspan = 1; } } @@ -680,20 +680,20 @@ if ($object->format=="D") //affichage des mois $colspan = 1; for ($i = 0; $i < $nbofsujet; $i++) { - $cur = intval($toutsujet[$i]); // intval() est utiliser pour supprimer le suffixe @* qui déplaît logiquement à strftime() + $cur = intval($toutsujet[$i]); // intval() est utiliser pour supprimer le suffixe @* qui déplaît logiquement à strftime() - if (isset($toutsujet[$i+1]) === false) { + if (isset($toutsujet[$i + 1]) === false) { $next = false; } else { - $next = intval($toutsujet[$i+1]); + $next = intval($toutsujet[$i + 1]); } - if ($next && dol_print_date($cur, "%B") == dol_print_date($next, "%B") && dol_print_date($cur, "%Y") == dol_print_date($next, "%Y")){ + if ($next && dol_print_date($cur, "%B") == dol_print_date($next, "%B") && dol_print_date($cur, "%Y") == dol_print_date($next, "%Y")) { $colspan++; } else { print ''."\n"; - $colspan=1; + $colspan = 1; } } @@ -710,17 +710,17 @@ if ($object->format=="D") $colspan = 1; for ($i = 0; $i < $nbofsujet; $i++) { $cur = intval($toutsujet[$i]); - if (isset($toutsujet[$i+1]) === false) { + if (isset($toutsujet[$i + 1]) === false) { $next = false; } else { - $next = intval($toutsujet[$i+1]); + $next = intval($toutsujet[$i + 1]); } if ($next && dol_print_date($cur, "%a %e") == dol_print_date($next, "%a %e") && dol_print_date($cur, "%B") == dol_print_date($next, "%B")) { $colspan++; } else { print ''."\n"; - $colspan=1; + $colspan = 1; } } @@ -736,7 +736,7 @@ if ($object->format=="D") print ''."\n"; for ($i = 0; isset($toutsujet[$i]); $i++) { - $heures=explode('@', $toutsujet[$i]); + $heures = explode('@', $toutsujet[$i]); if (isset($heures[1])) { print ''."\n"; } else { @@ -760,7 +760,7 @@ else for ($i = 0; isset($toutsujet[$i]); $i++) { - $tmp=explode('@', $toutsujet[$i]); + $tmp = explode('@', $toutsujet[$i]); print ''."\n"; } @@ -773,20 +773,20 @@ else $sumfor = array(); $sumagainst = array(); $compteur = 0; -$sql ="SELECT id_users, nom as name, id_sondage, reponses"; -$sql.=" FROM ".MAIN_DB_PREFIX."opensurvey_user_studs"; -$sql.=" WHERE id_sondage = '".$db->escape($numsondage)."'"; +$sql = "SELECT id_users, nom as name, id_sondage, reponses"; +$sql .= " FROM ".MAIN_DB_PREFIX."opensurvey_user_studs"; +$sql .= " WHERE id_sondage = '".$db->escape($numsondage)."'"; dol_syslog('sql='.$sql); -$resql=$db->query($sql); -if (! $resql) +$resql = $db->query($sql); +if (!$resql) { dol_print_error($db); exit; } -$num=$db->num_rows($resql); +$num = $db->num_rows($resql); while ($compteur < $num) { - $obj=$db->fetch_object($resql); + $obj = $db->fetch_object($resql); $ensemblereponses = $obj->reponses; @@ -800,40 +800,40 @@ while ($compteur < $num) print ''."\n"; // si la ligne n'est pas a changer, on affiche les données - if (! $testligneamodifier) + if (!$testligneamodifier) { for ($i = 0; $i < $nbcolonnes; $i++) { $car = substr($ensemblereponses, $i, 1); //print 'xx'.$i."-".$car.'-'.$listofanswers[$i]['format'].'zz'; - if (empty($listofanswers[$i]['format']) || ! in_array($listofanswers[$i]['format'], array('yesno','foragainst'))) + if (empty($listofanswers[$i]['format']) || !in_array($listofanswers[$i]['format'], array('yesno', 'foragainst'))) { if (((string) $car) == "1") print ''."\n"; else print ''."\n"; // Total - if (! isset($sumfor[$i])) $sumfor[$i] = 0; + if (!isset($sumfor[$i])) $sumfor[$i] = 0; if (((string) $car) == "1") $sumfor[$i]++; } - if (! empty($listofanswers[$i]['format']) && $listofanswers[$i]['format'] == 'yesno') + if (!empty($listofanswers[$i]['format']) && $listofanswers[$i]['format'] == 'yesno') { if (((string) $car) == "1") print ''."\n"; elseif (((string) $car) == "0") print ''."\n"; else print ''."\n"; // Total - if (! isset($sumfor[$i])) $sumfor[$i] = 0; - if (! isset($sumagainst[$i])) $sumagainst[$i] = 0; + if (!isset($sumfor[$i])) $sumfor[$i] = 0; + if (!isset($sumagainst[$i])) $sumagainst[$i] = 0; if (((string) $car) == "1") $sumfor[$i]++; if (((string) $car) == "0") $sumagainst[$i]++; } - if (! empty($listofanswers[$i]['format']) && $listofanswers[$i]['format'] == 'foragainst') + if (!empty($listofanswers[$i]['format']) && $listofanswers[$i]['format'] == 'foragainst') { if (((string) $car) == "1") print ''."\n"; elseif (((string) $car) == "0") print ''."\n"; else print ''."\n"; // Total - if (! isset($sumfor[$i])) $sumfor[$i] = 0; - if (! isset($sumagainst[$i])) $sumagainst[$i] = 0; + if (!isset($sumfor[$i])) $sumfor[$i] = 0; + if (!isset($sumagainst[$i])) $sumagainst[$i] = 0; if (((string) $car) == "1") $sumfor[$i]++; if (((string) $car) == "0") $sumagainst[$i]++; } @@ -848,20 +848,20 @@ while ($compteur < $num) { $car = substr($ensemblereponses, $i, 1); print ''."\n"; @@ -872,33 +872,33 @@ while ($compteur < $num) for ($i = 0; $i < $nbcolonnes; $i++) { $car = substr($ensemblereponses, $i, 1); - if (empty($listofanswers[$i]['format']) || ! in_array($listofanswers[$i]['format'], array('yesno','foragainst'))) + if (empty($listofanswers[$i]['format']) || !in_array($listofanswers[$i]['format'], array('yesno', 'foragainst'))) { if (((string) $car) == "1") print ''."\n"; else print ''."\n"; // Total - if (! isset($sumfor[$i])) $sumfor[$i] = 0; + if (!isset($sumfor[$i])) $sumfor[$i] = 0; if (((string) $car) == "1") $sumfor[$i]++; } - if (! empty($listofanswers[$i]['format']) && $listofanswers[$i]['format'] == 'yesno') + if (!empty($listofanswers[$i]['format']) && $listofanswers[$i]['format'] == 'yesno') { if (((string) $car) == "1") print ''."\n"; elseif (((string) $car) == "0") print ''."\n"; else print ''."\n"; // Total - if (! isset($sumfor[$i])) $sumfor[$i] = 0; - if (! isset($sumagainst[$i])) $sumagainst[$i] = 0; + if (!isset($sumfor[$i])) $sumfor[$i] = 0; + if (!isset($sumagainst[$i])) $sumagainst[$i] = 0; if (((string) $car) == "1") $sumfor[$i]++; if (((string) $car) == "0") $sumagainst[$i]++; } - if (! empty($listofanswers[$i]['format']) && $listofanswers[$i]['format'] == 'foragainst') + if (!empty($listofanswers[$i]['format']) && $listofanswers[$i]['format'] == 'foragainst') { if (((string) $car) == "1") print ''."\n"; elseif (((string) $car) == "0") print ''."\n"; else print ''."\n"; // Total - if (! isset($sumfor[$i])) $sumfor[$i] = 0; - if (! isset($sumagainst[$i])) $sumagainst[$i] = 0; + if (!isset($sumfor[$i])) $sumfor[$i] = 0; + if (!isset($sumagainst[$i])) $sumagainst[$i] = 0; if (((string) $car) == "1") $sumfor[$i]++; if (((string) $car) == "0") $sumagainst[$i]++; } @@ -913,7 +913,7 @@ while ($compteur < $num) } //demande de confirmation pour modification de ligne - for ($i=0; $i<$nblines; $i++) + for ($i = 0; $i < $nblines; $i++) { if (isset($_POST["modifierligne".$i])) { @@ -943,23 +943,23 @@ if (empty($testligneamodifier)) for ($i = 0; $i < $nbcolonnes; $i++) { print ''."\n"; @@ -971,10 +971,10 @@ if (empty($testligneamodifier)) } // Select value of best choice (for checkbox columns only) -$nbofcheckbox=0; -for ($i=0; $i < $nbcolonnes + 1; $i++) +$nbofcheckbox = 0; +for ($i = 0; $i < $nbcolonnes + 1; $i++) { - if (empty($listofanswers[$i]['format']) || ! in_array($listofanswers[$i]['format'], array('yesno','foragainst'))) + if (empty($listofanswers[$i]['format']) || !in_array($listofanswers[$i]['format'], array('yesno', 'foragainst'))) $nbofcheckbox++; if (isset($sumfor[$i])) { @@ -993,18 +993,18 @@ for ($i=0; $i < $nbcolonnes + 1; $i++) // Show line total print ''."\n"; print ''."\n"; -print ''."\n"; +print ''."\n"; for ($i = 0; $i < $nbcolonnes; $i++) { - $showsumfor = isset($sumfor[$i])?$sumfor[$i]:''; - $showsumagainst = isset($sumagainst[$i])?$sumagainst[$i]:''; + $showsumfor = isset($sumfor[$i]) ? $sumfor[$i] : ''; + $showsumagainst = isset($sumagainst[$i]) ? $sumagainst[$i] : ''; if (empty($showsumfor)) $showsumfor = 0; if (empty($showsumagainst)) $showsumagainst = 0; print ''."\n"; } print ''; @@ -1015,7 +1015,7 @@ if ($nbofcheckbox >= 2) print ''."\n"; print ''."\n"; for ($i = 0; $i < $nbcolonnes; $i++) { - if (empty($listofanswers[$i]['format']) || ! in_array($listofanswers[$i]['format'], array('yesno','foragainst')) && isset($sumfor[$i]) && isset($meilleurecolonne) && $sumfor[$i] == $meilleurecolonne) + if (empty($listofanswers[$i]['format']) || !in_array($listofanswers[$i]['format'], array('yesno', 'foragainst')) && isset($sumfor[$i]) && isset($meilleurecolonne) && $sumfor[$i] == $meilleurecolonne) { print ''."\n"; } else { @@ -1043,7 +1043,7 @@ print '
    '; if ($current) print strftime("%Y", $current); print ''.dol_print_date($cur, "%B").''.dol_print_date($cur, "%a %e").''.dol_htmlentities($heures[1]).''.dol_htmlentities($tmp[0]).''.dol_htmlentities($obj->name).'OKKO'.$langs->trans("Yes").''.$langs->trans("No").' '.$langs->trans("For").''.$langs->trans("Against").' '; - if (empty($listofanswers[$i]['format']) || ! in_array($listofanswers[$i]['format'], array('yesno','foragainst'))) + if (empty($listofanswers[$i]['format']) || !in_array($listofanswers[$i]['format'], array('yesno', 'foragainst'))) { print ''; } - if (! empty($listofanswers[$i]['format']) && $listofanswers[$i]['format'] == 'yesno') + if (!empty($listofanswers[$i]['format']) && $listofanswers[$i]['format'] == 'yesno') { - $arraychoice=array('2'=>' ','0'=>$langs->trans("No"),'1'=>$langs->trans("Yes")); + $arraychoice = array('2'=>' ', '0'=>$langs->trans("No"), '1'=>$langs->trans("Yes")); print $form->selectarray("choix".$i, $arraychoice, $car); } - if (! empty($listofanswers[$i]['format']) && $listofanswers[$i]['format'] == 'foragainst') + if (!empty($listofanswers[$i]['format']) && $listofanswers[$i]['format'] == 'foragainst') { - $arraychoice=array('2'=>' ','0'=>$langs->trans("Against"),'1'=>$langs->trans("For")); + $arraychoice = array('2'=>' ', '0'=>$langs->trans("Against"), '1'=>$langs->trans("For")); print $form->selectarray("choix".$i, $arraychoice, $car); } print 'OKKO'.$langs->trans("For").''.$langs->trans("Against").' '.$langs->trans("For").''.$langs->trans("Against").' '; - if (empty($listofanswers[$i]['format']) || ! in_array($listofanswers[$i]['format'], array('yesno','foragainst'))) + if (empty($listofanswers[$i]['format']) || !in_array($listofanswers[$i]['format'], array('yesno', 'foragainst'))) { print ''; } - if (! empty($listofanswers[$i]['format']) && $listofanswers[$i]['format'] == 'yesno') + if (!empty($listofanswers[$i]['format']) && $listofanswers[$i]['format'] == 'yesno') { - $arraychoice=array('2'=>' ','0'=>$langs->trans("No"),'1'=>$langs->trans("Yes")); + $arraychoice = array('2'=>' ', '0'=>$langs->trans("No"), '1'=>$langs->trans("Yes")); print $form->selectarray("choix".$i, $arraychoice); } - if (! empty($listofanswers[$i]['format']) && $listofanswers[$i]['format'] == 'foragainst') + if (!empty($listofanswers[$i]['format']) && $listofanswers[$i]['format'] == 'foragainst') { - $arraychoice=array('2'=>' ','0'=>$langs->trans("Against"),'1'=>$langs->trans("For")); + $arraychoice = array('2'=>' ', '0'=>$langs->trans("Against"), '1'=>$langs->trans("For")); print $form->selectarray("choix".$i, $arraychoice); } print '
    '. $langs->trans("Total") .''.$langs->trans("Total").''; - if (empty($listofanswers[$i]['format']) || ! in_array($listofanswers[$i]['format'], array('yesno','foragainst'))) print $showsumfor; - if (! empty($listofanswers[$i]['format']) && $listofanswers[$i]['format'] == 'yesno') print $langs->trans("Yes").': '.$showsumfor.'
    '.$langs->trans("No").': '.$showsumagainst; - if (! empty($listofanswers[$i]['format']) && $listofanswers[$i]['format'] == 'foragainst') print $langs->trans("For").': '.$showsumfor.'
    '.$langs->trans("Against").': '.$showsumagainst; + if (empty($listofanswers[$i]['format']) || !in_array($listofanswers[$i]['format'], array('yesno', 'foragainst'))) print $showsumfor; + if (!empty($listofanswers[$i]['format']) && $listofanswers[$i]['format'] == 'yesno') print $langs->trans("Yes").': '.$showsumfor.'
    '.$langs->trans("No").': '.$showsumagainst; + if (!empty($listofanswers[$i]['format']) && $listofanswers[$i]['format'] == 'foragainst') print $langs->trans("For").': '.$showsumfor.'
    '.$langs->trans("Against").': '.$showsumagainst; print '
    '."\n"; print ''."\n"; -$toutsujet = explode(",", $object->sujet); // With old versions, this field was not set +$toutsujet = explode(",", $object->sujet); // With old versions, this field was not set $compteursujet = 0; $meilleursujet = ''; @@ -1051,21 +1051,21 @@ for ($i = 0; $i < $nbcolonnes; $i++) { if (isset($sumfor[$i]) === true && isset($meilleurecolonne) === true && $sumfor[$i] == $meilleurecolonne) { - $meilleursujet.=", "; + $meilleursujet .= ", "; if ($object->format == "D") { $meilleursujetexport = $toutsujet[$i]; //var_dump($toutsujet); if (strpos($toutsujet[$i], '@') !== false) { $toutsujetdate = explode("@", $toutsujet[$i]); - $meilleursujet .= dol_print_date($toutsujetdate[0], 'daytext'). ($toutsujetdate[0] ? ' ('.dol_print_date($toutsujetdate[0], '%A').')' : '') . ' - ' . $toutsujetdate[1]; + $meilleursujet .= dol_print_date($toutsujetdate[0], 'daytext').($toutsujetdate[0] ? ' ('.dol_print_date($toutsujetdate[0], '%A').')' : '').' - '.$toutsujetdate[1]; } else { - $meilleursujet .= dol_print_date($toutsujet[$i], 'daytext'). ($toutsujet[$i] ? ' ('.dol_print_date($toutsujet[$i], '%A').')' : ''); + $meilleursujet .= dol_print_date($toutsujet[$i], 'daytext').($toutsujet[$i] ? ' ('.dol_print_date($toutsujet[$i], '%A').')' : ''); } } else { - $tmps=explode('@', $toutsujet[$i]); + $tmps = explode('@', $toutsujet[$i]); $meilleursujet .= dol_htmlentities($tmps[0]); } @@ -1082,9 +1082,9 @@ if ($nbofcheckbox >= 2) print '

    '."\n"; if (isset($meilleurecolonne) && $compteursujet == "1") { - print " " . $langs->trans('TheBestChoice') . ": ".$meilleursujet." " . $langs->trans("with") . " ".$meilleurecolonne." " . $vote_str . ".\n"; + print " ".$langs->trans('TheBestChoice').": ".$meilleursujet." ".$langs->trans("with")." ".$meilleurecolonne." ".$vote_str.".\n"; } elseif (isset($meilleurecolonne)) { - print " " . $langs->trans('TheBestChoices') . ": ".$meilleursujet." " . $langs->trans("with") . " ".$meilleurecolonne." " . $vote_str . ".\n"; + print " ".$langs->trans('TheBestChoices').": ".$meilleursujet." ".$langs->trans("with")." ".$meilleurecolonne." ".$vote_str.".\n"; } print '


    '."\n"; } diff --git a/htdocs/opensurvey/wizard/choix_autre.php b/htdocs/opensurvey/wizard/choix_autre.php index a8a1f8248d1..f8a3e13b80a 100644 --- a/htdocs/opensurvey/wizard/choix_autre.php +++ b/htdocs/opensurvey/wizard/choix_autre.php @@ -40,19 +40,19 @@ if (!$user->rights->opensurvey->write) accessforbidden(); if (isset($_SESSION["nbrecases"])) { for ($i = 0; $i < $_SESSION["nbrecases"]; $i++) { if (isset($_POST["choix"][$i])) { - $_SESSION["choix$i"]=$_POST["choix"][$i]; + $_SESSION["choix$i"] = $_POST["choix"][$i]; } if (isset($_POST["typecolonne"][$i])) { - $_SESSION["typecolonne$i"]=$_POST["typecolonne"][$i]; + $_SESSION["typecolonne$i"] = $_POST["typecolonne"][$i]; } } } else { //nombre de cases par défaut - $_SESSION["nbrecases"]=5; + $_SESSION["nbrecases"] = 5; } if (GETPOST("ajoutcases") || GETPOST("ajoutcases_x")) { - $_SESSION["nbrecases"]=$_SESSION["nbrecases"]+5; + $_SESSION["nbrecases"] = $_SESSION["nbrecases"] + 5; } // Create survey into database @@ -62,23 +62,23 @@ if (isset($_POST["confirmecreation"])) $toutchoix = ''; for ($i = 0; $i < $_SESSION["nbrecases"] + 1; $i++) { - if (! empty($_POST["choix"][$i])) + if (!empty($_POST["choix"][$i])) { - $toutchoix.=','; - $toutchoix.=str_replace(array(",","@"), " ", $_POST["choix"][$i]).(empty($_POST["typecolonne"][$i])?'':'@'.$_POST["typecolonne"][$i]); + $toutchoix .= ','; + $toutchoix .= str_replace(array(",", "@"), " ", $_POST["choix"][$i]).(empty($_POST["typecolonne"][$i]) ? '' : '@'.$_POST["typecolonne"][$i]); } } - $toutchoix=substr("$toutchoix", 1); - $_SESSION["toutchoix"]=$toutchoix; + $toutchoix = substr("$toutchoix", 1); + $_SESSION["toutchoix"] = $toutchoix; //test de remplissage des cases $testremplissage = ''; - for ($i=0;$i<$_SESSION["nbrecases"];$i++) + for ($i = 0; $i < $_SESSION["nbrecases"]; $i++) { if (isset($_POST["choix"][$i])) { - $testremplissage="ok"; + $testremplissage = "ok"; } } @@ -87,7 +87,7 @@ if (isset($_POST["confirmecreation"])) setEventMessages($langs->trans("ErrorOpenSurveyOneChoice"), null, 'errors'); } else { //format du sondage AUTRE - $_SESSION["formatsondage"]="A"; + $_SESSION["formatsondage"] = "A"; // Add into database ajouter_sondage(); @@ -101,10 +101,10 @@ if (isset($_POST["confirmecreation"])) * View */ -$form=new Form($db); +$form = new Form($db); -$arrayofjs=array(); -$arrayofcss=array('/opensurvey/css/style.css'); +$arrayofjs = array(); +$arrayofcss = array('/opensurvey/css/style.css'); llxHeader('', $langs->trans("OpenSurvey"), "", '', 0, 0, $arrayofjs, $arrayofcss); if (empty($_SESSION['titre'])) @@ -123,7 +123,7 @@ print '
    '."\n"; print load_fiche_titre($langs->trans("CreatePoll").' (2 / 2)'); -print '
    '. $langs->trans("PollOnChoice") .'

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

    '."\n"; print '
    '."\n"; print ''."\n"; @@ -134,8 +134,8 @@ for ($i = 0; $i < $_SESSION["nbrecases"]; $i++) { if (isset($_SESSION["choix$i"]) === false) { $_SESSION["choix$i"] = ''; } - print ''."\n"; } @@ -144,7 +144,7 @@ print '
    '. $langs->trans("TitleChoice") .' '.$j.': '; - $tmparray=array('checkbox'=>$langs->trans("CheckBox"),'yesno'=>$langs->trans("YesNoList"),'foragainst'=>$langs->trans("PourContreList")); + print '
    '.$langs->trans("TitleChoice").' '.$j.': '; + $tmparray = array('checkbox'=>$langs->trans("CheckBox"), 'yesno'=>$langs->trans("YesNoList"), 'foragainst'=>$langs->trans("PourContreList")); print '   '.$langs->trans("Type").' '.$form->selectarray("typecolonne[]", $tmparray, $_SESSION["typecolonne$i"]); print '
    '."\n"; //ajout de cases supplementaires print ''."\n"; -print ''."\n"; +print ''."\n"; print '
    '. $langs->trans("5MoreChoices") .''.$langs->trans("5MoreChoices").'
    '."\n"; print'
    '."\n"; diff --git a/htdocs/opensurvey/wizard/create_survey.php b/htdocs/opensurvey/wizard/create_survey.php index 56bca6bc1be..0f71b0ceabf 100644 --- a/htdocs/opensurvey/wizard/create_survey.php +++ b/htdocs/opensurvey/wizard/create_survey.php @@ -99,19 +99,19 @@ if (GETPOST("creation_sondage_date") || GETPOST("creation_sondage_autre")) } } - if (! $testdate) { + if (!$testdate) { setEventMessages($langs->trans('ErrorFieldRequired', $langs->transnoentitiesnoconv("ExpireDate")), null, 'errors'); } if ($titre && $testdate) { - if (! empty($creation_sondage_date)) + if (!empty($creation_sondage_date)) { header("Location: choix_date.php"); exit(); } - if (! empty($creation_sondage_autre)) + if (!empty($creation_sondage_autre)) { header("Location: choix_autre.php"); exit(); @@ -128,8 +128,8 @@ if (GETPOST("creation_sondage_date") || GETPOST("creation_sondage_autre")) $form = new Form($db); -$arrayofjs=array(); -$arrayofcss=array('/opensurvey/css/style.css'); +$arrayofjs = array(); +$arrayofcss = array('/opensurvey/css/style.css'); llxHeader('', $langs->trans("OpenSurvey"), '', "", 0, 0, $arrayofjs, $arrayofcss); print load_fiche_titre($langs->trans("CreatePoll").' (1 / 2)'); @@ -140,24 +140,24 @@ print ''."\n"; dol_fiche_head(); // Affichage des différents champs textes a remplir -print ''."\n"; +print '
    '."\n"; -print ''."\n"; -if (! $_SESSION["titre"] && (GETPOST('creation_sondage_date') || GETPOST('creation_sondage_autre'))) +print ''."\n"; +if (!$_SESSION["titre"] && (GETPOST('creation_sondage_date') || GETPOST('creation_sondage_autre'))) { setEventMessages($langs->trans("ErrorFieldRequired", $langs->transnoentitiesnoconv("PollTitle")), null, 'errors'); } print ''."\n"; -print ''."\n"; print ''."\n"; -print ''."\n"; print '
    '. $langs->trans("PollTitle") .'
    '.$langs->trans("PollTitle").'
    '. $langs->trans("Description") .''; -$doleditor=new DolEditor('commentaires', $_SESSION["commentaires"], '', 120, 'dolibarr_notes', 'In', 1, 1, 1, ROWS_7, '90%'); +print '
    '.$langs->trans("Description").''; +$doleditor = new DolEditor('commentaires', $_SESSION["commentaires"], '', 120, 'dolibarr_notes', 'In', 1, 1, 1, ROWS_7, '90%'); $doleditor->Create(0, ''); print '
    '. $langs->trans("ExpireDate") .''; +print '
    '.$langs->trans("ExpireDate").''; -print $form->selectDate($champdatefin?$champdatefin:-1, 'champdatefin', '', '', '', "add", 1, 0); +print $form->selectDate($champdatefin ? $champdatefin : -1, 'champdatefin', '', '', '', "add", 1, 0); print '
    '."\n"; @@ -173,16 +173,16 @@ print '
    '."\n"; // Check or not -if ($_SESSION["mailsonde"]) $cochemail="checked"; +if ($_SESSION["mailsonde"]) $cochemail = "checked"; -print ' '. $langs->trans("ToReceiveEMailForEachVote") .'
    '."\n"; +print ' '.$langs->trans("ToReceiveEMailForEachVote").'
    '."\n"; if ($_SESSION['allow_comments']) $allow_comments = 'checked'; -if (isset($_POST['allow_comments'])) $allow_comments=GETPOST('allow_comments')?'checked':''; +if (isset($_POST['allow_comments'])) $allow_comments = GETPOST('allow_comments') ? 'checked' : ''; print ' '.$langs->trans('CanComment').'
    '."\n"; if ($_SESSION['allow_spy']) $allow_spy = 'checked'; -if (isset($_POST['allow_spy'])) $allow_spy=GETPOST('allow_spy')?'checked':''; +if (isset($_POST['allow_spy'])) $allow_spy = GETPOST('allow_spy') ? 'checked' : ''; print ' '.$langs->trans('CanSeeOthersVote').'
    '."\n"; if (GETPOST('choix_sondage')) @@ -190,15 +190,15 @@ if (GETPOST('choix_sondage')) if (GETPOST('choix_sondage') == 'date') print ''; else print ''; print ''; - print '
    trans("TypeDate"):$langs->trans("TypeClassic")).')">'; + print '
    trans("TypeDate") : $langs->trans("TypeClassic")).')">'; } else { // Show image to selecte between date survey or other survey print '
    '."\n"; - print ' '."\n"; + print ' '."\n"; print ''."\n"; - print ' '."\n"; + print ' '."\n"; print ''."\n"; print '
    '. $langs->trans("CreateSurveyDate") .'
    '.$langs->trans("CreateSurveyDate").'
    '. $langs->trans("CreateSurveyStandard") .'
    '.$langs->trans("CreateSurveyStandard").'
    '."\n"; } diff --git a/htdocs/paybox/admin/paybox.php b/htdocs/paybox/admin/paybox.php index 1d1b82bde62..8ac92f60f18 100644 --- a/htdocs/paybox/admin/paybox.php +++ b/htdocs/paybox/admin/paybox.php @@ -121,7 +121,7 @@ dol_fiche_head($head, 'payboxaccount', '', -1); print $langs->trans("PayBoxDesc")."
    \n"; print '
    '; -print ''; +print '
    '; print ''; print ''; print ''; diff --git a/htdocs/paypal/admin/paypal.php b/htdocs/paypal/admin/paypal.php index 608492ba455..7136b505f8a 100644 --- a/htdocs/paypal/admin/paypal.php +++ b/htdocs/paypal/admin/paypal.php @@ -136,7 +136,7 @@ if (! function_exists('curl_version')) print '
    '; -print '
    '.$langs->trans("AccountParameter").''.$langs->trans("Value").'
    '; +print '
    '; // Account Parameters print ''; diff --git a/htdocs/paypal/lib/paypal.lib.php b/htdocs/paypal/lib/paypal.lib.php index 22356994008..ab9ba921e16 100644 --- a/htdocs/paypal/lib/paypal.lib.php +++ b/htdocs/paypal/lib/paypal.lib.php @@ -40,7 +40,7 @@ function paypaladmin_prepare_head() $head[$h][2] = 'paypalaccount'; $h++; - $object=new stdClass(); + $object = new stdClass(); // Show more tabs from modules // Entries must be declared in modules descriptor with line @@ -68,12 +68,12 @@ function showPaypalPaymentUrl($type, $ref) $langs->load("paypal"); $langs->load("paybox"); - $servicename='PayPal'; - $out='

    '; - $out.=img_picto('', 'globe').' '.$langs->trans("ToOfferALinkForOnlinePayment", $servicename).'
    '; - $url=getPaypalPaymentUrl(0, $type, $ref); - $out.=''; - $out.=ajax_autoselect("paypalurl", 0); + $servicename = 'PayPal'; + $out = '

    '; + $out .= img_picto('', 'globe').' '.$langs->trans("ToOfferALinkForOnlinePayment", $servicename).'
    '; + $url = getPaypalPaymentUrl(0, $type, $ref); + $out .= ''; + $out .= ajax_autoselect("paypalurl", 0); return $out; } @@ -92,92 +92,92 @@ function getPaypalPaymentUrl($mode, $type, $ref = '', $amount = '9.99', $freetag { global $conf; - $ref=str_replace(' ', '', $ref); + $ref = str_replace(' ', '', $ref); if ($type == 'free') { - $out=DOL_MAIN_URL_ROOT.'/public/paypal/newpayment.php?amount='.($mode?'':'').$amount.($mode?'':'').'&tag='.($mode?'':'').$freetag.($mode?'':''); - if (! empty($conf->global->PAYPAL_SECURITY_TOKEN)) + $out = DOL_MAIN_URL_ROOT.'/public/paypal/newpayment.php?amount='.($mode ? '' : '').$amount.($mode ? '' : '').'&tag='.($mode ? '' : '').$freetag.($mode ? '' : ''); + if (!empty($conf->global->PAYPAL_SECURITY_TOKEN)) { - if (empty($conf->global->PAYPAL_SECURITY_TOKEN_UNIQUE)) $out.='&securekey='.$conf->global->PAYPAL_SECURITY_TOKEN; - else $out.='&securekey='.dol_hash($conf->global->PAYPAL_SECURITY_TOKEN, 2); + if (empty($conf->global->PAYPAL_SECURITY_TOKEN_UNIQUE)) $out .= '&securekey='.$conf->global->PAYPAL_SECURITY_TOKEN; + else $out .= '&securekey='.dol_hash($conf->global->PAYPAL_SECURITY_TOKEN, 2); } } if ($type == 'order') { - $out=DOL_MAIN_URL_ROOT.'/public/paypal/newpayment.php?source=order&ref='.($mode?'':''); - if ($mode == 1) $out.='order_ref'; - if ($mode == 0) $out.=urlencode($ref); - $out.=($mode?'':''); - if (! empty($conf->global->PAYPAL_SECURITY_TOKEN)) + $out = DOL_MAIN_URL_ROOT.'/public/paypal/newpayment.php?source=order&ref='.($mode ? '' : ''); + if ($mode == 1) $out .= 'order_ref'; + if ($mode == 0) $out .= urlencode($ref); + $out .= ($mode ? '' : ''); + if (!empty($conf->global->PAYPAL_SECURITY_TOKEN)) { - if (empty($conf->global->PAYPAL_SECURITY_TOKEN_UNIQUE)) $out.='&securekey='.$conf->global->PAYPAL_SECURITY_TOKEN; + if (empty($conf->global->PAYPAL_SECURITY_TOKEN_UNIQUE)) $out .= '&securekey='.$conf->global->PAYPAL_SECURITY_TOKEN; else { - $out.='&securekey='.($mode?'':''); - if ($mode == 1) $out.="hash('".$conf->global->PAYPAL_SECURITY_TOKEN."' + '".$type."' + order_ref)"; - if ($mode == 0) $out.= dol_hash($conf->global->PAYPAL_SECURITY_TOKEN . $type . $ref, 2); - $out.=($mode?'':''); + $out .= '&securekey='.($mode ? '' : ''); + if ($mode == 1) $out .= "hash('".$conf->global->PAYPAL_SECURITY_TOKEN."' + '".$type."' + order_ref)"; + if ($mode == 0) $out .= dol_hash($conf->global->PAYPAL_SECURITY_TOKEN.$type.$ref, 2); + $out .= ($mode ? '' : ''); } } } if ($type == 'invoice') { - $out=DOL_MAIN_URL_ROOT.'/public/paypal/newpayment.php?source=invoice&ref='.($mode?'':''); - if ($mode == 1) $out.='invoice_ref'; - if ($mode == 0) $out.=urlencode($ref); - $out.=($mode?'':''); - if (! empty($conf->global->PAYPAL_SECURITY_TOKEN)) + $out = DOL_MAIN_URL_ROOT.'/public/paypal/newpayment.php?source=invoice&ref='.($mode ? '' : ''); + if ($mode == 1) $out .= 'invoice_ref'; + if ($mode == 0) $out .= urlencode($ref); + $out .= ($mode ? '' : ''); + if (!empty($conf->global->PAYPAL_SECURITY_TOKEN)) { - if (empty($conf->global->PAYPAL_SECURITY_TOKEN_UNIQUE)) $out.='&securekey='.$conf->global->PAYPAL_SECURITY_TOKEN; + if (empty($conf->global->PAYPAL_SECURITY_TOKEN_UNIQUE)) $out .= '&securekey='.$conf->global->PAYPAL_SECURITY_TOKEN; else { - $out.='&securekey='.($mode?'':''); - if ($mode == 1) $out.="hash('".$conf->global->PAYPAL_SECURITY_TOKEN."' + '".$type."' + invoice_ref)"; - if ($mode == 0) $out.= dol_hash($conf->global->PAYPAL_SECURITY_TOKEN . $type . $ref, 2); - $out.=($mode?'':''); + $out .= '&securekey='.($mode ? '' : ''); + if ($mode == 1) $out .= "hash('".$conf->global->PAYPAL_SECURITY_TOKEN."' + '".$type."' + invoice_ref)"; + if ($mode == 0) $out .= dol_hash($conf->global->PAYPAL_SECURITY_TOKEN.$type.$ref, 2); + $out .= ($mode ? '' : ''); } } } if ($type == 'contractline') { - $out=DOL_MAIN_URL_ROOT.'/public/paypal/newpayment.php?source=contractline&ref='.($mode?'':''); - if ($mode == 1) $out.='contractline_ref'; - if ($mode == 0) $out.=urlencode($ref); - $out.=($mode?'':''); - if (! empty($conf->global->PAYPAL_SECURITY_TOKEN)) + $out = DOL_MAIN_URL_ROOT.'/public/paypal/newpayment.php?source=contractline&ref='.($mode ? '' : ''); + if ($mode == 1) $out .= 'contractline_ref'; + if ($mode == 0) $out .= urlencode($ref); + $out .= ($mode ? '' : ''); + if (!empty($conf->global->PAYPAL_SECURITY_TOKEN)) { - if (empty($conf->global->PAYPAL_SECURITY_TOKEN_UNIQUE)) $out.='&securekey='.$conf->global->PAYPAL_SECURITY_TOKEN; + if (empty($conf->global->PAYPAL_SECURITY_TOKEN_UNIQUE)) $out .= '&securekey='.$conf->global->PAYPAL_SECURITY_TOKEN; else { - $out.='&securekey='.($mode?'':''); - if ($mode == 1) $out.="hash('".$conf->global->PAYPAL_SECURITY_TOKEN."' + '".$type."' + contractline_ref)"; - if ($mode == 0) $out.= dol_hash($conf->global->PAYPAL_SECURITY_TOKEN . $type . $ref, 2); - $out.=($mode?'':''); + $out .= '&securekey='.($mode ? '' : ''); + if ($mode == 1) $out .= "hash('".$conf->global->PAYPAL_SECURITY_TOKEN."' + '".$type."' + contractline_ref)"; + if ($mode == 0) $out .= dol_hash($conf->global->PAYPAL_SECURITY_TOKEN.$type.$ref, 2); + $out .= ($mode ? '' : ''); } } } if ($type == 'membersubscription') { - $out=DOL_MAIN_URL_ROOT.'/public/paypal/newpayment.php?source=membersubscription&ref='.($mode?'':''); - if ($mode == 1) $out.='member_ref'; - if ($mode == 0) $out.=urlencode($ref); - $out.=($mode?'':''); - if (! empty($conf->global->PAYPAL_SECURITY_TOKEN)) + $out = DOL_MAIN_URL_ROOT.'/public/paypal/newpayment.php?source=membersubscription&ref='.($mode ? '' : ''); + if ($mode == 1) $out .= 'member_ref'; + if ($mode == 0) $out .= urlencode($ref); + $out .= ($mode ? '' : ''); + if (!empty($conf->global->PAYPAL_SECURITY_TOKEN)) { - if (empty($conf->global->PAYPAL_SECURITY_TOKEN_UNIQUE)) $out.='&securekey='.$conf->global->PAYPAL_SECURITY_TOKEN; + if (empty($conf->global->PAYPAL_SECURITY_TOKEN_UNIQUE)) $out .= '&securekey='.$conf->global->PAYPAL_SECURITY_TOKEN; else { - $out.='&securekey='.($mode?'':''); - if ($mode == 1) $out.="hash('".$conf->global->PAYPAL_SECURITY_TOKEN."' + '".$type."' + member_ref)"; - if ($mode == 0) $out.= dol_hash($conf->global->PAYPAL_SECURITY_TOKEN . $type . $ref, 2); - $out.=($mode?'':''); + $out .= '&securekey='.($mode ? '' : ''); + if ($mode == 1) $out .= "hash('".$conf->global->PAYPAL_SECURITY_TOKEN."' + '".$type."' + member_ref)"; + if ($mode == 0) $out .= dol_hash($conf->global->PAYPAL_SECURITY_TOKEN.$type.$ref, 2); + $out .= ($mode ? '' : ''); } } } // For multicompany - $out.="&entity=".$conf->entity; // Check the entity because He may be the same reference in several entities + $out .= "&entity=".$conf->entity; // Check the entity because He may be the same reference in several entities return $out; } @@ -209,27 +209,27 @@ function print_paypal_redirect($paymentAmount, $currencyCodeType, $paymentType, //' //'------------------------------------------------- - if (empty($conf->global->PAYPAL_API_INTEGRAL_OR_PAYPALONLY)) $conf->global->PAYPAL_API_INTEGRAL_OR_PAYPALONLY='integral'; + if (empty($conf->global->PAYPAL_API_INTEGRAL_OR_PAYPALONLY)) $conf->global->PAYPAL_API_INTEGRAL_OR_PAYPALONLY = 'integral'; - $solutionType='Sole'; - $landingPage='Billing'; + $solutionType = 'Sole'; + $landingPage = 'Billing'; // For payment with Paypal only if ($conf->global->PAYPAL_API_INTEGRAL_OR_PAYPALONLY == 'paypalonly') { - $solutionType='Mark'; - $landingPage='Login'; + $solutionType = 'Mark'; + $landingPage = 'Login'; } // For payment with Credit card or Paypal if ($conf->global->PAYPAL_API_INTEGRAL_OR_PAYPALONLY == 'integral') { - $solutionType='Sole'; - $landingPage='Billing'; + $solutionType = 'Sole'; + $landingPage = 'Billing'; } // For payment with Credit card if ($conf->global->PAYPAL_API_INTEGRAL_OR_PAYPALONLY == 'cconly') { - $solutionType='Sole'; - $landingPage='Billing'; + $solutionType = 'Sole'; + $landingPage = 'Billing'; } dol_syslog("expresscheckout redirect with callSetExpressCheckout $paymentAmount, $currencyCodeType, $paymentType, $returnURL, $cancelURL, $tag, $solutionType, $landingPage, $shipToName, $shipToStreet, $shipToCity, $shipToState, $shipToCountryCode, $shipToZip, $shipToStreet2, $phoneNum"); @@ -255,12 +255,12 @@ function print_paypal_redirect($paymentAmount, $currencyCodeType, $paymentType, ); $ack = strtoupper($resArray["ACK"]); - if($ack=="SUCCESS" || $ack=="SUCCESSWITHWARNING") + if ($ack == "SUCCESS" || $ack == "SUCCESSWITHWARNING") { - $token=$resArray["TOKEN"]; + $token = $resArray["TOKEN"]; // Redirect to paypal.com here - $payPalURL = $API_Url . $token; + $payPalURL = $API_Url.$token; header("Location: ".$payPalURL); exit; } @@ -274,15 +274,15 @@ function print_paypal_redirect($paymentAmount, $currencyCodeType, $paymentType, if ($ErrorCode == 10729) { - $mesg.= "PayPal can't accept payments for this thirdparty. An address is defined but is not complete (missing State).
    Ask system administrator to fix address or to setup Paypal module to accept payments even on not complete addresses (remove option PAYPAL_REQUIRE_VALID_SHIPPING_ADDRESS).
    \n"; + $mesg .= "PayPal can't accept payments for this thirdparty. An address is defined but is not complete (missing State).
    Ask system administrator to fix address or to setup Paypal module to accept payments even on not complete addresses (remove option PAYPAL_REQUIRE_VALID_SHIPPING_ADDRESS).
    \n"; } else { - $mesg = $langs->trans('SetExpressCheckoutAPICallFailed') . "
    \n"; - $mesg.= $langs->trans('DetailedErrorMessage') . ": " . $ErrorLongMsg."
    \n"; - $mesg.= $langs->trans('ShortErrorMessage') . ": " . $ErrorShortMsg."
    \n"; - $mesg.= $langs->trans('ErrorCode') . ": " . $ErrorCode."
    \n"; - $mesg.= $langs->trans('ErrorSeverityCode') . ": " . $ErrorSeverityCode."
    \n"; + $mesg = $langs->trans('SetExpressCheckoutAPICallFailed')."
    \n"; + $mesg .= $langs->trans('DetailedErrorMessage').": ".$ErrorLongMsg."
    \n"; + $mesg .= $langs->trans('ShortErrorMessage').": ".$ErrorShortMsg."
    \n"; + $mesg .= $langs->trans('ErrorCode').": ".$ErrorCode."
    \n"; + $mesg .= $langs->trans('ErrorSeverityCode').": ".$ErrorSeverityCode."
    \n"; } return $mesg; @@ -342,92 +342,92 @@ function callSetExpressCheckout($paymentAmount, $currencyCodeType, $paymentType, $nvpstr = ''; //$nvpstr = $nvpstr . "&VERSION=".$API_version; // Already added by hash_call - $nvpstr = $nvpstr . "&RETURNURL=" . urlencode($returnURL); - $nvpstr = $nvpstr . "&CANCELURL=" . urlencode($cancelURL); - if (! empty($conf->global->PAYPAL_ALLOW_NOTES)) + $nvpstr = $nvpstr."&RETURNURL=".urlencode($returnURL); + $nvpstr = $nvpstr."&CANCELURL=".urlencode($cancelURL); + if (!empty($conf->global->PAYPAL_ALLOW_NOTES)) { - $nvpstr = $nvpstr . "&ALLOWNOTE=0"; + $nvpstr = $nvpstr."&ALLOWNOTE=0"; } if (empty($conf->global->PAYPAL_REQUIRE_VALID_SHIPPING_ADDRESS)) { - $nvpstr = $nvpstr . "&NOSHIPPING=1"; // An empty or not complete shipping address will be accepted + $nvpstr = $nvpstr."&NOSHIPPING=1"; // An empty or not complete shipping address will be accepted } else { - $nvpstr = $nvpstr . "&NOSHIPPING=0"; // A valid shipping address is required (full required fields mandatory) + $nvpstr = $nvpstr."&NOSHIPPING=0"; // A valid shipping address is required (full required fields mandatory) } - $nvpstr = $nvpstr . "&SOLUTIONTYPE=" . urlencode($solutionType); - $nvpstr = $nvpstr . "&LANDINGPAGE=" . urlencode($landingPage); - if (! empty($conf->global->PAYPAL_CUSTOMER_SERVICE_NUMBER)) + $nvpstr = $nvpstr."&SOLUTIONTYPE=".urlencode($solutionType); + $nvpstr = $nvpstr."&LANDINGPAGE=".urlencode($landingPage); + if (!empty($conf->global->PAYPAL_CUSTOMER_SERVICE_NUMBER)) { - $nvpstr = $nvpstr . "&CUSTOMERSERVICENUMBER=" . urlencode($conf->global->PAYPAL_CUSTOMER_SERVICE_NUMBER); // Hotline phone number + $nvpstr = $nvpstr."&CUSTOMERSERVICENUMBER=".urlencode($conf->global->PAYPAL_CUSTOMER_SERVICE_NUMBER); // Hotline phone number } $paypalprefix = 'PAYMENTREQUEST_0_'; //$paypalprefix = ''; - if (! empty($paypalprefix) && $paymentType == 'Sole') $paymentType='Sale'; + if (!empty($paypalprefix) && $paymentType == 'Sole') $paymentType = 'Sale'; - $nvpstr = $nvpstr . "&AMT=". urlencode($paymentAmount); // Total for all elements + $nvpstr = $nvpstr."&AMT=".urlencode($paymentAmount); // Total for all elements - $nvpstr = $nvpstr . "&".$paypalprefix."INVNUM=" . urlencode($tag); - $nvpstr = $nvpstr . "&".$paypalprefix."AMT=". urlencode($paymentAmount); // AMT deprecated by paypal -> PAYMENTREQUEST_n_AMT - $nvpstr = $nvpstr . "&".$paypalprefix."ITEMAMT=". urlencode($paymentAmount); // AMT deprecated by paypal -> PAYMENTREQUEST_n_AMT - $nvpstr = $nvpstr . "&".$paypalprefix."PAYMENTACTION=" . urlencode($paymentType); // PAYMENTACTION deprecated by paypal -> PAYMENTREQUEST_n_PAYMENTACTION - $nvpstr = $nvpstr . "&".$paypalprefix."CURRENCYCODE=" . urlencode($currencyCodeType); // CURRENCYCODE deprecated by paypal -> PAYMENTREQUEST_n_CURRENCYCODE + $nvpstr = $nvpstr."&".$paypalprefix."INVNUM=".urlencode($tag); + $nvpstr = $nvpstr."&".$paypalprefix."AMT=".urlencode($paymentAmount); // AMT deprecated by paypal -> PAYMENTREQUEST_n_AMT + $nvpstr = $nvpstr."&".$paypalprefix."ITEMAMT=".urlencode($paymentAmount); // AMT deprecated by paypal -> PAYMENTREQUEST_n_AMT + $nvpstr = $nvpstr."&".$paypalprefix."PAYMENTACTION=".urlencode($paymentType); // PAYMENTACTION deprecated by paypal -> PAYMENTREQUEST_n_PAYMENTACTION + $nvpstr = $nvpstr."&".$paypalprefix."CURRENCYCODE=".urlencode($currencyCodeType); // CURRENCYCODE deprecated by paypal -> PAYMENTREQUEST_n_CURRENCYCODE - $nvpstr = $nvpstr . "&".$paypalprefix."L_PAYMENTREQUEST_0_QTY0=1"; - $nvpstr = $nvpstr . "&".$paypalprefix."L_PAYMENTREQUEST_0_AMT0=".urlencode($paymentAmount); - $nvpstr = $nvpstr . "&".$paypalprefix."L_PAYMENTREQUEST_0_NAME0=".urlencode($desc); - $nvpstr = $nvpstr . "&".$paypalprefix."L_PAYMENTREQUEST_0_NUMBER0=0"; + $nvpstr = $nvpstr."&".$paypalprefix."L_PAYMENTREQUEST_0_QTY0=1"; + $nvpstr = $nvpstr."&".$paypalprefix."L_PAYMENTREQUEST_0_AMT0=".urlencode($paymentAmount); + $nvpstr = $nvpstr."&".$paypalprefix."L_PAYMENTREQUEST_0_NAME0=".urlencode($desc); + $nvpstr = $nvpstr."&".$paypalprefix."L_PAYMENTREQUEST_0_NUMBER0=0"; - $nvpstr = $nvpstr . "&".$paypalprefix."SHIPTONAME=" . urlencode($shipToName); // SHIPTONAME deprecated by paypal -> PAYMENTREQUEST_n_SHIPTONAME - $nvpstr = $nvpstr . "&".$paypalprefix."SHIPTOSTREET=" . urlencode($shipToStreet); // - $nvpstr = $nvpstr . "&".$paypalprefix."SHIPTOSTREET2=" . urlencode($shipToStreet2); - $nvpstr = $nvpstr . "&".$paypalprefix."SHIPTOCITY=" . urlencode($shipToCity); - $nvpstr = $nvpstr . "&".$paypalprefix."SHIPTOSTATE=" . urlencode($shipToState); - $nvpstr = $nvpstr . "&".$paypalprefix."SHIPTOCOUNTRYCODE=" . urlencode($shipToCountryCode); - $nvpstr = $nvpstr . "&".$paypalprefix."SHIPTOZIP=" . urlencode($shipToZip); - $nvpstr = $nvpstr . "&".$paypalprefix."PHONENUM=" . urlencode($phoneNum); - if (! empty($email)) $nvpstr = $nvpstr . "&".$paypalprefix."EMAIL=" . urlencode($email); // EMAIL deprecated by paypal -> PAYMENTREQUEST_n_EMAIL - if (! empty($desc)) $nvpstr = $nvpstr . "&".$paypalprefix."DESC=" . urlencode($desc); // DESC deprecated by paypal -> PAYMENTREQUEST_n_DESC + $nvpstr = $nvpstr."&".$paypalprefix."SHIPTONAME=".urlencode($shipToName); // SHIPTONAME deprecated by paypal -> PAYMENTREQUEST_n_SHIPTONAME + $nvpstr = $nvpstr."&".$paypalprefix."SHIPTOSTREET=".urlencode($shipToStreet); // + $nvpstr = $nvpstr."&".$paypalprefix."SHIPTOSTREET2=".urlencode($shipToStreet2); + $nvpstr = $nvpstr."&".$paypalprefix."SHIPTOCITY=".urlencode($shipToCity); + $nvpstr = $nvpstr."&".$paypalprefix."SHIPTOSTATE=".urlencode($shipToState); + $nvpstr = $nvpstr."&".$paypalprefix."SHIPTOCOUNTRYCODE=".urlencode($shipToCountryCode); + $nvpstr = $nvpstr."&".$paypalprefix."SHIPTOZIP=".urlencode($shipToZip); + $nvpstr = $nvpstr."&".$paypalprefix."PHONENUM=".urlencode($phoneNum); + if (!empty($email)) $nvpstr = $nvpstr."&".$paypalprefix."EMAIL=".urlencode($email); // EMAIL deprecated by paypal -> PAYMENTREQUEST_n_EMAIL + if (!empty($desc)) $nvpstr = $nvpstr."&".$paypalprefix."DESC=".urlencode($desc); // DESC deprecated by paypal -> PAYMENTREQUEST_n_DESC - if (! empty($conf->global->PAYPAL_LOGOIMG) && $mysoc->logo) + if (!empty($conf->global->PAYPAL_LOGOIMG) && $mysoc->logo) { global $dolibarr_main_url_root; // Define $urlwithroot - $urlwithouturlroot=preg_replace('/'.preg_quote(DOL_URL_ROOT, '/').'$/i', '', trim($dolibarr_main_url_root)); - $urlwithroot=$urlwithouturlroot.DOL_URL_ROOT; // This is to use external domain name found into config file + $urlwithouturlroot = preg_replace('/'.preg_quote(DOL_URL_ROOT, '/').'$/i', '', trim($dolibarr_main_url_root)); + $urlwithroot = $urlwithouturlroot.DOL_URL_ROOT; // This is to use external domain name found into config file //$urlwithroot=DOL_MAIN_URL_ROOT; // This is to use same domain name than current - $urllogo=$urlwithroot."/viewimage.php?modulepart=mycompany&file=".urlencode('logos/'.$mysoc->logo); - $nvpstr = $nvpstr . "&LOGOIMG=" . urlencode($urllogo); + $urllogo = $urlwithroot."/viewimage.php?modulepart=mycompany&file=".urlencode('logos/'.$mysoc->logo); + $nvpstr = $nvpstr."&LOGOIMG=".urlencode($urllogo); } - if (! empty($conf->global->PAYPAL_BRANDNAME)) + if (!empty($conf->global->PAYPAL_BRANDNAME)) { - $nvpstr = $nvpstr . "&BRANDNAME=" . urlencode($conf->global->PAYPAL_BRANDNAME); // BRANDNAME + $nvpstr = $nvpstr."&BRANDNAME=".urlencode($conf->global->PAYPAL_BRANDNAME); // BRANDNAME } - if (! empty($conf->global->PAYPAL_NOTETOBUYER)) + if (!empty($conf->global->PAYPAL_NOTETOBUYER)) { - $nvpstr = $nvpstr . "&NOTETOBUYER=" . urlencode($conf->global->PAYPAL_NOTETOBUYER); // PAYPAL_NOTETOBUYER + $nvpstr = $nvpstr."&NOTETOBUYER=".urlencode($conf->global->PAYPAL_NOTETOBUYER); // PAYPAL_NOTETOBUYER } $_SESSION["FinalPaymentAmt"] = $paymentAmount; $_SESSION["currencyCodeType"] = $currencyCodeType; - $_SESSION["PaymentType"] = $paymentType; // 'Mark', 'Sole' - $_SESSION['ipaddress'] = $_SERVER['REMOTE_ADDR']; // Payer ip + $_SESSION["PaymentType"] = $paymentType; // 'Mark', 'Sole' + $_SESSION['ipaddress'] = $_SERVER['REMOTE_ADDR']; // Payer ip //'--------------------------------------------------------------------------------------------------------------- //' Make the API call to PayPal //' If the API call succeded, then redirect the buyer to PayPal to begin to authorize payment. //' If an error occured, show the resulting errors //'--------------------------------------------------------------------------------------------------------------- - $resArray=hash_call("SetExpressCheckout", $nvpstr); + $resArray = hash_call("SetExpressCheckout", $nvpstr); $ack = strtoupper($resArray["ACK"]); - if($ack=="SUCCESS" || $ack=="SUCCESSWITHWARNING") + if ($ack == "SUCCESS" || $ack == "SUCCESSWITHWARNING") { $token = urldecode($resArray["TOKEN"]); - $_SESSION['TOKEN']=$token; + $_SESSION['TOKEN'] = $token; } return $resArray; @@ -459,7 +459,7 @@ function getDetails($token) //' Build a second API request to PayPal, using the token as the //' ID to get the details on the payment authorization //'--------------------------------------------------------------------------- - $nvpstr="&TOKEN=" . $token; + $nvpstr = "&TOKEN=".$token; //'--------------------------------------------------------------------------- //' Make the API call and store the results in an array. @@ -467,9 +467,9 @@ function getDetails($token) //' an action to complete the payment. //' If failed, show the error //'--------------------------------------------------------------------------- - $resArray=hash_call("GetExpressCheckoutDetails", $nvpstr); + $resArray = hash_call("GetExpressCheckoutDetails", $nvpstr); $ack = strtoupper($resArray["ACK"]); - if($ack == "SUCCESS" || $ack=="SUCCESSWITHWARNING") + if ($ack == "SUCCESS" || $ack == "SUCCESSWITHWARNING") { $_SESSION['payer_id'] = $resArray['PAYERID']; } @@ -502,18 +502,18 @@ function confirmPayment($token, $paymentType, $currencyCodeType, $payerID, $ipad global $PAYPAL_API_USER, $PAYPAL_API_PASSWORD, $PAYPAL_API_SIGNATURE; $nvpstr = ''; - $nvpstr .= '&TOKEN=' . urlencode($token); - $nvpstr .= '&PAYERID=' . urlencode($payerID); - $nvpstr .= '&PAYMENTACTION=' . urlencode($paymentType); - $nvpstr .= '&AMT=' . urlencode($FinalPaymentAmt); - $nvpstr .= '&CURRENCYCODE=' . urlencode($currencyCodeType); - $nvpstr .= '&IPADDRESS=' . urlencode($ipaddress); - $nvpstr .= '&INVNUM=' . urlencode($tag); + $nvpstr .= '&TOKEN='.urlencode($token); + $nvpstr .= '&PAYERID='.urlencode($payerID); + $nvpstr .= '&PAYMENTACTION='.urlencode($paymentType); + $nvpstr .= '&AMT='.urlencode($FinalPaymentAmt); + $nvpstr .= '&CURRENCYCODE='.urlencode($currencyCodeType); + $nvpstr .= '&IPADDRESS='.urlencode($ipaddress); + $nvpstr .= '&INVNUM='.urlencode($tag); /* Make the call to PayPal to finalize payment If an error occured, show the resulting errors */ - $resArray=hash_call("DoExpressCheckoutPayment", $nvpstr); + $resArray = hash_call("DoExpressCheckoutPayment", $nvpstr); /* Display the API response back to the browser. If the response from PayPal was a success, display the response parameters' @@ -591,8 +591,8 @@ function hash_call($methodName, $nvpStr) global $PAYPAL_API_USER, $PAYPAL_API_PASSWORD, $PAYPAL_API_SIGNATURE; // TODO problem with triggers - $API_version="98.0"; - if (! empty($conf->global->PAYPAL_API_SANDBOX) || GETPOST('forcesandbox', 'alpha')) // We can force sand box with param 'forcesandbox' + $API_version = "98.0"; + if (!empty($conf->global->PAYPAL_API_SANDBOX) || GETPOST('forcesandbox', 'alpha')) // We can force sand box with param 'forcesandbox' { $API_Endpoint = "https://api-3t.sandbox.paypal.com/nvp"; $API_Url = "https://www.sandbox.paypal.com/webscr?cmd=_express-checkout&token="; @@ -604,14 +604,14 @@ function hash_call($methodName, $nvpStr) } // Clean parameters - $PAYPAL_API_USER=""; - if (! empty($conf->global->PAYPAL_API_USER)) $PAYPAL_API_USER=$conf->global->PAYPAL_API_USER; - $PAYPAL_API_PASSWORD=""; - if (! empty($conf->global->PAYPAL_API_PASSWORD)) $PAYPAL_API_PASSWORD=$conf->global->PAYPAL_API_PASSWORD; - $PAYPAL_API_SIGNATURE=""; - if (! empty($conf->global->PAYPAL_API_SIGNATURE)) $PAYPAL_API_SIGNATURE=$conf->global->PAYPAL_API_SIGNATURE; - $PAYPAL_API_SANDBOX=""; - if (! empty($conf->global->PAYPAL_API_SANDBOX)) $PAYPAL_API_SANDBOX=$conf->global->PAYPAL_API_SANDBOX; + $PAYPAL_API_USER = ""; + if (!empty($conf->global->PAYPAL_API_USER)) $PAYPAL_API_USER = $conf->global->PAYPAL_API_USER; + $PAYPAL_API_PASSWORD = ""; + if (!empty($conf->global->PAYPAL_API_PASSWORD)) $PAYPAL_API_PASSWORD = $conf->global->PAYPAL_API_PASSWORD; + $PAYPAL_API_SIGNATURE = ""; + if (!empty($conf->global->PAYPAL_API_SIGNATURE)) $PAYPAL_API_SIGNATURE = $conf->global->PAYPAL_API_SIGNATURE; + $PAYPAL_API_SANDBOX = ""; + if (!empty($conf->global->PAYPAL_API_SANDBOX)) $PAYPAL_API_SANDBOX = $conf->global->PAYPAL_API_SANDBOX; // TODO END problem with triggers dol_syslog("Paypal API endpoint ".$API_Endpoint); @@ -626,14 +626,14 @@ function hash_call($methodName, $nvpStr) curl_setopt($ch, CURLOPT_URL, $API_Endpoint); curl_setopt($ch, CURLOPT_VERBOSE, 1); // TLSv1 by default or change to TLSv1.2 in module configuration - curl_setopt($ch, CURLOPT_SSLVERSION, (empty($conf->global->PAYPAL_SSLVERSION)?1:$conf->global->PAYPAL_SSLVERSION)); + curl_setopt($ch, CURLOPT_SSLVERSION, (empty($conf->global->PAYPAL_SSLVERSION) ? 1 : $conf->global->PAYPAL_SSLVERSION)); //turning off the server and peer verification(TrustManager Concept). curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false); curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false); - curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, empty($conf->global->MAIN_USE_CONNECT_TIMEOUT)?5:$conf->global->MAIN_USE_CONNECT_TIMEOUT); - curl_setopt($ch, CURLOPT_TIMEOUT, empty($conf->global->MAIN_USE_RESPONSE_TIMEOUT)?30:$conf->global->MAIN_USE_RESPONSE_TIMEOUT); + curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, empty($conf->global->MAIN_USE_CONNECT_TIMEOUT) ? 5 : $conf->global->MAIN_USE_CONNECT_TIMEOUT); + curl_setopt($ch, CURLOPT_TIMEOUT, empty($conf->global->MAIN_USE_RESPONSE_TIMEOUT) ? 30 : $conf->global->MAIN_USE_RESPONSE_TIMEOUT); curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1); curl_setopt($ch, CURLOPT_POST, 1); @@ -641,15 +641,15 @@ function hash_call($methodName, $nvpStr) //if USE_PROXY constant set to true in Constants.php, then only proxy will be enabled. if ($USE_PROXY) { - dol_syslog("Paypal API hash_call set proxy to ".$PROXY_HOST. ":" . $PROXY_PORT." - ".$PROXY_USER. ":" . $PROXY_PASS); + dol_syslog("Paypal API hash_call 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); + curl_setopt($ch, CURLOPT_PROXY, $PROXY_HOST.":".$PROXY_PORT); + if ($PROXY_USER) curl_setopt($ch, CURLOPT_PROXYUSERPWD, $PROXY_USER.":".$PROXY_PASS); } //NVPRequest for submitting to server - $nvpreq ="METHOD=" . urlencode($methodName) . "&VERSION=" . urlencode($API_version) . "&PWD=" . urlencode($PAYPAL_API_PASSWORD) . "&USER=" . urlencode($PAYPAL_API_USER) . "&SIGNATURE=" . urlencode($PAYPAL_API_SIGNATURE) . $nvpStr; - $nvpreq.="&LOCALECODE=".strtoupper($langs->getDefaultLang(1)); + $nvpreq = "METHOD=".urlencode($methodName)."&VERSION=".urlencode($API_version)."&PWD=".urlencode($PAYPAL_API_PASSWORD)."&USER=".urlencode($PAYPAL_API_USER)."&SIGNATURE=".urlencode($PAYPAL_API_SIGNATURE).$nvpStr; + $nvpreq .= "&LOCALECODE=".strtoupper($langs->getDefaultLang(1)); //$nvpreq.="&BRANDNAME=".urlencode(); // Override merchant name //$nvpreq.="&NOTIFYURL=".urlencode(); // For Instant Payment Notification url @@ -662,18 +662,18 @@ function hash_call($methodName, $nvpStr) //getting response from server $response = curl_exec($ch); - $nvpReqArray=deformatNVP($nvpreq); - $_SESSION['nvpReqArray']=$nvpReqArray; + $nvpReqArray = deformatNVP($nvpreq); + $_SESSION['nvpReqArray'] = $nvpReqArray; //convrting NVPResponse to an Associative Array dol_syslog("Paypal API hash_call Response nvpresp=".$response); - $nvpResArray=deformatNVP($response); + $nvpResArray = deformatNVP($response); if (curl_errno($ch)) { // moving to display page to display curl errors - $_SESSION['curl_error_no']=curl_errno($ch); - $_SESSION['curl_error_msg']=curl_error($ch); + $_SESSION['curl_error_no'] = curl_errno($ch); + $_SESSION['curl_error_msg'] = curl_error($ch); //Execute the Error handling module to display errors. } @@ -696,22 +696,22 @@ function hash_call($methodName, $nvpStr) */ function deformatNVP($nvpstr) { - $intial=0; + $intial = 0; $nvpArray = array(); - while(strlen($nvpstr)) + while (strlen($nvpstr)) { //postion of Key - $keypos= strpos($nvpstr, '='); + $keypos = strpos($nvpstr, '='); //position of value - $valuepos = strpos($nvpstr, '&') ? strpos($nvpstr, '&'): strlen($nvpstr); + $valuepos = strpos($nvpstr, '&') ? strpos($nvpstr, '&') : strlen($nvpstr); /*getting the Key and Value values and storing in a Associative Array*/ - $keyval=substr($nvpstr, $intial, $keypos); - $valval=substr($nvpstr, $keypos+1, $valuepos-$keypos-1); + $keyval = substr($nvpstr, $intial, $keypos); + $valval = substr($nvpstr, $keypos + 1, $valuepos - $keypos - 1); //decoding the respose - $nvpArray[urldecode($keyval)] =urldecode($valval); - $nvpstr=substr($nvpstr, $valuepos+1, strlen($nvpstr)); + $nvpArray[urldecode($keyval)] = urldecode($valval); + $nvpstr = substr($nvpstr, $valuepos + 1, strlen($nvpstr)); } return $nvpArray; } @@ -723,16 +723,16 @@ function deformatNVP($nvpstr) */ function getApiError() { - $errors=array(); + $errors = array(); - $resArray=$_SESSION['reshash']; + $resArray = $_SESSION['reshash']; - if(isset($_SESSION['curl_error_no'])) + if (isset($_SESSION['curl_error_no'])) { $errors[] = $_SESSION['curl_error_no'].'-'.$_SESSION['curl_error_msg']; } - foreach($resArray as $key => $value) + foreach ($resArray as $key => $value) { $errors[] = $key.'-'.$value; } diff --git a/htdocs/printing/admin/printing.php b/htdocs/printing/admin/printing.php index 8c71ff0fcb7..4549e9657de 100644 --- a/htdocs/printing/admin/printing.php +++ b/htdocs/printing/admin/printing.php @@ -33,17 +33,17 @@ use OAuth\Common\Storage\DoliStorage; // Load translation files required by the page $langs->loadLangs(array('admin', 'printing', 'oauth')); -if (! $user->admin) accessforbidden(); +if (!$user->admin) accessforbidden(); $action = GETPOST('action', 'alpha'); $mode = GETPOST('mode', 'alpha'); -$value = GETPOST('value', 'alpha', 0, null, null, 1); // The value may be __google__docs so we force disable of replace +$value = GETPOST('value', 'alpha', 0, null, null, 1); // The value may be __google__docs so we force disable of replace $varname = GETPOST('varname', 'alpha'); $driver = GETPOST('driver', 'alpha'); -if (! empty($driver)) $langs->load($driver); +if (!empty($driver)) $langs->load($driver); -if (!$mode) $mode='config'; +if (!$mode) $mode = 'config'; $OAUTH_SERVICENAME_GOOGLE = 'Google'; @@ -61,15 +61,15 @@ if (($mode == 'test' || $mode == 'setup') && empty($driver)) if ($action == 'setconst' && $user->admin) { - $error=0; + $error = 0; $db->begin(); foreach ($_POST['setupdriver'] as $setupconst) { //print '
    '.print_r($setupconst, true).'
    '; - $result=dolibarr_set_const($db, $setupconst['varname'], $setupconst['value'], 'chaine', 0, '', $conf->entity); - if (! $result > 0) $error++; + $result = dolibarr_set_const($db, $setupconst['varname'], $setupconst['value'], 'chaine', 0, '', $conf->entity); + if (!$result > 0) $error++; } - if (! $error) + if (!$error) { $db->commit(); setEventMessages($langs->trans("SetupSaved"), null); @@ -79,17 +79,17 @@ if ($action == 'setconst' && $user->admin) $db->rollback(); dol_print_error($db); } - $action=''; + $action = ''; } if ($action == 'setvalue' && $user->admin) { $db->begin(); - $result=dolibarr_set_const($db, $varname, $value, 'chaine', 0, '', $conf->entity); - if (! $result > 0) $error++; + $result = dolibarr_set_const($db, $varname, $value, 'chaine', 0, '', $conf->entity); + if (!$result > 0) $error++; - if (! $error) + if (!$error) { $db->commit(); setEventMessages($langs->trans("SetupSaved"), null); @@ -111,7 +111,7 @@ $form = new Form($db); llxHeader('', $langs->trans("PrintingSetup")); -$linkback=''.$langs->trans("BackToModuleList").''; +$linkback = ''.$langs->trans("BackToModuleList").''; print load_fiche_titre($langs->trans("PrintingSetup"), $linkback, 'title_setup'); $head = printingAdminPrepareHead($mode); @@ -126,38 +126,38 @@ if ($mode == 'setup' && $user->admin) print $langs->trans("PrintingDriverDesc".$driver)."

    \n"; - print '
    '."\n"; + print '
    '."\n"; print ''; print ''; print ''; print ''; print "\n"; - $submit_enabled=0; + $submit_enabled = 0; - if (! empty($driver)) { + if (!empty($driver)) { require_once DOL_DOCUMENT_ROOT.'/core/modules/printing/'.$driver.'.modules.php'; $classname = 'printing_'.$driver; $langs->load($driver); $printer = new $classname($db); - $i=0; - $submit_enabled=0; + $i = 0; + $submit_enabled = 0; foreach ($printer->conf as $key) { switch ($key['type']) { case "text": case "password": print ''; - print ''.$langs->trans($key['varname']).''; - print ''; + print ''; - print ''; + print ''; print ''."\n"; break; case "info": // Google Api setup or Google OAuth Token print ''; - print ''; + print ''; if ($key['varname'] == 'PRINTGCP_TOKEN_ACCESS') { print $langs->trans("IsTokenGenerated"); @@ -173,7 +173,7 @@ if ($mode == 'setup' && $user->admin) if ($key['varname'] == 'PRINTGCP_TOKEN_ACCESS') { // Delete remote tokens - if (! empty($key['delete'])) print ''.$langs->trans('DeleteAccess').'

    '; + if (!empty($key['delete'])) print ''.$langs->trans('DeleteAccess').'

    '; // Request remote token print ''.$langs->trans('RequestAccess').'

    '; // Check remote access @@ -183,7 +183,7 @@ if ($mode == 'setup' && $user->admin) print '
    '."\n"; break; case "submit": - if ($key['enabled']) $submit_enabled=1; + if ($key['enabled']) $submit_enabled = 1; break; } $i++; @@ -194,14 +194,14 @@ if ($mode == 'setup' && $user->admin) print ''; print ''; print '
    '.$langs->trans("Parameters").''.$langs->trans("Value").' 
    '.$langs->trans($key['varname']).' '.($key['example']!=''?$langs->trans("Example").' : '.$key['example']:'').' '.($key['example'] != '' ? $langs->trans("Example").' : '.$key['example'] : '').'
    '.$langs->trans("Token").''; - $tokenobj=null; + $tokenobj = null; // Dolibarr storage $storage = new DoliStorage($db, $conf); try { $tokenobj = $storage->retrieveAccessToken($OAUTH_SERVICENAME_GOOGLE); } - catch(Exception $e) + catch (Exception $e) { // Return an error if token not found } @@ -228,7 +228,7 @@ if ($mode == 'setup' && $user->admin) dol_fiche_end(); - if (! empty($driver)) + if (!empty($driver)) { if ($submit_enabled) { print '
    '; @@ -243,7 +243,7 @@ if ($mode == 'config' && $user->admin) print $langs->trans("PrintingDesc")."

    \n"; - print ''."\n"; + print '
    '."\n"; print ''; print ''; @@ -264,7 +264,7 @@ if ($mode == 'config' && $user->admin) print ''; print ''; print '
    '.$langs->trans("Description").'
    '.img_picto('', $printer->picto).' '.$langs->trans($printer->desc).''; - if (! empty($conf->use_javascript_ajax)) + if (!empty($conf->use_javascript_ajax)) { print ajax_constantonoff($printer->active); } @@ -295,8 +295,8 @@ if ($mode == 'test' && $user->admin) print $langs->trans('PrintTestDesc'.$driver)."

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

    \n"; - print '
    '; + print '
    '; print ''; print ''; print ''; @@ -340,7 +340,7 @@ if ($mode == 'userconf' && $user->admin) print "\n"; $sql = 'SELECT p.rowid, p.printer_name, p.printer_location, p.printer_id, p.copy, p.module, p.driver, p.userid, u.login FROM '.MAIN_DB_PREFIX.'printing as p, '.MAIN_DB_PREFIX.'user as u WHERE p.userid=u.rowid'; $resql = $db->query($sql); - while ($row=$db->fetch_array($resql)) { + while ($row = $db->fetch_array($resql)) { print ''; print ''; print ''; diff --git a/htdocs/product/admin/dynamic_prices.php b/htdocs/product/admin/dynamic_prices.php index 14bd92ca4ee..98bfc5a304c 100644 --- a/htdocs/product/admin/dynamic_prices.php +++ b/htdocs/product/admin/dynamic_prices.php @@ -161,7 +161,7 @@ if ($action != 'create_updater' && $action != 'edit_updater') { print load_fiche_titre($langs->trans("GlobalVariables"), '', ''); - print '
    '.$langs->trans("User").''.$langs->trans("PrintModule").'
    '.$row['login'].''.$row['module'].'
    '; + print '
    '; print ''; print ''; print ''; @@ -242,7 +242,7 @@ if ($action != 'create_variable' && $action != 'edit_variable') { print load_fiche_titre($langs->trans("GlobalVariableUpdaters"), '', ''); - print '
    '.$langs->trans("Variable").''.$langs->trans("Description").'
    '; + print '
    '; print ''; print ''; print ''; diff --git a/htdocs/product/admin/product.php b/htdocs/product/admin/product.php index d6f636bf4c9..deafff12cfe 100644 --- a/htdocs/product/admin/product.php +++ b/htdocs/product/admin/product.php @@ -300,7 +300,7 @@ $dirmodels=array_merge(array('/'), (array) $conf->modules_parts['models']); print load_fiche_titre($langs->trans("ProductCodeChecker"), '', ''); -print '
    '.$langs->trans("VariableToUpdate").''.$langs->trans("Description").'
    '."\n"; +print '
    '."\n"; print ''."\n"; print ' '; print ' '; @@ -401,7 +401,7 @@ print '
    '; print load_fiche_titre($langs->trans("ProductDocumentTemplates"), '', ''); -print '
    '.$langs->trans("Name").''.$langs->trans("Description").'
    '; +print '
    '; print ''; print ''; print ''; @@ -537,7 +537,7 @@ print ''; print ''; print ''; -print '
    '.$langs->trans("Name").''.$langs->trans("Description").'
    '; +print '
    '; print ''; print ''."\n"; print ''."\n"; diff --git a/htdocs/product/admin/product_tools.php b/htdocs/product/admin/product_tools.php index 4210a3a560a..ccdd666bc30 100644 --- a/htdocs/product/admin/product_tools.php +++ b/htdocs/product/admin/product_tools.php @@ -296,7 +296,7 @@ else print ''; print ''; - print '
    '.$langs->trans("Parameters").''.$langs->trans("Value").'
    '; + print '
    '; print ''; print ''."\n"; print ''."\n"; diff --git a/htdocs/product/agenda.php b/htdocs/product/agenda.php index c6585f5e590..33eec8c5375 100644 --- a/htdocs/product/agenda.php +++ b/htdocs/product/agenda.php @@ -61,8 +61,8 @@ if (empty($page) || $page == -1) { $page = 0; } // If $page is not defined, $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('agendathirdparty')); @@ -72,14 +72,14 @@ $hookmanager->initHooks(array('agendathirdparty')); * Actions */ -$parameters=array('id'=>$id); -$reshook=$hookmanager->executeHooks('doActions', $parameters, $object, $action); // Note that $action and $object may have been modified by some hooks +$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 (empty($reshook)) { // Cancel - if (GETPOST('cancel', 'alpha') && ! empty($backtopage)) + if (GETPOST('cancel', 'alpha') && !empty($backtopage)) { header("Location: ".$backtopage); exit; @@ -88,8 +88,8 @@ if (empty($reshook)) // Purge search criteria if (GETPOST('button_removefilter_x', 'alpha') || GETPOST('button_removefilter.x', 'alpha') || GETPOST('button_removefilter', 'alpha')) // All tests are required to be compatible with all browsers { - $actioncode=''; - $search_agenda_label=''; + $actioncode = ''; + $search_agenda_label = ''; } } @@ -151,16 +151,16 @@ if ($id > 0 || $ref) // Actions buttons - $objproduct=$object; - $objcon=new stdClass(); + $objproduct = $object; + $objcon = new stdClass(); - $out=''; - $permok=$user->rights->agenda->myactions->create; - if ((! empty($objproduct->id) || ! empty($objcon->id)) && $permok) + $out = ''; + $permok = $user->rights->agenda->myactions->create; + if ((!empty($objproduct->id) || !empty($objcon->id)) && $permok) { //$out.='trans("AddAnAction"),'filenew'); //$out.=""; diff --git a/htdocs/product/ajax/products.php b/htdocs/product/ajax/products.php index 4f6eea5b903..8a2d643189b 100644 --- a/htdocs/product/ajax/products.php +++ b/htdocs/product/ajax/products.php @@ -22,13 +22,13 @@ * \brief File to return Ajax response on product list request */ -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('NOREQUIRESOC')) define('NOREQUIRESOC', '1'); -if (! defined('NOCSRFCHECK')) define('NOCSRFCHECK', '1'); -if (empty($_GET['keysearch']) && ! defined('NOREQUIREHTML')) define('NOREQUIREHTML', '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 (!defined('NOREQUIRESOC')) define('NOREQUIRESOC', '1'); +if (!defined('NOCSRFCHECK')) define('NOCSRFCHECK', '1'); +if (empty($_GET['keysearch']) && !defined('NOREQUIREHTML')) define('NOREQUIREHTML', '1'); require '../../main.inc.php'; @@ -57,9 +57,9 @@ $hidepriceinlabel = GETPOST('hidepriceinlabel', 'int'); dol_syslog(join(',', $_GET)); // print_r($_GET); -if (! empty($action) && $action == 'fetch' && ! empty($id)) +if (!empty($action) && $action == 'fetch' && !empty($id)) { - require_once DOL_DOCUMENT_ROOT . '/product/class/product.class.php'; + require_once DOL_DOCUMENT_ROOT.'/product/class/product.class.php'; $outjson = array(); @@ -77,11 +77,11 @@ if (! empty($action) && $action == 'fetch' && ! empty($id)) $found = false; // Price by qty - if (! empty($price_by_qty_rowid) && $price_by_qty_rowid >= 1 && (! empty($conf->global->PRODUIT_CUSTOMER_PRICES_BY_QTY))) // If we need a particular price related to qty + if (!empty($price_by_qty_rowid) && $price_by_qty_rowid >= 1 && (!empty($conf->global->PRODUIT_CUSTOMER_PRICES_BY_QTY))) // If we need a particular price related to qty { $sql = "SELECT price, unitprice, quantity, remise_percent"; - $sql .= " FROM " . MAIN_DB_PREFIX . "product_price_by_qty "; - $sql .= " WHERE rowid=" . $price_by_qty_rowid . ""; + $sql .= " FROM ".MAIN_DB_PREFIX."product_price_by_qty "; + $sql .= " WHERE rowid=".$price_by_qty_rowid.""; $result = $db->query($sql); if ($result) { @@ -99,14 +99,14 @@ if (! empty($action) && $action == 'fetch' && ! empty($id)) } // Multiprice - if (! $found && isset($price_level) && $price_level >= 1 && (! empty($conf->global->PRODUIT_MULTIPRICES))) // If we need a particular price + if (!$found && isset($price_level) && $price_level >= 1 && (!empty($conf->global->PRODUIT_MULTIPRICES))) // If we need a particular price // level (from 1 to 6) { $sql = "SELECT price, price_ttc, price_base_type, tva_tx"; - $sql .= " FROM " . MAIN_DB_PREFIX . "product_price "; - $sql .= " WHERE fk_product='" . $id . "'"; - $sql .= " AND entity IN (" . getEntity('productprice') . ")"; - $sql .= " AND price_level=" . $price_level; + $sql .= " FROM ".MAIN_DB_PREFIX."product_price "; + $sql .= " WHERE fk_product='".$id."'"; + $sql .= " AND entity IN (".getEntity('productprice').")"; + $sql .= " AND price_level=".$price_level; $sql .= " ORDER BY date_price"; $sql .= " DESC LIMIT 1"; @@ -124,12 +124,12 @@ if (! empty($action) && $action == 'fetch' && ! empty($id)) } // Price by customer - if (! empty($conf->global->PRODUIT_CUSTOMER_PRICES) && ! empty($socid)) { - require_once DOL_DOCUMENT_ROOT . '/product/class/productcustomerprice.class.php'; + if (!empty($conf->global->PRODUIT_CUSTOMER_PRICES) && !empty($socid)) { + require_once DOL_DOCUMENT_ROOT.'/product/class/productcustomerprice.class.php'; $prodcustprice = new Productcustomerprice($db); - $filter = array('t.fk_product' => $object->id,'t.fk_soc' => $socid); + $filter = array('t.fk_product' => $object->id, 't.fk_soc' => $socid); $result = $prodcustprice->fetch_all('', '', 0, 0, $filter); if ($result) { @@ -143,21 +143,21 @@ if (! empty($action) && $action == 'fetch' && ! empty($id)) } } - if (! $found) { + if (!$found) { $outprice_ht = price($object->price); $outprice_ttc = price($object->price_ttc); $outpricebasetype = $object->price_base_type; $outtva_tx = $object->tva_tx; } - $outjson = array('ref' => $outref,'label' => $outlabel,'desc' => $outdesc,'type' => $outtype,'price_ht' => $outprice_ht,'price_ttc' => $outprice_ttc,'pricebasetype' => $outpricebasetype,'tva_tx' => $outtva_tx,'qty' => $outqty,'discount' => $outdiscount); + $outjson = array('ref' => $outref, 'label' => $outlabel, 'desc' => $outdesc, 'type' => $outtype, 'price_ht' => $outprice_ht, 'price_ttc' => $outprice_ttc, 'pricebasetype' => $outpricebasetype, 'tva_tx' => $outtva_tx, 'qty' => $outqty, 'discount' => $outdiscount); } echo json_encode($outjson); } else { - require_once DOL_DOCUMENT_ROOT . '/core/class/html.form.class.php'; + require_once DOL_DOCUMENT_ROOT.'/core/class/html.form.class.php'; $langs->load("products"); $langs->load("main"); @@ -170,19 +170,19 @@ else return; } - $match = preg_grep('/(' . $htmlname . '[0-9]+)/', array_keys($_GET)); + $match = preg_grep('/('.$htmlname.'[0-9]+)/', array_keys($_GET)); sort($match); - $idprod = (! empty($match[0]) ? $match[0] : ''); + $idprod = (!empty($match[0]) ? $match[0] : ''); - if (GETPOST($htmlname, 'alpha') == '' && (! $idprod || ! GETPOST($idprod, 'alpha'))) + if (GETPOST($htmlname, 'alpha') == '' && (!$idprod || !GETPOST($idprod, 'alpha'))) { print json_encode(array()); return; } // When used from jQuery, the search term is added as GET param "term". - $searchkey = (($idprod && GETPOST($idprod, 'alpha')) ? GETPOST($idprod, 'alpha') : (GETPOST($htmlname, 'alpha') ? GETPOST($htmlname, 'alpha') : '')); + $searchkey = (($idprod && GETPOST($idprod, 'alpha')) ? GETPOST($idprod, 'alpha') : (GETPOST($htmlname, 'alpha') ? GETPOST($htmlname, 'alpha') : '')); $form = new Form($db); if (empty($mode) || $mode == 1) { // mode=1: customer diff --git a/htdocs/product/canvas/product/tpl/card_create.tpl.php b/htdocs/product/canvas/product/tpl/card_create.tpl.php index b12a0d41370..99ddd39d49b 100644 --- a/htdocs/product/canvas/product/tpl/card_create.tpl.php +++ b/htdocs/product/canvas/product/tpl/card_create.tpl.php @@ -16,16 +16,16 @@ */ // 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; } -$object=$GLOBALS['object']; +$object = $GLOBALS['object']; -$statutarray=array('1' => $langs->trans("OnSell"), '0' => $langs->trans("NotOnSell")); +$statutarray = array('1' => $langs->trans("OnSell"), '0' => $langs->trans("NotOnSell")); ?> @@ -35,7 +35,7 @@ print load_fiche_titre($langs->trans("NewProduct"), '', 'products'); dol_fiche_head(''); ?> -error)?'':$object->error), $object->errors); ?> +error) ? '' : $object->error), $object->errors); ?> @@ -71,7 +71,7 @@ dol_fiche_head(''); -stock->enabled)) { ?> +stock->enabled)) { ?> @@ -108,7 +108,7 @@ dol_fiche_head('');
    -global->PRODUIT_MULTIPRICES) { ?> +global->PRODUIT_MULTIPRICES) { ?>
    '.$langs->trans("Parameters").''.$langs->trans("Value").'selectarray('statut_buy', $statutarray, $object->status_buy); ?>
    trans("StockLimit"); ?>
    diff --git a/htdocs/product/canvas/service/tpl/card_create.tpl.php b/htdocs/product/canvas/service/tpl/card_create.tpl.php index d51e1541278..26daca173a4 100644 --- a/htdocs/product/canvas/service/tpl/card_create.tpl.php +++ b/htdocs/product/canvas/service/tpl/card_create.tpl.php @@ -16,16 +16,16 @@ */ // 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; } -$object=$GLOBALS['object']; +$object = $GLOBALS['object']; -$statutarray=array('1' => $langs->trans("OnSell"), '0' => $langs->trans("NotOnSell")); +$statutarray = array('1' => $langs->trans("OnSell"), '0' => $langs->trans("NotOnSell")); ?> @@ -80,7 +80,7 @@ dol_fiche_head('');
    -global->PRODUIT_MULTIPRICES) { ?> +global->PRODUIT_MULTIPRICES) { ?>
    trans("SellingPrice"); ?>
    diff --git a/htdocs/product/card.php b/htdocs/product/card.php index cc8d4e6bc89..8fccf28c472 100644 --- a/htdocs/product/card.php +++ b/htdocs/product/card.php @@ -51,62 +51,62 @@ require_once DOL_DOCUMENT_ROOT.'/core/lib/company.lib.php'; require_once DOL_DOCUMENT_ROOT.'/categories/class/categorie.class.php'; require_once DOL_DOCUMENT_ROOT.'/core/modules/product/modules_product.class.php'; -if (! empty($conf->propal->enabled)) require_once DOL_DOCUMENT_ROOT.'/comm/propal/class/propal.class.php'; -if (! empty($conf->facture->enabled)) require_once DOL_DOCUMENT_ROOT.'/compta/facture/class/facture.class.php'; -if (! empty($conf->commande->enabled)) require_once DOL_DOCUMENT_ROOT.'/commande/class/commande.class.php'; -if (! empty($conf->accounting->enabled)) require_once DOL_DOCUMENT_ROOT.'/core/lib/accounting.lib.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->propal->enabled)) require_once DOL_DOCUMENT_ROOT.'/comm/propal/class/propal.class.php'; +if (!empty($conf->facture->enabled)) require_once DOL_DOCUMENT_ROOT.'/compta/facture/class/facture.class.php'; +if (!empty($conf->commande->enabled)) require_once DOL_DOCUMENT_ROOT.'/commande/class/commande.class.php'; +if (!empty($conf->accounting->enabled)) require_once DOL_DOCUMENT_ROOT.'/core/lib/accounting.lib.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'; // Load translation files required by the page $langs->loadLangs(array('products', 'other')); -if (! empty($conf->stock->enabled)) $langs->load("stocks"); -if (! empty($conf->facture->enabled)) $langs->load("bills"); -if (! empty($conf->productbatch->enabled)) $langs->load("productbatch"); +if (!empty($conf->stock->enabled)) $langs->load("stocks"); +if (!empty($conf->facture->enabled)) $langs->load("bills"); +if (!empty($conf->productbatch->enabled)) $langs->load("productbatch"); -$mesg=''; $error=0; $errors=array(); +$mesg = ''; $error = 0; $errors = array(); -$refalreadyexists=0; +$refalreadyexists = 0; -$id=GETPOST('id', 'int'); -$ref=GETPOST('ref', 'alpha'); -$type=GETPOST('type', 'int'); -$action=(GETPOST('action', 'alpha') ? GETPOST('action', 'alpha') : 'view'); -$cancel=GETPOST('cancel', 'alpha'); -$backtopage = GETPOST('backtopage', 'alpha'); -$confirm=GETPOST('confirm', 'alpha'); -$socid=GETPOST('socid', 'int'); +$id = GETPOST('id', 'int'); +$ref = GETPOST('ref', 'alpha'); +$type = GETPOST('type', 'int'); +$action = (GETPOST('action', 'alpha') ? GETPOST('action', 'alpha') : 'view'); +$cancel = GETPOST('cancel', 'alpha'); +$backtopage = GETPOST('backtopage', 'alpha'); +$confirm = GETPOST('confirm', 'alpha'); +$socid = GETPOST('socid', 'int'); $duration_value = GETPOST('duration_value', 'int'); $duration_unit = GETPOST('duration_unit', 'alpha'); -if (! empty($user->socid)) $socid=$user->socid; +if (!empty($user->socid)) $socid = $user->socid; $object = new Product($db); -$object->type = $type; // so test later to fill $usercancxxx is correct +$object->type = $type; // so test later to fill $usercancxxx is correct $extrafields = new ExtraFields($db); // fetch optionals attributes and labels $extrafields->fetch_name_optionals_label($object->table_element); -if ($id > 0 || ! empty($ref)) +if ($id > 0 || !empty($ref)) { $result = $object->fetch($id, $ref); - if (! empty($conf->product->enabled)) $upload_dir = $conf->product->multidir_output[$object->entity].'/'.get_exdir(0, 0, 0, 0, $object, 'product').dol_sanitizeFileName($object->ref); - elseif (! empty($conf->service->enabled)) $upload_dir = $conf->service->multidir_output[$object->entity].'/'.get_exdir(0, 0, 0, 0, $object, 'product').dol_sanitizeFileName($object->ref); + if (!empty($conf->product->enabled)) $upload_dir = $conf->product->multidir_output[$object->entity].'/'.get_exdir(0, 0, 0, 0, $object, 'product').dol_sanitizeFileName($object->ref); + elseif (!empty($conf->service->enabled)) $upload_dir = $conf->service->multidir_output[$object->entity].'/'.get_exdir(0, 0, 0, 0, $object, 'product').dol_sanitizeFileName($object->ref); - if (! empty($conf->global->PRODUCT_USE_OLD_PATH_FOR_PHOTO)) // For backward compatiblity, we scan also old dirs + if (!empty($conf->global->PRODUCT_USE_OLD_PATH_FOR_PHOTO)) // For backward compatiblity, we scan also old dirs { - if (! empty($conf->product->enabled)) $upload_dirold = $conf->product->multidir_output[$object->entity].'/'.substr(substr("000".$object->id, -2), 1, 1).'/'.substr(substr("000".$object->id, -2), 0, 1).'/'.$object->id."/photos"; + if (!empty($conf->product->enabled)) $upload_dirold = $conf->product->multidir_output[$object->entity].'/'.substr(substr("000".$object->id, -2), 1, 1).'/'.substr(substr("000".$object->id, -2), 0, 1).'/'.$object->id."/photos"; else $upload_dirold = $conf->service->multidir_output[$object->entity].'/'.substr(substr("000".$object->id, -2), 1, 1).'/'.substr(substr("000".$object->id, -2), 0, 1).'/'.$object->id."/photos"; } } -$modulepart='product'; +$modulepart = 'product'; // Get object canvas (By default, this is not defined, so standard usage of dolibarr) -$canvas = !empty($object->canvas)?$object->canvas:GETPOST("canvas"); -$objcanvas=null; -if (! empty($canvas)) +$canvas = !empty($object->canvas) ? $object->canvas : GETPOST("canvas"); +$objcanvas = null; +if (!empty($canvas)) { require_once DOL_DOCUMENT_ROOT.'/core/class/canvas.class.php'; $objcanvas = new Canvas($db, $action); @@ -114,12 +114,12 @@ if (! empty($canvas)) } // Security check -$fieldvalue = (! empty($id) ? $id : (! empty($ref) ? $ref : '')); -$fieldtype = (! empty($id) ? 'rowid' : 'ref'); -$result=restrictedArea($user, 'produit|service', $fieldvalue, 'product&product', '', '', $fieldtype); +$fieldvalue = (!empty($id) ? $id : (!empty($ref) ? $ref : '')); +$fieldtype = (!empty($id) ? 'rowid' : 'ref'); +$result = restrictedArea($user, 'produit|service', $fieldvalue, 'product&product', '', '', $fieldtype); // Initialize technical object to manage hooks of page. Note that conf->hooks_modules contains array of hook context -$hookmanager->initHooks(array('productcard','globalcard')); +$hookmanager->initHooks(array('productcard', 'globalcard')); @@ -132,11 +132,11 @@ if ($cancel) $action = ''; $usercanread = (($object->type == Product::TYPE_PRODUCT && $user->rights->produit->lire) || ($object->type == Product::TYPE_SERVICE && $user->rights->service->lire)); $usercancreate = (($object->type == Product::TYPE_PRODUCT && $user->rights->produit->creer) || ($object->type == Product::TYPE_SERVICE && $user->rights->service->creer)); $usercandelete = (($object->type == Product::TYPE_PRODUCT && $user->rights->produit->supprimer) || ($object->type == Product::TYPE_SERVICE && $user->rights->service->supprimer)); -$createbarcode=empty($conf->barcode->enabled)?0:1; -if (! empty($conf->global->MAIN_USE_ADVANCED_PERMS) && empty($user->rights->barcode->creer_advance)) $createbarcode=0; +$createbarcode = empty($conf->barcode->enabled) ? 0 : 1; +if (!empty($conf->global->MAIN_USE_ADVANCED_PERMS) && empty($user->rights->barcode->creer_advance)) $createbarcode = 0; -$parameters=array('id'=>$id, 'ref'=>$ref, 'objcanvas'=>$objcanvas); -$reshook=$hookmanager->executeHooks('doActions', $parameters, $object, $action); // Note that $action and $object may have been modified by some hooks +$parameters = array('id'=>$id, 'ref'=>$ref, '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 (empty($reshook)) @@ -157,7 +157,7 @@ if (empty($reshook)) include DOL_DOCUMENT_ROOT.'/core/actions_printing.inc.php'; // Barcode type - if ($action == 'setfk_barcode_type' && $createbarcode) + if ($action == 'setfk_barcode_type' && $createbarcode) { $result = $object->setValueFrom('fk_barcode_type', GETPOST('fk_barcode_type'), '', null, 'text', '', $user, 'PRODUCT_MODIFY'); header("Location: ".$_SERVER['PHP_SELF']."?id=".$object->id); @@ -165,9 +165,9 @@ if (empty($reshook)) } // Barcode value - if ($action == 'setbarcode' && $createbarcode) + if ($action == 'setbarcode' && $createbarcode) { - $result=$object->check_barcode(GETPOST('barcode'), GETPOST('barcode_type_code')); + $result = $object->check_barcode(GETPOST('barcode'), GETPOST('barcode_type_code')); if ($result >= 0) { @@ -191,9 +191,9 @@ if (empty($reshook)) // Add a product or service if ($action == 'add' && $usercancreate) { - $error=0; + $error = 0; - if (! GETPOST('label')) + if (!GETPOST('label')) { setEventMessages($langs->trans('ErrorFieldRequired', $langs->transnoentities('Label')), null, 'errors'); $action = "create"; @@ -205,14 +205,14 @@ if (empty($reshook)) $action = "create"; $error++; } - if (! empty($duration_value) && empty($duration_unit)) + if (!empty($duration_value) && empty($duration_unit)) { setEventMessages($langs->trans('ErrorFieldRequired', $langs->transnoentities('Unit')), null, 'errors'); $action = "create"; $error++; } - if (! $error) + if (!$error) { $units = GETPOST('units', 'int'); @@ -229,25 +229,25 @@ if (empty($reshook)) else $object->price_min = GETPOST('price_min'); - $tva_tx_txt = GETPOST('tva_tx', 'alpha'); // tva_tx can be '8.5' or '8.5*' or '8.5 (XXX)' or '8.5* (XXX)' + $tva_tx_txt = GETPOST('tva_tx', 'alpha'); // tva_tx can be '8.5' or '8.5*' or '8.5 (XXX)' or '8.5* (XXX)' // We must define tva_tx, npr and local taxes $vatratecode = ''; - $tva_tx = preg_replace('/[^0-9\.].*$/', '', $tva_tx_txt); // keep remove all after the numbers and dot + $tva_tx = preg_replace('/[^0-9\.].*$/', '', $tva_tx_txt); // keep remove all after the numbers and dot $npr = preg_match('/\*/', $tva_tx_txt) ? 1 : 0; $localtax1 = 0; $localtax2 = 0; $localtax1_type = '0'; $localtax2_type = '0'; // If value contains the unique code of vat line (new recommanded method), we use it to find npr and local taxes if (preg_match('/\((.*)\)/', $tva_tx_txt, $reg)) { // We look into database using code (we can't use get_localtax() because it depends on buyer that is not known). Same in update price. - $vatratecode=$reg[1]; + $vatratecode = $reg[1]; // Get record from code $sql = "SELECT t.rowid, t.code, t.recuperableonly, t.localtax1, t.localtax2, t.localtax1_type, t.localtax2_type"; - $sql.= " FROM ".MAIN_DB_PREFIX."c_tva as t, ".MAIN_DB_PREFIX."c_country as c"; - $sql.= " WHERE t.fk_pays = c.rowid AND c.code = '".$mysoc->country_code."'"; - $sql.= " AND t.taux = ".((float) $tva_tx)." AND t.active = 1"; - $sql.= " AND t.code ='".$vatratecode."'"; - $resql=$db->query($sql); + $sql .= " FROM ".MAIN_DB_PREFIX."c_tva as t, ".MAIN_DB_PREFIX."c_country as c"; + $sql .= " WHERE t.fk_pays = c.rowid AND c.code = '".$mysoc->country_code."'"; + $sql .= " AND t.taux = ".((float) $tva_tx)." AND t.active = 1"; + $sql .= " AND t.code ='".$vatratecode."'"; + $resql = $db->query($sql); if ($resql) { $obj = $db->fetch_object($resql); @@ -270,19 +270,19 @@ if (empty($reshook)) $object->type = $type; $object->status = GETPOST('statut'); $object->status_buy = GETPOST('statut_buy'); - $object->status_batch = GETPOST('status_batch'); + $object->status_batch = GETPOST('status_batch'); $object->barcode_type = GETPOST('fk_barcode_type'); - $object->barcode = GETPOST('barcode'); + $object->barcode = GETPOST('barcode'); // Set barcode_type_xxx from barcode_type id - $stdobject=new GenericObject($db); - $stdobject->element='product'; - $stdobject->barcode_type=GETPOST('fk_barcode_type'); - $result=$stdobject->fetch_barcode(); + $stdobject = new GenericObject($db); + $stdobject->element = 'product'; + $stdobject->barcode_type = GETPOST('fk_barcode_type'); + $result = $stdobject->fetch_barcode(); if ($result < 0) { $error++; - $mesg='Failed to get bar code type information '; + $mesg = 'Failed to get bar code type information '; setEventMessages($mesg.$stdobject->error, $mesg.$stdobject->errors, 'errors'); } $object->barcode_type_code = $stdobject->barcode_type_code; @@ -290,36 +290,36 @@ if (empty($reshook)) $object->barcode_type_label = $stdobject->barcode_type_label; $object->description = dol_htmlcleanlastbr(GETPOST('desc', 'none')); - $object->url = GETPOST('url'); + $object->url = GETPOST('url'); $object->note_private = dol_htmlcleanlastbr(GETPOST('note_private', 'none')); - $object->note = $object->note_private; // deprecated + $object->note = $object->note_private; // deprecated $object->customcode = GETPOST('customcode', 'alpha'); $object->country_id = GETPOST('country_id', 'int'); $object->duration_value = $duration_value; $object->duration_unit = $duration_unit; $object->fk_default_warehouse = GETPOST('fk_default_warehouse'); - $object->seuil_stock_alerte = GETPOST('seuil_stock_alerte')?GETPOST('seuil_stock_alerte'):0; - $object->desiredstock = GETPOST('desiredstock')?GETPOST('desiredstock'):0; + $object->seuil_stock_alerte = GETPOST('seuil_stock_alerte') ?GETPOST('seuil_stock_alerte') : 0; + $object->desiredstock = GETPOST('desiredstock') ?GETPOST('desiredstock') : 0; $object->canvas = GETPOST('canvas'); $object->net_measure = GETPOST('net_measure'); - $object->net_measure_units = GETPOST('net_measure_units'); // This is not the fk_unit but the power of unit + $object->net_measure_units = GETPOST('net_measure_units'); // This is not the fk_unit but the power of unit $object->weight = GETPOST('weight'); - $object->weight_units = GETPOST('weight_units'); // This is not the fk_unit but the power of unit + $object->weight_units = GETPOST('weight_units'); // This is not the fk_unit but the power of unit $object->length = GETPOST('size'); - $object->length_units = GETPOST('size_units'); // This is not the fk_unit but the power of unit - $object->width = GETPOST('sizewidth'); + $object->length_units = GETPOST('size_units'); // This is not the fk_unit but the power of unit + $object->width = GETPOST('sizewidth'); $object->height = GETPOST('sizeheight'); $object->surface = GETPOST('surface'); - $object->surface_units = GETPOST('surface_units'); // This is not the fk_unit but the power of unit + $object->surface_units = GETPOST('surface_units'); // This is not the fk_unit but the power of unit $object->volume = GETPOST('volume'); - $object->volume_units = GETPOST('volume_units'); // This is not the fk_unit but the power of unit + $object->volume_units = GETPOST('volume_units'); // This is not the fk_unit but the power of unit $object->finished = GETPOST('finished', 'alpha'); - $object->fk_unit = GETPOST('units', 'alpha'); // This is the fk_unit of sale + $object->fk_unit = GETPOST('units', 'alpha'); // This is the fk_unit of sale - $accountancy_code_sell = GETPOST('accountancy_code_sell', 'alpha'); - $accountancy_code_sell_intra = GETPOST('accountancy_code_sell_intra', 'alpha'); - $accountancy_code_sell_export = GETPOST('accountancy_code_sell_export', 'alpha'); - $accountancy_code_buy = GETPOST('accountancy_code_buy', 'alpha'); + $accountancy_code_sell = GETPOST('accountancy_code_sell', 'alpha'); + $accountancy_code_sell_intra = GETPOST('accountancy_code_sell_intra', 'alpha'); + $accountancy_code_sell_export = GETPOST('accountancy_code_sell_export', 'alpha'); + $accountancy_code_buy = GETPOST('accountancy_code_buy', 'alpha'); if ($accountancy_code_sell <= 0) { $object->accountancy_code_sell = ''; } else { $object->accountancy_code_sell = $accountancy_code_sell; } if ($accountancy_code_sell_intra <= 0) { $object->accountancy_code_sell_intra = ''; } else { $object->accountancy_code_sell_intra = $accountancy_code_sell_intra; } @@ -327,9 +327,9 @@ if (empty($reshook)) if ($accountancy_code_buy <= 0) { $object->accountancy_code_buy = ''; } else { $object->accountancy_code_buy = $accountancy_code_buy; } // MultiPrix - if (! empty($conf->global->PRODUIT_MULTIPRICES)) + if (!empty($conf->global->PRODUIT_MULTIPRICES)) { - for($i=2;$i<=$conf->global->PRODUIT_MULTIPRICES_LIMIT;$i++) + for ($i = 2; $i <= $conf->global->PRODUIT_MULTIPRICES_LIMIT; $i++) { if (isset($_POST["price_".$i])) { @@ -347,7 +347,7 @@ if (empty($reshook)) $ret = $extrafields->setOptionalsFromPost(null, $object); if ($ret < 0) $error++; - if (! $error) + if (!$error) { $id = $object->create($user); } @@ -358,10 +358,10 @@ if (empty($reshook)) $categories = GETPOST('categories', 'array'); $object->setCategories($categories); - if (! empty($backtopage)) + if (!empty($backtopage)) { - $backtopage = preg_replace('/--IDFORBACKTOPAGE--/', $object->id, $backtopage); // New method to autoselect project after a New on another form object creation - if (preg_match('/\?/', $backtopage)) $backtopage.='&socid='.$object->id; // Old method + $backtopage = preg_replace('/--IDFORBACKTOPAGE--/', $object->id, $backtopage); // New method to autoselect project after a New on another form object creation + if (preg_match('/\?/', $backtopage)) $backtopage .= '&socid='.$object->id; // Old method header("Location: ".$backtopage); exit; } @@ -391,22 +391,22 @@ if (empty($reshook)) { if ($object->id > 0) { - $object->oldcopy= clone $object; + $object->oldcopy = clone $object; $object->ref = $ref; $object->label = GETPOST('label'); $object->description = dol_htmlcleanlastbr(GETPOST('desc', 'none')); - $object->url = GETPOST('url'); - if (! empty($conf->global->MAIN_DISABLE_NOTES_TAB)) + $object->url = GETPOST('url'); + if (!empty($conf->global->MAIN_DISABLE_NOTES_TAB)) { - $object->note_private = dol_htmlcleanlastbr(GETPOST('note_private', 'none')); - $object->note = $object->note_private; + $object->note_private = dol_htmlcleanlastbr(GETPOST('note_private', 'none')); + $object->note = $object->note_private; } $object->customcode = GETPOST('customcode', 'alpha'); $object->country_id = GETPOST('country_id', 'int'); $object->status = GETPOST('statut', 'int'); $object->status_buy = GETPOST('statut_buy', 'int'); - $object->status_batch = GETPOST('status_batch', 'aZ09'); + $object->status_batch = GETPOST('status_batch', 'aZ09'); // removed from update view so GETPOST always empty $object->fk_default_warehouse = GETPOST('fk_default_warehouse'); /* @@ -418,18 +418,18 @@ if (empty($reshook)) $object->canvas = GETPOST('canvas'); $object->net_measure = GETPOST('net_measure'); - $object->net_measure_units = GETPOST('net_measure_units'); // This is not the fk_unit but the power of unit + $object->net_measure_units = GETPOST('net_measure_units'); // This is not the fk_unit but the power of unit $object->weight = GETPOST('weight'); - $object->weight_units = GETPOST('weight_units'); // This is not the fk_unit but the power of unit + $object->weight_units = GETPOST('weight_units'); // This is not the fk_unit but the power of unit $object->length = GETPOST('size'); - $object->length_units = GETPOST('size_units'); // This is not the fk_unit but the power of unit - $object->width = GETPOST('sizewidth'); - $object->height = GETPOST('sizeheight'); + $object->length_units = GETPOST('size_units'); // This is not the fk_unit but the power of unit + $object->width = GETPOST('sizewidth'); + $object->height = GETPOST('sizeheight'); $object->surface = GETPOST('surface'); - $object->surface_units = GETPOST('surface_units'); // This is not the fk_unit but the power of unit + $object->surface_units = GETPOST('surface_units'); // This is not the fk_unit but the power of unit $object->volume = GETPOST('volume'); - $object->volume_units = GETPOST('volume_units'); // This is not the fk_unit but the power of unit + $object->volume_units = GETPOST('volume_units'); // This is not the fk_unit but the power of unit $object->finished = GETPOST('finished', 'alpha'); $units = GETPOST('units', 'int'); @@ -440,27 +440,27 @@ if (empty($reshook)) $object->fk_unit = null; } - $object->barcode_type = GETPOST('fk_barcode_type'); - $object->barcode = GETPOST('barcode'); + $object->barcode_type = GETPOST('fk_barcode_type'); + $object->barcode = GETPOST('barcode'); // Set barcode_type_xxx from barcode_type id - $stdobject=new GenericObject($db); - $stdobject->element='product'; - $stdobject->barcode_type=GETPOST('fk_barcode_type'); - $result=$stdobject->fetch_barcode(); + $stdobject = new GenericObject($db); + $stdobject->element = 'product'; + $stdobject->barcode_type = GETPOST('fk_barcode_type'); + $result = $stdobject->fetch_barcode(); if ($result < 0) { $error++; - $mesg='Failed to get bar code type information '; + $mesg = 'Failed to get bar code type information '; setEventMessages($mesg.$stdobject->error, $mesg.$stdobject->errors, 'errors'); } $object->barcode_type_code = $stdobject->barcode_type_code; $object->barcode_type_coder = $stdobject->barcode_type_coder; $object->barcode_type_label = $stdobject->barcode_type_label; - $accountancy_code_sell = GETPOST('accountancy_code_sell', 'alpha'); - $accountancy_code_sell_intra = GETPOST('accountancy_code_sell_intra', 'alpha'); - $accountancy_code_sell_export = GETPOST('accountancy_code_sell_export', 'alpha'); - $accountancy_code_buy = GETPOST('accountancy_code_buy', 'alpha'); + $accountancy_code_sell = GETPOST('accountancy_code_sell', 'alpha'); + $accountancy_code_sell_intra = GETPOST('accountancy_code_sell_intra', 'alpha'); + $accountancy_code_sell_export = GETPOST('accountancy_code_sell_export', 'alpha'); + $accountancy_code_buy = GETPOST('accountancy_code_buy', 'alpha'); if ($accountancy_code_sell <= 0) { $object->accountancy_code_sell = ''; } else { $object->accountancy_code_sell = $accountancy_code_sell; } if ($accountancy_code_sell_intra <= 0) { $object->accountancy_code_sell_intra = ''; } else { $object->accountancy_code_sell_intra = $accountancy_code_sell_intra; } @@ -471,7 +471,7 @@ if (empty($reshook)) $ret = $extrafields->setOptionalsFromPost(null, $object); if ($ret < 0) $error++; - if (! $error && $object->check()) + if (!$error && $object->check()) { if ($object->update($object->id, $user) > 0) { @@ -499,10 +499,10 @@ if (empty($reshook)) } // Action clone object - if ($action == 'confirm_clone' && $confirm != 'yes') { $action=''; } + if ($action == 'confirm_clone' && $confirm != 'yes') { $action = ''; } if ($action == 'confirm_clone' && $confirm == 'yes' && $usercancreate) { - if (! GETPOST('clone_content') && ! GETPOST('clone_prices') ) + if (!GETPOST('clone_content') && !GETPOST('clone_prices')) { setEventMessages($langs->trans("NoCloneOptionsSpecified"), null, 'errors'); } @@ -557,7 +557,7 @@ if (empty($reshook)) if ($result < 1) { $db->rollback(); setEventMessages($langs->trans('ErrorProductClone'), null, 'errors'); - header('Location: ' . $_SERVER['PHP_SELF'] . '?id=' . $originalId); + header('Location: '.$_SERVER['PHP_SELF'].'?id='.$originalId); exit(); } } @@ -572,7 +572,7 @@ if (empty($reshook)) } else { - $id=$originalId; + $id = $originalId; if ($object->error == 'ErrorProductAlreadyExists') { @@ -581,8 +581,8 @@ if (empty($reshook)) $refalreadyexists++; $action = ""; - $mesg=$langs->trans("ErrorProductAlreadyExists", $object->ref); - $mesg.=' '.$langs->trans("ShowCardHere").'.'; + $mesg = $langs->trans("ErrorProductAlreadyExists", $object->ref); + $mesg .= ' '.$langs->trans("ShowCardHere").'.'; setEventMessages($mesg, null, 'errors'); $object->fetch($id); } @@ -614,7 +614,7 @@ if (empty($reshook)) } // Delete a product - if ($action == 'confirm_delete' && $confirm != 'yes') { $action=''; } + if ($action == 'confirm_delete' && $confirm != 'yes') { $action = ''; } if ($action == 'confirm_delete' && $confirm == 'yes' && $usercandelete) { $result = $object->delete($user); @@ -628,7 +628,7 @@ if (empty($reshook)) { setEventMessages($langs->trans($object->error), null, 'errors'); $reload = 0; - $action=''; + $action = ''; } } @@ -636,11 +636,11 @@ if (empty($reshook)) // Add product into object if ($object->id > 0 && $action == 'addin') { - $thirpdartyid =0 ; + $thirpdartyid = 0; if (GETPOST('propalid') > 0) { $propal = new Propal($db); - $result=$propal->fetch(GETPOST('propalid')); + $result = $propal->fetch(GETPOST('propalid')); if ($result <= 0) { dol_print_error($db, $propal->error); @@ -651,7 +651,7 @@ if (empty($reshook)) elseif (GETPOST('commandeid') > 0) { $commande = new Commande($db); - $result=$commande->fetch(GETPOST('commandeid')); + $result = $commande->fetch(GETPOST('commandeid')); if ($result <= 0) { dol_print_error($db, $commande->error); @@ -662,7 +662,7 @@ if (empty($reshook)) elseif (GETPOST('factureid') > 0) { $facture = new Facture($db); - $result=$facture->fetch(GETPOST('factureid')); + $result = $facture->fetch(GETPOST('factureid')); if ($result <= 0) { dol_print_error($db, $facture->error); @@ -671,7 +671,7 @@ if (empty($reshook)) $thirpdartyid = $facture->socid; } - if ( $thirpdartyid > 0) { + if ($thirpdartyid > 0) { $soc = new Societe($db); $result = $soc->fetch($thirpdartyid); if ($result <= 0) { @@ -683,7 +683,7 @@ if (empty($reshook)) $tva_tx = get_default_tva($mysoc, $soc, $object->id); $tva_npr = get_default_npr($mysoc, $soc, $object->id); - if (empty($tva_tx)) $tva_npr=0; + if (empty($tva_tx)) $tva_npr = 0; $localtax1_tx = get_localtax($tva_tx, 1, $soc, $mysoc, $tva_npr); $localtax2_tx = get_localtax($tva_tx, 2, $soc, $mysoc, $tva_npr); @@ -697,7 +697,7 @@ if (empty($reshook)) $pu_ttc = $object->multiprices_ttc[$soc->price_level]; $price_base_type = $object->multiprices_base_type[$soc->price_level]; } elseif (!empty($conf->global->PRODUIT_CUSTOMER_PRICES)) { - require_once DOL_DOCUMENT_ROOT . '/product/class/productcustomerprice.class.php'; + require_once DOL_DOCUMENT_ROOT.'/product/class/productcustomerprice.class.php'; $prodcustprice = new Productcustomerprice($db); @@ -729,7 +729,7 @@ if (empty($reshook)) if (GETPOST('propalid') > 0) { // Define cost price for margin calculation - $buyprice=0; + $buyprice = 0; if (($result = $propal->defineBuyPrice($pu_ht, GETPOST('remise_percent'), $object->id)) < 0) { dol_syslog($langs->trans('FailedToGetCostPrice')); @@ -765,14 +765,14 @@ if (empty($reshook)) $object->fk_unit ); if ($result > 0) { - header("Location: " . DOL_URL_ROOT . "/comm/propal/card.php?id=" . $propal->id); + header("Location: ".DOL_URL_ROOT."/comm/propal/card.php?id=".$propal->id); return; } - setEventMessages($langs->trans("ErrorUnknown") . ": $result", null, 'errors'); + setEventMessages($langs->trans("ErrorUnknown").": $result", null, 'errors'); } elseif (GETPOST('commandeid') > 0) { // Define cost price for margin calculation - $buyprice=0; + $buyprice = 0; if (($result = $commande->defineBuyPrice($pu_ht, GETPOST('remise_percent'), $object->id)) < 0) { dol_syslog($langs->trans('FailedToGetCostPrice')); @@ -810,12 +810,12 @@ if (empty($reshook)) ); if ($result > 0) { - header("Location: " . DOL_URL_ROOT . "/commande/card.php?id=" . $commande->id); + header("Location: ".DOL_URL_ROOT."/commande/card.php?id=".$commande->id); exit; } } elseif (GETPOST('factureid') > 0) { // Define cost price for margin calculation - $buyprice=0; + $buyprice = 0; if (($result = $facture->defineBuyPrice($pu_ht, GETPOST('remise_percent'), $object->id)) < 0) { dol_syslog($langs->trans('FailedToGetCostPrice')); @@ -858,13 +858,13 @@ if (empty($reshook)) ); if ($result > 0) { - header("Location: " . DOL_URL_ROOT . "/compta/facture/card.php?facid=" . $facture->id); + header("Location: ".DOL_URL_ROOT."/compta/facture/card.php?facid=".$facture->id); exit; } } } else { - $action=""; + $action = ""; setEventMessages($langs->trans("WarningSelectOneDocument"), null, 'warnings'); } } @@ -881,13 +881,13 @@ $helpurl = ''; $shortlabel = dol_trunc($object->label, 16); if (GETPOST("type") == '0' || ($object->type == Product::TYPE_PRODUCT)) { - $title = $langs->trans('Product')." ". $shortlabel ." - ".$langs->trans('Card'); - $helpurl='EN:Module_Products|FR:Module_Produits|ES:Módulo_Productos'; + $title = $langs->trans('Product')." ".$shortlabel." - ".$langs->trans('Card'); + $helpurl = 'EN:Module_Products|FR:Module_Produits|ES:Módulo_Productos'; } if (GETPOST("type") == '1' || ($object->type == Product::TYPE_SERVICE)) { - $title = $langs->trans('Service')." ". $shortlabel ." - ".$langs->trans('Card'); - $helpurl='EN:Module_Services_En|FR:Module_Services|ES:Módulo_Servicios'; + $title = $langs->trans('Service')." ".$shortlabel." - ".$langs->trans('Card'); + $helpurl = 'EN:Module_Services_En|FR:Module_Services|ES:Módulo_Servicios'; } llxHeader('', $title, $helpurl); @@ -895,22 +895,22 @@ llxHeader('', $title, $helpurl); $form = new Form($db); $formfile = new FormFile($db); $formproduct = new FormProduct($db); -if (! empty($conf->accounting->enabled)) $formaccounting = new FormAccounting($db); +if (!empty($conf->accounting->enabled)) $formaccounting = new FormAccounting($db); // Load object modBarCodeProduct -$res=0; -if (! empty($conf->barcode->enabled) && ! empty($conf->global->BARCODE_PRODUCT_ADDON_NUM)) +$res = 0; +if (!empty($conf->barcode->enabled) && !empty($conf->global->BARCODE_PRODUCT_ADDON_NUM)) { - $module=strtolower($conf->global->BARCODE_PRODUCT_ADDON_NUM); - $dirbarcode=array_merge(array('/core/modules/barcode/'), $conf->modules_parts['barcode']); + $module = strtolower($conf->global->BARCODE_PRODUCT_ADDON_NUM); + $dirbarcode = array_merge(array('/core/modules/barcode/'), $conf->modules_parts['barcode']); foreach ($dirbarcode as $dirroot) { - $res=dol_include_once($dirroot.$module.'.php'); + $res = dol_include_once($dirroot.$module.'.php'); if ($res) break; } if ($res > 0) { - $modBarCodeProduct =new $module(); + $modBarCodeProduct = new $module(); } } @@ -923,11 +923,11 @@ if (is_object($objcanvas) && $objcanvas->displayCanvasExists($action)) if (empty($object->error) && $id) { $object = new Product($db); - $result=$object->fetch($id); + $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 + $objcanvas->assign_values($action, $object->id, $object->ref); // Set value for templates + $objcanvas->display_canvas($action); // Show template } else { @@ -940,12 +940,12 @@ else require_once DOL_DOCUMENT_ROOT.'/core/class/doleditor.class.php'; // Load object modCodeProduct - $module=(! empty($conf->global->PRODUCT_CODEPRODUCT_ADDON)?$conf->global->PRODUCT_CODEPRODUCT_ADDON:'mod_codeproduct_leopard'); + $module = (!empty($conf->global->PRODUCT_CODEPRODUCT_ADDON) ? $conf->global->PRODUCT_CODEPRODUCT_ADDON : 'mod_codeproduct_leopard'); if (substr($module, 0, 16) == 'mod_codeproduct_' && substr($module, -3) == 'php') { - $module = substr($module, 0, dol_strlen($module)-4); + $module = substr($module, 0, dol_strlen($module) - 4); } - $result=dol_include_once('/core/modules/product/'.$module.'.php'); + $result = dol_include_once('/core/modules/product/'.$module.'.php'); if ($result > 0) { $modCodeProduct = new $module(); @@ -957,15 +957,15 @@ else print ''; print ''; print ''."\n"; - if (! empty($modCodeProduct->code_auto)) + if (!empty($modCodeProduct->code_auto)) print ''; - if (! empty($modBarCodeProduct->code_auto)) + if (!empty($modBarCodeProduct->code_auto)) print ''; print ''; - if ($type==1) $title=$langs->trans("NewService"); - else $title=$langs->trans("NewProduct"); - $linkback=""; + if ($type == 1) $title = $langs->trans("NewService"); + else $title = $langs->trans("NewProduct"); + $linkback = ""; print load_fiche_titre($title, $linkback, 'products'); dol_fiche_head(''); @@ -973,9 +973,9 @@ else print '
    trans("SellingPrice"); ?>
    '; print ''; - $tmpcode=''; - if (! empty($modCodeProduct->code_auto)) $tmpcode=$modCodeProduct->getNextValue($object, $type); - print ''; // To buy print ''; // Batch number management - if (! empty($conf->productbatch->enabled)) + if (!empty($conf->productbatch->enabled)) { print ''; } - $showbarcode=empty($conf->barcode->enabled)?0:1; - if (! empty($conf->global->MAIN_USE_ADVANCED_PERMS) && empty($user->rights->barcode->lire_advance)) $showbarcode=0; + $showbarcode = empty($conf->barcode->enabled) ? 0 : 1; + if (!empty($conf->global->MAIN_USE_ADVANCED_PERMS) && empty($user->rights->barcode->lire_advance)) $showbarcode = 0; if ($showbarcode) { print ''; } @@ -1043,7 +1043,7 @@ else print ''; print ''; - if ($type != 1 && ! empty($conf->stock->enabled)) + if ($type != 1 && !empty($conf->stock->enabled)) { // Default warehouse print ''; // Brut Weight print ''; // Brut Length @@ -1095,7 +1095,7 @@ else print ' x '; print ' x '; print ''; - print $formproduct->selectMeasuringUnits("size_units", "size", GETPOSTISSET('size_units')?GETPOST('size_units', 'alpha'):'0', 0, 2); + print $formproduct->selectMeasuringUnits("size_units", "size", GETPOSTISSET('size_units') ?GETPOST('size_units', 'alpha') : '0', 0, 2); print ''; } if (empty($conf->global->PRODUCT_DISABLE_SURFACE)) @@ -1103,7 +1103,7 @@ else // Brut Surface print ''; } if (empty($conf->global->PRODUCT_DISABLE_VOLUME)) @@ -1111,22 +1111,22 @@ else // Brut Volume print ''; } - if (! empty($conf->global->PRODUCT_ADD_NET_MEASURE)) + if (!empty($conf->global->PRODUCT_ADD_NET_MEASURE)) { // Net Measure print ''; } } // Units - if($conf->global->PRODUCT_USE_UNITS) + if ($conf->global->PRODUCT_USE_UNITS) { print ''; print '
    '.$langs->trans("Ref").''; + $tmpcode = ''; + if (!empty($modCodeProduct->code_auto)) $tmpcode = $modCodeProduct->getNextValue($object, $type); + print ''.$langs->trans("Ref").''; if ($refalreadyexists) { print $langs->trans("RefAlreadyExists"); @@ -987,45 +987,45 @@ else // On sell print '
    '.$langs->trans("Status").' ('.$langs->trans("Sell").')'; - $statutarray=array('1' => $langs->trans("OnSell"), '0' => $langs->trans("NotOnSell")); + $statutarray = array('1' => $langs->trans("OnSell"), '0' => $langs->trans("NotOnSell")); print $form->selectarray('statut', $statutarray, GETPOST('statut')); print '
    '.$langs->trans("Status").' ('.$langs->trans("Buy").')'; - $statutarray=array('1' => $langs->trans("ProductStatusOnBuy"), '0' => $langs->trans("ProductStatusNotOnBuy")); + $statutarray = array('1' => $langs->trans("ProductStatusOnBuy"), '0' => $langs->trans("ProductStatusNotOnBuy")); print $form->selectarray('statut_buy', $statutarray, GETPOST('statut_buy')); print '
    '.$langs->trans("ManageLotSerial").''; - $statutarray=array('0' => $langs->trans("ProductStatusNotOnBatch"), '1' => $langs->trans("ProductStatusOnBatch")); + $statutarray = array('0' => $langs->trans("ProductStatusNotOnBatch"), '1' => $langs->trans("ProductStatusOnBatch")); print $form->selectarray('status_batch', $statutarray, GETPOST('status_batch')); print '
    '.$langs->trans('BarcodeType').''; if (isset($_POST['fk_barcode_type'])) { - $fk_barcode_type=GETPOST('fk_barcode_type'); + $fk_barcode_type = GETPOST('fk_barcode_type'); } else { - if (empty($fk_barcode_type) && ! empty($conf->global->PRODUIT_DEFAULT_BARCODE_TYPE)) $fk_barcode_type = $conf->global->PRODUIT_DEFAULT_BARCODE_TYPE; + if (empty($fk_barcode_type) && !empty($conf->global->PRODUIT_DEFAULT_BARCODE_TYPE)) $fk_barcode_type = $conf->global->PRODUIT_DEFAULT_BARCODE_TYPE; } require_once DOL_DOCUMENT_ROOT.'/core/class/html.formbarcode.class.php'; $formbarcode = new FormBarCode($db); print $formbarcode->selectBarcodeType($fk_barcode_type, 'fk_barcode_type', 1); print ''.$langs->trans("BarcodeValue").''; - $tmpcode=isset($_POST['barcode'])?GETPOST('barcode'):$object->barcode; - if (empty($tmpcode) && ! empty($modBarCodeProduct->code_auto)) $tmpcode=$modBarCodeProduct->getNextValue($object, $type); + $tmpcode = isset($_POST['barcode']) ?GETPOST('barcode') : $object->barcode; + if (empty($tmpcode) && !empty($modBarCodeProduct->code_auto)) $tmpcode = $modBarCodeProduct->getNextValue($object, $type); print ''; print '
    '.$langs->trans("DefaultWarehouse").''; @@ -1078,14 +1078,14 @@ else { // Nature print '
    '.$langs->trans("Nature").''; - $statutarray=array('1' => $langs->trans("Finished"), '0' => $langs->trans("RowMaterial")); + $statutarray = array('1' => $langs->trans("Finished"), '0' => $langs->trans("RowMaterial")); print $form->selectarray('finished', $statutarray, GETPOST('finished', 'alpha'), 1); print '
    '.$langs->trans("Weight").''; print ''; - print $formproduct->selectMeasuringUnits("weight_units", "weight", GETPOSTISSET('weight_units')?GETPOST('weight_units', 'alpha'):(empty($conf->global->MAIN_WEIGHT_DEFAULT_UNIT)?0:$conf->global->MAIN_WEIGHT_DEFAULT_UNIT), 0, 2); + print $formproduct->selectMeasuringUnits("weight_units", "weight", GETPOSTISSET('weight_units') ?GETPOST('weight_units', 'alpha') : (empty($conf->global->MAIN_WEIGHT_DEFAULT_UNIT) ? 0 : $conf->global->MAIN_WEIGHT_DEFAULT_UNIT), 0, 2); print '
    '.$langs->trans("Surface").''; print ''; - print $formproduct->selectMeasuringUnits("surface_units", "surface", GETPOSTISSET('surface_units')?GETPOST('surface_units', 'alpha'):'0', 0, 2); + print $formproduct->selectMeasuringUnits("surface_units", "surface", GETPOSTISSET('surface_units') ?GETPOST('surface_units', 'alpha') : '0', 0, 2); print '
    '.$langs->trans("Volume").''; print ''; - print $formproduct->selectMeasuringUnits("volume_units", "volume", GETPOSTISSET('volume_units')?GETPOST('volume_units', 'alpha'):'0', 0, 2); + print $formproduct->selectMeasuringUnits("volume_units", "volume", GETPOSTISSET('volume_units') ?GETPOST('volume_units', 'alpha') : '0', 0, 2); print '
    '.$langs->trans("NetMeasure").''; print ''; - print $formproduct->selectMeasuringUnits("net_measure_units", '', GETPOSTISSET('net_measure_units')?GETPOST('net_measure_units', 'alpha'):(empty($conf->global->MAIN_WEIGHT_DEFAULT_UNIT)?0:$conf->global->MAIN_WEIGHT_DEFAULT_UNIT), 0, 0); + print $formproduct->selectMeasuringUnits("net_measure_units", '', GETPOSTISSET('net_measure_units') ?GETPOST('net_measure_units', 'alpha') : (empty($conf->global->MAIN_WEIGHT_DEFAULT_UNIT) ? 0 : $conf->global->MAIN_WEIGHT_DEFAULT_UNIT), 0, 0); print '
    '.$langs->trans('DefaultUnitToShow').''; @@ -1146,8 +1146,8 @@ else } // Other attributes - $parameters=array('colspan' => 3); - $reshook=$hookmanager->executeHooks('formObjectOptions', $parameters, $object, $action); // Note that $action and $object may have been modified by hook + $parameters = array('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)) { @@ -1178,13 +1178,13 @@ else print '
    '; - if (! empty($conf->global->PRODUIT_MULTIPRICES)) + if (!empty($conf->global->PRODUIT_MULTIPRICES)) { // We do no show price array on create when multiprices enabled. // We must set them on prices tab. - print ''; + print '
    '; // VAT - print ''; @@ -1193,7 +1193,7 @@ else } else { - print '
    ' . $langs->trans("VATRate") . ''; + print '
    '.$langs->trans("VATRate").''; $defaultva = get_default_tva($mysoc, $mysoc); print $form->load_tva("tva_tx", $defaultva, $mysoc, $mysoc, 0, 0, '', false, 1); print '
    '; + print '
    '; // Price print ''; @@ -1208,7 +1208,7 @@ else // VAT print ''; @@ -1218,7 +1218,7 @@ else } // Accountancy codes - print '
    '.$langs->trans("SellingPrice").'
    '.$langs->trans("VATRate").''; - $defaultva=get_default_tva($mysoc, $mysoc); + $defaultva = get_default_tva($mysoc, $mysoc); print $form->load_tva("tva_tx", $defaultva, $mysoc, $mysoc, 0, 0, '', false, 1); print '
    '; + print '
    '; if (! empty($conf->accounting->enabled)) { @@ -1226,9 +1226,9 @@ else print ''; print ''; @@ -1239,9 +1239,9 @@ else print ''; print ''; @@ -1252,9 +1252,9 @@ else print ''; @@ -1295,9 +1295,9 @@ else dol_fiche_end(); print '
    '; - print ''; + print ''; print '     '; - print ''; + print ''; print '
    '; print ''; @@ -1326,9 +1326,9 @@ else print ''; print ''; - $head=product_prepare_head($object); - $titre=$langs->trans("CardProduct".$object->type); - $picto=($object->type== Product::TYPE_SERVICE?'service':'product'); + $head = product_prepare_head($object); + $titre = $langs->trans("CardProduct".$object->type); + $picto = ($object->type == Product::TYPE_SERVICE ? 'service' : 'product'); dol_fiche_head($head, 'card', $titre, 0, $picto); print '
    '.$langs->trans("ProductAccountancySellCode").''; if($type = 0) { - $accountancy_code_sell = (GETPOST('accountancy_code_sell', 'alpha')?(GETPOST('accountancy_code_sell', 'alpha')):$conf->global->ACCOUNTING_PRODUCT_SOLD_ACCOUNT); + $accountancy_code_sell = (GETPOSTISSET('accountancy_code_sell')?GETPOST('accountancy_code_sell', 'alpha'):$conf->global->ACCOUNTING_PRODUCT_SOLD_ACCOUNT); } else { - $accountancy_code_sell = (GETPOST('accountancy_code_sell', 'alpha')?(GETPOST('accountancy_code_sell', 'alpha')):$conf->global->ACCOUNTING_SERVICE_SOLD_ACCOUNT); + $accountancy_code_sell = (GETPOSTISSET('accountancy_code_sell')?GETPOST('accountancy_code_sell', 'alpha'):$conf->global->ACCOUNTING_SERVICE_SOLD_ACCOUNT); } print $formaccounting->select_account($accountancy_code_sell, 'accountancy_code_sell', 1, null, 1, 1, ''); print '
    '.$langs->trans("ProductAccountancySellIntraCode").''; if($type = 0) { - $accountancy_code_sell_intra = (GETPOST('accountancy_code_sell_intra', 'alpha')?(GETPOST('accountancy_code_sell_intra', 'alpha')):$conf->global->ACCOUNTING_PRODUCT_SOLD_INTRA_ACCOUNT); + $accountancy_code_sell_intra = (GETPOSTISSET('accountancy_code_sell_intra')?GETPOST('accountancy_code_sell_intra', 'alpha'):$conf->global->ACCOUNTING_PRODUCT_SOLD_INTRA_ACCOUNT); } else { - $accountancy_code_sell_intra = GETPOST('accountancy_code_sell_intra', 'alpha'); + $accountancy_code_sell_intra = (GETPOSTISSET('accountancy_code_sell_intra')?GETPOST('accountancy_code_sell_intra', 'alpha'):$conf->global->ACCOUNTING_SERVICE_SOLD_INTRA_ACCOUNT); } print $formaccounting->select_account($accountancy_code_sell_intra, 'accountancy_code_sell_intra', 1, null, 1, 1, ''); print '
    '; if($type = 0) { - $accountancy_code_sell_export = (GETPOST('accountancy_code_sell_export', 'alpha')?(GETPOST('accountancy_code_sell_export', 'alpha')):$conf->global->ACCOUNTING_PRODUCT_SOLD_EXPORT_ACCOUNT); + $accountancy_code_sell_export = (GETPOST('accountancy_code_sell_export')?GETPOST('accountancy_code_sell_export', 'alpha'):$conf->global->ACCOUNTING_PRODUCT_SOLD_EXPORT_ACCOUNT); } else { - $accountancy_code_sell_export = GETPOST('accountancy_code_sell_export', 'alpha'); + $accountancy_code_sell_export = (GETPOST('accountancy_code_sell_export')?GETPOST('accountancy_code_sell_export', 'alpha'):$conf->global->ACCOUNTING_SERVICE_SOLD_EXPORT_ACCOUNT); } print $formaccounting->select_account($accountancy_code_sell_export, 'accountancy_code_sell_export', 1, null, 1, 1, ''); print '
    '; @@ -1374,37 +1374,37 @@ else // Batch number managment if ($conf->productbatch->enabled) { - if ($object->isProduct() || ! empty($conf->global->STOCK_SUPPORTS_SERVICES)) + if ($object->isProduct() || !empty($conf->global->STOCK_SUPPORTS_SERVICES)) { print ''; } } // Barcode - $showbarcode=empty($conf->barcode->enabled)?0:1; - if (! empty($conf->global->MAIN_USE_ADVANCED_PERMS) && empty($user->rights->barcode->lire_advance)) $showbarcode=0; + $showbarcode = empty($conf->barcode->enabled) ? 0 : 1; + if (!empty($conf->global->MAIN_USE_ADVANCED_PERMS) && empty($user->rights->barcode->lire_advance)) $showbarcode = 0; if ($showbarcode) { print ''; } @@ -1425,7 +1425,7 @@ else print ''; // Stock - if ($object->isProduct() && ! empty($conf->stock->enabled)) + if ($object->isProduct() && !empty($conf->stock->enabled)) { // Default warehouse print ''; @@ -1498,7 +1498,7 @@ else print ''; } - if (! empty($conf->global->PRODUCT_ADD_NET_MEASURE)) + if (!empty($conf->global->PRODUCT_ADD_NET_MEASURE)) { // Net Measure print ''; print ''; // Origin country @@ -1528,8 +1528,8 @@ else } // Other attributes - $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 + $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)) { @@ -1543,8 +1543,8 @@ else $cate_arbo = $form->select_all_categories(Categorie::TYPE_PRODUCT, '', 'parent', 64, 0, 1); $c = new Categorie($db); $cats = $c->containing($object->id, Categorie::TYPE_PRODUCT); - $arrayselected=array(); - foreach($cats as $cat) { + $arrayselected = array(); + foreach ($cats as $cat) { $arrayselected[] = $cat->id; } print $form->multiselectarray('categories', $cate_arbo, $arrayselected, '', 0, '', 0, '100%'); @@ -1552,7 +1552,7 @@ else } // Note private - if (! empty($conf->global->MAIN_DISABLE_NOTES_TAB)) + if (!empty($conf->global->MAIN_DISABLE_NOTES_TAB)) { print ''; @@ -306,9 +306,9 @@ if ($object->id) if ($conf->global->MAIN_MULTILANGS) { - if (array_key_exists($filetoadd['name'] . '_' . $default_lang, $filetomerge->lines)) + if (array_key_exists($filetoadd['name'].'_'.$default_lang, $filetomerge->lines)) { - $filename = $filetoadd['name'] . ' - ' . $langs->trans('Language_' . $default_lang); + $filename = $filetoadd['name'].' - '.$langs->trans('Language_'.$default_lang); $checked = ' checked '; } } @@ -321,13 +321,13 @@ if ($object->id) } print ''; } } print ''; print '
    '.$langs->trans("ManageLotSerial").''; - $statutarray=array('0' => $langs->trans("ProductStatusNotOnBatch"), '1' => $langs->trans("ProductStatusOnBatch")); + $statutarray = array('0' => $langs->trans("ProductStatusNotOnBatch"), '1' => $langs->trans("ProductStatusOnBatch")); print $form->selectarray('status_batch', $statutarray, $object->status_batch); print '
    '.$langs->trans('BarcodeType').''; if (isset($_POST['fk_barcode_type'])) { - $fk_barcode_type=GETPOST('fk_barcode_type'); + $fk_barcode_type = GETPOST('fk_barcode_type'); } else { - $fk_barcode_type=$object->barcode_type; - if (empty($fk_barcode_type) && ! empty($conf->global->PRODUIT_DEFAULT_BARCODE_TYPE)) $fk_barcode_type = $conf->global->PRODUIT_DEFAULT_BARCODE_TYPE; + $fk_barcode_type = $object->barcode_type; + if (empty($fk_barcode_type) && !empty($conf->global->PRODUIT_DEFAULT_BARCODE_TYPE)) $fk_barcode_type = $conf->global->PRODUIT_DEFAULT_BARCODE_TYPE; } require_once DOL_DOCUMENT_ROOT.'/core/class/html.formbarcode.class.php'; $formbarcode = new FormBarCode($db); print $formbarcode->selectBarcodeType($fk_barcode_type, 'fk_barcode_type', 1); print ''.$langs->trans("BarcodeValue").''; - $tmpcode=isset($_POST['barcode'])?GETPOST('barcode'):$object->barcode; - if (empty($tmpcode) && ! empty($modBarCodeProduct->code_auto)) $tmpcode=$modBarCodeProduct->getNextValue($object, $type); + $tmpcode = isset($_POST['barcode']) ?GETPOST('barcode') : $object->barcode; + if (empty($tmpcode) && !empty($modBarCodeProduct->code_auto)) $tmpcode = $modBarCodeProduct->getNextValue($object, $type); print ''; print '
    '.$langs->trans("DefaultWarehouse").''; @@ -1461,7 +1461,7 @@ else { // Nature print '
    '.$langs->trans("Nature").''; - $statutarray=array('-1'=>' ', '1' => $langs->trans("Finished"), '0' => $langs->trans("RowMaterial")); + $statutarray = array('-1'=>' ', '1' => $langs->trans("Finished"), '0' => $langs->trans("RowMaterial")); print $form->selectarray('finished', $statutarray, $object->finished); print '
    '.$langs->trans("NetMeasure").''; @@ -1508,7 +1508,7 @@ else } } // Units - if($conf->global->PRODUCT_USE_UNITS) + if ($conf->global->PRODUCT_USE_UNITS) { print '
    '.$langs->trans('DefaultUnitToShow').''; @@ -1517,7 +1517,7 @@ else } // Custom code - if (! $object->isService() && empty($conf->global->PRODUCT_DISABLE_CUSTOM_INFO)) + if (!$object->isService() && empty($conf->global->PRODUCT_DISABLE_CUSTOM_INFO)) { print '
    '.$langs->trans("CustomCode").'
    '.$langs->trans("NoteNotVisibleOnBill").''; @@ -1566,9 +1566,9 @@ else print '
    '; - print ''; + print '
    '; - if (! empty($conf->accounting->enabled)) + if (!empty($conf->accounting->enabled)) { // Accountancy_code_sell print ''; @@ -1637,20 +1637,20 @@ else // Fiche en mode visu else { - $showbarcode=empty($conf->barcode->enabled)?0:1; - if (! empty($conf->global->MAIN_USE_ADVANCED_PERMS) && empty($user->rights->barcode->lire_advance)) $showbarcode=0; + $showbarcode = empty($conf->barcode->enabled) ? 0 : 1; + if (!empty($conf->global->MAIN_USE_ADVANCED_PERMS) && empty($user->rights->barcode->lire_advance)) $showbarcode = 0; - $head=product_prepare_head($object); - $titre=$langs->trans("CardProduct".$object->type); - $picto=($object->type== Product::TYPE_SERVICE?'service':'product'); + $head = product_prepare_head($object); + $titre = $langs->trans("CardProduct".$object->type); + $picto = ($object->type == Product::TYPE_SERVICE ? 'service' : 'product'); dol_fiche_head($head, 'card', $titre, -1, $picto); $linkback = ''.$langs->trans("BackToList").''; - $object->next_prev_filter=" fk_product_type = ".$object->type; + $object->next_prev_filter = " fk_product_type = ".$object->type; $shownav = 1; - if ($user->socid && ! in_array('product', explode(',', $conf->global->MAIN_MODULES_FOR_EXTERNAL))) $shownav=0; + if ($user->socid && !in_array('product', explode(',', $conf->global->MAIN_MODULES_FOR_EXTERNAL))) $shownav = 0; dol_banner_tab($object, 'ref', $linkback, $shownav, 'ref'); @@ -1662,10 +1662,10 @@ else print '
    '.$langs->trans("ProductAccountancySellCode").'
    '; // Type - if (! empty($conf->product->enabled) && ! empty($conf->service->enabled)) + 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"); + $typeformat = 'select;0:'.$langs->trans("Product").',1:'.$langs->trans("Service"); print ''."\n"; @@ -1709,8 +1709,8 @@ else print ''; // Batch number management (to batch) - if (! empty($conf->productbatch->enabled)) + if (!empty($conf->productbatch->enabled)) { - if ($object->isProduct() || ! empty($conf->global->STOCK_SUPPORTS_SERVICES)) + if ($object->isProduct() || !empty($conf->global->STOCK_SUPPORTS_SERVICES)) { print ''; + print ''; // Public URL print ''; // Default warehouse - if ($object->isProduct() && ! empty($conf->stock->enabled)) + if ($object->isProduct() && !empty($conf->stock->enabled)) { $warehouse = new Entrepot($db); $warehouse->fetch($object->fk_default_warehouse); print ''; } @@ -1864,13 +1864,13 @@ else print ''; } @@ -1939,7 +1939,7 @@ else print "\n"; } - if (! empty($conf->global->PRODUCT_ADD_NET_MEASURE)) + if (!empty($conf->global->PRODUCT_ADD_NET_MEASURE)) { // Net Measure print ''; @@ -1976,21 +1976,21 @@ else } // Other attributes - $parameters=array('colspan' => ' colspan="'.(2+(($showphoto||$showbarcode)?1:0)).'"'); - include DOL_DOCUMENT_ROOT . '/core/tpl/extrafields_view.tpl.php'; + $parameters = array('colspan' => ' colspan="'.(2 + (($showphoto || $showbarcode) ? 1 : 0)).'"'); + include DOL_DOCUMENT_ROOT.'/core/tpl/extrafields_view.tpl.php'; // Categories - if($conf->categorie->enabled) { + if ($conf->categorie->enabled) { print '"; } // Note private - if (! empty($conf->global->MAIN_DISABLE_NOTES_TAB)) + if (!empty($conf->global->MAIN_DISABLE_NOTES_TAB)) { print ' '."\n"; - print ''."\n"; + print ''."\n"; print ' '."\n"; } @@ -2010,45 +2010,45 @@ else } // Load object modCodeProduct -$module=(! empty($conf->global->PRODUCT_CODEPRODUCT_ADDON)?$conf->global->PRODUCT_CODEPRODUCT_ADDON:'mod_codeproduct_leopard'); +$module = (!empty($conf->global->PRODUCT_CODEPRODUCT_ADDON) ? $conf->global->PRODUCT_CODEPRODUCT_ADDON : 'mod_codeproduct_leopard'); if (substr($module, 0, 16) == 'mod_codeproduct_' && substr($module, -3) == 'php') { - $module = substr($module, 0, dol_strlen($module)-4); + $module = substr($module, 0, dol_strlen($module) - 4); } -$result=dol_include_once('/core/modules/product/'.$module.'.php'); +$result = dol_include_once('/core/modules/product/'.$module.'.php'); if ($result > 0) { $modCodeProduct = new $module(); } -$tmpcode=''; -if (! empty($modCodeProduct->code_auto)) $tmpcode=$modCodeProduct->getNextValue($object, $object->type); +$tmpcode = ''; +if (!empty($modCodeProduct->code_auto)) $tmpcode = $modCodeProduct->getNextValue($object, $object->type); // Define confirmation messages -$formquestionclone=array( +$formquestionclone = array( 'text' => $langs->trans("ConfirmClone"), - array('type' => 'text', 'name' => 'clone_ref','label' => $langs->trans("NewRefForClone"), 'value' => empty($tmpcode) ? $langs->trans("CopyOf").' '.$object->ref : $tmpcode, 'size'=>24), - array('type' => 'checkbox', 'name' => 'clone_content','label' => $langs->trans("CloneContentProduct"), 'value' => 1), + array('type' => 'text', 'name' => 'clone_ref', 'label' => $langs->trans("NewRefForClone"), 'value' => empty($tmpcode) ? $langs->trans("CopyOf").' '.$object->ref : $tmpcode, 'size'=>24), + array('type' => 'checkbox', 'name' => 'clone_content', 'label' => $langs->trans("CloneContentProduct"), 'value' => 1), array('type' => 'checkbox', 'name' => 'clone_categories', 'label' => $langs->trans("CloneCategoriesProduct"), 'value' => 1), ); if (!empty($conf->global->PRODUIT_MULTIPRICES)) { - $formquestionclone[] = array('type' => 'checkbox', 'name' => 'clone_prices', 'label' => $langs->trans("ClonePricesProduct").' ('.$langs->trans("CustomerPrices").')', 'value' => 0); + $formquestionclone[] = array('type' => 'checkbox', 'name' => 'clone_prices', 'label' => $langs->trans("ClonePricesProduct").' ('.$langs->trans("CustomerPrices").')', 'value' => 0); } -if (! empty($conf->global->PRODUIT_SOUSPRODUITS)) +if (!empty($conf->global->PRODUIT_SOUSPRODUITS)) { - $formquestionclone[]=array('type' => 'checkbox', 'name' => 'clone_composition', 'label' => $langs->trans('CloneCompositionProduct'), 'value' => 1); + $formquestionclone[] = array('type' => 'checkbox', 'name' => 'clone_composition', 'label' => $langs->trans('CloneCompositionProduct'), 'value' => 1); } // Confirm delete product -if (($action == 'delete' && (empty($conf->use_javascript_ajax) || ! empty($conf->dol_use_jmobile))) // Output when action = clone if jmobile or no js - || (! empty($conf->use_javascript_ajax) && empty($conf->dol_use_jmobile))) // Always output when not jmobile nor js +if (($action == 'delete' && (empty($conf->use_javascript_ajax) || !empty($conf->dol_use_jmobile))) // Output when action = clone if jmobile or no js + || (!empty($conf->use_javascript_ajax) && empty($conf->dol_use_jmobile))) // Always output when not jmobile nor js { print $form->formconfirm("card.php?id=".$object->id, $langs->trans("DeleteProduct"), $langs->trans("ConfirmDeleteProduct"), "confirm_delete", '', 0, "action-delete"); } // Clone confirmation -if (($action == 'clone' && (empty($conf->use_javascript_ajax) || ! empty($conf->dol_use_jmobile))) // Output when action = clone if jmobile or no js - || (! empty($conf->use_javascript_ajax) && empty($conf->dol_use_jmobile))) // Always output when not jmobile nor js +if (($action == 'clone' && (empty($conf->use_javascript_ajax) || !empty($conf->dol_use_jmobile))) // Output when action = clone if jmobile or no js + || (!empty($conf->use_javascript_ajax) && empty($conf->dol_use_jmobile))) // Always output when not jmobile nor js { print $form->formconfirm($_SERVER["PHP_SELF"].'?id='.$object->id, $langs->trans('ToClone'), $langs->trans('ConfirmCloneProduct', $object->ref), 'confirm_clone', $formquestionclone, 'yes', 'action-clone', 350, 600); } @@ -2063,17 +2063,17 @@ if ($action != 'create' && $action != 'edit') { print "\n".'
    '."\n"; - $parameters=array(); - $reshook=$hookmanager->executeHooks('addMoreActionsButtons', $parameters, $object, $action); // Note that $action and $object may have been modified by hook + $parameters = array(); + $reshook = $hookmanager->executeHooks('addMoreActionsButtons', $parameters, $object, $action); // Note that $action and $object may have been modified by hook if (empty($reshook)) { if ($usercancreate) { - if (! isset($object->no_button_edit) || $object->no_button_edit <> 1) print 'id.'">'.$langs->trans("Modify").''; + if (!isset($object->no_button_edit) || $object->no_button_edit <> 1) print 'id.'">'.$langs->trans("Modify").''; - if (! isset($object->no_button_copy) || $object->no_button_copy <> 1) + if (!isset($object->no_button_copy) || $object->no_button_copy <> 1) { - if (! empty($conf->use_javascript_ajax) && empty($conf->dol_use_jmobile)) + if (!empty($conf->use_javascript_ajax) && empty($conf->dol_use_jmobile)) { print ''.$langs->trans('ToClone').''."\n"; } @@ -2087,9 +2087,9 @@ if ($action != 'create' && $action != 'edit') if ($usercandelete) { - if (empty($object_is_used) && (! isset($object->no_button_delete) || $object->no_button_delete <> 1)) + if (empty($object_is_used) && (!isset($object->no_button_delete) || $object->no_button_delete <> 1)) { - if (! empty($conf->use_javascript_ajax) && empty($conf->dol_use_jmobile)) + if (!empty($conf->use_javascript_ajax) && empty($conf->dol_use_jmobile)) { print ''.$langs->trans('Delete').''."\n"; } @@ -2116,14 +2116,14 @@ if ($action != 'create' && $action != 'edit') * All the "Add to" areas */ -if (! empty($conf->global->PRODUCT_ADD_FORM_ADD_TO) && $object->id && ($action == '' || $action == 'view') && $object->status) +if (!empty($conf->global->PRODUCT_ADD_FORM_ADD_TO) && $object->id && ($action == '' || $action == 'view') && $object->status) { //Variable used to check if any text is going to be printed $html = ''; //print '
    '; // Propals - if (! empty($conf->propal->enabled) && $user->rights->propale->creer) + if (!empty($conf->propal->enabled) && $user->rights->propale->creer) { $propal = new Propal($db); @@ -2148,7 +2148,7 @@ if (! empty($conf->global->PRODUCT_ADD_FORM_ADD_TO) && $object->id && ($action = } // Commande - if (! empty($conf->commande->enabled) && $user->rights->commande->creer) + if (!empty($conf->commande->enabled) && $user->rights->commande->creer) { $commande = new Commande($db); @@ -2172,7 +2172,7 @@ if (! empty($conf->global->PRODUCT_ADD_FORM_ADD_TO) && $object->id && ($action = } // Factures - if (! empty($conf->facture->enabled) && $user->rights->facture->creer) + if (!empty($conf->facture->enabled) && $user->rights->facture->creer) { $invoice = new Facture($db); @@ -2238,27 +2238,27 @@ if ($action != 'create' && $action != 'edit' && $action != 'delete') // Documents $objectref = dol_sanitizeFileName($object->ref); - $relativepath = $comref . '/' . $objectref . '.pdf'; - $filedir = $conf->product->dir_output . '/' . $objectref; - $urlsource=$_SERVER["PHP_SELF"]."?id=".$object->id; - $genallowed=$usercanread; - $delallowed=$usercancreate; + $relativepath = $comref.'/'.$objectref.'.pdf'; + $filedir = $conf->product->dir_output.'/'.$objectref; + $urlsource = $_SERVER["PHP_SELF"]."?id=".$object->id; + $genallowed = $usercanread; + $delallowed = $usercancreate; print $formfile->showdocuments($modulepart, $object->ref, $filedir, $urlsource, $genallowed, $delallowed, '', 0, 0, 0, 28, 0, '', 0, '', $object->default_lang, '', $object); - $somethingshown=$formfile->numoffiles; + $somethingshown = $formfile->numoffiles; print '
    '; $MAXEVENT = 10; $morehtmlright = ''; - $morehtmlright.= $langs->trans("SeeAll"); - $morehtmlright.= ''; + $morehtmlright .= $langs->trans("SeeAll"); + $morehtmlright .= ''; // List of actions on element - include_once DOL_DOCUMENT_ROOT . '/core/class/html.formactions.class.php'; + include_once DOL_DOCUMENT_ROOT.'/core/class/html.formactions.class.php'; $formactions = new FormActions($db); - $somethingshown = $formactions->showactions($object, 'product', 0, 1, '', $MAXEVENT, '', $morehtmlright); // Show all action for product + $somethingshown = $formactions->showactions($object, 'product', 0, 1, '', $MAXEVENT, '', $morehtmlright); // Show all action for product print '
    '; } diff --git a/htdocs/product/class/api_products.class.php b/htdocs/product/class/api_products.class.php index 947e4292c1a..f9a4a12b0df 100644 --- a/htdocs/product/class/api_products.class.php +++ b/htdocs/product/class/api_products.class.php @@ -346,7 +346,7 @@ class Products extends DolibarrApi /** * Delete product * - * @param int $id Product ID + * @param int $id Product ID * @return array */ public function delete($id) @@ -673,18 +673,18 @@ class Products extends DolibarrApi throw new RestException(400, 'bad value for parameter id, ref, ref_ext or barcode'); } - $id = (empty($id)?0:$id); + $id = (empty($id) ? 0 : $id); - if(! DolibarrApiAccess::$user->rights->produit->lire) { + if (!DolibarrApiAccess::$user->rights->produit->lire) { throw new RestException(403); } $result = $this->product->fetch($id, $ref, $ref_ext, $barcode); - if(! $result ) { + if (!$result) { throw new RestException(404, 'Product not found'); } - if(! DolibarrApi::_checkAccessToResource('product', $this->product->id)) { + if (!DolibarrApi::_checkAccessToResource('product', $this->product->id)) { throw new RestException(401, 'Access not allowed for login '.DolibarrApiAccess::$user->login); } @@ -765,18 +765,18 @@ class Products extends DolibarrApi throw new RestException(400, 'bad value for parameter id, ref, ref_ext or barcode'); } - $id = (empty($id)?0:$id); + $id = (empty($id) ? 0 : $id); - if(! DolibarrApiAccess::$user->rights->produit->lire) { + if (!DolibarrApiAccess::$user->rights->produit->lire) { throw new RestException(403); } $result = $this->product->fetch($id, $ref, $ref_ext, $barcode); - if(! $result ) { + if (!$result) { throw new RestException(404, 'Product not found'); } - if(! DolibarrApi::_checkAccessToResource('product', $this->product->id)) { + if (!DolibarrApi::_checkAccessToResource('product', $this->product->id)) { throw new RestException(401, 'Access not allowed for login '.DolibarrApiAccess::$user->login); } diff --git a/htdocs/product/class/html.formproduct.class.php b/htdocs/product/class/html.formproduct.class.php index 72fd475e6ae..b7a5111f775 100644 --- a/htdocs/product/class/html.formproduct.class.php +++ b/htdocs/product/class/html.formproduct.class.php @@ -37,11 +37,11 @@ class FormProduct /** * @var string Error code (or message) */ - public $error=''; + public $error = ''; // Cache arrays - public $cache_warehouses=array(); - public $cache_lot=array(); + public $cache_warehouses = array(); + public $cache_lot = array(); /** @@ -76,7 +76,7 @@ class FormProduct { global $conf, $langs; - if (empty($fk_product) && count($this->cache_warehouses)) return 0; // Cache already loaded and we do not want a list with information specific to a product + if (empty($fk_product) && count($this->cache_warehouses)) return 0; // Cache already loaded and we do not want a list with information specific to a product if (is_array($exclude)) $excludeGroups = implode("','", $exclude); @@ -100,59 +100,59 @@ class FormProduct { if (!empty($batch)) { - $sql.= ", pb.qty as stock"; + $sql .= ", pb.qty as stock"; } else { - $sql.= ", ps.reel as stock"; + $sql .= ", ps.reel as stock"; } } elseif ($sumStock) { - $sql.= ", sum(ps.reel) as stock"; + $sql .= ", sum(ps.reel) as stock"; } - $sql.= " FROM ".MAIN_DB_PREFIX."entrepot as e"; - $sql.= " LEFT JOIN ".MAIN_DB_PREFIX."product_stock as ps on ps.fk_entrepot = e.rowid"; + $sql .= " FROM ".MAIN_DB_PREFIX."entrepot as e"; + $sql .= " LEFT JOIN ".MAIN_DB_PREFIX."product_stock as ps on ps.fk_entrepot = e.rowid"; if (!empty($fk_product)) { - $sql.= " AND ps.fk_product = '".$fk_product."'"; + $sql .= " AND ps.fk_product = '".$fk_product."'"; if (!empty($batch)) { - $sql.= " LEFT JOIN ".MAIN_DB_PREFIX."product_batch as pb on pb.fk_product_stock = ps.rowid AND pb.batch = '".$batch."'"; + $sql .= " LEFT JOIN ".MAIN_DB_PREFIX."product_batch as pb on pb.fk_product_stock = ps.rowid AND pb.batch = '".$batch."'"; } } - $sql.= " WHERE e.entity IN (".getEntity('stock').")"; + $sql .= " WHERE e.entity IN (".getEntity('stock').")"; if (count($warehouseStatus)) { - $sql.= " AND e.statut IN (".$this->db->escape(implode(',', $warehouseStatus)).")"; + $sql .= " AND e.statut IN (".$this->db->escape(implode(',', $warehouseStatus)).")"; } else { - $sql.= " AND e.statut = 1"; + $sql .= " AND e.statut = 1"; } - if(!empty($exclude)) $sql.= ' AND e.rowid NOT IN('.$this->db->escape(implode(',', $exclude)).')'; + if (!empty($exclude)) $sql .= ' AND e.rowid NOT IN('.$this->db->escape(implode(',', $exclude)).')'; // minimum stock if ($stockMin !== false) { if (!empty($fk_product)) { if (!empty($batch)) { - $sql .= " AND pb.qty > " . $this->db->escape($stockMin); + $sql .= " AND pb.qty > ".$this->db->escape($stockMin); } else { - $sql .= " AND ps.reel > " . $this->db->escape($stockMin); + $sql .= " AND ps.reel > ".$this->db->escape($stockMin); } } } if ($sumStock && empty($fk_product)) { - $sql.= " GROUP BY e.rowid, e.ref, e.description, e.fk_parent"; + $sql .= " GROUP BY e.rowid, e.ref, e.description, e.fk_parent"; // minimum stock if ($stockMin !== false) { - $sql .= " HAVING sum(ps.reel) > " . $this->db->escape($stockMin); + $sql .= " HAVING sum(ps.reel) > ".$this->db->escape($stockMin); } } - $sql.= " ORDER BY " . $orderBy; + $sql .= " ORDER BY ".$orderBy; dol_syslog(get_class($this).'::loadWarehouses', LOG_DEBUG); $resql = $this->db->query($sql); @@ -164,16 +164,16 @@ class FormProduct { $obj = $this->db->fetch_object($resql); if ($sumStock) $obj->stock = price2num($obj->stock, 5); - $this->cache_warehouses[$obj->rowid]['id'] =$obj->rowid; - $this->cache_warehouses[$obj->rowid]['label']=$obj->label; - $this->cache_warehouses[$obj->rowid]['parent_id']=$obj->fk_parent; + $this->cache_warehouses[$obj->rowid]['id'] = $obj->rowid; + $this->cache_warehouses[$obj->rowid]['label'] = $obj->label; + $this->cache_warehouses[$obj->rowid]['parent_id'] = $obj->fk_parent; $this->cache_warehouses[$obj->rowid]['description'] = $obj->description; $this->cache_warehouses[$obj->rowid]['stock'] = $obj->stock; $i++; } // Full label init - foreach($this->cache_warehouses as $obj_rowid=>$tab) { + foreach ($this->cache_warehouses as $obj_rowid=>$tab) { $this->cache_warehouses[$obj_rowid]['full_label'] = $this->get_parent_path($tab); } @@ -197,11 +197,11 @@ class FormProduct private function get_parent_path($tab, $final_label = '') { //phpcs:enable - if(empty($final_label)) $final_label = $tab['label']; + if (empty($final_label)) $final_label = $tab['label']; - if(empty($tab['parent_id'])) return $final_label; + if (empty($tab['parent_id'])) return $final_label; else { - if(!empty($this->cache_warehouses[$tab['parent_id']])) { + if (!empty($this->cache_warehouses[$tab['parent_id']])) { $final_label = $this->cache_warehouses[$tab['parent_id']]['label'].' >> '.$final_label; return $this->get_parent_path($this->cache_warehouses[$tab['parent_id']], $final_label); } @@ -309,8 +309,8 @@ class FormProduct print '
    '; print (empty($conf->global->PRODUCT_DENY_CHANGE_PRODUCT_TYPE)) ? $form->editfieldkey("Type", 'fk_product_type', $object->type, $object, $usercancreate, $typeformat) : $langs->trans('Type'); print ''; @@ -1695,7 +1695,7 @@ else else { $object->fetch_barcode(); - print $object->barcode_type_label?$object->barcode_type_label:($object->barcode?'
    '.$langs->trans("SetDefaultBarcodeType").'
    ':''); + print $object->barcode_type_label ? $object->barcode_type_label : ($object->barcode ? '
    '.$langs->trans("SetDefaultBarcodeType").'
    ' : ''); } print '
    '; if ($action == 'editbarcode') { - $tmpcode=isset($_POST['barcode'])?GETPOST('barcode'):$object->barcode; - if (empty($tmpcode) && ! empty($modBarCodeProduct->code_auto)) $tmpcode=$modBarCodeProduct->getNextValue($object, $type); + $tmpcode = isset($_POST['barcode']) ?GETPOST('barcode') : $object->barcode; + if (empty($tmpcode) && !empty($modBarCodeProduct->code_auto)) $tmpcode = $modBarCodeProduct->getNextValue($object, $type); print '
    '; print ''; @@ -1731,9 +1731,9 @@ else print '
    '; print $langs->trans("ProductAccountancySellCode"); print ''; - if (! empty($conf->accounting->enabled)) + if (!empty($conf->accounting->enabled)) { - if (! empty($object->accountancy_code_sell)) + if (!empty($object->accountancy_code_sell)) { $accountingaccount = new AccountingAccount($db); $accountingaccount->fetch('', $object->accountancy_code_sell, 1); @@ -1751,9 +1751,9 @@ else print '
    '; print $langs->trans("ProductAccountancySellIntraCode"); print ''; - if (! empty($conf->accounting->enabled)) + if (!empty($conf->accounting->enabled)) { - if (! empty($object->accountancy_code_sell_intra)) + if (!empty($object->accountancy_code_sell_intra)) { $accountingaccount2 = new AccountingAccount($db); $accountingaccount2->fetch('', $object->accountancy_code_sell_intra, 1); @@ -1770,9 +1770,9 @@ else print '
    '; print $langs->trans("ProductAccountancySellExportCode"); print ''; - if (! empty($conf->accounting->enabled)) + if (!empty($conf->accounting->enabled)) { - if (! empty($object->accountancy_code_sell_export)) + if (!empty($object->accountancy_code_sell_export)) { $accountingaccount3 = new AccountingAccount($db); $accountingaccount3->fetch('', $object->accountancy_code_sell_export, 1); @@ -1788,9 +1788,9 @@ else print '
    '; print $langs->trans("ProductAccountancyBuyCode"); print ''; - if (! empty($conf->accounting->enabled)) + if (!empty($conf->accounting->enabled)) { - if (! empty($object->accountancy_code_buy)) + if (!empty($object->accountancy_code_buy)) { $accountingaccount4 = new AccountingAccount($db); $accountingaccount4->fetch('', $object->accountancy_code_buy, 1); @@ -1803,12 +1803,12 @@ else print '
    '.$langs->trans("ManageLotSerial").''; - if (! empty($conf->use_javascript_ajax) && $usercancreate && ! empty($conf->global->MAIN_DIRECT_STATUS_UPDATE)) { + if (!empty($conf->use_javascript_ajax) && $usercancreate && !empty($conf->global->MAIN_DIRECT_STATUS_UPDATE)) { print ajax_object_onoff($object, 'status_batch', 'tobatch', 'ProductStatusOnBatch', 'ProductStatusNotOnBatch'); } else { print $object->getLibStatut(0, 2); @@ -1818,7 +1818,7 @@ else } // Description - print '
    '.$langs->trans("Description").''.(dol_textishtml($object->description)?$object->description:dol_nl2br($object->description, 1, true)).'
    '.$langs->trans("Description").''.(dol_textishtml($object->description) ? $object->description : dol_nl2br($object->description, 1, true)).'
    '.$langs->trans("PublicUrl").''; @@ -1826,13 +1826,13 @@ else print '
    '.$langs->trans("DefaultWarehouse").''; - print (! empty($warehouse->id) ? $warehouse->getNomUrl(1) : ''); + print (!empty($warehouse->id) ? $warehouse->getNomUrl(1) : ''); print '
    '.$langs->trans("Duration").''.$object->duration_value.' '; if ($object->duration_value > 1) { - $dur=array("i"=>$langs->trans("Minute"),"h"=>$langs->trans("Hours"),"d"=>$langs->trans("Days"),"w"=>$langs->trans("Weeks"),"m"=>$langs->trans("Months"),"y"=>$langs->trans("Years")); + $dur = array("i"=>$langs->trans("Minute"), "h"=>$langs->trans("Hours"), "d"=>$langs->trans("Days"), "w"=>$langs->trans("Weeks"), "m"=>$langs->trans("Months"), "y"=>$langs->trans("Years")); } elseif ($object->duration_value > 0) { - $dur=array("i"=>$langs->trans("Minute"),"h"=>$langs->trans("Hour"),"d"=>$langs->trans("Day"),"w"=>$langs->trans("Week"),"m"=>$langs->trans("Month"),"y"=>$langs->trans("Year")); + $dur = array("i"=>$langs->trans("Minute"), "h"=>$langs->trans("Hour"), "d"=>$langs->trans("Day"), "w"=>$langs->trans("Week"), "m"=>$langs->trans("Month"), "y"=>$langs->trans("Year")); } - print (! empty($object->duration_unit) && isset($dur[$object->duration_unit]) ? $langs->trans($dur[$object->duration_unit]) : '')." "; + print (!empty($object->duration_unit) && isset($dur[$object->duration_unit]) ? $langs->trans($dur[$object->duration_unit]) : '')." "; print '
    '.$langs->trans("NetMeasure").''; @@ -1955,7 +1955,7 @@ else } // Unit - if (! empty($conf->global->PRODUCT_USE_UNITS)) + if (!empty($conf->global->PRODUCT_USE_UNITS)) { $unit = $object->getLabelOfUnit(); @@ -1967,7 +1967,7 @@ else } // Custom code - if (! $object->isService() && empty($conf->global->PRODUCT_DISABLE_CUSTOM_INFO)) + if (!$object->isService() && empty($conf->global->PRODUCT_DISABLE_CUSTOM_INFO)) { print '
    '.$langs->trans("CustomCode").''.$object->customcode.'
    '.$langs->trans("Categories").''; print $form->showCategories($object->id, 'product', 1); print "
    '.$langs->trans("NotePrivate").''.(dol_textishtml($object->note_private)?$object->note_private:dol_nl2br($object->note_private, 1, true)).'
    '.$langs->trans("NotePrivate").''.(dol_textishtml($object->note_private) ? $object->note_private : dol_nl2br($object->note_private, 1, true)).'
    '; } else { if ($selected) { - require_once DOL_DOCUMENT_ROOT .'/product/stock/class/entrepot.class.php'; - $warehousestatic=new Entrepot($this->db); + require_once DOL_DOCUMENT_ROOT.'/product/stock/class/entrepot.class.php'; + $warehousestatic = new Entrepot($this->db); $warehousestatic->fetch($selected); print $warehousestatic->getNomUrl(); } else { @@ -357,7 +357,7 @@ class FormProduct $return = ''; // TODO Use a cache - require_once DOL_DOCUMENT_ROOT . '/core/class/cunits.class.php'; + require_once DOL_DOCUMENT_ROOT.'/core/class/cunits.class.php'; $measuringUnits = new CUnits($db); $filter = array(); @@ -375,10 +375,10 @@ class FormProduct dol_print_error($db); return -1; } else { - $return .= ''; if ($adddefault || $adddefault === '') { - $return .= ''; + $return .= ''; } foreach ($measuringUnits->records as $lines) @@ -392,7 +392,7 @@ class FormProduct elseif ($mode == 2 && $lines->scale == $default) $return .= ' selected'; elseif ($mode == 0 && $lines->id == $default) $return .= ' selected'; $return .= '>'; - if ($measuring_style == 'time') $return.= $langs->trans(ucfirst($lines->label)); + if ($measuring_style == 'time') $return .= $langs->trans(ucfirst($lines->label)); else $return .= $langs->trans($lines->label); $return .= ''; } @@ -426,11 +426,11 @@ class FormProduct dol_syslog(get_class($this)."::selectLot $selected, $htmlname, $filterstatus, $empty, $disabled, $fk_product, $fk_entrepot, $empty_label, $forcecombo, $morecss", LOG_DEBUG); - $out=''; + $out = ''; $productIdArray = array(); - if (! is_array($objectLines) || ! count($objectLines)) + if (!is_array($objectLines) || !count($objectLines)) { - if (! empty($fk_product)) $productIdArray[] = $fk_product; + if (!empty($fk_product)) $productIdArray[] = $fk_product; } else { @@ -515,7 +515,7 @@ class FormProduct // check cache already loaded for product id's foreach ($productIdArray as $productId) { - $cacheLoaded = ! empty($this->cache_lot[$productId]) ? true : false; + $cacheLoaded = !empty($this->cache_lot[$productId]) ? true : false; } } if ($cacheLoaded) @@ -528,14 +528,14 @@ class FormProduct $this->cache_lot = array(); $productIdList = implode(',', $productIdArray); $sql = "SELECT pb.batch, pb.rowid, ps.fk_entrepot, pb.qty, e.ref as label, ps.fk_product"; - $sql.= " FROM ".MAIN_DB_PREFIX."product_batch as pb"; - $sql.= " LEFT JOIN ".MAIN_DB_PREFIX."product_stock as ps on ps.rowid = pb.fk_product_stock"; - $sql.= " LEFT JOIN ".MAIN_DB_PREFIX."entrepot as e on e.rowid = ps.fk_entrepot AND e.entity IN (".getEntity('stock').")"; + $sql .= " FROM ".MAIN_DB_PREFIX."product_batch as pb"; + $sql .= " LEFT JOIN ".MAIN_DB_PREFIX."product_stock as ps on ps.rowid = pb.fk_product_stock"; + $sql .= " LEFT JOIN ".MAIN_DB_PREFIX."entrepot as e on e.rowid = ps.fk_entrepot AND e.entity IN (".getEntity('stock').")"; if (!empty($productIdList)) { - $sql.= " WHERE ps.fk_product IN (".$productIdList.")"; + $sql .= " WHERE ps.fk_product IN (".$productIdList.")"; } - $sql.= " ORDER BY e.ref, pb.batch"; + $sql .= " ORDER BY e.ref, pb.batch"; dol_syslog(get_class($this).'::loadLotStock', LOG_DEBUG); $resql = $this->db->query($sql); @@ -546,10 +546,10 @@ class FormProduct while ($i < $num) { $obj = $this->db->fetch_object($resql); - $this->cache_lot[$obj->fk_product][$obj->rowid]['id'] =$obj->rowid; - $this->cache_lot[$obj->fk_product][$obj->rowid]['batch']=$obj->batch; - $this->cache_lot[$obj->fk_product][$obj->rowid]['entrepot_id']=$obj->fk_entrepot; - $this->cache_lot[$obj->fk_product][$obj->rowid]['entrepot_label']=$obj->label; + $this->cache_lot[$obj->fk_product][$obj->rowid]['id'] = $obj->rowid; + $this->cache_lot[$obj->fk_product][$obj->rowid]['batch'] = $obj->batch; + $this->cache_lot[$obj->fk_product][$obj->rowid]['entrepot_id'] = $obj->fk_entrepot; + $this->cache_lot[$obj->fk_product][$obj->rowid]['entrepot_label'] = $obj->label; $this->cache_lot[$obj->fk_product][$obj->rowid]['qty'] = $obj->qty; $i++; } diff --git a/htdocs/product/class/product.class.php b/htdocs/product/class/product.class.php index 4d8afaad9aa..e99d4e46420 100644 --- a/htdocs/product/class/product.class.php +++ b/htdocs/product/class/product.class.php @@ -76,7 +76,7 @@ class Product extends CommonObject */ protected $table_ref_field = 'ref'; - public $regeximgext='\.gif|\.jpg|\.jpeg|\.png|\.bmp|\.xpm|\.xbm'; // See also into images.lib.php + public $regeximgext = '\.gif|\.jpg|\.jpeg|\.png|\.bmp|\.xpm|\.xbm'; // See also into images.lib.php /* * @deprecated @@ -116,7 +116,7 @@ class Product extends CommonObject * * @var float */ - public $price; // Price net + public $price; // Price net /** * Price with tax @@ -146,19 +146,19 @@ class Product extends CommonObject public $price_base_type; //! Arrays for multiprices - public $multiprices=array(); - public $multiprices_ttc=array(); - public $multiprices_base_type=array(); - public $multiprices_min=array(); - public $multiprices_min_ttc=array(); - public $multiprices_tva_tx=array(); - public $multiprices_recuperableonly=array(); + public $multiprices = array(); + public $multiprices_ttc = array(); + public $multiprices_base_type = array(); + public $multiprices_min = array(); + public $multiprices_min_ttc = array(); + public $multiprices_tva_tx = array(); + public $multiprices_recuperableonly = array(); //! Price by quantity arrays public $price_by_qty; - public $prices_by_qty=array(); - public $prices_by_qty_id=array(); - public $prices_by_qty_list=array(); + public $prices_by_qty = array(); + public $prices_by_qty_id = array(); + public $prices_by_qty_list = array(); //! Default VAT code for product (link to code into llx_c_tva but without foreign keys) public $default_vat_code; @@ -167,7 +167,7 @@ class Product extends CommonObject public $tva_tx; //! French VAT NPR (0 or 1) - public $tva_npr=0; + public $tva_npr = 0; //! Other local taxes public $localtax1_tx; @@ -204,12 +204,12 @@ class Product extends CommonObject * * @var int */ - public $seuil_stock_alerte=0; + public $seuil_stock_alerte = 0; /** * Ask for replenishment when $desiredstock < $stock_reel */ - public $desiredstock=0; + public $desiredstock = 0; /* * Service expiration @@ -226,14 +226,14 @@ class Product extends CommonObject * * @var int */ - public $status=0; + public $status = 0; /** * Status indicate whether the product is available for purchase '1' or not '0' * * @var int */ - public $status_buy=0; + public $status_buy = 0; /** * Status indicates whether the product is a finished product '1' or a raw material '0' @@ -247,7 +247,7 @@ class Product extends CommonObject * * @var int */ - public $status_batch=0; + public $status_batch = 0; /** * Customs code @@ -311,15 +311,15 @@ class Product extends CommonObject * * @var array */ - public $barcodes_extra=array(); + public $barcodes_extra = array(); - public $stats_propale=array(); - public $stats_commande=array(); - public $stats_contrat=array(); - public $stats_facture=array(); - public $stats_commande_fournisseur=array(); + public $stats_propale = array(); + public $stats_commande = array(); + public $stats_contrat = array(); + public $stats_facture = array(); + public $stats_commande_fournisseur = array(); - public $multilangs=array(); + public $multilangs = array(); //! Size of image public $imgWidth; @@ -330,7 +330,9 @@ class Product extends CommonObject */ public $date_creation; - + /** + * @var integer|string date_modification + */ public $date_modification; //! Id du fournisseur @@ -339,10 +341,10 @@ class Product extends CommonObject //! Product ID already linked to a reference supplier public $product_id_already_linked; - public $nbphoto=0; + public $nbphoto = 0; //! Contains detail of stock of product into each warehouse - public $stock_warehouse=array(); + public $stock_warehouse = array(); public $oldcopy; @@ -509,10 +511,10 @@ class Product extends CommonObject $this->status_buy = 0; } - $price_ht=0; - $price_ttc=0; - $price_min_ht=0; - $price_min_ttc=0; + $price_ht = 0; + $price_ttc = 0; + $price_min_ht = 0; + $price_min_ttc = 0; // if ($this->price_base_type == 'TTC' && $this->price_ttc > 0) { @@ -539,44 +541,44 @@ class Product extends CommonObject } $this->accountancy_code_buy = trim($this->accountancy_code_buy); - $this->accountancy_code_sell= trim($this->accountancy_code_sell); - $this->accountancy_code_sell_intra= trim($this->accountancy_code_sell_intra); - $this->accountancy_code_sell_export= trim($this->accountancy_code_sell_export); + $this->accountancy_code_sell = trim($this->accountancy_code_sell); + $this->accountancy_code_sell_intra = trim($this->accountancy_code_sell_intra); + $this->accountancy_code_sell_export = trim($this->accountancy_code_sell_export); // Barcode value - $this->barcode=trim($this->barcode); + $this->barcode = trim($this->barcode); // Check parameters if (empty($this->label)) { - $this->error='ErrorMandatoryParametersNotProvided'; + $this->error = 'ErrorMandatoryParametersNotProvided'; return -1; } if (empty($this->ref)) { // Load object modCodeProduct - $module=(! empty($conf->global->PRODUCT_CODEPRODUCT_ADDON)?$conf->global->PRODUCT_CODEPRODUCT_ADDON:'mod_codeproduct_leopard'); + $module = (!empty($conf->global->PRODUCT_CODEPRODUCT_ADDON) ? $conf->global->PRODUCT_CODEPRODUCT_ADDON : 'mod_codeproduct_leopard'); if ($module != 'mod_codeproduct_leopard') // Do not load module file for leopard { if (substr($module, 0, 16) == 'mod_codeproduct_' && substr($module, -3) == 'php') { - $module = substr($module, 0, dol_strlen($module)-4); + $module = substr($module, 0, dol_strlen($module) - 4); } dol_include_once('/core/modules/product/'.$module.'.php'); $modCodeProduct = new $module; - if (! empty($modCodeProduct->code_auto)) { + if (!empty($modCodeProduct->code_auto)) { $this->ref = $modCodeProduct->getNextValue($this, $this->type); } unset($modCodeProduct); } if (empty($this->ref)) { - $this->error='ProductModuleNotSetupForAutoRef'; + $this->error = 'ProductModuleNotSetupForAutoRef'; return -2; } } dol_syslog(get_class($this)."::create ref=".$this->ref." price=".$this->price." price_ttc=".$this->price_ttc." tva_tx=".$this->tva_tx." price_base_type=".$this->price_base_type, LOG_DEBUG); - $now=dol_now(); + $now = dol_now(); $this->db->begin(); @@ -591,9 +593,9 @@ class Product extends CommonObject if ($result >= 0) { $sql = "SELECT count(*) as nb"; - $sql.= " FROM ".MAIN_DB_PREFIX."product"; - $sql.= " WHERE entity IN (".getEntity('product').")"; - $sql.= " AND ref = '" .$this->db->escape($this->ref)."'"; + $sql .= " FROM ".MAIN_DB_PREFIX."product"; + $sql .= " WHERE entity IN (".getEntity('product').")"; + $sql .= " AND ref = '".$this->db->escape($this->ref)."'"; $result = $this->db->query($sql); if ($result) { @@ -601,56 +603,56 @@ class Product extends CommonObject if ($obj->nb == 0) { // Produit non deja existant $sql = "INSERT INTO ".MAIN_DB_PREFIX."product ("; - $sql.= "datec"; - $sql.= ", entity"; - $sql.= ", ref"; - $sql.= ", ref_ext"; - $sql.= ", price_min"; - $sql.= ", price_min_ttc"; - $sql.= ", label"; - $sql.= ", fk_user_author"; - $sql.= ", fk_product_type"; - $sql.= ", price"; - $sql.= ", price_ttc"; - $sql.= ", price_base_type"; - $sql.= ", tobuy"; - $sql.= ", tosell"; - $sql.= ", accountancy_code_buy"; - $sql.= ", accountancy_code_sell"; - $sql.= ", accountancy_code_sell_intra"; - $sql.= ", accountancy_code_sell_export"; - $sql.= ", canvas"; - $sql.= ", finished"; - $sql.= ", tobatch"; - $sql.= ", fk_unit"; - $sql.= ") VALUES ("; - $sql.= "'".$this->db->idate($now)."'"; - $sql.= ", ".$conf->entity; - $sql.= ", '".$this->db->escape($this->ref)."'"; - $sql.= ", ".(! empty($this->ref_ext)?"'".$this->db->escape($this->ref_ext)."'":"null"); - $sql.= ", ".price2num($price_min_ht); - $sql.= ", ".price2num($price_min_ttc); - $sql.= ", ".(! empty($this->label)?"'".$this->db->escape($this->label)."'":"null"); - $sql.= ", ".$user->id; - $sql.= ", ".$this->type; - $sql.= ", ".price2num($price_ht); - $sql.= ", ".price2num($price_ttc); - $sql.= ", '".$this->db->escape($this->price_base_type)."'"; - $sql.= ", ".$this->status; - $sql.= ", ".$this->status_buy; - $sql.= ", '".$this->db->escape($this->accountancy_code_buy)."'"; - $sql.= ", '".$this->db->escape($this->accountancy_code_sell)."'"; - $sql.= ", '".$this->db->escape($this->accountancy_code_sell_intra)."'"; - $sql.= ", '".$this->db->escape($this->accountancy_code_sell_export)."'"; - $sql.= ", '".$this->db->escape($this->canvas)."'"; - $sql.= ", ".((! isset($this->finished) || $this->finished < 0 || $this->finished == '') ? 'null' : (int) $this->finished); - $sql.= ", ".((empty($this->status_batch) || $this->status_batch < 0)? '0':$this->status_batch); - $sql.= ", ".(!$this->fk_unit ? 'NULL' : $this->fk_unit); - $sql.= ")"; + $sql .= "datec"; + $sql .= ", entity"; + $sql .= ", ref"; + $sql .= ", ref_ext"; + $sql .= ", price_min"; + $sql .= ", price_min_ttc"; + $sql .= ", label"; + $sql .= ", fk_user_author"; + $sql .= ", fk_product_type"; + $sql .= ", price"; + $sql .= ", price_ttc"; + $sql .= ", price_base_type"; + $sql .= ", tobuy"; + $sql .= ", tosell"; + $sql .= ", accountancy_code_buy"; + $sql .= ", accountancy_code_sell"; + $sql .= ", accountancy_code_sell_intra"; + $sql .= ", accountancy_code_sell_export"; + $sql .= ", canvas"; + $sql .= ", finished"; + $sql .= ", tobatch"; + $sql .= ", fk_unit"; + $sql .= ") VALUES ("; + $sql .= "'".$this->db->idate($now)."'"; + $sql .= ", ".$conf->entity; + $sql .= ", '".$this->db->escape($this->ref)."'"; + $sql .= ", ".(!empty($this->ref_ext) ? "'".$this->db->escape($this->ref_ext)."'" : "null"); + $sql .= ", ".price2num($price_min_ht); + $sql .= ", ".price2num($price_min_ttc); + $sql .= ", ".(!empty($this->label) ? "'".$this->db->escape($this->label)."'" : "null"); + $sql .= ", ".$user->id; + $sql .= ", ".$this->type; + $sql .= ", ".price2num($price_ht); + $sql .= ", ".price2num($price_ttc); + $sql .= ", '".$this->db->escape($this->price_base_type)."'"; + $sql .= ", ".$this->status; + $sql .= ", ".$this->status_buy; + $sql .= ", '".$this->db->escape($this->accountancy_code_buy)."'"; + $sql .= ", '".$this->db->escape($this->accountancy_code_sell)."'"; + $sql .= ", '".$this->db->escape($this->accountancy_code_sell_intra)."'"; + $sql .= ", '".$this->db->escape($this->accountancy_code_sell_export)."'"; + $sql .= ", '".$this->db->escape($this->canvas)."'"; + $sql .= ", ".((!isset($this->finished) || $this->finished < 0 || $this->finished == '') ? 'null' : (int) $this->finished); + $sql .= ", ".((empty($this->status_batch) || $this->status_batch < 0) ? '0' : $this->status_batch); + $sql .= ", ".(!$this->fk_unit ? 'NULL' : $this->fk_unit); + $sql .= ")"; dol_syslog(get_class($this)."::Create", LOG_DEBUG); $result = $this->db->query($sql); - if ($result ) { + if ($result) { $id = $this->db->last_insert_id(MAIN_DB_PREFIX."product"); if ($id > 0) { @@ -669,19 +671,19 @@ class Product extends CommonObject else { $error++; - $this->error=$this->db->lasterror(); + $this->error = $this->db->lasterror(); } } else { $error++; - $this->error='ErrorFailedToGetInsertedId'; + $this->error = 'ErrorFailedToGetInsertedId'; } } else { $error++; - $this->error=$this->db->lasterror(); + $this->error = $this->db->lasterror(); } } else @@ -695,18 +697,18 @@ class Product extends CommonObject else { $error++; - $this->error=$this->db->lasterror(); + $this->error = $this->db->lasterror(); } - if (! $error && ! $notrigger) { + if (!$error && !$notrigger) { // Call trigger - $result=$this->call_trigger('PRODUCT_CREATE', $user); + $result = $this->call_trigger('PRODUCT_CREATE', $user); if ($result < 0) { $error++; } // End call triggers } - if (! $error) { + if (!$error) { $this->db->commit(); return $this->id; } @@ -733,12 +735,12 @@ class Product extends CommonObject */ public function verify() { - $this->errors=array(); + $this->errors = array(); $result = 0; $this->ref = trim($this->ref); - if (! $this->ref) { + if (!$this->ref) { $this->errors[] = 'ErrorBadRef'; $result = -2; } @@ -777,13 +779,13 @@ class Product extends CommonObject { // phpcs:enable global $conf; - if (! empty($conf->barcode->enabled) && ! empty($conf->global->BARCODE_PRODUCT_ADDON_NUM)) { - $module=strtolower($conf->global->BARCODE_PRODUCT_ADDON_NUM); + if (!empty($conf->barcode->enabled) && !empty($conf->global->BARCODE_PRODUCT_ADDON_NUM)) { + $module = strtolower($conf->global->BARCODE_PRODUCT_ADDON_NUM); - $dirsociete=array_merge(array('/core/modules/barcode/'), $conf->modules_parts['barcode']); + $dirsociete = array_merge(array('/core/modules/barcode/'), $conf->modules_parts['barcode']); foreach ($dirsociete as $dirroot) { - $res=dol_include_once($dirroot.$module.'.php'); + $res = dol_include_once($dirroot.$module.'.php'); if ($res) { break; } } @@ -815,10 +817,10 @@ class Product extends CommonObject { global $langs, $conf, $hookmanager; - $error=0; + $error = 0; // Check parameters - if (! $this->label) { $this->label = 'MISSING LABEL'; + if (!$this->label) { $this->label = 'MISSING LABEL'; } // Clean parameters @@ -837,9 +839,9 @@ class Product extends CommonObject $this->height = price2num($this->height); $this->height_units = trim($this->height_units); // set unit not defined - if ($this->length_units) { $this->width_units = $this->length_units; // Not used yet + if ($this->length_units) { $this->width_units = $this->length_units; // Not used yet } - if ($this->length_units) { $this->height_units = $this->length_units; // Not used yet + if ($this->length_units) { $this->height_units = $this->length_units; // Not used yet } // Automated compute surface and volume if not filled if (empty($this->surface) && !empty($this->length) && !empty($this->width) && $this->length_units == $this->width_units) { @@ -847,7 +849,7 @@ class Product extends CommonObject $this->surface_units = measuring_units_squared($this->length_units); } if (empty($this->volume) && !empty($this->surface_units) && !empty($this->height) && $this->length_units == $this->height_units) { - $this->volume = $this->surface * $this->height; + $this->volume = $this->surface * $this->height; $this->volume_units = measuring_units_cubed($this->height_units); } @@ -885,12 +887,12 @@ class Product extends CommonObject } // Barcode value - $this->barcode=trim($this->barcode); + $this->barcode = trim($this->barcode); $this->accountancy_code_buy = trim($this->accountancy_code_buy); - $this->accountancy_code_sell= trim($this->accountancy_code_sell); - $this->accountancy_code_sell_intra= trim($this->accountancy_code_sell_intra); - $this->accountancy_code_sell_export= trim($this->accountancy_code_sell_export); + $this->accountancy_code_sell = trim($this->accountancy_code_sell); + $this->accountancy_code_sell_intra = trim($this->accountancy_code_sell_intra); + $this->accountancy_code_sell_export = trim($this->accountancy_code_sell_export); $this->db->begin(); @@ -898,14 +900,14 @@ class Product extends CommonObject // Check name is required and codes are ok or unique. // If error, this->errors[] is filled if ($action != 'add') { - $result = $this->verify(); // We don't check when update called during a create because verify was already done + $result = $this->verify(); // We don't check when update called during a create because verify was already done } if ($result >= 0) { if (empty($this->oldcopy)) { - $org=new self($this->db); + $org = new self($this->db); $org->fetch($this->id); - $this->oldcopy=$org; + $this->oldcopy = $org; } // Test if batch management is activated on existing product @@ -924,9 +926,9 @@ class Product extends CommonObject { if ($detail->batch == $valueforundefinedlot || $detail->batch == 'Undefined') { // We discard this line, we will create it later - $sqlclean="DELETE FROM ".MAIN_DB_PREFIX."product_batch WHERE batch in('Undefined', '".$valueforundefinedlot."') AND fk_product_stock = ".$ObjW->id; + $sqlclean = "DELETE FROM ".MAIN_DB_PREFIX."product_batch WHERE batch in('Undefined', '".$valueforundefinedlot."') AND fk_product_stock = ".$ObjW->id; $result = $this->db->query($sqlclean); - if (! $result) { + if (!$result) { dol_print_error($this->db); exit; } @@ -945,7 +947,7 @@ class Product extends CommonObject if ($ObjBatch->create($user, 1) < 0) { $error++; - $this->errors=$ObjBatch->errors; + $this->errors = $ObjBatch->errors; } } } @@ -1073,7 +1075,7 @@ class Product extends CommonObject $comb = new ProductCombination($this->db); foreach ($comb->fetchAllByFkProductParent($this->id) as $currcomb) { - $currcomb->updateProperties($this); + $currcomb->updateProperties($this, $user); } } @@ -1091,18 +1093,18 @@ class Product extends CommonObject if ($this->db->errno() == 'DB_ERROR_RECORD_ALREADY_EXISTS') { $langs->load("errors"); if (empty($conf->barcode->enabled) || empty($this->barcode)) { - $this->error=$langs->trans("Error")." : ".$langs->trans("ErrorProductAlreadyExists", $this->ref); + $this->error = $langs->trans("Error")." : ".$langs->trans("ErrorProductAlreadyExists", $this->ref); } else { - $this->error=$langs->trans("Error")." : ".$langs->trans("ErrorProductBarCodeAlreadyExists", $this->barcode); + $this->error = $langs->trans("Error")." : ".$langs->trans("ErrorProductBarCodeAlreadyExists", $this->barcode); } - $this->errors[]=$this->error; + $this->errors[] = $this->error; $this->db->rollback(); return -1; } else { - $this->error=$langs->trans("Error")." : ".$this->db->error()." - ".$sql; - $this->errors[]=$this->error; + $this->error = $langs->trans("Error")." : ".$this->db->error()." - ".$sql; + $this->errors[] = $this->error; $this->db->rollback(); return -2; } @@ -1127,17 +1129,17 @@ class Product extends CommonObject { // Deprecation warning if ($id > 0) { - dol_syslog(__METHOD__ . " with parameter is deprecated", LOG_WARNING); + dol_syslog(__METHOD__." with parameter is deprecated", LOG_WARNING); } global $conf, $langs; - include_once DOL_DOCUMENT_ROOT . '/core/lib/files.lib.php'; + include_once DOL_DOCUMENT_ROOT.'/core/lib/files.lib.php'; - $error=0; + $error = 0; // Clean parameters if (empty($id)) { - $id=$this->id; + $id = $this->id; } else { $this->fetch($id); } @@ -1156,39 +1158,39 @@ class Product extends CommonObject if (empty($objectisused)) { $this->db->begin(); - if (! $error && empty($notrigger)) { + if (!$error && empty($notrigger)) { // Call trigger - $result=$this->call_trigger('PRODUCT_DELETE', $user); + $result = $this->call_trigger('PRODUCT_DELETE', $user); if ($result < 0) { $error++; } // End call triggers } // Delete from product_batch on product delete - if (! $error) { + if (!$error) { $sql = "DELETE FROM ".MAIN_DB_PREFIX.'product_batch'; - $sql.= " WHERE fk_product_stock IN ("; - $sql.= "SELECT rowid FROM ".MAIN_DB_PREFIX.'product_stock'; - $sql.= " WHERE fk_product = ".$id.")"; + $sql .= " WHERE fk_product_stock IN ("; + $sql .= "SELECT rowid FROM ".MAIN_DB_PREFIX.'product_stock'; + $sql .= " WHERE fk_product = ".$id.")"; $result = $this->db->query($sql); - if (! $result) { + if (!$result) { $error++; $this->errors[] = $this->db->lasterror(); } } // Delete all child tables - if (! $error) { - $elements = array('product_fournisseur_price','product_price','product_lang','categorie_product','product_stock','product_customer_price','product_lot'); // product_batch is done before - foreach($elements as $table) + if (!$error) { + $elements = array('product_fournisseur_price', 'product_price', 'product_lang', 'categorie_product', 'product_stock', 'product_customer_price', 'product_lot'); // product_batch is done before + foreach ($elements as $table) { - if (! $error) { + if (!$error) { $sql = "DELETE FROM ".MAIN_DB_PREFIX.$table; - $sql.= " WHERE fk_product = ".$id; + $sql .= " WHERE fk_product = ".$id; $result = $this->db->query($sql); - if (! $result) { + if (!$result) { $error++; $this->errors[] = $this->db->lasterror(); } @@ -1218,35 +1220,35 @@ class Product extends CommonObject // Delete from product_association if (!$error) { $sql = "DELETE FROM ".MAIN_DB_PREFIX."product_association"; - $sql.= " WHERE fk_product_pere = ".$id." OR fk_product_fils = ".$id; + $sql .= " WHERE fk_product_pere = ".$id." OR fk_product_fils = ".$id; $result = $this->db->query($sql); - if (! $result) { + if (!$result) { $error++; $this->errors[] = $this->db->lasterror(); } } // Delete product - if (! $error) { + if (!$error) { $sqlz = "DELETE FROM ".MAIN_DB_PREFIX."product"; - $sqlz.= " WHERE rowid = ".$id; + $sqlz .= " WHERE rowid = ".$id; $resultz = $this->db->query($sqlz); - if (! $resultz ) { + if (!$resultz) { $error++; $this->errors[] = $this->db->lasterror(); } } - if (! $error) { + if (!$error) { // We remove directory $ref = dol_sanitizeFileName($this->ref); if ($conf->product->dir_output) { - $dir = $conf->product->dir_output . "/" . $ref; + $dir = $conf->product->dir_output."/".$ref; if (file_exists($dir)) { - $res=@dol_delete_dir_recursive($dir); - if (! $res) { + $res = @dol_delete_dir_recursive($dir); + if (!$res) { $this->errors[] = 'ErrorFailToDeleteDir'; $error++; } @@ -1255,25 +1257,25 @@ class Product extends CommonObject } // Remove extrafields - if ((! $error) && (empty($conf->global->MAIN_EXTRAFIELDS_DISABLED))) // For avoid conflicts if trigger used + if ((!$error) && (empty($conf->global->MAIN_EXTRAFIELDS_DISABLED))) // For avoid conflicts if trigger used { - $result=$this->deleteExtraFields(); + $result = $this->deleteExtraFields(); if ($result < 0) { $error++; dol_syslog(get_class($this)."::delete error -4 ".$this->error, LOG_ERR); } } - if (! $error) { + if (!$error) { $this->db->commit(); return 1; } else { - 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); + $this->error .= ($this->error ? ', '.$errmsg : $errmsg); } $this->db->rollback(); return -$error; @@ -1303,75 +1305,75 @@ class Product extends CommonObject { if ($key == $current_lang) { $sql = "SELECT rowid"; - $sql.= " FROM ".MAIN_DB_PREFIX."product_lang"; - $sql.= " WHERE fk_product=".$this->id; - $sql.= " AND lang='".$key."'"; + $sql .= " FROM ".MAIN_DB_PREFIX."product_lang"; + $sql .= " WHERE fk_product=".$this->id; + $sql .= " AND lang='".$key."'"; $result = $this->db->query($sql); if ($this->db->num_rows($result)) // if there is already a description line for this language { $sql2 = "UPDATE ".MAIN_DB_PREFIX."product_lang"; - $sql2.= " SET "; - $sql2.= " label='".$this->db->escape($this->label)."',"; - $sql2.= " description='".$this->db->escape($this->description)."'"; - if (! empty($conf->global->PRODUCT_USE_OTHER_FIELD_IN_TRANSLATION)) { $sql2.= ", note='".$this->db->escape($this->other)."'"; + $sql2 .= " SET "; + $sql2 .= " label='".$this->db->escape($this->label)."',"; + $sql2 .= " description='".$this->db->escape($this->description)."'"; + if (!empty($conf->global->PRODUCT_USE_OTHER_FIELD_IN_TRANSLATION)) { $sql2 .= ", note='".$this->db->escape($this->other)."'"; } - $sql2.= " WHERE fk_product=".$this->id." AND lang='".$this->db->escape($key)."'"; + $sql2 .= " WHERE fk_product=".$this->id." AND lang='".$this->db->escape($key)."'"; } else { $sql2 = "INSERT INTO ".MAIN_DB_PREFIX."product_lang (fk_product, lang, label, description"; - if (! empty($conf->global->PRODUCT_USE_OTHER_FIELD_IN_TRANSLATION)) { $sql2.=", note"; + if (!empty($conf->global->PRODUCT_USE_OTHER_FIELD_IN_TRANSLATION)) { $sql2 .= ", note"; } - $sql2.= ")"; - $sql2.= " VALUES(".$this->id.",'".$this->db->escape($key)."','". $this->db->escape($this->label)."',"; - $sql2.= " '".$this->db->escape($this->description)."'"; - if (! empty($conf->global->PRODUCT_USE_OTHER_FIELD_IN_TRANSLATION)) { $sql2.= ", '".$this->db->escape($this->other)."'"; + $sql2 .= ")"; + $sql2 .= " VALUES(".$this->id.",'".$this->db->escape($key)."','".$this->db->escape($this->label)."',"; + $sql2 .= " '".$this->db->escape($this->description)."'"; + if (!empty($conf->global->PRODUCT_USE_OTHER_FIELD_IN_TRANSLATION)) { $sql2 .= ", '".$this->db->escape($this->other)."'"; } - $sql2.= ")"; + $sql2 .= ")"; } dol_syslog(get_class($this).'::setMultiLangs key = current_lang = '.$key); - if (! $this->db->query($sql2)) { - $this->error=$this->db->lasterror(); + if (!$this->db->query($sql2)) { + $this->error = $this->db->lasterror(); return -1; } } elseif (isset($this->multilangs[$key])) { $sql = "SELECT rowid"; - $sql.= " FROM ".MAIN_DB_PREFIX."product_lang"; - $sql.= " WHERE fk_product=".$this->id; - $sql.= " AND lang='".$key."'"; + $sql .= " FROM ".MAIN_DB_PREFIX."product_lang"; + $sql .= " WHERE fk_product=".$this->id; + $sql .= " AND lang='".$key."'"; $result = $this->db->query($sql); if ($this->db->num_rows($result)) // if there is already a description line for this language { $sql2 = "UPDATE ".MAIN_DB_PREFIX."product_lang"; - $sql2.= " SET "; - $sql2.= " label='".$this->db->escape($this->multilangs["$key"]["label"])."',"; - $sql2.= " description='".$this->db->escape($this->multilangs["$key"]["description"])."'"; - if (! empty($conf->global->PRODUCT_USE_OTHER_FIELD_IN_TRANSLATION)) { $sql2.= ", note='".$this->db->escape($this->multilangs["$key"]["other"])."'"; + $sql2 .= " SET "; + $sql2 .= " label='".$this->db->escape($this->multilangs["$key"]["label"])."',"; + $sql2 .= " description='".$this->db->escape($this->multilangs["$key"]["description"])."'"; + if (!empty($conf->global->PRODUCT_USE_OTHER_FIELD_IN_TRANSLATION)) { $sql2 .= ", note='".$this->db->escape($this->multilangs["$key"]["other"])."'"; } - $sql2.= " WHERE fk_product=".$this->id." AND lang='".$this->db->escape($key)."'"; + $sql2 .= " WHERE fk_product=".$this->id." AND lang='".$this->db->escape($key)."'"; } else { $sql2 = "INSERT INTO ".MAIN_DB_PREFIX."product_lang (fk_product, lang, label, description"; - if (! empty($conf->global->PRODUCT_USE_OTHER_FIELD_IN_TRANSLATION)) { $sql2.=", note"; + if (!empty($conf->global->PRODUCT_USE_OTHER_FIELD_IN_TRANSLATION)) { $sql2 .= ", note"; } - $sql2.= ")"; - $sql2.= " VALUES(".$this->id.",'".$this->db->escape($key)."','". $this->db->escape($this->multilangs["$key"]["label"])."',"; - $sql2.= " '".$this->db->escape($this->multilangs["$key"]["description"])."'"; - if (! empty($conf->global->PRODUCT_USE_OTHER_FIELD_IN_TRANSLATION)) { $sql2.= ", '".$this->db->escape($this->multilangs["$key"]["other"])."'"; + $sql2 .= ")"; + $sql2 .= " VALUES(".$this->id.",'".$this->db->escape($key)."','".$this->db->escape($this->multilangs["$key"]["label"])."',"; + $sql2 .= " '".$this->db->escape($this->multilangs["$key"]["description"])."'"; + if (!empty($conf->global->PRODUCT_USE_OTHER_FIELD_IN_TRANSLATION)) { $sql2 .= ", '".$this->db->escape($this->multilangs["$key"]["other"])."'"; } - $sql2.= ")"; + $sql2 .= ")"; } // We do not save if main fields are empty if ($this->multilangs["$key"]["label"] || $this->multilangs["$key"]["description"]) { - if (! $this->db->query($sql2)) { - $this->error=$this->db->lasterror(); + if (!$this->db->query($sql2)) { + $this->error = $this->db->lasterror(); return -1; } } @@ -1404,7 +1406,7 @@ class Product extends CommonObject public function delMultiLangs($langtodelete, $user) { $sql = "DELETE FROM ".MAIN_DB_PREFIX."product_lang"; - $sql.= " WHERE fk_product=".$this->id." AND lang='".$this->db->escape($langtodelete)."'"; + $sql .= " WHERE fk_product=".$this->id." AND lang='".$this->db->escape($langtodelete)."'"; dol_syslog(get_class($this).'::delMultiLangs', LOG_DEBUG); $result = $this->db->query($sql); @@ -1421,7 +1423,7 @@ class Product extends CommonObject } else { - $this->error=$this->db->lasterror(); + $this->error = $this->db->lasterror(); dol_syslog(get_class($this).'::delMultiLangs error='.$this->error, LOG_ERR); return -1; } @@ -1454,19 +1456,19 @@ class Product extends CommonObject } $sql = "UPDATE ".MAIN_DB_PREFIX.$this->table_element." SET "; - $sql.= "$field = '".$this->db->escape($value)."'"; - $sql.= " WHERE rowid = ".$this->id; + $sql .= "$field = '".$this->db->escape($value)."'"; + $sql .= " WHERE rowid = ".$this->id; dol_syslog(get_class($this)."::".__FUNCTION__." sql=".$sql, LOG_DEBUG); $resql = $this->db->query($sql); if ($resql) { // Call triggers - include_once DOL_DOCUMENT_ROOT . '/core/class/interfaces.class.php'; - $interface=new Interfaces($this->db); - $result=$interface->run_triggers('PRODUCT_MODIFY', $this, $user, $langs, $conf); + include_once DOL_DOCUMENT_ROOT.'/core/class/interfaces.class.php'; + $interface = new Interfaces($this->db); + $result = $interface->run_triggers('PRODUCT_MODIFY', $this, $user, $langs, $conf); if ($result < 0) { - $this->errors=$interface->errors; + $this->errors = $interface->errors; $this->db->rollback(); return -1; } @@ -1479,7 +1481,7 @@ class Product extends CommonObject } else { - $this->error=$this->db->lasterror(); + $this->error = $this->db->lasterror(); $this->db->rollback(); return -1; } @@ -1497,8 +1499,8 @@ class Product extends CommonObject $current_lang = $langs->getDefaultLang(); $sql = "SELECT lang, label, description, note as other"; - $sql.= " FROM ".MAIN_DB_PREFIX."product_lang"; - $sql.= " WHERE fk_product=".$this->id; + $sql .= " FROM ".MAIN_DB_PREFIX."product_lang"; + $sql .= " WHERE fk_product=".$this->id; $result = $this->db->query($sql); if ($result) { @@ -1508,18 +1510,18 @@ class Product extends CommonObject if ($obj->lang == $current_lang) // si on a les traduct. dans la langue courante on les charge en infos principales. { $this->label = $obj->label; - $this->description = $obj->description; + $this->description = $obj->description; $this->other = $obj->other; } $this->multilangs["$obj->lang"]["label"] = $obj->label; - $this->multilangs["$obj->lang"]["description"] = $obj->description; + $this->multilangs["$obj->lang"]["description"] = $obj->description; $this->multilangs["$obj->lang"]["other"] = $obj->other; } return 1; } else { - $this->error="Error: ".$this->db->lasterror()." - ".$sql; + $this->error = "Error: ".$this->db->lasterror()." - ".$sql; return -1; } } @@ -1539,24 +1541,24 @@ class Product extends CommonObject // phpcs:enable global $conf; - $now=dol_now(); + $now = dol_now(); // Clean parameters if (empty($this->price_by_qty)) { - $this->price_by_qty=0; + $this->price_by_qty = 0; } // Add new price $sql = "INSERT INTO ".MAIN_DB_PREFIX."product_price(price_level,date_price, fk_product, fk_user_author, price, price_ttc, price_base_type,tosell, tva_tx, default_vat_code, recuperableonly,"; - $sql.= " localtax1_tx, localtax2_tx, localtax1_type, localtax2_type, price_min,price_min_ttc,price_by_qty,entity,fk_price_expression) "; - $sql.= " VALUES(".($level?$level:1).", '".$this->db->idate($now)."',".$this->id.",".$user->id.",".$this->price.",".$this->price_ttc.",'".$this->db->escape($this->price_base_type)."',".$this->status.",".$this->tva_tx.", ".($this->default_vat_code?("'".$this->db->escape($this->default_vat_code)."'"):"null").",".$this->tva_npr.","; - $sql.= " ".$this->localtax1_tx.", ".$this->localtax2_tx.", '".$this->db->escape($this->localtax1_type)."', '".$this->db->escape($this->localtax2_type)."', ".$this->price_min.",".$this->price_min_ttc.",".$this->price_by_qty.",".$conf->entity.",".($this->fk_price_expression > 0?$this->fk_price_expression:'null'); - $sql.= ")"; + $sql .= " localtax1_tx, localtax2_tx, localtax1_type, localtax2_type, price_min,price_min_ttc,price_by_qty,entity,fk_price_expression) "; + $sql .= " VALUES(".($level ? $level : 1).", '".$this->db->idate($now)."',".$this->id.",".$user->id.",".$this->price.",".$this->price_ttc.",'".$this->db->escape($this->price_base_type)."',".$this->status.",".$this->tva_tx.", ".($this->default_vat_code ? ("'".$this->db->escape($this->default_vat_code)."'") : "null").",".$this->tva_npr.","; + $sql .= " ".$this->localtax1_tx.", ".$this->localtax2_tx.", '".$this->db->escape($this->localtax1_type)."', '".$this->db->escape($this->localtax2_type)."', ".$this->price_min.",".$this->price_min_ttc.",".$this->price_by_qty.",".$conf->entity.",".($this->fk_price_expression > 0 ? $this->fk_price_expression : 'null'); + $sql .= ")"; dol_syslog(get_class($this)."::_log_price", LOG_DEBUG); - $resql=$this->db->query($sql); - if(! $resql) { - $this->error=$this->db->lasterror(); + $resql = $this->db->query($sql); + if (!$resql) { + $this->error = $this->db->lasterror(); dol_print_error($this->db); return -1; } @@ -1579,18 +1581,18 @@ class Product extends CommonObject { // phpcs:enable $sql = "DELETE FROM ".MAIN_DB_PREFIX."product_price_by_qty"; - $sql.= " WHERE fk_product_price=".$rowid; - $resql=$this->db->query($sql); + $sql .= " WHERE fk_product_price=".$rowid; + $resql = $this->db->query($sql); $sql = "DELETE FROM ".MAIN_DB_PREFIX."product_price"; - $sql.= " WHERE rowid=".$rowid; - $resql=$this->db->query($sql); + $sql .= " WHERE rowid=".$rowid; + $resql = $this->db->query($sql); if ($resql) { return 1; } else { - $this->error=$this->db->lasterror(); + $this->error = $this->db->lasterror(); return -1; } } @@ -1612,7 +1614,7 @@ class Product extends CommonObject // Update if prices fields are defined $tva_tx = get_default_tva($thirdparty_seller, $thirdparty_buyer, $this->id); $tva_npr = get_default_npr($thirdparty_seller, $thirdparty_buyer, $this->id); - if (empty($tva_tx)) $tva_npr=0; + if (empty($tva_tx)) $tva_npr = 0; $pu_ht = $this->price; $pu_ttc = $this->price_ttc; @@ -1725,14 +1727,14 @@ class Product extends CommonObject // We do a first seach with a select by searching with couple prodfournprice and qty only (later we will search on triplet qty/product_id/fourn_ref) $sql = "SELECT pfp.rowid, pfp.price as price, pfp.quantity as quantity, pfp.remise_percent,"; - $sql.= " pfp.fk_product, pfp.ref_fourn, pfp.desc_fourn, pfp.fk_soc, pfp.tva_tx, pfp.fk_supplier_price_expression"; - $sql.= " ,pfp.default_vat_code"; - $sql.= " ,pfp.multicurrency_price, pfp.multicurrency_unitprice, pfp.multicurrency_tx, pfp.fk_multicurrency, pfp.multicurrency_code"; - $sql.= " FROM ".MAIN_DB_PREFIX."product_fournisseur_price as pfp"; - $sql.= " WHERE pfp.rowid = ".$prodfournprice; - if ($qty > 0) { $sql.= " AND pfp.quantity <= ".$qty; + $sql .= " pfp.fk_product, pfp.ref_fourn, pfp.desc_fourn, pfp.fk_soc, pfp.tva_tx, pfp.fk_supplier_price_expression"; + $sql .= " ,pfp.default_vat_code"; + $sql .= " ,pfp.multicurrency_price, pfp.multicurrency_unitprice, pfp.multicurrency_tx, pfp.fk_multicurrency, pfp.multicurrency_code"; + $sql .= " FROM ".MAIN_DB_PREFIX."product_fournisseur_price as pfp"; + $sql .= " WHERE pfp.rowid = ".$prodfournprice; + if ($qty > 0) { $sql .= " AND pfp.quantity <= ".$qty; } - $sql.= " ORDER BY pfp.quantity DESC"; + $sql .= " ORDER BY pfp.quantity DESC"; dol_syslog(get_class($this)."::get_buyprice first search by prodfournprice/qty", LOG_DEBUG); $resql = $this->db->query($sql); @@ -1755,41 +1757,41 @@ class Product extends CommonObject } } $this->product_fourn_price_id = $obj->rowid; - $this->buyprice = $obj->price; // deprecated - $this->fourn_pu = $obj->price / $obj->quantity; // Unit price of product of supplier - $this->fourn_price_base_type = 'HT'; // Price base type - $this->fourn_socid = $obj->fk_soc; // Company that offer this price - $this->ref_fourn = $obj->ref_fourn; // deprecated - $this->ref_supplier = $obj->ref_fourn; // Ref supplier - $this->desc_supplier = $obj->desc_fourn; // desc supplier - $this->remise_percent = $obj->remise_percent; // remise percent if present and not typed - $this->vatrate_supplier = $obj->tva_tx; // Vat ref supplier - $this->default_vat_code = $obj->default_vat_code; // Vat code supplier + $this->buyprice = $obj->price; // deprecated + $this->fourn_pu = $obj->price / $obj->quantity; // Unit price of product of supplier + $this->fourn_price_base_type = 'HT'; // Price base type + $this->fourn_socid = $obj->fk_soc; // Company that offer this price + $this->ref_fourn = $obj->ref_fourn; // deprecated + $this->ref_supplier = $obj->ref_fourn; // Ref supplier + $this->desc_supplier = $obj->desc_fourn; // desc supplier + $this->remise_percent = $obj->remise_percent; // remise percent if present and not typed + $this->vatrate_supplier = $obj->tva_tx; // Vat ref supplier + $this->default_vat_code = $obj->default_vat_code; // Vat code supplier $this->fourn_multicurrency_price = $obj->multicurrency_price; $this->fourn_multicurrency_unitprice = $obj->multicurrency_unitprice; $this->fourn_multicurrency_tx = $obj->multicurrency_tx; $this->fourn_multicurrency_id = $obj->fk_multicurrency; $this->fourn_multicurrency_code = $obj->multicurrency_code; - $result=$obj->fk_product; + $result = $obj->fk_product; return $result; } else // If not found { // We do a second search by doing a select again but searching with less reliable criteria: couple qty/id product, and if set fourn_ref or fk_soc. $sql = "SELECT pfp.rowid, pfp.price as price, pfp.quantity as quantity, pfp.fk_soc,"; - $sql.= " pfp.fk_product, pfp.ref_fourn as ref_supplier, pfp.desc_fourn as desc_supplier, pfp.tva_tx, pfp.fk_supplier_price_expression"; - $sql.= " ,pfp.default_vat_code"; - $sql.= " ,pfp.multicurrency_price, pfp.multicurrency_unitprice, pfp.multicurrency_tx, pfp.fk_multicurrency, pfp.multicurrency_code"; - $sql.= " FROM ".MAIN_DB_PREFIX."product_fournisseur_price as pfp"; - $sql.= " WHERE pfp.fk_product = ".$product_id; - if ($fourn_ref != 'none') { $sql.= " AND pfp.ref_fourn = '".$fourn_ref."'"; + $sql .= " pfp.fk_product, pfp.ref_fourn as ref_supplier, pfp.desc_fourn as desc_supplier, pfp.tva_tx, pfp.fk_supplier_price_expression"; + $sql .= " ,pfp.default_vat_code"; + $sql .= " ,pfp.multicurrency_price, pfp.multicurrency_unitprice, pfp.multicurrency_tx, pfp.fk_multicurrency, pfp.multicurrency_code"; + $sql .= " FROM ".MAIN_DB_PREFIX."product_fournisseur_price as pfp"; + $sql .= " WHERE pfp.fk_product = ".$product_id; + if ($fourn_ref != 'none') { $sql .= " AND pfp.ref_fourn = '".$fourn_ref."'"; } - if ($fk_soc > 0) { $sql.= " AND pfp.fk_soc = ".$fk_soc; + if ($fk_soc > 0) { $sql .= " AND pfp.fk_soc = ".$fk_soc; } - if ($qty > 0) { $sql.= " AND pfp.quantity <= ".$qty; + if ($qty > 0) { $sql .= " AND pfp.quantity <= ".$qty; } - $sql.= " ORDER BY pfp.quantity DESC"; - $sql.= " LIMIT 1"; + $sql .= " ORDER BY pfp.quantity DESC"; + $sql .= " LIMIT 1"; dol_syslog(get_class($this)."::get_buyprice second search from qty/ref/product_id", LOG_DEBUG); $resql = $this->db->query($sql); @@ -1812,40 +1814,40 @@ class Product extends CommonObject } } $this->product_fourn_price_id = $obj->rowid; - $this->buyprice = $obj->price; // deprecated - $this->fourn_qty = $obj->quantity; // min quantity for price for a virtual supplier - $this->fourn_pu = $obj->price / $obj->quantity; // Unit price of product for a virtual supplier - $this->fourn_price_base_type = 'HT'; // Price base type for a virtual supplier - $this->fourn_socid = $obj->fk_soc; // Company that offer this price - $this->ref_fourn = $obj->ref_supplier; // deprecated - $this->ref_supplier = $obj->ref_supplier; // Ref supplier - $this->desc_supplier = $obj->desc_supplier; // desc supplier - $this->remise_percent = $obj->remise_percent; // remise percent if present and not typed - $this->vatrate_supplier = $obj->tva_tx; // Vat ref supplier - $this->default_vat_code = $obj->default_vat_code; // Vat code supplier + $this->buyprice = $obj->price; // deprecated + $this->fourn_qty = $obj->quantity; // min quantity for price for a virtual supplier + $this->fourn_pu = $obj->price / $obj->quantity; // Unit price of product for a virtual supplier + $this->fourn_price_base_type = 'HT'; // Price base type for a virtual supplier + $this->fourn_socid = $obj->fk_soc; // Company that offer this price + $this->ref_fourn = $obj->ref_supplier; // deprecated + $this->ref_supplier = $obj->ref_supplier; // Ref supplier + $this->desc_supplier = $obj->desc_supplier; // desc supplier + $this->remise_percent = $obj->remise_percent; // remise percent if present and not typed + $this->vatrate_supplier = $obj->tva_tx; // Vat ref supplier + $this->default_vat_code = $obj->default_vat_code; // Vat code supplier $this->fourn_multicurrency_price = $obj->multicurrency_price; $this->fourn_multicurrency_unitprice = $obj->multicurrency_unitprice; $this->fourn_multicurrency_tx = $obj->multicurrency_tx; $this->fourn_multicurrency_id = $obj->fk_multicurrency; $this->fourn_multicurrency_code = $obj->multicurrency_code; - $result=$obj->fk_product; + $result = $obj->fk_product; return $result; } else { - return -1; // Ce produit n'existe pas avec cet id tarif fournisseur ou existe mais qte insuffisante, ni pour le couple produit/ref fournisseur dans la quantité. + return -1; // Ce produit n'existe pas avec cet id tarif fournisseur ou existe mais qte insuffisante, ni pour le couple produit/ref fournisseur dans la quantité. } } else { - $this->error=$this->db->lasterror(); + $this->error = $this->db->lasterror(); return -3; } } } else { - $this->error=$this->db->lasterror(); + $this->error = $this->db->lasterror(); return -2; } } @@ -1869,33 +1871,33 @@ class Product extends CommonObject */ public function updatePrice($newprice, $newpricebase, $user, $newvat = '', $newminprice = 0, $level = 0, $newnpr = 0, $newpbq = 0, $ignore_autogen = 0, $localtaxes_array = array(), $newdefaultvatcode = '') { - global $conf,$langs; + global $conf, $langs; - $id=$this->id; + $id = $this->id; dol_syslog(get_class($this)."::update_price id=".$id." newprice=".$newprice." newpricebase=".$newpricebase." newminprice=".$newminprice." level=".$level." npr=".$newnpr." newdefaultvatcode=".$newdefaultvatcode); // Clean parameters if (empty($this->tva_tx)) { - $this->tva_tx=0; + $this->tva_tx = 0; } if (empty($newnpr)) { - $newnpr=0; + $newnpr = 0; } // Check parameters if ($newvat == '') { - $newvat=$this->tva_tx; + $newvat = $this->tva_tx; } // If multiprices are enabled, then we check if the current product is subject to price autogeneration // Price will be modified ONLY when the first one is the one that is being modified - if ((!empty($conf->global->PRODUIT_MULTIPRICES) || ! empty($conf->global->PRODUIT_CUSTOMER_PRICES_BY_QTY_MULTIPRICES)) && !$ignore_autogen && $this->price_autogen && ($level == 1)) { + if ((!empty($conf->global->PRODUIT_MULTIPRICES) || !empty($conf->global->PRODUIT_CUSTOMER_PRICES_BY_QTY_MULTIPRICES)) && !$ignore_autogen && $this->price_autogen && ($level == 1)) { return $this->generateMultiprices($user, $newprice, $newpricebase, $newvat, $newnpr, $newpbq); } - if (! empty($newminprice) && ($newminprice > $newprice)) { - $this->error='ErrorPriceCantBeLowerThanMinPrice'; + if (!empty($newminprice) && ($newminprice > $newprice)) { + $this->error = 'ErrorPriceCantBeLowerThanMinPrice'; return -1; } @@ -1912,14 +1914,14 @@ class Product extends CommonObject } else { - $price_min=0; - $price_min_ttc=0; + $price_min = 0; + $price_min_ttc = 0; } } else { $price = price2num($newprice, 'MU'); - $price_ttc = ( $newnpr != 1 ) ? price2num($newprice) * (1 + ($newvat / 100)) : $price; + $price_ttc = ($newnpr != 1) ? price2num($newprice) * (1 + ($newvat / 100)) : $price; $price_ttc = price2num($price_ttc, 'MU'); if ($newminprice !== '' || $newminprice === 0) { @@ -1930,30 +1932,30 @@ class Product extends CommonObject } else { - $price_min=0; - $price_min_ttc=0; + $price_min = 0; + $price_min_ttc = 0; } } //print 'x'.$id.'-'.$newprice.'-'.$newpricebase.'-'.$price.'-'.$price_ttc.'-'.$price_min.'-'.$price_min_ttc; if (count($localtaxes_array) > 0) { - $localtaxtype1=$localtaxes_array['0']; - $localtax1=$localtaxes_array['1']; - $localtaxtype2=$localtaxes_array['2']; - $localtax2=$localtaxes_array['3']; + $localtaxtype1 = $localtaxes_array['0']; + $localtax1 = $localtaxes_array['1']; + $localtaxtype2 = $localtaxes_array['2']; + $localtax2 = $localtaxes_array['3']; } else // old method. deprecated because ot can't retreive type { - $localtaxtype1='0'; - $localtax1=get_localtax($newvat, 1); - $localtaxtype2='0'; - $localtax2=get_localtax($newvat, 2); + $localtaxtype1 = '0'; + $localtax1 = get_localtax($newvat, 1); + $localtaxtype2 = '0'; + $localtax2 = get_localtax($newvat, 2); } if (empty($localtax1)) { - $localtax1=0; // If = '' then = 0 + $localtax1 = 0; // If = '' then = 0 } if (empty($localtax2)) { - $localtax2=0; // If = '' then = 0 + $localtax2 = 0; // If = '' then = 0 } $this->db->begin(); @@ -1961,31 +1963,31 @@ class Product extends CommonObject // Ne pas mettre de quote sur les numeriques decimaux. // Ceci provoque des stockages avec arrondis en base au lieu des valeurs exactes. $sql = "UPDATE ".MAIN_DB_PREFIX."product SET"; - $sql.= " price_base_type='".$newpricebase."',"; - $sql.= " price=".$price.","; - $sql.= " price_ttc=".$price_ttc.","; - $sql.= " price_min=".$price_min.","; - $sql.= " price_min_ttc=".$price_min_ttc.","; - $sql.= " localtax1_tx=".($localtax1>=0?$localtax1:'NULL').","; - $sql.= " localtax2_tx=".($localtax2>=0?$localtax2:'NULL').","; - $sql.= " localtax1_type=".($localtaxtype1!=''?"'".$localtaxtype1."'":"'0'").","; - $sql.= " localtax2_type=".($localtaxtype2!=''?"'".$localtaxtype2."'":"'0'").","; - $sql.= " default_vat_code=".($newdefaultvatcode?"'".$this->db->escape($newdefaultvatcode)."'":"null").","; - $sql.= " tva_tx='".price2num($newvat)."',"; - $sql.= " recuperableonly='".$newnpr."'"; - $sql.= " WHERE rowid = ".$id; + $sql .= " price_base_type='".$newpricebase."',"; + $sql .= " price=".$price.","; + $sql .= " price_ttc=".$price_ttc.","; + $sql .= " price_min=".$price_min.","; + $sql .= " price_min_ttc=".$price_min_ttc.","; + $sql .= " localtax1_tx=".($localtax1 >= 0 ? $localtax1 : 'NULL').","; + $sql .= " localtax2_tx=".($localtax2 >= 0 ? $localtax2 : 'NULL').","; + $sql .= " localtax1_type=".($localtaxtype1 != '' ? "'".$localtaxtype1."'" : "'0'").","; + $sql .= " localtax2_type=".($localtaxtype2 != '' ? "'".$localtaxtype2."'" : "'0'").","; + $sql .= " default_vat_code=".($newdefaultvatcode ? "'".$this->db->escape($newdefaultvatcode)."'" : "null").","; + $sql .= " tva_tx='".price2num($newvat)."',"; + $sql .= " recuperableonly='".$newnpr."'"; + $sql .= " WHERE rowid = ".$id; dol_syslog(get_class($this)."::update_price", LOG_DEBUG); - $resql=$this->db->query($sql); + $resql = $this->db->query($sql); if ($resql) { $this->multiprices[$level] = $price; $this->multiprices_ttc[$level] = $price_ttc; - $this->multiprices_min[$level]= $price_min; - $this->multiprices_min_ttc[$level]= $price_min_ttc; - $this->multiprices_base_type[$level]= $newpricebase; - $this->multiprices_default_vat_code[$level]= $newdefaultvatcode; - $this->multiprices_tva_tx[$level]= $newvat; - $this->multiprices_recuperableonly[$level]= $newnpr; + $this->multiprices_min[$level] = $price_min; + $this->multiprices_min_ttc[$level] = $price_min_ttc; + $this->multiprices_base_type[$level] = $newpricebase; + $this->multiprices_default_vat_code[$level] = $newdefaultvatcode; + $this->multiprices_tva_tx[$level] = $newvat; + $this->multiprices_recuperableonly[$level] = $newnpr; $this->price = $price; $this->price_ttc = $price_ttc; @@ -2004,12 +2006,12 @@ class Product extends CommonObject // Price by quantity $this->price_by_qty = $newpbq; - $this->_log_price($user, $level); // Save price for level into table product_price + $this->_log_price($user, $level); // Save price for level into table product_price - $this->level = $level; // Store level of price edited for trigger + $this->level = $level; // Store level of price edited for trigger // Call trigger - $result=$this->call_trigger('PRODUCT_PRICE_MODIFY', $user); + $result = $this->call_trigger('PRODUCT_PRICE_MODIFY', $user); if ($result < 0) { $this->db->rollback(); return -1; @@ -2114,18 +2116,18 @@ class Product extends CommonObject $this->customcode = $obj->customcode; $this->country_id = $obj->fk_country; - $this->country_code = getCountry($this->country_id, 2, $this->db); + $this->country_code = getCountry($this->country_id, 2, $this->db); $this->price = $obj->price; $this->price_ttc = $obj->price_ttc; $this->price_min = $obj->price_min; $this->price_min_ttc = $obj->price_min_ttc; - $this->price_base_type = $obj->price_base_type; + $this->price_base_type = $obj->price_base_type; $this->cost_price = $obj->cost_price; - $this->default_vat_code = $obj->default_vat_code; + $this->default_vat_code = $obj->default_vat_code; $this->tva_tx = $obj->tva_tx; //! French VAT NPR $this->tva_npr = $obj->tva_npr; - $this->recuperableonly = $obj->tva_npr; // For backward compatibility + $this->recuperableonly = $obj->tva_npr; // For backward compatibility //! Local taxes $this->localtax1_tx = $obj->localtax1_tx; $this->localtax2_tx = $obj->localtax2_tx; @@ -2174,7 +2176,7 @@ class Product extends CommonObject $this->ref_ext = $obj->ref_ext; $this->fk_price_expression = $obj->fk_price_expression; $this->fk_unit = $obj->fk_unit; - $this->price_autogen = $obj->price_autogen; + $this->price_autogen = $obj->price_autogen; $this->db->free($resql); @@ -2183,35 +2185,35 @@ class Product extends CommonObject $this->fetch_optionals(); // multilangs - if (! empty($conf->global->MAIN_MULTILANGS)) { + if (!empty($conf->global->MAIN_MULTILANGS)) { $this->getMultiLangs(); } // Load multiprices array - if (! empty($conf->global->PRODUIT_MULTIPRICES)) // prices per segment + if (!empty($conf->global->PRODUIT_MULTIPRICES)) // prices per segment { - for ($i=1; $i <= $conf->global->PRODUIT_MULTIPRICES_LIMIT; $i++) + for ($i = 1; $i <= $conf->global->PRODUIT_MULTIPRICES_LIMIT; $i++) { $sql = "SELECT price, price_ttc, price_min, price_min_ttc,"; - $sql.= " price_base_type, tva_tx, default_vat_code, tosell, price_by_qty, rowid, recuperableonly"; - $sql.= " FROM ".MAIN_DB_PREFIX."product_price"; - $sql.= " WHERE entity IN (".getEntity('productprice').")"; - $sql.= " AND price_level=".$i; - $sql.= " AND fk_product = ".$this->id; - $sql.= " ORDER BY date_price DESC, rowid DESC"; - $sql.= " LIMIT 1"; + $sql .= " price_base_type, tva_tx, default_vat_code, tosell, price_by_qty, rowid, recuperableonly"; + $sql .= " FROM ".MAIN_DB_PREFIX."product_price"; + $sql .= " WHERE entity IN (".getEntity('productprice').")"; + $sql .= " AND price_level=".$i; + $sql .= " AND fk_product = ".$this->id; + $sql .= " ORDER BY date_price DESC, rowid DESC"; + $sql .= " LIMIT 1"; $resql = $this->db->query($sql); if ($resql) { $result = $this->db->fetch_array($resql); - $this->multiprices[$i]=$result["price"]; - $this->multiprices_ttc[$i]=$result["price_ttc"]; - $this->multiprices_min[$i]=$result["price_min"]; - $this->multiprices_min_ttc[$i]=$result["price_min_ttc"]; - $this->multiprices_base_type[$i]=$result["price_base_type"]; + $this->multiprices[$i] = $result["price"]; + $this->multiprices_ttc[$i] = $result["price_ttc"]; + $this->multiprices_min[$i] = $result["price_min"]; + $this->multiprices_min_ttc[$i] = $result["price_min_ttc"]; + $this->multiprices_base_type[$i] = $result["price_base_type"]; // Next two fields are used only if PRODUIT_MULTIPRICES_USE_VAT_PER_LEVEL is on - $this->multiprices_tva_tx[$i]=$result["tva_tx"]; // TODO Add ' ('.$result['default_vat_code'].')' - $this->multiprices_recuperableonly[$i]=$result["recuperableonly"]; + $this->multiprices_tva_tx[$i] = $result["tva_tx"]; // TODO Add ' ('.$result['default_vat_code'].')' + $this->multiprices_recuperableonly[$i] = $result["recuperableonly"]; // Price by quantity /* @@ -2256,47 +2258,47 @@ class Product extends CommonObject } } } - elseif (! empty($conf->global->PRODUIT_CUSTOMER_PRICES)) // prices per customers + elseif (!empty($conf->global->PRODUIT_CUSTOMER_PRICES)) // prices per customers { // Nothing loaded by default. List may be very long. } - elseif (! empty($conf->global->PRODUIT_CUSTOMER_PRICES_BY_QTY)) // prices per quantity + elseif (!empty($conf->global->PRODUIT_CUSTOMER_PRICES_BY_QTY)) // prices per quantity { $sql = "SELECT price, price_ttc, price_min, price_min_ttc,"; - $sql.= " price_base_type, tva_tx, default_vat_code, tosell, price_by_qty, rowid"; - $sql.= " FROM ".MAIN_DB_PREFIX."product_price"; - $sql.= " WHERE fk_product = ".$this->id; - $sql.= " ORDER BY date_price DESC, rowid DESC"; - $sql.= " LIMIT 1"; + $sql .= " price_base_type, tva_tx, default_vat_code, tosell, price_by_qty, rowid"; + $sql .= " FROM ".MAIN_DB_PREFIX."product_price"; + $sql .= " WHERE fk_product = ".$this->id; + $sql .= " ORDER BY date_price DESC, rowid DESC"; + $sql .= " LIMIT 1"; $resql = $this->db->query($sql); if ($resql) { $result = $this->db->fetch_array($resql); // Price by quantity - $this->prices_by_qty[0]=$result["price_by_qty"]; - $this->prices_by_qty_id[0]=$result["rowid"]; + $this->prices_by_qty[0] = $result["price_by_qty"]; + $this->prices_by_qty_id[0] = $result["rowid"]; // Récuperation de la liste des prix selon qty si flag positionné if ($this->prices_by_qty[0] == 1) { $sql = "SELECT rowid,price, unitprice, quantity, remise_percent, remise, remise, price_base_type"; - $sql.= " FROM ".MAIN_DB_PREFIX."product_price_by_qty"; - $sql.= " WHERE fk_product_price = ".$this->prices_by_qty_id[0]; - $sql.= " ORDER BY quantity ASC"; - $resultat=array(); + $sql .= " FROM ".MAIN_DB_PREFIX."product_price_by_qty"; + $sql .= " WHERE fk_product_price = ".$this->prices_by_qty_id[0]; + $sql .= " ORDER BY quantity ASC"; + $resultat = array(); $resql = $this->db->query($sql); if ($resql) { - $ii=0; - while ($result= $this->db->fetch_array($resql)) { - $resultat[$ii]=array(); - $resultat[$ii]["rowid"]=$result["rowid"]; - $resultat[$ii]["price"]= $result["price"]; - $resultat[$ii]["unitprice"]= $result["unitprice"]; - $resultat[$ii]["quantity"]= $result["quantity"]; - $resultat[$ii]["remise_percent"]= $result["remise_percent"]; + $ii = 0; + while ($result = $this->db->fetch_array($resql)) { + $resultat[$ii] = array(); + $resultat[$ii]["rowid"] = $result["rowid"]; + $resultat[$ii]["price"] = $result["price"]; + $resultat[$ii]["unitprice"] = $result["unitprice"]; + $resultat[$ii]["quantity"] = $result["quantity"]; + $resultat[$ii]["remise_percent"] = $result["remise_percent"]; //$resultat[$ii]["remise"]= $result["remise"]; // deprecated - $resultat[$ii]["price_base_type"]= $result["price_base_type"]; + $resultat[$ii]["price_base_type"] = $result["price_base_type"]; $ii++; } - $this->prices_by_qty_list[0]=$resultat; + $this->prices_by_qty_list[0] = $resultat; } else { @@ -2311,56 +2313,56 @@ class Product extends CommonObject return -1; } } - elseif (! empty($conf->global->PRODUIT_CUSTOMER_PRICES_BY_QTY_MULTIPRICES)) // prices per customer and quantity + elseif (!empty($conf->global->PRODUIT_CUSTOMER_PRICES_BY_QTY_MULTIPRICES)) // prices per customer and quantity { - for ($i=1; $i <= $conf->global->PRODUIT_MULTIPRICES_LIMIT; $i++) + for ($i = 1; $i <= $conf->global->PRODUIT_MULTIPRICES_LIMIT; $i++) { $sql = "SELECT price, price_ttc, price_min, price_min_ttc,"; - $sql.= " price_base_type, tva_tx, default_vat_code, tosell, price_by_qty, rowid, recuperableonly"; - $sql.= " FROM ".MAIN_DB_PREFIX."product_price"; - $sql.= " WHERE entity IN (".getEntity('productprice').")"; - $sql.= " AND price_level=".$i; - $sql.= " AND fk_product = ".$this->id; - $sql.= " ORDER BY date_price DESC, rowid DESC"; - $sql.= " LIMIT 1"; + $sql .= " price_base_type, tva_tx, default_vat_code, tosell, price_by_qty, rowid, recuperableonly"; + $sql .= " FROM ".MAIN_DB_PREFIX."product_price"; + $sql .= " WHERE entity IN (".getEntity('productprice').")"; + $sql .= " AND price_level=".$i; + $sql .= " AND fk_product = ".$this->id; + $sql .= " ORDER BY date_price DESC, rowid DESC"; + $sql .= " LIMIT 1"; $resql = $this->db->query($sql); if ($resql) { $result = $this->db->fetch_array($resql); - $this->multiprices[$i]=$result["price"]; - $this->multiprices_ttc[$i]=$result["price_ttc"]; - $this->multiprices_min[$i]=$result["price_min"]; - $this->multiprices_min_ttc[$i]=$result["price_min_ttc"]; - $this->multiprices_base_type[$i]=$result["price_base_type"]; + $this->multiprices[$i] = $result["price"]; + $this->multiprices_ttc[$i] = $result["price_ttc"]; + $this->multiprices_min[$i] = $result["price_min"]; + $this->multiprices_min_ttc[$i] = $result["price_min_ttc"]; + $this->multiprices_base_type[$i] = $result["price_base_type"]; // Next two fields are used only if PRODUIT_MULTIPRICES_USE_VAT_PER_LEVEL is on - $this->multiprices_tva_tx[$i]=$result["tva_tx"]; // TODO Add ' ('.$result['default_vat_code'].')' - $this->multiprices_recuperableonly[$i]=$result["recuperableonly"]; + $this->multiprices_tva_tx[$i] = $result["tva_tx"]; // TODO Add ' ('.$result['default_vat_code'].')' + $this->multiprices_recuperableonly[$i] = $result["recuperableonly"]; // Price by quantity - $this->prices_by_qty[$i]=$result["price_by_qty"]; - $this->prices_by_qty_id[$i]=$result["rowid"]; + $this->prices_by_qty[$i] = $result["price_by_qty"]; + $this->prices_by_qty_id[$i] = $result["rowid"]; // Récuperation de la liste des prix selon qty si flag positionné if ($this->prices_by_qty[$i] == 1) { $sql = "SELECT rowid, price, unitprice, quantity, remise_percent, remise, price_base_type"; - $sql.= " FROM ".MAIN_DB_PREFIX."product_price_by_qty"; - $sql.= " WHERE fk_product_price = ".$this->prices_by_qty_id[$i]; - $sql.= " ORDER BY quantity ASC"; - $resultat=array(); + $sql .= " FROM ".MAIN_DB_PREFIX."product_price_by_qty"; + $sql .= " WHERE fk_product_price = ".$this->prices_by_qty_id[$i]; + $sql .= " ORDER BY quantity ASC"; + $resultat = array(); $resql = $this->db->query($sql); if ($resql) { - $ii=0; - while ($result= $this->db->fetch_array($resql)) { - $resultat[$ii]=array(); - $resultat[$ii]["rowid"]=$result["rowid"]; - $resultat[$ii]["price"]= $result["price"]; - $resultat[$ii]["unitprice"]= $result["unitprice"]; - $resultat[$ii]["quantity"]= $result["quantity"]; - $resultat[$ii]["remise_percent"]= $result["remise_percent"]; - $resultat[$ii]["remise"]= $result["remise"]; // deprecated - $resultat[$ii]["price_base_type"]= $result["price_base_type"]; + $ii = 0; + while ($result = $this->db->fetch_array($resql)) { + $resultat[$ii] = array(); + $resultat[$ii]["rowid"] = $result["rowid"]; + $resultat[$ii]["price"] = $result["price"]; + $resultat[$ii]["unitprice"] = $result["unitprice"]; + $resultat[$ii]["quantity"] = $result["quantity"]; + $resultat[$ii]["remise_percent"] = $result["remise_percent"]; + $resultat[$ii]["remise"] = $result["remise"]; // deprecated + $resultat[$ii]["price_base_type"] = $result["price_base_type"]; $ii++; } - $this->prices_by_qty_list[$i]=$resultat; + $this->prices_by_qty_list[$i] = $resultat; } else { @@ -2494,34 +2496,34 @@ class Product extends CommonObject global $user; $sql = "SELECT COUNT(DISTINCT p.fk_soc) as nb_suppliers, COUNT(DISTINCT p.rowid) as nb,"; - $sql.= " COUNT(pd.rowid) as nb_rows, SUM(pd.qty) as qty"; - $sql.= " FROM ".MAIN_DB_PREFIX."supplier_proposaldet as pd"; - $sql.= ", ".MAIN_DB_PREFIX."supplier_proposal as p"; - $sql.= ", ".MAIN_DB_PREFIX."societe as s"; + $sql .= " COUNT(pd.rowid) as nb_rows, SUM(pd.qty) as qty"; + $sql .= " FROM ".MAIN_DB_PREFIX."supplier_proposaldet as pd"; + $sql .= ", ".MAIN_DB_PREFIX."supplier_proposal as p"; + $sql .= ", ".MAIN_DB_PREFIX."societe as s"; if (!$user->rights->societe->client->voir && !$socid) { $sql .= ", ".MAIN_DB_PREFIX."societe_commerciaux as sc"; } - $sql.= " WHERE p.rowid = pd.fk_supplier_proposal"; - $sql.= " AND p.fk_soc = s.rowid"; - $sql.= " AND p.entity IN (".getEntity('supplier_proposal').")"; - $sql.= " AND pd.fk_product = ".$this->id; - if (!$user->rights->societe->client->voir && !$socid) { $sql .= " AND p.fk_soc = sc.fk_soc AND sc.fk_user = " .$user->id; + $sql .= " WHERE p.rowid = pd.fk_supplier_proposal"; + $sql .= " AND p.fk_soc = s.rowid"; + $sql .= " AND p.entity IN (".getEntity('supplier_proposal').")"; + $sql .= " AND pd.fk_product = ".$this->id; + if (!$user->rights->societe->client->voir && !$socid) { $sql .= " AND p.fk_soc = sc.fk_soc AND sc.fk_user = ".$user->id; } //$sql.= " AND pr.fk_statut != 0"; - if ($socid > 0) { $sql.= " AND p.fk_soc = ".$socid; + if ($socid > 0) { $sql .= " AND p.fk_soc = ".$socid; } $result = $this->db->query($sql); - if ($result ) { - $obj=$this->db->fetch_object($result); - $this->stats_proposal_supplier['suppliers']=$obj->nb_suppliers; - $this->stats_proposal_supplier['nb']=$obj->nb; - $this->stats_proposal_supplier['rows']=$obj->nb_rows; - $this->stats_proposal_supplier['qty']=$obj->qty?$obj->qty:0; + if ($result) { + $obj = $this->db->fetch_object($result); + $this->stats_proposal_supplier['suppliers'] = $obj->nb_suppliers; + $this->stats_proposal_supplier['nb'] = $obj->nb; + $this->stats_proposal_supplier['rows'] = $obj->nb_rows; + $this->stats_proposal_supplier['qty'] = $obj->qty ? $obj->qty : 0; return 1; } else { - $this->error=$this->db->error(); + $this->error = $this->db->error(); return -1; } } @@ -2583,10 +2585,10 @@ class Product extends CommonObject if ($fatherData['incdec']) { $pFather->load_stats_commande($socid, $filtrestatut); - $this->stats_commande['customers']+=$pFather->stats_commande['customers']; - $this->stats_commande['nb']+=$pFather->stats_commande['nb']; - $this->stats_commande['rows']+=$pFather->stats_commande['rows']; - $this->stats_commande['qty']+=$pFather->stats_commande['qty'] * $qtyCoef; + $this->stats_commande['customers'] += $pFather->stats_commande['customers']; + $this->stats_commande['nb'] += $pFather->stats_commande['nb']; + $this->stats_commande['rows'] += $pFather->stats_commande['rows']; + $this->stats_commande['qty'] += $pFather->stats_commande['qty'] * $qtyCoef; } } } @@ -2595,8 +2597,8 @@ class Product extends CommonObject // If stock decrease is on invoice validation, the theorical stock continue to // count the orders to ship in theorical stock when some are already removed b invoice validation. // If option DECREASE_ONLY_UNINVOICEDPRODUCTS is on, we make a compensation. - if (! empty($conf->global->STOCK_CALCULATE_ON_BILL)) { - if (! empty($conf->global->DECREASE_ONLY_UNINVOICEDPRODUCTS)) { + if (!empty($conf->global->STOCK_CALCULATE_ON_BILL)) { + if (!empty($conf->global->DECREASE_ONLY_UNINVOICEDPRODUCTS)) { $adeduire = 0; $sql = "SELECT sum(fd.qty) as count FROM ".MAIN_DB_PREFIX."facturedet fd "; $sql .= " JOIN ".MAIN_DB_PREFIX."facture f ON fd.fk_facture = f.rowid "; @@ -2606,7 +2608,7 @@ class Product extends CommonObject dol_syslog(__METHOD__.":: sql $sql", LOG_NOTICE); $resql = $this->db->query($sql); - if ($resql ) { + if ($resql) { if ($this->db->num_rows($resql) > 0) { $obj = $this->db->fetch_object($resql); $adeduire += $obj->count; @@ -2621,7 +2623,7 @@ class Product extends CommonObject } else { - $this->error=$this->db->error(); + $this->error = $this->db->error(); return -1; } } @@ -2638,42 +2640,42 @@ class Product extends CommonObject public function load_stats_commande_fournisseur($socid = 0, $filtrestatut = '', $forVirtualStock = 0) { // phpcs:enable - global $conf,$user; + global $conf, $user; $sql = "SELECT COUNT(DISTINCT c.fk_soc) as nb_suppliers, COUNT(DISTINCT c.rowid) as nb,"; - $sql.= " COUNT(cd.rowid) as nb_rows, SUM(cd.qty) as qty"; - $sql.= " FROM ".MAIN_DB_PREFIX."commande_fournisseurdet as cd"; - $sql.= ", ".MAIN_DB_PREFIX."commande_fournisseur as c"; - $sql.= ", ".MAIN_DB_PREFIX."societe as s"; + $sql .= " COUNT(cd.rowid) as nb_rows, SUM(cd.qty) as qty"; + $sql .= " FROM ".MAIN_DB_PREFIX."commande_fournisseurdet as cd"; + $sql .= ", ".MAIN_DB_PREFIX."commande_fournisseur as c"; + $sql .= ", ".MAIN_DB_PREFIX."societe as s"; if (!$user->rights->societe->client->voir && !$socid && !$forVirtualStock) { - $sql.= ", ".MAIN_DB_PREFIX."societe_commerciaux as sc"; + $sql .= ", ".MAIN_DB_PREFIX."societe_commerciaux as sc"; } - $sql.= " WHERE c.rowid = cd.fk_commande"; - $sql.= " AND c.fk_soc = s.rowid"; - $sql.= " AND c.entity IN (".getEntity('supplier_order').")"; - $sql.= " AND cd.fk_product = ".$this->id; + $sql .= " WHERE c.rowid = cd.fk_commande"; + $sql .= " AND c.fk_soc = s.rowid"; + $sql .= " AND c.entity IN (".getEntity('supplier_order').")"; + $sql .= " AND cd.fk_product = ".$this->id; if (!$user->rights->societe->client->voir && !$socid && !$forVirtualStock) { - $sql.= " AND c.fk_soc = sc.fk_soc AND sc.fk_user = " .$user->id; + $sql .= " AND c.fk_soc = sc.fk_soc AND sc.fk_user = ".$user->id; } if ($socid > 0) { - $sql.= " AND c.fk_soc = ".$socid; + $sql .= " AND c.fk_soc = ".$socid; } if ($filtrestatut != '') { - $sql.= " AND c.fk_statut in (".$filtrestatut.")"; // Peut valoir 0 + $sql .= " AND c.fk_statut in (".$filtrestatut.")"; // Peut valoir 0 } $result = $this->db->query($sql); - if ($result ) { - $obj=$this->db->fetch_object($result); - $this->stats_commande_fournisseur['suppliers']=$obj->nb_suppliers; - $this->stats_commande_fournisseur['nb']=$obj->nb; - $this->stats_commande_fournisseur['rows']=$obj->nb_rows; - $this->stats_commande_fournisseur['qty']=$obj->qty?$obj->qty:0; + if ($result) { + $obj = $this->db->fetch_object($result); + $this->stats_commande_fournisseur['suppliers'] = $obj->nb_suppliers; + $this->stats_commande_fournisseur['nb'] = $obj->nb; + $this->stats_commande_fournisseur['rows'] = $obj->nb_rows; + $this->stats_commande_fournisseur['qty'] = $obj->qty ? $obj->qty : 0; return 1; } else { - $this->error=$this->db->error().' sql='.$sql; + $this->error = $this->db->error().' sql='.$sql; return -1; } } @@ -2682,12 +2684,13 @@ class Product extends CommonObject /** * Charge tableau des stats expedition client pour le produit/service * - * @param int $socid Id societe pour filtrer sur une societe - * @param string $filtrestatut Id statut pour filtrer sur un statut - * @param int $forVirtualStock Ignore rights filter for virtual stock calculation. - * @return array Tableau des stats + * @param int $socid Id societe pour filtrer sur une societe + * @param string $filtrestatut Id statut pour filtrer sur un statut + * @param int $forVirtualStock Ignore rights filter for virtual stock calculation. + * @param string $filterShipmentStatus [=''] Ids shipment status separated by comma + * @return int <0 if KO, >0 if OK (Tableau des stats) */ - public function load_stats_sending($socid = 0, $filtrestatut = '', $forVirtualStock = 0) + public function load_stats_sending($socid = 0, $filtrestatut = '', $forVirtualStock = 0, $filterShipmentStatus = '') { // phpcs:enable global $conf,$user; @@ -2717,6 +2720,7 @@ class Product extends CommonObject if ($filtrestatut <> '') { $sql.= " AND c.fk_statut in (".$filtrestatut.")"; } + if (!empty($filterShipmentStatus)) $sql.= " AND e.fk_statut IN (" . $filterShipmentStatus . ")"; $result = $this->db->query($sql); if ($result ) { @@ -2767,38 +2771,38 @@ class Product extends CommonObject public function load_stats_reception($socid = 0, $filtrestatut = '', $forVirtualStock = 0) { // phpcs:enable - global $conf,$user; + global $conf, $user; $sql = "SELECT COUNT(DISTINCT cf.fk_soc) as nb_customers, COUNT(DISTINCT cf.rowid) as nb,"; - $sql.= " COUNT(fd.rowid) as nb_rows, SUM(fd.qty) as qty"; - $sql.= " FROM ".MAIN_DB_PREFIX."commande_fournisseur_dispatch as fd"; - $sql.= ", ".MAIN_DB_PREFIX."commande_fournisseur as cf"; - $sql.= ", ".MAIN_DB_PREFIX."societe as s"; - if (!$user->rights->societe->client->voir && !$socid && !$forVirtualStock) { $sql.= ", ".MAIN_DB_PREFIX."societe_commerciaux as sc"; + $sql .= " COUNT(fd.rowid) as nb_rows, SUM(fd.qty) as qty"; + $sql .= " FROM ".MAIN_DB_PREFIX."commande_fournisseur_dispatch as fd"; + $sql .= ", ".MAIN_DB_PREFIX."commande_fournisseur as cf"; + $sql .= ", ".MAIN_DB_PREFIX."societe as s"; + if (!$user->rights->societe->client->voir && !$socid && !$forVirtualStock) { $sql .= ", ".MAIN_DB_PREFIX."societe_commerciaux as sc"; } - $sql.= " WHERE cf.rowid = fd.fk_commande"; - $sql.= " AND cf.fk_soc = s.rowid"; - $sql.= " AND cf.entity IN (".getEntity('supplier_order').")"; - $sql.= " AND fd.fk_product = ".$this->id; - if (!$user->rights->societe->client->voir && !$socid && !$forVirtualStock) { $sql.= " AND cf.fk_soc = sc.fk_soc AND sc.fk_user = " .$user->id; + $sql .= " WHERE cf.rowid = fd.fk_commande"; + $sql .= " AND cf.fk_soc = s.rowid"; + $sql .= " AND cf.entity IN (".getEntity('supplier_order').")"; + $sql .= " AND fd.fk_product = ".$this->id; + if (!$user->rights->societe->client->voir && !$socid && !$forVirtualStock) { $sql .= " AND cf.fk_soc = sc.fk_soc AND sc.fk_user = ".$user->id; } - if ($socid > 0) { $sql.= " AND cf.fk_soc = ".$socid; + if ($socid > 0) { $sql .= " AND cf.fk_soc = ".$socid; } - if ($filtrestatut <> '') { $sql.= " AND cf.fk_statut in (".$filtrestatut.")"; + if ($filtrestatut <> '') { $sql .= " AND cf.fk_statut in (".$filtrestatut.")"; } $result = $this->db->query($sql); - if ($result ) { - $obj=$this->db->fetch_object($result); - $this->stats_reception['suppliers']=$obj->nb_customers; - $this->stats_reception['nb']=$obj->nb; - $this->stats_reception['rows']=$obj->nb_rows; - $this->stats_reception['qty']=$obj->qty?$obj->qty:0; + if ($result) { + $obj = $this->db->fetch_object($result); + $this->stats_reception['suppliers'] = $obj->nb_customers; + $this->stats_reception['nb'] = $obj->nb; + $this->stats_reception['rows'] = $obj->nb_rows; + $this->stats_reception['qty'] = $obj->qty ? $obj->qty : 0; return 1; } else { - $this->error=$this->db->error(); + $this->error = $this->db->error(); return -1; } } @@ -2956,19 +2960,19 @@ class Product extends CommonObject global $user; $sql = "SELECT COUNT(DISTINCT f.fk_soc) as nb_suppliers, COUNT(DISTINCT f.rowid) as nb,"; - $sql.= " COUNT(fd.rowid) as nb_rows, SUM(fd.qty) as qty"; - $sql.= " FROM ".MAIN_DB_PREFIX."facture_fourn_det as fd"; - $sql.= ", ".MAIN_DB_PREFIX."facture_fourn as f"; - $sql.= ", ".MAIN_DB_PREFIX."societe as s"; + $sql .= " COUNT(fd.rowid) as nb_rows, SUM(fd.qty) as qty"; + $sql .= " FROM ".MAIN_DB_PREFIX."facture_fourn_det as fd"; + $sql .= ", ".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"; + $sql .= ", ".MAIN_DB_PREFIX."societe_commerciaux as sc"; } - $sql.= " WHERE f.rowid = fd.fk_facture_fourn"; - $sql.= " AND f.fk_soc = s.rowid"; - $sql.= " AND f.entity IN (".getEntity('facture_fourn').")"; - $sql.= " AND fd.fk_product = ".$this->id; + $sql .= " WHERE f.rowid = fd.fk_facture_fourn"; + $sql .= " AND f.fk_soc = s.rowid"; + $sql .= " AND f.entity IN (".getEntity('facture_fourn').")"; + $sql .= " AND fd.fk_product = ".$this->id; if (!$user->rights->societe->client->voir && !$socid) { - $sql.= " AND f.fk_soc = sc.fk_soc AND sc.fk_user = " .$user->id; + $sql .= " AND f.fk_soc = sc.fk_soc AND sc.fk_user = ".$user->id; } //$sql.= " AND f.fk_statut != 0"; if ($socid > 0) { @@ -2976,17 +2980,17 @@ class Product extends CommonObject } $result = $this->db->query($sql); - if ($result ) { - $obj=$this->db->fetch_object($result); - $this->stats_facture_fournisseur['suppliers']=$obj->nb_suppliers; - $this->stats_facture_fournisseur['nb']=$obj->nb; - $this->stats_facture_fournisseur['rows']=$obj->nb_rows; - $this->stats_facture_fournisseur['qty']=$obj->qty?$obj->qty:0; + if ($result) { + $obj = $this->db->fetch_object($result); + $this->stats_facture_fournisseur['suppliers'] = $obj->nb_suppliers; + $this->stats_facture_fournisseur['nb'] = $obj->nb; + $this->stats_facture_fournisseur['rows'] = $obj->nb_rows; + $this->stats_facture_fournisseur['qty'] = $obj->qty ? $obj->qty : 0; return 1; } else { - $this->error=$this->db->error(); + $this->error = $this->db->error(); return -1; } } @@ -3011,17 +3015,17 @@ class Product extends CommonObject { $arr = $this->db->fetch_array($resql); if ($mode == 'byunit') { - $tab[$arr[1]] = $arr[0]; // 1st field + $tab[$arr[1]] = $arr[0]; // 1st field } if ($mode == 'bynumber') { - $tab[$arr[1]] = $arr[2]; // 3rd field + $tab[$arr[1]] = $arr[2]; // 3rd field } $i++; } } else { - $this->error=$this->db->error().' sql='.$sql; + $this->error = $this->db->error().' sql='.$sql; return -1; } @@ -3031,16 +3035,16 @@ class Product extends CommonObject } else { - $month=12; // We imagine we are at end of year, so we get last 12 month before, so all correct year. + $month = 12; // We imagine we are at end of year, so we get last 12 month before, so all correct year. } $result = array(); - for ($j = 0 ; $j < 12 ; $j++) + for ($j = 0; $j < 12; $j++) { - $idx=ucfirst(dol_trunc(dol_print_date(dol_mktime(12, 0, 0, $month, 1, $year), "%b"), 3, 'right', 'UTF-8', 1)); - $monthnum=sprintf("%02s", $month); + $idx = ucfirst(dol_trunc(dol_print_date(dol_mktime(12, 0, 0, $month, 1, $year), "%b"), 3, 'right', 'UTF-8', 1)); + $monthnum = sprintf("%02s", $month); - $result[$j] = array($idx,isset($tab[$year.$month])?$tab[$year.$month]:0); + $result[$j] = array($idx, isset($tab[$year.$month]) ? $tab[$year.$month] : 0); // $result[$j] = array($monthnum,isset($tab[$year.$month])?$tab[$year.$month]:0); $month = "0".($month - 1); @@ -3076,35 +3080,35 @@ class Product extends CommonObject $sql = "SELECT sum(d.qty), date_format(f.datef, '%Y%m')"; if ($mode == 'bynumber') { - $sql.= ", count(DISTINCT f.rowid)"; + $sql .= ", count(DISTINCT f.rowid)"; } - $sql.= " FROM ".MAIN_DB_PREFIX."facturedet as d, ".MAIN_DB_PREFIX."facture as f, ".MAIN_DB_PREFIX."societe as s"; + $sql .= " FROM ".MAIN_DB_PREFIX."facturedet as d, ".MAIN_DB_PREFIX."facture as f, ".MAIN_DB_PREFIX."societe as s"; if ($filteronproducttype >= 0) { - $sql.=", ".MAIN_DB_PREFIX."product as p"; + $sql .= ", ".MAIN_DB_PREFIX."product as p"; } if (!$user->rights->societe->client->voir && !$socid) { - $sql.= ", ".MAIN_DB_PREFIX."societe_commerciaux as sc"; + $sql .= ", ".MAIN_DB_PREFIX."societe_commerciaux as sc"; } - $sql.= " WHERE f.rowid = d.fk_facture"; + $sql .= " WHERE f.rowid = d.fk_facture"; if ($this->id > 0) { - $sql.= " AND d.fk_product =".$this->id; + $sql .= " AND d.fk_product =".$this->id; } else { - $sql.=" AND d.fk_product > 0"; + $sql .= " AND d.fk_product > 0"; } if ($filteronproducttype >= 0) { - $sql.= " AND p.rowid = d.fk_product AND p.fk_product_type =".$filteronproducttype; + $sql .= " AND p.rowid = d.fk_product AND p.fk_product_type =".$filteronproducttype; } - $sql.= " AND f.fk_soc = s.rowid"; - $sql.= " AND f.entity IN (".getEntity('invoice').")"; + $sql .= " AND f.fk_soc = s.rowid"; + $sql .= " AND f.entity IN (".getEntity('invoice').")"; if (!$user->rights->societe->client->voir && !$socid) { - $sql.= " AND f.fk_soc = sc.fk_soc AND sc.fk_user = " .$user->id; + $sql .= " AND f.fk_soc = sc.fk_soc AND sc.fk_user = ".$user->id; } if ($socid > 0) { - $sql.= " AND f.fk_soc = $socid"; + $sql .= " AND f.fk_soc = $socid"; } - $sql.=$morefilter; - $sql.= " GROUP BY date_format(f.datef,'%Y%m')"; - $sql.= " ORDER BY date_format(f.datef,'%Y%m') DESC"; + $sql .= $morefilter; + $sql .= " GROUP BY date_format(f.datef,'%Y%m')"; + $sql .= " ORDER BY date_format(f.datef,'%Y%m') DESC"; return $this->_get_stats($sql, $mode, $year); } @@ -3129,35 +3133,35 @@ class Product extends CommonObject $sql = "SELECT sum(d.qty), date_format(f.datef, '%Y%m')"; if ($mode == 'bynumber') { - $sql.= ", count(DISTINCT f.rowid)"; + $sql .= ", count(DISTINCT f.rowid)"; } - $sql.= " FROM ".MAIN_DB_PREFIX."facture_fourn_det as d, ".MAIN_DB_PREFIX."facture_fourn as f, ".MAIN_DB_PREFIX."societe as s"; + $sql .= " FROM ".MAIN_DB_PREFIX."facture_fourn_det as d, ".MAIN_DB_PREFIX."facture_fourn as f, ".MAIN_DB_PREFIX."societe as s"; if ($filteronproducttype >= 0) { - $sql.=", ".MAIN_DB_PREFIX."product as p"; + $sql .= ", ".MAIN_DB_PREFIX."product as p"; } if (!$user->rights->societe->client->voir && !$socid) { - $sql.= ", ".MAIN_DB_PREFIX."societe_commerciaux as sc"; + $sql .= ", ".MAIN_DB_PREFIX."societe_commerciaux as sc"; } - $sql.= " WHERE f.rowid = d.fk_facture_fourn"; + $sql .= " WHERE f.rowid = d.fk_facture_fourn"; if ($this->id > 0) { - $sql.= " AND d.fk_product =".$this->id; + $sql .= " AND d.fk_product =".$this->id; } else { - $sql.=" AND d.fk_product > 0"; + $sql .= " AND d.fk_product > 0"; } if ($filteronproducttype >= 0) { - $sql.= " AND p.rowid = d.fk_product AND p.fk_product_type =".$filteronproducttype; + $sql .= " AND p.rowid = d.fk_product AND p.fk_product_type =".$filteronproducttype; } - $sql.= " AND f.fk_soc = s.rowid"; - $sql.= " AND f.entity IN (".getEntity('facture_fourn').")"; + $sql .= " AND f.fk_soc = s.rowid"; + $sql .= " AND f.entity IN (".getEntity('facture_fourn').")"; if (!$user->rights->societe->client->voir && !$socid) { - $sql.= " AND f.fk_soc = sc.fk_soc AND sc.fk_user = " .$user->id; + $sql .= " AND f.fk_soc = sc.fk_soc AND sc.fk_user = ".$user->id; } if ($socid > 0) { - $sql.= " AND f.fk_soc = $socid"; + $sql .= " AND f.fk_soc = $socid"; } - $sql.=$morefilter; - $sql.= " GROUP BY date_format(f.datef,'%Y%m')"; - $sql.= " ORDER BY date_format(f.datef,'%Y%m') DESC"; + $sql .= $morefilter; + $sql .= " GROUP BY date_format(f.datef,'%Y%m')"; + $sql .= " ORDER BY date_format(f.datef,'%Y%m') DESC"; return $this->_get_stats($sql, $mode, $year); } @@ -3181,35 +3185,35 @@ class Product extends CommonObject $sql = "SELECT sum(d.qty), date_format(p.datep, '%Y%m')"; if ($mode == 'bynumber') { - $sql.= ", count(DISTINCT p.rowid)"; + $sql .= ", count(DISTINCT p.rowid)"; } - $sql.= " FROM ".MAIN_DB_PREFIX."propaldet as d, ".MAIN_DB_PREFIX."propal as p, ".MAIN_DB_PREFIX."societe as s"; + $sql .= " FROM ".MAIN_DB_PREFIX."propaldet as d, ".MAIN_DB_PREFIX."propal as p, ".MAIN_DB_PREFIX."societe as s"; if ($filteronproducttype >= 0) { - $sql.=", ".MAIN_DB_PREFIX."product as prod"; + $sql .= ", ".MAIN_DB_PREFIX."product as prod"; } if (!$user->rights->societe->client->voir && !$socid) { $sql .= ", ".MAIN_DB_PREFIX."societe_commerciaux as sc"; } - $sql.= " WHERE p.rowid = d.fk_propal"; + $sql .= " WHERE p.rowid = d.fk_propal"; if ($this->id > 0) { - $sql.= " AND d.fk_product =".$this->id; + $sql .= " AND d.fk_product =".$this->id; } else { - $sql.=" AND d.fk_product > 0"; + $sql .= " AND d.fk_product > 0"; } if ($filteronproducttype >= 0) { - $sql.= " AND prod.rowid = d.fk_product AND prod.fk_product_type =".$filteronproducttype; + $sql .= " AND prod.rowid = d.fk_product AND prod.fk_product_type =".$filteronproducttype; } - $sql.= " AND p.fk_soc = s.rowid"; - $sql.= " AND p.entity IN (".getEntity('propal').")"; + $sql .= " AND p.fk_soc = s.rowid"; + $sql .= " AND p.entity IN (".getEntity('propal').")"; if (!$user->rights->societe->client->voir && !$socid) { - $sql.= " AND p.fk_soc = sc.fk_soc AND sc.fk_user = " .$user->id; + $sql .= " AND p.fk_soc = sc.fk_soc AND sc.fk_user = ".$user->id; } if ($socid > 0) { - $sql.= " AND p.fk_soc = ".$socid; + $sql .= " AND p.fk_soc = ".$socid; } - $sql.=$morefilter; - $sql.= " GROUP BY date_format(p.datep,'%Y%m')"; - $sql.= " ORDER BY date_format(p.datep,'%Y%m') DESC"; + $sql .= $morefilter; + $sql .= " GROUP BY date_format(p.datep,'%Y%m')"; + $sql .= " ORDER BY date_format(p.datep,'%Y%m') DESC"; return $this->_get_stats($sql, $mode, $year); } @@ -3233,35 +3237,35 @@ class Product extends CommonObject $sql = "SELECT sum(d.qty), date_format(p.date_valid, '%Y%m')"; if ($mode == 'bynumber') { - $sql.= ", count(DISTINCT p.rowid)"; + $sql .= ", count(DISTINCT p.rowid)"; } - $sql.= " FROM ".MAIN_DB_PREFIX."supplier_proposaldet as d, ".MAIN_DB_PREFIX."supplier_proposal as p, ".MAIN_DB_PREFIX."societe as s"; + $sql .= " FROM ".MAIN_DB_PREFIX."supplier_proposaldet as d, ".MAIN_DB_PREFIX."supplier_proposal as p, ".MAIN_DB_PREFIX."societe as s"; if ($filteronproducttype >= 0) { - $sql.=", ".MAIN_DB_PREFIX."product as prod"; + $sql .= ", ".MAIN_DB_PREFIX."product as prod"; } if (!$user->rights->societe->client->voir && !$socid) { $sql .= ", ".MAIN_DB_PREFIX."societe_commerciaux as sc"; } - $sql.= " WHERE p.rowid = d.fk_supplier_proposal"; + $sql .= " WHERE p.rowid = d.fk_supplier_proposal"; if ($this->id > 0) { - $sql.= " AND d.fk_product =".$this->id; + $sql .= " AND d.fk_product =".$this->id; } else { - $sql.=" AND d.fk_product > 0"; + $sql .= " AND d.fk_product > 0"; } if ($filteronproducttype >= 0) { - $sql.= " AND prod.rowid = d.fk_product AND prod.fk_product_type =".$filteronproducttype; + $sql .= " AND prod.rowid = d.fk_product AND prod.fk_product_type =".$filteronproducttype; } - $sql.= " AND p.fk_soc = s.rowid"; - $sql.= " AND p.entity IN (".getEntity('supplier_proposal').")"; + $sql .= " AND p.fk_soc = s.rowid"; + $sql .= " AND p.entity IN (".getEntity('supplier_proposal').")"; if (!$user->rights->societe->client->voir && !$socid) { - $sql.= " AND p.fk_soc = sc.fk_soc AND sc.fk_user = " .$user->id; + $sql .= " AND p.fk_soc = sc.fk_soc AND sc.fk_user = ".$user->id; } if ($socid > 0) { - $sql.= " AND p.fk_soc = ".$socid; + $sql .= " AND p.fk_soc = ".$socid; } - $sql.=$morefilter; - $sql.= " GROUP BY date_format(p.date_valid,'%Y%m')"; - $sql.= " ORDER BY date_format(p.date_valid,'%Y%m') DESC"; + $sql .= $morefilter; + $sql .= " GROUP BY date_format(p.date_valid,'%Y%m')"; + $sql .= " ORDER BY date_format(p.date_valid,'%Y%m') DESC"; return $this->_get_stats($sql, $mode, $year); } @@ -3284,35 +3288,35 @@ class Product extends CommonObject $sql = "SELECT sum(d.qty), date_format(c.date_commande, '%Y%m')"; if ($mode == 'bynumber') { - $sql.= ", count(DISTINCT c.rowid)"; + $sql .= ", count(DISTINCT c.rowid)"; } - $sql.= " FROM ".MAIN_DB_PREFIX."commandedet as d, ".MAIN_DB_PREFIX."commande as c, ".MAIN_DB_PREFIX."societe as s"; + $sql .= " FROM ".MAIN_DB_PREFIX."commandedet as d, ".MAIN_DB_PREFIX."commande as c, ".MAIN_DB_PREFIX."societe as s"; if ($filteronproducttype >= 0) { - $sql.=", ".MAIN_DB_PREFIX."product as p"; + $sql .= ", ".MAIN_DB_PREFIX."product as p"; } if (!$user->rights->societe->client->voir && !$socid) { $sql .= ", ".MAIN_DB_PREFIX."societe_commerciaux as sc"; } - $sql.= " WHERE c.rowid = d.fk_commande"; + $sql .= " WHERE c.rowid = d.fk_commande"; if ($this->id > 0) { - $sql.= " AND d.fk_product =".$this->id; + $sql .= " AND d.fk_product =".$this->id; } else { - $sql.=" AND d.fk_product > 0"; + $sql .= " AND d.fk_product > 0"; } if ($filteronproducttype >= 0) { - $sql.= " AND p.rowid = d.fk_product AND p.fk_product_type =".$filteronproducttype; + $sql .= " AND p.rowid = d.fk_product AND p.fk_product_type =".$filteronproducttype; } - $sql.= " AND c.fk_soc = s.rowid"; - $sql.= " AND c.entity IN (".getEntity('commande').")"; + $sql .= " AND c.fk_soc = s.rowid"; + $sql .= " AND c.entity IN (".getEntity('commande').")"; if (!$user->rights->societe->client->voir && !$socid) { - $sql.= " AND c.fk_soc = sc.fk_soc AND sc.fk_user = " .$user->id; + $sql .= " AND c.fk_soc = sc.fk_soc AND sc.fk_user = ".$user->id; } if ($socid > 0) { - $sql.= " AND c.fk_soc = ".$socid; + $sql .= " AND c.fk_soc = ".$socid; } - $sql.=$morefilter; - $sql.= " GROUP BY date_format(c.date_commande,'%Y%m')"; - $sql.= " ORDER BY date_format(c.date_commande,'%Y%m') DESC"; + $sql .= $morefilter; + $sql .= " GROUP BY date_format(c.date_commande,'%Y%m')"; + $sql .= " ORDER BY date_format(c.date_commande,'%Y%m') DESC"; return $this->_get_stats($sql, $mode, $year); } @@ -3335,35 +3339,35 @@ class Product extends CommonObject $sql = "SELECT sum(d.qty), date_format(c.date_commande, '%Y%m')"; if ($mode == 'bynumber') { - $sql.= ", count(DISTINCT c.rowid)"; + $sql .= ", count(DISTINCT c.rowid)"; } - $sql.= " FROM ".MAIN_DB_PREFIX."commande_fournisseurdet as d, ".MAIN_DB_PREFIX."commande_fournisseur as c, ".MAIN_DB_PREFIX."societe as s"; + $sql .= " FROM ".MAIN_DB_PREFIX."commande_fournisseurdet as d, ".MAIN_DB_PREFIX."commande_fournisseur as c, ".MAIN_DB_PREFIX."societe as s"; if ($filteronproducttype >= 0) { - $sql.=", ".MAIN_DB_PREFIX."product as p"; + $sql .= ", ".MAIN_DB_PREFIX."product as p"; } if (!$user->rights->societe->client->voir && !$socid) { $sql .= ", ".MAIN_DB_PREFIX."societe_commerciaux as sc"; } - $sql.= " WHERE c.rowid = d.fk_commande"; + $sql .= " WHERE c.rowid = d.fk_commande"; if ($this->id > 0) { - $sql.= " AND d.fk_product =".$this->id; + $sql .= " AND d.fk_product =".$this->id; } else { - $sql.=" AND d.fk_product > 0"; + $sql .= " AND d.fk_product > 0"; } if ($filteronproducttype >= 0) { - $sql.= " AND p.rowid = d.fk_product AND p.fk_product_type =".$filteronproducttype; + $sql .= " AND p.rowid = d.fk_product AND p.fk_product_type =".$filteronproducttype; } - $sql.= " AND c.fk_soc = s.rowid"; - $sql.= " AND c.entity IN (".getEntity('supplier_order').")"; + $sql .= " AND c.fk_soc = s.rowid"; + $sql .= " AND c.entity IN (".getEntity('supplier_order').")"; if (!$user->rights->societe->client->voir && !$socid) { - $sql.= " AND c.fk_soc = sc.fk_soc AND sc.fk_user = " .$user->id; + $sql .= " AND c.fk_soc = sc.fk_soc AND sc.fk_user = ".$user->id; } if ($socid > 0) { - $sql.= " AND c.fk_soc = ".$socid; + $sql .= " AND c.fk_soc = ".$socid; } - $sql.=$morefilter; - $sql.= " GROUP BY date_format(c.date_commande,'%Y%m')"; - $sql.= " ORDER BY date_format(c.date_commande,'%Y%m') DESC"; + $sql .= $morefilter; + $sql .= " GROUP BY date_format(c.date_commande,'%Y%m')"; + $sql .= " ORDER BY date_format(c.date_commande,'%Y%m') DESC"; return $this->_get_stats($sql, $mode, $year); } @@ -3436,17 +3440,17 @@ class Product extends CommonObject { // phpcs:enable // Clean parameters - if (! is_numeric($id_pere)) { - $id_pere=0; + if (!is_numeric($id_pere)) { + $id_pere = 0; } - if (! is_numeric($id_fils)) { - $id_fils=0; + if (!is_numeric($id_fils)) { + $id_fils = 0; } - if (! is_numeric($incdec)) { - $incdec=0; + if (!is_numeric($incdec)) { + $incdec = 0; } - $result=$this->del_sousproduit($id_pere, $id_fils); + $result = $this->del_sousproduit($id_pere, $id_fils); if ($result < 0) { return $result; } @@ -3454,7 +3458,7 @@ class Product extends CommonObject // Check not already father of id_pere (to avoid father -> child -> father links) $sql = 'SELECT fk_product_pere from '.MAIN_DB_PREFIX.'product_association'; $sql .= ' WHERE fk_product_pere = '.$id_fils.' AND fk_product_fils = '.$id_pere; - if (! $this->db->query($sql)) { + if (!$this->db->query($sql)) { dol_print_error($this->db); return -1; } @@ -3463,15 +3467,15 @@ class Product extends CommonObject $result = $this->db->query($sql); if ($result) { $num = $this->db->num_rows($result); - if($num > 0) { - $this->error="isFatherOfThis"; + if ($num > 0) { + $this->error = "isFatherOfThis"; return -1; } else { $sql = 'INSERT INTO '.MAIN_DB_PREFIX.'product_association(fk_product_pere,fk_product_fils,qty,incdec)'; $sql .= ' VALUES ('.$id_pere.', '.$id_fils.', '.$qty.', '.$incdec.')'; - if (! $this->db->query($sql)) { + if (!$this->db->query($sql)) { dol_print_error($this->db); return -1; } @@ -3498,22 +3502,22 @@ class Product extends CommonObject { // phpcs:enable // Clean parameters - if (! is_numeric($id_pere)) { - $id_pere=0; + if (!is_numeric($id_pere)) { + $id_pere = 0; } - if (! is_numeric($id_fils)) { - $id_fils=0; + if (!is_numeric($id_fils)) { + $id_fils = 0; } - if (! is_numeric($incdec)) { - $incdec=1; + if (!is_numeric($incdec)) { + $incdec = 1; } - if (! is_numeric($qty)) { - $qty=1; + if (!is_numeric($qty)) { + $qty = 1; } $sql = 'UPDATE '.MAIN_DB_PREFIX.'product_association SET '; - $sql.= 'qty='.$qty; - $sql.= ',incdec='.$incdec; + $sql .= 'qty='.$qty; + $sql .= ',incdec='.$incdec; $sql .= ' WHERE fk_product_pere='.$id_pere.' AND fk_product_fils='.$id_fils; if (!$this->db->query($sql)) { @@ -3537,19 +3541,19 @@ class Product extends CommonObject public function del_sousproduit($fk_parent, $fk_child) { // phpcs:enable - if (! is_numeric($fk_parent)) { - $fk_parent=0; + if (!is_numeric($fk_parent)) { + $fk_parent = 0; } - if (! is_numeric($fk_child)) { - $fk_child=0; + if (!is_numeric($fk_child)) { + $fk_child = 0; } $sql = "DELETE FROM ".MAIN_DB_PREFIX."product_association"; - $sql.= " WHERE fk_product_pere = ".$fk_parent; - $sql.= " AND fk_product_fils = ".$fk_child; + $sql .= " WHERE fk_product_pere = ".$fk_parent; + $sql .= " AND fk_product_fils = ".$fk_child; dol_syslog(get_class($this).'::del_sousproduit', LOG_DEBUG); - if (! $this->db->query($sql)) { + if (!$this->db->query($sql)) { dol_print_error($this->db); return -1; } @@ -3569,15 +3573,15 @@ class Product extends CommonObject { // phpcs:enable $sql = "SELECT fk_product_pere, qty, incdec"; - $sql.= " FROM ".MAIN_DB_PREFIX."product_association"; - $sql.= " WHERE fk_product_pere = '".$fk_parent."'"; - $sql.= " AND fk_product_fils = '".$fk_child."'"; + $sql .= " FROM ".MAIN_DB_PREFIX."product_association"; + $sql .= " WHERE fk_product_pere = '".$fk_parent."'"; + $sql .= " AND fk_product_fils = '".$fk_child."'"; $result = $this->db->query($sql); if ($result) { $num = $this->db->num_rows($result); - if($num > 0) { + if ($num > 0) { $obj = $this->db->fetch_object($result); $this->is_sousproduit_qty = $obj->qty; $this->is_sousproduit_incdec = $obj->incdec; @@ -3682,7 +3686,7 @@ class Product extends CommonObject } else { - $this->error=$this->db->lasterror(); + $this->error = $this->db->lasterror(); return -1; } } @@ -3695,7 +3699,7 @@ class Product extends CommonObject } else { - $this->error=$this->db->lasterror(); + $this->error = $this->db->lasterror(); return -2; } } @@ -3715,14 +3719,14 @@ class Product extends CommonObject $list = array(); $sql = "SELECT DISTINCT p.fk_soc"; - $sql.= " FROM ".MAIN_DB_PREFIX."product_fournisseur_price as p"; - $sql.= " WHERE p.fk_product = ".$this->id; - $sql.= " AND p.entity = ".$conf->entity; + $sql .= " FROM ".MAIN_DB_PREFIX."product_fournisseur_price as p"; + $sql .= " WHERE p.fk_product = ".$this->id; + $sql .= " AND p.entity = ".$conf->entity; $result = $this->db->query($sql); if ($result) { $num = $this->db->num_rows($result); - $i=0; + $i = 0; while ($i < $num) { $obj = $this->db->fetch_object($result); @@ -3836,11 +3840,11 @@ class Product extends CommonObject $this->db->begin(); $sql = 'INSERT INTO '.MAIN_DB_PREFIX.'product_association (fk_product_pere, fk_product_fils, qty)'; - $sql.= " SELECT ".$toId.", fk_product_fils, qty FROM ".MAIN_DB_PREFIX."product_association"; - $sql.= " WHERE fk_product_pere = ".$fromId; + $sql .= " SELECT ".$toId.", fk_product_fils, qty FROM ".MAIN_DB_PREFIX."product_association"; + $sql .= " WHERE fk_product_pere = ".$fromId; dol_syslog(get_class($this).'::clone_association', LOG_DEBUG); - if (! $this->db->query($sql)) { + if (!$this->db->query($sql)) { $this->db->rollback(); return -1; } @@ -3862,7 +3866,7 @@ class Product extends CommonObject // phpcs:enable $this->db->begin(); - $now=dol_now(); + $now = dol_now(); // les fournisseurs /*$sql = "INSERT ".MAIN_DB_PREFIX."product_fournisseur (" @@ -3879,14 +3883,14 @@ class Product extends CommonObject // les prix de fournisseurs. $sql = "INSERT ".MAIN_DB_PREFIX."product_fournisseur_price ("; - $sql.= " datec, fk_product, fk_soc, price, quantity, fk_user)"; - $sql.= " SELECT '".$this->db->idate($now)."', ".$toId. ", fk_soc, price, quantity, fk_user"; - $sql.= " FROM ".MAIN_DB_PREFIX."product_fournisseur_price"; - $sql.= " WHERE fk_product = ".$fromId; + $sql .= " datec, fk_product, fk_soc, price, quantity, fk_user)"; + $sql .= " SELECT '".$this->db->idate($now)."', ".$toId.", fk_soc, price, quantity, fk_user"; + $sql .= " FROM ".MAIN_DB_PREFIX."product_fournisseur_price"; + $sql .= " WHERE fk_product = ".$fromId; dol_syslog(get_class($this).'::clone_fournisseurs', LOG_DEBUG); - $resql=$this->db->query($sql); - if (! $resql) { + $resql = $this->db->query($sql); + if (!$resql) { $this->db->rollback(); return -1; } @@ -3955,7 +3959,7 @@ class Product extends CommonObject // Recursive call if there is childs to child if (is_array($desc_pere['childs'])) { //print 'YYY We go down for '.$desc_pere[3]." -> \n"; - $this->fetch_prod_arbo($desc_pere['childs'], $compl_path.$desc_pere[3]." -> ", $desc_pere[1]*$multiply, $level+1, $id); + $this->fetch_prod_arbo($desc_pere['childs'], $compl_path.$desc_pere[3]." -> ", $desc_pere[1] * $multiply, $level + 1, $id); } } } @@ -3974,7 +3978,7 @@ class Product extends CommonObject // phpcs:enable $this->res = array(); if (isset($this->sousprods) && is_array($this->sousprods)) { - foreach($this->sousprods as $prod_name => $desc_product) + foreach ($this->sousprods as $prod_name => $desc_product) { if (is_array($desc_product)) { $this->fetch_prod_arbo($desc_product, "", $multiply, 1, $this->id); } @@ -3994,8 +3998,8 @@ class Product extends CommonObject $nb = 0; $sql = "SELECT COUNT(pa.rowid) as nb"; - $sql.= " FROM ".MAIN_DB_PREFIX."product_association as pa"; - $sql.= " WHERE pa.fk_product_fils = ".$this->id." OR pa.fk_product_pere = ".$this->id; + $sql .= " FROM ".MAIN_DB_PREFIX."product_association as pa"; + $sql .= " WHERE pa.fk_product_fils = ".$this->id." OR pa.fk_product_pere = ".$this->id; $resql = $this->db->query($sql); if ($resql) { $obj = $this->db->fetch_object($resql); @@ -4019,7 +4023,7 @@ class Product extends CommonObject { $nb = 0; $sql = "SELECT count(rowid) as nb FROM ".MAIN_DB_PREFIX."product_attribute_combination WHERE fk_product_parent = ".$this->id; - $sql.= " AND entity IN (".getEntity('product').")"; + $sql .= " AND entity IN (".getEntity('product').")"; $resql = $this->db->query($sql); if ($resql) { @@ -4041,7 +4045,7 @@ class Product extends CommonObject { global $conf; if (!empty($conf->variants->enabled)) { - $sql = "SELECT rowid FROM " . MAIN_DB_PREFIX . "product_attribute_combination WHERE fk_product_child = " . $this->id . " AND entity IN (" . getEntity('product') . ")"; + $sql = "SELECT rowid FROM ".MAIN_DB_PREFIX."product_attribute_combination WHERE fk_product_child = ".$this->id." AND entity IN (".getEntity('product').")"; $query = $this->db->query($sql); @@ -4067,14 +4071,14 @@ class Product extends CommonObject public function getFather() { $sql = "SELECT p.rowid, p.label as label, p.ref as ref, pa.fk_product_pere as id, p.fk_product_type, pa.qty, pa.incdec, p.entity"; - $sql.= " FROM ".MAIN_DB_PREFIX."product_association as pa,"; - $sql.= " ".MAIN_DB_PREFIX."product as p"; - $sql.= " WHERE p.rowid = pa.fk_product_pere"; - $sql.= " AND pa.fk_product_fils = ".$this->id; + $sql .= " FROM ".MAIN_DB_PREFIX."product_association as pa,"; + $sql .= " ".MAIN_DB_PREFIX."product as p"; + $sql .= " WHERE p.rowid = pa.fk_product_pere"; + $sql .= " AND pa.fk_product_fils = ".$this->id; $res = $this->db->query($sql); if ($res) { - $prods = array (); + $prods = array(); while ($record = $this->db->fetch_array($res)) { // $record['id'] = $record['rowid'] = id of father @@ -4083,8 +4087,8 @@ class Product extends CommonObject $prods[$record['id']]['label'] = $record['label']; $prods[$record['id']]['qty'] = $record['qty']; $prods[$record['id']]['incdec'] = $record['incdec']; - $prods[$record['id']]['fk_product_type'] = $record['fk_product_type']; - $prods[$record['id']]['entity'] = $record['entity']; + $prods[$record['id']]['fk_product_type'] = $record['fk_product_type']; + $prods[$record['id']]['entity'] = $record['entity']; } return $prods; } @@ -4109,31 +4113,31 @@ class Product extends CommonObject global $alreadyfound; $sql = "SELECT p.rowid, p.label as label, pa.qty as qty, pa.fk_product_fils as id, p.fk_product_type, pa.incdec"; - $sql.= " FROM ".MAIN_DB_PREFIX."product as p"; - $sql.= ", ".MAIN_DB_PREFIX."product_association as pa"; - $sql.= " WHERE p.rowid = pa.fk_product_fils"; - $sql.= " AND pa.fk_product_pere = ".$id; - $sql.= " AND pa.fk_product_fils != ".$id; // This should not happens, it is to avoid infinite loop if it happens + $sql .= " FROM ".MAIN_DB_PREFIX."product as p"; + $sql .= ", ".MAIN_DB_PREFIX."product_association as pa"; + $sql .= " WHERE p.rowid = pa.fk_product_fils"; + $sql .= " AND pa.fk_product_pere = ".$id; + $sql .= " AND pa.fk_product_fils != ".$id; // This should not happens, it is to avoid infinite loop if it happens dol_syslog(get_class($this).'::getChildsArbo id='.$id.' level='.$level, LOG_DEBUG); - if ($level == 1) { $alreadyfound=array($id=>1); // We init array of found object to start of tree, so if we found it later (should not happened), we stop immediatly + if ($level == 1) { $alreadyfound = array($id=>1); // We init array of found object to start of tree, so if we found it later (should not happened), we stop immediatly } // Protection against infinite loop if ($level > 30) { return array(); } - $res = $this->db->query($sql); + $res = $this->db->query($sql); if ($res) { $prods = array(); while ($rec = $this->db->fetch_array($res)) { - if (! empty($alreadyfound[$rec['rowid']])) { + if (!empty($alreadyfound[$rec['rowid']])) { dol_syslog(get_class($this).'::getChildsArbo the product id='.$rec['rowid'].' was already found at a higher level in tree. We discard to avoid infinite loop', LOG_WARNING); continue; } - $alreadyfound[$rec['rowid']]=1; - $prods[$rec['rowid']]= array( + $alreadyfound[$rec['rowid']] = 1; + $prods[$rec['rowid']] = array( 0=>$rec['rowid'], 1=>$rec['qty'], 2=>$rec['fk_product_type'], @@ -4143,8 +4147,8 @@ class Product extends CommonObject //$prods[$this->db->escape($rec['label'])]= array(0=>$rec['id'],1=>$rec['qty'],2=>$rec['fk_product_type']); //$prods[$this->db->escape($rec['label'])]= array(0=>$rec['id'],1=>$rec['qty']); if (empty($firstlevelonly)) { - $listofchilds=$this->getChildsArbo($rec['rowid'], 0, $level + 1); - foreach($listofchilds as $keyChild => $valueChild) + $listofchilds = $this->getChildsArbo($rec['rowid'], 0, $level + 1); + foreach ($listofchilds as $keyChild => $valueChild) { $prods[$rec['rowid']]['childs'][$keyChild] = $valueChild; } @@ -4170,13 +4174,13 @@ class Product extends CommonObject public function get_sousproduits_arbo() { // phpcs:enable - $parent=array(); + $parent = array(); - foreach($this->getChildsArbo($this->id) as $keyChild => $valueChild) // Warning. getChildsArbo can call getChildsArbo recursively. Starting point is $value[0]=id of product + foreach ($this->getChildsArbo($this->id) as $keyChild => $valueChild) // Warning. getChildsArbo can call getChildsArbo recursively. Starting point is $value[0]=id of product { $parent[$this->label][$keyChild] = $valueChild; } - foreach($parent as $key => $value) // key=label, value is array of childs + foreach ($parent as $key => $value) // key=label, value is array of childs { $this->sousprods[$key] = $value; } @@ -4340,13 +4344,13 @@ class Product extends CommonObject */ public function generateDocument($modele, $outputlangs, $hidedetails = 0, $hidedesc = 0, $hideref = 0) { - global $conf,$user,$langs; + global $conf, $user, $langs; $langs->load("products"); // Positionne le modele sur le nom du modele a utiliser - if (! dol_strlen($modele)) { - if (! empty($conf->global->PRODUCT_ADDON_PDF)) { + if (!dol_strlen($modele)) { + if (!empty($conf->global->PRODUCT_ADDON_PDF)) { $modele = $conf->global->PRODUCT_ADDON_PDF; } else @@ -4400,7 +4404,7 @@ class Product extends CommonObject $labelStatus = $labelStatusShort = ''; $langs->load('products'); - if (! empty($conf->productbatch->enabled)) { $langs->load("productbatch"); + if (!empty($conf->productbatch->enabled)) { $langs->load("productbatch"); } if ($type == 2) { @@ -4415,7 +4419,7 @@ class Product extends CommonObject case 2: return $this->LibStatut($status, 3, 2).' '.$this->LibStatut($status, 1, 2); case 3: - return dolGetStatus($langs->trans('ProductStatusNotOnBatch'), '', '', empty($status)?'status5':'status4', 3, 'dot'); + return dolGetStatus($langs->trans('ProductStatusNotOnBatch'), '', '', empty($status) ? 'status5' : 'status4', 3, 'dot'); case 4: return $this->LibStatut($status, 3, 2).' '.$this->LibStatut($status, 0, 2); case 5: @@ -4506,14 +4510,14 @@ class Product extends CommonObject if ($id_entrepot) { $this->db->begin(); - include_once DOL_DOCUMENT_ROOT .'/product/stock/class/mouvementstock.class.php'; + include_once DOL_DOCUMENT_ROOT.'/product/stock/class/mouvementstock.class.php'; $op[0] = "+".trim($nbpiece); $op[1] = "-".trim($nbpiece); - $movementstock=new MouvementStock($this->db); + $movementstock = new MouvementStock($this->db); $movementstock->setOrigin($origin_element, $origin_id); - $result=$movementstock->_create($user, $this->id, $id_entrepot, $op[$movement], $movement, $price, $label, $inventorycode); + $result = $movementstock->_create($user, $this->id, $id_entrepot, $op[$movement], $movement, $price, $label, $inventorycode); if ($result >= 0) { $this->db->commit(); @@ -4521,8 +4525,8 @@ class Product extends CommonObject } else { - $this->error=$movementstock->error; - $this->errors=$movementstock->errors; + $this->error = $movementstock->error; + $this->errors = $movementstock->errors; $this->db->rollback(); return -1; @@ -4554,14 +4558,14 @@ class Product extends CommonObject if ($id_entrepot) { $this->db->begin(); - include_once DOL_DOCUMENT_ROOT .'/product/stock/class/mouvementstock.class.php'; + include_once DOL_DOCUMENT_ROOT.'/product/stock/class/mouvementstock.class.php'; $op[0] = "+".trim($nbpiece); $op[1] = "-".trim($nbpiece); - $movementstock=new MouvementStock($this->db); + $movementstock = new MouvementStock($this->db); $movementstock->setOrigin($origin_element, $origin_id); - $result=$movementstock->_create($user, $this->id, $id_entrepot, $op[$movement], $movement, $price, $label, $inventorycode, '', $dlc, $dluo, $lot); + $result = $movementstock->_create($user, $this->id, $id_entrepot, $op[$movement], $movement, $price, $label, $inventorycode, '', $dlc, $dluo, $lot); if ($result >= 0) { $this->db->commit(); @@ -4569,8 +4573,8 @@ class Product extends CommonObject } else { - $this->error=$movementstock->error; - $this->errors=$movementstock->errors; + $this->error = $movementstock->error; + $this->errors = $movementstock->errors; $this->db->rollback(); return -1; @@ -4610,19 +4614,19 @@ class Product extends CommonObject } $sql = "SELECT ps.rowid, ps.reel, ps.fk_entrepot"; - $sql.= " FROM ".MAIN_DB_PREFIX."product_stock as ps"; - $sql.= ", ".MAIN_DB_PREFIX."entrepot as w"; - $sql.= " WHERE w.entity IN (".getEntity('stock').")"; - $sql.= " AND w.rowid = ps.fk_entrepot"; - $sql.= " AND ps.fk_product = ".$this->id; - if ($conf->global->ENTREPOT_EXTRA_STATUS && count($warehouseStatus)) { $sql.= " AND w.statut IN (".$this->db->escape(implode(',', $warehouseStatus)).")"; + $sql .= " FROM ".MAIN_DB_PREFIX."product_stock as ps"; + $sql .= ", ".MAIN_DB_PREFIX."entrepot as w"; + $sql .= " WHERE w.entity IN (".getEntity('stock').")"; + $sql .= " AND w.rowid = ps.fk_entrepot"; + $sql .= " AND ps.fk_product = ".$this->id; + if ($conf->global->ENTREPOT_EXTRA_STATUS && count($warehouseStatus)) { $sql .= " AND w.statut IN (".$this->db->escape(implode(',', $warehouseStatus)).")"; } dol_syslog(get_class($this)."::load_stock", LOG_DEBUG); $result = $this->db->query($sql); if ($result) { $num = $this->db->num_rows($result); - $i=0; + $i = 0; if ($num > 0) { while ($i < $num) { @@ -4630,23 +4634,23 @@ class Product extends CommonObject $this->stock_warehouse[$row->fk_entrepot] = new stdClass(); $this->stock_warehouse[$row->fk_entrepot]->real = $row->reel; $this->stock_warehouse[$row->fk_entrepot]->id = $row->rowid; - if ((! preg_match('/nobatch/', $option)) && $this->hasbatch()) { $this->stock_warehouse[$row->fk_entrepot]->detail_batch=Productbatch::findAll($this->db, $row->rowid, 1, $this->id); + if ((!preg_match('/nobatch/', $option)) && $this->hasbatch()) { $this->stock_warehouse[$row->fk_entrepot]->detail_batch = Productbatch::findAll($this->db, $row->rowid, 1, $this->id); } - $this->stock_reel+=$row->reel; + $this->stock_reel += $row->reel; $i++; } } $this->db->free($result); - if (! preg_match('/novirtual/', $option)) { - $this->load_virtual_stock(); // This also load stats_commande_fournisseur, ... + if (!preg_match('/novirtual/', $option)) { + $this->load_virtual_stock(); // This also load stats_commande_fournisseur, ... } return 1; } else { - $this->error=$this->db->lasterror(); + $this->error = $this->db->lasterror(); return -1; } } @@ -4665,66 +4669,73 @@ class Product extends CommonObject // phpcs:enable global $conf, $hookmanager, $action; - $stock_commande_client=0; - $stock_commande_fournisseur=0; - $stock_sending_client=0; - $stock_reception_fournisseur=0; + $stock_commande_client = 0; + $stock_commande_fournisseur = 0; + $stock_sending_client = 0; + $stock_reception_fournisseur = 0; - if (! empty($conf->commande->enabled)) + if (!empty($conf->commande->enabled)) { - $result=$this->load_stats_commande(0, '1,2', 1); + $result = $this->load_stats_commande(0, '1,2', 1); if ($result < 0) dol_print_error($this->db, $this->error); - $stock_commande_client=$this->stats_commande['qty']; + $stock_commande_client = $this->stats_commande['qty']; } - if (! empty($conf->expedition->enabled)) + if (!empty($conf->expedition->enabled)) { - $result=$this->load_stats_sending(0, '1,2', 1); + require_once DOL_DOCUMENT_ROOT . '/expedition/class/expedition.class.php'; + $filterShipmentStatus = ''; + if (!empty($conf->global->STOCK_CALCULATE_ON_SHIPMENT)) { + $filterShipmentStatus = Expedition::STATUS_VALIDATED . ',' . Expedition::STATUS_CLOSED; + } elseif (!empty($conf->global->STOCK_CALCULATE_ON_SHIPMENT_CLOSE)) { + $filterShipmentStatus = Expedition::STATUS_CLOSED; + } + $result = $this->load_stats_sending(0, '1,2', 1, $filterShipmentStatus); if ($result < 0) dol_print_error($this->db, $this->error); - $stock_sending_client=$this->stats_expedition['qty']; + $stock_sending_client = $this->stats_expedition['qty']; } - if (! empty($conf->fournisseur->enabled)) + if (!empty($conf->fournisseur->enabled)) { - $result=$this->load_stats_commande_fournisseur(0, '1,2,3,4', 1); + $result = $this->load_stats_commande_fournisseur(0, '1,2,3,4', 1); if ($result < 0) dol_print_error($this->db, $this->error); - $stock_commande_fournisseur=$this->stats_commande_fournisseur['qty']; + $stock_commande_fournisseur = $this->stats_commande_fournisseur['qty']; - $result=$this->load_stats_reception(0, '4', 1); + $result = $this->load_stats_reception(0, '4', 1); if ($result < 0) dol_print_error($this->db, $this->error); - $stock_reception_fournisseur=$this->stats_reception['qty']; + $stock_reception_fournisseur = $this->stats_reception['qty']; } // Stock decrease mode - if (! empty($conf->global->STOCK_CALCULATE_ON_SHIPMENT) || ! empty($conf->global->STOCK_CALCULATE_ON_SHIPMENT_CLOSE)) { - $this->stock_theorique=$this->stock_reel-$stock_commande_client+$stock_sending_client; + if (!empty($conf->global->STOCK_CALCULATE_ON_SHIPMENT) || !empty($conf->global->STOCK_CALCULATE_ON_SHIPMENT_CLOSE)) { + $this->stock_theorique = $this->stock_reel - $stock_commande_client + $stock_sending_client; } - if (! empty($conf->global->STOCK_CALCULATE_ON_VALIDATE_ORDER)) { - $this->stock_theorique=$this->stock_reel; + if (!empty($conf->global->STOCK_CALCULATE_ON_VALIDATE_ORDER)) { + $this->stock_theorique = $this->stock_reel; } - if (! empty($conf->global->STOCK_CALCULATE_ON_BILL)) { - $this->stock_theorique=$this->stock_reel-$stock_commande_client; + if (!empty($conf->global->STOCK_CALCULATE_ON_BILL)) { + $this->stock_theorique = $this->stock_reel - $stock_commande_client; } // Stock Increase mode - if (! empty($conf->global->STOCK_CALCULATE_ON_RECEPTION) || ! empty($conf->global->STOCK_CALCULATE_ON_RECEPTION_CLOSE)) { - $this->stock_theorique+=$stock_commande_fournisseur-$stock_reception_fournisseur; + if (!empty($conf->global->STOCK_CALCULATE_ON_RECEPTION) || !empty($conf->global->STOCK_CALCULATE_ON_RECEPTION_CLOSE)) { + $this->stock_theorique += $stock_commande_fournisseur - $stock_reception_fournisseur; } - if (! empty($conf->global->STOCK_CALCULATE_ON_SUPPLIER_DISPATCH_ORDER)) { - $this->stock_theorique+=$stock_commande_fournisseur-$stock_reception_fournisseur; + if (!empty($conf->global->STOCK_CALCULATE_ON_SUPPLIER_DISPATCH_ORDER)) { + $this->stock_theorique += $stock_commande_fournisseur - $stock_reception_fournisseur; } - if (! empty($conf->global->STOCK_CALCULATE_ON_SUPPLIER_VALIDATE_ORDER)) { - $this->stock_theorique-=$stock_reception_fournisseur; + if (!empty($conf->global->STOCK_CALCULATE_ON_SUPPLIER_VALIDATE_ORDER)) { + $this->stock_theorique -= $stock_reception_fournisseur; } - if (! empty($conf->global->STOCK_CALCULATE_ON_SUPPLIER_BILL)) { - $this->stock_theorique+=$stock_commande_fournisseur-$stock_reception_fournisseur; + if (!empty($conf->global->STOCK_CALCULATE_ON_SUPPLIER_BILL)) { + $this->stock_theorique += $stock_commande_fournisseur - $stock_reception_fournisseur; } - if (! is_object($hookmanager)) { + if (!is_object($hookmanager)) { include_once DOL_DOCUMENT_ROOT.'/core/class/hookmanager.class.php'; - $hookmanager=new HookManager($this->db); + $hookmanager = new HookManager($this->db); } $hookmanager->initHooks(array('productdao')); - $parameters=array('id'=>$this->id); + $parameters = array('id'=>$this->id); // Note that $action and $object may have been modified by some hooks - $reshook=$hookmanager->executeHooks('loadvirtualstock', $parameters, $this, $action); + $reshook = $hookmanager->executeHooks('loadvirtualstock', $parameters, $this, $action); if ($reshook > 0) $this->stock_theorique = $hookmanager->resArray['stock_theorique']; return 1; @@ -4740,20 +4751,20 @@ class Product extends CommonObject */ public function loadBatchInfo($batch) { - $result=array(); + $result = array(); $sql = "SELECT pb.batch, pb.eatby, pb.sellby, SUM(pb.qty) AS qty FROM ".MAIN_DB_PREFIX."product_batch as pb, ".MAIN_DB_PREFIX."product_stock as ps"; - $sql.= " WHERE pb.fk_product_stock = ps.rowid AND ps.fk_product = ".$this->id." AND pb.batch = '".$this->db->escape($batch)."'"; - $sql.= " GROUP BY pb.batch, pb.eatby, pb.sellby"; + $sql .= " WHERE pb.fk_product_stock = ps.rowid AND ps.fk_product = ".$this->id." AND pb.batch = '".$this->db->escape($batch)."'"; + $sql .= " GROUP BY pb.batch, pb.eatby, pb.sellby"; dol_syslog(get_class($this)."::loadBatchInfo load first entry found for lot/serial = ".$batch, LOG_DEBUG); $resql = $this->db->query($sql); if ($resql) { $num = $this->db->num_rows($resql); - $i=0; + $i = 0; while ($i < $num) { $obj = $this->db->fetch_object($resql); - $result[]=array('batch'=>$batch, 'eatby'=>$this->db->jdate($obj->eatby), 'sellby'=>$this->db->jdate($obj->sellby), 'qty'=>$obj->qty); + $result[] = array('batch'=>$batch, 'eatby'=>$this->db->jdate($obj->eatby), 'sellby'=>$this->db->jdate($obj->sellby), 'qty'=>$obj->qty); $i++; } return $result; @@ -4784,21 +4795,21 @@ class Product extends CommonObject $result = 0; $dir = $sdir; - if (! empty($conf->global->PRODUCT_USE_OLD_PATH_FOR_PHOTO)) { - $dir .= '/'. get_exdir($this->id, 2, 0, 0, $this, 'product') . $this->id ."/photos"; + if (!empty($conf->global->PRODUCT_USE_OLD_PATH_FOR_PHOTO)) { + $dir .= '/'.get_exdir($this->id, 2, 0, 0, $this, 'product').$this->id."/photos"; } else { $dir .= '/'.get_exdir(0, 0, 0, 0, $this, 'product').dol_sanitizeFileName($this->ref); } dol_mkdir($dir); - $dir_osencoded=$dir; + $dir_osencoded = $dir; if (is_dir($dir_osencoded)) { - $originImage = $dir . '/' . $file['name']; + $originImage = $dir.'/'.$file['name']; // Cree fichier en taille origine - $result=dol_move_uploaded_file($file['tmp_name'], $originImage, 1); + $result = dol_move_uploaded_file($file['tmp_name'], $originImage, 1); if (file_exists(dol_osencode($originImage))) { // Create thumbs @@ -4823,25 +4834,25 @@ class Product extends CommonObject public function is_photo_available($sdir) { // phpcs:enable - include_once DOL_DOCUMENT_ROOT .'/core/lib/files.lib.php'; - include_once DOL_DOCUMENT_ROOT .'/core/lib/images.lib.php'; + include_once DOL_DOCUMENT_ROOT.'/core/lib/files.lib.php'; + include_once DOL_DOCUMENT_ROOT.'/core/lib/images.lib.php'; global $conf; $dir = $sdir; - if (! empty($conf->global->PRODUCT_USE_OLD_PATH_FOR_PHOTO)) { $dir .= '/'. get_exdir($this->id, 2, 0, 0, $this, 'product') . $this->id ."/photos/"; + if (!empty($conf->global->PRODUCT_USE_OLD_PATH_FOR_PHOTO)) { $dir .= '/'.get_exdir($this->id, 2, 0, 0, $this, 'product').$this->id."/photos/"; } else { $dir .= '/'.get_exdir(0, 0, 0, 0, $this, 'product').dol_sanitizeFileName($this->ref).'/'; } - $nbphoto=0; + $nbphoto = 0; - $dir_osencoded=dol_osencode($dir); + $dir_osencoded = dol_osencode($dir); if (file_exists($dir_osencoded)) { - $handle=opendir($dir_osencoded); + $handle = opendir($dir_osencoded); if (is_resource($handle)) { while (($file = readdir($handle)) !== false) { - if (! utf8_check($file)) { $file=utf8_encode($file); // To be sure data is stored in UTF8 in memory + if (!utf8_check($file)) { $file = utf8_encode($file); // To be sure data is stored in UTF8 in memory } if (dol_is_file($dir.$file) && image_format_supported($file) > 0) { return true; } @@ -4865,36 +4876,36 @@ class Product extends CommonObject include_once DOL_DOCUMENT_ROOT.'/core/lib/files.lib.php'; include_once DOL_DOCUMENT_ROOT.'/core/lib/images.lib.php'; - $nbphoto=0; - $tabobj=array(); + $nbphoto = 0; + $tabobj = array(); - $dir_osencoded=dol_osencode($dir); - $handle=@opendir($dir_osencoded); + $dir_osencoded = dol_osencode($dir); + $handle = @opendir($dir_osencoded); if (is_resource($handle)) { while (($file = readdir($handle)) !== false) { - if (! utf8_check($file)) { $file=utf8_encode($file); // readdir returns ISO + if (!utf8_check($file)) { $file = utf8_encode($file); // readdir returns ISO } if (dol_is_file($dir.$file) && image_format_supported($file) >= 0) { $nbphoto++; // On determine nom du fichier vignette - $photo=$file; - $photo_vignette=''; + $photo = $file; + $photo_vignette = ''; if (preg_match('/('.$this->regeximgext.')$/i', $photo, $regs)) { - $photo_vignette=preg_replace('/'.$regs[0].'/i', '', $photo).'_small'.$regs[0]; + $photo_vignette = preg_replace('/'.$regs[0].'/i', '', $photo).'_small'.$regs[0]; } $dirthumb = $dir.'thumbs/'; // Objet - $obj=array(); - $obj['photo']=$photo; - if ($photo_vignette && dol_is_file($dirthumb.$photo_vignette)) { $obj['photo_vignette']='thumbs/' . $photo_vignette; - } else { $obj['photo_vignette']=""; + $obj = array(); + $obj['photo'] = $photo; + if ($photo_vignette && dol_is_file($dirthumb.$photo_vignette)) { $obj['photo_vignette'] = 'thumbs/'.$photo_vignette; + } else { $obj['photo_vignette'] = ""; } - $tabobj[$nbphoto-1]=$obj; + $tabobj[$nbphoto - 1] = $obj; // On continue ou on arrete de boucler ? if ($nbmax && $nbphoto >= $nbmax) { break; @@ -4930,12 +4941,12 @@ class Product extends CommonObject // Si elle existe, on efface la vignette if (preg_match('/('.$this->regeximgext.')$/i', $filename, $regs)) { - $photo_vignette=preg_replace('/'.$regs[0].'/i', '', $filename).'_small'.$regs[0]; + $photo_vignette = preg_replace('/'.$regs[0].'/i', '', $filename).'_small'.$regs[0]; if (file_exists(dol_osencode($dirthumb.$photo_vignette))) { dol_delete_file($dirthumb.$photo_vignette); } - $photo_vignette=preg_replace('/'.$regs[0].'/i', '', $filename).'_mini'.$regs[0]; + $photo_vignette = preg_replace('/'.$regs[0].'/i', '', $filename).'_mini'.$regs[0]; if (file_exists(dol_osencode($dirthumb.$photo_vignette))) { dol_delete_file($dirthumb.$photo_vignette); } @@ -4952,7 +4963,7 @@ class Product extends CommonObject public function get_image_size($file) { // phpcs:enable - $file_osencoded=dol_osencode($file); + $file_osencoded = dol_osencode($file); $infoImg = getimagesize($file_osencoded); // Get information on image $this->imgWidth = $infoImg[0]; // Largeur de l'image $this->imgHeight = $infoImg[1]; // Hauteur de l'image @@ -4969,25 +4980,25 @@ class Product extends CommonObject // phpcs:enable global $conf, $user, $hookmanager; - $this->nb=array(); + $this->nb = array(); $sql = "SELECT count(p.rowid) as nb, fk_product_type"; - $sql.= " FROM ".MAIN_DB_PREFIX."product as p"; - $sql.= ' WHERE p.entity IN ('.getEntity($this->element, 1).')'; + $sql .= " FROM ".MAIN_DB_PREFIX."product as p"; + $sql .= ' WHERE p.entity IN ('.getEntity($this->element, 1).')'; // Add where from hooks if (is_object($hookmanager)) { - $parameters=array(); - $reshook=$hookmanager->executeHooks('printFieldListWhere', $parameters); // Note that $action and $object may have been modified by hook - $sql.=$hookmanager->resPrint; + $parameters = array(); + $reshook = $hookmanager->executeHooks('printFieldListWhere', $parameters); // Note that $action and $object may have been modified by hook + $sql .= $hookmanager->resPrint; } - $sql.= ' GROUP BY fk_product_type'; + $sql .= ' GROUP BY fk_product_type'; - $resql=$this->db->query($sql); + $resql = $this->db->query($sql); if ($resql) { - while ($obj=$this->db->fetch_object($resql)) + while ($obj = $this->db->fetch_object($resql)) { - if ($obj->fk_product_type == 1) { $this->nb["services"]=$obj->nb; - } else { $this->nb["products"]=$obj->nb; + if ($obj->fk_product_type == 1) { $this->nb["services"] = $obj->nb; + } else { $this->nb["products"] = $obj->nb; } } $this->db->free($resql); @@ -4996,7 +5007,7 @@ class Product extends CommonObject else { dol_print_error($this->db); - $this->error=$this->db->error(); + $this->error = $this->db->error(); return -1; } } @@ -5035,19 +5046,19 @@ class Product extends CommonObject // phpcs:enable global $conf; - $result=''; - if (! empty($conf->global->BARCODE_PRODUCT_ADDON_NUM)) { - $dirsociete=array_merge(array('/core/modules/barcode/'), $conf->modules_parts['barcode']); + $result = ''; + if (!empty($conf->global->BARCODE_PRODUCT_ADDON_NUM)) { + $dirsociete = array_merge(array('/core/modules/barcode/'), $conf->modules_parts['barcode']); foreach ($dirsociete as $dirroot) { - $res=dol_include_once($dirroot.$conf->global->BARCODE_PRODUCT_ADDON_NUM.'.php'); + $res = dol_include_once($dirroot.$conf->global->BARCODE_PRODUCT_ADDON_NUM.'.php'); if ($res) { break; } } $var = $conf->global->BARCODE_PRODUCT_ADDON_NUM; $mod = new $var; - $result=$mod->getNextValue($object, $type); + $result = $mod->getNextValue($object, $type); dol_syslog(get_class($this)."::get_barcode barcode=".$result." module=".$var); } @@ -5063,22 +5074,22 @@ class Product extends CommonObject */ public function initAsSpecimen() { - global $user,$langs,$conf,$mysoc; + global $user, $langs, $conf, $mysoc; - $now=dol_now(); + $now = dol_now(); // Initialize parameters - $this->specimen=1; - $this->id=0; + $this->specimen = 1; + $this->id = 0; $this->ref = 'PRODUCT_SPEC'; $this->label = 'PRODUCT SPECIMEN'; $this->description = 'This is description of this product specimen that was created the '.dol_print_date($now, 'dayhourlog').'.'; - $this->specimen=1; - $this->country_id=1; - $this->tosell=1; - $this->tobuy=1; - $this->tobatch=0; - $this->note='This is a comment (private)'; + $this->specimen = 1; + $this->country_id = 1; + $this->tosell = 1; + $this->tobuy = 1; + $this->tobatch = 0; + $this->note = 'This is a comment (private)'; $this->date_creation = $now; $this->date_modification = $now; @@ -5097,7 +5108,7 @@ class Product extends CommonObject $this->volume = 300; $this->volume_unit = 0; - $this->barcode=-1; // Create barcode automatically + $this->barcode = -1; // Create barcode automatically } /** @@ -5124,7 +5135,7 @@ class Product extends CommonObject $sql = 'select '.$label_type.' from '.MAIN_DB_PREFIX.'c_units where rowid='.$this->fk_unit; $resql = $this->db->query($sql); - if($resql && $this->db->num_rows($resql) > 0) { + if ($resql && $this->db->num_rows($resql) > 0) { $res = $this->db->fetch_array($resql); $label = $res[$label_type]; $this->db->free($resql); @@ -5132,7 +5143,7 @@ class Product extends CommonObject } else { - $this->error=$this->db->error().' sql='.$sql; + $this->error = $this->db->error().' sql='.$sql; dol_syslog(get_class($this)."::getLabelOfUnit Error ".$this->error, LOG_ERR); return -1; } @@ -5160,15 +5171,15 @@ class Product extends CommonObject // phpcs:enable global $conf; - $maxpricesupplier=0; + $maxpricesupplier = 0; - if (! empty($conf->global->PRODUCT_MINIMUM_RECOMMENDED_PRICE)) { + if (!empty($conf->global->PRODUCT_MINIMUM_RECOMMENDED_PRICE)) { include_once DOL_DOCUMENT_ROOT.'/fourn/class/fournisseur.product.class.php'; $product_fourn = new ProductFournisseur($this->db); $product_fourn_list = $product_fourn->list_product_fournisseur_price($this->id, '', ''); - if (is_array($product_fourn_list) && count($product_fourn_list)>0) { - foreach($product_fourn_list as $productfourn) + if (is_array($product_fourn_list) && count($product_fourn_list) > 0) { + foreach ($product_fourn_list as $productfourn) { if ($productfourn->fourn_unitprice > $maxpricesupplier) { $maxpricesupplier = $productfourn->fourn_unitprice; @@ -5196,12 +5207,12 @@ class Product extends CommonObject public function setCategories($categories) { // Handle single category - if (! is_array($categories)) { + if (!is_array($categories)) { $categories = array($categories); } // Get current categories - include_once DOL_DOCUMENT_ROOT . '/categories/class/categorie.class.php'; + include_once DOL_DOCUMENT_ROOT.'/categories/class/categorie.class.php'; $c = new Categorie($this->db); $existing = $c->containing($this->id, Categorie::TYPE_PRODUCT, 'id'); @@ -5215,7 +5226,7 @@ class Product extends CommonObject } // Process - foreach($to_del as $del) { + foreach ($to_del as $del) { if ($c->fetch($del) > 0) { $c->del_type($this, Categorie::TYPE_PRODUCT); } @@ -5283,14 +5294,14 @@ class Product extends CommonObject //We have to make sure it does exist and it is > 0 //First price level only allows changing min_price if ($i > 1 && isset($rules[$i]->var_percent) && $rules[$i]->var_percent) { - $price = $prices[$rules[$i]->fk_level] * (1 + ($rules[$i]->var_percent/100)); + $price = $prices[$rules[$i]->fk_level] * (1 + ($rules[$i]->var_percent / 100)); } $prices[$i] = $price; //We have to make sure it does exist and it is > 0 if (isset($rules[$i]->var_min_percent) && $rules[$i]->var_min_percent) { - $price_min = $price * (1 - ($rules[$i]->var_min_percent/100)); + $price_min = $price * (1 - ($rules[$i]->var_min_percent / 100)); } //Little check to make sure the price is modified before triggering generation @@ -5334,11 +5345,11 @@ class Product extends CommonObject public function info($id) { $sql = "SELECT p.rowid, p.ref, p.datec as date_creation, p.tms as date_modification,"; - $sql.= " p.fk_user_author, p.fk_user_modif"; - $sql.= " FROM ".MAIN_DB_PREFIX.$this->table_element." as p"; - $sql.= " WHERE p.rowid = ".$id; + $sql .= " p.fk_user_author, p.fk_user_modif"; + $sql .= " FROM ".MAIN_DB_PREFIX.$this->table_element." as p"; + $sql .= " WHERE p.rowid = ".$id; - $result=$this->db->query($sql); + $result = $this->db->query($sql); if ($result) { if ($this->db->num_rows($result)) { $obj = $this->db->fetch_object($result); @@ -5348,7 +5359,7 @@ class Product extends CommonObject if ($obj->fk_user_author) { $cuser = new User($this->db); $cuser->fetch($obj->fk_user_author); - $this->user_creation = $cuser; + $this->user_creation = $cuser; } if ($obj->fk_user_modif) { @@ -5357,7 +5368,7 @@ class Product extends CommonObject $this->user_modification = $muser; } - $this->ref = $obj->ref; + $this->ref = $obj->ref; $this->date_creation = $this->db->jdate($obj->date_creation); $this->date_modification = $this->db->jdate($obj->date_modification); } diff --git a/htdocs/product/class/productbatch.class.php b/htdocs/product/class/productbatch.class.php index 54ceff8eb9d..a0a85bbec94 100644 --- a/htdocs/product/class/productbatch.class.php +++ b/htdocs/product/class/productbatch.class.php @@ -33,15 +33,15 @@ class Productbatch extends CommonObject /** * @var string ID to identify managed object */ - public $element='productbatch'; + public $element = 'productbatch'; - private static $_table_element='product_batch'; //!< Name of table without prefix where object is stored + private static $_table_element = 'product_batch'; //!< Name of table without prefix where object is stored - public $tms=''; + public $tms = ''; public $fk_product_stock; - public $sellby=''; - public $eatby=''; - public $batch=''; + public $sellby = ''; + public $eatby = ''; + public $batch = ''; public $qty; public $warehouseid; @@ -73,7 +73,7 @@ class Productbatch extends CommonObject public function create($user, $notrigger = 0) { global $conf, $langs; - $error=0; + $error = 0; // Clean parameters $this->cleanParam(); @@ -83,32 +83,32 @@ class Productbatch extends CommonObject // Insert request $sql = "INSERT INTO ".MAIN_DB_PREFIX."product_batch ("; - $sql.= "fk_product_stock,"; - $sql.= "sellby,"; - $sql.= "eatby,"; - $sql.= "batch,"; - $sql.= "qty,"; - $sql.= "import_key"; - $sql.= ") VALUES ("; - $sql.= " ".(! isset($this->fk_product_stock)?'NULL':$this->fk_product_stock).","; - $sql.= " ".(! isset($this->sellby) || dol_strlen($this->sellby)==0?'NULL':"'".$this->db->idate($this->sellby)."'").","; - $sql.= " ".(! isset($this->eatby) || dol_strlen($this->eatby)==0?'NULL':"'".$this->db->idate($this->eatby)."'").","; - $sql.= " ".(! isset($this->batch)?'NULL':"'".$this->db->escape($this->batch)."'").","; - $sql.= " ".(! isset($this->qty)?'NULL':$this->qty).","; - $sql.= " ".(! isset($this->import_key)?'NULL':"'".$this->db->escape($this->import_key)."'").""; + $sql .= "fk_product_stock,"; + $sql .= "sellby,"; + $sql .= "eatby,"; + $sql .= "batch,"; + $sql .= "qty,"; + $sql .= "import_key"; + $sql .= ") VALUES ("; + $sql .= " ".(!isset($this->fk_product_stock) ? 'NULL' : $this->fk_product_stock).","; + $sql .= " ".(!isset($this->sellby) || dol_strlen($this->sellby) == 0 ? 'NULL' : "'".$this->db->idate($this->sellby)."'").","; + $sql .= " ".(!isset($this->eatby) || dol_strlen($this->eatby) == 0 ? 'NULL' : "'".$this->db->idate($this->eatby)."'").","; + $sql .= " ".(!isset($this->batch) ? 'NULL' : "'".$this->db->escape($this->batch)."'").","; + $sql .= " ".(!isset($this->qty) ? 'NULL' : $this->qty).","; + $sql .= " ".(!isset($this->import_key) ? 'NULL' : "'".$this->db->escape($this->import_key)."'").""; - $sql.= ")"; + $sql .= ")"; $this->db->begin(); dol_syslog(get_class($this)."::create", LOG_DEBUG); - $resql=$this->db->query($sql); - if (! $resql) { $error++; $this->errors[]="Error ".$this->db->lasterror(); } - if (! $error) + $resql = $this->db->query($sql); + if (!$resql) { $error++; $this->errors[] = "Error ".$this->db->lasterror(); } + if (!$error) { $this->id = $this->db->last_insert_id(MAIN_DB_PREFIX.self::$_table_element); - if (! $notrigger) + if (!$notrigger) { // Uncomment this and change MYOBJECT to your own tag if you // want this action calls a trigger. @@ -126,7 +126,7 @@ class Productbatch extends CommonObject if ($error) { $this->db->rollback(); - return -1*$error; + return -1 * $error; } else { @@ -146,23 +146,23 @@ class Productbatch extends CommonObject { global $langs; $sql = "SELECT"; - $sql.= " t.rowid,"; + $sql .= " t.rowid,"; - $sql.= " t.tms,"; - $sql.= " t.fk_product_stock,"; - $sql.= " t.sellby as oldsellby,"; - $sql.= " t.eatby as oldeatby,"; - $sql.= " t.batch,"; - $sql.= " t.qty,"; - $sql.= " t.import_key,"; - $sql.= " w.fk_entrepot,"; - $sql.= " w.fk_product,"; - $sql.= " pl.eatby,"; - $sql.= " pl.sellby"; + $sql .= " t.tms,"; + $sql .= " t.fk_product_stock,"; + $sql .= " t.sellby as oldsellby,"; + $sql .= " t.eatby as oldeatby,"; + $sql .= " t.batch,"; + $sql .= " t.qty,"; + $sql .= " t.import_key,"; + $sql .= " w.fk_entrepot,"; + $sql .= " w.fk_product,"; + $sql .= " pl.eatby,"; + $sql .= " pl.sellby"; - $sql.= " FROM ".MAIN_DB_PREFIX."product_batch as t INNER JOIN ".MAIN_DB_PREFIX."product_stock w on t.fk_product_stock = w.rowid"; - $sql.= " LEFT JOIN ".MAIN_DB_PREFIX."product_lot as pl on pl.fk_product = w.fk_product and pl.batch = t.batch"; - $sql.= " WHERE t.rowid = ".$id; + $sql .= " FROM ".MAIN_DB_PREFIX."product_batch as t INNER JOIN ".MAIN_DB_PREFIX."product_stock w on t.fk_product_stock = w.rowid"; + $sql .= " LEFT JOIN ".MAIN_DB_PREFIX."product_lot as pl on pl.fk_product = w.fk_product and pl.batch = t.batch"; + $sql .= " WHERE t.rowid = ".$id; dol_syslog(get_class($this)."::fetch", LOG_DEBUG); $resql = $this->db->query($sql); @@ -172,16 +172,16 @@ class Productbatch extends CommonObject { $obj = $this->db->fetch_object($resql); - $this->id = $obj->rowid; + $this->id = $obj->rowid; $this->tms = $this->db->jdate($obj->tms); $this->fk_product_stock = $obj->fk_product_stock; - $this->sellby = $this->db->jdate($obj->sellby?$obj->sellby:$obj->oldsellby); - $this->eatby = $this->db->jdate($obj->eatby?$obj->eatby:$obj->oldeatby); + $this->sellby = $this->db->jdate($obj->sellby ? $obj->sellby : $obj->oldsellby); + $this->eatby = $this->db->jdate($obj->eatby ? $obj->eatby : $obj->oldeatby); $this->batch = $obj->batch; $this->qty = $obj->qty; $this->import_key = $obj->import_key; - $this->warehouseid= $obj->fk_entrepot; - $this->fk_product= $obj->fk_product; + $this->warehouseid = $obj->fk_entrepot; + $this->fk_product = $obj->fk_product; } $this->db->free($resql); @@ -204,7 +204,7 @@ class Productbatch extends CommonObject public function update($user = null, $notrigger = 0) { global $conf, $langs; - $error=0; + $error = 0; // Clean parameters $this->cleanParam(); @@ -248,13 +248,13 @@ class Productbatch extends CommonObject // Commit or rollback if ($error) { - foreach($this->errors as $errmsg) + foreach ($this->errors as $errmsg) { dol_syslog(get_class($this)."::update ".$errmsg, LOG_ERR); - $this->error.=($this->error?', '.$errmsg:$errmsg); + $this->error .= ($this->error ? ', '.$errmsg : $errmsg); } $this->db->rollback(); - return -1*$error; + return -1 * $error; } else { @@ -273,13 +273,13 @@ class Productbatch extends CommonObject public function delete($user, $notrigger = 0) { global $conf, $langs; - $error=0; + $error = 0; $this->db->begin(); - if (! $error) + if (!$error) { - if (! $notrigger) + if (!$notrigger) { // Uncomment this and change MYOBJECT to your own tag if you // want this action calls a trigger. @@ -293,26 +293,26 @@ class Productbatch extends CommonObject } } - if (! $error) + if (!$error) { $sql = "DELETE FROM ".MAIN_DB_PREFIX.self::$_table_element.""; - $sql.= " WHERE rowid=".$this->id; + $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) + foreach ($this->errors as $errmsg) { dol_syslog(get_class($this)."::delete ".$errmsg, LOG_ERR); - $this->error.=($this->error?', '.$errmsg:$errmsg); + $this->error .= ($this->error ? ', '.$errmsg : $errmsg); } $this->db->rollback(); - return -1*$error; + return -1 * $error; } else { @@ -365,7 +365,7 @@ class Productbatch extends CommonObject unset($object->context['createfromclone']); // End - if (! $error) + if (!$error) { $this->db->commit(); return $object->id; @@ -386,14 +386,14 @@ class Productbatch extends CommonObject */ public function initAsSpecimen() { - $this->id=0; + $this->id = 0; - $this->tms=''; - $this->fk_product_stock=''; - $this->sellby=''; - $this->eatby=''; - $this->batch=''; - $this->import_key=''; + $this->tms = ''; + $this->fk_product_stock = ''; + $this->sellby = ''; + $this->eatby = ''; + $this->batch = ''; + $this->import_key = ''; } /** @@ -403,10 +403,10 @@ class Productbatch extends CommonObject */ private function cleanParam() { - if (isset($this->fk_product_stock)) $this->fk_product_stock=(int) trim($this->fk_product_stock); - if (isset($this->batch)) $this->batch=trim($this->batch); - if (isset($this->qty)) $this->qty=(float) trim($this->qty); - if (isset($this->import_key)) $this->import_key=trim($this->import_key); + if (isset($this->fk_product_stock)) $this->fk_product_stock = (int) trim($this->fk_product_stock); + if (isset($this->batch)) $this->batch = trim($this->batch); + if (isset($this->qty)) $this->qty = (float) trim($this->qty); + if (isset($this->import_key)) $this->import_key = trim($this->import_key); } /** @@ -424,33 +424,33 @@ class Productbatch extends CommonObject $where = array(); $sql = "SELECT"; - $sql.= " t.rowid,"; - $sql.= " t.tms,"; - $sql.= " t.fk_product_stock,"; - $sql.= " t.sellby,"; // deprecated - $sql.= " t.eatby,"; // deprecated - $sql.= " t.batch,"; - $sql.= " t.qty,"; - $sql.= " t.import_key"; - $sql.= " FROM ".MAIN_DB_PREFIX.self::$_table_element." as t"; - $sql.= " WHERE fk_product_stock=".$fk_product_stock; + $sql .= " t.rowid,"; + $sql .= " t.tms,"; + $sql .= " t.fk_product_stock,"; + $sql .= " t.sellby,"; // deprecated + $sql .= " t.eatby,"; // deprecated + $sql .= " t.batch,"; + $sql .= " t.qty,"; + $sql .= " t.import_key"; + $sql .= " FROM ".MAIN_DB_PREFIX.self::$_table_element." as t"; + $sql .= " WHERE fk_product_stock=".$fk_product_stock; - if (! empty($eatby)) array_push($where, " eatby = '".$this->db->idate($eatby)."'"); // deprecated - if (! empty($sellby)) array_push($where, " sellby = '".$this->db->idate($sellby)."'"); // deprecated + if (!empty($eatby)) array_push($where, " eatby = '".$this->db->idate($eatby)."'"); // deprecated + if (!empty($sellby)) array_push($where, " sellby = '".$this->db->idate($sellby)."'"); // deprecated - if (! empty($batch_number)) $sql.= " AND batch = '".$this->db->escape($batch_number)."'"; + if (!empty($batch_number)) $sql .= " AND batch = '".$this->db->escape($batch_number)."'"; - if (! empty($where)) $sql.= " AND (".implode(" OR ", $where).")"; + if (!empty($where)) $sql .= " AND (".implode(" OR ", $where).")"; dol_syslog(get_class($this)."::fetch", LOG_DEBUG); - $resql=$this->db->query($sql); + $resql = $this->db->query($sql); if ($resql) { if ($this->db->num_rows($resql)) { $obj = $this->db->fetch_object($resql); - $this->id = $obj->rowid; + $this->id = $obj->rowid; $this->tms = $this->db->jdate($obj->tms); $this->fk_product_stock = $obj->fk_product_stock; @@ -466,7 +466,7 @@ class Productbatch extends CommonObject } else { - $this->error="Error ".$this->db->lasterror(); + $this->error = "Error ".$this->db->lasterror(); return -1; } } @@ -485,33 +485,33 @@ class Productbatch extends CommonObject $ret = array(); $sql = "SELECT"; - $sql.= " t.rowid,"; - $sql.= " t.tms,"; - $sql.= " t.fk_product_stock,"; - $sql.= " t.sellby as oldsellby,"; // deprecated but may not be migrated into new table - $sql.= " t.eatby as oldeatby,"; // deprecated but may not be migrated into new table - $sql.= " t.batch,"; - $sql.= " t.qty,"; - $sql.= " t.import_key"; + $sql .= " t.rowid,"; + $sql .= " t.tms,"; + $sql .= " t.fk_product_stock,"; + $sql .= " t.sellby as oldsellby,"; // deprecated but may not be migrated into new table + $sql .= " t.eatby as oldeatby,"; // deprecated but may not be migrated into new table + $sql .= " t.batch,"; + $sql .= " t.qty,"; + $sql .= " t.import_key"; if ($fk_product > 0) { - $sql.= ", pl.rowid as lotid, pl.eatby as eatby, pl.sellby as sellby"; + $sql .= ", pl.rowid as lotid, pl.eatby as eatby, pl.sellby as sellby"; // TODO May add extrafields to ? } - $sql.= " FROM ".MAIN_DB_PREFIX."product_batch as t"; + $sql .= " FROM ".MAIN_DB_PREFIX."product_batch as t"; if ($fk_product > 0) { - $sql.= " LEFT JOIN ".MAIN_DB_PREFIX."product_lot as pl ON pl.fk_product = ".$fk_product." AND pl.batch = t.batch"; + $sql .= " LEFT JOIN ".MAIN_DB_PREFIX."product_lot as pl ON pl.fk_product = ".$fk_product." AND pl.batch = t.batch"; // TODO May add extrafields to ? } - $sql.= " WHERE fk_product_stock=".$fk_product_stock; - if ($with_qty) $sql.= " AND t.qty <> 0"; + $sql .= " WHERE fk_product_stock=".$fk_product_stock; + if ($with_qty) $sql .= " AND t.qty <> 0"; dol_syslog("productbatch::findAll", LOG_DEBUG); - $resql=$db->query($sql); + $resql = $db->query($sql); if ($resql) { $num = $db->num_rows($resql); - $i=0; + $i = 0; while ($i < $num) { $obj = $db->fetch_object($resql); @@ -527,7 +527,7 @@ class Productbatch extends CommonObject $tmp->qty = $obj->qty; $tmp->import_key = $obj->import_key; - $ret[$tmp->batch] = $tmp; // $ret is for a $fk_product_stock and unique key is on $fk_product_stock+batch + $ret[$tmp->batch] = $tmp; // $ret is for a $fk_product_stock and unique key is on $fk_product_stock+batch $i++; } $db->free($resql); @@ -536,7 +536,7 @@ class Productbatch extends CommonObject } else { - $error="Error ".$db->lasterror(); + $error = "Error ".$db->lasterror(); return -1; } } diff --git a/htdocs/product/class/productcustomerprice.class.php b/htdocs/product/class/productcustomerprice.class.php index 8117d8fb6aa..dd542b71f8d 100644 --- a/htdocs/product/class/productcustomerprice.class.php +++ b/htdocs/product/class/productcustomerprice.class.php @@ -21,7 +21,7 @@ * \ingroup produit * \brief File of class to manage predefined price products or services by customer */ -require_once DOL_DOCUMENT_ROOT . '/core/class/commonobject.class.php'; +require_once DOL_DOCUMENT_ROOT.'/core/class/commonobject.class.php'; /** * File of class to manage predefined price products or services by customer @@ -73,7 +73,7 @@ class Productcustomerprice extends CommonObject */ public $fk_user; - public $lines = array (); + public $lines = array(); /** @@ -166,7 +166,7 @@ class Productcustomerprice extends CommonObject } // Insert request - $sql = "INSERT INTO " . MAIN_DB_PREFIX . "product_customer_price("; + $sql = "INSERT INTO ".MAIN_DB_PREFIX."product_customer_price("; $sql .= "entity,"; $sql .= "datec,"; $sql .= "fk_product,"; @@ -186,39 +186,39 @@ class Productcustomerprice extends CommonObject $sql .= "fk_user,"; $sql .= "import_key"; $sql .= ") VALUES ("; - $sql .= " " . $conf->entity . ","; - $sql .= " '" . $this->db->idate(dol_now()) . "',"; - $sql .= " " . (! isset($this->fk_product) ? 'NULL' : "'" . $this->db->escape($this->fk_product) . "'") . ","; - $sql .= " " . (! isset($this->fk_soc) ? 'NULL' : "'" . $this->db->escape($this->fk_soc) . "'") . ","; - $sql .= " " . (empty($this->price) ? '0' : "'" . $this->db->escape($this->price) . "'") . ","; - $sql .= " " . (empty($this->price_ttc) ? '0' : "'" . $this->db->escape($this->price_ttc) . "'") . ","; - $sql .= " " . (empty($this->price_min) ? '0' : "'" . $this->db->escape($this->price_min) . "'") . ","; - $sql .= " " . (empty($this->price_min_ttc) ? '0' : "'" . $this->db->escape($this->price_min_ttc) . "'") . ","; - $sql .= " " . (! isset($this->price_base_type) ? 'NULL' : "'" . $this->db->escape($this->price_base_type) . "'") . ","; + $sql .= " ".$conf->entity.","; + $sql .= " '".$this->db->idate(dol_now())."',"; + $sql .= " ".(!isset($this->fk_product) ? 'NULL' : "'".$this->db->escape($this->fk_product)."'").","; + $sql .= " ".(!isset($this->fk_soc) ? 'NULL' : "'".$this->db->escape($this->fk_soc)."'").","; + $sql .= " ".(empty($this->price) ? '0' : "'".$this->db->escape($this->price)."'").","; + $sql .= " ".(empty($this->price_ttc) ? '0' : "'".$this->db->escape($this->price_ttc)."'").","; + $sql .= " ".(empty($this->price_min) ? '0' : "'".$this->db->escape($this->price_min)."'").","; + $sql .= " ".(empty($this->price_min_ttc) ? '0' : "'".$this->db->escape($this->price_min_ttc)."'").","; + $sql .= " ".(!isset($this->price_base_type) ? 'NULL' : "'".$this->db->escape($this->price_base_type)."'").","; $sql .= " ".($this->default_vat_code ? "'".$this->db->escape($this->default_vat_code)."'" : "null").","; - $sql .= " " . (! isset($this->tva_tx) ? 'NULL' : (empty($this->tva_tx)?0:$this->tva_tx)) . ","; - $sql .= " " . (! isset($this->recuperableonly) ? 'NULL' : "'" . $this->db->escape($this->recuperableonly) . "'") . ","; - $sql .= " " . (empty($this->localtax1_type) ? "'0'" : "'" . $this->db->escape($this->localtax1_type) . "'") . ","; - $sql .= " " . (! isset($this->localtax1_tx) ? 'NULL' : (empty($this->localtax1_tx)?0:$this->localtax1_tx)) . ","; - $sql .= " " . (empty($this->localtax2_type) ? "'0'" : "'" . $this->db->escape($this->localtax2_type) . "'") . ","; - $sql .= " " . (! isset($this->localtax2_tx) ? 'NULL' : (empty($this->localtax2_tx)?0:$this->localtax2_tx)) . ","; - $sql .= " " . $user->id . ","; - $sql .= " " . (! isset($this->import_key) ? 'NULL' : "'" . $this->db->escape($this->import_key) . "'") . ""; + $sql .= " ".(!isset($this->tva_tx) ? 'NULL' : (empty($this->tva_tx) ? 0 : $this->tva_tx)).","; + $sql .= " ".(!isset($this->recuperableonly) ? 'NULL' : "'".$this->db->escape($this->recuperableonly)."'").","; + $sql .= " ".(empty($this->localtax1_type) ? "'0'" : "'".$this->db->escape($this->localtax1_type)."'").","; + $sql .= " ".(!isset($this->localtax1_tx) ? 'NULL' : (empty($this->localtax1_tx) ? 0 : $this->localtax1_tx)).","; + $sql .= " ".(empty($this->localtax2_type) ? "'0'" : "'".$this->db->escape($this->localtax2_type)."'").","; + $sql .= " ".(!isset($this->localtax2_tx) ? 'NULL' : (empty($this->localtax2_tx) ? 0 : $this->localtax2_tx)).","; + $sql .= " ".$user->id.","; + $sql .= " ".(!isset($this->import_key) ? 'NULL' : "'".$this->db->escape($this->import_key)."'").""; $sql .= ")"; $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) { - $this->id = $this->db->last_insert_id(MAIN_DB_PREFIX . "product_customer_price"); + if (!$error) { + $this->id = $this->db->last_insert_id(MAIN_DB_PREFIX."product_customer_price"); - if (! $notrigger) { + if (!$notrigger) { // Uncomment this and change MYOBJECT to your own tag if you // want this action calls a trigger. @@ -231,21 +231,21 @@ class Productcustomerprice extends CommonObject } } - if (! $error) { + if (!$error) { $result = $this->setPriceOnAffiliateThirdparty($user, $forceupdateaffiliate); if ($result < 0) { - $error ++; + $error++; } } // Commit or rollback if ($error) { foreach ($this->errors as $errmsg) { - dol_syslog(get_class($this) . "::create " . $errmsg, LOG_ERR); - $this->error .= ($this->error ? ', ' . $errmsg : $errmsg); + dol_syslog(get_class($this)."::create ".$errmsg, LOG_ERR); + $this->error .= ($this->error ? ', '.$errmsg : $errmsg); } $this->db->rollback(); - return - 1 * $error; + return -1 * $error; } else { $this->db->commit(); return $this->id; @@ -283,10 +283,10 @@ class Productcustomerprice extends CommonObject $sql .= " t.fk_user,"; $sql .= " t.import_key"; - $sql .= " FROM " . MAIN_DB_PREFIX . "product_customer_price as t"; - $sql .= " WHERE t.rowid = " . $id; + $sql .= " FROM ".MAIN_DB_PREFIX."product_customer_price as t"; + $sql .= " WHERE t.rowid = ".$id; - dol_syslog(get_class($this) . "::fetch", LOG_DEBUG); + dol_syslog(get_class($this)."::fetch", LOG_DEBUG); $resql = $this->db->query($sql); if ($resql) { if ($this->db->num_rows($resql)) { @@ -316,8 +316,8 @@ class Productcustomerprice extends CommonObject return 1; } else { - $this->error = "Error " . $this->db->lasterror(); - return - 1; + $this->error = "Error ".$this->db->lasterror(); + return -1; } } @@ -337,8 +337,8 @@ class Productcustomerprice extends CommonObject // phpcs:enable global $langs; - if ( empty($sortfield)) $sortfield = "t.rowid"; - if ( empty($sortorder)) $sortorder = "DESC"; + if (empty($sortfield)) $sortfield = "t.rowid"; + if (empty($sortorder)) $sortorder = "DESC"; $sql = "SELECT"; $sql .= " t.rowid,"; @@ -364,39 +364,39 @@ class Productcustomerprice extends CommonObject $sql .= " t.import_key,"; $sql .= " soc.nom as socname,"; $sql .= " prod.ref as prodref"; - $sql .= " FROM " . MAIN_DB_PREFIX . "product_customer_price as t "; - $sql .= " ," . MAIN_DB_PREFIX . "product as prod "; - $sql .= " ," . MAIN_DB_PREFIX . "societe as soc "; + $sql .= " FROM ".MAIN_DB_PREFIX."product_customer_price as t "; + $sql .= " ,".MAIN_DB_PREFIX."product as prod "; + $sql .= " ,".MAIN_DB_PREFIX."societe as soc "; $sql .= " WHERE soc.rowid=t.fk_soc "; $sql .= " AND prod.rowid=t.fk_product "; - $sql .= " AND prod.entity IN (" . getEntity('product') . ")"; - $sql .= " AND t.entity IN (" . getEntity('productprice') . ")"; + $sql .= " AND prod.entity IN (".getEntity('product').")"; + $sql .= " AND t.entity IN (".getEntity('productprice').")"; // Manage filter if (count($filter) > 0) { foreach ($filter as $key => $value) { if (strpos($key, 'date')) // To allow $filter['YEAR(s.dated)']=>$year { - $sql .= ' AND ' . $key . ' = \'' . $value . '\''; + $sql .= ' AND '.$key.' = \''.$value.'\''; } elseif ($key == 'soc.nom') { - $sql .= ' AND ' . $key . ' LIKE \'%' . $value . '%\''; + $sql .= ' AND '.$key.' LIKE \'%'.$value.'%\''; } elseif ($key == 'prod.ref') { - $sql .= ' AND ' . $key . ' LIKE \'%' . $value . '%\''; + $sql .= ' AND '.$key.' LIKE \'%'.$value.'%\''; } else { - $sql .= ' AND ' . $key . ' = ' . $value; + $sql .= ' AND '.$key.' = '.$value; } } } - $sql.= $this->db->order($sortfield, $sortorder); - if (! empty($limit)) $sql .= ' ' . $this->db->plimit($limit + 1, $offset); + $sql .= $this->db->order($sortfield, $sortorder); + if (!empty($limit)) $sql .= ' '.$this->db->plimit($limit + 1, $offset); - dol_syslog(get_class($this) . "::fetch_all", LOG_DEBUG); + dol_syslog(get_class($this)."::fetch_all", LOG_DEBUG); $resql = $this->db->query($sql); if ($resql) { - $this->lines = array (); + $this->lines = array(); $num = $this->db->num_rows($resql); - while ( $obj = $this->db->fetch_object($resql) ) { + while ($obj = $this->db->fetch_object($resql)) { $line = new PriceByCustomerLine(); $line->id = $obj->rowid; @@ -429,8 +429,8 @@ class Productcustomerprice extends CommonObject return $num; } else { - $this->error = "Error " . $this->db->lasterror(); - return - 1; + $this->error = "Error ".$this->db->lasterror(); + return -1; } } @@ -450,8 +450,8 @@ class Productcustomerprice extends CommonObject // phpcs:enable global $langs; - if (! empty($sortfield)) $sortfield = "t.rowid"; - if (! empty($sortorder)) $sortorder = "DESC"; + if (!empty($sortfield)) $sortfield = "t.rowid"; + if (!empty($sortorder)) $sortorder = "DESC"; $sql = "SELECT"; $sql .= " t.rowid,"; @@ -474,38 +474,38 @@ class Productcustomerprice extends CommonObject $sql .= " t.import_key,"; $sql .= " soc.nom as socname,"; $sql .= " prod.ref as prodref"; - $sql .= " FROM " . MAIN_DB_PREFIX . "product_customer_price_log as t "; - $sql .= " ," . MAIN_DB_PREFIX . "product as prod "; - $sql .= " ," . MAIN_DB_PREFIX . "societe as soc "; + $sql .= " FROM ".MAIN_DB_PREFIX."product_customer_price_log as t "; + $sql .= " ,".MAIN_DB_PREFIX."product as prod "; + $sql .= " ,".MAIN_DB_PREFIX."societe as soc "; $sql .= " WHERE soc.rowid=t.fk_soc "; $sql .= " AND prod.rowid=t.fk_product "; - $sql .= " AND prod.entity IN (" . getEntity('product') . ")"; - $sql .= " AND t.entity IN (" . getEntity('productprice') . ")"; + $sql .= " AND prod.entity IN (".getEntity('product').")"; + $sql .= " AND t.entity IN (".getEntity('productprice').")"; // Manage filter if (count($filter) > 0) { foreach ($filter as $key => $value) { if (strpos($key, 'date')) // To allow $filter['YEAR(s.dated)']=>$year { - $sql .= ' AND ' . $key . ' = \'' . $value . '\''; + $sql .= ' AND '.$key.' = \''.$value.'\''; } elseif ($key == 'soc.nom') { - $sql .= ' AND ' . $key . ' LIKE \'%' . $value . '%\''; + $sql .= ' AND '.$key.' LIKE \'%'.$value.'%\''; } else { - $sql .= ' AND ' . $key . ' = ' . $value; + $sql .= ' AND '.$key.' = '.$value; } } } - $sql.= $this->db->order($sortfield, $sortorder); - if (! empty($limit)) $sql .= ' ' . $this->db->plimit($limit + 1, $offset); + $sql .= $this->db->order($sortfield, $sortorder); + if (!empty($limit)) $sql .= ' '.$this->db->plimit($limit + 1, $offset); - dol_syslog(get_class($this) . "::fetch_all_log", LOG_DEBUG); + dol_syslog(get_class($this)."::fetch_all_log", LOG_DEBUG); $resql = $this->db->query($sql); if ($resql) { - $this->lines = array (); + $this->lines = array(); $num = $this->db->num_rows($resql); - while ( $obj = $this->db->fetch_object($resql) ) { + while ($obj = $this->db->fetch_object($resql)) { $line = new PriceByCustomerLine(); $line->id = $obj->rowid; @@ -536,8 +536,8 @@ class Productcustomerprice extends CommonObject return $num; } else { - $this->error = "Error " . $this->db->lasterror(); - return - 1; + $this->error = "Error ".$this->db->lasterror(); + return -1; } } @@ -622,7 +622,7 @@ class Productcustomerprice extends CommonObject // Do a copy of current record into log table // Insert request - $sql = "INSERT INTO " . MAIN_DB_PREFIX . "product_customer_price_log("; + $sql = "INSERT INTO ".MAIN_DB_PREFIX."product_customer_price_log("; $sql .= "entity,"; $sql .= "datec,"; @@ -665,75 +665,75 @@ class Productcustomerprice extends CommonObject $sql .= " t.fk_user,"; $sql .= " t.import_key"; - $sql .= " FROM " . MAIN_DB_PREFIX . "product_customer_price as t"; - $sql .= " WHERE t.rowid = " . $this->id; + $sql .= " FROM ".MAIN_DB_PREFIX."product_customer_price as t"; + $sql .= " WHERE t.rowid = ".$this->id; $this->db->begin(); - dol_syslog(get_class($this) . "::update", LOG_DEBUG); + 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(); } // Update request - $sql = "UPDATE " . MAIN_DB_PREFIX . "product_customer_price SET"; + $sql = "UPDATE ".MAIN_DB_PREFIX."product_customer_price SET"; - $sql .= " entity=" . $conf->entity . ","; - $sql .= " datec='" . $this->db->idate(dol_now()) . "',"; - $sql .= " tms=" . (dol_strlen($this->tms) != 0 ? "'" . $this->db->idate($this->tms) . "'" : 'null') . ","; - $sql .= " fk_product=" . (isset($this->fk_product) ? $this->fk_product : "null") . ","; - $sql .= " fk_soc=" . (isset($this->fk_soc) ? $this->fk_soc : "null") . ","; - $sql .= " price=" . (isset($this->price) ? $this->price : "null") . ","; - $sql .= " price_ttc=" . (isset($this->price_ttc) ? $this->price_ttc : "null") . ","; - $sql .= " price_min=" . (isset($this->price_min) ? $this->price_min : "null") . ","; - $sql .= " price_min_ttc=" . (isset($this->price_min_ttc) ? $this->price_min_ttc : "null") . ","; - $sql .= " price_base_type=" . (isset($this->price_base_type) ? "'" . $this->db->escape($this->price_base_type) . "'" : "null") . ","; + $sql .= " entity=".$conf->entity.","; + $sql .= " datec='".$this->db->idate(dol_now())."',"; + $sql .= " tms=".(dol_strlen($this->tms) != 0 ? "'".$this->db->idate($this->tms)."'" : 'null').","; + $sql .= " fk_product=".(isset($this->fk_product) ? $this->fk_product : "null").","; + $sql .= " fk_soc=".(isset($this->fk_soc) ? $this->fk_soc : "null").","; + $sql .= " price=".(isset($this->price) ? $this->price : "null").","; + $sql .= " price_ttc=".(isset($this->price_ttc) ? $this->price_ttc : "null").","; + $sql .= " price_min=".(isset($this->price_min) ? $this->price_min : "null").","; + $sql .= " price_min_ttc=".(isset($this->price_min_ttc) ? $this->price_min_ttc : "null").","; + $sql .= " price_base_type=".(isset($this->price_base_type) ? "'".$this->db->escape($this->price_base_type)."'" : "null").","; $sql .= " default_vat_code = ".($this->default_vat_code ? "'".$this->db->escape($this->default_vat_code)."'" : "null").","; - $sql .= " tva_tx=" . (isset($this->tva_tx) ? (empty($this->tva_tx)?0:$this->tva_tx) : "null") . ","; - $sql .= " recuperableonly=" . (isset($this->recuperableonly) ? $this->recuperableonly : "null") . ","; - $sql .= " localtax1_tx=" . (isset($this->localtax1_tx) ? (empty($this->localtax1_tx)?0:$this->localtax1_tx) : "null") . ","; - $sql .= " localtax2_tx=" . (isset($this->localtax2_tx) ? (empty($this->localtax2_tx)?0:$this->localtax2_tx) : "null") . ","; - $sql .= " localtax1_type=" . (! empty($this->localtax1_type) ? "'".$this->db->escape($this->localtax1_type)."'": "'0'") . ","; - $sql .= " localtax2_type=" . (! empty($this->localtax2_type) ? "'".$this->db->escape($this->localtax2_type)."'": "'0'") . ","; - $sql .= " fk_user=" . $user->id . ","; - $sql .= " import_key=" . (isset($this->import_key) ? "'" . $this->db->escape($this->import_key) . "'" : "null") . ""; + $sql .= " tva_tx=".(isset($this->tva_tx) ? (empty($this->tva_tx) ? 0 : $this->tva_tx) : "null").","; + $sql .= " recuperableonly=".(isset($this->recuperableonly) ? $this->recuperableonly : "null").","; + $sql .= " localtax1_tx=".(isset($this->localtax1_tx) ? (empty($this->localtax1_tx) ? 0 : $this->localtax1_tx) : "null").","; + $sql .= " localtax2_tx=".(isset($this->localtax2_tx) ? (empty($this->localtax2_tx) ? 0 : $this->localtax2_tx) : "null").","; + $sql .= " localtax1_type=".(!empty($this->localtax1_type) ? "'".$this->db->escape($this->localtax1_type)."'" : "'0'").","; + $sql .= " localtax2_type=".(!empty($this->localtax2_type) ? "'".$this->db->escape($this->localtax2_type)."'" : "'0'").","; + $sql .= " fk_user=".$user->id.","; + $sql .= " import_key=".(isset($this->import_key) ? "'".$this->db->escape($this->import_key)."'" : "null").""; - $sql .= " WHERE rowid=" . $this->id; + $sql .= " WHERE rowid=".$this->id; - dol_syslog(get_class($this) . "::update", LOG_DEBUG); + 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(); } - if (! $error) { - if (! $notrigger) { + if (!$error) { + if (!$notrigger) { // Call triggers - include_once DOL_DOCUMENT_ROOT . '/core/class/interfaces.class.php'; - $interface=new Interfaces($this->db); - $result=$interface->run_triggers('PRODUCT_CUSTOMER_PRICE_UPDATE', $this, $user, $langs, $conf); - if ($result < 0) { $error++; $this->errors=$interface->errors; } + include_once DOL_DOCUMENT_ROOT.'/core/class/interfaces.class.php'; + $interface = new Interfaces($this->db); + $result = $interface->run_triggers('PRODUCT_CUSTOMER_PRICE_UPDATE', $this, $user, $langs, $conf); + if ($result < 0) { $error++; $this->errors = $interface->errors; } // End call triggers } } - if (! $error) { + if (!$error) { $result = $this->setPriceOnAffiliateThirdparty($user, $forceupdateaffiliate); if ($result < 0) { - $error ++; + $error++; } } // Commit or rollback if ($error) { foreach ($this->errors as $errmsg) { - dol_syslog(get_class($this) . "::update " . $errmsg, LOG_ERR); - $this->error .= ($this->error ? ', ' . $errmsg : $errmsg); + dol_syslog(get_class($this)."::update ".$errmsg, LOG_ERR); + $this->error .= ($this->error ? ', '.$errmsg : $errmsg); } $this->db->rollback(); - return - 1 * $error; + return -1 * $error; } else { $this->db->commit(); return 1; @@ -754,34 +754,34 @@ class Productcustomerprice extends CommonObject // Find all susidiaries $sql = "SELECT s.rowid"; - $sql .= " FROM " . MAIN_DB_PREFIX . "societe as s"; - $sql .= " WHERE s.parent = " . $this->fk_soc; - $sql .= " AND s.entity IN (" . getEntity('societe') . ")"; + $sql .= " FROM ".MAIN_DB_PREFIX."societe as s"; + $sql .= " WHERE s.parent = ".$this->fk_soc; + $sql .= " AND s.entity IN (".getEntity('societe').")"; - dol_syslog(get_class($this) . "::setPriceOnAffiliateThirdparty", LOG_DEBUG); + dol_syslog(get_class($this)."::setPriceOnAffiliateThirdparty", LOG_DEBUG); $resql = $this->db->query($sql); if ($resql) { - $this->lines = array (); + $this->lines = array(); $num = $this->db->num_rows($resql); - while ( ($obj = $this->db->fetch_object($resql)) && (empty($error)) ) { + while (($obj = $this->db->fetch_object($resql)) && (empty($error))) { // find if there is an existing line for the product and the subsidiaries $prodsocprice = new Productcustomerprice($this->db); - $filter = array ( - 't.fk_product' => $this->fk_product,'t.fk_soc' => $obj->rowid + $filter = array( + 't.fk_product' => $this->fk_product, 't.fk_soc' => $obj->rowid ); $result = $prodsocprice->fetch_all('', '', 0, 0, $filter); if ($result < 0) { - $error ++; + $error++; $this->error = $prodsocprice->error; } else { // There is one line if (count($prodsocprice->lines) > 0) { // If force update => Update - if (! empty($forceupdateaffiliate)) { + if (!empty($forceupdateaffiliate)) { $prodsocpriceupd = new Productcustomerprice($this->db); $prodsocpriceupd->fetch($prodsocprice->lines [0]->id); @@ -793,7 +793,7 @@ class Productcustomerprice extends CommonObject $resultupd = $prodsocpriceupd->update($user, 0, $forceupdateaffiliate); if ($result < 0) { - $error ++; + $error++; $this->error = $prodsocpriceupd->error; } } @@ -810,7 +810,7 @@ class Productcustomerprice extends CommonObject $resultupd = $prodsocpricenew->create($user, 0, $forceupdateaffiliate); if ($result < 0) { - $error ++; + $error++; $this->error = $prodsocpriceupd->error; } } @@ -821,11 +821,11 @@ class Productcustomerprice extends CommonObject if (empty($error)) { return 1; } else { - return - 1; + return -1; } } else { - $this->error = "Error " . $this->db->lasterror(); - return - 1; + $this->error = "Error ".$this->db->lasterror(); + return -1; } } @@ -844,8 +844,8 @@ class Productcustomerprice 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. @@ -858,26 +858,26 @@ class Productcustomerprice extends CommonObject } } - if (! $error) { - $sql = "DELETE FROM " . MAIN_DB_PREFIX . "product_customer_price"; - $sql .= " WHERE rowid=" . $this->id; + if (!$error) { + $sql = "DELETE FROM ".MAIN_DB_PREFIX."product_customer_price"; + $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) { - $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) { - dol_syslog(get_class($this) . "::delete " . $errmsg, LOG_ERR); - $this->error .= ($this->error ? ', ' . $errmsg : $errmsg); + dol_syslog(get_class($this)."::delete ".$errmsg, LOG_ERR); + $this->error .= ($this->error ? ', '.$errmsg : $errmsg); } $this->db->rollback(); - return - 1 * $error; + return -1 * $error; } else { $this->db->commit(); return 1; @@ -908,28 +908,28 @@ class Productcustomerprice extends CommonObject // ... // Create clone - $object->context['createfromclone']='createfromclone'; + $object->context['createfromclone'] = 'createfromclone'; $result = $object->create($user); // Other options if ($result < 0) { $this->error = $object->error; - $this->errors=array_merge($this->errors, $object->errors); + $this->errors = array_merge($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 { $this->db->rollback(); - return - 1; + return -1; } } diff --git a/htdocs/product/document.php b/htdocs/product/document.php index ef508c9a200..f12b20b7921 100644 --- a/htdocs/product/document.php +++ b/htdocs/product/document.php @@ -62,33 +62,33 @@ if (empty($page) || $page == -1) { $page = 0; } // If $page is not defined, $offset = $conf->liste_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 Product($db); -if ($id > 0 || ! empty($ref)) +if ($id > 0 || !empty($ref)) { $result = $object->fetch($id, $ref); - if (! empty($conf->product->enabled)) $upload_dir = $conf->product->multidir_output[$object->entity].'/'.get_exdir(0, 0, 0, 0, $object, 'product').dol_sanitizeFileName($object->ref); - elseif (! empty($conf->service->enabled)) $upload_dir = $conf->service->multidir_output[$object->entity].'/'.get_exdir(0, 0, 0, 0, $object, 'product').dol_sanitizeFileName($object->ref); + if (!empty($conf->product->enabled)) $upload_dir = $conf->product->multidir_output[$object->entity].'/'.get_exdir(0, 0, 0, 0, $object, 'product').dol_sanitizeFileName($object->ref); + elseif (!empty($conf->service->enabled)) $upload_dir = $conf->service->multidir_output[$object->entity].'/'.get_exdir(0, 0, 0, 0, $object, 'product').dol_sanitizeFileName($object->ref); - if (! empty($conf->global->PRODUCT_USE_OLD_PATH_FOR_PHOTO)) // For backward compatiblity, we scan also old dirs + if (!empty($conf->global->PRODUCT_USE_OLD_PATH_FOR_PHOTO)) // For backward compatiblity, we scan also old dirs { - if (! empty($conf->product->enabled)) $upload_dirold = $conf->product->multidir_output[$object->entity].'/'.substr(substr("000".$object->id, -2), 1, 1).'/'.substr(substr("000".$object->id, -2), 0, 1).'/'.$object->id."/photos"; + if (!empty($conf->product->enabled)) $upload_dirold = $conf->product->multidir_output[$object->entity].'/'.substr(substr("000".$object->id, -2), 1, 1).'/'.substr(substr("000".$object->id, -2), 0, 1).'/'.$object->id."/photos"; else $upload_dirold = $conf->service->multidir_output[$object->entity].'/'.substr(substr("000".$object->id, -2), 1, 1).'/'.substr(substr("000".$object->id, -2), 0, 1).'/'.$object->id."/photos"; } } -$modulepart='produit'; +$modulepart = 'produit'; /* * Actions */ -$parameters=array('id'=>$id); -$reshook=$hookmanager->executeHooks('doActions', $parameters, $object, $action); // Note that $action and $object may have been modified by some hooks +$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 (empty($reshook)) @@ -102,10 +102,10 @@ if (empty($reshook)) $urlfile = GETPOST('urlfile', 'alpha'); $filename = basename($urlfile); $filetomerge = new Propalmergepdfproduct($db); - $filetomerge->fk_product=$object->id; - $filetomerge->file_name=$filename; - $result=$filetomerge->delete_by_file($user); - if ($result<0) { + $filetomerge->fk_product = $object->id; + $filetomerge->file_name = $filename; + $result = $filetomerge->delete_by_file($user); + if ($result < 0) { setEventMessages($filetomerge->error, $filetomerge->errors, 'errors'); } } @@ -115,7 +115,7 @@ if (empty($reshook)) include_once DOL_DOCUMENT_ROOT.'/core/actions_linkedfiles.inc.php'; } -if ($action=='filemerge') +if ($action == 'filemerge') { $is_refresh = GETPOST('refresh'); if (empty($is_refresh)) { @@ -131,11 +131,11 @@ if ($action=='filemerge') $filetomerge = new Propalmergepdfproduct($db); if ($conf->global->MAIN_MULTILANGS) { - $result=$filetomerge->delete_by_product($user, $object->id, $lang_id); + $result = $filetomerge->delete_by_product($user, $object->id, $lang_id); } else { - $result=$filetomerge->delete_by_product($user, $object->id); + $result = $filetomerge->delete_by_product($user, $object->id); } - if ($result<0) { + if ($result < 0) { setEventMessages($filetomerge->error, $filetomerge->errors, 'errors'); } @@ -149,8 +149,8 @@ if ($action=='filemerge') $filetomerge->lang = $lang_id; } - $result=$filetomerge->create($user); - if ($result<0) { + $result = $filetomerge->create($user); + if ($result < 0) { setEventMessages($filetomerge->error, $filetomerge->errors, 'errors'); } } @@ -170,13 +170,13 @@ $helpurl = ''; $shortlabel = dol_trunc($object->label, 16); if (GETPOST("type") == '0' || ($object->type == Product::TYPE_PRODUCT)) { - $title = $langs->trans('Product')." ". $shortlabel ." - ".$langs->trans('Documents'); - $helpurl='EN:Module_Products|FR:Module_Produits|ES:Módulo_Productos'; + $title = $langs->trans('Product')." ".$shortlabel." - ".$langs->trans('Documents'); + $helpurl = 'EN:Module_Products|FR:Module_Produits|ES:Módulo_Productos'; } if (GETPOST("type") == '1' || ($object->type == Product::TYPE_SERVICE)) { - $title = $langs->trans('Service')." ". $shortlabel ." - ".$langs->trans('Documents'); - $helpurl='EN:Module_Services_En|FR:Module_Services|ES:Módulo_Servicios'; + $title = $langs->trans('Service')." ".$shortlabel." - ".$langs->trans('Documents'); + $helpurl = 'EN:Module_Services_En|FR:Module_Services|ES:Módulo_Servicios'; } llxHeader('', $title, $helpurl); @@ -234,8 +234,8 @@ if ($object->id) dol_fiche_end(); $permission = (($object->type == Product::TYPE_PRODUCT && $user->rights->produit->creer) || ($object->type == Product::TYPE_SERVICE && $user->rights->service->creer)); - $param = '&id=' . $object->id; - include_once DOL_DOCUMENT_ROOT . '/core/tpl/document_actions_post_headers.tpl.php'; + $param = '&id='.$object->id; + include_once DOL_DOCUMENT_ROOT.'/core/tpl/document_actions_post_headers.tpl.php'; // Merge propal PDF document PDF files @@ -255,7 +255,7 @@ if ($object->id) $filearray = dol_dir_list($upload_dir, "files", 0, '', '\.meta$', 'name', SORT_ASC, 1); - if (! empty($conf->global->PRODUCT_USE_OLD_PATH_FOR_PHOTO)) // For backward compatiblity, we scan also old dirs + if (!empty($conf->global->PRODUCT_USE_OLD_PATH_FOR_PHOTO)) // For backward compatiblity, we scan also old dirs { $filearray = array_merge($filearray, dol_dir_list($upload_dirold, "files", 0, '', '\.meta$', 'name', SORT_ASC, 1)); } @@ -269,8 +269,8 @@ if ($object->id) print $langs->trans('PropalMergePdfProductActualFile'); } - print '
    '; - print ''; + print ''; + print ''; print ''; if (count($filetomerge->lines) == 0) { print $langs->trans('PropalMergePdfProductChooseFile'); @@ -291,7 +291,7 @@ if ($object->id) print Form::selectarray('lang_id', $langs_available, $default_lang, 0, 0, 0, '', 0, 0, 0, 'ASC'); if ($conf->global->MAIN_MULTILANGS) { - print ''; + print ''; } print '
    '; - print '' . $filename . ''; + print ''.$filename.''; print '
    '; - print ''; + print ''; print '
    '; diff --git a/htdocs/product/dynamic_price/editor.php b/htdocs/product/dynamic_price/editor.php index 026c036bc97..9b16db0eef9 100644 --- a/htdocs/product/dynamic_price/editor.php +++ b/htdocs/product/dynamic_price/editor.php @@ -177,7 +177,7 @@ print ''; +print ''; // Price expression selector print '
    '.$langs->trans("PriceExpressionSelected").''; diff --git a/htdocs/product/fournisseurs.php b/htdocs/product/fournisseurs.php index e1940864dd0..b419185d84e 100644 --- a/htdocs/product/fournisseurs.php +++ b/htdocs/product/fournisseurs.php @@ -39,26 +39,26 @@ require_once DOL_DOCUMENT_ROOT.'/comm/propal/class/propal.class.php'; require_once DOL_DOCUMENT_ROOT.'/fourn/class/fournisseur.product.class.php'; require_once DOL_DOCUMENT_ROOT.'/product/dynamic_price/class/price_expression.class.php'; require_once DOL_DOCUMENT_ROOT.'/product/dynamic_price/class/price_parser.class.php'; -if(!empty($conf->barcode->enabled)) dol_include_once('/core/class/html.formbarcode.class.php'); +if (!empty($conf->barcode->enabled)) dol_include_once('/core/class/html.formbarcode.class.php'); // Load translation files required by the page $langs->loadLangs(array('products', 'suppliers', 'bills', 'margins')); $id = GETPOST('id', 'int'); $ref = GETPOST('ref', 'alpha'); -$rowid=GETPOST('rowid', 'int'); -$action=GETPOST('action', 'alpha'); -$cancel=GETPOST('cancel', 'alpha'); -$contextpage=GETPOST('contextpage', 'aZ')?GETPOST('contextpage', 'aZ'):'pricesuppliercard'; +$rowid = GETPOST('rowid', 'int'); +$action = GETPOST('action', 'alpha'); +$cancel = GETPOST('cancel', 'alpha'); +$contextpage = GETPOST('contextpage', 'aZ') ?GETPOST('contextpage', 'aZ') : 'pricesuppliercard'; -$socid=GETPOST('socid', 'int'); -$cost_price=GETPOST('cost_price', 'alpha'); -$backtopage=GETPOST('backtopage', 'alpha'); -$error=0; +$socid = GETPOST('socid', 'int'); +$cost_price = GETPOST('cost_price', 'alpha'); +$backtopage = GETPOST('backtopage', 'alpha'); +$error = 0; $extrafields = new ExtraFields($db); // If socid provided by ajax company selector -if (! empty($_REQUEST['search_fourn_id'])) +if (!empty($_REQUEST['search_fourn_id'])) { $_GET['id_fourn'] = $_GET['search_fourn_id']; $_POST['id_fourn'] = $_POST['search_fourn_id']; @@ -66,26 +66,26 @@ if (! empty($_REQUEST['search_fourn_id'])) } // Security check -$fieldvalue = (! empty($id) ? $id : (! empty($ref) ? $ref : '')); -$fieldtype = (! empty($ref) ? 'ref' : 'rowid'); -if ($user->socid) $socid=$user->socid; -$result=restrictedArea($user, 'produit|service', $fieldvalue, 'product&product', '', '', $fieldtype); +$fieldvalue = (!empty($id) ? $id : (!empty($ref) ? $ref : '')); +$fieldtype = (!empty($ref) ? 'ref' : 'rowid'); +if ($user->socid) $socid = $user->socid; +$result = restrictedArea($user, 'produit|service', $fieldvalue, 'product&product', '', '', $fieldtype); if (empty($user->rights->fournisseur->lire)) accessforbidden(); -$limit = GETPOST('limit', 'int')?GETPOST('limit', 'int'):$conf->liste_limit; +$limit = GETPOST('limit', 'int') ?GETPOST('limit', 'int') : $conf->liste_limit; $sortfield = GETPOST("sortfield", 'alpha'); $sortorder = GETPOST("sortorder", 'alpha'); -$page = (GETPOST("page", 'int')?GETPOST("page", 'int'):0); +$page = (GETPOST("page", 'int') ?GETPOST("page", 'int') : 0); if (empty($page) || $page == -1) { $page = 0; } // If $page is not defined, or '' or -1 $offset = $limit * $page; $pageprev = $page - 1; $pagenext = $page + 1; -if (! $sortfield) $sortfield="s.nom"; -if (! $sortorder) $sortorder="ASC"; +if (!$sortfield) $sortfield = "s.nom"; +if (!$sortorder) $sortorder = "ASC"; // Initialize technical object to manage hooks of page. Note that conf->hooks_modules contains array of hook context -$hookmanager->initHooks(array('pricesuppliercard','globalcard')); +$hookmanager->initHooks(array('pricesuppliercard', 'globalcard')); $object = new ProductFournisseur($db); if ($id > 0 || $ref) @@ -96,21 +96,21 @@ if ($id > 0 || $ref) $sortfield = GETPOST("sortfield", 'alpha'); $sortorder = GETPOST("sortorder", 'alpha'); -if (! $sortfield) $sortfield="s.nom"; -if (! $sortorder) $sortorder="ASC"; +if (!$sortfield) $sortfield = "s.nom"; +if (!$sortorder) $sortorder = "ASC"; /* * Actions */ -if ($cancel) $action=''; +if ($cancel) $action = ''; $usercanread = (($object->type == Product::TYPE_PRODUCT && $user->rights->produit->lire) || ($object->type == Product::TYPE_SERVICE && $user->rights->service->lire)); $usercancreate = (($object->type == Product::TYPE_PRODUCT && $user->rights->produit->creer) || ($object->type == Product::TYPE_SERVICE && $user->rights->service->creer)); -$parameters=array('socid'=>$socid, 'id_prod'=>$id); -$reshook=$hookmanager->executeHooks('doActions', $parameters, $object, $action); // Note that $action and $object may have been modified by some hooks +$parameters = array('socid'=>$socid, 'id_prod'=>$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 (empty($reshook)) @@ -119,13 +119,13 @@ if (empty($reshook)) { if ($id) { - $result=$object->fetch($id); + $result = $object->fetch($id); $object->cost_price = price2num($cost_price); - $result=$object->update($object->id, $user); + $result = $object->update($object->id, $user); if ($result > 0) { setEventMessages($langs->trans("RecordSaved"), null, 'mesgs'); - $action=''; + $action = ''; } else { @@ -140,11 +140,11 @@ if (empty($reshook)) if ($rowid) // id of product supplier price to remove { $action = ''; - $result=$object->remove_product_fournisseur_price($rowid); - if($result > 0){ - $db->query("DELETE FROM " . MAIN_DB_PREFIX . "product_fournisseur_price_extrafields WHERE fk_object = $rowid"); + $result = $object->remove_product_fournisseur_price($rowid); + if ($result > 0) { + $db->query("DELETE FROM ".MAIN_DB_PREFIX."product_fournisseur_price_extrafields WHERE fk_object = $rowid"); setEventMessages($langs->trans("PriceRemoved"), null, 'mesgs'); - }else{ + } else { $error++; setEventMessages($object->error, $object->errors, 'errors'); } @@ -153,23 +153,23 @@ if (empty($reshook)) if ($action == 'save_price') { - $id_fourn=GETPOST("id_fourn"); - if (empty($id_fourn)) $id_fourn=GETPOST("search_id_fourn"); - $ref_fourn=GETPOST("ref_fourn"); - if (empty($ref_fourn)) $ref_fourn=GETPOST("search_ref_fourn"); - $ref_fourn_old=GETPOST("ref_fourn_old"); + $id_fourn = GETPOST("id_fourn"); + if (empty($id_fourn)) $id_fourn = GETPOST("search_id_fourn"); + $ref_fourn = GETPOST("ref_fourn"); + if (empty($ref_fourn)) $ref_fourn = GETPOST("search_ref_fourn"); + $ref_fourn_old = GETPOST("ref_fourn_old"); if (empty($ref_fourn_old)) $ref_fourn_old = $ref_fourn; - $quantity=price2num(GETPOST("qty", 'nohtml'), 'MS'); - $remise_percent=price2num(GETPOST('remise_percent', 'alpha')); - $npr = preg_match('/\*/', $_POST['tva_tx']) ? 1 : 0 ; + $quantity = price2num(GETPOST("qty", 'nohtml'), 'MS'); + $remise_percent = price2num(GETPOST('remise_percent', 'alpha')); + $npr = preg_match('/\*/', $_POST['tva_tx']) ? 1 : 0; $tva_tx = str_replace('*', '', GETPOST('tva_tx', 'alpha')); $tva_tx = price2num($tva_tx); $price_expression = GETPOST('eid', 'int') ? GETPOST('eid', 'int') : ''; // Discard expression if not in expression mode $delivery_time_days = GETPOST('delivery_time_days', 'int') ? GETPOST('delivery_time_days', 'int') : ''; $supplier_reputation = GETPOST('supplier_reputation'); $supplier_description = GETPOST('supplier_description', 'alpha'); - $barcode=GETPOST('barcode', 'alpha'); - $fk_barcode_type=GETPOST('fk_barcode_type', 'int'); + $barcode = GETPOST('barcode', 'alpha'); + $fk_barcode_type = GETPOST('fk_barcode_type', 'int'); if ($tva_tx == '') { @@ -177,7 +177,7 @@ if (empty($reshook)) $langs->load("errors"); setEventMessages($langs->trans("ErrorFieldRequired", $langs->transnoentities("VATRateForSupplierProduct")), null, 'errors'); } - if (! is_numeric($tva_tx)) + if (!is_numeric($tva_tx)) { $error++; $langs->load("errors"); @@ -232,13 +232,13 @@ if (empty($reshook)) } } - if (! $error) + if (!$error) { $db->begin(); - if (! $error) + if (!$error) { - $ret=$object->add_fournisseur($user, $id_fourn, $ref_fourn_old, $quantity); // This insert record with no value for price. Values are update later with update_buyprice + $ret = $object->add_fournisseur($user, $id_fourn, $ref_fourn_old, $quantity); // This insert record with no value for price. Values are update later with update_buyprice if ($ret == -3) { $error++; @@ -255,37 +255,38 @@ if (empty($reshook)) } } - if (! $error) + if (!$error) { - $supplier=new Fournisseur($db); - $result=$supplier->fetch($id_fourn); - if (isset($_POST['ref_fourn_price_id'])) - $object->fetch_product_fournisseur_price($_POST['ref_fourn_price_id']); + $supplier = new Fournisseur($db); + $result = $supplier->fetch($id_fourn); + if (GETPOSTISSET('ref_fourn_price_id')) { + $object->fetch_product_fournisseur_price(GETPOST('ref_fourn_price_id', 'int')); + } - $extralabels=$extrafields->fetch_name_optionals_label("product_fournisseur_price"); + $extralabels = $extrafields->fetch_name_optionals_label("product_fournisseur_price"); $extrafield_values = $extrafields->getOptionalsFromPost("product_fournisseur_price"); $sql = ""; - $resql = $db->query("SELECT * FROM " . MAIN_DB_PREFIX . "product_fournisseur_price_extrafields WHERE fk_object = " . $object->product_fourn_price_id); + $resql = $db->query("SELECT * FROM ".MAIN_DB_PREFIX."product_fournisseur_price_extrafields WHERE fk_object = ".$object->product_fourn_price_id); // Insert a new extrafields row, if none exists if ($db->num_rows($resql) != 1) { - $sql = "INSERT INTO " . MAIN_DB_PREFIX . "product_fournisseur_price_extrafields (fk_object, "; + $sql = "INSERT INTO ".MAIN_DB_PREFIX."product_fournisseur_price_extrafields (fk_object, "; foreach ($extrafield_values as $key => $value) { - $sql .= str_replace('options_', '', $key) . ', '; + $sql .= str_replace('options_', '', $key).', '; } - $sql = substr($sql, 0, strlen($sql)-2) . ") VALUES (" . $object->product_fourn_price_id . ", "; + $sql = substr($sql, 0, strlen($sql) - 2).") VALUES (".$object->product_fourn_price_id.", "; foreach ($extrafield_values as $key => $value) { - $sql .= '"' . $value . '", '; + $sql .= '"'.$value.'", '; } - $sql = substr($sql, 0, strlen($sql)-2) . ')'; + $sql = substr($sql, 0, strlen($sql) - 2).')'; } // else update the existing one else { - $sql = "UPDATE " . MAIN_DB_PREFIX . "product_fournisseur_price_extrafields SET "; + $sql = "UPDATE ".MAIN_DB_PREFIX."product_fournisseur_price_extrafields SET "; foreach ($extrafield_values as $key => $value) { - $sql .= str_replace('options_', '', $key) . ' = "' . $value . '", '; + $sql .= str_replace('options_', '', $key).' = "'.$value.'", '; } - $sql = substr($sql, 0, strlen($sql)-2) . ' WHERE fk_object = ' . $object->product_fourn_price_id; + $sql = substr($sql, 0, strlen($sql) - 2).' WHERE fk_object = '.$object->product_fourn_price_id; } // Execute the sql command from above @@ -321,10 +322,10 @@ if (empty($reshook)) setEventMessages($priceparser->translatedError(), null, 'errors'); } } - if (! $error && ! empty($conf->dynamicprices->enabled)) + if (!$error && !empty($conf->dynamicprices->enabled)) { //Set the price expression for this supplier price - $ret=$object->setSupplierPriceExpression($price_expression); + $ret = $object->setSupplierPriceExpression($price_expression); if ($ret < 0) { $error++; @@ -334,10 +335,10 @@ if (empty($reshook)) } } - if (! $error) + if (!$error) { $db->commit(); - $action=''; + $action = ''; } else { @@ -361,13 +362,13 @@ $helpurl = ''; $shortlabel = dol_trunc($object->label, 16); if (GETPOST("type") == '0' || ($object->type == Product::TYPE_PRODUCT)) { - $title = $langs->trans('Product')." ". $shortlabel ." - ".$langs->trans('BuyingPrices'); - $helpurl='EN:Module_Products|FR:Module_Produits|ES:Módulo_Productos'; + $title = $langs->trans('Product')." ".$shortlabel." - ".$langs->trans('BuyingPrices'); + $helpurl = 'EN:Module_Products|FR:Module_Produits|ES:Módulo_Productos'; } if (GETPOST("type") == '1' || ($object->type == Product::TYPE_SERVICE)) { - $title = $langs->trans('Service')." ". $shortlabel ." - ".$langs->trans('BuyingPrices'); - $helpurl='EN:Module_Services_En|FR:Module_Services|ES:Módulo_Servicios'; + $title = $langs->trans('Service')." ".$shortlabel." - ".$langs->trans('BuyingPrices'); + $helpurl = 'EN:Module_Services_En|FR:Module_Services|ES:Módulo_Servicios'; } llxHeader('', $title, $helpurl); @@ -380,23 +381,23 @@ if ($id > 0 || $ref) { if ($action == 'ask_remove_pf') { $form = new Form($db); - $formconfirm = $form->formconfirm($_SERVER["PHP_SELF"] . '?id=' . $id . '&rowid=' . $rowid, $langs->trans('DeleteProductBuyPrice'), $langs->trans('ConfirmDeleteProductBuyPrice'), 'confirm_remove_pf', '', 0, 1); + $formconfirm = $form->formconfirm($_SERVER["PHP_SELF"].'?id='.$id.'&rowid='.$rowid, $langs->trans('DeleteProductBuyPrice'), $langs->trans('ConfirmDeleteProductBuyPrice'), 'confirm_remove_pf', '', 0, 1); echo $formconfirm; } if ($action <> 'edit' && $action <> 're-edit') { - $head=product_prepare_head($object); - $titre=$langs->trans("CardProduct".$object->type); - $picto=($object->type== Product::TYPE_SERVICE?'service':'product'); + $head = product_prepare_head($object); + $titre = $langs->trans("CardProduct".$object->type); + $picto = ($object->type == Product::TYPE_SERVICE ? 'service' : 'product'); dol_fiche_head($head, 'suppliers', $titre, -1, $picto); $linkback = ''.$langs->trans("BackToList").''; - $object->next_prev_filter=" fk_product_type = ".$object->type; + $object->next_prev_filter = " fk_product_type = ".$object->type; $shownav = 1; - if ($user->socid && ! in_array('product', explode(',', $conf->global->MAIN_MODULES_FOR_EXTERNAL))) $shownav=0; + if ($user->socid && !in_array('product', explode(',', $conf->global->MAIN_MODULES_FOR_EXTERNAL))) $shownav = 0; dol_banner_tab($object, 'ref', $linkback, $shownav, 'ref'); @@ -419,9 +420,9 @@ if ($id > 0 || $ref) // Cost price. Can be used for margin module for option "calculate margin on explicit cost price // Accountancy sell code print '
    '; - $textdesc =$langs->trans("CostPriceDescription"); - $textdesc.="
    ".$langs->trans("CostPriceUsage"); - $text=$form->textwithpicto($langs->trans("CostPrice"), $textdesc, 1, 'help', ''); + $textdesc = $langs->trans("CostPriceDescription"); + $textdesc .= "
    ".$langs->trans("CostPriceUsage"); + $text = $form->textwithpicto($langs->trans("CostPrice"), $textdesc, 1, 'help', ''); print $form->editfieldkey($text, 'cost_price', $object->cost_price, $object, $usercancreate, 'amount:6'); print '
    '; print $form->editfieldval($text, 'cost_price', $object->cost_price, $object, $usercancreate, 'amount:6'); @@ -436,7 +437,7 @@ if ($id > 0 || $ref) // Form to add or update a price - if (($action == 'add_price' || $action == 'update_price' ) && $usercancreate) + if (($action == 'add_price' || $action == 'update_price') && $usercancreate) { $langs->load("suppliers"); @@ -456,13 +457,13 @@ if ($id > 0 || $ref) dol_fiche_head(); - print ''; + print '
    '; // Supplier print ''; print ''; // Availability - if (! empty($conf->global->FOURN_PRODUCT_AVAILABILITY)) + if (!empty($conf->global->FOURN_PRODUCT_AVAILABILITY)) { $langs->load("propal"); print ''; // Vat rate - $default_vat=''; + $default_vat = ''; // We don't have supplier, so we try to guess. // For this we build a fictive supplier with same properties than user but using vat) $mysoc2 = clone $mysoc; - $mysoc2->name='Fictive seller with same country'; - $mysoc2->tva_assuj=1; - $default_vat=get_default_tva($mysoc2, $mysoc, $object->id, 0); - $default_npr=get_default_npr($mysoc2, $mysoc, $object->id, 0); - if (empty($default_vat)) $default_npr=$default_vat; + $mysoc2->name = 'Fictive seller with same country'; + $mysoc2->tva_assuj = 1; + $default_vat = get_default_tva($mysoc2, $mysoc, $object->id, 0); + $default_npr = get_default_npr($mysoc2, $mysoc, $object->id, 0); + if (empty($default_vat)) $default_npr = $default_vat; print ''; print ''; - if (! empty($conf->dynamicprices->enabled)) //Only show price mode and expression selector if module is enabled + if (!empty($conf->dynamicprices->enabled)) //Only show price mode and expression selector if module is enabled { // Price mode selector print ''; print ''; print ''; // Currency tx print ''; - print ''; print ''; // Currency price qty min print ''; - $pricesupplierincurrencytouse=(GETPOST('multicurrency_price')?GETPOST('multicurrency_price'):(isset($object->fourn_multicurrency_price)?$object->fourn_multicurrency_price:'')); + $pricesupplierincurrencytouse = (GETPOST('multicurrency_price') ?GETPOST('multicurrency_price') : (isset($object->fourn_multicurrency_price) ? $object->fourn_multicurrency_price : '')); print ''; // Price qty min - print ''; + print ''; print ''; - print ''; + print ''; } // Discount qty min print ''; - print ''; print ''; @@ -712,22 +713,22 @@ SCRIPT; // Reputation print ''; // Barcode - if (! empty($conf->barcode->enabled)) + if (!empty($conf->barcode->enabled)) { // Option to define a transport cost on supplier price print ''; - print ''; + print ''; print ''; print ''; $formbarcode = new FormBarCode($db); // Barcode type print ''; - print ''; + print ''; print ''; @@ -737,18 +738,18 @@ SCRIPT; // Option to define a transport cost on supplier price if ($conf->global->PRODUCT_CHARGES) { - if (! empty($conf->margin->enabled)) + if (!empty($conf->margin->enabled)) { print ''; print ''; - print ''; print ''; } } // Product description of the supplier - if (! empty($conf->global->PRODUIT_FOURN_TEXTS)) + if (!empty($conf->global->PRODUIT_FOURN_TEXTS)) { //WYSIWYG Editor require_once DOL_DOCUMENT_ROOT.'/core/class/doleditor.class.php'; @@ -765,28 +766,30 @@ SCRIPT; } $extrafields->fetch_name_optionals_label("product_fournisseur_price"); - $extralabels=$extrafields->attributes["product_fournisseur_price"]['label']; + $extralabels = $extrafields->attributes["product_fournisseur_price"]['label']; // Extrafields - $resql = $db->query("SELECT * FROM " . MAIN_DB_PREFIX . "product_fournisseur_price_extrafields WHERE fk_object = " . $rowid); - if ($db->num_rows($resql) != 1) { - foreach ($extralabels as $key => $value) { - if (! empty($extrafields->attributes["product_fournisseur_price"]['list'][$key]) && ($extrafields->attributes["product_fournisseur_price"]['list'][$key] == 1 || $extrafields->attributes["product_fournisseur_price"]['list'][$key] == 3 || ($action == "update_price" && $extrafields->attributes["product_fournisseur_price"]['list'][$key] == 4))) { - print 'attributes["product_fournisseur_price"]['required'][$key] ? ' class="fieldrequired"' : '') . '>' . $langs->trans($value) . ''; + $resql = $db->query("SELECT * FROM ".MAIN_DB_PREFIX."product_fournisseur_price_extrafields WHERE fk_object = ".$rowid); + if (!empty($extralabels)) { + if ($db->num_rows($resql) != 1) { + foreach ($extralabels as $key => $value) { + if (!empty($extrafields->attributes["product_fournisseur_price"]['list'][$key]) && ($extrafields->attributes["product_fournisseur_price"]['list'][$key] == 1 || $extrafields->attributes["product_fournisseur_price"]['list'][$key] == 3 || ($action == "update_price" && $extrafields->attributes["product_fournisseur_price"]['list'][$key] == 4))) { + print 'attributes["product_fournisseur_price"]['required'][$key] ? ' class="fieldrequired"' : '').'>'.$langs->trans($value).''; + } } - } - } else { - $resql = $db->fetch_object($resql); - foreach ($extralabels as $key => $value) { - if (! empty($extrafields->attributes["product_fournisseur_price"]['list'][$key]) && ($extrafields->attributes["product_fournisseur_price"]['list'][$key] == 1 || $extrafields->attributes["product_fournisseur_price"]['list'][$key] == 3 || ($action == "update_price" && $extrafields->attributes["product_fournisseur_price"]['list'][$key] == 4))) { - print 'attributes["product_fournisseur_price"]['required'][$key] ? ' class="fieldrequired"' : '') . '>' . $langs->trans($value) . ''; + } else { + $resql = $db->fetch_object($resql); + foreach ($extralabels as $key => $value) { + if (!empty($extrafields->attributes["product_fournisseur_price"]['list'][$key]) && ($extrafields->attributes["product_fournisseur_price"]['list'][$key] == 1 || $extrafields->attributes["product_fournisseur_price"]['list'][$key] == 3 || ($action == "update_price" && $extrafields->attributes["product_fournisseur_price"]['list'][$key] == 4))) { + print 'attributes["product_fournisseur_price"]['required'][$key] ? ' class="fieldrequired"' : '').'>'.$langs->trans($value).''; + } } } } if (is_object($hookmanager)) { - $parameters=array('id_fourn'=>$id_fourn,'prod_id'=>$object->id); - $reshook=$hookmanager->executeHooks('formObjectOptions', $parameters, $object, $action); + $parameters = array('id_fourn'=>$id_fourn, 'prod_id'=>$object->id); + $reshook = $hookmanager->executeHooks('formObjectOptions', $parameters, $object, $action); print $hookmanager->resPrint; } @@ -809,8 +812,8 @@ SCRIPT; if ($action != 'add_price' && $action != 'update_price') { - $parameters=array(); - $reshook=$hookmanager->executeHooks('addMoreActionsButtons', $parameters, $object, $action); // Note that $action and $object may have been modified by hook + $parameters = array(); + $reshook = $hookmanager->executeHooks('addMoreActionsButtons', $parameters, $object, $action); // Note that $action and $object may have been modified by hook if (empty($reshook)) { if ($usercancreate) @@ -826,10 +829,10 @@ SCRIPT; if ($user->rights->fournisseur->lire) // Duplicate ? this check is already in the head of this file { - $param=''; - if (! empty($contextpage) && $contextpage != $_SERVER["PHP_SELF"]) $param.='&contextpage='.urlencode($contextpage); - if ($limit > 0 && $limit != $conf->liste_limit) $param.='&limit='.urlencode($limit); - $param.='&ref='.urlencode($object->ref); + $param = ''; + if (!empty($contextpage) && $contextpage != $_SERVER["PHP_SELF"]) $param .= '&contextpage='.urlencode($contextpage); + if ($limit > 0 && $limit != $conf->liste_limit) $param .= '&limit='.urlencode($limit); + $param .= '&ref='.urlencode($object->ref); $product_fourn = new ProductFournisseur($db); $product_fourn_list = $product_fourn->list_product_fournisseur_price($object->id, $sortfield, $sortorder, $limit, $offset); @@ -842,9 +845,9 @@ SCRIPT; // Suppliers list title print '
    '; - print '
    '.$langs->trans("Supplier").''; if ($rowid) { - $supplier=new Fournisseur($db); + $supplier = new Fournisseur($db); $supplier->fetch($socid); print $supplier->getNomUrl(1); print ''; @@ -472,12 +473,12 @@ if ($id > 0 || $ref) } else { - $events=array(); - $events[]=array('method' => 'getVatRates', 'url' => dol_buildpath('/core/ajax/vatrates.php', 1), 'htmlname' => 'tva_tx', 'params' => array()); + $events = array(); + $events[] = array('method' => 'getVatRates', 'url' => dol_buildpath('/core/ajax/vatrates.php', 1), 'htmlname' => 'tva_tx', 'params' => array()); print $form->select_company(GETPOST("id_fourn", 'alpha'), 'id_fourn', 'fournisseur=1', 'SelectThirdParty', 0, 0, $events); - $parameters=array('filtre'=>"fournisseur=1",'html_name'=>'id_fourn','selected'=>GETPOST("id_fourn"),'showempty'=>1,'prod_id'=>$object->id); - $reshook=$hookmanager->executeHooks('formCreateThirdpartyOptions', $parameters, $object, $action); + $parameters = array('filtre'=>"fournisseur=1", 'html_name'=>'id_fourn', 'selected'=>GETPOST("id_fourn"), 'showempty'=>1, 'prod_id'=>$object->id); + $reshook = $hookmanager->executeHooks('formCreateThirdpartyOptions', $parameters, $object, $action); if (empty($reshook)) { if (empty($form->result)) @@ -497,13 +498,13 @@ if ($id > 0 || $ref) } else { - print ''; + print ''; } print '
    '.$langs->trans("Availability").''; @@ -529,46 +530,46 @@ if ($id > 0 || $ref) if ($conf->global->PRODUCT_USE_UNITS) { $unit = $object->getLabelOfUnit(); if ($unit !== '') { - print '  ' . $langs->trans($unit); + print '  '.$langs->trans($unit); } } print '
    '.$langs->trans("VATRateForSupplierProduct").''; //print $form->load_tva('tva_tx',$object->tva_tx,$supplier,$mysoc); // Do not use list here as it may be any vat rates for any country - if (! empty($rowid)) // If we have a supplier, it is an update, we must show the vat of current supplier price + if (!empty($rowid)) // If we have a supplier, it is an update, we must show the vat of current supplier price { - $tmpproductsupplier=new ProductFournisseur($db); + $tmpproductsupplier = new ProductFournisseur($db); $tmpproductsupplier->fetch_product_fournisseur_price($rowid, 1); - $default_vat=$tmpproductsupplier->fourn_tva_tx; - $default_npr=$tmpproductsupplier->fourn_tva_npr; + $default_vat = $tmpproductsupplier->fourn_tva_tx; + $default_npr = $tmpproductsupplier->fourn_tva_npr; } else { if (empty($default_vat)) { - $default_vat=$object->tva_tx; + $default_vat = $object->tva_tx; } } - $vattosuggest=(GETPOST("tva_tx")?vatrate(GETPOST("tva_tx")):($default_vat!=''?vatrate($default_vat):'')); - $vattosuggest=preg_replace('/\s*\(.*\)$/', '', $vattosuggest); + $vattosuggest = (GETPOST("tva_tx") ?vatrate(GETPOST("tva_tx")) : ($default_vat != '' ?vatrate($default_vat) : '')); + $vattosuggest = preg_replace('/\s*\(.*\)$/', '', $vattosuggest); print ''; print '
    '.$langs->trans("PriceMode").''; @@ -606,28 +607,28 @@ if ($id > 0 || $ref) // Currency print '
    '.$langs->trans("Currency").''; - $currencycodetouse = GETPOST('multicurrency_code')?GETPOST('multicurrency_code'):(isset($object->fourn_multicurrency_code)?$object->fourn_multicurrency_code:''); - if (empty($currencycodetouse) && $object->fourn_multicurrency_tx == 1) $currencycodetouse=$conf->currency; + $currencycodetouse = GETPOST('multicurrency_code') ?GETPOST('multicurrency_code') : (isset($object->fourn_multicurrency_code) ? $object->fourn_multicurrency_code : ''); + if (empty($currencycodetouse) && $object->fourn_multicurrency_tx == 1) $currencycodetouse = $conf->currency; print $form->selectMultiCurrency($currencycodetouse, "multicurrency_code", 1); print '
    '.$langs->trans("CurrencyRate").''; + print ''; print '
    '.$langs->trans("PriceQtyMinCurrency").''; print ' '; - print $form->selectPriceBaseType((GETPOST('multicurrency_price_base_type')?GETPOST('multicurrency_price_base_type'):'HT'), "multicurrency_price_base_type"); // We keep 'HT' here, multicurrency_price_base_type is not yet supported for supplier prices + print $form->selectPriceBaseType((GETPOST('multicurrency_price_base_type') ?GETPOST('multicurrency_price_base_type') : 'HT'), "multicurrency_price_base_type"); // We keep 'HT' here, multicurrency_price_base_type is not yet supported for supplier prices print '
    ' . $langs->trans("PriceQtyMin") . '
    '.$langs->trans("PriceQtyMin").''; print ''; print ''; @@ -690,17 +691,17 @@ if ($id > 0 || $ref) SCRIPT; } else { // Price qty min - print '
    ' . $langs->trans("PriceQtyMin") . ''; + print '
    '.$langs->trans("PriceQtyMin").''; print ' '; - print $form->selectPriceBaseType((GETPOST('price_base_type') ? GETPOST('price_base_type') : 'HT'), "price_base_type"); // We keep 'HT' here, price_base_type is not yet supported for supplier prices + print $form->selectPriceBaseType((GETPOST('price_base_type') ? GETPOST('price_base_type') : 'HT'), "price_base_type"); // We keep 'HT' here, price_base_type is not yet supported for supplier prices print '
    '.$langs->trans("DiscountQtyMin").' %'; + print ' %'; print '
    '.$langs->trans("SupplierReputation").''; - echo $form->selectarray('supplier_reputation', $object->reputations, $supplier_reputation?$supplier_reputation:$object->supplier_reputation); + echo $form->selectarray('supplier_reputation', $object->reputations, $supplier_reputation ? $supplier_reputation : $object->supplier_reputation); print '
    ' . $langs->trans('BarcodeValue') . ''.$langs->trans('BarcodeValue').'
    ' . $langs->trans('BarcodeType') . ''.$langs->trans('BarcodeType').''; print $formbarcode->selectBarcodeType(($rowid ? $object->fourn_fk_barcode_type : $conf->global->PRODUIT_DEFAULT_BARCODE_TYPE), 'fk_barcode_type', 1); print '
    '.$langs->trans("Charges").''; + print ''; print '
    ' . $extrafields->showInputField($key, '', '', '', '', '', 0, 'product_fournisseur_price') . '
    '.$extrafields->showInputField($key, '', '', '', '', '', 0, 'product_fournisseur_price').'
    ' . $extrafields->showInputField($key, $resql->{$key}, '', '', '', '', 0, 'product_fournisseur_price') . '
    '.$extrafields->showInputField($key, $resql->{$key}, '', '', '', '', 0, 'product_fournisseur_price').'
    '; + print '
    '; - $param="&id=".$object->id; + $param = "&id=".$object->id; print ''; print_liste_field_titre("AppliedPricesFrom", $_SERVER["PHP_SELF"], "pfp.datec", "", $param, "", $sortfield, $sortorder); @@ -873,30 +876,32 @@ SCRIPT; // fetch optionals attributes and labels $extrafields->fetch_name_optionals_label("product_fournisseur_price"); - $extralabels=$extrafields->attributes["product_fournisseur_price"]['label']; - foreach ($extralabels as $key => $value) { - // Show field if not hidden - if (! empty($extrafields->attributes["product_fournisseur_price"]['list'][$key]) && $extrafields->attributes["product_fournisseur_price"]['list'][$key] != 3) { - print_liste_field_titre($value, $_SERVER["PHP_SELF"], '', '', $param, '', $sortfield, $sortorder, 'right '); + $extralabels = $extrafields->attributes["product_fournisseur_price"]['label']; + if (!empty($extralabels)) { + foreach ($extralabels as $key => $value) { + // Show field if not hidden + if (!empty($extrafields->attributes["product_fournisseur_price"]['list'][$key]) && $extrafields->attributes["product_fournisseur_price"]['list'][$key] != 3) { + print_liste_field_titre($value, $_SERVER["PHP_SELF"], '', '', $param, '', $sortfield, $sortorder, 'right '); + } } } if (is_object($hookmanager)) { - $parameters=array('id_fourn'=>$id_fourn, 'prod_id'=>$object->id); - $reshook=$hookmanager->executeHooks('printFieldListTitle', $parameters, $object, $action); + $parameters = array('id_fourn'=>$id_fourn, 'prod_id'=>$object->id); + $reshook = $hookmanager->executeHooks('printFieldListTitle', $parameters, $object, $action); } print_liste_field_titre(''); print "\n"; if (is_array($product_fourn_list)) { - foreach($product_fourn_list as $productfourn) + foreach ($product_fourn_list as $productfourn) { print ''; // Date from - print ''; + print ''; // Supplier print ''; @@ -912,10 +917,10 @@ SCRIPT; } // Availability - if(!empty($conf->global->FOURN_PRODUCT_AVAILABILITY)) + if (!empty($conf->global->FOURN_PRODUCT_AVAILABILITY)) { $form->load_cache_availability(); - $availability= $form->cache_availability[$productfourn->fk_availability]['label']; + $availability = $form->cache_availability[$productfourn->fk_availability]['label']; print ''; } @@ -926,7 +931,7 @@ SCRIPT; if ($conf->global->PRODUCT_USE_UNITS) { $unit = $object->getLabelOfUnit(); if ($unit !== '') { - print '  ' . $langs->trans($unit); + print '  '.$langs->trans($unit); } } print ''; @@ -938,7 +943,7 @@ SCRIPT; // Price for the quantity print ''; if ($conf->multicurrency->enabled) { @@ -991,9 +996,9 @@ SCRIPT; // Barcode type print ''; } @@ -1003,26 +1008,28 @@ SCRIPT; print ''; // Extrafields - $resql = $db->query("SELECT * FROM " . MAIN_DB_PREFIX . "product_fournisseur_price_extrafields WHERE fk_object = " . $productfourn->product_fourn_price_id); - if ($db->num_rows($resql) != 1) { - foreach ($extralabels as $key => $value) { - if (! empty($extrafields->attributes["product_fournisseur_price"]['list'][$key]) && $extrafields->attributes["product_fournisseur_price"]['list'][$key] != 3) { - print ""; + $resql = $db->query("SELECT * FROM ".MAIN_DB_PREFIX."product_fournisseur_price_extrafields WHERE fk_object = ".$productfourn->product_fourn_price_id); + if (!empty($extralabels)) { + if ($db->num_rows($resql) != 1) { + foreach ($extralabels as $key => $value) { + if (!empty($extrafields->attributes["product_fournisseur_price"]['list'][$key]) && $extrafields->attributes["product_fournisseur_price"]['list'][$key] != 3) { + print ""; + } } - } - } else { - $resql = $db->fetch_object($resql); - foreach ($extralabels as $key => $value) { - if (! empty($extrafields->attributes["product_fournisseur_price"]['list'][$key]) && $extrafields->attributes["product_fournisseur_price"]['list'][$key] != 3) { - print '"; + } else { + $resql = $db->fetch_object($resql); + foreach ($extralabels as $key => $value) { + if (!empty($extrafields->attributes["product_fournisseur_price"]['list'][$key]) && $extrafields->attributes["product_fournisseur_price"]['list'][$key] != 3) { + print '"; + } } } } if (is_object($hookmanager)) { - $parameters=array('id_pfp'=>$productfourn->product_fourn_price_id,'id_fourn'=>$id_fourn,'prod_id'=>$object->id); - $reshook=$hookmanager->executeHooks('printFieldListValue', $parameters, $object, $action); + $parameters = array('id_pfp'=>$productfourn->product_fourn_price_id, 'id_fourn'=>$id_fourn, 'prod_id'=>$object->id); + $reshook = $hookmanager->executeHooks('printFieldListValue', $parameters, $object, $action); } // Modify-Remove diff --git a/htdocs/product/index.php b/htdocs/product/index.php index 87e5eb6d2fb..6f5467a4517 100644 --- a/htdocs/product/index.php +++ b/htdocs/product/index.php @@ -33,14 +33,14 @@ require_once DOL_DOCUMENT_ROOT.'/product/class/product.class.php'; require_once DOL_DOCUMENT_ROOT.'/core/lib/date.lib.php'; require_once DOL_DOCUMENT_ROOT.'/product/dynamic_price/class/price_parser.class.php'; -$type=GETPOST("type", 'int'); -if ($type =='' && !$user->rights->produit->lire) $type='1'; // Force global page on service page only -if ($type =='' && !$user->rights->service->lire) $type='0'; // Force global page on product page only +$type = GETPOST("type", 'int'); +if ($type == '' && !$user->rights->produit->lire) $type = '1'; // Force global page on service page only +if ($type == '' && !$user->rights->service->lire) $type = '0'; // Force global page on product page only // Security check -if ($type=='0') $result=restrictedArea($user, 'produit'); -elseif ($type=='1') $result=restrictedArea($user, 'service'); -else $result=restrictedArea($user, 'produit|service'); +if ($type == '0') $result = restrictedArea($user, 'produit'); +elseif ($type == '1') $result = restrictedArea($user, 'service'); +else $result = restrictedArea($user, 'produit|service'); // Load translation files required by the page $langs->loadLangs(array('products', 'stocks')); @@ -57,38 +57,38 @@ $product_static = new Product($db); $transAreaType = $langs->trans("ProductsAndServicesArea"); -$helpurl=''; -if (! isset($_GET["type"])) +$helpurl = ''; +if (!isset($_GET["type"])) { $transAreaType = $langs->trans("ProductsAndServicesArea"); - $helpurl='EN:Module_Products|FR:Module_Produits|ES:Módulo_Productos'; + $helpurl = 'EN:Module_Products|FR:Module_Produits|ES:Módulo_Productos'; } if ((isset($_GET["type"]) && $_GET["type"] == 0) || empty($conf->service->enabled)) { $transAreaType = $langs->trans("ProductsArea"); - $helpurl='EN:Module_Products|FR:Module_Produits|ES:Módulo_Productos'; + $helpurl = 'EN:Module_Products|FR:Module_Produits|ES:Módulo_Productos'; } if ((isset($_GET["type"]) && $_GET["type"] == 1) || empty($conf->product->enabled)) { $transAreaType = $langs->trans("ServicesArea"); - $helpurl='EN:Module_Services_En|FR:Module_Services|ES:Módulo_Servicios'; + $helpurl = 'EN:Module_Services_En|FR:Module_Services|ES:Módulo_Servicios'; } llxHeader("", $langs->trans("ProductsAndServices"), $helpurl); -$linkback=""; +$linkback = ""; print load_fiche_titre($transAreaType, $linkback, 'products'); 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->product->enabled) || ! empty($conf->service->enabled)) && ($user->rights->produit->lire || $user->rights->service->lire)) + if ((!empty($conf->product->enabled) || !empty($conf->service->enabled)) && ($user->rights->produit->lire || $user->rights->service->lire)) { - $listofsearchfields['search_product']=array('text'=>'ProductOrService'); + $listofsearchfields['search_product'] = array('text'=>'ProductOrService'); } if (count($listofsearchfields)) @@ -97,8 +97,8 @@ if (! empty($conf->global->MAIN_SEARCH_FORM_ON_HOME_AREAS)) // This is usele print ''; print '
    '; print '
    '.dol_print_date(($productfourn->fourn_date_creation ? $productfourn->fourn_date_creation: $productfourn->date_creation), 'dayhour').''.dol_print_date(($productfourn->fourn_date_creation ? $productfourn->fourn_date_creation : $productfourn->date_creation), 'dayhour').''.$productfourn->getSocNomUrl(1, 'supplier').''.$availability.''; - print $productfourn->fourn_price?price($productfourn->fourn_price):""; + print $productfourn->fourn_price ?price($productfourn->fourn_price) : ""; print ''; - $productfourn->barcode_type = !empty($productfourn->fk_barcode_type) ? $productfourn->fk_barcode_type:0; + $productfourn->barcode_type = !empty($productfourn->fk_barcode_type) ? $productfourn->fk_barcode_type : 0; $productfourn->fetch_barcode(); - print $productfourn->barcode_type_label?$productfourn->barcode_type_label:($productfourn->barcode?'
    '.$langs->trans("SetDefaultBarcodeType").'
    ':''); + print $productfourn->barcode_type_label ? $productfourn->barcode_type_label : ($productfourn->barcode ? '
    '.$langs->trans("SetDefaultBarcodeType").'
    ' : ''); print '
    ' . $extrafields->showOutputField($key, $resql->{$key}) . "'.$extrafields->showOutputField($key, $resql->{$key})."
    '; - $i=0; - foreach($listofsearchfields as $key => $value) + $i = 0; + foreach ($listofsearchfields as $key => $value) { if ($i == 0) print ''; print ''; @@ -118,61 +118,61 @@ if (! empty($conf->global->MAIN_SEARCH_FORM_ON_HOME_AREAS)) // This is usele * Number of products and/or services */ $prodser = array(); -$prodser[0][0]=$prodser[0][1]=$prodser[0][2]=$prodser[0][3]=0; -$prodser[1][0]=$prodser[1][1]=$prodser[1][2]=$prodser[1][3]=0; +$prodser[0][0] = $prodser[0][1] = $prodser[0][2] = $prodser[0][3] = 0; +$prodser[1][0] = $prodser[1][1] = $prodser[1][2] = $prodser[1][3] = 0; $sql = "SELECT COUNT(p.rowid) as total, p.fk_product_type, p.tosell, p.tobuy"; -$sql.= " FROM ".MAIN_DB_PREFIX."product as p"; -$sql.= ' WHERE p.entity IN ('.getEntity($product_static->element, 1).')'; +$sql .= " FROM ".MAIN_DB_PREFIX."product as p"; +$sql .= ' WHERE p.entity IN ('.getEntity($product_static->element, 1).')'; // Add where from hooks -$parameters=array(); -$reshook=$hookmanager->executeHooks('printFieldListWhere', $parameters); // Note that $action and $object may have been modified by hook -$sql.=$hookmanager->resPrint; -$sql.= " GROUP BY p.fk_product_type, p.tosell, p.tobuy"; +$parameters = array(); +$reshook = $hookmanager->executeHooks('printFieldListWhere', $parameters); // Note that $action and $object may have been modified by hook +$sql .= $hookmanager->resPrint; +$sql .= " GROUP BY p.fk_product_type, p.tosell, p.tobuy"; $result = $db->query($sql); while ($objp = $db->fetch_object($result)) { - $status=3; // On sale + On purchase - if (! $objp->tosell && ! $objp->tobuy) $status=0; // Not on sale, not on purchase - if ($objp->tosell && ! $objp->tobuy) $status=1; // On sale only - if (! $objp->tosell && $objp->tobuy) $status=2; // On purchase only - $prodser[$objp->fk_product_type][$status]=$objp->total; - if ($objp->tosell) $prodser[$objp->fk_product_type]['sell']+=$objp->total; - if ($objp->tobuy) $prodser[$objp->fk_product_type]['buy']+=$objp->total; - if (! $objp->tosell && ! $objp->tobuy) $prodser[$objp->fk_product_type]['none']+=$objp->total; + $status = 3; // On sale + On purchase + if (!$objp->tosell && !$objp->tobuy) $status = 0; // Not on sale, not on purchase + if ($objp->tosell && !$objp->tobuy) $status = 1; // On sale only + if (!$objp->tosell && $objp->tobuy) $status = 2; // On purchase only + $prodser[$objp->fk_product_type][$status] = $objp->total; + if ($objp->tosell) $prodser[$objp->fk_product_type]['sell'] += $objp->total; + if ($objp->tobuy) $prodser[$objp->fk_product_type]['buy'] += $objp->total; + if (!$objp->tosell && !$objp->tobuy) $prodser[$objp->fk_product_type]['none'] += $objp->total; } if ($conf->use_javascript_ajax) { print '
    '; - print '
    '.$langs->trans("Search").'
    '; + print '
    '; print ''; print ''; print '
    '.$langs->trans("Statistics").'
    '; - $SommeA=$prodser[0]['sell']; - $SommeB=$prodser[0]['buy']; - $SommeC=$prodser[0]['none']; - $SommeD=$prodser[1]['sell']; - $SommeE=$prodser[1]['buy']; - $SommeF=$prodser[1]['none']; - $total=0; - $dataval=array(); - $datalabels=array(); - $i=0; + $SommeA = $prodser[0]['sell']; + $SommeB = $prodser[0]['buy']; + $SommeC = $prodser[0]['none']; + $SommeD = $prodser[1]['sell']; + $SommeE = $prodser[1]['buy']; + $SommeF = $prodser[1]['none']; + $total = 0; + $dataval = array(); + $datalabels = array(); + $i = 0; $total = $SommeA + $SommeB + $SommeC + $SommeD + $SommeE + $SommeF; - $dataseries=array(); - if (! empty($conf->product->enabled)) + $dataseries = array(); + if (!empty($conf->product->enabled)) { - $dataseries[]=array($langs->trans("ProductsOnSale"), round($SommeA)); - $dataseries[]=array($langs->trans("ProductsOnPurchase"), round($SommeB)); - $dataseries[]=array($langs->trans("ProductsNotOnSell"), round($SommeC)); + $dataseries[] = array($langs->trans("ProductsOnSale"), round($SommeA)); + $dataseries[] = array($langs->trans("ProductsOnPurchase"), round($SommeB)); + $dataseries[] = array($langs->trans("ProductsNotOnSell"), round($SommeC)); } - if (! empty($conf->service->enabled)) + if (!empty($conf->service->enabled)) { - $dataseries[]=array($langs->trans("ServicesOnSale"), round($SommeD)); - $dataseries[]=array($langs->trans("ServicesOnPurchase"), round($SommeE)); - $dataseries[]=array($langs->trans("ServicesNotOnSell"), round($SommeF)); + $dataseries[] = array($langs->trans("ServicesOnSale"), round($SommeD)); + $dataseries[] = array($langs->trans("ServicesOnPurchase"), round($SommeE)); + $dataseries[] = array($langs->trans("ServicesNotOnSell"), round($SommeF)); } include_once DOL_DOCUMENT_ROOT.'/core/class/dolgraph.class.php'; @@ -183,7 +183,7 @@ if ($conf->use_javascript_ajax) $dolgraph->SetType(array('pie')); $dolgraph->setWidth('100%'); $dolgraph->draw('idgraphstatus'); - print $dolgraph->show($total?0:1); + print $dolgraph->show($total ? 0 : 1); print '
    '; @@ -191,48 +191,48 @@ if ($conf->use_javascript_ajax) } -if (! empty($conf->categorie->enabled) && ! empty($conf->global->CATEGORY_GRAPHSTATS_ON_PRODUCTS)) +if (!empty($conf->categorie->enabled) && !empty($conf->global->CATEGORY_GRAPHSTATS_ON_PRODUCTS)) { require_once DOL_DOCUMENT_ROOT.'/categories/class/categorie.class.php'; print '
    '; print '
    '; - print ''; + print '
    '; print ''; print ''; - $total+=$obj->nb; + $total += $obj->nb; $i++; } } @@ -270,19 +270,19 @@ print '
    '; /* * Latest modified products */ -$max=15; +$max = 15; $sql = "SELECT p.rowid, p.label, p.price, p.ref, p.fk_product_type, p.tosell, p.tobuy, p.tobatch, p.fk_price_expression,"; -$sql.= " p.entity,"; -$sql.= " p.tms as datem"; -$sql.= " FROM ".MAIN_DB_PREFIX."product as p"; -$sql.= " WHERE p.entity IN (".getEntity($product_static->element, 1).")"; -if ($type != '') $sql.= " AND p.fk_product_type = ".$type; +$sql .= " p.entity,"; +$sql .= " p.tms as datem"; +$sql .= " FROM ".MAIN_DB_PREFIX."product as p"; +$sql .= " WHERE p.entity IN (".getEntity($product_static->element, 1).")"; +if ($type != '') $sql .= " AND p.fk_product_type = ".$type; // Add where from hooks -$parameters=array(); -$reshook=$hookmanager->executeHooks('printFieldListWhere', $parameters); // Note that $action and $object may have been modified by hook -$sql.=$hookmanager->resPrint; -$sql.= $db->order("p.tms", "DESC"); -$sql.= $db->plimit($max, 0); +$parameters = array(); +$reshook = $hookmanager->executeHooks('printFieldListWhere', $parameters); // Note that $action and $object may have been modified by hook +$sql .= $hookmanager->resPrint; +$sql .= $db->order("p.tms", "DESC"); +$sql .= $db->plimit($max, 0); //print $sql; $result = $db->query($sql); @@ -299,9 +299,9 @@ if ($result) if (isset($_GET["type"]) && $_GET["type"] == 1) $transRecordedType = $langs->trans("LastRecordedServices", $max); print '
    '; - print '
    '.$langs->trans("Categories").'
    '; $sql = "SELECT c.label, count(*) as nb"; - $sql.= " FROM ".MAIN_DB_PREFIX."categorie_product as cs"; - $sql.= " LEFT JOIN ".MAIN_DB_PREFIX."categorie as c ON cs.fk_categorie = c.rowid"; - $sql.= " WHERE c.type = 0"; - $sql.= " AND c.entity IN (".getEntity('category').")"; - $sql.= " GROUP BY c.label"; - $total=0; + $sql .= " FROM ".MAIN_DB_PREFIX."categorie_product as cs"; + $sql .= " LEFT JOIN ".MAIN_DB_PREFIX."categorie as c ON cs.fk_categorie = c.rowid"; + $sql .= " WHERE c.type = 0"; + $sql .= " AND c.entity IN (".getEntity('category').")"; + $sql .= " GROUP BY c.label"; + $total = 0; $result = $db->query($sql); if ($result) { $num = $db->num_rows($result); - $i=0; - if (! empty($conf->use_javascript_ajax)) + $i = 0; + if (!empty($conf->use_javascript_ajax)) { - $dataseries=array(); - $rest=0; - $nbmax=10; + $dataseries = array(); + $rest = 0; + $nbmax = 10; while ($i < $num) { $obj = $db->fetch_object($result); if ($i < $nbmax) { - $dataseries[]=array($obj->label, round($obj->nb)); + $dataseries[] = array($obj->label, round($obj->nb)); } else { - $rest+=$obj->nb; + $rest += $obj->nb; } - $total+=$obj->nb; + $total += $obj->nb; $i++; } if ($i > $nbmax) { - $dataseries[]=array($langs->trans("Other"), round($rest)); + $dataseries[] = array($langs->trans("Other"), round($rest)); } include_once DOL_DOCUMENT_ROOT.'/core/class/dolgraph.class.php'; @@ -243,7 +243,7 @@ if (! empty($conf->categorie->enabled) && ! empty($conf->global->CATEGORY_GRAPHS $dolgraph->SetType(array('pie')); $dolgraph->setWidth('100%'); $dolgraph->draw('idstatscategproduct'); - print $dolgraph->show($total?0:1); + print $dolgraph->show($total ? 0 : 1); } else { @@ -252,7 +252,7 @@ if (! empty($conf->categorie->enabled) && ! empty($conf->global->CATEGORY_GRAPHS $obj = $db->fetch_object($result); print '
    '.$obj->label.''.$obj->nb.'
    '; + print '
    '; - $colnb=2; + $colnb = 2; if (empty($conf->global->PRODUIT_MULTIPRICES)) $colnb++; print ''; @@ -313,12 +313,12 @@ if ($result) $objp = $db->fetch_object($result); //Multilangs - if (! empty($conf->global->MAIN_MULTILANGS)) + if (!empty($conf->global->MAIN_MULTILANGS)) { $sql = "SELECT label"; - $sql.= " FROM ".MAIN_DB_PREFIX."product_lang"; - $sql.= " WHERE fk_product=".$objp->rowid; - $sql.= " AND lang='". $langs->getDefaultLang() ."'"; + $sql .= " FROM ".MAIN_DB_PREFIX."product_lang"; + $sql .= " WHERE fk_product=".$objp->rowid; + $sql .= " AND lang='".$langs->getDefaultLang()."'"; $resultd = $db->query($sql); if ($resultd) @@ -331,10 +331,10 @@ if ($result) print ''; print '
    '.$transRecordedType.'
    '; - $product_static->id=$objp->rowid; - $product_static->ref=$objp->ref; + $product_static->id = $objp->rowid; + $product_static->ref = $objp->ref; $product_static->label = $objp->label; - $product_static->type=$objp->fk_product_type; + $product_static->type = $objp->fk_product_type; $product_static->entity = $objp->entity; $product_static->status_batch = $objp->tobatch; print $product_static->getNomUrl(1, '', 16); @@ -387,10 +387,10 @@ else // TODO Move this into a page that should be available into menu "accountancy - report - turnover - per quarter" // Also method used for counting must provide the 2 possible methods like done by all other reports into menu "accountancy - report - turnover": // "commitment engagment" method and "cash accounting" method -if (! empty($conf->global->MAIN_SHOW_PRODUCT_ACTIVITY_TRIM)) +if (!empty($conf->global->MAIN_SHOW_PRODUCT_ACTIVITY_TRIM)) { - if (! empty($conf->product->enabled)) activitytrim(0); - if (! empty($conf->service->enabled)) activitytrim(1); + if (!empty($conf->product->enabled)) activitytrim(0); + if (!empty($conf->service->enabled)) activitytrim(1); } @@ -412,42 +412,42 @@ $db->close(); */ function activitytrim($product_type) { - global $conf,$langs,$db; + global $conf, $langs, $db; global $bc; // We display the last 3 years - $yearofbegindate=date('Y', dol_time_plus_duree(time(), -3, "y")); + $yearofbegindate = date('Y', dol_time_plus_duree(time(), -3, "y")); // breakdown by quarter $sql = "SELECT DATE_FORMAT(p.datep,'%Y') as annee, DATE_FORMAT(p.datep,'%m') as mois, SUM(fd.total_ht) as Mnttot"; - $sql.= " FROM ".MAIN_DB_PREFIX."facture as f, ".MAIN_DB_PREFIX."facturedet as fd"; - $sql.= " , ".MAIN_DB_PREFIX."paiement as p,".MAIN_DB_PREFIX."paiement_facture as pf"; - $sql.= " WHERE f.entity IN (".getEntity('invoice').")"; - $sql.= " AND f.rowid = fd.fk_facture"; - $sql.= " AND pf.fk_facture = f.rowid"; - $sql.= " AND pf.fk_paiement= p.rowid"; - $sql.= " AND fd.product_type=".$product_type; - $sql.= " AND p.datep >= '".$db->idate(dol_get_first_day($yearofbegindate), 1)."'"; - $sql.= " GROUP BY annee, mois "; - $sql.= " ORDER BY annee, mois "; + $sql .= " FROM ".MAIN_DB_PREFIX."facture as f, ".MAIN_DB_PREFIX."facturedet as fd"; + $sql .= " , ".MAIN_DB_PREFIX."paiement as p,".MAIN_DB_PREFIX."paiement_facture as pf"; + $sql .= " WHERE f.entity IN (".getEntity('invoice').")"; + $sql .= " AND f.rowid = fd.fk_facture"; + $sql .= " AND pf.fk_facture = f.rowid"; + $sql .= " AND pf.fk_paiement= p.rowid"; + $sql .= " AND fd.product_type=".$product_type; + $sql .= " AND p.datep >= '".$db->idate(dol_get_first_day($yearofbegindate), 1)."'"; + $sql .= " GROUP BY annee, mois "; + $sql .= " ORDER BY annee, mois "; $result = $db->query($sql); if ($result) { - $tmpyear=0; - $trim1=0; - $trim2=0; - $trim3=0; - $trim4=0; + $tmpyear = 0; + $trim1 = 0; + $trim2 = 0; + $trim3 = 0; + $trim4 = 0; $lgn = 0; $num = $db->num_rows($result); - if ($num > 0 ) + if ($num > 0) { print '
    '; print ''; - if ($product_type==0) + if ($product_type == 0) print ''; else print ''; @@ -465,23 +465,23 @@ function activitytrim($product_type) $objp = $db->fetch_object($result); if ($tmpyear != $objp->annee) { - if ($trim1+$trim2+$trim3+$trim4 > 0) + if ($trim1 + $trim2 + $trim3 + $trim4 > 0) { print ''; print ''; print ''; print ''; print ''; - print ''; + print ''; print ''; $lgn++; } // We go to the following year $tmpyear = $objp->annee; - $trim1=0; - $trim2=0; - $trim3=0; - $trim4=0; + $trim1 = 0; + $trim2 = 0; + $trim3 = 0; + $trim4 = 0; } if ($objp->mois == "01" || $objp->mois == "02" || $objp->mois == "03") @@ -498,17 +498,17 @@ function activitytrim($product_type) $i++; } - if ($trim1+$trim2+$trim3+$trim4 > 0) + if ($trim1 + $trim2 + $trim3 + $trim4 > 0) { print ''; print ''; print ''; print ''; print ''; - print ''; + print ''; print ''; } - if ($num > 0 ) + if ($num > 0) print '
    '.$langs->trans("ProductSellByQuarterHT").'
    '.$langs->trans("ServiceSellByQuarterHT").'
    '.$tmpyear.''.price($trim1).''.price($trim2).''.price($trim3).''.price($trim4).''.price($trim1+$trim2+$trim3+$trim4).''.price($trim1 + $trim2 + $trim3 + $trim4).'
    '.$tmpyear.''.price($trim1).''.price($trim2).''.price($trim3).''.price($trim4).''.price($trim1+$trim2+$trim3+$trim4).''.price($trim1 + $trim2 + $trim3 + $trim4).'
    '; } } diff --git a/htdocs/product/inventory/card.php b/htdocs/product/inventory/card.php index 2659d325676..43821b99b31 100644 --- a/htdocs/product/inventory/card.php +++ b/htdocs/product/inventory/card.php @@ -27,15 +27,15 @@ include_once DOL_DOCUMENT_ROOT.'/product/inventory/class/inventory.class.php'; include_once DOL_DOCUMENT_ROOT.'/product/inventory/lib/inventory.lib.php'; // Load translation files required by the page -$langs->loadLangs(array("stocks","other")); +$langs->loadLangs(array("stocks", "other")); // Get parameters -$id = GETPOST('id', 'int'); +$id = GETPOST('id', 'int'); $ref = GETPOST('ref', 'alpha'); -$action = GETPOST('action', 'aZ09'); +$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 +$contextpage = GETPOST('contextpage', 'aZ') ?GETPOST('contextpage', 'aZ') : 'myobjectcard'; // To manage different context of search $backtopage = GETPOST('backtopage', 'alpha'); if (empty($conf->global->MAIN_USE_ADVANCED_PERMS)) @@ -48,28 +48,28 @@ else } // Initialize technical objects -$object=new Inventory($db); +$object = new Inventory($db); $extrafields = new ExtraFields($db); -$diroutputmassaction=$conf->stock->dir_output . '/temp/massgeneration/'.$user->id; -$hookmanager->initHooks(array('inventorycard')); // Note that conf->hooks_modules contains array +$diroutputmassaction = $conf->stock->dir_output.'/temp/massgeneration/'.$user->id; +$hookmanager->initHooks(array('inventorycard')); // 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_'); +$search_array_options = $extrafields->getOptionalsFromPost($object->table_element, '', 'search_'); // Initialize array of search criterias -$search_all=trim(GETPOST("search_all", 'alpha')); -$search=array(); -foreach($object->fields as $key => $val) +$search_all = trim(GETPOST("search_all", 'alpha')); +$search = array(); +foreach ($object->fields as $key => $val) { - if (GETPOST('search_'.$key, 'alpha')) $search[$key]=GETPOST('search_'.$key, 'alpha'); + 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. +include DOL_DOCUMENT_ROOT.'/core/actions_fetchobject.inc.php'; // Must be include, not include_once. // Security check - Protection if external user //if ($user->socid > 0) access_forbidden(); @@ -92,13 +92,13 @@ else * Actions */ -$parameters=array(); -$reshook=$hookmanager->executeHooks('doActions', $parameters, $object, $action); // Note that $action and $object may have been modified by some hooks +$parameters = array(); +$reshook = $hookmanager->executeHooks('doActions', $parameters, $object, $action); // Note that $action and $object may have been modified by some hooks if ($reshook < 0) setEventMessages($hookmanager->error, $hookmanager->errors, 'errors'); if (empty($reshook)) { - $error=0; + $error = 0; $backurlforlist = DOL_URL_ROOT.'/product/inventory/list.php'; @@ -125,7 +125,7 @@ if (empty($reshook)) * View */ -$form=new Form($db); +$form = new Form($db); llxHeader('', $langs->trans('Inventory'), ''); @@ -160,10 +160,10 @@ if ($action == 'create') print ''."\n"; // Common attributes - include DOL_DOCUMENT_ROOT . '/core/tpl/commonfields_add.tpl.php'; + include DOL_DOCUMENT_ROOT.'/core/tpl/commonfields_add.tpl.php'; // Other attributes - include DOL_DOCUMENT_ROOT . '/core/tpl/extrafields_add.tpl.php'; + include DOL_DOCUMENT_ROOT.'/core/tpl/extrafields_add.tpl.php'; print '
    '."\n"; @@ -172,7 +172,7 @@ if ($action == 'create') print '
    '; print ''; print '  '; - print ''; // Cancel for create does not post form if we don't know the backtopage + print ''; // Cancel for create does not post form if we don't know the backtopage print '
    '; print ''; @@ -196,10 +196,10 @@ if (($id || $ref) && $action == 'edit') print ''."\n"; // Common attributes - include DOL_DOCUMENT_ROOT . '/core/tpl/commonfields_edit.tpl.php'; + include DOL_DOCUMENT_ROOT.'/core/tpl/commonfields_edit.tpl.php'; // Other attributes - include DOL_DOCUMENT_ROOT . '/core/tpl/extrafields_edit.tpl.php'; + include DOL_DOCUMENT_ROOT.'/core/tpl/extrafields_edit.tpl.php'; print '
    '; @@ -224,7 +224,7 @@ if ($object->id > 0 && (empty($action) || ($action != 'edit' && $action != 'crea // Confirmation to delete if ($action == 'delete') { - $formconfirm = $form->formconfirm($_SERVER["PHP_SELF"] . '?id=' . $object->id, $langs->trans('DeleteInventory'), $langs->trans('ConfirmDeleteOrder'), 'confirm_delete', '', 0, 1); + $formconfirm = $form->formconfirm($_SERVER["PHP_SELF"].'?id='.$object->id, $langs->trans('DeleteInventory'), $langs->trans('ConfirmDeleteOrder'), 'confirm_delete', '', 0, 1); } // Confirmation to delete line if ($action == 'deleteline') @@ -236,14 +236,14 @@ if ($object->id > 0 && (empty($action) || ($action != 'edit' && $action != 'crea if ($action == 'clone') { // Create an array for form $formquestion = array(); - $formconfirm = $form->formconfirm($_SERVER["PHP_SELF"] . '?id=' . $object->id, $langs->trans('ToClone'), $langs->trans('ConfirmCloneMyObject', $object->ref), 'confirm_clone', $formquestion, 'yes', 1); + $formconfirm = $form->formconfirm($_SERVER["PHP_SELF"].'?id='.$object->id, $langs->trans('ToClone'), $langs->trans('ConfirmCloneMyObject', $object->ref), 'confirm_clone', $formquestion, 'yes', 1); } // Call Hook formConfirm $parameters = array('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; @@ -251,9 +251,9 @@ if ($object->id > 0 && (empty($action) || ($action != 'edit' && $action != 'crea // Object card // ------------------------------------------------------------ - $linkback = '' . $langs->trans("BackToList") . ''; + $linkback = ''.$langs->trans("BackToList").''; - $morehtmlref='
    '; + $morehtmlref = '
    '; /* // Ref bis $morehtmlref.=$form->editfieldkey("RefBis", 'ref_client', $object->ref_client, $object, $user->rights->inventory->creer, 'string', '', 0, 1); @@ -293,7 +293,7 @@ if ($object->id > 0 && (empty($action) || ($action != 'edit' && $action != 'crea } } */ - $morehtmlref.='
    '; + $morehtmlref .= '
    '; dol_banner_tab($object, 'ref', $linkback, 1, 'ref', 'ref', $morehtmlref); @@ -305,10 +305,10 @@ if ($object->id > 0 && (empty($action) || ($action != 'edit' && $action != 'crea print ''."\n"; // Common attributes - include DOL_DOCUMENT_ROOT . '/core/tpl/commonfields_view.tpl.php'; + include DOL_DOCUMENT_ROOT.'/core/tpl/commonfields_view.tpl.php'; // Other attributes. Fields from hook formObjectOptions and Extrafields. - include DOL_DOCUMENT_ROOT . '/core/tpl/extrafields_view.tpl.php'; + include DOL_DOCUMENT_ROOT.'/core/tpl/extrafields_view.tpl.php'; print '
    '; print ''; @@ -322,14 +322,14 @@ if ($object->id > 0 && (empty($action) || ($action != 'edit' && $action != 'crea // Buttons for actions if ($action != 'presend' && $action != 'editline') { print '
    '."\n"; - $parameters=array(); - $reshook=$hookmanager->executeHooks('addMoreActionsButtons', $parameters, $object, $action); // Note that $action and $object may have been modified by hook + $parameters = array(); + $reshook = $hookmanager->executeHooks('addMoreActionsButtons', $parameters, $object, $action); // Note that $action and $object may have been modified by hook if ($reshook < 0) setEventMessages($hookmanager->error, $hookmanager->errors, 'errors'); if (empty($reshook)) { // Send - print '' . $langs->trans('SendMail') . ''."\n"; + print ''.$langs->trans('SendMail').''."\n"; if ($permissiontoadd) { diff --git a/htdocs/product/inventory/class/inventory.class.php b/htdocs/product/inventory/class/inventory.class.php index 4434f82fbcf..ca3a0c114d8 100644 --- a/htdocs/product/inventory/class/inventory.class.php +++ b/htdocs/product/inventory/class/inventory.class.php @@ -25,7 +25,7 @@ */ // Put here all includes required by your class file -require_once DOL_DOCUMENT_ROOT . '/core/class/commonobject.class.php'; +require_once DOL_DOCUMENT_ROOT.'/core/class/commonobject.class.php'; //require_once DOL_DOCUMENT_ROOT . '/societe/class/societe.class.php'; //require_once DOL_DOCUMENT_ROOT . '/product/class/product.class.php'; @@ -83,7 +83,7 @@ class Inventory extends CommonObject /** * @var array Array with all fields and their property */ - public $fields=array( + public $fields = array( 'rowid' => array('type'=>'integer', 'label'=>'TechnicalID', 'visible'=>-1, 'enabled'=>1, 'position'=>1, 'notnull'=>1, 'index'=>1, 'comment'=>'Id',), 'ref' => array('type'=>'varchar(64)', 'label'=>'Ref', 'visible'=>1, 'enabled'=>1, 'position'=>10, 'notnull'=>1, 'index'=>1, 'searchall'=>1, 'comment'=>'Reference of object', 'css'=>'maxwidth200'), 'entity' => array('type'=>'integer', 'label'=>'Entity', 'visible'=>0, 'enabled'=>1, 'position'=>20, 'notnull'=>1, 'index'=>1,), @@ -131,8 +131,17 @@ class Inventory extends CommonObject */ public $status; + /** + * @var integer|string date_creation + */ public $date_creation; + + /** + * @var integer|string date_validation + */ public $date_validation; + + public $tms; /** @@ -199,8 +208,8 @@ class Inventory extends CommonObject $this->db = $db; - if (empty($conf->global->MAIN_SHOW_TECHNICAL_ID)) $this->fields['rowid']['visible']=0; - if (empty($conf->multicompany->enabled)) $this->fields['entity']['enabled']=0; + if (empty($conf->global->MAIN_SHOW_TECHNICAL_ID)) $this->fields['rowid']['visible'] = 0; + if (empty($conf->multicompany->enabled)) $this->fields['entity']['enabled'] = 0; } @@ -335,37 +344,37 @@ class Inventory extends CommonObject global $dolibarr_main_authentication, $dolibarr_main_demo; global $menumanager; - 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 = ''; $companylink = ''; - $label = '' . $langs->trans("Inventory") . ''; - $label.= '
    '; - $label.= '' . $langs->trans('Ref') . ': ' . $this->ref; + $label = ''.$langs->trans("Inventory").''; + $label .= '
    '; + $label .= ''.$langs->trans('Ref').': '.$this->ref; $url = dol_buildpath('/product/inventory/card.php', 1).'?id='.$this->id; - $linkclose=''; + $linkclose = ''; if (empty($notooltip)) { - if (! empty($conf->global->MAIN_OPTIMIZEFORTEXTBROWSER)) + if (!empty($conf->global->MAIN_OPTIMIZEFORTEXTBROWSER)) { - $label=$langs->trans("ShowInventory"); - $linkclose.=' alt="'.dol_escape_htmltag($label, 1).'"'; + $label = $langs->trans("ShowInventory"); + $linkclose .= ' alt="'.dol_escape_htmltag($label, 1).'"'; } - $linkclose.=' title="'.dol_escape_htmltag($label, 1).'"'; - $linkclose.=' class="classfortooltip'.($morecss?' '.$morecss:'').'"'; + $linkclose .= ' title="'.dol_escape_htmltag($label, 1).'"'; + $linkclose .= ' class="classfortooltip'.($morecss ? ' '.$morecss : '').'"'; } - else $linkclose = ($morecss?' class="'.$morecss.'"':''); + else $linkclose = ($morecss ? ' class="'.$morecss.'"' : ''); $linkstart = ''; - $linkend=''; + $linkstart .= $linkclose.'>'; + $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)) : ''); @@ -396,16 +405,12 @@ class Inventory extends CommonObject // phpcs:enable global $langs; - if (empty($this->labelStatus)) - { - global $langs; - //$langs->load("mrp"); - $this->labelStatus[self::STATUS_DRAFT] = $langs->trans('Draft'); - $this->labelStatus[self::STATUS_VALIDATED] = $langs->trans('Enabled'); - $this->labelStatus[self::STATUS_CANCELED] = $langs->trans('Canceled'); - } + $labelStatus = array(); + $labelStatus[self::STATUS_DRAFT] = $langs->trans('Draft'); + $labelStatus[self::STATUS_VALIDATED] = $langs->trans('Enabled'); + $labelStatus[self::STATUS_CANCELED] = $langs->trans('Canceled'); - return dolGetStatus($this->labelStatus[$status], $this->labelStatus[$status], '', 'status'.$status, $mode); + return dolGetStatus($labelStatus[$status], $labelStatus[$status], '', 'status'.$status, $mode); } /** @@ -417,10 +422,10 @@ class Inventory extends CommonObject public function info($id) { $sql = 'SELECT rowid, date_creation as datec, tms as datem,'; - $sql.= ' fk_user_creat, fk_user_modif'; - $sql.= ' FROM '.MAIN_DB_PREFIX.$this->table_element.' as t'; - $sql.= ' WHERE t.rowid = '.$id; - $result=$this->db->query($sql); + $sql .= ' fk_user_creat, fk_user_modif'; + $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)) @@ -431,7 +436,7 @@ class Inventory extends CommonObject { $cuser = new User($this->db); $cuser->fetch($obj->fk_user_author); - $this->user_creation = $cuser; + $this->user_creation = $cuser; } if ($obj->fk_user_valid) @@ -445,7 +450,7 @@ class Inventory extends CommonObject { $cluser = new User($this->db); $cluser->fetch($obj->fk_user_cloture); - $this->user_cloture = $cluser; + $this->user_cloture = $cluser; } $this->date_creation = $this->db->jdate($obj->datec); diff --git a/htdocs/product/inventory/list.php b/htdocs/product/inventory/list.php index ac2ac589200..843a7b6cb0a 100644 --- a/htdocs/product/inventory/list.php +++ b/htdocs/product/inventory/list.php @@ -29,22 +29,22 @@ require_once DOL_DOCUMENT_ROOT.'/core/lib/company.lib.php'; require_once DOL_DOCUMENT_ROOT.'/product/inventory/class/inventory.class.php'; // Load translation files required by the page -$langs->loadLangs(array("stocks","other")); +$langs->loadLangs(array("stocks", "other")); -$action = GETPOST('action', 'aZ09')?GETPOST('action', 'aZ09'):'view'; // The action 'add', 'create', 'edit', 'update', 'view', ... -$massaction = GETPOST('massaction', 'alpha'); // The bulk action (combo box choice into lists) -$show_files = GETPOST('show_files', 'int'); // Show files area generated by bulk actions ? -$confirm = GETPOST('confirm', 'alpha'); // Result of a confirmation -$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'):'inventorylist'; // 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') +$action = GETPOST('action', 'aZ09') ?GETPOST('action', 'aZ09') : 'view'; // The action 'add', 'create', 'edit', 'update', 'view', ... +$massaction = GETPOST('massaction', 'alpha'); // The bulk action (combo box choice into lists) +$show_files = GETPOST('show_files', 'int'); // Show files area generated by bulk actions ? +$confirm = GETPOST('confirm', 'alpha'); // Result of a confirmation +$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') : 'inventorylist'; // 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') -$id = GETPOST('id', 'int'); +$id = GETPOST('id', 'int'); // Load variable for pagination -$limit = GETPOST('limit', 'int')?GETPOST('limit', 'int'):$conf->liste_limit; +$limit = GETPOST('limit', 'int') ?GETPOST('limit', 'int') : $conf->liste_limit; $sortfield = GETPOST('sortfield', 'alpha'); $sortorder = GETPOST('sortorder', 'alpha'); $page = GETPOST('page', 'int'); @@ -54,20 +54,20 @@ $pageprev = $page - 1; $pagenext = $page + 1; // Initialize technical objects -$object=new Inventory($db); +$object = new Inventory($db); $extrafields = new ExtraFields($db); -$diroutputmassaction=$conf->inventory->dir_output . '/temp/massgeneration/'.$user->id; -$hookmanager->initHooks(array('inventorylist')); // Note that conf->hooks_modules contains array +$diroutputmassaction = $conf->inventory->dir_output.'/temp/massgeneration/'.$user->id; +$hookmanager->initHooks(array('inventorylist')); // 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_'); +$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 -$socid=0; +$socid = 0; if ($user->socid > 0) // Protection if external user { //$socid = $user->socid; @@ -83,34 +83,34 @@ else } // Initialize array of search criterias -$search_all=trim(GETPOST("search_all", 'alpha')); -$search=array(); -foreach($object->fields as $key => $val) +$search_all = trim(GETPOST("search_all", 'alpha')); +$search = array(); +foreach ($object->fields as $key => $val) { - if (GETPOST('search_'.$key, 'alpha')) $search[$key]=GETPOST('search_'.$key, 'alpha'); + 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) +foreach ($object->fields as $key => $val) { - if ($val['searchall']) $fieldstosearchall['t.'.$key]=$val['label']; + if ($val['searchall']) $fieldstosearchall['t.'.$key] = $val['label']; } // Definition of fields for list -$arrayfields=array(); -foreach($object->fields as $key => $val) +$arrayfields = array(); +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) + 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], 'checked'=>(($extrafields->attributes[$object->table_element]['list'][$key]<0)?0:1), 'position'=>$extrafields->attributes[$object->table_element]['pos'][$key], 'enabled'=>(abs($extrafields->attributes[$object->table_element]['list'][$key])!=3 && $extrafields->attributes[$object->table_element]['perms'][$key])); + if (!empty($extrafields->attributes[$object->table_element]['list'][$key])) + $arrayfields["ef.".$key] = array('label'=>$extrafields->attributes[$object->table_element]['label'][$key], 'checked'=>(($extrafields->attributes[$object->table_element]['list'][$key] < 0) ? 0 : 1), 'position'=>$extrafields->attributes[$object->table_element]['pos'][$key], 'enabled'=>(abs($extrafields->attributes[$object->table_element]['list'][$key]) != 3 && $extrafields->attributes[$object->table_element]['perms'][$key])); } } $object->fields = dol_sort_array($object->fields, 'position'); @@ -122,11 +122,11 @@ $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(); -$reshook=$hookmanager->executeHooks('doActions', $parameters, $object, $action); // Note that $action and $object may have been modified by some hooks +$parameters = array(); +$reshook = $hookmanager->executeHooks('doActions', $parameters, $object, $action); // Note that $action and $object may have been modified by some hooks if ($reshook < 0) setEventMessages($hookmanager->error, $hookmanager->errors, 'errors'); if (empty($reshook)) @@ -135,24 +135,24 @@ if (empty($reshook)) 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 { - foreach($object->fields as $key => $val) + foreach ($object->fields as $key => $val) { - $search[$key]=''; + $search[$key] = ''; } - $toselect=''; - $search_array_options=array(); + $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')) { - $massaction=''; // Protection to avoid mass action if we force a new search during a mass action confirmation + $massaction = ''; // Protection to avoid mass action if we force a new search during a mass action confirmation } // Mass actions - $objectclass='Inventory'; - $objectlabel='Inventory'; + $objectclass = 'Inventory'; + $objectlabel = 'Inventory'; $permissiontoread = $user->rights->stock->lire; $permissiontodelete = $user->rights->stock->supprimer; $uploaddir = $conf->stock->dir_output; @@ -165,48 +165,48 @@ if (empty($reshook)) * View */ -$form=new Form($db); +$form = new Form($db); -$now=dol_now(); +$now = dol_now(); //$help_url="EN:Module_Inventory|FR:Module_Inventory_FR|ES:Módulo_Inventory"; -$help_url=''; +$help_url = ''; $title = $langs->trans('ListOfInventories'); // Build and execute select // -------------------------------------------------------------------- $sql = 'SELECT '; -foreach($object->fields as $key => $val) +foreach ($object->fields as $key => $val) { - $sql.='t.'.$key.', '; + $sql .= 't.'.$key.', '; } // Add fields from extrafields -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.', ' : ''); +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.', ' : ''); } // Add fields from hooks -$parameters=array(); -$reshook=$hookmanager->executeHooks('printFieldListSelect', $parameters, $object); // Note that $action and $object may have been modified by hook -$sql.=$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) +$parameters = array(); +$reshook = $hookmanager->executeHooks('printFieldListSelect', $parameters, $object); // Note that $action and $object may have been modified by hook +$sql .= $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; - $mode_search=(($object->isInt($object->fields[$key]) || $object->isFloat($object->fields[$key]))?1:0); - if ($search[$key] != '') $sql.=natural_search($key, $search[$key], (($key == 'status')?2:$mode_search)); + $mode_search = (($object->isInt($object->fields[$key]) || $object->isFloat($object->fields[$key])) ? 1 : 0); + 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 -$parameters=array(); -$reshook=$hookmanager->executeHooks('printFieldListWhere', $parameters, $object); // Note that $action and $object may have been modified by hook -$sql.=$hookmanager->resPrint; +$parameters = array(); +$reshook = $hookmanager->executeHooks('printFieldListWhere', $parameters, $object); // Note that $action and $object may have been modified by hook +$sql .= $hookmanager->resPrint; /* If a group by is required $sql.= " GROUP BY " @@ -225,7 +225,7 @@ $sql.=$hookmanager->resPrint; $sql=preg_replace('/, $/','', $sql); */ -$sql.=$db->order($sortfield, $sortorder); +$sql .= $db->order($sortfield, $sortorder); // Count total nb of records $nbtotalofrecords = ''; @@ -246,10 +246,10 @@ if (is_numeric($nbtotalofrecords) && $limit > $nbtotalofrecords) } else { - $sql.= $db->plimit($limit+1, $offset); + $sql .= $db->plimit($limit + 1, $offset); - $resql=$db->query($sql); - if (! $resql) + $resql = $db->query($sql); + if (!$resql) { dol_print_error($db); exit; @@ -259,7 +259,7 @@ else } // Direct jump if only one record found -if ($num == 1 && ! empty($conf->global->MAIN_SEARCH_DIRECT_OPEN_IF_ONLY_ONE) && $search_all) +if ($num == 1 && !empty($conf->global->MAIN_SEARCH_DIRECT_OPEN_IF_ONLY_ONE) && $search_all) { $obj = $db->fetch_object($resql); $id = $obj->rowid; @@ -273,28 +273,28 @@ if ($num == 1 && ! empty($conf->global->MAIN_SEARCH_DIRECT_OPEN_IF_ONLY_ONE) && llxHeader('', $title, $help_url); -$arrayofselected=is_array($toselect)?$toselect:array(); +$arrayofselected = is_array($toselect) ? $toselect : array(); -$param=''; -if (! empty($contextpage) && $contextpage != $_SERVER["PHP_SELF"]) $param.='&contextpage='.urlencode($contextpage); -if ($limit > 0 && $limit != $conf->liste_limit) $param.='&limit='.urlencode($limit); -foreach($search as $key => $val) +$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 (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'; // List of mass actions available -$arrayofmassactions = array( +$arrayofmassactions = array( //'presend'=>$langs->trans("SendByMail"), //'builddoc'=>$langs->trans("PDFMerge"), ); -if ($user->rights->stock->supprimer) $arrayofmassactions['predelete']=''.$langs->trans("Delete"); -if (GETPOST('nomassaction', 'int') || in_array($massaction, array('presend','predelete'))) $arrayofmassactions=array(); -$massactionbutton=$form->selectMassAction('', $arrayofmassactions); +if ($user->rights->stock->supprimer) $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 ''; @@ -311,16 +311,16 @@ $newcardbutton = dolGetButtonTitle($langs->trans('New'), '', 'fa fa-plus-circle' print_barre_liste($title, $page, $_SERVER["PHP_SELF"], $param, $sortfield, $sortorder, $massactionbutton, $num, $nbtotalofrecords, 'products', 0, $newcardbutton, '', $limit); // Add code for pre mass action (confirmation or email presend form) -$topicmail="Information"; -$modelmail="inventory"; -$objecttmp=new Inventory($db); -$trackid='inve'.$object->id; +$topicmail = "Information"; +$modelmail = "inventory"; +$objecttmp = new Inventory($db); +$trackid = 'inve'.$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); - print '
    '.$langs->trans("FilterOnInto", $sall) . join(', ', $fieldstosearchall).'
    '; + foreach ($fieldstosearchall as $key => $val) $fieldstosearchall[$key] = $langs->trans($val); + print '
    '.$langs->trans("FilterOnInto", $sall).join(', ', $fieldstosearchall).'
    '; } $moreforfilter = ''; @@ -328,39 +328,39 @@ $moreforfilter = ''; $moreforfilter.= $langs->trans('MyFilter') . ': '; $moreforfilter.= '
    ';*/ -$parameters=array(); -$reshook=$hookmanager->executeHooks('printFieldPreListTitle', $parameters, $object); // Note that $action and $object may have been modified by hook +$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($moreforfilter)) +if (!empty($moreforfilter)) { print '
    '; print $moreforfilter; print '
    '; } -$varpage=empty($contextpage)?$_SERVER["PHP_SELF"]:$contextpage; -$selectedfields=$form->multiSelectArrayWithCheckbox('selectedfields', $arrayfields, $varpage); // This also change content of $arrayfields -$selectedfields.=(count($arrayofmassactions) ? $form->showCheckAddButtons('checkforselect', 1) : ''); +$varpage = empty($contextpage) ? $_SERVER["PHP_SELF"] : $contextpage; +$selectedfields = $form->multiSelectArrayWithCheckbox('selectedfields', $arrayfields, $varpage); // This also change content of $arrayfields +$selectedfields .= (count($arrayofmassactions) ? $form->showCheckAddButtons('checkforselect', 1) : ''); -print '
    '; // You can use div-table-responsive-no-min if you dont need reserved height for your table -print ''."\n"; +print '
    '; // You can use div-table-responsive-no-min if you dont need reserved height for your table +print '
    '."\n"; // Fields title search // -------------------------------------------------------------------- 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'])) + $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'])) { - print ''; @@ -370,12 +370,12 @@ foreach($object->fields as $key => $val) include DOL_DOCUMENT_ROOT.'/core/tpl/extrafields_list_search_input.tpl.php'; // Fields from hook -$parameters=array('arrayfields'=>$arrayfields); -$reshook=$hookmanager->executeHooks('printFieldListOption', $parameters, $object); // Note that $action and $object may have been modified by hook +$parameters = array('arrayfields'=>$arrayfields); +$reshook = $hookmanager->executeHooks('printFieldListOption', $parameters, $object); // Note that $action and $object may have been modified by hook print $hookmanager->resPrint; // Action column print ''; print ''."\n"; @@ -384,23 +384,23 @@ 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'])) + $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'])) { - print getTitleFieldOfList($arrayfields['t.'.$key]['label'], 0, $_SERVER['PHP_SELF'], 't.'.$key, '', $param, ($cssforfield?'class="'.$cssforfield.'"':''), $sortfield, $sortorder, ($cssforfield?$cssforfield.' ':''))."\n"; + print getTitleFieldOfList($arrayfields['t.'.$key]['label'], 0, $_SERVER['PHP_SELF'], 't.'.$key, '', $param, ($cssforfield ? 'class="'.$cssforfield.'"' : ''), $sortfield, $sortorder, ($cssforfield ? $cssforfield.' ' : ''))."\n"; } } // 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, $object); // Note that $action and $object may have been modified by hook +$parameters = array('arrayfields'=>$arrayfields, 'param'=>$param, 'sortfield'=>$sortfield, 'sortorder'=>$sortorder); +$reshook = $hookmanager->executeHooks('printFieldListTitle', $parameters, $object); // Note that $action and $object may have been modified by hook print $hookmanager->resPrint; // Action column print getTitleFieldOfList($selectedfields, 0, $_SERVER["PHP_SELF"], '', '', '', '', $sortfield, $sortorder, 'center maxwidthsearch ')."\n"; @@ -408,55 +408,55 @@ print ''."\n"; // Detect if we need a fetch on each output line -$needToFetchEachLine=0; +$needToFetchEachLine = 0; if (is_array($extrafields->attributes[$object->table_element]['computed']) && count($extrafields->attributes[$object->table_element]['computed']) > 0) { foreach ($extrafields->attributes[$object->table_element]['computed'] as $key => $val) { - if (preg_match('/\$object/', $val)) $needToFetchEachLine++; // There is at least one compute field that use $object + if (preg_match('/\$object/', $val)) $needToFetchEachLine++; // There is at least one compute field that use $object } } // Loop on record // -------------------------------------------------------------------- -$i=0; -$totalarray=array(); +$i = 0; +$totalarray = array(); while ($i < min($num, $limit)) { $obj = $db->fetch_object($resql); - if (empty($obj)) break; // Should not happen + if (empty($obj)) break; // Should not happen // Store properties in $object $object->id = $obj->rowid; - foreach($object->fields as $key => $val) + foreach ($object->fields as $key => $val) { if (property_exists($obj, $key)) $object->$key = $obj->$key; } // 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'; + $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('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($val['type'], array('double(24,8)', 'double(6,3)', 'integer', 'real', 'price')) && $key != 'status') $cssforfield .= ($cssforfield ? ' ' : '').'right'; - if (! empty($arrayfields['t.'.$key]['checked'])) + if (!empty($arrayfields['t.'.$key]['checked'])) { print ''; if ($key == 'status') print $object->getLibStatut(5); - elseif (in_array($val['type'], array('date','datetime','timestamp'))) print $object->showOutputField($val, $key, $db->jdate($obj->$key), ''); + elseif (in_array($val['type'], array('date', 'datetime', 'timestamp'))) print $object->showOutputField($val, $key, $db->jdate($obj->$key), ''); else print $object->showOutputField($val, $key, $obj->$key, ''); print ''; - if (! $i) $totalarray['nbfield']++; - if (! empty($val['isameasure'])) + if (!$i) $totalarray['nbfield']++; + if (!empty($val['isameasure'])) { - if (! $i) $totalarray['pos'][$totalarray['nbfield']]='t.'.$key; + if (!$i) $totalarray['pos'][$totalarray['nbfield']] = 't.'.$key; $totalarray['val']['t.'.$key] += $obj->$key; } } @@ -464,19 +464,19 @@ while ($i < min($num, $limit)) // Extra fields include DOL_DOCUMENT_ROOT.'/core/tpl/extrafields_list_print_fields.tpl.php'; // Fields from hook - $parameters=array('arrayfields'=>$arrayfields, 'obj'=>$obj); - $reshook=$hookmanager->executeHooks('printFieldListValue', $parameters, $object); // Note that $action and $object may have been modified by hook + $parameters = array('arrayfields'=>$arrayfields, 'obj'=>$obj); + $reshook = $hookmanager->executeHooks('printFieldListValue', $parameters, $object); // Note that $action and $object may have been modified by hook print $hookmanager->resPrint; // Action column print ''; - if (! $i) $totalarray['nbfield']++; + if (!$i) $totalarray['nbfield']++; print ''."\n"; @@ -490,16 +490,16 @@ include DOL_DOCUMENT_ROOT.'/core/tpl/list_print_total.tpl.php'; // If no record found if ($num == 0) { - $colspan=1; - foreach($arrayfields as $key => $val) { if (! empty($val['checked'])) $colspan++; } + $colspan = 1; + foreach ($arrayfields as $key => $val) { if (!empty($val['checked'])) $colspan++; } print ''; } $db->free($resql); -$parameters=array('arrayfields'=>$arrayfields, 'sql'=>$sql); -$reshook=$hookmanager->executeHooks('printFieldListFooter', $parameters, $object); // Note that $action and $object may have been modified by hook +$parameters = array('arrayfields'=>$arrayfields, 'sql'=>$sql); +$reshook = $hookmanager->executeHooks('printFieldListFooter', $parameters, $object); // Note that $action and $object may have been modified by hook print $hookmanager->resPrint; print '
    '; + print ''; if (is_array($val['arrayofkeyval'])) print $form->selectarray('search_'.$key, $val['arrayofkeyval'], $search[$key], $val['notnull'], 0, 0, '', 1, 0, 0, '', 'maxwidth75'); else print ''; print ''; -$searchpicto=$form->showFilterButtons(); +$searchpicto = $form->showFilterButtons(); print $searchpicto; print '
    '; if ($massactionbutton || $massaction) // If we are in select mode (massactionbutton defined) or if we have already selected and sent an action ($massaction) defined { - $selected=0; - if (in_array($obj->rowid, $arrayofselected)) $selected=1; - print ''; + $selected = 0; + if (in_array($obj->rowid, $arrayofselected)) $selected = 1; + print ''; } print '
    '.$langs->trans("NoRecordFound").'
    '."\n"; @@ -509,19 +509,19 @@ print ''."\n"; if (in_array('builddoc', $arrayofmassactions) && ($nbtotalofrecords === '' || $nbtotalofrecords)) { - $hidegeneratedfilelistifempty=1; - if ($massaction == 'builddoc' || $action == 'remove_file' || $show_files) $hidegeneratedfilelistifempty=0; + $hidegeneratedfilelistifempty = 1; + 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); // Show list of available documents - $urlsource=$_SERVER['PHP_SELF'].'?sortfield='.$sortfield.'&sortorder='.$sortorder; - $urlsource.=str_replace('&', '&', $param); + $urlsource = $_SERVER['PHP_SELF'].'?sortfield='.$sortfield.'&sortorder='.$sortorder; + $urlsource .= str_replace('&', '&', $param); - $filedir=$diroutputmassaction; - $genallowed=$user->rights->mymodule->read; - $delallowed=$user->rights->mymodule->create; + $filedir = $diroutputmassaction; + $genallowed = $user->rights->mymodule->read; + $delallowed = $user->rights->mymodule->create; print $formfile->showdocuments('massfilesarea_mymodule', '', $filedir, $urlsource, 0, $delallowed, '', 1, 1, 0, 48, 1, $param, $title, '', '', '', null, $hidegeneratedfilelistifempty); } diff --git a/htdocs/product/list.php b/htdocs/product/list.php index d9369fcb148..33ad0b4806c 100644 --- a/htdocs/product/list.php +++ b/htdocs/product/list.php @@ -37,26 +37,26 @@ require_once DOL_DOCUMENT_ROOT.'/product/class/product.class.php'; require_once DOL_DOCUMENT_ROOT.'/fourn/class/fournisseur.product.class.php'; require_once DOL_DOCUMENT_ROOT.'/core/lib/company.lib.php'; require_once DOL_DOCUMENT_ROOT.'/core/class/html.formother.class.php'; -if (! empty($conf->categorie->enabled)) +if (!empty($conf->categorie->enabled)) require_once DOL_DOCUMENT_ROOT.'/categories/class/categorie.class.php'; // Load translation files required by the page $langs->loadLangs(array('products', 'stocks', 'suppliers', 'companies')); -if (! empty($conf->productbatch->enabled)) $langs->load("productbatch"); +if (!empty($conf->productbatch->enabled)) $langs->load("productbatch"); -$action=GETPOST('action', 'alpha'); -$massaction=GETPOST('massaction', 'alpha'); -$show_files=GETPOST('show_files', 'int'); -$confirm=GETPOST('confirm', 'alpha'); +$action = GETPOST('action', 'alpha'); +$massaction = GETPOST('massaction', 'alpha'); +$show_files = GETPOST('show_files', 'int'); +$confirm = GETPOST('confirm', 'alpha'); $toselect = GETPOST('toselect', 'array'); -$sall=trim((GETPOST('search_all', 'alphanohtml')!='')?GETPOST('search_all', 'alphanohtml'):GETPOST('sall', 'alphanohtml')); -$search_ref=GETPOST("search_ref", 'alpha'); -$search_barcode=GETPOST("search_barcode", 'alpha'); -$search_label=GETPOST("search_label", 'alpha'); +$sall = trim((GETPOST('search_all', 'alphanohtml') != '') ?GETPOST('search_all', 'alphanohtml') : GETPOST('sall', 'alphanohtml')); +$search_ref = GETPOST("search_ref", 'alpha'); +$search_barcode = GETPOST("search_barcode", 'alpha'); +$search_label = GETPOST("search_label", 'alpha'); $search_type = GETPOST("search_type", 'int'); $search_sale = GETPOST("search_sale", 'int'); -$search_vatrate=GETPOST("search_vatrate", 'alpha'); +$search_vatrate = GETPOST("search_vatrate", 'alpha'); $searchCategoryProductOperator = (GETPOST('search_category_product_operator', 'int') ? GETPOST('search_category_product_operator', 'int') : 0); $searchCategoryProductList = GETPOST('search_category_product_list', 'array'); $search_tosell = GETPOST("search_tosell", 'int'); @@ -69,49 +69,49 @@ $search_accountancy_code_sell_intra = GETPOST("search_accountancy_code_sell_intr $search_accountancy_code_sell_export = GETPOST("search_accountancy_code_sell_export", 'alpha'); $search_accountancy_code_buy = GETPOST("search_accountancy_code_buy", 'alpha'); $optioncss = GETPOST('optioncss', 'alpha'); -$type=GETPOST("type", "int"); +$type = GETPOST("type", "int"); //Show/hide child products -if (!empty($conf->variants->enabled) && ! empty($conf->global->PRODUIT_ATTRIBUTES_HIDECHILD)) { +if (!empty($conf->variants->enabled) && !empty($conf->global->PRODUIT_ATTRIBUTES_HIDECHILD)) { $show_childproducts = GETPOST('search_show_childproducts'); } else { $show_childproducts = ''; } -$diroutputmassaction=$conf->product->dir_output . '/temp/massgeneration/'.$user->id; +$diroutputmassaction = $conf->product->dir_output.'/temp/massgeneration/'.$user->id; -$limit = GETPOST('limit', 'int')?GETPOST('limit', 'int'):$conf->liste_limit; +$limit = GETPOST('limit', 'int') ?GETPOST('limit', 'int') : $conf->liste_limit; $sortfield = GETPOST("sortfield", 'alpha'); $sortorder = GETPOST("sortorder", 'alpha'); -$page = (GETPOST("page", 'int')?GETPOST("page", 'int'):0); +$page = (GETPOST("page", 'int') ?GETPOST("page", 'int') : 0); if (empty($page) || $page == -1) { $page = 0; } // If $page is not defined, or '' or -1 $offset = $limit * $page; $pageprev = $page - 1; $pagenext = $page + 1; -if (! $sortfield) $sortfield="p.ref"; -if (! $sortorder) $sortorder="ASC"; +if (!$sortfield) $sortfield = "p.ref"; +if (!$sortorder) $sortorder = "ASC"; // Initialize context for list -$contextpage=GETPOST('contextpage', 'aZ')?GETPOST('contextpage', 'aZ'):'productservicelist'; -if ((string) $type == '1') { $contextpage='servicelist'; if ($search_type=='') $search_type='1'; } -if ((string) $type == '0') { $contextpage='productlist'; if ($search_type=='') $search_type='0'; } +$contextpage = GETPOST('contextpage', 'aZ') ?GETPOST('contextpage', 'aZ') : 'productservicelist'; +if ((string) $type == '1') { $contextpage = 'servicelist'; if ($search_type == '') $search_type = '1'; } +if ((string) $type == '0') { $contextpage = 'productlist'; if ($search_type == '') $search_type = '0'; } // Initialize technical object to manage hooks. Note that conf->hooks_modules contains array of hooks -$object=new Product($db); +$object = new Product($db); $hookmanager->initHooks(array('productservicelist')); $extrafields = new ExtraFields($db); -$form=new Form($db); +$form = new Form($db); // fetch optionals attributes and labels $extrafields->fetch_name_optionals_label('product'); -$search_array_options=$extrafields->getOptionalsFromPost($object->table_element, '', 'search_'); +$search_array_options = $extrafields->getOptionalsFromPost($object->table_element, '', 'search_'); -if (empty($action)) $action='list'; +if (empty($action)) $action = 'list'; // Get object canvas (By default, this is not defined, so standard usage of dolibarr) -$canvas=GETPOST("canvas"); -$objcanvas=null; -if (! empty($canvas)) +$canvas = GETPOST("canvas"); +$objcanvas = null; +if (!empty($canvas)) { require_once DOL_DOCUMENT_ROOT.'/core/class/canvas.class.php'; $objcanvas = new Canvas($db, $action); @@ -119,15 +119,15 @@ if (! empty($canvas)) } // Security check -if ($search_type=='0') $result=restrictedArea($user, 'produit', '', '', '', '', '', $objcanvas); -elseif ($search_type=='1') $result=restrictedArea($user, 'service', '', '', '', '', '', $objcanvas); -else $result=restrictedArea($user, 'produit|service', '', '', '', '', '', $objcanvas); +if ($search_type == '0') $result = restrictedArea($user, 'produit', '', '', '', '', '', $objcanvas); +elseif ($search_type == '1') $result = restrictedArea($user, 'service', '', '', '', '', '', $objcanvas); +else $result = restrictedArea($user, 'produit|service', '', '', '', '', '', $objcanvas); // Define virtualdiffersfromphysical -$virtualdiffersfromphysical=0; -if (! empty($conf->global->STOCK_CALCULATE_ON_SHIPMENT) || ! empty($conf->global->STOCK_CALCULATE_ON_SUPPLIER_DISPATCH_ORDER) || ! empty($conf->global->STOCK_CALCULATE_ON_RECEPTION) ) +$virtualdiffersfromphysical = 0; +if (!empty($conf->global->STOCK_CALCULATE_ON_SHIPMENT) || !empty($conf->global->STOCK_CALCULATE_ON_SUPPLIER_DISPATCH_ORDER) || !empty($conf->global->STOCK_CALCULATE_ON_RECEPTION)) { - $virtualdiffersfromphysical=1; // According to increase/decrease stock options, virtual and physical stock may differs. + $virtualdiffersfromphysical = 1; // According to increase/decrease stock options, virtual and physical stock may differs. } // List of fields to search into when doing a "search in all" @@ -140,52 +140,52 @@ $fieldstosearchall = array( ); // multilang -if (! empty($conf->global->MAIN_MULTILANGS)) +if (!empty($conf->global->MAIN_MULTILANGS)) { - $fieldstosearchall['pl.label']='ProductLabelTranslated'; - $fieldstosearchall['pl.description']='ProductDescriptionTranslated'; - $fieldstosearchall['pl.note']='ProductNoteTranslated'; + $fieldstosearchall['pl.label'] = 'ProductLabelTranslated'; + $fieldstosearchall['pl.description'] = 'ProductDescriptionTranslated'; + $fieldstosearchall['pl.note'] = 'ProductNoteTranslated'; } -if (! empty($conf->barcode->enabled)) { - $fieldstosearchall['p.barcode']='Gencod'; - $fieldstosearchall['pfp.barcode']='GencodBuyPrice'; +if (!empty($conf->barcode->enabled)) { + $fieldstosearchall['p.barcode'] = 'Gencod'; + $fieldstosearchall['pfp.barcode'] = 'GencodBuyPrice'; } // Personalized search criterias. Example: $conf->global->PRODUCT_QUICKSEARCH_ON_FIELDS = 'p.ref=ProductRef;p.label=ProductLabel' -if (! empty($conf->global->PRODUCT_QUICKSEARCH_ON_FIELDS)) $fieldstosearchall=dolExplodeIntoArray($conf->global->PRODUCT_QUICKSEARCH_ON_FIELDS); +if (!empty($conf->global->PRODUCT_QUICKSEARCH_ON_FIELDS)) $fieldstosearchall = dolExplodeIntoArray($conf->global->PRODUCT_QUICKSEARCH_ON_FIELDS); if (empty($conf->global->PRODUIT_MULTIPRICES)) { - $titlesellprice=$langs->trans("SellingPrice"); - if (! empty($conf->global->PRODUIT_CUSTOMER_PRICES)) + $titlesellprice = $langs->trans("SellingPrice"); + if (!empty($conf->global->PRODUIT_CUSTOMER_PRICES)) { - $titlesellprice=$form->textwithpicto($langs->trans("SellingPrice"), $langs->trans("DefaultPriceRealPriceMayDependOnCustomer")); + $titlesellprice = $form->textwithpicto($langs->trans("SellingPrice"), $langs->trans("DefaultPriceRealPriceMayDependOnCustomer")); } } -$isInEEC=isInEEC($mysoc); +$isInEEC = isInEEC($mysoc); // Definition of fields for lists -$arrayfields=array( +$arrayfields = array( 'p.ref'=>array('label'=>$langs->trans("Ref"), 'checked'=>1), //'pfp.ref_fourn'=>array('label'=>$langs->trans("RefSupplier"), 'checked'=>1, 'enabled'=>(! empty($conf->barcode->enabled))), 'p.label'=>array('label'=>$langs->trans("Label"), 'checked'=>1), - 'p.fk_product_type'=>array('label'=>$langs->trans("Type"), 'checked'=>0, 'enabled'=>(! empty($conf->product->enabled) && ! empty($conf->service->enabled))), - 'p.barcode'=>array('label'=>$langs->trans("Gencod"), 'checked'=>1, 'enabled'=>(! empty($conf->barcode->enabled))), - 'p.duration'=>array('label'=>$langs->trans("Duration"), 'checked'=>($contextpage != 'productlist'), 'enabled'=>(! empty($conf->service->enabled) && (string) $type == '1')), - 'p.weight'=>array('label'=>$langs->trans("Weight"), 'checked'=>0, 'enabled'=>(! empty($conf->product->enabled))), - 'p.length'=>array('label'=>$langs->trans("Length"), 'checked'=>0, 'enabled'=>(! empty($conf->product->enabled) && ! empty($conf->global->PRODUCT_DISABLE_SIZE))), - 'p.surface'=>array('label'=>$langs->trans("Surface"), 'checked'=>0, 'enabled'=>(! empty($conf->product->enabled) && ! empty($conf->global->PRODUCT_DISABLE_SURFACE))), - 'p.volume'=>array('label'=>$langs->trans("Volume"), 'checked'=>0, 'enabled'=>(! empty($conf->product->enabled) && ! empty($conf->global->PRODUCT_DISABLE_VOLUME))), + 'p.fk_product_type'=>array('label'=>$langs->trans("Type"), 'checked'=>0, 'enabled'=>(!empty($conf->product->enabled) && !empty($conf->service->enabled))), + 'p.barcode'=>array('label'=>$langs->trans("Gencod"), 'checked'=>1, 'enabled'=>(!empty($conf->barcode->enabled))), + 'p.duration'=>array('label'=>$langs->trans("Duration"), 'checked'=>($contextpage != 'productlist'), 'enabled'=>(!empty($conf->service->enabled) && (string) $type == '1')), + 'p.weight'=>array('label'=>$langs->trans("Weight"), 'checked'=>0, 'enabled'=>(!empty($conf->product->enabled))), + 'p.length'=>array('label'=>$langs->trans("Length"), 'checked'=>0, 'enabled'=>(!empty($conf->product->enabled) && !empty($conf->global->PRODUCT_DISABLE_SIZE))), + 'p.surface'=>array('label'=>$langs->trans("Surface"), 'checked'=>0, 'enabled'=>(!empty($conf->product->enabled) && !empty($conf->global->PRODUCT_DISABLE_SURFACE))), + 'p.volume'=>array('label'=>$langs->trans("Volume"), 'checked'=>0, 'enabled'=>(!empty($conf->product->enabled) && !empty($conf->global->PRODUCT_DISABLE_VOLUME))), 'p.sellprice'=>array('label'=>$langs->trans("SellingPrice"), 'checked'=>1, 'enabled'=>empty($conf->global->PRODUIT_MULTIPRICES)), - 'p.minbuyprice'=>array('label'=>$langs->trans("BuyingPriceMinShort"), 'checked'=>1, 'enabled'=>(! empty($user->rights->fournisseur->lire))), - 'p.numbuyprice'=>array('label'=>$langs->trans("BuyingPriceNumShort"), 'checked'=>0, 'enabled'=>(! empty($user->rights->fournisseur->lire))), - 'p.tva_tx'=>array('label'=>$langs->trans("VATRate"), 'checked'=>0, 'enabled'=>(! empty($user->rights->fournisseur->lire))), - 'p.pmp'=>array('label'=>$langs->trans("PMPValueShort"), 'checked'=>0, 'enabled'=>(! empty($user->rights->fournisseur->lire))), - 'p.seuil_stock_alerte'=>array('label'=>$langs->trans("StockLimit"), 'checked'=>0, 'enabled'=>(! empty($conf->stock->enabled) && $user->rights->stock->lire && $contextpage != 'service')), - 'p.desiredstock'=>array('label'=>$langs->trans("DesiredStock"), 'checked'=>1, 'enabled'=>(! empty($conf->stock->enabled) && $user->rights->stock->lire && $contextpage != 'service')), - 'p.stock'=>array('label'=>$langs->trans("PhysicalStock"), 'checked'=>1, 'enabled'=>(! empty($conf->stock->enabled) && $user->rights->stock->lire && $contextpage != 'service')), - 'stock_virtual'=>array('label'=>$langs->trans("VirtualStock"), 'checked'=>1, 'enabled'=>(! empty($conf->stock->enabled) && $user->rights->stock->lire && $contextpage != 'service' && $virtualdiffersfromphysical)), - 'p.tobatch'=>array('label'=>$langs->trans("ManageLotSerial"), 'checked'=>0, 'enabled'=>(! empty($conf->productbatch->enabled))), + 'p.minbuyprice'=>array('label'=>$langs->trans("BuyingPriceMinShort"), 'checked'=>1, 'enabled'=>(!empty($user->rights->fournisseur->lire))), + 'p.numbuyprice'=>array('label'=>$langs->trans("BuyingPriceNumShort"), 'checked'=>0, 'enabled'=>(!empty($user->rights->fournisseur->lire))), + 'p.tva_tx'=>array('label'=>$langs->trans("VATRate"), 'checked'=>0, 'enabled'=>(!empty($user->rights->fournisseur->lire))), + 'p.pmp'=>array('label'=>$langs->trans("PMPValueShort"), 'checked'=>0, 'enabled'=>(!empty($user->rights->fournisseur->lire))), + 'p.seuil_stock_alerte'=>array('label'=>$langs->trans("StockLimit"), 'checked'=>0, 'enabled'=>(!empty($conf->stock->enabled) && $user->rights->stock->lire && $contextpage != 'service')), + 'p.desiredstock'=>array('label'=>$langs->trans("DesiredStock"), 'checked'=>1, 'enabled'=>(!empty($conf->stock->enabled) && $user->rights->stock->lire && $contextpage != 'service')), + 'p.stock'=>array('label'=>$langs->trans("PhysicalStock"), 'checked'=>1, 'enabled'=>(!empty($conf->stock->enabled) && $user->rights->stock->lire && $contextpage != 'service')), + 'stock_virtual'=>array('label'=>$langs->trans("VirtualStock"), 'checked'=>1, 'enabled'=>(!empty($conf->stock->enabled) && $user->rights->stock->lire && $contextpage != 'service' && $virtualdiffersfromphysical)), + 'p.tobatch'=>array('label'=>$langs->trans("ManageLotSerial"), 'checked'=>0, 'enabled'=>(!empty($conf->productbatch->enabled))), 'p.accountancy_code_sell'=>array('label'=>$langs->trans("ProductAccountancySellCode"), 'checked'=>0, 'position'=>400), 'p.accountancy_code_sell_intra'=>array('label'=>$langs->trans("ProductAccountancySellIntraCode"), 'checked'=>0, 'enabled'=>$isInEEC, 'position'=>401), 'p.accountancy_code_sell_export'=>array('label'=>$langs->trans("ProductAccountancySellExportCode"), 'checked'=>0, 'position'=>402), @@ -198,10 +198,10 @@ $arrayfields=array( // Extra fields if (is_array($extrafields->attributes[$object->table_element]['label']) && count($extrafields->attributes[$object->table_element]['label'])) { - foreach($extrafields->attributes[$object->table_element]['label'] as $key => $val) + foreach ($extrafields->attributes[$object->table_element]['label'] as $key => $val) { - if (! empty($extrafields->attributes[$object->table_element]['list'][$key])) - $arrayfields["ef.".$key]=array('label'=>$extrafields->attributes[$object->table_element]['label'][$key], 'checked'=>(($extrafields->attributes[$object->table_element]['list'][$key]<0)?0:1), 'position'=>$extrafields->attributes[$object->table_element]['pos'][$key], 'enabled'=>(abs($extrafields->attributes[$object->table_element]['list'][$key])!=3 && $extrafields->attributes[$object->table_element]['perms'][$key])); + if (!empty($extrafields->attributes[$object->table_element]['list'][$key])) + $arrayfields["ef.".$key] = array('label'=>$extrafields->attributes[$object->table_element]['label'][$key], 'checked'=>(($extrafields->attributes[$object->table_element]['list'][$key] < 0) ? 0 : 1), 'position'=>$extrafields->attributes[$object->table_element]['pos'][$key], 'enabled'=>(abs($extrafields->attributes[$object->table_element]['list'][$key]) != 3 && $extrafields->attributes[$object->table_element]['perms'][$key])); } } $object->fields = dol_sort_array($object->fields, 'position'); @@ -213,11 +213,11 @@ $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(); -$reshook=$hookmanager->executeHooks('doActions', $parameters, $object, $action); // Note that $action and $object may have been modified by some hooks +$parameters = array(); +$reshook = $hookmanager->executeHooks('doActions', $parameters, $object, $action); // Note that $action and $object may have been modified by some hooks if ($reshook < 0) setEventMessages($hookmanager->error, $hookmanager->errors, 'errors'); if (empty($reshook)) @@ -228,30 +228,30 @@ if (empty($reshook)) // Purge search criteria if (GETPOST('button_removefilter_x', 'alpha') || GETPOST('button_removefilter.x', 'alpha') || GETPOST('button_removefilter', 'alpha')) // All tests are required to be compatible with all browsers { - $sall=""; - $search_ref=""; - $search_label=""; - $search_barcode=""; + $sall = ""; + $search_ref = ""; + $search_label = ""; + $search_barcode = ""; $searchCategoryProductOperator = 0; $searchCategoryProductList = array(); - $search_tosell=""; - $search_tobuy=""; - $search_vatrate=""; - $search_tobatch=''; + $search_tosell = ""; + $search_tobuy = ""; + $search_vatrate = ""; + $search_tobatch = ''; //$search_type=''; // There is 2 types of list: a list of product and a list of services. No list with both. So when we clear search criteria, we must keep the filter on type. $show_childproducts = ''; - $search_accountancy_code_sell=''; - $search_accountancy_code_sell_intra=''; - $search_accountancy_code_sell_export=''; - $search_accountancy_code_buy=''; - $search_array_options=array(); + $search_accountancy_code_sell = ''; + $search_accountancy_code_sell_intra = ''; + $search_accountancy_code_sell_export = ''; + $search_accountancy_code_buy = ''; + $search_array_options = array(); } // Mass actions - $objectclass='Product'; - if ((string) $search_type == '1') { $objectlabel='Services'; } - if ((string) $search_type == '0') { $objectlabel='Products'; } + $objectclass = 'Product'; + if ((string) $search_type == '1') { $objectlabel = 'Services'; } + if ((string) $search_type == '0') { $objectlabel = 'Products'; } $permissiontoread = $user->rights->produit->lire; $permissiontodelete = $user->rights->produit->supprimer; @@ -264,9 +264,9 @@ if (empty($reshook)) * View */ -$htmlother=new FormOther($db); +$htmlother = new FormOther($db); -$title=$langs->trans("ProductsAndServices"); +$title = $langs->trans("ProductsAndServices"); if ($search_type != '' && $search_type != '-1') { @@ -285,111 +285,111 @@ else } $sql = 'SELECT DISTINCT p.rowid, p.ref, p.label, p.fk_product_type, p.barcode, p.price, p.tva_tx, p.price_ttc, p.price_base_type, p.entity,'; -$sql.= ' p.fk_product_type, p.duration, p.tosell, p.tobuy, p.seuil_stock_alerte, p.desiredstock,'; -$sql.= ' p.tobatch, p.accountancy_code_sell, p.accountancy_code_sell_intra, p.accountancy_code_sell_export, p.accountancy_code_buy,'; -$sql.= ' p.datec as date_creation, p.tms as date_update, p.pmp, p.stock,'; -$sql.= ' p.weight, p.weight_units, p.length, p.length_units, p.surface, p.surface_units, p.volume, p.volume_units, p.width, p.width_units, p.height, p.height_units,'; -$sql.= ' MIN(pfp.unitprice) as minsellprice'; -if (!empty($conf->variants->enabled) && (!empty($conf->global->PRODUIT_ATTRIBUTES_HIDECHILD) && ! $show_childproducts )) { +$sql .= ' p.fk_product_type, p.duration, p.tosell, p.tobuy, p.seuil_stock_alerte, p.desiredstock,'; +$sql .= ' p.tobatch, p.accountancy_code_sell, p.accountancy_code_sell_intra, p.accountancy_code_sell_export, p.accountancy_code_buy,'; +$sql .= ' p.datec as date_creation, p.tms as date_update, p.pmp, p.stock,'; +$sql .= ' p.weight, p.weight_units, p.length, p.length_units, p.surface, p.surface_units, p.volume, p.volume_units, p.width, p.width_units, p.height, p.height_units,'; +$sql .= ' MIN(pfp.unitprice) as minsellprice'; +if (!empty($conf->variants->enabled) && (!empty($conf->global->PRODUIT_ATTRIBUTES_HIDECHILD) && !$show_childproducts)) { $sql .= ', pac.rowid prod_comb_id'; } // 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 : ''); +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 : ''); } // 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.'product as p'; -if (is_array($extrafields->attributes[$object->table_element]['label']) && count($extrafields->attributes[$object->table_element]['label'])) $sql.= " LEFT JOIN ".MAIN_DB_PREFIX."product_extrafields as ef on (p.rowid = ef.fk_object)"; -if (!empty($searchCategoryProductList) || !empty($catid)) $sql.= ' LEFT JOIN '.MAIN_DB_PREFIX."categorie_product as cp ON p.rowid = cp.fk_product"; // We'll need this table joined to the select in order to filter by categ -$sql.= " LEFT JOIN ".MAIN_DB_PREFIX."product_fournisseur_price as pfp ON p.rowid = pfp.fk_product"; +$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.'product as p'; +if (is_array($extrafields->attributes[$object->table_element]['label']) && count($extrafields->attributes[$object->table_element]['label'])) $sql .= " LEFT JOIN ".MAIN_DB_PREFIX."product_extrafields as ef on (p.rowid = ef.fk_object)"; +if (!empty($searchCategoryProductList) || !empty($catid)) $sql .= ' LEFT JOIN '.MAIN_DB_PREFIX."categorie_product as cp ON p.rowid = cp.fk_product"; // We'll need this table joined to the select in order to filter by categ +$sql .= " LEFT JOIN ".MAIN_DB_PREFIX."product_fournisseur_price as pfp ON p.rowid = pfp.fk_product"; // multilang -if (! empty($conf->global->MAIN_MULTILANGS)) $sql.= " LEFT JOIN ".MAIN_DB_PREFIX."product_lang as pl ON pl.fk_product = p.rowid AND pl.lang = '".$langs->getDefaultLang() ."'"; +if (!empty($conf->global->MAIN_MULTILANGS)) $sql .= " LEFT JOIN ".MAIN_DB_PREFIX."product_lang as pl ON pl.fk_product = p.rowid AND pl.lang = '".$langs->getDefaultLang()."'"; -if (!empty($conf->variants->enabled) && (!empty($conf->global->PRODUIT_ATTRIBUTES_HIDECHILD) && ! $show_childproducts )) { +if (!empty($conf->variants->enabled) && (!empty($conf->global->PRODUIT_ATTRIBUTES_HIDECHILD) && !$show_childproducts)) { $sql .= " LEFT JOIN ".MAIN_DB_PREFIX."product_attribute_combination pac ON pac.fk_product_child = p.rowid"; } -$sql.= ' WHERE p.entity IN ('.getEntity('product').')'; +$sql .= ' WHERE p.entity IN ('.getEntity('product').')'; if ($sall) $sql .= natural_search(array_keys($fieldstosearchall), $sall); // if the type is not 1, we show all products (type = 0,2,3) if (dol_strlen($search_type) && $search_type != '-1') { - if ($search_type == 1) $sql.= " AND p.fk_product_type = 1"; - else $sql.= " AND p.fk_product_type <> 1"; + if ($search_type == 1) $sql .= " AND p.fk_product_type = 1"; + else $sql .= " AND p.fk_product_type <> 1"; } -if (!empty($conf->variants->enabled) && (!empty($conf->global->PRODUIT_ATTRIBUTES_HIDECHILD) && ! $show_childproducts )) { +if (!empty($conf->variants->enabled) && (!empty($conf->global->PRODUIT_ATTRIBUTES_HIDECHILD) && !$show_childproducts)) { $sql .= " AND pac.rowid IS NULL"; } if ($search_ref) $sql .= natural_search('p.ref', $search_ref); if ($search_label) $sql .= natural_search('p.label', $search_label); if ($search_barcode) $sql .= natural_search('p.barcode', $search_barcode); -if (isset($search_tosell) && dol_strlen($search_tosell) > 0 && $search_tosell!=-1) $sql.= " AND p.tosell = ".$db->escape($search_tosell); -if (isset($search_tobuy) && dol_strlen($search_tobuy) > 0 && $search_tobuy!=-1) $sql.= " AND p.tobuy = ".$db->escape($search_tobuy); +if (isset($search_tosell) && dol_strlen($search_tosell) > 0 && $search_tosell != -1) $sql .= " AND p.tosell = ".$db->escape($search_tosell); +if (isset($search_tobuy) && dol_strlen($search_tobuy) > 0 && $search_tobuy != -1) $sql .= " AND p.tobuy = ".$db->escape($search_tobuy); if ($search_vatrate) $sql .= natural_search('p.tva_tx', $search_vatrate); -if (dol_strlen($canvas) > 0) $sql.= " AND p.canvas = '".$db->escape($canvas)."'"; -if ($catid > 0) $sql.= " AND cp.fk_categorie = ".$catid; -if ($catid == -2) $sql.= " AND cp.fk_categorie IS NULL"; +if (dol_strlen($canvas) > 0) $sql .= " AND p.canvas = '".$db->escape($canvas)."'"; +if ($catid > 0) $sql .= " AND cp.fk_categorie = ".$catid; +if ($catid == -2) $sql .= " AND cp.fk_categorie IS NULL"; $searchCategoryProductSqlList = array(); if ($searchCategoryProductOperator == 1) { foreach ($searchCategoryProductList as $searchCategoryProduct) { if (intval($searchCategoryProduct) == -2) { $searchCategoryProductSqlList[] = "cp.fk_categorie IS NULL"; } elseif (intval($searchCategoryProduct) > 0) { - $searchCategoryProductSqlList[] = "cp.fk_categorie = " . $db->escape($searchCategoryProduct); + $searchCategoryProductSqlList[] = "cp.fk_categorie = ".$db->escape($searchCategoryProduct); } } if (!empty($searchCategoryProductSqlList)) { - $sql .= " AND (" . implode(' OR ', $searchCategoryProductSqlList) . ")"; + $sql .= " AND (".implode(' OR ', $searchCategoryProductSqlList).")"; } } else { foreach ($searchCategoryProductList as $searchCategoryProduct) { if (intval($searchCategoryProduct) == -2) { $searchCategoryProductSqlList[] = "cp.fk_categorie IS NULL"; } elseif (intval($searchCategoryProduct) > 0) { - $searchCategoryProductSqlList[] = "p.rowid IN (SELECT fk_product FROM " . MAIN_DB_PREFIX . "categorie_product WHERE fk_categorie = " . $searchCategoryProduct . ")"; + $searchCategoryProductSqlList[] = "p.rowid IN (SELECT fk_product FROM ".MAIN_DB_PREFIX."categorie_product WHERE fk_categorie = ".$searchCategoryProduct.")"; } } if (!empty($searchCategoryProductSqlList)) { - $sql .= " AND (" . implode(' AND ', $searchCategoryProductSqlList) . ")"; + $sql .= " AND (".implode(' AND ', $searchCategoryProductSqlList).")"; } } -if ($fourn_id > 0) $sql.= " AND pfp.fk_soc = ".$fourn_id; -if ($search_tobatch != '' && $search_tobatch >= 0) $sql.= " AND p.tobatch = ".$db->escape($search_tobatch); -if ($search_accountancy_code_sell) $sql.= natural_search('p.accountancy_code_sell', $search_accountancy_code_sell); -if ($search_accountancy_code_sell_intra) $sql.= natural_search('p.accountancy_code_sell_intra', $search_accountancy_code_sell_intra); -if ($search_accountancy_code_sell_export) $sql.= natural_search('p.accountancy_code_sell_export', $search_accountancy_code_sell_export); -if ($search_accountancy_code_buy) $sql.= natural_search('p.accountancy_code_buy', $search_accountancy_code_buy); +if ($fourn_id > 0) $sql .= " AND pfp.fk_soc = ".$fourn_id; +if ($search_tobatch != '' && $search_tobatch >= 0) $sql .= " AND p.tobatch = ".$db->escape($search_tobatch); +if ($search_accountancy_code_sell) $sql .= natural_search('p.accountancy_code_sell', $search_accountancy_code_sell); +if ($search_accountancy_code_sell_intra) $sql .= natural_search('p.accountancy_code_sell_intra', $search_accountancy_code_sell_intra); +if ($search_accountancy_code_sell_export) $sql .= natural_search('p.accountancy_code_sell_export', $search_accountancy_code_sell_export); +if ($search_accountancy_code_buy) $sql .= natural_search('p.accountancy_code_buy', $search_accountancy_code_buy); // Add where from extra fields include DOL_DOCUMENT_ROOT.'/core/tpl/extrafields_list_search_sql.tpl.php'; // Add where from hooks -$parameters=array(); -$reshook=$hookmanager->executeHooks('printFieldListWhere', $parameters); // Note that $action and $object may have been modified by hook -$sql.=$hookmanager->resPrint; -$sql.= " GROUP BY p.rowid, p.ref, p.label, p.barcode, p.price, p.tva_tx, p.price_ttc, p.price_base_type,"; -$sql.= " p.fk_product_type, p.duration, p.tosell, p.tobuy, p.seuil_stock_alerte, p.desiredstock,"; -$sql.= ' p.datec, p.tms, p.entity, p.tobatch, p.accountancy_code_sell, p.accountancy_code_sell_intra, p.accountancy_code_sell_export, p.accountancy_code_buy, p.pmp, p.stock,'; -$sql.= ' p.weight, p.weight_units, p.length, p.length_units, p.surface, p.surface_units, p.volume, p.volume_units, p.width, p.width_units, p.height, p.height_units'; +$parameters = array(); +$reshook = $hookmanager->executeHooks('printFieldListWhere', $parameters); // Note that $action and $object may have been modified by hook +$sql .= $hookmanager->resPrint; +$sql .= " GROUP BY p.rowid, p.ref, p.label, p.barcode, p.price, p.tva_tx, p.price_ttc, p.price_base_type,"; +$sql .= " p.fk_product_type, p.duration, p.tosell, p.tobuy, p.seuil_stock_alerte, p.desiredstock,"; +$sql .= ' p.datec, p.tms, p.entity, p.tobatch, p.accountancy_code_sell, p.accountancy_code_sell_intra, p.accountancy_code_sell_export, p.accountancy_code_buy, p.pmp, p.stock,'; +$sql .= ' p.weight, p.weight_units, p.length, p.length_units, p.surface, p.surface_units, p.volume, p.volume_units, p.width, p.width_units, p.height, p.height_units'; -if (!empty($conf->variants->enabled) && (!empty($conf->global->PRODUIT_ATTRIBUTES_HIDECHILD) && ! $show_childproducts )) { +if (!empty($conf->variants->enabled) && (!empty($conf->global->PRODUIT_ATTRIBUTES_HIDECHILD) && !$show_childproducts)) { $sql .= ', pac.rowid'; } // 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 : ''); +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 : ''); } // Add fields from hooks -$parameters=array(); -$reshook=$hookmanager->executeHooks('printFieldSelect', $parameters); // Note that $action and $object may have been modified by hook -$sql.=$hookmanager->resPrint; +$parameters = array(); +$reshook = $hookmanager->executeHooks('printFieldSelect', $parameters); // Note that $action and $object may have been modified by hook +$sql .= $hookmanager->resPrint; //if (GETPOST("toolowstock")) $sql.= " HAVING SUM(s.reel) < p.seuil_stock_alerte"; // Not used yet -$sql.= $db->order($sortfield, $sortorder); +$sql .= $db->order($sortfield, $sortorder); $nbtotalofrecords = ''; if (empty($conf->global->MAIN_DISABLE_FULL_SCANLIST)) @@ -403,7 +403,7 @@ if (empty($conf->global->MAIN_DISABLE_FULL_SCANLIST)) } } -$sql.= $db->plimit($limit + 1, $offset); +$sql .= $db->plimit($limit + 1, $offset); $resql = $db->query($sql); @@ -411,9 +411,9 @@ if ($resql) { $num = $db->num_rows($resql); - $arrayofselected=is_array($toselect)?$toselect:array(); + $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; @@ -421,81 +421,81 @@ if ($resql) exit; } - $helpurl=''; + $helpurl = ''; if ($search_type != '') { if ($search_type == 0) { - $helpurl='EN:Module_Products|FR:Module_Produits|ES:Módulo_Productos'; + $helpurl = 'EN:Module_Products|FR:Module_Produits|ES:Módulo_Productos'; } elseif ($search_type == 1) { - $helpurl='EN:Module_Services_En|FR:Module_Services|ES:Módulo_Servicios'; + $helpurl = 'EN:Module_Services_En|FR:Module_Services|ES:Módulo_Servicios'; } } llxHeader('', $title, $helpurl, ''); // Displays product removal confirmation - if (GETPOST('delprod')) { + if (GETPOST('delprod')) { setEventMessages($langs->trans("ProductDeleted", GETPOST('delprod')), null, 'mesgs'); } - $param=''; - if (! empty($contextpage) && $contextpage != $_SERVER["PHP_SELF"]) $param.='&contextpage='.urlencode($contextpage); - if ($limit > 0 && $limit != $conf->liste_limit) $param.='&limit='.urlencode($limit); - if ($sall) $param.="&sall=".urlencode($sall); - if ($searchCategoryProductOperator == 1) $param .= "&search_category_product_operator=" . urlencode($searchCategoryProductOperator); + $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 ($searchCategoryProductOperator == 1) $param .= "&search_category_product_operator=".urlencode($searchCategoryProductOperator); foreach ($searchCategoryProductList as $searchCategoryProduct) { - $param .= "&search_category_product_list[]=" . urlencode($searchCategoryProduct); + $param .= "&search_category_product_list[]=".urlencode($searchCategoryProduct); } - if ($search_ref) $param="&search_ref=".urlencode($search_ref); - if ($search_ref_supplier) $param="&search_ref_supplier=".urlencode($search_ref_supplier); - if ($search_barcode) $param.=($search_barcode?"&search_barcode=".urlencode($search_barcode):""); - if ($search_label) $param.="&search_label=".urlencode($search_label); - if ($search_tosell != '') $param.="&search_tosell=".urlencode($search_tosell); - if ($search_tobuy != '') $param.="&search_tobuy=".urlencode($search_tobuy); + if ($search_ref) $param = "&search_ref=".urlencode($search_ref); + if ($search_ref_supplier) $param = "&search_ref_supplier=".urlencode($search_ref_supplier); + if ($search_barcode) $param .= ($search_barcode ? "&search_barcode=".urlencode($search_barcode) : ""); + if ($search_label) $param .= "&search_label=".urlencode($search_label); + if ($search_tosell != '') $param .= "&search_tosell=".urlencode($search_tosell); + if ($search_tobuy != '') $param .= "&search_tobuy=".urlencode($search_tobuy); if ($search_vatrate) $sql .= natural_search('p.tva_tx', $search_vatrate); - if ($fourn_id > 0) $param.=($fourn_id?"&fourn_id=".$fourn_id:""); + if ($fourn_id > 0) $param .= ($fourn_id ? "&fourn_id=".$fourn_id : ""); //if ($seach_categ) $param.=($search_categ?"&search_categ=".urlencode($search_categ):""); - if ($show_childproducts) $param.=($show_childproducts?"&search_show_childproducts=".urlencode($show_childproducts):""); - if ($type != '') $param.='&type='.urlencode($type); - if ($search_type != '') $param.='&search_type='.urlencode($search_type); - if ($optioncss != '') $param.='&optioncss='.urlencode($optioncss); - if ($search_tobatch) $param="&search_ref_supplier=".urlencode($search_ref_supplier); - if ($search_accountancy_code_sell) $param="&search_accountancy_code_sell=".urlencode($search_accountancy_code_sell); - if ($search_accountancy_code_sell_intra) $param="&search_accountancy_code_sell_intra=".urlencode($search_accountancy_code_sell_intra); - if ($search_accountancy_code_sell_export) $param="&search_accountancy_code_sell_export=".urlencode($search_accountancy_code_sell_export); - if ($search_accountancy_code_buy) $param="&search_accountancy_code_buy=".urlencode($search_accountancy_code_buy); + if ($show_childproducts) $param .= ($show_childproducts ? "&search_show_childproducts=".urlencode($show_childproducts) : ""); + if ($type != '') $param .= '&type='.urlencode($type); + if ($search_type != '') $param .= '&search_type='.urlencode($search_type); + if ($optioncss != '') $param .= '&optioncss='.urlencode($optioncss); + if ($search_tobatch) $param = "&search_ref_supplier=".urlencode($search_ref_supplier); + if ($search_accountancy_code_sell) $param = "&search_accountancy_code_sell=".urlencode($search_accountancy_code_sell); + if ($search_accountancy_code_sell_intra) $param = "&search_accountancy_code_sell_intra=".urlencode($search_accountancy_code_sell_intra); + if ($search_accountancy_code_sell_export) $param = "&search_accountancy_code_sell_export=".urlencode($search_accountancy_code_sell_export); + if ($search_accountancy_code_buy) $param = "&search_accountancy_code_buy=".urlencode($search_accountancy_code_buy); // Add $param from extra fields include DOL_DOCUMENT_ROOT.'/core/tpl/extrafields_list_search_param.tpl.php'; // List of mass actions available - $arrayofmassactions = array( + $arrayofmassactions = array( 'generate_doc'=>$langs->trans("ReGeneratePDF"), //'builddoc'=>$langs->trans("PDFMerge"), //'presend'=>$langs->trans("SendByMail"), ); - if ($user->rights->produit->supprimer) $arrayofmassactions['predelete']="".$langs->trans("Delete"); - if (in_array($massaction, array('presend','predelete'))) $arrayofmassactions=array(); - $massactionbutton=$form->selectMassAction('', $arrayofmassactions); + if ($user->rights->produit->supprimer) $arrayofmassactions['predelete'] = "".$langs->trans("Delete"); + if (in_array($massaction, array('presend', 'predelete'))) $arrayofmassactions = array(); + $massactionbutton = $form->selectMassAction('', $arrayofmassactions); - $newcardbutton=''; - $rightskey='produit'; - if($type == Product::TYPE_SERVICE) $rightskey='service'; - if($user->rights->{$rightskey}->creer) + $newcardbutton = ''; + $rightskey = 'produit'; + if ($type == Product::TYPE_SERVICE) $rightskey = 'service'; + if ($user->rights->{$rightskey}->creer) { - $oldtype=$type; + $oldtype = $type; if ($type === "") { - $newcardbutton.= dolGetButtonTitle($langs->trans('NewProduct'), '', 'fa fa-plus-circle', DOL_URL_ROOT.'/product/card.php?action=create&type=0'); + $newcardbutton .= dolGetButtonTitle($langs->trans('NewProduct'), '', 'fa fa-plus-circle', DOL_URL_ROOT.'/product/card.php?action=create&type=0'); $type = Product::TYPE_SERVICE; } - $label='NewProduct'; - if($type == Product::TYPE_SERVICE) $label='NewService'; - $newcardbutton.= dolGetButtonTitle($langs->trans($label), '', 'fa fa-plus-circle', DOL_URL_ROOT.'/product/card.php?action=create&type='.$type); + $label = 'NewProduct'; + if ($type == Product::TYPE_SERVICE) $label = 'NewService'; + $newcardbutton .= dolGetButtonTitle($langs->trans($label), '', 'fa fa-plus-circle', DOL_URL_ROOT.'/product/card.php?action=create&type='.$type); - $type=$oldtype; + $type = $oldtype; } print '
    '; @@ -511,13 +511,13 @@ if ($resql) print_barre_liste($texte, $page, $_SERVER["PHP_SELF"], $param, $sortfield, $sortorder, $massactionbutton, $num, $nbtotalofrecords, 'products', 0, $newcardbutton, '', $limit); - $topicmail="Information"; - $modelmail="product"; - $objecttmp=new Product($db); - $trackid='prod'.$object->id; + $topicmail = "Information"; + $modelmail = "product"; + $objecttmp = new Product($db); + $trackid = 'prod'.$object->id; include DOL_DOCUMENT_ROOT.'/core/tpl/massactions_pre.tpl.php'; - if (! empty($catid)) + if (!empty($catid)) { print "
    "; $c = new Categorie($db); @@ -528,35 +528,35 @@ if ($resql) if ($sall) { - foreach($fieldstosearchall as $key => $val) $fieldstosearchall[$key]=$langs->trans($val); - print '
    '.$langs->trans("FilterOnInto", $sall) . join(', ', $fieldstosearchall).'
    '; + foreach ($fieldstosearchall as $key => $val) $fieldstosearchall[$key] = $langs->trans($val); + print '
    '.$langs->trans("FilterOnInto", $sall).join(', ', $fieldstosearchall).'
    '; } // Filter on categories - $moreforfilter=''; - if (! empty($conf->categorie->enabled)) + $moreforfilter = ''; + if (!empty($conf->categorie->enabled)) { - $moreforfilter.='
    '; - $moreforfilter.=$langs->trans('Categories'). ': '; + $moreforfilter .= '
    '; + $moreforfilter .= $langs->trans('Categories').': '; $categoriesProductArr = $form->select_all_categories(Categorie::TYPE_PRODUCT, '', '', 64, 0, 1); - $categoriesProductArr[-2] = '- ' . $langs->trans('NotCategorized') . ' -'; - $moreforfilter.=Form::multiselectarray('search_category_product_list', $categoriesProductArr, $searchCategoryProductList, 0, 0, 'minwidth300'); - $moreforfilter.=' ' . $langs->trans('UseOrOperatorForCategories'); - $moreforfilter.='
    '; + $categoriesProductArr[-2] = '- '.$langs->trans('NotCategorized').' -'; + $moreforfilter .= Form::multiselectarray('search_category_product_list', $categoriesProductArr, $searchCategoryProductList, 0, 0, 'minwidth300'); + $moreforfilter .= ' '.$langs->trans('UseOrOperatorForCategories'); + $moreforfilter .= '
    '; } //Show/hide child products. Hidden by default if (!empty($conf->variants->enabled) && !empty($conf->global->PRODUIT_ATTRIBUTES_HIDECHILD)) { - $moreforfilter.='
    '; - $moreforfilter.= ''; - $moreforfilter.= ' '; - $moreforfilter.='
    '; + $moreforfilter .= '
    '; + $moreforfilter .= ''; + $moreforfilter .= ' '; + $moreforfilter .= '
    '; } - $parameters=array(); - $reshook=$hookmanager->executeHooks('printFieldPreListTitle', $parameters); // Note that $action and $object may have been modified by hook - if (empty($reshook)) $moreforfilter.=$hookmanager->resPrint; - else $moreforfilter=$hookmanager->resPrint; + $parameters = array(); + $reshook = $hookmanager->executeHooks('printFieldPreListTitle', $parameters); // Note that $action and $object may have been modified by hook + if (empty($reshook)) $moreforfilter .= $hookmanager->resPrint; + else $moreforfilter = $hookmanager->resPrint; if ($moreforfilter) { @@ -565,258 +565,258 @@ if ($resql) print '
    '; } - $varpage=empty($contextpage)?$_SERVER["PHP_SELF"]:$contextpage; - $selectedfields=$form->multiSelectArrayWithCheckbox('selectedfields', $arrayfields, $varpage); // This also change content of $arrayfields - if ($massactionbutton) $selectedfields.=$form->showCheckAddButtons('checkforselect', 1); + $varpage = empty($contextpage) ? $_SERVER["PHP_SELF"] : $contextpage; + $selectedfields = $form->multiSelectArrayWithCheckbox('selectedfields', $arrayfields, $varpage); // This also change content of $arrayfields + if ($massactionbutton) $selectedfields .= $form->showCheckAddButtons('checkforselect', 1); print '
    '; - print ''."\n"; + print '
    '."\n"; // Lines with input filters print ''; - if (! empty($arrayfields['p.ref']['checked'])) + if (!empty($arrayfields['p.ref']['checked'])) { print ''; } - if (! empty($arrayfields['pfp.ref_fourn']['checked'])) + if (!empty($arrayfields['pfp.ref_fourn']['checked'])) { print ''; } - if (! empty($arrayfields['p.label']['checked'])) + if (!empty($arrayfields['p.label']['checked'])) { print ''; } // Type - if (! empty($arrayfields['p.fk_product_type']['checked'])) + if (!empty($arrayfields['p.fk_product_type']['checked'])) { print ''; } // Barcode - if (! empty($arrayfields['p.barcode']['checked'])) + if (!empty($arrayfields['p.barcode']['checked'])) { print ''; } // Duration - if (! empty($arrayfields['p.duration']['checked'])) + if (!empty($arrayfields['p.duration']['checked'])) { print ''; } // Weight - if (! empty($arrayfields['p.weight']['checked'])) + if (!empty($arrayfields['p.weight']['checked'])) { print ''; } // Length - if (! empty($arrayfields['p.length']['checked'])) + if (!empty($arrayfields['p.length']['checked'])) { print ''; } // Surface - if (! empty($arrayfields['p.surface']['checked'])) + if (!empty($arrayfields['p.surface']['checked'])) { print ''; } // Volume - if (! empty($arrayfields['p.volume']['checked'])) + if (!empty($arrayfields['p.volume']['checked'])) { print ''; } // Sell price - if (! empty($arrayfields['p.sellprice']['checked'])) + if (!empty($arrayfields['p.sellprice']['checked'])) { print ''; } // Minimum buying Price - if (! empty($arrayfields['p.minbuyprice']['checked'])) + if (!empty($arrayfields['p.minbuyprice']['checked'])) { print ''; } // Number buying Price - if (! empty($arrayfields['p.numbuyprice']['checked'])) + if (!empty($arrayfields['p.numbuyprice']['checked'])) { print ''; } // Sell price - if (! empty($arrayfields['p.tva_tx']['checked'])) + if (!empty($arrayfields['p.tva_tx']['checked'])) { print ''; } // WAP - if (! empty($arrayfields['p.pmp']['checked'])) + if (!empty($arrayfields['p.pmp']['checked'])) { print ''; } // Limit for alert - if (! empty($arrayfields['p.seuil_stock_alerte']['checked'])) + if (!empty($arrayfields['p.seuil_stock_alerte']['checked'])) { print ''; } // Desired stock - if (! empty($arrayfields['p.desiredstock']['checked'])) + if (!empty($arrayfields['p.desiredstock']['checked'])) { print ''; } // Stock - if (! empty($arrayfields['p.stock']['checked'])) print ''; + if (!empty($arrayfields['p.stock']['checked'])) print ''; // Stock - if (! empty($arrayfields['stock_virtual']['checked'])) print ''; + if (!empty($arrayfields['stock_virtual']['checked'])) print ''; // To batch - if (! empty($arrayfields['p.tobatch']['checked'])) print ''; + if (!empty($arrayfields['p.tobatch']['checked'])) print ''; // Accountancy code sell - if (! empty($arrayfields['p.accountancy_code_sell']['checked'])) print ''; - if (! empty($arrayfields['p.accountancy_code_sell_intra']['checked'])) print ''; - if (! empty($arrayfields['p.accountancy_code_sell_export']['checked'])) print ''; + if (!empty($arrayfields['p.accountancy_code_sell']['checked'])) print ''; + if (!empty($arrayfields['p.accountancy_code_sell_intra']['checked'])) print ''; + if (!empty($arrayfields['p.accountancy_code_sell_export']['checked'])) print ''; // Accountancy code buy - if (! empty($arrayfields['p.accountancy_code_buy']['checked'])) print ''; + if (!empty($arrayfields['p.accountancy_code_buy']['checked'])) print ''; // Extra fields include DOL_DOCUMENT_ROOT.'/core/tpl/extrafields_list_search_input.tpl.php'; // Fields from hook - $parameters=array('arrayfields'=>$arrayfields); - $reshook=$hookmanager->executeHooks('printFieldListOption', $parameters); // Note that $action and $object may have been modified by hook + $parameters = array('arrayfields'=>$arrayfields); + $reshook = $hookmanager->executeHooks('printFieldListOption', $parameters); // Note that $action and $object may have been modified by hook print $hookmanager->resPrint; // Date creation - if (! empty($arrayfields['p.datec']['checked'])) + if (!empty($arrayfields['p.datec']['checked'])) { print ''; } // Date modification - if (! empty($arrayfields['p.tms']['checked'])) + if (!empty($arrayfields['p.tms']['checked'])) { print ''; } - if (! empty($arrayfields['p.tosell']['checked'])) + if (!empty($arrayfields['p.tosell']['checked'])) { print ''; } - if (! empty($arrayfields['p.tobuy']['checked'])) + if (!empty($arrayfields['p.tobuy']['checked'])) { print ''; } print ''; print ''; print ''; - if (! empty($arrayfields['p.ref']['checked'])) { + 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['pfp.ref_fourn']['checked'])) { + if (!empty($arrayfields['pfp.ref_fourn']['checked'])) { print_liste_field_titre($arrayfields['pfp.ref_fourn']['label'], $_SERVER["PHP_SELF"], "pfp.ref_fourn", "", $param, "", $sortfield, $sortorder); } - if (! empty($arrayfields['p.label']['checked'])) { + if (!empty($arrayfields['p.label']['checked'])) { print_liste_field_titre($arrayfields['p.label']['label'], $_SERVER["PHP_SELF"], "p.label", "", $param, "", $sortfield, $sortorder); } - if (! empty($arrayfields['p.fk_product_type']['checked'])) { + if (!empty($arrayfields['p.fk_product_type']['checked'])) { print_liste_field_titre($arrayfields['p.fk_product_type']['label'], $_SERVER["PHP_SELF"], "p.fk_product_type", "", $param, "", $sortfield, $sortorder); } - if (! empty($arrayfields['p.barcode']['checked'])) { + if (!empty($arrayfields['p.barcode']['checked'])) { print_liste_field_titre($arrayfields['p.barcode']['label'], $_SERVER["PHP_SELF"], "p.barcode", "", $param, "", $sortfield, $sortorder); } - if (! empty($arrayfields['p.duration']['checked'])) { + if (!empty($arrayfields['p.duration']['checked'])) { print_liste_field_titre($arrayfields['p.duration']['label'], $_SERVER["PHP_SELF"], "p.duration", "", $param, '', $sortfield, $sortorder, 'center '); } - if (! empty($arrayfields['p.weight']['checked'])) print_liste_field_titre($arrayfields['p.weight']['label'], $_SERVER["PHP_SELF"], "p.weight", "", $param, '', $sortfield, $sortorder, 'center '); - if (! empty($arrayfields['p.length']['checked'])) print_liste_field_titre($arrayfields['p.length']['label'], $_SERVER["PHP_SELF"], "p.length", "", $param, '', $sortfield, $sortorder, 'center '); - if (! empty($arrayfields['p.surface']['checked'])) print_liste_field_titre($arrayfields['p.surface']['label'], $_SERVER["PHP_SELF"], "p.surface", "", $param, '', $sortfield, $sortorder, 'center '); - if (! empty($arrayfields['p.volume']['checked'])) print_liste_field_titre($arrayfields['p.volume']['label'], $_SERVER["PHP_SELF"], "p.volume", "", $param, '', $sortfield, $sortorder, 'center '); - if (! empty($arrayfields['p.sellprice']['checked'])) { + if (!empty($arrayfields['p.weight']['checked'])) print_liste_field_titre($arrayfields['p.weight']['label'], $_SERVER["PHP_SELF"], "p.weight", "", $param, '', $sortfield, $sortorder, 'center '); + if (!empty($arrayfields['p.length']['checked'])) print_liste_field_titre($arrayfields['p.length']['label'], $_SERVER["PHP_SELF"], "p.length", "", $param, '', $sortfield, $sortorder, 'center '); + if (!empty($arrayfields['p.surface']['checked'])) print_liste_field_titre($arrayfields['p.surface']['label'], $_SERVER["PHP_SELF"], "p.surface", "", $param, '', $sortfield, $sortorder, 'center '); + if (!empty($arrayfields['p.volume']['checked'])) print_liste_field_titre($arrayfields['p.volume']['label'], $_SERVER["PHP_SELF"], "p.volume", "", $param, '', $sortfield, $sortorder, 'center '); + if (!empty($arrayfields['p.sellprice']['checked'])) { print_liste_field_titre($arrayfields['p.sellprice']['label'], $_SERVER["PHP_SELF"], "", "", $param, '', $sortfield, $sortorder, 'right '); } - if (! empty($arrayfields['p.minbuyprice']['checked'])) { + if (!empty($arrayfields['p.minbuyprice']['checked'])) { print_liste_field_titre($arrayfields['p.minbuyprice']['label'], $_SERVER["PHP_SELF"], "", "", $param, '', $sortfield, $sortorder, 'right '); } - if (! empty($arrayfields['p.numbuyprice']['checked'])) { + if (!empty($arrayfields['p.numbuyprice']['checked'])) { print_liste_field_titre($arrayfields['p.numbuyprice']['label'], $_SERVER["PHP_SELF"], "", "", $param, '', $sortfield, $sortorder, 'right '); } - if (! empty($arrayfields['p.tva_tx']['checked'])) { + if (!empty($arrayfields['p.tva_tx']['checked'])) { print_liste_field_titre($arrayfields['p.tva_tx']['label'], $_SERVER["PHP_SELF"], "", "", $param, '', $sortfield, $sortorder, 'right '); } - if (! empty($arrayfields['p.pmp']['checked'])) { + if (!empty($arrayfields['p.pmp']['checked'])) { print_liste_field_titre($arrayfields['p.pmp']['label'], $_SERVER["PHP_SELF"], "", "", $param, '', $sortfield, $sortorder, 'right '); } - if (! empty($arrayfields['p.seuil_stock_alerte']['checked'])) { + if (!empty($arrayfields['p.seuil_stock_alerte']['checked'])) { print_liste_field_titre($arrayfields['p.seuil_stock_alerte']['label'], $_SERVER["PHP_SELF"], "p.seuil_stock_alerte", "", $param, '', $sortfield, $sortorder, 'right '); } - if (! empty($arrayfields['p.desiredstock']['checked'])) { + if (!empty($arrayfields['p.desiredstock']['checked'])) { print_liste_field_titre($arrayfields['p.desiredstock']['label'], $_SERVER["PHP_SELF"], "p.desiredstock", "", $param, '', $sortfield, $sortorder, 'right '); } - if (! empty($arrayfields['p.stock']['checked'])) { + if (!empty($arrayfields['p.stock']['checked'])) { print_liste_field_titre($arrayfields['p.stock']['label'], $_SERVER["PHP_SELF"], "p.stock", "", $param, '', $sortfield, $sortorder, 'right '); } - if (! empty($arrayfields['stock_virtual']['checked'])) { + if (!empty($arrayfields['stock_virtual']['checked'])) { print_liste_field_titre($arrayfields['stock_virtual']['label'], $_SERVER["PHP_SELF"], "", "", $param, '', $sortfield, $sortorder, 'right '); } - if (! empty($arrayfields['p.tobatch']['checked'])) { + if (!empty($arrayfields['p.tobatch']['checked'])) { print_liste_field_titre($arrayfields['p.tobatch']['label'], $_SERVER["PHP_SELF"], "p.tobatch", "", $param, '', $sortfield, $sortorder, 'center '); } - if (! empty($arrayfields['p.accountancy_code_sell']['checked'])) { + if (!empty($arrayfields['p.accountancy_code_sell']['checked'])) { print_liste_field_titre($arrayfields['p.accountancy_code_sell']['label'], $_SERVER["PHP_SELF"], "p.accountancy_code_sell", "", $param, '', $sortfield, $sortorder); } - if (! empty($arrayfields['p.accountancy_code_sell_intra']['checked'])) { + if (!empty($arrayfields['p.accountancy_code_sell_intra']['checked'])) { print_liste_field_titre($arrayfields['p.accountancy_code_sell_intra']['label'], $_SERVER["PHP_SELF"], "p.accountancy_code_sell_intra", "", $param, '', $sortfield, $sortorder); } - if (! empty($arrayfields['p.accountancy_code_sell_export']['checked'])) { + if (!empty($arrayfields['p.accountancy_code_sell_export']['checked'])) { print_liste_field_titre($arrayfields['p.accountancy_code_sell_export']['label'], $_SERVER["PHP_SELF"], "p.accountancy_code_sell_export", "", $param, '', $sortfield, $sortorder); } - if (! empty($arrayfields['p.accountancy_code_buy']['checked'])) { + if (!empty($arrayfields['p.accountancy_code_buy']['checked'])) { print_liste_field_titre($arrayfields['p.accountancy_code_buy']['label'], $_SERVER["PHP_SELF"], "p.accountancy_code_buy", "", $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 + $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['p.datec']['checked'])) { + if (!empty($arrayfields['p.datec']['checked'])) { print_liste_field_titre($arrayfields['p.datec']['label'], $_SERVER["PHP_SELF"], "p.datec", "", $param, '', $sortfield, $sortorder, 'center nowrap '); } - if (! empty($arrayfields['p.tms']['checked'])) { + if (!empty($arrayfields['p.tms']['checked'])) { print_liste_field_titre($arrayfields['p.tms']['label'], $_SERVER["PHP_SELF"], "p.tms", "", $param, '', $sortfield, $sortorder, 'center nowrap '); } - if (! empty($arrayfields['p.tosell']['checked'])) { + if (!empty($arrayfields['p.tosell']['checked'])) { print_liste_field_titre($arrayfields['p.tosell']['label'], $_SERVER["PHP_SELF"], "p.tosell", "", $param, '', $sortfield, $sortorder, 'right '); } - if (! empty($arrayfields['p.tobuy']['checked'])) { + if (!empty($arrayfields['p.tobuy']['checked'])) { print_liste_field_titre($arrayfields['p.tobuy']['label'], $_SERVER["PHP_SELF"], "p.tobuy", "", $param, '', $sortfield, $sortorder, 'right '); } print_liste_field_titre($selectedfields, $_SERVER["PHP_SELF"], "", '', '', '', $sortfield, $sortorder, 'center maxwidthsearch '); @@ -827,25 +827,25 @@ if ($resql) $product_fourn = new ProductFournisseur($db); $i = 0; - $totalarray=array(); + $totalarray = array(); while ($i < min($num, $limit)) { $obj = $db->fetch_object($resql); // Multilangs - if (! empty($conf->global->MAIN_MULTILANGS)) // si l'option est active + if (!empty($conf->global->MAIN_MULTILANGS)) // si l'option est active { $sql = "SELECT label"; - $sql.= " FROM ".MAIN_DB_PREFIX."product_lang"; - $sql.= " WHERE fk_product=".$obj->rowid; - $sql.= " AND lang='". $db->escape($langs->getDefaultLang()) ."'"; - $sql.= " LIMIT 1"; + $sql .= " FROM ".MAIN_DB_PREFIX."product_lang"; + $sql .= " WHERE fk_product=".$obj->rowid; + $sql .= " AND lang='".$db->escape($langs->getDefaultLang())."'"; + $sql .= " LIMIT 1"; $result = $db->query($sql); if ($result) { $objtp = $db->fetch_object($result); - if (! empty($objtp->label)) $obj->label = $objtp->label; + if (!empty($objtp->label)) $obj->label = $objtp->label; } } @@ -876,11 +876,11 @@ if ($resql) $product_static->surface = $obj->surface; $product_static->surface_units = $obj->surface_units; - if ((! empty($conf->stock->enabled) && $user->rights->stock->lire && $search_type != 1) || ! empty($conf->global->STOCK_DISABLE_OPTIM_LOAD)) // To optimize call of load_stock + if ((!empty($conf->stock->enabled) && $user->rights->stock->lire && $search_type != 1) || !empty($conf->global->STOCK_DISABLE_OPTIM_LOAD)) // To optimize call of load_stock { - if ($obj->fk_product_type != 1 || ! empty($conf->global->STOCK_SUPPORTS_SERVICES)) // Not a service + if ($obj->fk_product_type != 1 || !empty($conf->global->STOCK_SUPPORTS_SERVICES)) // Not a service { - $product_static->load_stock('nobatch'); // Load stock_reel + stock_warehouse. This also call load_virtual_stock() + $product_static->load_stock('nobatch'); // Load stock_reel + stock_warehouse. This also call load_virtual_stock() } } @@ -888,107 +888,107 @@ if ($resql) print ''; // Ref - if (! empty($arrayfields['p.ref']['checked'])) + if (!empty($arrayfields['p.ref']['checked'])) { print '\n"; - if (! $i) $totalarray['nbfield']++; + if (!$i) $totalarray['nbfield']++; } // Ref supplier - if (! empty($arrayfields['pfp.ref_fourn']['checked'])) + if (!empty($arrayfields['pfp.ref_fourn']['checked'])) { print '\n"; - if (! $i) $totalarray['nbfield']++; + if (!$i) $totalarray['nbfield']++; } // Label - if (! empty($arrayfields['p.label']['checked'])) + if (!empty($arrayfields['p.label']['checked'])) { print ''; - if (! $i) $totalarray['nbfield']++; + if (!$i) $totalarray['nbfield']++; } // Type - if (! empty($arrayfields['p.fk_product_type']['checked'])) + if (!empty($arrayfields['p.fk_product_type']['checked'])) { print ''; - if (! $i) $totalarray['nbfield']++; + if (!$i) $totalarray['nbfield']++; } // Barcode - if (! empty($arrayfields['p.barcode']['checked'])) + if (!empty($arrayfields['p.barcode']['checked'])) { print ''; - if (! $i) $totalarray['nbfield']++; + if (!$i) $totalarray['nbfield']++; } // Duration - if (! empty($arrayfields['p.duration']['checked'])) + if (!empty($arrayfields['p.duration']['checked'])) { print ''; - if (! $i) $totalarray['nbfield']++; + if (!$i) $totalarray['nbfield']++; } // Weight - if (! empty($arrayfields['p.weight']['checked'])) + if (!empty($arrayfields['p.weight']['checked'])) { print ''; - if (! $i) $totalarray['nbfield']++; + if (!$i) $totalarray['nbfield']++; } // Length - if (! empty($arrayfields['p.length']['checked'])) + if (!empty($arrayfields['p.length']['checked'])) { print ''; - if (! $i) $totalarray['nbfield']++; + if (!$i) $totalarray['nbfield']++; } // Surface - if (! empty($arrayfields['p.surface']['checked'])) + if (!empty($arrayfields['p.surface']['checked'])) { print ''; - if (! $i) $totalarray['nbfield']++; + if (!$i) $totalarray['nbfield']++; } // Volume - if (! empty($arrayfields['p.volume']['checked'])) + if (!empty($arrayfields['p.volume']['checked'])) { print ''; - if (! $i) $totalarray['nbfield']++; + if (!$i) $totalarray['nbfield']++; } // Sell price - if (! empty($arrayfields['p.sellprice']['checked'])) + if (!empty($arrayfields['p.sellprice']['checked'])) { print ''; - if (! $i) $totalarray['nbfield']++; + if (!$i) $totalarray['nbfield']++; } // Better buy price - if (! empty($arrayfields['p.minbuyprice']['checked'])) + if (!empty($arrayfields['p.minbuyprice']['checked'])) { print ''; - if (! $i) $totalarray['nbfield']++; + if (!$i) $totalarray['nbfield']++; } // Number of buy prices - if (! empty($arrayfields['p.numbuyprice']['checked'])) + if (!empty($arrayfields['p.numbuyprice']['checked'])) { print ''; - if (! $i) $totalarray['nbfield']++; + if (!$i) $totalarray['nbfield']++; } // WAP - if (! empty($arrayfields['p.pmp']['checked'])) + if (!empty($arrayfields['p.pmp']['checked'])) { print ''; - if (! $i) $totalarray['nbfield']++; + if (!$i) $totalarray['nbfield']++; } // Desired stock - if (! empty($arrayfields['p.desiredstock']['checked'])) + if (!empty($arrayfields['p.desiredstock']['checked'])) { print ''; - if (! $i) $totalarray['nbfield']++; + if (!$i) $totalarray['nbfield']++; } // Stock real - if (! empty($arrayfields['p.stock']['checked'])) + if (!empty($arrayfields['p.stock']['checked'])) { print ''; - if (! $i) $totalarray['nbfield']++; + if (!$i) $totalarray['nbfield']++; } // Stock virtual - if (! empty($arrayfields['stock_virtual']['checked'])) + if (!empty($arrayfields['stock_virtual']['checked'])) { print ''; - if (! $i) $totalarray['nbfield']++; + if (!$i) $totalarray['nbfield']++; } // Lot/Serial - if (! empty($arrayfields['p.tobatch']['checked'])) + if (!empty($arrayfields['p.tobatch']['checked'])) { print ''; - if (! $i) $totalarray['nbfield']++; + if (!$i) $totalarray['nbfield']++; } // Accountancy code sell - if (! empty($arrayfields['p.accountancy_code_sell']['checked'])) + if (!empty($arrayfields['p.accountancy_code_sell']['checked'])) { print ''; - if (! $i) $totalarray['nbfield']++; + if (!$i) $totalarray['nbfield']++; } - if (! empty($arrayfields['p.accountancy_code_sell_intra']['checked'])) + if (!empty($arrayfields['p.accountancy_code_sell_intra']['checked'])) { print ''; - if (! $i) $totalarray['nbfield']++; + if (!$i) $totalarray['nbfield']++; } - if (! empty($arrayfields['p.accountancy_code_sell_export']['checked'])) + if (!empty($arrayfields['p.accountancy_code_sell_export']['checked'])) { print ''; - if (! $i) $totalarray['nbfield']++; + if (!$i) $totalarray['nbfield']++; } // Accountancy code buy - if (! empty($arrayfields['p.accountancy_code_buy']['checked'])) + if (!empty($arrayfields['p.accountancy_code_buy']['checked'])) { print ''; - if (! $i) $totalarray['nbfield']++; + if (!$i) $totalarray['nbfield']++; } // Extra fields include DOL_DOCUMENT_ROOT.'/core/tpl/extrafields_list_print_fields.tpl.php'; // Fields from hook - $parameters=array('arrayfields'=>$arrayfields, 'obj'=>$obj); - $reshook=$hookmanager->executeHooks('printFieldListValue', $parameters); // Note that $action and $object may have been modified by hook + $parameters = array('arrayfields'=>$arrayfields, 'obj'=>$obj); + $reshook = $hookmanager->executeHooks('printFieldListValue', $parameters); // Note that $action and $object may have been modified by hook print $hookmanager->resPrint; // 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 (to sell) - if (! empty($arrayfields['p.tosell']['checked'])) + if (!empty($arrayfields['p.tosell']['checked'])) { print ''; - if (! $i) $totalarray['nbfield']++; + if (!$i) $totalarray['nbfield']++; } // Status (to buy) - if (! empty($arrayfields['p.tobuy']['checked'])) + if (!empty($arrayfields['p.tobuy']['checked'])) { print ''; - if (! $i) $totalarray['nbfield']++; + if (!$i) $totalarray['nbfield']++; } // Action print ''; - if (! $i) $totalarray['nbfield']++; + if (!$i) $totalarray['nbfield']++; print "\n"; $i++; diff --git a/htdocs/product/popuprop.php b/htdocs/product/popuprop.php index c50ca3538aa..95bf2b965a2 100644 --- a/htdocs/product/popuprop.php +++ b/htdocs/product/popuprop.php @@ -157,7 +157,7 @@ else print_barre_liste($title, $page, $_SERVER["PHP_SELF"], $param, $sortfield, $sortorder, "", $num, $totalnboflines, ''); -print '
    '; print ''; print ''; print ''; print ''; print ''; print ''; - $array=array('-1'=>' ', '0'=>$langs->trans('Product'), '1'=>$langs->trans('Service')); + $array = array('-1'=>' ', '0'=>$langs->trans('Product'), '1'=>$langs->trans('Service')); print $form->selectarray('search_type', $array, $search_type); print ''; print ''; print ''; print ''; print ''; print ''; print ''; print ''; print ''; print ' '; print ''; print ' '; print ''; print ''; print ''; print ' '; print ''; print ' '; print ''; print ' '; print '    '.$form->selectyesno($search_tobatch, '', '', '', 1).''.$form->selectyesno($search_tobatch, '', '', '', 1).''; print ''; print ''; - print $form->selectarray('search_tosell', array('0'=>$langs->trans('ProductStatusNotOnSellShort'),'1'=>$langs->trans('ProductStatusOnSellShort')), $search_tosell, 1); + print $form->selectarray('search_tosell', array('0'=>$langs->trans('ProductStatusNotOnSellShort'), '1'=>$langs->trans('ProductStatusOnSellShort')), $search_tosell, 1); print ''; - print $form->selectarray('search_tobuy', array('0'=>$langs->trans('ProductStatusNotOnBuyShort'),'1'=>$langs->trans('ProductStatusOnBuyShort')), $search_tobuy, 1); + print $form->selectarray('search_tobuy', array('0'=>$langs->trans('ProductStatusNotOnBuyShort'), '1'=>$langs->trans('ProductStatusOnBuyShort')), $search_tobuy, 1); print ''; - $searchpicto=$form->showFilterButtons(); + $searchpicto = $form->showFilterButtons(); print $searchpicto; print '
    '; print $product_static->getNomUrl(1); print "'; print $product_static->getNomUrl(1); print "'.dol_trunc($obj->label, 80).''.$obj->fk_product_type.''.$obj->barcode.''; if (preg_match('/([^a-z]+)[a-z]$/i', $obj->duration)) { - $duration_value = substr($obj->duration, 0, dol_strlen($obj->duration)-1); - $duration_unit = substr($obj->duration, -1); + $duration_value = substr($obj->duration, 0, dol_strlen($obj->duration) - 1); + $duration_unit = substr($obj->duration, -1); if ((float) $duration_value > 1) { - $dur=array("i"=>$langs->trans("Minutes"),"h"=>$langs->trans("Hours"),"d"=>$langs->trans("Days"),"w"=>$langs->trans("Weeks"),"m"=>$langs->trans("Months"),"y"=>$langs->trans("Years")); + $dur = array("i"=>$langs->trans("Minutes"), "h"=>$langs->trans("Hours"), "d"=>$langs->trans("Days"), "w"=>$langs->trans("Weeks"), "m"=>$langs->trans("Months"), "y"=>$langs->trans("Years")); } elseif ((float) $duration_value > 0) { - $dur=array("i"=>$langs->trans("Minute"),"h"=>$langs->trans("Hour"),"d"=>$langs->trans("Day"),"w"=>$langs->trans("Week"),"m"=>$langs->trans("Month"),"y"=>$langs->trans("Year")); + $dur = array("i"=>$langs->trans("Minute"), "h"=>$langs->trans("Hour"), "d"=>$langs->trans("Day"), "w"=>$langs->trans("Week"), "m"=>$langs->trans("Month"), "y"=>$langs->trans("Year")); } print $duration_value; - print ((! empty($duration_unit) && isset($dur[$duration_unit]) && $duration_value != '') ? ' '.$langs->trans($dur[$duration_unit]) : ''); + print ((!empty($duration_unit) && isset($dur[$duration_unit]) && $duration_value != '') ? ' '.$langs->trans($dur[$duration_unit]) : ''); } - elseif (! preg_match('/^[a-z]$/i', $obj->duration)) // If duration is a simple char (like 's' of 'm'), we do not show value + elseif (!preg_match('/^[a-z]$/i', $obj->duration)) // If duration is a simple char (like 's' of 'm'), we do not show value { print $obj->duration; } print ''; print $obj->weight; print ''; print $obj->length; print ''; print $obj->surface; print ''; print $obj->volume; print ''; if ($obj->tosell) @@ -997,11 +997,11 @@ if ($resql) else print price($obj->price).' '.$langs->trans("HT"); } print ''; if ($obj->tobuy && $obj->minsellprice != '') @@ -1011,28 +1011,28 @@ if ($resql) { if ($product_fourn->product_fourn_price_id > 0) { - if (! empty($conf->fournisseur->enabled) && $user->rights->fournisseur->lire) + if (!empty($conf->fournisseur->enabled) && $user->rights->fournisseur->lire) { - $htmltext=$product_fourn->display_price_product_fournisseur(1, 1, 0, 1); - print $form->textwithpicto(price($product_fourn->fourn_unitprice * (1 - $product_fourn->fourn_remise_percent/100) - $product_fourn->fourn_remise).' '.$langs->trans("HT"), $htmltext); + $htmltext = $product_fourn->display_price_product_fournisseur(1, 1, 0, 1); + print $form->textwithpicto(price($product_fourn->fourn_unitprice * (1 - $product_fourn->fourn_remise_percent / 100) - $product_fourn->fourn_remise).' '.$langs->trans("HT"), $htmltext); } else print price($product_fourn->fourn_unitprice).' '.$langs->trans("HT"); } } } print ''; if ($obj->tobuy) { if (count($productFournList = $product_fourn->list_product_fournisseur_price($obj->rowid)) > 0) { - $htmltext=$product_fourn->display_price_product_fournisseur(1, 1, 0, 1, $productFournList); + $htmltext = $product_fourn->display_price_product_fournisseur(1, 1, 0, 1, $productFournList); print $form->textwithpicto(count($productFournList), $htmltext); } } @@ -1040,16 +1040,16 @@ if ($resql) } // Sell Tax Rate - if (! empty($arrayfields['p.tva_tx']['checked'])) + if (!empty($arrayfields['p.tva_tx']['checked'])) { print ''; print vatrate($obj->tva_tx, true); print ''; print price($product_static->pmp, 1, $langs); @@ -1057,7 +1057,7 @@ if ($resql) } // Limit alert - if (! empty($arrayfields['p.seuil_stock_alerte']['checked'])) + if (!empty($arrayfields['p.seuil_stock_alerte']['checked'])) { print ''; if ($obj->fk_product_type != 1) @@ -1065,10 +1065,10 @@ if ($resql) print $obj->seuil_stock_alerte; } print ''; if ($obj->fk_product_type != 1) @@ -1076,10 +1076,10 @@ if ($resql) print $obj->desiredstock; } print ''; if ($obj->fk_product_type != 1) @@ -1088,10 +1088,10 @@ if ($resql) print $product_static->stock_reel; } print ''; if ($obj->fk_product_type != 1) @@ -1100,95 +1100,95 @@ if ($resql) print $product_static->stock_theorique; } print ''; print yn($obj->tobatch); print ''.$obj->accountancy_code_sell.''.$obj->accountancy_code_sell_intra.''.$obj->accountancy_code_sell_export.''.$obj->accountancy_code_buy.''; 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 (! empty($conf->use_javascript_ajax) && $user->rights->produit->creer && ! empty($conf->global->MAIN_DIRECT_STATUS_UPDATE)) { + if (!empty($conf->use_javascript_ajax) && $user->rights->produit->creer && !empty($conf->global->MAIN_DIRECT_STATUS_UPDATE)) { print ajax_object_onoff($product_static, 'status', 'tosell', 'ProductStatusOnSell', 'ProductStatusNotOnSell'); } else { print $product_static->LibStatut($obj->tosell, 5, 0); } print ''; - if (! empty($conf->use_javascript_ajax) && $user->rights->produit->creer && ! empty($conf->global->MAIN_DIRECT_STATUS_UPDATE)) { + if (!empty($conf->use_javascript_ajax) && $user->rights->produit->creer && !empty($conf->global->MAIN_DIRECT_STATUS_UPDATE)) { print ajax_object_onoff($product_static, 'status_buy', 'tobuy', 'ProductStatusOnBuy', 'ProductStatusNotOnBuy'); } else { print $product_static->LibStatut($obj->tobuy, 5, 1); } print ''; if ($massactionbutton || $massaction) // If we are in select mode (massactionbutton defined) or if we have already selected and sent an action ($massaction) defined { - $selected=0; - if (in_array($obj->rowid, $arrayofselected)) $selected=1; - print ''; + $selected = 0; + if (in_array($obj->rowid, $arrayofselected)) $selected = 1; + print ''; } print '
    '; +print '
    '; print ""; print_liste_field_titre('Ref', $_SERVER["PHP_SELF"], 'p.ref', '', $param, '', $sortfield, $sortorder); diff --git a/htdocs/product/price.php b/htdocs/product/price.php index f6820bc37bc..6609d6c3968 100644 --- a/htdocs/product/price.php +++ b/htdocs/product/price.php @@ -34,14 +34,14 @@ * \brief Page to show product prices */ require '../main.inc.php'; -require_once DOL_DOCUMENT_ROOT . '/core/lib/product.lib.php'; -require_once DOL_DOCUMENT_ROOT . '/core/lib/price.lib.php'; -require_once DOL_DOCUMENT_ROOT . '/product/class/product.class.php'; -require_once DOL_DOCUMENT_ROOT . '/product/dynamic_price/class/price_expression.class.php'; -require_once DOL_DOCUMENT_ROOT . '/product/dynamic_price/class/price_parser.class.php'; +require_once DOL_DOCUMENT_ROOT.'/core/lib/product.lib.php'; +require_once DOL_DOCUMENT_ROOT.'/core/lib/price.lib.php'; +require_once DOL_DOCUMENT_ROOT.'/product/class/product.class.php'; +require_once DOL_DOCUMENT_ROOT.'/product/dynamic_price/class/price_expression.class.php'; +require_once DOL_DOCUMENT_ROOT.'/product/dynamic_price/class/price_parser.class.php'; -if (! empty($conf->global->PRODUIT_CUSTOMER_PRICES)) { - require_once DOL_DOCUMENT_ROOT . '/product/class/productcustomerprice.class.php'; +if (!empty($conf->global->PRODUIT_CUSTOMER_PRICES)) { + require_once DOL_DOCUMENT_ROOT.'/product/class/productcustomerprice.class.php'; $prodcustprice = new Productcustomerprice($db); } @@ -49,7 +49,7 @@ if (! empty($conf->global->PRODUIT_CUSTOMER_PRICES)) { // Load translation files required by the page $langs->loadLangs(array('products', 'bills', 'companies', 'other')); -$mesg=''; $error=0; $errors=array(); +$mesg = ''; $error = 0; $errors = array(); $id = GETPOST('id', 'int'); $ref = GETPOST('ref', 'alpha'); @@ -60,32 +60,32 @@ $eid = GETPOST('eid', 'int'); $search_soc = GETPOST('search_soc'); // Security check -$fieldvalue = (! empty($id) ? $id : (! empty($ref) ? $ref : '')); -$fieldtype = (! empty($ref) ? 'ref' : 'rowid'); +$fieldvalue = (!empty($id) ? $id : (!empty($ref) ? $ref : '')); +$fieldtype = (!empty($ref) ? 'ref' : 'rowid'); if ($user->socid) $socid = $user->socid; $result = restrictedArea($user, 'produit|service', $fieldvalue, 'product&product', '', '', $fieldtype); -if ($id > 0 || ! empty($ref)) +if ($id > 0 || !empty($ref)) { $object = new Product($db); $object->fetch($id, $ref); } // Clean param -if ((! empty($conf->global->PRODUIT_MULTIPRICES) || ! empty($conf->global->PRODUIT_CUSTOMER_PRICES_BY_QTY_MULTIPRICES)) && empty($conf->global->PRODUIT_MULTIPRICES_LIMIT)) $conf->global->PRODUIT_MULTIPRICES_LIMIT = 5; +if ((!empty($conf->global->PRODUIT_MULTIPRICES) || !empty($conf->global->PRODUIT_CUSTOMER_PRICES_BY_QTY_MULTIPRICES)) && empty($conf->global->PRODUIT_MULTIPRICES_LIMIT)) $conf->global->PRODUIT_MULTIPRICES_LIMIT = 5; // Initialize technical object to manage hooks of page. Note that conf->hooks_modules contains array of hook context -$hookmanager->initHooks(array('productpricecard','globalcard')); +$hookmanager->initHooks(array('productpricecard', 'globalcard')); /* * Actions */ -if ($cancel) $action=''; +if ($cancel) $action = ''; -$parameters=array('id'=>$id, 'ref'=>$ref); -$reshook=$hookmanager->executeHooks('doActions', $parameters, $object, $action); // Note that $action and $object may have been modified by some hooks +$parameters = array('id'=>$id, 'ref'=>$ref); +$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)) @@ -97,7 +97,7 @@ if (empty($reshook)) if ($action == 'setlabelsellingprice' && $user->admin) { - require_once DOL_DOCUMENT_ROOT . '/core/lib/admin.lib.php'; + require_once DOL_DOCUMENT_ROOT.'/core/lib/admin.lib.php'; $keyforlabel = 'PRODUIT_MULTIPRICES_LABEL'.GETPOST('pricelevel'); dolibarr_set_const($db, $keyforlabel, GETPOST('labelsellingprice', 'alpha'), 'chaine', 0, '', $conf->entity); $action = ''; @@ -105,7 +105,7 @@ if (empty($reshook)) if (($action == 'update_vat') && !$cancel && ($user->rights->produit->creer || $user->rights->service->creer)) { - $tva_tx_txt = GETPOST('tva_tx', 'alpha'); // tva_tx can be '8.5' or '8.5*' or '8.5 (XXX)' or '8.5* (XXX)' + $tva_tx_txt = GETPOST('tva_tx', 'alpha'); // tva_tx can be '8.5' or '8.5*' or '8.5 (XXX)' or '8.5* (XXX)' // We must define tva_tx, npr and local taxes $tva_tx = $tva_tx_txt; @@ -113,24 +113,24 @@ if (empty($reshook)) if (preg_match('/\((.*)\)/', $tva_tx_txt, $reg)) { $vat_src_code = $reg[1]; - $tva_tx = preg_replace('/\s*\(.*\)/', '', $tva_tx_txt); // Remove code into vatrate. + $tva_tx = preg_replace('/\s*\(.*\)/', '', $tva_tx_txt); // Remove code into vatrate. } - $tva_tx = price2num(preg_replace('/\*/', '', $tva_tx)); // keep remove all after the numbers and dot + $tva_tx = price2num(preg_replace('/\*/', '', $tva_tx)); // keep remove all after the numbers and dot $npr = preg_match('/\*/', $tva_tx_txt) ? 1 : 0; $localtax1 = 0; $localtax2 = 0; $localtax1_type = '0'; $localtax2_type = '0'; // If value contains the unique code of vat line (new recommanded method), we use it to find npr and local taxes if (preg_match('/\((.*)\)/', $tva_tx_txt, $reg)) { // We look into database using code (we can't use get_localtax() because it depends on buyer that is not known). Same in create product. - $vatratecode=$reg[1]; + $vatratecode = $reg[1]; // Get record from code $sql = "SELECT t.rowid, t.code, t.recuperableonly, t.localtax1, t.localtax2, t.localtax1_type, t.localtax2_type"; - $sql.= " FROM ".MAIN_DB_PREFIX."c_tva as t, ".MAIN_DB_PREFIX."c_country as c"; - $sql.= " WHERE t.fk_pays = c.rowid AND c.code = '".$mysoc->country_code."'"; - $sql.= " AND t.taux = ".((float) $tva_tx)." AND t.active = 1"; - $sql.= " AND t.code ='".$vatratecode."'"; - $resql=$db->query($sql); + $sql .= " FROM ".MAIN_DB_PREFIX."c_tva as t, ".MAIN_DB_PREFIX."c_country as c"; + $sql .= " WHERE t.fk_pays = c.rowid AND c.code = '".$mysoc->country_code."'"; + $sql .= " AND t.taux = ".((float) $tva_tx)." AND t.active = 1"; + $sql .= " AND t.code ='".$vatratecode."'"; + $resql = $db->query($sql); if ($resql) { $obj = $db->fetch_object($resql); @@ -162,11 +162,11 @@ if (empty($reshook)) if ($error) { //$localtaxarray=array('0'=>$localtax1_type,'1'=>$localtax1,'2'=>$localtax2_type,'3'=>$localtax2); - $localtaxarray=array(); // We do not store localtaxes into product, we will use instead the "vat code" to retreive them. + $localtaxarray = array(); // We do not store localtaxes into product, we will use instead the "vat code" to retreive them. $object->updatePrice(0, $object->price_base_type, $user, $tva_tx, '', 0, $npr, 0, 0, $localtaxarray, $vatratecode); } - if (! $error) + if (!$error) { $db->commit(); } @@ -175,7 +175,7 @@ if (empty($reshook)) $db->rollback(); } - $action=''; + $action = ''; } if (($action == 'update_price') && !$cancel && $object->getRights()->creer) @@ -195,14 +195,14 @@ if (empty($reshook)) $priceparser = new PriceParser($db); if ($priceparser->parseProduct($object) < 0) { - $error ++; + $error++; setEventMessages($priceparser->translatedError(), null, 'errors'); } } } // Multiprices - if (! $error && (! empty($conf->global->PRODUIT_MULTIPRICES) || ! empty($conf->global->PRODUIT_CUSTOMER_PRICES_BY_QTY_MULTIPRICES))) { + if (!$error && (!empty($conf->global->PRODUIT_MULTIPRICES) || !empty($conf->global->PRODUIT_CUSTOMER_PRICES_BY_QTY_MULTIPRICES))) { $newprice = GETPOST('price', 'array'); $newprice_min = GETPOST('price_min', 'array'); $newpricebase = GETPOST('multiprices_base_type', 'array'); @@ -216,7 +216,7 @@ if (empty($reshook)) //Shall we generate prices using price rules? $object->price_autogen = GETPOST('usePriceRules') == 'on'; - for ($i = 1; $i <= $conf->global->PRODUIT_MULTIPRICES_LIMIT; $i ++) + for ($i = 1; $i <= $conf->global->PRODUIT_MULTIPRICES_LIMIT; $i++) { if (!isset($newprice[$i])) { continue; @@ -229,9 +229,9 @@ if (empty($reshook)) if (preg_match('/\((.*)\)/', $tva_tx_txt, $reg)) { $vat_src_code = $reg[1]; - $tva_tx = preg_replace('/\s*\(.*\)/', '', $tva_tx_txt); // Remove code into vatrate. + $tva_tx = preg_replace('/\s*\(.*\)/', '', $tva_tx_txt); // Remove code into vatrate. } - $tva_tx = price2num(preg_replace('/\*/', '', $tva_tx)); // keep remove all after the numbers and dot + $tva_tx = price2num(preg_replace('/\*/', '', $tva_tx)); // keep remove all after the numbers and dot $npr = preg_match('/\*/', $tva_tx_txt) ? 1 : 0; $localtax1 = $newlocaltax1_tx[$i]; @@ -241,14 +241,14 @@ if (empty($reshook)) if (preg_match('/\((.*)\)/', $tva_tx_txt, $reg)) { // We look into database using code - $vatratecode=$reg[1]; + $vatratecode = $reg[1]; // Get record from code $sql = "SELECT t.rowid, t.code, t.recuperableonly, t.localtax1, t.localtax2, t.localtax1_type, t.localtax2_type"; - $sql.= " FROM ".MAIN_DB_PREFIX."c_tva as t, ".MAIN_DB_PREFIX."c_country as c"; - $sql.= " WHERE t.fk_pays = c.rowid AND c.code = '".$mysoc->country_code."'"; - $sql.= " AND t.taux = ".((float) $tva_tx)." AND t.active = 1"; - $sql.= " AND t.code ='".$vatratecode."'"; - $resql=$db->query($sql); + $sql .= " FROM ".MAIN_DB_PREFIX."c_tva as t, ".MAIN_DB_PREFIX."c_country as c"; + $sql .= " WHERE t.fk_pays = c.rowid AND c.code = '".$mysoc->country_code."'"; + $sql .= " AND t.taux = ".((float) $tva_tx)." AND t.active = 1"; + $sql .= " AND t.code ='".$vatratecode."'"; + $resql = $db->query($sql); if ($resql) { $obj = $db->fetch_object($resql); @@ -265,8 +265,8 @@ if (empty($reshook)) 'price_min' => $newprice_min[$i], 'price_base_type' => $newpricebase[$i], 'default_vat_code' => $vatratecode, - 'vat_tx' => $tva_tx, // default_vat_code should be used in priority in a future - 'npr' => $npr, // default_vat_code should be used in priority in a future + 'vat_tx' => $tva_tx, // default_vat_code should be used in priority in a future + 'npr' => $npr, // default_vat_code should be used in priority in a future 'localtaxes_array' => array('0'=>$localtax1_type, '1'=>$localtax1, '2'=>$localtax2_type, '3'=>$localtax2) // default_vat_code should be used in priority in a future ); @@ -276,18 +276,18 @@ if (empty($reshook)) } } } - elseif (! $error) + elseif (!$error) { - $tva_tx_txt = GETPOST('tva_tx', 'alpha'); // tva_tx can be '8.5' or '8.5*' or '8.5 (XXX)' or '8.5* (XXX)' + $tva_tx_txt = GETPOST('tva_tx', 'alpha'); // tva_tx can be '8.5' or '8.5*' or '8.5 (XXX)' or '8.5* (XXX)' $tva_tx = $tva_tx_txt; $vatratecode = ''; if (preg_match('/\((.*)\)/', $tva_tx_txt, $reg)) { $vat_src_code = $reg[1]; - $tva_tx = preg_replace('/\s*\(.*\)/', '', $tva_tx_txt); // Remove code into vatrate. + $tva_tx = preg_replace('/\s*\(.*\)/', '', $tva_tx_txt); // Remove code into vatrate. } - $tva_tx = price2num(preg_replace('/\*/', '', $tva_tx)); // keep remove all after the numbers and dot + $tva_tx = price2num(preg_replace('/\*/', '', $tva_tx)); // keep remove all after the numbers and dot $npr = preg_match('/\*/', $tva_tx_txt) ? 1 : 0; $localtax1 = 0; $localtax2 = 0; $localtax1_type = '0'; $localtax2_type = '0'; @@ -295,14 +295,14 @@ if (empty($reshook)) if (preg_match('/\((.*)\)/', $tva_tx_txt, $reg)) { // We look into database using code - $vatratecode=$reg[1]; + $vatratecode = $reg[1]; // Get record from code $sql = "SELECT t.rowid, t.code, t.recuperableonly, t.localtax1, t.localtax2, t.localtax1_type, t.localtax2_type"; - $sql.= " FROM ".MAIN_DB_PREFIX."c_tva as t, ".MAIN_DB_PREFIX."c_country as c"; - $sql.= " WHERE t.fk_pays = c.rowid AND c.code = '".$mysoc->country_code."'"; - $sql.= " AND t.taux = ".$tva_tx." AND t.active = 1"; - $sql.= " AND t.code ='".$vatratecode."'"; - $resql=$db->query($sql); + $sql .= " FROM ".MAIN_DB_PREFIX."c_tva as t, ".MAIN_DB_PREFIX."c_country as c"; + $sql .= " WHERE t.fk_pays = c.rowid AND c.code = '".$mysoc->country_code."'"; + $sql .= " AND t.taux = ".$tva_tx." AND t.active = 1"; + $sql .= " AND t.code ='".$vatratecode."'"; + $resql = $db->query($sql); if ($resql) { $obj = $db->fetch_object($resql); @@ -325,8 +325,8 @@ if (empty($reshook)) 'price_min' => $_POST["price_min"], 'price_base_type' => $_POST["price_base_type"], 'default_vat_code' => $vatratecode, - 'vat_tx' => $tva_tx, // default_vat_code should be used in priority in a future - 'npr' => $npr, // default_vat_code should be used in priority in a future + 'vat_tx' => $tva_tx, // default_vat_code should be used in priority in a future + 'npr' => $npr, // default_vat_code should be used in priority in a future 'localtaxes_array' => array('0'=>$localtax1_type, '1'=>$localtax1, '2'=>$localtax2_type, '3'=>$localtax2) // default_vat_code should be used in priority in a future ); } @@ -346,17 +346,17 @@ if (empty($reshook)) if (!empty($conf->global->PRODUCT_MINIMUM_RECOMMENDED_PRICE) && $newprice_min < $maxpricesupplier) { setEventMessages($langs->trans("MinimumPriceLimit", price($maxpricesupplier, 0, '', 1, - 1, - 1, 'auto')), null, 'errors'); - $error ++; + $error++; break; } - if($object->multiprices[$key]!=$newprice || $object->multiprices_min[$key]!=$newprice_min || $object->multiprices_base_type[$key]!=$val['price_base_type']) + if ($object->multiprices[$key] != $newprice || $object->multiprices_min[$key] != $newprice_min || $object->multiprices_base_type[$key] != $val['price_base_type']) $res = $object->updatePrice($newprice, $val['price_base_type'], $user, $val['vat_tx'], $newprice_min, $key, $val['npr'], $psq, 0, $val['localtaxes_array'], $val['default_vat_code']); - else $res=0; + else $res = 0; if ($res < 0) { - $error ++; + $error++; setEventMessages($object->error, $object->errors, 'errors'); break; } @@ -427,7 +427,7 @@ if (empty($reshook)) $error++; setEventMessages($langs->trans("ErrorFieldRequired", $langs->transnoentities("Price")), null, 'errors'); } - if (! $error) { + if (!$error) { // Calcul du prix HT et du prix unitaire if ($object->price_base_type == 'TTC') { $price = price2num($newprice) / (1 + ($object->tva_tx / 100)); @@ -438,22 +438,22 @@ if (empty($reshook)) // Ajout / mise à jour if ($rowid > 0) { - $sql = "UPDATE " . MAIN_DB_PREFIX . "product_price_by_qty SET"; - $sql .= " price='" . $price . "',"; - $sql .= " unitprice=" . $unitPrice . ","; - $sql .= " quantity=" . $quantity . ","; - $sql .= " remise_percent=" . $remise_percent . ","; - $sql .= " remise=" . $remise; - $sql .= " WHERE rowid = " . $rowid; + $sql = "UPDATE ".MAIN_DB_PREFIX."product_price_by_qty SET"; + $sql .= " price='".$price."',"; + $sql .= " unitprice=".$unitPrice.","; + $sql .= " quantity=".$quantity.","; + $sql .= " remise_percent=".$remise_percent.","; + $sql .= " remise=".$remise; + $sql .= " WHERE rowid = ".$rowid; $result = $db->query($sql); - if (! $result) dol_print_error($db); + if (!$result) dol_print_error($db); } else { - $sql = "INSERT INTO " . MAIN_DB_PREFIX . "product_price_by_qty (fk_product_price,price,unitprice,quantity,remise_percent,remise) values ("; - $sql .= $priceid . ',' . $price . ',' . $unitPrice . ',' . $quantity . ',' . $remise_percent . ',' . $remise . ')'; + $sql = "INSERT INTO ".MAIN_DB_PREFIX."product_price_by_qty (fk_product_price,price,unitprice,quantity,remise_percent,remise) values ("; + $sql .= $priceid.','.$price.','.$unitPrice.','.$quantity.','.$remise_percent.','.$remise.')'; $result = $db->query($sql); - if (! $result) dol_print_error($db); + if (!$result) dol_print_error($db); } } } @@ -462,8 +462,8 @@ if (empty($reshook)) { $rowid = GETPOST('rowid', 'int'); if (!empty($rowid)) { - $sql = "DELETE FROM " . MAIN_DB_PREFIX . "product_price_by_qty"; - $sql .= " WHERE rowid = " . $rowid; + $sql = "DELETE FROM ".MAIN_DB_PREFIX."product_price_by_qty"; + $sql .= " WHERE rowid = ".$rowid; $result = $db->query($sql); } else { @@ -475,8 +475,8 @@ if (empty($reshook)) { $priceid = GETPOST('priceid', 'int'); if (!empty($rowid)) { - $sql = "DELETE FROM " . MAIN_DB_PREFIX . "product_price_by_qty"; - $sql .= " WHERE fk_product_price = " . $priceid; + $sql = "DELETE FROM ".MAIN_DB_PREFIX."product_price_by_qty"; + $sql .= " WHERE fk_product_price = ".$priceid; $result = $db->query($sql); } else { @@ -508,9 +508,9 @@ if (empty($reshook)) if (preg_match('/\((.*)\)/', $tva_tx_txt, $reg)) { $vat_src_code = $reg[1]; - $tva_tx = preg_replace('/\s*\(.*\)/', '', $tva_tx_txt); // Remove code into vatrate. + $tva_tx = preg_replace('/\s*\(.*\)/', '', $tva_tx_txt); // Remove code into vatrate. } - $tva_tx = price2num(preg_replace('/\*/', '', $tva_tx)); // keep remove all after the numbers and dot + $tva_tx = price2num(preg_replace('/\*/', '', $tva_tx)); // keep remove all after the numbers and dot $npr = preg_match('/\*/', $tva_tx_txt) ? 1 : 0; $localtax1 = 0; $localtax2 = 0; $localtax1_type = '0'; $localtax2_type = '0'; @@ -518,14 +518,14 @@ if (empty($reshook)) if (preg_match('/\((.*)\)/', $tva_tx_txt, $reg)) { // We look into database using code - $vatratecode=$reg[1]; + $vatratecode = $reg[1]; // Get record from code $sql = "SELECT t.rowid, t.code, t.recuperableonly, t.localtax1, t.localtax2, t.localtax1_type, t.localtax2_type"; - $sql.= " FROM ".MAIN_DB_PREFIX."c_tva as t, ".MAIN_DB_PREFIX."c_country as c"; - $sql.= " WHERE t.fk_pays = c.rowid AND c.code = '".$mysoc->country_code."'"; - $sql.= " AND t.taux = ".$tva_tx." AND t.active = 1"; - $sql.= " AND t.code ='".$vatratecode."'"; - $resql=$db->query($sql); + $sql .= " FROM ".MAIN_DB_PREFIX."c_tva as t, ".MAIN_DB_PREFIX."c_country as c"; + $sql .= " WHERE t.fk_pays = c.rowid AND c.code = '".$mysoc->country_code."'"; + $sql .= " AND t.taux = ".$tva_tx." AND t.active = 1"; + $sql .= " AND t.code ='".$vatratecode."'"; + $resql = $db->query($sql); if ($resql) { $obj = $db->fetch_object($resql); @@ -545,22 +545,22 @@ if (empty($reshook)) $prodcustprice->localtax1_type = $localtax1_type; $prodcustprice->localtax2_type = $localtax2_type; - if (! ($prodcustprice->fk_soc > 0)) + if (!($prodcustprice->fk_soc > 0)) { $langs->load("errors"); setEventMessages($langs->trans("ErrorFieldRequired", $langs->transnoentitiesnoconv("ThirdParty")), null, 'errors'); $error++; - $action='add_customer_price'; + $action = 'add_customer_price'; } - if (! empty($conf->global->PRODUCT_MINIMUM_RECOMMENDED_PRICE) && $prodcustprice->price_min < $maxpricesupplier) + if (!empty($conf->global->PRODUCT_MINIMUM_RECOMMENDED_PRICE) && $prodcustprice->price_min < $maxpricesupplier) { $langs->load("errors"); setEventMessages($langs->trans("MinimumPriceLimit", price($maxpricesupplier, 0, '', 1, -1, -1, 'auto')), null, 'errors'); $error++; - $action='add_customer_price'; + $action = 'add_customer_price'; } - if (! $error) + if (!$error) { $result = $prodcustprice->create($user, 0, $update_child_soc); @@ -608,9 +608,9 @@ if (empty($reshook)) if (preg_match('/\((.*)\)/', $tva_tx_txt, $reg)) { $vat_src_code = $reg[1]; - $tva_tx = preg_replace('/\s*\(.*\)/', '', $tva_tx_txt); // Remove code into vatrate. + $tva_tx = preg_replace('/\s*\(.*\)/', '', $tva_tx_txt); // Remove code into vatrate. } - $tva_tx = price2num(preg_replace('/\*/', '', $tva_tx)); // keep remove all after the numbers and dot + $tva_tx = price2num(preg_replace('/\*/', '', $tva_tx)); // keep remove all after the numbers and dot $npr = preg_match('/\*/', $tva_tx_txt) ? 1 : 0; $localtax1 = 0; $localtax2 = 0; $localtax1_type = '0'; $localtax2_type = '0'; @@ -618,14 +618,14 @@ if (empty($reshook)) if (preg_match('/\((.*)\)/', $tva_tx_txt, $reg)) { // We look into database using code - $vatratecode=$reg[1]; + $vatratecode = $reg[1]; // Get record from code $sql = "SELECT t.rowid, t.code, t.recuperableonly, t.localtax1, t.localtax2, t.localtax1_type, t.localtax2_type"; - $sql.= " FROM ".MAIN_DB_PREFIX."c_tva as t, ".MAIN_DB_PREFIX."c_country as c"; - $sql.= " WHERE t.fk_pays = c.rowid AND c.code = '".$mysoc->country_code."'"; - $sql.= " AND t.taux = ".$tva_tx." AND t.active = 1"; - $sql.= " AND t.code ='".$vatratecode."'"; - $resql=$db->query($sql); + $sql .= " FROM ".MAIN_DB_PREFIX."c_tva as t, ".MAIN_DB_PREFIX."c_country as c"; + $sql .= " WHERE t.fk_pays = c.rowid AND c.code = '".$mysoc->country_code."'"; + $sql .= " AND t.taux = ".$tva_tx." AND t.active = 1"; + $sql .= " AND t.code ='".$vatratecode."'"; + $resql = $db->query($sql); if ($resql) { $obj = $db->fetch_object($resql); @@ -649,10 +649,10 @@ if (empty($reshook)) { setEventMessages($langs->trans("MinimumPriceLimit", price($maxpricesupplier, 0, '', 1, -1, -1, 'auto')), null, 'errors'); $error++; - $action='update_customer_price'; + $action = 'update_customer_price'; } - if ( ! $error) + if (!$error) { $result = $prodcustprice->update($user, 0, $update_child_soc); @@ -674,7 +674,7 @@ if (empty($reshook)) $form = new Form($db); -if (! empty($id) || ! empty($ref)) +if (!empty($id) || !empty($ref)) { // fetch updated prices $object->fetch($id, $ref); @@ -685,28 +685,28 @@ $helpurl = ''; $shortlabel = dol_trunc($object->label, 16); if (GETPOST("type") == '0' || ($object->type == Product::TYPE_PRODUCT)) { - $title = $langs->trans('Product')." ". $shortlabel ." - ".$langs->trans('SellingPrices'); - $helpurl='EN:Module_Products|FR:Module_Produits|ES:Módulo_Productos'; + $title = $langs->trans('Product')." ".$shortlabel." - ".$langs->trans('SellingPrices'); + $helpurl = 'EN:Module_Products|FR:Module_Produits|ES:Módulo_Productos'; } if (GETPOST("type") == '1' || ($object->type == Product::TYPE_SERVICE)) { - $title = $langs->trans('Service')." ". $shortlabel ." - ".$langs->trans('SellingPrices'); - $helpurl='EN:Module_Services_En|FR:Module_Services|ES:Módulo_Servicios'; + $title = $langs->trans('Service')." ".$shortlabel." - ".$langs->trans('SellingPrices'); + $helpurl = 'EN:Module_Services_En|FR:Module_Services|ES:Módulo_Servicios'; } llxHeader('', $title, $helpurl); $head = product_prepare_head($object); -$titre = $langs->trans("CardProduct" . $object->type); +$titre = $langs->trans("CardProduct".$object->type); $picto = ($object->type == Product::TYPE_SERVICE ? 'service' : 'product'); dol_fiche_head($head, 'price', $titre, -1, $picto); $linkback = ''.$langs->trans("BackToList").''; -$object->next_prev_filter=" fk_product_type = ".$object->type; +$object->next_prev_filter = " fk_product_type = ".$object->type; $shownav = 1; -if ($user->socid && ! in_array('product', explode(',', $conf->global->MAIN_MODULES_FOR_EXTERNAL))) $shownav=0; +if ($user->socid && !in_array('product', explode(',', $conf->global->MAIN_MODULES_FOR_EXTERNAL))) $shownav = 0; dol_banner_tab($object, 'ref', $linkback, $shownav, 'ref'); @@ -717,10 +717,10 @@ print '
    '; print '
    '; // Price per customer segment/level -if (! empty($conf->global->PRODUIT_MULTIPRICES) || ! empty($conf->global->PRODUIT_CUSTOMER_PRICES_BY_QTY_MULTIPRICES)) +if (!empty($conf->global->PRODUIT_MULTIPRICES) || !empty($conf->global->PRODUIT_CUSTOMER_PRICES_BY_QTY_MULTIPRICES)) { // Price and min price are variable (depends on level of company). - if (! empty($socid)) + if (!empty($socid)) { $soc = new Societe($db); $soc->id = $socid; @@ -737,47 +737,47 @@ if (! empty($conf->global->PRODUIT_MULTIPRICES) || ! empty($conf->global->PRODUI print price($object->multiprices[$soc->price_level]); } if ($object->multiprices_base_type[$soc->price_level]) { - print ' ' . $langs->trans($object->multiprices_base_type[$soc->price_level]); + print ' '.$langs->trans($object->multiprices_base_type[$soc->price_level]); } else { - print ' ' . $langs->trans($object->price_base_type); + print ' '.$langs->trans($object->price_base_type); } print ''; // Price min - print ''; - if (! empty($conf->global->PRODUIT_MULTIPRICES_USE_VAT_PER_LEVEL)) // using this option is a bug. kept for backward compatibility + if (!empty($conf->global->PRODUIT_MULTIPRICES_USE_VAT_PER_LEVEL)) // using this option is a bug. kept for backward compatibility { // TVA - print ''; } else { // TVA - print ''; - print ''; + print ''; + print ''; print ''; } else { // TVA - print ''; print ''; - for($i = 1; $i <= $conf->global->PRODUIT_MULTIPRICES_LIMIT; $i++) + for ($i = 1; $i <= $conf->global->PRODUIT_MULTIPRICES_LIMIT; $i++) { print ''; // Label of price print ''; if ($object->multiprices_base_type [$i] == 'TTC') { - print ''; // Price by quantity - if (! empty($conf->global->PRODUIT_CUSTOMER_PRICES_BY_QTY) || ! empty($conf->global->PRODUIT_CUSTOMER_PRICES_BY_QTY_MULTIPRICES)) // TODO Fix the form included into a tr instead of a td + if (!empty($conf->global->PRODUIT_CUSTOMER_PRICES_BY_QTY) || !empty($conf->global->PRODUIT_CUSTOMER_PRICES_BY_QTY_MULTIPRICES)) // TODO Fix the form included into a tr instead of a td { - print ''; } @@ -957,14 +957,14 @@ if (! empty($conf->global->PRODUIT_MULTIPRICES) || ! empty($conf->global->PRODUI else { // TVA - print ''; // Price - print ''; // Price minimum - print ''; // Price by quantity - if (! empty($conf->global->PRODUIT_CUSTOMER_PRICES_BY_QTY) || ! empty($conf->global->PRODUIT_CUSTOMER_PRICES_BY_QTY_MULTIPRICES)) // TODO Fix the form inside tr instead of td + if (!empty($conf->global->PRODUIT_CUSTOMER_PRICES_BY_QTY) || !empty($conf->global->PRODUIT_CUSTOMER_PRICES_BY_QTY_MULTIPRICES)) // TODO Fix the form inside tr instead of td { - print '
    ' . $langs->trans("MinPrice") . ''; + print '
    '.$langs->trans("MinPrice").''; if ($object->multiprices_base_type[$soc->price_level] == 'TTC') { - print price($object->multiprices_min_ttc[$soc->price_level]) . ' ' . $langs->trans($object->multiprices_base_type[$soc->price_level]); + print price($object->multiprices_min_ttc[$soc->price_level]).' '.$langs->trans($object->multiprices_base_type[$soc->price_level]); } else { - print price($object->multiprices_min[$soc->price_level]) . ' ' . $langs->trans(empty($object->multiprices_base_type[$soc->price_level])?'HT':$object->multiprices_base_type[$soc->price_level]); + print price($object->multiprices_min[$soc->price_level]).' '.$langs->trans(empty($object->multiprices_base_type[$soc->price_level]) ? 'HT' : $object->multiprices_base_type[$soc->price_level]); } print '
    ' . $langs->trans("DefaultTaxRate") . ''; + print '
    '.$langs->trans("DefaultTaxRate").''; - $positiverates=''; - if (price2num($object->multiprices_tva_tx[$soc->price_level])) $positiverates.=($positiverates?'/':'').price2num($object->multiprices_tva_tx[$soc->price_level]); - if (price2num($object->multiprices_localtax1_type[$soc->price_level])) $positiverates.=($positiverates?'/':'').price2num($object->multiprices_localtax1_tx[$soc->price_level]); - if (price2num($object->multiprices_localtax2_type[$soc->price_level])) $positiverates.=($positiverates?'/':'').price2num($object->multiprices_localtax2_tx[$soc->price_level]); - if (empty($positiverates)) $positiverates='0'; - echo vatrate($positiverates.($object->default_vat_code?' ('.$object->default_vat_code.')':''), '%', $object->tva_npr); + $positiverates = ''; + if (price2num($object->multiprices_tva_tx[$soc->price_level])) $positiverates .= ($positiverates ? '/' : '').price2num($object->multiprices_tva_tx[$soc->price_level]); + if (price2num($object->multiprices_localtax1_type[$soc->price_level])) $positiverates .= ($positiverates ? '/' : '').price2num($object->multiprices_localtax1_tx[$soc->price_level]); + if (price2num($object->multiprices_localtax2_type[$soc->price_level])) $positiverates .= ($positiverates ? '/' : '').price2num($object->multiprices_localtax2_tx[$soc->price_level]); + if (empty($positiverates)) $positiverates = '0'; + echo vatrate($positiverates.($object->default_vat_code ? ' ('.$object->default_vat_code.')' : ''), '%', $object->tva_npr); //print vatrate($object->multiprices_tva_tx[$soc->price_level], true); print '
    ' . $langs->trans("DefaultTaxRate") . ''; + print '
    '.$langs->trans("DefaultTaxRate").''; - $positiverates=''; - if (price2num($object->tva_tx)) $positiverates.=($positiverates?'/':'').price2num($object->tva_tx); - if (price2num($object->localtax1_type)) $positiverates.=($positiverates?'/':'').price2num($object->localtax1_tx); - if (price2num($object->localtax2_type)) $positiverates.=($positiverates?'/':'').price2num($object->localtax2_tx); - if (empty($positiverates)) $positiverates='0'; - echo vatrate($positiverates.($object->default_vat_code?' ('.$object->default_vat_code.')':''), '%', $object->tva_npr); + $positiverates = ''; + if (price2num($object->tva_tx)) $positiverates .= ($positiverates ? '/' : '').price2num($object->tva_tx); + if (price2num($object->localtax1_type)) $positiverates .= ($positiverates ? '/' : '').price2num($object->localtax1_tx); + if (price2num($object->localtax2_type)) $positiverates .= ($positiverates ? '/' : '').price2num($object->localtax2_tx); + if (empty($positiverates)) $positiverates = '0'; + echo vatrate($positiverates.($object->default_vat_code ? ' ('.$object->default_vat_code.')' : ''), '%', $object->tva_npr); /* if ($object->default_vat_code) { @@ -789,24 +789,24 @@ if (! empty($conf->global->PRODUIT_MULTIPRICES) || ! empty($conf->global->PRODUI } else { - if (! empty($conf->global->PRODUIT_MULTIPRICES_USE_VAT_PER_LEVEL)) // using this option is a bug. kept for backward compatibility + if (!empty($conf->global->PRODUIT_MULTIPRICES_USE_VAT_PER_LEVEL)) // using this option is a bug. kept for backward compatibility { // We show only vat for level 1 - print '
    ' . $langs->trans("DefaultTaxRate") . '' . vatrate($object->multiprices_tva_tx[1], true) . '
    '.$langs->trans("DefaultTaxRate").''.vatrate($object->multiprices_tva_tx[1], true).'
    ' . $langs->trans("DefaultTaxRate") . ''; + print '
    '.$langs->trans("DefaultTaxRate").''; - $positiverates=''; - if (price2num($object->tva_tx)) $positiverates.=($positiverates?'/':'').price2num($object->tva_tx); - if (price2num($object->localtax1_type)) $positiverates.=($positiverates?'/':'').price2num($object->localtax1_tx); - if (price2num($object->localtax2_type)) $positiverates.=($positiverates?'/':'').price2num($object->localtax2_tx); - if (empty($positiverates)) $positiverates='0'; - echo vatrate($positiverates.($object->default_vat_code?' ('.$object->default_vat_code.')':''), '%', $object->tva_npr); + $positiverates = ''; + if (price2num($object->tva_tx)) $positiverates .= ($positiverates ? '/' : '').price2num($object->tva_tx); + if (price2num($object->localtax1_type)) $positiverates .= ($positiverates ? '/' : '').price2num($object->localtax1_tx); + if (price2num($object->localtax2_type)) $positiverates .= ($positiverates ? '/' : '').price2num($object->localtax2_tx); + if (empty($positiverates)) $positiverates = '0'; + echo vatrate($positiverates.($object->default_vat_code ? ' ('.$object->default_vat_code.')' : ''), '%', $object->tva_npr); /* if ($object->default_vat_code) { @@ -828,35 +828,35 @@ if (! empty($conf->global->PRODUIT_MULTIPRICES) || ! empty($conf->global->PRODUI print ''.$langs->trans("MinPrice").'
    '; - $keyforlabel='PRODUIT_MULTIPRICES_LABEL'.$i; + $keyforlabel = 'PRODUIT_MULTIPRICES_LABEL'.$i; if (preg_match('/editlabelsellingprice/', $action)) { print ''; print ''; print ''; print ''; - print $langs->trans("SellingPrice") . ' ' . $i.' - '; + print $langs->trans("SellingPrice").' '.$i.' - '; print ''; print ' '; print ''; } else { - print $langs->trans("SellingPrice") . ' ' . $i; - if (! empty($conf->global->$keyforlabel)) print ' - '.$langs->trans($conf->global->$keyforlabel); + print $langs->trans("SellingPrice").' '.$i; + if (!empty($conf->global->$keyforlabel)) print ' - '.$langs->trans($conf->global->$keyforlabel); } print '' . price($object->multiprices_ttc[$i]); + print ''.price($object->multiprices_ttc[$i]); } else { - print '' . price($object->multiprices[$i]); + print ''.price($object->multiprices[$i]); } if ($object->multiprices_base_type[$i]) { @@ -867,60 +867,60 @@ if (! empty($conf->global->PRODUIT_MULTIPRICES) || ! empty($conf->global->PRODUI // Prix min print ''; - if (empty($object->multiprices_base_type[$i])) $object->multiprices_base_type[$i]="HT"; + if (empty($object->multiprices_base_type[$i])) $object->multiprices_base_type[$i] = "HT"; if ($object->multiprices_base_type[$i] == 'TTC') { - print price($object->multiprices_min_ttc[$i]) . ' ' . $langs->trans($object->multiprices_base_type[$i]); + print price($object->multiprices_min_ttc[$i]).' '.$langs->trans($object->multiprices_base_type[$i]); } else { - print price($object->multiprices_min[$i]) . ' ' . $langs->trans($object->multiprices_base_type[$i]); + print price($object->multiprices_min[$i]).' '.$langs->trans($object->multiprices_base_type[$i]); } print '
    ' . $langs->trans("PriceByQuantity") . ' ' . $i; - if (! empty($conf->global->$keyforlabel)) print ' - '.$langs->trans($conf->global->$keyforlabel); + print '
    '.$langs->trans("PriceByQuantity").' '.$i; + if (!empty($conf->global->$keyforlabel)) print ' - '.$langs->trans($conf->global->$keyforlabel); print ''; if ($object->prices_by_qty[$i] == 1) { print ''; print ''; - print ''; - print ''; - print ''; - print ''; + print ''; + print ''; + print ''; + print ''; print ''; print ''; foreach ($object->prices_by_qty_list[$i] as $ii => $prices) { if ($action == 'edit_price_by_qty' && $rowid == $prices['rowid'] && ($user->rights->produit->creer || $user->rights->service->creer)) { - print ''; + print ''; print ''; - print ''; - print ''; - print ''; - print ''; - print ''; - print ''; - print ''; + print ''; + print ''; + print ''; + print ''; + print ''; + print ''; + print ''; print ''; print ''; } else { - print ''; - print ''; - print ''; - print ''; - print ''; + print ''; + print ''; + print ''; + print ''; + print ''; print ''; + print ''; // id in product_price + print ''; // id in product_price + print ''; print ''; - print ''; + print ''; print ''; print ''; - print ''; + print ''; print ''; print ''; } print '
    ' . $langs->trans("PriceByQuantityRange") . ' ' . $i . '' . $langs->trans("HT") . '' . $langs->trans("UnitPrice") . '' . $langs->trans("Discount") . ''.$langs->trans("PriceByQuantityRange").' '.$i.''.$langs->trans("HT").''.$langs->trans("UnitPrice").''.$langs->trans("Discount").' 
     ' . $object->price_base_type . ' %
     '.$object->price_base_type.' %
    ' . $prices['quantity'] . '' . price($prices['price']) . '' . price($prices['unitprice']) . '' . price($prices['remise_percent']) . ' %
    '.$prices['quantity'].''.price($prices['price']).''.price($prices['unitprice']).''.price($prices['remise_percent']).' %'; if (($user->rights->produit->creer || $user->rights->service->creer)) { - print ''; - print img_edit() . ''; - print ''; - print img_delete() . ''; + print ''; + print img_edit().''; + print ''; + print img_delete().''; } else { print ' '; } @@ -929,25 +929,25 @@ if (! empty($conf->global->PRODUIT_MULTIPRICES) || ! empty($conf->global->PRODUI } } if ($action != 'edit_price_by_qty' && ($user->rights->produit->creer || $user->rights->service->creer)) { - print '
    '; + print ''; print ''; - print ''; // id in product_price - print ''; // id in product_price - print '
     ' . $object->price_base_type . ' '.$object->price_base_type.'  %
    '; - print '(' . $langs->trans("DisablePriceByQty").')'; + print '('.$langs->trans("DisablePriceByQty").')'; } else { print $langs->trans("No"); - print '  (' . $langs->trans("Activate") . ')'; + print '  ('.$langs->trans("Activate").')'; } print '
    ' . $langs->trans("DefaultTaxRate") . ''; + print '
    '.$langs->trans("DefaultTaxRate").''; - $positiverates=''; - if (price2num($object->tva_tx)) $positiverates.=($positiverates?'/':'').price2num($object->tva_tx); - if (price2num($object->localtax1_type)) $positiverates.=($positiverates?'/':'').price2num($object->localtax1_tx); - if (price2num($object->localtax2_type)) $positiverates.=($positiverates?'/':'').price2num($object->localtax2_tx); - if (empty($positiverates)) $positiverates='0'; - echo vatrate($positiverates.($object->default_vat_code?' ('.$object->default_vat_code.')':''), '%', $object->tva_npr); + $positiverates = ''; + if (price2num($object->tva_tx)) $positiverates .= ($positiverates ? '/' : '').price2num($object->tva_tx); + if (price2num($object->localtax1_type)) $positiverates .= ($positiverates ? '/' : '').price2num($object->localtax1_tx); + if (price2num($object->localtax2_type)) $positiverates .= ($positiverates ? '/' : '').price2num($object->localtax2_tx); + if (empty($positiverates)) $positiverates = '0'; + echo vatrate($positiverates.($object->default_vat_code ? ' ('.$object->default_vat_code.')' : ''), '%', $object->tva_npr); /* if ($object->default_vat_code) { @@ -974,33 +974,33 @@ else print '
    ' . $langs->trans("SellingPrice") . ''; + print '
    '.$langs->trans("SellingPrice").''; if ($object->price_base_type == 'TTC') { - print price($object->price_ttc) . ' ' . $langs->trans($object->price_base_type); + print price($object->price_ttc).' '.$langs->trans($object->price_base_type); } else { - print price($object->price) . ' ' . $langs->trans($object->price_base_type); + print price($object->price).' '.$langs->trans($object->price_base_type); } print '
    ' . $langs->trans("MinPrice") . ''; + print '
    '.$langs->trans("MinPrice").''; if ($object->price_base_type == 'TTC') { - print price($object->price_min_ttc) . ' ' . $langs->trans($object->price_base_type); + print price($object->price_min_ttc).' '.$langs->trans($object->price_base_type); } else { - print price($object->price_min) . ' ' . $langs->trans($object->price_base_type); + print price($object->price_min).' '.$langs->trans($object->price_base_type); } print '
    ' . $langs->trans("PriceByQuantity"); + print '
    '.$langs->trans("PriceByQuantity"); if ($object->prices_by_qty[0] == 0) { - print '  (' . $langs->trans("Activate").')'; + print '  ('.$langs->trans("Activate").')'; } else { - print '  (' . $langs->trans("DisablePriceByQty").')'; + print '  ('.$langs->trans("DisablePriceByQty").')'; } print ''; @@ -1009,21 +1009,21 @@ else print ''; print ''; //print ''; - print ''; - print ''; + print ''; + print ''; print ''; - print ''; - print ''; + print ''; + print ''; print ''; print ''; if ($action != 'edit_price_by_qty') { - print ''; // FIXME a form into a table is not allowed + print ''; // FIXME a form into a table is not allowed print ''; - print ''; // id in product_price - print ''; // id in product_price_by_qty + print ''; // id in product_price + print ''; // id in product_price_by_qty - print ''; + print ''; print ''; print ''; print ''; print ''; print ''; - print ''; + print ''; print ''; print ''; @@ -1040,39 +1040,39 @@ else { if ($action == 'edit_price_by_qty' && $rowid == $prices['rowid'] && ($user->rights->produit->creer || $user->rights->service->creer)) { - print ''; + print ''; print ''; - print ''; // id in product_price - print ''; // id in product_price_by_qty - print ''; - print ''; - print ''; + print ''; // id in product_price + print ''; // id in product_price_by_qty + print ''; + print ''; + print ''; print ''; print ''; - print ''; - print ''; + print ''; + print ''; print ''; print ''; } else { - print ''; - print ''; - print ''; + print ''; + print ''; + print ''; print ''; - print ''; - print ''; + print ''; + print ''; print '
    ' . $langs->trans("PriceByQuantityRange") . '' . $langs->trans("Quantity") . '' . $langs->trans("Price") . ''.$langs->trans("Quantity").''.$langs->trans("Price").'' . $langs->trans("UnitPrice") . '' . $langs->trans("Discount") . ''.$langs->trans("UnitPrice").''.$langs->trans("Discount").' 
    '; @@ -1031,7 +1031,7 @@ else print '  %
    '; //print $object->price_base_type; print $prices['price_base_type']; print '  % %
    ' . $prices['quantity'] . '' . price($prices['price']) . '
    '.$prices['quantity'].''.price($prices['price']).''; //print $object->price_base_type; print $prices['price_base_type']; print '' . price($prices['unitprice']) . '' . price($prices['remise_percent']) . ' %'.price($prices['unitprice']).''.price($prices['remise_percent']).' %'; if (($user->rights->produit->creer || $user->rights->service->creer)) { - print ''; - print img_edit() . ''; - print ''; - print img_delete() . ''; + print ''; + print img_edit().''; + print ''; + print img_delete().''; } else { print ' '; } @@ -1104,10 +1104,10 @@ dol_fiche_end(); /* */ /* ************************************************************************** */ -if (! $action || $action == 'delete' || $action == 'showlog_customer_price' || $action == 'showlog_default_price' || $action == 'add_customer_price' +if (!$action || $action == 'delete' || $action == 'showlog_customer_price' || $action == 'showlog_default_price' || $action == 'add_customer_price' || $action == 'activate_price_by_qty' || $action == 'disable_price_by_qty') { - print "\n" . '
    ' . "\n"; + print "\n".'
    '."\n"; if ($object->isVariant()) { if ($user->rights->produit->creer || $user->rights->service->creer) { @@ -1116,23 +1116,23 @@ if (! $action || $action == 'delete' || $action == 'showlog_customer_price' || $ } else { if (empty($conf->global->PRODUIT_MULTIPRICES) && empty($conf->global->PRODUIT_CUSTOMER_PRICES_BY_QTY_MULTIPRICES)) { if ($user->rights->produit->creer || $user->rights->service->creer) { - print ''; + print ''; } } if (!empty($conf->global->PRODUIT_CUSTOMER_PRICES)) { if ($user->rights->produit->creer || $user->rights->service->creer) { - print ''; + print ''; } } if (!empty($conf->global->PRODUIT_MULTIPRICES) || !empty($conf->global->PRODUIT_CUSTOMER_PRICES_BY_QTY_MULTIPRICES)) { if ($user->rights->produit->creer || $user->rights->service->creer) { - print ''; + print ''; } if ($user->rights->produit->creer || $user->rights->service->creer) { - print ''; + print ''; } } } @@ -1150,17 +1150,17 @@ if ($action == 'edit_vat' && ($user->rights->produit->creer || $user->rights->se { print load_fiche_titre($langs->trans("UpdateVAT"), ''); - print '
    '; - print ''; + print ''; + print ''; print ''; - print ''; + print ''; dol_fiche_head(''); - print ''; + print '
    '; // VAT - print ''; @@ -1169,9 +1169,9 @@ if ($action == 'edit_vat' && ($user->rights->produit->creer || $user->rights->se dol_fiche_end(); print '
    '; - print ''; + print ''; print '     '; - print ''; + print ''; print '
    '; print '

    '; @@ -1184,17 +1184,17 @@ if ($action == 'edit_price' && $object->getRights()->creer) if (empty($conf->global->PRODUIT_MULTIPRICES) && empty($conf->global->PRODUIT_CUSTOMER_PRICES_BY_QTY_MULTIPRICES)) { print ''."\n"; - print ''; - print ''; + print ''; + print ''; print ''; - print ''; + print ''; dol_fiche_head(''); - print '
    ' . $langs->trans("DefaultTaxRate") . ''; + print '
    '.$langs->trans("DefaultTaxRate").''; print $form->load_tva("tva_tx", $object->default_vat_code ? $object->tva_tx.' ('.$object->default_vat_code.')' : $object->tva_tx, $mysoc, '', $object->id, $object->tva_npr, $object->type, false, 1); print '
    '; + print '
    '; // VAT - print ''; @@ -1208,7 +1208,7 @@ if ($action == 'edit_price' && $object->getRights()->creer) print ''; // Only show price mode and expression selector if module is enabled - if (! empty($conf->dynamicprices->enabled)) { + if (!empty($conf->dynamicprices->enabled)) { // Price mode selector print ''; @@ -1263,28 +1263,28 @@ if ($action == 'edit_price' && $object->getRights()->creer) print $form->textwithpicto($text, $langs->trans("PrecisionUnitIsLimitedToXDecimals", $conf->global->MAIN_MAX_DECIMALS_UNIT), 1, 1); print ''; } print ''; print ''; - $parameters=array('colspan' => 2); - $reshook=$hookmanager->executeHooks('formObjectOptions', $parameters, $object, $action); // Note that $action and $object may have been modified by hook + $parameters = array(); + $reshook = $hookmanager->executeHooks('formObjectOptions', $parameters, $object, $action); // Note that $action and $object may have been modified by hook print '
    ' . $langs->trans("DefaultTaxRate") . ''; + print '
    '.$langs->trans("DefaultTaxRate").''; print $form->load_tva("tva_tx", $object->default_vat_code ? $object->tva_tx.' ('.$object->default_vat_code.')' : $object->tva_tx, $mysoc, '', $object->id, $object->tva_npr, $object->type, false, 1); print '
    '.$langs->trans("PriceMode").''; $price_expression = new PriceExpression($db); @@ -1251,9 +1251,9 @@ if ($action == 'edit_price' && $object->getRights()->creer) print $form->textwithpicto($text, $langs->trans("PrecisionUnitIsLimitedToXDecimals", $conf->global->MAIN_MAX_DECIMALS_UNIT), 1, 1); print ''; if ($object->price_base_type == 'TTC') { - print ''; + print ''; } else { - print ''; + print ''; } print '
    '; if ($object->price_base_type == 'TTC') { - print ''; + print ''; } else { - print ''; + print ''; } - if (! empty($conf->global->PRODUCT_MINIMUM_RECOMMENDED_PRICE)) + if (!empty($conf->global->PRODUCT_MINIMUM_RECOMMENDED_PRICE)) { print '   '.$langs->trans("MinimumRecommendedPrice", price($maxpricesupplier, 0, '', 1, -1, -1, 'auto')).' '.img_warning().'
    '; dol_fiche_end(); print '
    '; - print ''; + print ''; print '     '; - print ''; + print ''; print '
    '; print '
    '; @@ -1316,15 +1316,15 @@ if ($action == 'edit_price' && $object->getRights()->creer) id . '" method="POST">'; - print ''; + print '
    '; + print ''; print ''; - print ''; + print ''; //dol_fiche_head('', '', '', -1); - if ((! empty($conf->global->PRODUIT_MULTIPRICES) || ! empty($conf->global->PRODUIT_CUSTOMER_PRICES_BY_QTY_MULTIPRICES)) && ! empty($conf->global->PRODUIT_MULTIPRICES_ALLOW_AUTOCALC_PRICELEVEL)) { - print $langs->trans('UseMultipriceRules'). ' price_autogen ? 'checked' : '').'>

    '; + if ((!empty($conf->global->PRODUIT_MULTIPRICES) || !empty($conf->global->PRODUIT_CUSTOMER_PRICES_BY_QTY_MULTIPRICES)) && !empty($conf->global->PRODUIT_MULTIPRICES_ALLOW_AUTOCALC_PRICELEVEL)) { + print $langs->trans('UseMultipriceRules').' price_autogen ? 'checked' : '').'>

    '; } print ''; @@ -1346,48 +1346,48 @@ if ($action == 'edit_price' && $object->getRights()->creer) print ''; - for ($i = 1; $i <= $conf->global->PRODUIT_MULTIPRICES_LIMIT; $i ++) + for ($i = 1; $i <= $conf->global->PRODUIT_MULTIPRICES_LIMIT; $i++) { print ''; print ''; // VAT if (empty($conf->global->PRODUIT_MULTIPRICES_USE_VAT_PER_LEVEL)) { print ''; } else { // This option is kept for backward compatibility but has no sense print ''; } // Selling price print ''; // Min price print ''; } @@ -1403,9 +1403,9 @@ if ($action == 'edit_price' && $object->getRights()->creer) //dol_fiche_end(); print '
    '; - print ''; + print ''; print '   '; - print '
    '; + print ''; print ''; } } @@ -1413,17 +1413,17 @@ if ($action == 'edit_price' && $object->getRights()->creer) // List of price changes - log historic (ordered by descending date) -if ((empty($conf->global->PRODUIT_CUSTOMER_PRICES) || $action=='showlog_default_price') && ! in_array($action, array('edit_price','edit_vat'))) +if ((empty($conf->global->PRODUIT_CUSTOMER_PRICES) || $action == 'showlog_default_price') && !in_array($action, array('edit_price', 'edit_vat'))) { $sql = "SELECT p.rowid, p.price, p.price_ttc, p.price_base_type, p.tva_tx, p.default_vat_code, p.recuperableonly, p.localtax1_tx, p.localtax1_type, p.localtax2_tx, p.localtax2_type,"; $sql .= " p.price_level, p.price_min, p.price_min_ttc,p.price_by_qty,"; $sql .= " p.date_price as dp, p.fk_price_expression, u.rowid as user_id, u.login"; - $sql .= " FROM " . MAIN_DB_PREFIX . "product_price as p,"; - $sql .= " " . MAIN_DB_PREFIX . "user as u"; - $sql .= " WHERE fk_product = " . $object->id; - $sql .= " AND p.entity IN (" . getEntity('productprice') . ")"; + $sql .= " FROM ".MAIN_DB_PREFIX."product_price as p,"; + $sql .= " ".MAIN_DB_PREFIX."user as u"; + $sql .= " WHERE fk_product = ".$object->id; + $sql .= " AND p.entity IN (".getEntity('productprice').")"; $sql .= " AND p.fk_user_author = u.rowid"; - if (! empty($socid) && ! empty($conf->global->PRODUIT_MULTIPRICES)) $sql .= " AND p.price_level = " . $soc->price_level; + if (!empty($socid) && !empty($conf->global->PRODUIT_MULTIPRICES)) $sql .= " AND p.price_level = ".$soc->price_level; $sql .= " ORDER BY p.date_price DESC, p.rowid DESC, p.price_level ASC"; // $sql .= $db->plimit(); @@ -1434,15 +1434,15 @@ if ((empty($conf->global->PRODUIT_CUSTOMER_PRICES) || $action=='showlog_default_ $num = $db->num_rows($result); - if (! $num) + if (!$num) { $db->free($result); // Il doit au moins y avoir la ligne de prix initial. // On l'ajoute donc pour remettre a niveau (pb vieilles versions) //$object->updatePrice($object->price, $object->price_base_type, $user, $object->tva_tx, $object->price_min); - if (! empty($conf->global->PRODUIT_MULTIPRICES)) { - $object->updatePrice($object->multiprices[1], $object->multiprices_base_type[1], $user, (empty($object->multiprices_tva_tx[1])?0:$object->multiprices_tva_tx[1]), $object->multiprices_min[1], 1); + if (!empty($conf->global->PRODUIT_MULTIPRICES)) { + $object->updatePrice($object->multiprices[1], $object->multiprices_base_type[1], $user, (empty($object->multiprices_tva_tx[1]) ? 0 : $object->multiprices_tva_tx[1]), $object->multiprices_min[1], 1); } else { $object->updatePrice($object->price, $object->price_base_type, $user, $object->tva_tx, $object->price_min); } @@ -1455,42 +1455,42 @@ if ((empty($conf->global->PRODUIT_CUSTOMER_PRICES) || $action=='showlog_default_ { // Default prices or // Log of previous customer prices - $backbutton='' . $langs->trans("Back") . ''; + $backbutton = ''.$langs->trans("Back").''; - if (! empty($conf->global->PRODUIT_CUSTOMER_PRICES)) print_barre_liste($langs->trans("DefaultPrice"), 0, $_SERVER["PHP_SELF"], '', '', '', $backbutton, 0, $num, 'title_accountancy.png'); + if (!empty($conf->global->PRODUIT_CUSTOMER_PRICES)) print_barre_liste($langs->trans("DefaultPrice"), 0, $_SERVER["PHP_SELF"], '', '', '', $backbutton, 0, $num, 'title_accountancy.png'); else print_barre_liste($langs->trans("PriceByCustomerLog"), 0, $_SERVER["PHP_SELF"], '', '', '', '', 0, $num, 'title_accountancy.png'); //if (! empty($conf->global->PRODUIT_CUSTOMER_PRICES)) print_barre_liste($langs->trans("DefaultPrice"),'','','','','',$backbutton, 0, 0, 'title_accountancy.png'); //else print_barre_liste($langs->trans("PriceByCustomerLog"),'','','','','','', 0, 0, 'title_accountancy.png'); print '
    '; - print '
    '; - print $form->textwithpicto($langs->trans('SellingPrice') . ' ' . $i, $langs->trans("PrecisionUnitIsLimitedToXDecimals", $conf->global->MAIN_MAX_DECIMALS_UNIT), 1, 1); + print $form->textwithpicto($langs->trans('SellingPrice').' '.$i, $langs->trans("PrecisionUnitIsLimitedToXDecimals", $conf->global->MAIN_MAX_DECIMALS_UNIT), 1, 1); print ''; - print ''; - print ''; - print ''; - print ''; - print ''; - print ''; + print ''; + print ''; + print ''; + print ''; + print ''; + print ''; print ''; - print $form->load_tva("tva_tx[" . $i.']', $object->multiprices_tva_tx[$i], $mysoc, '', $object->id, false, $object->type, false, 1); + print $form->load_tva("tva_tx[".$i.']', $object->multiprices_tva_tx[$i], $mysoc, '', $object->id, false, $object->type, false, 1); print ''; if ($object->multiprices_base_type [$i] == 'TTC') { - print ''; + print ''; } else { - print ''; + print ''; } - print ' '.$form->selectPriceBaseType($object->multiprices_base_type [$i], "multiprices_base_type[" . $i."]"); + print ' '.$form->selectPriceBaseType($object->multiprices_base_type [$i], "multiprices_base_type[".$i."]"); print ''; if ($object->multiprices_base_type [$i] == 'TTC') { - print ''; + print ''; } else { - print ''; + print ''; } - if ( !empty($conf->global->PRODUCT_MINIMUM_RECOMMENDED_PRICE)) + if (!empty($conf->global->PRODUCT_MINIMUM_RECOMMENDED_PRICE)) { print ''.$langs->trans("MinimumRecommendedPrice", price($maxpricesupplier, 0, '', 1, -1, -1, 'auto')).' '.img_warning().'
    '; + print '
    '; print ''; - print ''; + print ''; - if (! empty($conf->global->PRODUIT_MULTIPRICES) || ! empty($conf->global->PRODUIT_CUSTOMER_PRICES_BY_QTY_MULTIPRICES)) { - print ''; + if (!empty($conf->global->PRODUIT_MULTIPRICES) || !empty($conf->global->PRODUIT_CUSTOMER_PRICES_BY_QTY_MULTIPRICES)) { + print ''; } - if (! empty($conf->global->PRODUIT_CUSTOMER_PRICES_BY_QTY) || ! empty($conf->global->PRODUIT_CUSTOMER_PRICES_BY_QTY_MULTIPRICES)) { - print ''; + if (!empty($conf->global->PRODUIT_CUSTOMER_PRICES_BY_QTY) || !empty($conf->global->PRODUIT_CUSTOMER_PRICES_BY_QTY_MULTIPRICES)) { + print ''; } - print ''; + print ''; print $conf->global->PRODUIT_MULTIPRICES_USE_VAT_PER_LEVEL; - if (empty($conf->global->PRODUIT_MULTIPRICES) && empty($conf->global->PRODUIT_CUSTOMER_PRICES_BY_QTY_MULTIPRICES)) print ''; - print ''; - print ''; - if (! empty($conf->dynamicprices->enabled)) { - print ''; + if (empty($conf->global->PRODUIT_MULTIPRICES) && empty($conf->global->PRODUIT_CUSTOMER_PRICES_BY_QTY_MULTIPRICES)) print ''; + print ''; + print ''; + if (!empty($conf->dynamicprices->enabled)) { + print ''; } - print ''; - print ''; - print ''; + print ''; + print ''; + print ''; if ($user->rights->produit->supprimer) print ''; print ''; - $notfirstlineforlevel=array(); + $notfirstlineforlevel = array(); $i = 0; while ($i < $num) @@ -1499,17 +1499,17 @@ if ((empty($conf->global->PRODUIT_CUSTOMER_PRICES) || $action=='showlog_default_ print ''; // Date - print ""; + print ""; // Price level - if (! empty($conf->global->PRODUIT_MULTIPRICES) || ! empty($conf->global->PRODUIT_CUSTOMER_PRICES_BY_QTY_MULTIPRICES)) { - print '"; + if (!empty($conf->global->PRODUIT_MULTIPRICES) || !empty($conf->global->PRODUIT_CUSTOMER_PRICES_BY_QTY_MULTIPRICES)) { + print '"; } // Price by quantity - if (! empty($conf->global->PRODUIT_CUSTOMER_PRICES_BY_QTY) || ! empty($conf->global->PRODUIT_CUSTOMER_PRICES_BY_QTY_MULTIPRICES)) + if (!empty($conf->global->PRODUIT_CUSTOMER_PRICES_BY_QTY) || !empty($conf->global->PRODUIT_CUSTOMER_PRICES_BY_QTY_MULTIPRICES)) { $type = ($objp->price_by_qty == 1) ? 'PriceByQuantity' : 'Standard'; - print '"; + print '"; } print ''; print ''; - print '"; + print '"; } else { @@ -1562,7 +1562,7 @@ if ((empty($conf->global->PRODUIT_CUSTOMER_PRICES) || $action=='showlog_default_ print price($objp->price_ttc); } print ""; - if (! empty($conf->dynamicprices->enabled)) { //Only if module is enabled + if (!empty($conf->dynamicprices->enabled)) { //Only if module is enabled print ''; } } @@ -1580,23 +1580,23 @@ if ((empty($conf->global->PRODUIT_CUSTOMER_PRICES) || $action=='showlog_default_ print ''; // User - print ''; + print ''; // Action if ($user->rights->produit->supprimer) { - $candelete=0; - if (! empty($conf->global->PRODUIT_MULTIPRICES) || ! empty($conf->global->PRODUIT_CUSTOMER_PRICES_BY_QTY_MULTIPRICES)) + $candelete = 0; + if (!empty($conf->global->PRODUIT_MULTIPRICES) || !empty($conf->global->PRODUIT_CUSTOMER_PRICES_BY_QTY_MULTIPRICES)) { - if (empty($notfirstlineforlevel[$objp->price_level])) $notfirstlineforlevel[$objp->price_level]=1; - else $candelete=1; + if (empty($notfirstlineforlevel[$objp->price_level])) $notfirstlineforlevel[$objp->price_level] = 1; + else $candelete = 1; } - elseif ($i > 0) $candelete=1; + elseif ($i > 0) $candelete = 1; print '
    ' . $langs->trans("AppliedPricesFrom") . ''.$langs->trans("AppliedPricesFrom").'' . $langs->trans("PriceLevel") . ''.$langs->trans("PriceLevel").'' . $langs->trans("Type") . ''.$langs->trans("Type").'' . $langs->trans("PriceBase") . ''.$langs->trans("PriceBase").'' . $langs->trans("DefaultTaxRate") . '' . $langs->trans("HT") . '' . $langs->trans("TTC") . '' . $langs->trans("PriceExpressionSelected") . ''.$langs->trans("DefaultTaxRate").''.$langs->trans("HT").''.$langs->trans("TTC").''.$langs->trans("PriceExpressionSelected").'' . $langs->trans("MinPrice") . ' ' . $langs->trans("HT") . '' . $langs->trans("MinPrice") . ' ' . $langs->trans("TTC") . '' . $langs->trans("ChangedBy") . ''.$langs->trans("MinPrice").' '.$langs->trans("HT").''.$langs->trans("MinPrice").' '.$langs->trans("TTC").''.$langs->trans("ChangedBy").' 
    " . dol_print_date($db->jdate($objp->dp), "dayhour") . "".dol_print_date($db->jdate($objp->dp), "dayhour")."' . $objp->price_level . "'.$objp->price_level."' . $langs->trans($type) . "'.$langs->trans($type)."'; @@ -1523,12 +1523,12 @@ if ((empty($conf->global->PRODUIT_CUSTOMER_PRICES) || $action=='showlog_default_ print ''; if (empty($objp->price_by_qty)) { - $positiverates=''; - if (price2num($objp->tva_tx)) $positiverates.=($positiverates?'/':'').price2num($objp->tva_tx); - if (price2num($objp->localtax1_type)) $positiverates.=($positiverates?'/':'').price2num($objp->localtax1_tx); - if (price2num($objp->localtax2_type)) $positiverates.=($positiverates?'/':'').price2num($objp->localtax2_tx); - if (empty($positiverates)) $positiverates='0'; - echo vatrate($positiverates.($objp->default_vat_code?' ('.$objp->default_vat_code.')':''), '%', $objp->tva_npr); + $positiverates = ''; + if (price2num($objp->tva_tx)) $positiverates .= ($positiverates ? '/' : '').price2num($objp->tva_tx); + if (price2num($objp->localtax1_type)) $positiverates .= ($positiverates ? '/' : '').price2num($objp->localtax1_tx); + if (price2num($objp->localtax2_type)) $positiverates .= ($positiverates ? '/' : '').price2num($objp->localtax2_tx); + if (empty($positiverates)) $positiverates = '0'; + echo vatrate($positiverates.($objp->default_vat_code ? ' ('.$objp->default_vat_code.')' : ''), '%', $objp->tva_npr); /* if ($objp->default_vat_code) { @@ -1541,14 +1541,14 @@ if ((empty($conf->global->PRODUIT_CUSTOMER_PRICES) || $action=='showlog_default_ } // Price - if (! empty($objp->fk_price_expression) && ! empty($conf->dynamicprices->enabled)) + if (!empty($objp->fk_price_expression) && !empty($conf->dynamicprices->enabled)) { $price_expression = new PriceExpression($db); $res = $price_expression->fetch($objp->fk_price_expression); $title = $price_expression->title; print '' . $title . "'.$title."' . img_object($langs->trans("ShowUser"), 'user') . ' ' . $objp->login . ''.img_object($langs->trans("ShowUser"), 'user').' '.$objp->login.''; if ($candelete) { - print 'id . '&lineid=' . $objp->rowid . '">'; + print 'id.'&lineid='.$objp->rowid.'">'; print img_delete(); print ''; } else @@ -1622,26 +1622,26 @@ if ((empty($conf->global->PRODUIT_CUSTOMER_PRICES) || $action=='showlog_default_ // Add area to show/add/edit a price for a dedicated customer -if (! empty($conf->global->PRODUIT_CUSTOMER_PRICES)) +if (!empty($conf->global->PRODUIT_CUSTOMER_PRICES)) { $prodcustprice = new Productcustomerprice($db); $sortfield = GETPOST("sortfield", 'alpha'); $sortorder = GETPOST("sortorder", 'alpha'); - $page = (GETPOST("page", 'int')?GETPOST("page", 'int'):0); + $page = (GETPOST("page", 'int') ?GETPOST("page", 'int') : 0); if (empty($page) || $page == -1) { $page = 0; } // If $page is not defined, or '' or -1 $offset = $conf->liste_limit * $page; $pageprev = $page - 1; $pagenext = $page + 1; - if (! $sortorder) + if (!$sortorder) $sortorder = "ASC"; - if (! $sortfield) + if (!$sortfield) $sortfield = "soc.nom"; // Build filter to diplay only concerned lines $filter = array('t.fk_product' => $object->id); - if (! empty($search_soc)) { + if (!empty($search_soc)) { $filter['soc.nom'] = $search_soc; } @@ -1652,23 +1652,23 @@ if (! empty($conf->global->PRODUIT_CUSTOMER_PRICES)) print load_fiche_titre($langs->trans('PriceByCustomer')); - print '
    '; - print ''; + print ''; + print ''; print ''; - print ''; + print ''; dol_fiche_head(); - print ''; + print '
    '; print ''; - print ''; + print ''; print ''; print ''; // VAT - print ''; @@ -1687,9 +1687,9 @@ if (! empty($conf->global->PRODUIT_CUSTOMER_PRICES)) print $form->textwithpicto($text, $langs->trans("PrecisionUnitIsLimitedToXDecimals", $conf->global->MAIN_MAX_DECIMALS_UNIT), 1, 1); print ''; @@ -1698,11 +1698,11 @@ if (! empty($conf->global->PRODUIT_CUSTOMER_PRICES)) $text = $langs->trans('MinPrice'); print $form->textwithpicto($text, $langs->trans("PrecisionUnitIsLimitedToXDecimals", $conf->global->MAIN_MAX_DECIMALS_UNIT), 1, 1); if ($object->price_base_type == 'TTC') { - print ''; } @@ -1720,9 +1720,9 @@ if (! empty($conf->global->PRODUIT_CUSTOMER_PRICES)) print $langs->trans('ForceUpdateChildPriceSoc'); print ''; - print ''; + print ''; print '     '; - print ''; + print ''; print ''; print ''; @@ -1739,23 +1739,23 @@ if (! empty($conf->global->PRODUIT_CUSTOMER_PRICES)) setEventMessages($prodcustprice->error, $prodcustprice->errors, 'errors'); } - print ''; - print ''; + print ''; + print ''; print ''; - print ''; + print ''; dol_fiche_head(); - print '
    ' . $langs->trans('ThirdParty') . ''.$langs->trans('ThirdParty').''; print $form->select_company('', 'socid', 's.client IN (1,2,3)', 'SelectThirdParty', 0, 0, array(), 0, 'minwidth300'); print '
    ' . $langs->trans("DefaultTaxRate") . ''; + print '
    '.$langs->trans("DefaultTaxRate").''; print $form->load_tva("tva_tx", $object->default_vat_code ? $object->tva_tx.' ('.$object->default_vat_code.')' : $object->tva_tx, $mysoc, '', $object->id, $object->tva_npr, $object->type, false, 1); print '
    '; if ($object->price_base_type == 'TTC') { - print ''; + print ''; } else { - print ''; + print ''; } print '
    '; + print ''; } else { - print ''; + print ''; } - if ( !empty($conf->global->PRODUCT_MINIMUM_RECOMMENDED_PRICE)) + if (!empty($conf->global->PRODUCT_MINIMUM_RECOMMENDED_PRICE)) { print ''.$langs->trans("MinimumRecommendedPrice", price($maxpricesupplier, 0, '', 1, -1, -1, 'auto')).' '.img_warning().'
    '; + print '
    '; print ''; - print ''; + print ''; $staticsoc = new Societe($db); $staticsoc->fetch($prodcustprice->fk_soc); - print ""; + print ""; print ''; // VAT - print ''; @@ -1774,9 +1774,9 @@ if (! empty($conf->global->PRODUIT_CUSTOMER_PRICES)) print $form->textwithpicto($text, $langs->trans("PrecisionUnitIsLimitedToXDecimals", $conf->global->MAIN_MAX_DECIMALS_UNIT), 1, 1); print ''; @@ -1786,12 +1786,12 @@ if (! empty($conf->global->PRODUIT_CUSTOMER_PRICES)) print $form->textwithpicto($text, $langs->trans("PrecisionUnitIsLimitedToXDecimals", $conf->global->MAIN_MAX_DECIMALS_UNIT), 1, 1); print ''; - if ( !empty($conf->global->PRODUCT_MINIMUM_RECOMMENDED_PRICE)) + if (!empty($conf->global->PRODUCT_MINIMUM_RECOMMENDED_PRICE)) { print ''; } @@ -1814,9 +1814,9 @@ if (! empty($conf->global->PRODUIT_CUSTOMER_PRICES)) print $langs->trans('ForceUpdateChildPriceSoc'); print ""; - print ''; + print ''; print '     '; - print ''; + print ''; print ''; print '
    '; @@ -1826,7 +1826,7 @@ if (! empty($conf->global->PRODUIT_CUSTOMER_PRICES)) // List of all log of prices by customers print ''."\n"; - $filter = array('t.fk_product' => $object->id,'t.fk_soc' => GETPOST('socid', 'int')); + $filter = array('t.fk_product' => $object->id, 't.fk_soc' => GETPOST('socid', 'int')); // Count total nb of records $nbtotalofrecords = ''; @@ -1839,43 +1839,43 @@ if (! empty($conf->global->PRODUIT_CUSTOMER_PRICES)) setEventMessages($prodcustprice->error, $prodcustprice->errors, 'errors'); } - $option = '&socid=' . GETPOST('socid', 'int') . '&id=' . $object->id; + $option = '&socid='.GETPOST('socid', 'int').'&id='.$object->id; $staticsoc = new Societe($db); $staticsoc->fetch(GETPOST('socid', 'int')); - $title=$langs->trans('PriceByCustomerLog'); - $title.=' - '.$staticsoc->getNomUrl(1); + $title = $langs->trans('PriceByCustomerLog'); + $title .= ' - '.$staticsoc->getNomUrl(1); - $backbutton='' . $langs->trans("Back") . ''; + $backbutton = ''.$langs->trans("Back").''; print_barre_liste($title, $page, $_SERVER['PHP_SELF'], $option, $sortfield, $sortorder, $backbutton, count($prodcustprice->lines), $nbtotalofrecords, 'title_accountancy.png'); if (count($prodcustprice->lines) > 0) { - print ''; - print ''; + print ''; + print ''; - print '
    ' . $langs->trans('ThirdParty') . ''.$langs->trans('ThirdParty').'" . $staticsoc->getNomUrl(1) . "".$staticsoc->getNomUrl(1)."
    ' . $langs->trans("DefaultTaxRate") . ''; + print '
    '.$langs->trans("DefaultTaxRate").''; print $form->load_tva("tva_tx", $prodcustprice->default_vat_code ? $prodcustprice->tva_tx.' ('.$prodcustprice->default_vat_code.')' : $prodcustprice->tva_tx, $mysoc, '', $object->id, $prodcustprice->recuperableonly, $object->type, false, 1); print '
    '; if ($prodcustprice->price_base_type == 'TTC') { - print ''; + print ''; } else { - print ''; + print ''; } print '
    '; if ($prodcustprice->price_base_type == 'TTC') { - print ''; + print ''; } else { - print ''; + print ''; } print ''.$langs->trans("MinimumRecommendedPrice", price($maxpricesupplier, 0, '', 1, -1, -1, 'auto')).' '.img_warning().'
    '; + print '
    '; print ''; - print ''; - print ''; - print ''; - print ''; - print ''; + print ''; + print ''; + print ''; + print ''; + print ''; if ($mysoc->localtax1_assuj == "1" || $mysoc->localtax2_assuj == "1") { //print ''; - print ''; + print ''; } else { - print ''; + print ''; } - print ''; - print ''; - print ''; + print ''; + print ''; + print ''; print ''; print ''; @@ -1888,19 +1888,19 @@ if (! empty($conf->global->PRODUIT_CUSTOMER_PRICES)) $tva_tx = $line->default_vat_code ? $line->tva_tx.' ('.$line->default_vat_code.')' : $line->tva_tx; // Line for default price - if ($line->price_base_type=='HT') + if ($line->price_base_type == 'HT') { - $pu=$line->price; + $pu = $line->price; } else { - $pu=$line->price_ttc; + $pu = $line->price_ttc; } // Local tax is not saved into table of product. We use value linked to VAT code. - $localtaxarray=getLocalTaxesFromRate($line->tva_tx.($line->default_vat_code?' ('.$line->default_vat_code.')':''), 0, $staticsoc, $mysoc); + $localtaxarray = getLocalTaxesFromRate($line->tva_tx.($line->default_vat_code ? ' ('.$line->default_vat_code.')' : ''), 0, $staticsoc, $mysoc); // Define part of HT, VAT, TTC - $resultarray=calcul_price_total(1, $pu, 0, $line->tva_tx, 1, 1, 0, $line->price_base_type, $line->recuperableonly, $object->type, $mysoc, $localtaxarray); + $resultarray = calcul_price_total(1, $pu, 0, $line->tva_tx, 1, 1, 0, $line->price_base_type, $line->recuperableonly, $object->type, $mysoc, $localtaxarray); // Calcul du total ht sans remise $total_ht = $resultarray[0]; $total_vat = $resultarray[1]; @@ -1910,35 +1910,35 @@ if (! empty($conf->global->PRODUIT_CUSTOMER_PRICES)) print ''; - print ""; - print ""; - print '"; + print ""; + print ""; + print '"; print '"; - print '"; + print '"; if ($mysoc->localtax1_assuj == "1" || $mysoc->localtax2_assuj == "1") { //print '"; - print ''; + print ''; } else { - print '"; + print '"; } - print ''; - print ''; + print ''; + print ''; // User $userstatic = new User($db); @@ -1969,67 +1969,67 @@ if (! empty($conf->global->PRODUIT_CUSTOMER_PRICES)) setEventMessages($prodcustprice->error, $prodcustprice->errors, 'errors'); } - $option = '&search_soc=' . $search_soc . '&id=' . $object->id; + $option = '&search_soc='.$search_soc.'&id='.$object->id; print_barre_liste($langs->trans('PriceByCustomer'), $page, $_SERVER ['PHP_SELF'], $option, $sortfield, $sortorder, '', count($prodcustprice->lines), $nbtotalofrecords, 'title_accountancy.png'); - print ''; - print ''; + print ''; + print ''; - print '
    ' . $langs->trans("ThirdParty") . '' . $langs->trans("AppliedPricesFrom") . '' . $langs->trans("PriceBase") . '' . $langs->trans("DefaultTaxRate") . '' . $langs->trans("HT") . ''.$langs->trans("ThirdParty").''.$langs->trans("AppliedPricesFrom").''.$langs->trans("PriceBase").''.$langs->trans("DefaultTaxRate").''.$langs->trans("HT").'' . $langs->trans("INCVATONLY") . '' . $langs->trans("INCT") . ''.$langs->trans("INCT").'' . $langs->trans("TTC") . ''.$langs->trans("TTC").'' . $langs->trans("MinPrice") . ' ' . $langs->trans("HT") . '' . $langs->trans("MinPrice") . ' ' . $langs->trans("TTC") . '' . $langs->trans("ChangedBy") . ''.$langs->trans("MinPrice").' '.$langs->trans("HT").''.$langs->trans("MinPrice").' '.$langs->trans("TTC").''.$langs->trans("ChangedBy").' 
    " . $staticsoc->getNomUrl(1) . "" . dol_print_date($line->datec, "dayhour") . "' . $langs->trans($line->price_base_type) . "".$staticsoc->getNomUrl(1)."".dol_print_date($line->datec, "dayhour")."'.$langs->trans($line->price_base_type)."'; - $positiverates=''; - if (price2num($line->tva_tx)) $positiverates.=($positiverates?'/':'').price2num($line->tva_tx); - if (price2num($line->localtax1_type)) $positiverates.=($positiverates?'/':'').price2num($line->localtax1_tx); - if (price2num($line->localtax2_type)) $positiverates.=($positiverates?'/':'').price2num($line->localtax2_tx); - if (empty($positiverates)) $positiverates='0'; + $positiverates = ''; + if (price2num($line->tva_tx)) $positiverates .= ($positiverates ? '/' : '').price2num($line->tva_tx); + if (price2num($line->localtax1_type)) $positiverates .= ($positiverates ? '/' : '').price2num($line->localtax1_tx); + if (price2num($line->localtax2_type)) $positiverates .= ($positiverates ? '/' : '').price2num($line->localtax2_tx); + if (empty($positiverates)) $positiverates = '0'; - echo vatrate($positiverates.($line->default_vat_code?' ('.$line->default_vat_code.')':''), '%', ($line->tva_npr?$line->tva_npr:$line->recuperableonly)); + echo vatrate($positiverates.($line->default_vat_code ? ' ('.$line->default_vat_code.')' : ''), '%', ($line->tva_npr ? $line->tva_npr : $line->recuperableonly)); //. vatrate($tva_tx, true, $line->recuperableonly) . print "' . price($line->price) . "'.price($line->price)."' . price($line->price_ttc) . "' . price($resultarray[2]) . ''.price($resultarray[2]).'' . price($line->price_ttc) . "'.price($line->price_ttc)."' . price($line->price_min) . '' . price($line->price_min_ttc) . ''.price($line->price_min).''.price($line->price_min_ttc).'
    '; + print '
    '; if (count($prodcustprice->lines) > 0 || $search_soc) { - $colspan=8; + $colspan = 8; //if ($mysoc->localtax1_assuj == "1" || $mysoc->localtax2_assuj == "1") $colspan++; print ''; - print ''; + print ''; print ''; // Print the search button print ''; print ''; } print ''; - print ''; - print ''; - print ''; - print ''; - print ''; + print ''; + print ''; + print ''; + print ''; + print ''; if ($mysoc->localtax1_assuj == "1" || $mysoc->localtax2_assuj == "1") { //print ''; - print ''; + print ''; } else { - print ''; + print ''; } - print ''; - print ''; - print ''; + print ''; + print ''; + print ''; print ''; print ''; // Line for default price - if ($object->price_base_type=='HT') + if ($object->price_base_type == 'HT') { - $pu=$object->price; + $pu = $object->price; } else { - $pu=$object->price_ttc; + $pu = $object->price_ttc; } // Local tax is not saved into table of product. We use value linked to VAT code. - $localtaxarray=getLocalTaxesFromRate($object->tva_tx.($object->default_vat_code?' ('.$object->default_vat_code.')':''), 0, $mysoc, $mysoc); + $localtaxarray = getLocalTaxesFromRate($object->tva_tx.($object->default_vat_code ? ' ('.$object->default_vat_code.')' : ''), 0, $mysoc, $mysoc); // Define part of HT, VAT, TTC - $resultarray=calcul_price_total(1, $pu, 0, $object->tva_tx, 1, 1, 0, $object->price_base_type, $object->recuperableonly, $object->type, $mysoc, $localtaxarray); + $resultarray = calcul_price_total(1, $pu, 0, $object->tva_tx, 1, 1, 0, $object->price_base_type, $object->recuperableonly, $object->type, $mysoc, $localtaxarray); // Calcul du total ht sans remise $total_ht = $resultarray[0]; $total_vat = $resultarray[1]; @@ -2038,48 +2038,48 @@ if (! empty($conf->global->PRODUIT_CUSTOMER_PRICES)) $total_ttc = $resultarray[2]; print ''; - print ""; - print ""; + print ""; + print ""; - print '"; + print '"; print '"; - print '"; + print '"; if ($mysoc->localtax1_assuj == "1" || $mysoc->localtax2_assuj == "1") { //print '"; - print ''; + print ''; } else { - print '"; + print '"; } - print ''; - print ''; + print ''; + print ''; print ''; if ($user->rights->produit->supprimer || $user->rights->service->supprimer) { print ''; - print ""; - print ""; + print ""; + print ""; - print '"; + print '"; print '"; - print '"; + print '"; if ($mysoc->localtax1_assuj == "1" || $mysoc->localtax2_assuj == "1") { //print '"; - print ''; + print ''; } else { - print '"; + print '"; } - print ''; - print ''; + print ''; + print ''; // User $userstatic = new User($db); @@ -2161,15 +2161,15 @@ if (! empty($conf->global->PRODUIT_CUSTOMER_PRICES)) if ($user->rights->produit->supprimer || $user->rights->service->supprimer) { print ''; diff --git a/htdocs/product/reassort.php b/htdocs/product/reassort.php index 3054aebfa9d..12c9163cf92 100644 --- a/htdocs/product/reassort.php +++ b/htdocs/product/reassort.php @@ -56,20 +56,20 @@ $sortfield = GETPOST("sortfield", 'alpha'); $sortorder = GETPOST("sortorder", 'alpha'); $page = GETPOST("page", 'int'); if (empty($page) || $page < 0) $page = 0; -if (! $sortfield) $sortfield="p.ref"; -if (! $sortorder) $sortorder="ASC"; -$limit = GETPOST('limit', 'int')?GETPOST('limit', 'int'):$conf->liste_limit; +if (!$sortfield) $sortfield = "p.ref"; +if (!$sortorder) $sortorder = "ASC"; +$limit = GETPOST('limit', 'int') ?GETPOST('limit', 'int') : $conf->liste_limit; if (empty($page) || $page == -1) { $page = 0; } // If $page is not defined, or '' or -1 -$offset = $limit * $page ; +$offset = $limit * $page; // Load sale and categ filters $search_sale = GETPOST("search_sale"); $search_categ = GETPOST("search_categ"); // Get object canvas (By default, this is not defined, so standard usage of dolibarr) -$canvas=GETPOST("canvas"); -$objcanvas=null; -if (! empty($canvas)) +$canvas = GETPOST("canvas"); +$objcanvas = null; +if (!empty($canvas)) { require_once DOL_DOCUMENT_ROOT.'/core/class/canvas.class.php'; $objcanvas = new Canvas($db, $action); @@ -77,10 +77,10 @@ if (! empty($canvas)) } // Define virtualdiffersfromphysical -$virtualdiffersfromphysical=0; -if (! empty($conf->global->STOCK_CALCULATE_ON_SHIPMENT) || ! empty($conf->global->STOCK_CALCULATE_ON_SUPPLIER_DISPATCH_ORDER)|| ! empty($conf->global->STOCK_CALCULATE_ON_RECEPTION)) +$virtualdiffersfromphysical = 0; +if (!empty($conf->global->STOCK_CALCULATE_ON_SHIPMENT) || !empty($conf->global->STOCK_CALCULATE_ON_SUPPLIER_DISPATCH_ORDER) || !empty($conf->global->STOCK_CALCULATE_ON_RECEPTION)) { - $virtualdiffersfromphysical=1; // According to increase/decrease stock options, virtual and physical stock may differs. + $virtualdiffersfromphysical = 1; // According to increase/decrease stock options, virtual and physical stock may differs. } @@ -91,18 +91,18 @@ if (! empty($conf->global->STOCK_CALCULATE_ON_SHIPMENT) || ! empty($conf->global 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=""; - $snom=""; - $sall=""; - $tosell=""; - $tobuy=""; - $search_sale=""; - $search_categ=""; - $type=""; - $catid=''; - $toolowstock=''; - $fourn_id=''; - $sbarcode=''; + $sref = ""; + $snom = ""; + $sall = ""; + $tosell = ""; + $tobuy = ""; + $search_sale = ""; + $search_categ = ""; + $type = ""; + $catid = ''; + $toolowstock = ''; + $fourn_id = ''; + $sbarcode = ''; } @@ -111,50 +111,50 @@ if (GETPOST('button_removefilter_x', 'alpha') || GETPOST('button_removefilter.x' * View */ -$helpurl='EN:Module_Stocks_En|FR:Module_Stock|ES:Módulo_Stocks'; +$helpurl = 'EN:Module_Stocks_En|FR:Module_Stock|ES:Módulo_Stocks'; -$form=new Form($db); -$htmlother=new FormOther($db); +$form = new Form($db); +$htmlother = new FormOther($db); $sql = 'SELECT p.rowid, p.ref, p.label, p.barcode, p.price, p.price_ttc, p.price_base_type, p.entity,'; -$sql.= ' p.fk_product_type, p.tms as datem,'; -$sql.= ' p.duration, p.tosell as statut, p.tobuy, p.seuil_stock_alerte, p.desiredstock,'; -$sql.= ' SUM(s.reel) as stock_physique'; -if (! empty($conf->global->PRODUCT_USE_UNITS)) $sql.= ', u.short_label as unit_short'; -$sql.= ' FROM '.MAIN_DB_PREFIX.'product as p'; -$sql.= ' LEFT JOIN '.MAIN_DB_PREFIX.'product_stock as s on p.rowid = s.fk_product'; -if (! empty($conf->global->PRODUCT_USE_UNITS)) $sql.= ' LEFT JOIN '.MAIN_DB_PREFIX.'c_units as u on p.fk_unit = u.rowid'; +$sql .= ' p.fk_product_type, p.tms as datem,'; +$sql .= ' p.duration, p.tosell as statut, p.tobuy, p.seuil_stock_alerte, p.desiredstock,'; +$sql .= ' SUM(s.reel) as stock_physique'; +if (!empty($conf->global->PRODUCT_USE_UNITS)) $sql .= ', u.short_label as unit_short'; +$sql .= ' FROM '.MAIN_DB_PREFIX.'product as p'; +$sql .= ' LEFT JOIN '.MAIN_DB_PREFIX.'product_stock as s on p.rowid = s.fk_product'; +if (!empty($conf->global->PRODUCT_USE_UNITS)) $sql .= ' LEFT JOIN '.MAIN_DB_PREFIX.'c_units as u on p.fk_unit = u.rowid'; // We'll need this table joined to the select in order to filter by categ -if ($search_categ) $sql.= ", ".MAIN_DB_PREFIX."categorie_product as cp"; -$sql.= " WHERE p.entity IN (".getEntity('product').")"; -if ($search_categ) $sql.= " AND p.rowid = cp.fk_product"; // Join for the needed table to filter by categ -if ($sall) $sql.=natural_search(array('p.ref', 'p.label', 'p.description', 'p.note'), $sall); +if ($search_categ) $sql .= ", ".MAIN_DB_PREFIX."categorie_product as cp"; +$sql .= " WHERE p.entity IN (".getEntity('product').")"; +if ($search_categ) $sql .= " AND p.rowid = cp.fk_product"; // Join for the needed table to filter by categ +if ($sall) $sql .= natural_search(array('p.ref', 'p.label', 'p.description', 'p.note'), $sall); // if the type is not 1, we show all products (type = 0,2,3) if (dol_strlen($type)) { - if ($type==1) + if ($type == 1) { - $sql.= " AND p.fk_product_type = '1'"; + $sql .= " AND p.fk_product_type = '1'"; } else { - $sql.= " AND p.fk_product_type <> '1'"; + $sql .= " AND p.fk_product_type <> '1'"; } } -if ($sref) $sql.= natural_search('p.ref', $sref); -if ($search_barcode) $sql.= natural_search('p.barcode', $search_barcode); -if ($snom) $sql.= natural_search('p.label', $snom); -if (! empty($tosell)) $sql.= " AND p.tosell = ".$tosell; -if (! empty($tobuy)) $sql.= " AND p.tobuy = ".$tobuy; -if (! empty($canvas)) $sql.= " AND p.canvas = '".$db->escape($canvas)."'"; -if($catid) $sql.= " AND cp.fk_categorie = ".$catid; -if ($fourn_id > 0) $sql.= " AND p.rowid = pf.fk_product AND pf.fk_soc = ".$fourn_id; +if ($sref) $sql .= natural_search('p.ref', $sref); +if ($search_barcode) $sql .= natural_search('p.barcode', $search_barcode); +if ($snom) $sql .= natural_search('p.label', $snom); +if (!empty($tosell)) $sql .= " AND p.tosell = ".$tosell; +if (!empty($tobuy)) $sql .= " AND p.tobuy = ".$tobuy; +if (!empty($canvas)) $sql .= " AND p.canvas = '".$db->escape($canvas)."'"; +if ($catid) $sql .= " AND cp.fk_categorie = ".$catid; +if ($fourn_id > 0) $sql .= " AND p.rowid = pf.fk_product AND pf.fk_soc = ".$fourn_id; // Insert categ filter if ($search_categ) $sql .= " AND cp.fk_categorie = ".$db->escape($search_categ); -$sql.= " GROUP BY p.rowid, p.ref, p.label, p.barcode, p.price, p.price_ttc, p.price_base_type, p.entity,"; -$sql.= " p.fk_product_type, p.tms, p.duration, p.tosell, p.tobuy, p.seuil_stock_alerte, p.desiredstock"; -if ($toolowstock) $sql.= " HAVING SUM(".$db->ifsql('s.reel IS NULL', '0', 's.reel').") < p.seuil_stock_alerte"; -$sql.= $db->order($sortfield, $sortorder); +$sql .= " GROUP BY p.rowid, p.ref, p.label, p.barcode, p.price, p.price_ttc, p.price_base_type, p.entity,"; +$sql .= " p.fk_product_type, p.tms, p.duration, p.tosell, p.tobuy, p.seuil_stock_alerte, p.desiredstock"; +if ($toolowstock) $sql .= " HAVING SUM(".$db->ifsql('s.reel IS NULL', '0', 's.reel').") < p.seuil_stock_alerte"; +$sql .= $db->order($sortfield, $sortorder); // Count total nb of records $nbtotalofrecords = ''; @@ -169,7 +169,7 @@ if (empty($conf->global->MAIN_DISABLE_FULL_SCANLIST)) } } -$sql.= $db->plimit($limit + 1, $offset); +$sql .= $db->plimit($limit + 1, $offset); $resql = $db->query($sql); if ($resql) @@ -187,31 +187,31 @@ if ($resql) if (isset($type)) { - if ($type==1) { $texte = $langs->trans("Services"); } + if ($type == 1) { $texte = $langs->trans("Services"); } else { $texte = $langs->trans("Products"); } } else { $texte = $langs->trans("ProductsAndServices"); } - $texte.=' ('.$langs->trans("MenuStocks").')'; + $texte .= ' ('.$langs->trans("MenuStocks").')'; - $param=''; - if ($limit > 0 && $limit != $conf->liste_limit) $param.='&limit='.urlencode($limit); - if ($sall) $param.="&sall=".urlencode($sall); - if ($tosell) $param.="&tosell=".urlencode($tosell); - if ($tobuy) $param.="&tobuy=".urlencode($tobuy); - if ($type) $param.="&type=".urlencode($type); - if ($fourn_id) $param.="&fourn_id=".urlencode($fourn_id); - if ($snom) $param.="&snom=".urlencode($snom); - if ($sref) $param.="&sref=".urlencode($sref); - if ($search_sale) $param.="&search_sale=".urlencode($search_sale); - if ($search_categ) $param.="&search_categ=".urlencode($search_categ); - if ($toolowstock) $param.="&toolowstock=".urlencode($toolowstock); - if ($sbarcode) $param.="&sbarcode=".urlencode($sbarcode); - if ($catid) $param.="&catid=".urlencode($catid); + $param = ''; + if ($limit > 0 && $limit != $conf->liste_limit) $param .= '&limit='.urlencode($limit); + if ($sall) $param .= "&sall=".urlencode($sall); + if ($tosell) $param .= "&tosell=".urlencode($tosell); + if ($tobuy) $param .= "&tobuy=".urlencode($tobuy); + if ($type) $param .= "&type=".urlencode($type); + if ($fourn_id) $param .= "&fourn_id=".urlencode($fourn_id); + if ($snom) $param .= "&snom=".urlencode($snom); + if ($sref) $param .= "&sref=".urlencode($sref); + if ($search_sale) $param .= "&search_sale=".urlencode($search_sale); + if ($search_categ) $param .= "&search_categ=".urlencode($search_categ); + if ($toolowstock) $param .= "&toolowstock=".urlencode($toolowstock); + if ($sbarcode) $param .= "&sbarcode=".urlencode($sbarcode); + if ($catid) $param .= "&catid=".urlencode($catid); llxHeader("", $texte, $helpurl); - print ''; + print ''; print ''; print ''; print ''; @@ -220,7 +220,7 @@ if ($resql) print_barre_liste($texte, $page, $_SERVER["PHP_SELF"], $param, $sortfield, $sortorder, '', $num, $nbtotalofrecords, 'products', 0, '', '', $limit); - if (! empty($catid)) + if (!empty($catid)) { print "
    "; $c = new Categorie($db); @@ -231,48 +231,48 @@ if ($resql) } // Filter on categories - $moreforfilter=''; - if (! empty($conf->categorie->enabled)) + $moreforfilter = ''; + if (!empty($conf->categorie->enabled)) { - $moreforfilter.='
    '; - $moreforfilter.=$langs->trans('Categories'). ': '; - $moreforfilter.=$htmlother->select_categories(Categorie::TYPE_PRODUCT, $search_categ, 'search_categ'); - $moreforfilter.='
    '; + $moreforfilter .= '
    '; + $moreforfilter .= $langs->trans('Categories').': '; + $moreforfilter .= $htmlother->select_categories(Categorie::TYPE_PRODUCT, $search_categ, 'search_categ'); + $moreforfilter .= '
    '; } - $moreforfilter.='
    '; - $moreforfilter.=$langs->trans("StockTooLow").' '; - $moreforfilter.='
    '; + $moreforfilter .= '
    '; + $moreforfilter .= $langs->trans("StockTooLow").' '; + $moreforfilter .= '
    '; - if (! empty($moreforfilter)) + if (!empty($moreforfilter)) { print '
    '; print $moreforfilter; - $parameters=array(); - $reshook=$hookmanager->executeHooks('printFieldPreListTitle', $parameters); // Note that $action and $object may have been modified by hook + $parameters = array(); + $reshook = $hookmanager->executeHooks('printFieldPreListTitle', $parameters); // Note that $action and $object may have been modified by hook print $hookmanager->resPrint; print '
    '; } - $param=''; - if ($tosell) $param.="&tosell=".$tosell; - if ($tobuy) $param.="&tobuy=".$tobuy; - if ($type) $param.="&type=".$type; - if ($fourn_id) $param.="&fourn_id=".$fourn_id; - if ($snom) $param.="&snom=".$snom; - if ($sref) $param.="&sref=".$sref; - if ($toolowstock) $param.="&toolowstock=".$toolowstock; - if ($search_categ) $param.="&search_categ=".$search_categ; + $param = ''; + if ($tosell) $param .= "&tosell=".$tosell; + if ($tobuy) $param .= "&tobuy=".$tobuy; + if ($type) $param .= "&type=".$type; + if ($fourn_id) $param .= "&fourn_id=".$fourn_id; + if ($snom) $param .= "&snom=".$snom; + if ($sref) $param .= "&sref=".$sref; + if ($toolowstock) $param .= "&toolowstock=".$toolowstock; + if ($search_categ) $param .= "&search_categ=".$search_categ; $formProduct = new FormProduct($db); $formProduct->loadWarehouses(); $warehouses_list = $formProduct->cache_warehouses; $nb_warehouse = count($warehouses_list); $colspan_warehouse = 1; - if (! empty($conf->global->STOCK_DETAIL_ON_WAREHOUSE)) { $colspan_warehouse = $nb_warehouse > 1 ? $nb_warehouse+1 : 1; } + if (!empty($conf->global->STOCK_DETAIL_ON_WAREHOUSE)) { $colspan_warehouse = $nb_warehouse > 1 ? $nb_warehouse + 1 : 1; } print '
    '; - print '
     '; - $searchpicto=$form->showFilterAndCheckAddButtons(0); + $searchpicto = $form->showFilterAndCheckAddButtons(0); print $searchpicto; print '
    ' . $langs->trans("ThirdParty") . '' . $langs->trans("AppliedPricesFrom") . '' . $langs->trans("PriceBase") . '' . $langs->trans("DefaultTaxRate") . '' . $langs->trans("HT") . ''.$langs->trans("ThirdParty").''.$langs->trans("AppliedPricesFrom").''.$langs->trans("PriceBase").''.$langs->trans("DefaultTaxRate").''.$langs->trans("HT").'' . $langs->trans("INCVATONLY") . '' . $langs->trans("INCT") . ''.$langs->trans("INCT").'' . $langs->trans("TTC") . ''.$langs->trans("TTC").'' . $langs->trans("MinPrice") . ' ' . $langs->trans("HT") . '' . $langs->trans("MinPrice") . ' ' . $langs->trans("TTC") . '' . $langs->trans("ChangedBy") . ''.$langs->trans("MinPrice").' '.$langs->trans("HT").''.$langs->trans("MinPrice").' '.$langs->trans("TTC").''.$langs->trans("ChangedBy").' 
    " . $langs->trans("Default") . "" . "".$langs->trans("Default").""."' . $langs->trans($object->price_base_type) . "'.$langs->trans($object->price_base_type)."'; - $positiverates=''; - if (price2num($object->tva_tx)) $positiverates.=($positiverates?'/':'').price2num($object->tva_tx); - if (price2num($object->localtax1_type)) $positiverates.=($positiverates?'/':'').price2num($object->localtax1_tx); - if (price2num($object->localtax2_type)) $positiverates.=($positiverates?'/':'').price2num($object->localtax2_tx); - if (empty($positiverates)) $positiverates='0'; - echo vatrate($positiverates.($object->default_vat_code?' ('.$object->default_vat_code.')':''), '%', $object->tva_npr); + $positiverates = ''; + if (price2num($object->tva_tx)) $positiverates .= ($positiverates ? '/' : '').price2num($object->tva_tx); + if (price2num($object->localtax1_type)) $positiverates .= ($positiverates ? '/' : '').price2num($object->localtax1_tx); + if (price2num($object->localtax2_type)) $positiverates .= ($positiverates ? '/' : '').price2num($object->localtax2_tx); + if (empty($positiverates)) $positiverates = '0'; + echo vatrate($positiverates.($object->default_vat_code ? ' ('.$object->default_vat_code.')' : ''), '%', $object->tva_npr); //print vatrate($object->tva_tx, true, $object->tva_npr); //print $object->default_vat_code?' ('.$object->default_vat_code.')':''; print "' . price($object->price) . "'.price($object->price)."' . price($object->price_ttc) . "' . price($resultarray[2]) . ''.price($resultarray[2]).'' . price($object->price_ttc) . "'.price($object->price_ttc)."' . price($object->price_min) . '' . price($object->price_min_ttc) . ''.price($object->price_min).''.price($object->price_min_ttc).''; print ''; - print 'id . '">'; + print 'id.'">'; print img_info($langs->trans('PriceByCustomerLog')); print ''; print ' '; - print 'id . '">'; + print 'id.'">'; print img_edit('default', 0, 'style="vertical-align: middle;"'); print ''; print '   '; @@ -2098,19 +2098,19 @@ if (! empty($conf->global->PRODUIT_CUSTOMER_PRICES)) $tva_tx = $line->default_vat_code ? $line->tva_tx.' ('.$line->default_vat_code.')' : $line->tva_tx; // Line for default price - if ($line->price_base_type=='HT') + if ($line->price_base_type == 'HT') { - $pu=$line->price; + $pu = $line->price; } else { - $pu=$line->price_ttc; + $pu = $line->price_ttc; } // Local tax is not saved into table of product. We use value linked to VAT code. - $localtaxarray=getLocalTaxesFromRate($line->tva_tx.($line->default_vat_code?' ('.$line->default_vat_code.')':''), 0, $staticsoc, $mysoc); + $localtaxarray = getLocalTaxesFromRate($line->tva_tx.($line->default_vat_code ? ' ('.$line->default_vat_code.')' : ''), 0, $staticsoc, $mysoc); // Define part of HT, VAT, TTC - $resultarray=calcul_price_total(1, $pu, 0, $line->tva_tx, 1, 1, 0, $line->price_base_type, $line->recuperableonly, $object->type, $mysoc, $localtaxarray); + $resultarray = calcul_price_total(1, $pu, 0, $line->tva_tx, 1, 1, 0, $line->price_base_type, $line->recuperableonly, $object->type, $mysoc, $localtaxarray); // Calcul du total ht sans remise $total_ht = $resultarray[0]; $total_vat = $resultarray[1]; @@ -2120,34 +2120,34 @@ if (! empty($conf->global->PRODUIT_CUSTOMER_PRICES)) print '
    " . $staticsoc->getNomUrl(1) . "" . dol_print_date($line->datec, "dayhour") . "".$staticsoc->getNomUrl(1)."".dol_print_date($line->datec, "dayhour")."' . $langs->trans($line->price_base_type) . "'.$langs->trans($line->price_base_type)."'; - $positiverates=''; - if (price2num($line->tva_tx)) $positiverates.=($positiverates?'/':'').price2num($line->tva_tx); - if (price2num($line->localtax1_type)) $positiverates.=($positiverates?'/':'').price2num($line->localtax1_tx); - if (price2num($line->localtax2_type)) $positiverates.=($positiverates?'/':'').price2num($line->localtax2_tx); - if (empty($positiverates)) $positiverates='0'; - echo vatrate($positiverates.($line->default_vat_code?' ('.$line->default_vat_code.')':''), '%', ($line->tva_npr?$line->tva_npr:$line->recuperableonly)); + $positiverates = ''; + if (price2num($line->tva_tx)) $positiverates .= ($positiverates ? '/' : '').price2num($line->tva_tx); + if (price2num($line->localtax1_type)) $positiverates .= ($positiverates ? '/' : '').price2num($line->localtax1_tx); + if (price2num($line->localtax2_type)) $positiverates .= ($positiverates ? '/' : '').price2num($line->localtax2_tx); + if (empty($positiverates)) $positiverates = '0'; + echo vatrate($positiverates.($line->default_vat_code ? ' ('.$line->default_vat_code.')' : ''), '%', ($line->tva_npr ? $line->tva_npr : $line->recuperableonly)); print "' . price($line->price) . "'.price($line->price)."' . price($line->price_ttc) . "' . price($resultarray[2]) . ''.price($resultarray[2]).'' . price($line->price_ttc) . "'.price($line->price_ttc)."' . price($line->price_min) . '' . price($line->price_min_ttc) . ''.price($line->price_min).''.price($line->price_min_ttc).''; - print 'id . '&socid=' . $line->fk_soc . '">'; + print 'id.'&socid='.$line->fk_soc.'">'; print img_info($langs->trans('PriceByCustomerLog')); print ''; print ' '; - print 'id . '&lineid=' . $line->id . '">'; + print 'id.'&lineid='.$line->id.'">'; print img_edit('default', 0, 'style="vertical-align: middle;"'); print ''; print ' '; - print 'id . '&lineid=' . $line->id . '">'; + print 'id.'&lineid='.$line->id.'">'; print img_delete('default', 'style="vertical-align: middle;"'); print ''; print '
    '; + print '
    '; // Fields title search print ''; @@ -283,7 +283,7 @@ if ($resql) print ''; print ''; // Duration - if (! empty($conf->service->enabled) && $type == 1) + if (!empty($conf->service->enabled) && $type == 1) { print ''; print ''; print ''; print ''; @@ -307,14 +307,14 @@ if ($resql) print ""; print_liste_field_titre("Ref", $_SERVER["PHP_SELF"], "p.ref", $param, "", "", $sortfield, $sortorder); print_liste_field_titre("Label", $_SERVER["PHP_SELF"], "p.label", $param, "", "", $sortfield, $sortorder); - if (! empty($conf->service->enabled) && $type == 1) print_liste_field_titre("Duration", $_SERVER["PHP_SELF"], "p.duration", $param, "", '', $sortfield, $sortorder, 'center '); + if (!empty($conf->service->enabled) && $type == 1) print_liste_field_titre("Duration", $_SERVER["PHP_SELF"], "p.duration", $param, "", '', $sortfield, $sortorder, 'center '); print_liste_field_titre("StockLimit", $_SERVER["PHP_SELF"], "p.seuil_stock_alerte", $param, "", '', $sortfield, $sortorder, 'right '); print_liste_field_titre("DesiredStock", $_SERVER["PHP_SELF"], "p.desiredstock", $param, "", '', $sortfield, $sortorder, 'right '); print_liste_field_titre("PhysicalStock", $_SERVER["PHP_SELF"], "stock_physique", $param, "", '', $sortfield, $sortorder, 'right '); // Details per warehouse - if (! empty($conf->global->STOCK_DETAIL_ON_WAREHOUSE)) // TODO This should be moved into the selection of fields on page product/list (page product/stock will be removed and replaced with product/list with its own context) + if (!empty($conf->global->STOCK_DETAIL_ON_WAREHOUSE)) // TODO This should be moved into the selection of fields on page product/list (page product/stock will be removed and replaced with product/list with its own context) { - if ($nb_warehouse>1) { + if ($nb_warehouse > 1) { foreach ($warehouses_list as &$wh) { print_liste_field_titre($wh['label'], '', '', '', '', '', '', '', 'right '); } @@ -322,7 +322,7 @@ if ($resql) } if ($virtualdiffersfromphysical) print_liste_field_titre("VirtualStock", $_SERVER["PHP_SELF"], "", $param, "", '', $sortfield, $sortorder, 'right '); // Units - if (! empty($conf->global->PRODUCT_USE_UNITS)) { + if (!empty($conf->global->PRODUCT_USE_UNITS)) { print_liste_field_titre("Unit", $_SERVER["PHP_SELF"], "unit_short", $param, "", 'align="right"', $sortfield, $sortorder); } print_liste_field_titre(''); @@ -335,7 +335,7 @@ if ($resql) { $objp = $db->fetch_object($resql); - $product=new Product($db); + $product = new Product($db); $product->fetch($objp->rowid); $product->load_stock(); @@ -346,7 +346,7 @@ if ($resql) print ''; print ''; - if (! empty($conf->service->enabled) && $type == 1) + if (!empty($conf->service->enabled) && $type == 1) { print ''; // Details per warehouse - if (! empty($conf->global->STOCK_DETAIL_ON_WAREHOUSE)) // TODO This should be moved into the selection of fields on page product/list (page product/stock will be removed and replaced with product/list with its own context) + if (!empty($conf->global->STOCK_DETAIL_ON_WAREHOUSE)) // TODO This should be moved into the selection of fields on page product/list (page product/stock will be removed and replaced with product/list with its own context) { - if($nb_warehouse>1) { - foreach($warehouses_list as &$wh) { + if ($nb_warehouse > 1) { + foreach ($warehouses_list as &$wh) { print ''; @@ -385,8 +385,8 @@ if ($resql) print ''; } // Units - if (! empty($conf->global->PRODUCT_USE_UNITS)) { - print ''; + if (!empty($conf->global->PRODUCT_USE_UNITS)) { + print ''; } print ''; print ''; diff --git a/htdocs/product/stats/card.php b/htdocs/product/stats/card.php index e5830ef7fc1..5ca7992be31 100644 --- a/htdocs/product/stats/card.php +++ b/htdocs/product/stats/card.php @@ -33,33 +33,33 @@ require_once DOL_DOCUMENT_ROOT.'/core/class/dolgraph.class.php'; require_once DOL_DOCUMENT_ROOT.'/categories/class/categorie.class.php'; require_once DOL_DOCUMENT_ROOT.'/core/class/html.formother.class.php'; -$WIDTH=DolGraph::getDefaultGraphSizeForStats('width', 380); -$HEIGHT=DolGraph::getDefaultGraphSizeForStats('height', 160); +$WIDTH = DolGraph::getDefaultGraphSizeForStats('width', 380); +$HEIGHT = DolGraph::getDefaultGraphSizeForStats('height', 160); // Load translation files required by the page $langs->loadLangs(array('companies', 'products', 'stocks', 'bills', 'other')); -$id = GETPOST('id', 'int'); // For this page, id can also be 'all' +$id = GETPOST('id', 'int'); // For this page, id can also be 'all' $ref = GETPOST('ref', 'alpha'); -$mode = (GETPOST('mode', 'alpha') ? GETPOST('mode', 'alpha') : 'byunit'); +$mode = (GETPOST('mode', 'alpha') ? GETPOST('mode', 'alpha') : 'byunit'); $search_year = GETPOST('search_year', 'int'); $search_categ = GETPOST('search_categ', 'int'); -$error = 0; +$error = 0; $mesg = ''; -$graphfiles=array(); +$graphfiles = array(); -$socid=''; -if (! empty($user->socid)) $socid=$user->socid; +$socid = ''; +if (!empty($user->socid)) $socid = $user->socid; // Security check -$fieldvalue = (! empty($id) ? $id : $ref); -$fieldtype = (! empty($ref) ? 'ref' : 'rowid'); -$result=restrictedArea($user, 'produit|service', $fieldvalue, 'product&product', '', '', $fieldtype); +$fieldvalue = (!empty($id) ? $id : $ref); +$fieldtype = (!empty($ref) ? 'ref' : 'rowid'); +$result = restrictedArea($user, 'produit|service', $fieldvalue, 'product&product', '', '', $fieldtype); -$tmp=dol_getdate(dol_now()); -$currentyear=$tmp['year']; -if (empty($search_year)) $search_year=$currentyear; +$tmp = dol_getdate(dol_now()); +$currentyear = $tmp['year']; +if (empty($search_year)) $search_year = $currentyear; /* @@ -77,30 +77,30 @@ $form = new Form($db); $htmlother = new FormOther($db); $object = new Product($db); -if (! $id && empty($ref)) +if (!$id && empty($ref)) { llxHeader("", $langs->trans("ProductStatistics")); $type = GETPOST('type', 'int'); - $helpurl=''; + $helpurl = ''; if ($type == '0') { - $helpurl='EN:Module_Products|FR:Module_Produits|ES:Módulo_Productos'; + $helpurl = 'EN:Module_Products|FR:Module_Produits|ES:Módulo_Productos'; //$title=$langs->trans("StatisticsOfProducts"); - $title=$langs->trans("Statistics"); + $title = $langs->trans("Statistics"); } elseif ($type == '1') { - $helpurl='EN:Module_Services_En|FR:Module_Services|ES:Módulo_Servicios'; + $helpurl = 'EN:Module_Services_En|FR:Module_Services|ES:Módulo_Servicios'; //$title=$langs->trans("StatisticsOfServices"); - $title=$langs->trans("Statistics"); + $title = $langs->trans("Statistics"); } else { - $helpurl='EN:Module_Services_En|FR:Module_Services|ES:Módulo_Servicios'; + $helpurl = 'EN:Module_Services_En|FR:Module_Services|ES:Módulo_Servicios'; //$title=$langs->trans("StatisticsOfProductsOrServices"); - $title=$langs->trans("Statistics"); + $title = $langs->trans("Statistics"); } print load_fiche_titre($title, $mesg, 'products'); @@ -114,39 +114,39 @@ else $shortlabel = dol_trunc($object->label, 16); if (GETPOST("type") == '0' || ($object->type == Product::TYPE_PRODUCT)) { - $title = $langs->trans('Product')." ". $shortlabel ." - ".$langs->trans('Statistics'); - $helpurl='EN:Module_Products|FR:Module_Produits|ES:Módulo_Productos'; + $title = $langs->trans('Product')." ".$shortlabel." - ".$langs->trans('Statistics'); + $helpurl = 'EN:Module_Products|FR:Module_Produits|ES:Módulo_Productos'; } if (GETPOST("type") == '1' || ($object->type == Product::TYPE_SERVICE)) { - $title = $langs->trans('Service')." ". $shortlabel ." - ".$langs->trans('Statistics'); - $helpurl='EN:Module_Services_En|FR:Module_Services|ES:Módulo_Servicios'; + $title = $langs->trans('Service')." ".$shortlabel." - ".$langs->trans('Statistics'); + $helpurl = 'EN:Module_Services_En|FR:Module_Services|ES:Módulo_Servicios'; } llxHeader('', $title, $helpurl); } -if ($result && (! empty($id) || ! empty($ref))) +if ($result && (!empty($id) || !empty($ref))) { - $head=product_prepare_head($object); - $titre=$langs->trans("CardProduct".$object->type); - $picto=($object->type==Product::TYPE_SERVICE?'service':'product'); + $head = product_prepare_head($object); + $titre = $langs->trans("CardProduct".$object->type); + $picto = ($object->type == Product::TYPE_SERVICE ? 'service' : 'product'); dol_fiche_head($head, 'stats', $titre, -1, $picto); $linkback = ''.$langs->trans("BackToList").''; - dol_banner_tab($object, 'ref', $linkback, ($user->socid?0:1), 'ref', '', '', '', 0, '', '', 1); + dol_banner_tab($object, 'ref', $linkback, ($user->socid ? 0 : 1), 'ref', '', '', '', 0, '', '', 1); dol_fiche_end(); } if (empty($id) & empty($ref)) { - $h=0; + $h = 0; $head = array(); - $head[$h][0] = DOL_URL_ROOT.'/product/stats/card.php'.($type != ''?'?type='.$type:''); + $head[$h][0] = DOL_URL_ROOT.'/product/stats/card.php'.($type != '' ? '?type='.$type : ''); $head[$h][1] = $langs->trans("Chart"); $head[$h][2] = 'chart'; $h++; @@ -159,7 +159,7 @@ if (empty($id) & empty($ref)) $title = $langs->trans("ListProductByPopularity"); } - $head[$h][0] = DOL_URL_ROOT.'/product/popuprop.php'.($type != ''?'?type='.$type:''); + $head[$h][0] = DOL_URL_ROOT.'/product/popuprop.php'.($type != '' ? '?type='.$type : ''); $head[$h][1] = $title; $head[$h][2] = 'popularityprop'; $h++; @@ -173,14 +173,14 @@ if ($result || empty($id)) print ''; print ''; - print '
    '; print ' '; @@ -298,7 +298,7 @@ if ($resql) print ' '; - $searchpicto=$form->showFilterAndCheckAddButtons(0); + $searchpicto = $form->showFilterAndCheckAddButtons(0); print $searchpicto; print '
    '.$product->label.''; if (preg_match('/([0-9]+)y/i', $objp->duration, $regs)) print $regs[1].' '.$langs->trans("DurationYear"); @@ -361,14 +361,14 @@ if ($resql) // Real stock print ''; if ($objp->seuil_stock_alerte != '' && ($objp->stock_physique < $objp->seuil_stock_alerte)) print img_warning($langs->trans("StockTooLow")).' '; - print $objp->stock_physique|0; + print $objp->stock_physique | 0; print ''; print empty($product->stock_warehouse[$wh['id']]->real) ? '0' : $product->stock_warehouse[$wh['id']]->real; print '' . $objp->unit_short . ''.$objp->unit_short.''.$langs->trans("Movements").''.$product->LibStatut($objp->statut, 5, 0).'
    '; + print '
    '; print ''; if (empty($id)) { // Type print ''; @@ -189,7 +189,7 @@ if ($result || empty($id)) { print ''; @@ -198,13 +198,13 @@ if ($result || empty($id)) // Year print ''; @@ -216,32 +216,32 @@ if ($result || empty($id)) // Choice of stats mode (byunit or bynumber) - if (! empty($conf->dol_use_jmobile)) print "\n".''; else print '
    '; print '
    '; //print '
    '.$langs->trans("Filter").'
    '.$langs->trans("ProductsAndServices").''; - $array=array('-1'=>' ', '0'=>$langs->trans('Product'), '1'=>$langs->trans('Service')); + $array = array('-1'=>' ', '0'=>$langs->trans('Product'), '1'=>$langs->trans('Service')); print $form->selectarray('type', $array, $type); print '
    '.$langs->trans("Categories").''; //$moreforfilter.='
    '; - $moreforfilter.=$htmlother->select_categories(Categorie::TYPE_PRODUCT, $search_categ, 'search_categ', 1); + $moreforfilter .= $htmlother->select_categories(Categorie::TYPE_PRODUCT, $search_categ, 'search_categ', 1); //$moreforfilter.='
    '; print $moreforfilter; print '
    '.$langs->trans("Year").''; - $arrayyears=array(); - for ($year = $currentyear - 10; $year < $currentyear + 10 ; $year++) + $arrayyears = array(); + for ($year = $currentyear - 10; $year < $currentyear + 10; $year++) { - $arrayyears[$year]=$year; + $arrayyears[$year] = $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('search_year', $arrayyears, $search_year, 0); print '
    '; // Generation des graphs - $dir = (! empty($conf->product->multidir_temp[$object->entity])?$conf->product->multidir_temp[$object->entity]:$conf->service->multidir_temp[$object->entity]); + $dir = (!empty($conf->product->multidir_temp[$object->entity]) ? $conf->product->multidir_temp[$object->entity] : $conf->service->multidir_temp[$object->entity]); if ($object->id > 0) // We are on statistics for a dedicated product { - if (! file_exists($dir.'/'.$object->id)) + if (!file_exists($dir.'/'.$object->id)) { if (dol_mkdir($dir.'/'.$object->id) < 0) { @@ -251,78 +251,78 @@ if ($result || empty($id)) } } - if($conf->propal->enabled) { - $graphfiles['propal']=array('modulepart'=>'productstats_proposals', - 'file' => $object->id.'/propal12m'.((string) $type != '' ? '_type'.$type : '').'_'.$mode.($search_year?'_year'.$search_year:'').'.png', - 'label' => ($mode=='byunit'?$langs->transnoentitiesnoconv("NumberOfUnitsProposals"):$langs->transnoentitiesnoconv("NumberOfProposals"))); + if ($conf->propal->enabled) { + $graphfiles['propal'] = array('modulepart'=>'productstats_proposals', + 'file' => $object->id.'/propal12m'.((string) $type != '' ? '_type'.$type : '').'_'.$mode.($search_year ? '_year'.$search_year : '').'.png', + 'label' => ($mode == 'byunit' ? $langs->transnoentitiesnoconv("NumberOfUnitsProposals") : $langs->transnoentitiesnoconv("NumberOfProposals"))); } - if($conf->supplier_proposal->enabled) { - $graphfiles['proposalssuppliers']=array('modulepart'=>'productstats_proposalssuppliers', - 'file' => $object->id.'/proposalssuppliers12m'.((string) $type != '' ? '_type'.$type : '').'_'.$mode.($search_year?'_year'.$search_year:'').'.png', - 'label' => ($mode=='byunit'?$langs->transnoentitiesnoconv("NumberOfUnitsSupplierProposals"):$langs->transnoentitiesnoconv("NumberOfSupplierProposals"))); + if ($conf->supplier_proposal->enabled) { + $graphfiles['proposalssuppliers'] = array('modulepart'=>'productstats_proposalssuppliers', + 'file' => $object->id.'/proposalssuppliers12m'.((string) $type != '' ? '_type'.$type : '').'_'.$mode.($search_year ? '_year'.$search_year : '').'.png', + 'label' => ($mode == 'byunit' ? $langs->transnoentitiesnoconv("NumberOfUnitsSupplierProposals") : $langs->transnoentitiesnoconv("NumberOfSupplierProposals"))); } - if($conf->order->enabled) { - $graphfiles['orders']=array('modulepart'=>'productstats_orders', - 'file' => $object->id.'/orders12m'.((string) $type != '' ? '_type'.$type : '').'_'.$mode.($search_year?'_year'.$search_year:'').'.png', - 'label' => ($mode=='byunit'?$langs->transnoentitiesnoconv("NumberOfUnitsCustomerOrders"):$langs->transnoentitiesnoconv("NumberOfCustomerOrders"))); + if ($conf->order->enabled) { + $graphfiles['orders'] = array('modulepart'=>'productstats_orders', + 'file' => $object->id.'/orders12m'.((string) $type != '' ? '_type'.$type : '').'_'.$mode.($search_year ? '_year'.$search_year : '').'.png', + 'label' => ($mode == 'byunit' ? $langs->transnoentitiesnoconv("NumberOfUnitsCustomerOrders") : $langs->transnoentitiesnoconv("NumberOfCustomerOrders"))); } - if($conf->supplier_order->enabled) { - $graphfiles['orderssuppliers']=array('modulepart'=>'productstats_orderssuppliers', - 'file' => $object->id.'/orderssuppliers12m'.((string) $type != '' ? '_type'.$type : '').'_'.$mode.($search_year?'_year'.$search_year:'').'.png', - 'label' => ($mode=='byunit'?$langs->transnoentitiesnoconv("NumberOfUnitsSupplierOrders"):$langs->transnoentitiesnoconv("NumberOfSupplierOrders"))); + if ($conf->supplier_order->enabled) { + $graphfiles['orderssuppliers'] = array('modulepart'=>'productstats_orderssuppliers', + 'file' => $object->id.'/orderssuppliers12m'.((string) $type != '' ? '_type'.$type : '').'_'.$mode.($search_year ? '_year'.$search_year : '').'.png', + 'label' => ($mode == 'byunit' ? $langs->transnoentitiesnoconv("NumberOfUnitsSupplierOrders") : $langs->transnoentitiesnoconv("NumberOfSupplierOrders"))); } - if($conf->facture->enabled) { - $graphfiles['invoices']=array('modulepart'=>'productstats_invoices', - 'file' => $object->id.'/invoices12m'.((string) $type != '' ? '_type'.$type : '').'_'.$mode.($search_year?'_year'.$search_year:'').'.png', - 'label' => ($mode=='byunit'?$langs->transnoentitiesnoconv("NumberOfUnitsCustomerInvoices"):$langs->transnoentitiesnoconv("NumberOfCustomerInvoices"))); + if ($conf->facture->enabled) { + $graphfiles['invoices'] = array('modulepart'=>'productstats_invoices', + 'file' => $object->id.'/invoices12m'.((string) $type != '' ? '_type'.$type : '').'_'.$mode.($search_year ? '_year'.$search_year : '').'.png', + 'label' => ($mode == 'byunit' ? $langs->transnoentitiesnoconv("NumberOfUnitsCustomerInvoices") : $langs->transnoentitiesnoconv("NumberOfCustomerInvoices"))); } - if($conf->supplier_invoice->enabled) { - $graphfiles['invoicessuppliers']=array('modulepart'=>'productstats_invoicessuppliers', - 'file' => $object->id.'/invoicessuppliers12m'.((string) $type != '' ? '_type'.$type : '').'_'.$mode.($search_year?'_year'.$search_year:'').'.png', - 'label' => ($mode=='byunit'?$langs->transnoentitiesnoconv("NumberOfUnitsSupplierInvoices"):$langs->transnoentitiesnoconv("NumberOfSupplierInvoices"))); + if ($conf->supplier_invoice->enabled) { + $graphfiles['invoicessuppliers'] = array('modulepart'=>'productstats_invoicessuppliers', + 'file' => $object->id.'/invoicessuppliers12m'.((string) $type != '' ? '_type'.$type : '').'_'.$mode.($search_year ? '_year'.$search_year : '').'.png', + 'label' => ($mode == 'byunit' ? $langs->transnoentitiesnoconv("NumberOfUnitsSupplierInvoices") : $langs->transnoentitiesnoconv("NumberOfSupplierInvoices"))); } - if($conf->contrat->enabled) { - $graphfiles['contracts']=array('modulepart'=>'productstats_contracts', - 'file' => $object->id.'/contracts12m'.((string) $type != '' ? '_type'.$type : '').'_'.$mode.($search_year?'_year'.$search_year:'').'.png', - 'label' => ($mode=='byunit'?$langs->transnoentitiesnoconv("NumberOfUnitsContracts"):$langs->transnoentitiesnoconv("NumberOfContracts"))); + if ($conf->contrat->enabled) { + $graphfiles['contracts'] = array('modulepart'=>'productstats_contracts', + 'file' => $object->id.'/contracts12m'.((string) $type != '' ? '_type'.$type : '').'_'.$mode.($search_year ? '_year'.$search_year : '').'.png', + 'label' => ($mode == 'byunit' ? $langs->transnoentitiesnoconv("NumberOfUnitsContracts") : $langs->transnoentitiesnoconv("NumberOfContracts"))); } $px = new DolGraph(); - if (! $error && count($graphfiles)>0) + if (!$error && count($graphfiles) > 0) { $mesg = $px->isGraphKo(); - if (! $mesg) + if (!$mesg) { - foreach($graphfiles as $key => $val) + foreach ($graphfiles as $key => $val) { - if (! $graphfiles[$key]['file']) continue; + if (!$graphfiles[$key]['file']) continue; $graph_data = array(); - if (dol_is_file($dir . '/' . $graphfiles[$key]['file'])) + if (dol_is_file($dir.'/'.$graphfiles[$key]['file'])) { // TODO Load cachefile $graphfiles[$key]['file'] } else { - $morefilters=''; + $morefilters = ''; if ($search_categ > 0) { - $categ=new Categorie($db); + $categ = new Categorie($db); $categ->fetch($search_categ); $listofprodids = $categ->getObjectsInCateg('product', 1); - $morefilters=' AND d.fk_product IN ('.((is_array($listofprodids) && count($listofprodids)) ? join(',', $listofprodids):'0').')'; + $morefilters = ' AND d.fk_product IN ('.((is_array($listofprodids) && count($listofprodids)) ? join(',', $listofprodids) : '0').')'; } if ($search_categ == -2) { - $morefilters=' AND d.fk_product NOT IN (SELECT cp.fk_product from '.MAIN_DB_PREFIX.'categorie_product as cp)'; + $morefilters = ' AND d.fk_product NOT IN (SELECT cp.fk_product from '.MAIN_DB_PREFIX.'categorie_product as cp)'; } if ($key == 'propal') $graph_data = $object->get_nb_propal($socid, $mode, ((string) $type != '' ? $type : -1), $search_year, $morefilters); @@ -340,18 +340,18 @@ if ($result || empty($id)) { $px->SetData($graph_data); $px->SetYLabel($graphfiles[$key]['label']); - $px->SetMaxValue($px->GetCeilMaxValue()<0?0:$px->GetCeilMaxValue()); - $px->SetMinValue($px->GetFloorMinValue()>0?0:$px->GetFloorMinValue()); + $px->SetMaxValue($px->GetCeilMaxValue() < 0 ? 0 : $px->GetCeilMaxValue()); + $px->SetMinValue($px->GetFloorMinValue() > 0 ? 0 : $px->GetFloorMinValue()); $px->SetWidth($WIDTH); $px->SetHeight($HEIGHT); $px->SetHorizTickIncrement(1); $px->SetShading(3); //print 'x '.$key.' '.$graphfiles[$key]['file']; - $url=DOL_URL_ROOT.'/viewimage.php?modulepart='.$graphfiles[$key]['modulepart'].'&entity='.$object->entity.'&file='.urlencode($graphfiles[$key]['file']); + $url = DOL_URL_ROOT.'/viewimage.php?modulepart='.$graphfiles[$key]['modulepart'].'&entity='.$object->entity.'&file='.urlencode($graphfiles[$key]['file']); $px->draw($dir."/".$graphfiles[$key]['file'], $url); - $graphfiles[$key]['output']=$px->show(); + $graphfiles[$key]['output'] = $px->show(); } else { @@ -364,19 +364,19 @@ if ($result || empty($id)) } // Show graphs - $i=0; - if ( count($graphfiles)>0) + $i = 0; + if (count($graphfiles) > 0) { - foreach($graphfiles as $key => $val) + foreach ($graphfiles as $key => $val) { - if (! $graphfiles[$key]['file']) continue; + if (!$graphfiles[$key]['file']) continue; - if ($graphfiles == 'propal' && ! $user->rights->propale->lire) continue; - if ($graphfiles == 'order' && ! $user->rights->commande->lire) continue; - if ($graphfiles == 'invoices' && ! $user->rights->facture->lire) continue; - if ($graphfiles == 'proposals_suppliers' && ! $user->rights->supplier_proposal->lire) continue; - if ($graphfiles == 'invoices_suppliers' && ! $user->rights->fournisseur->facture->lire) continue; - if ($graphfiles == 'orders_suppliers' && ! $user->rights->fournisseur->commande->lire) continue; + if ($graphfiles == 'propal' && !$user->rights->propale->lire) continue; + if ($graphfiles == 'order' && !$user->rights->commande->lire) continue; + if ($graphfiles == 'invoices' && !$user->rights->facture->lire) continue; + if ($graphfiles == 'proposals_suppliers' && !$user->rights->supplier_proposal->lire) continue; + if ($graphfiles == 'invoices_suppliers' && !$user->rights->fournisseur->facture->lire) continue; + if ($graphfiles == 'orders_suppliers' && !$user->rights->fournisseur->commande->lire) continue; if ($i % 2 == 0) @@ -389,19 +389,19 @@ if ($result || empty($id)) } // Date generation - if ($graphfiles[$key]['output'] && ! $px->isGraphKo()) + if ($graphfiles[$key]['output'] && !$px->isGraphKo()) { - if (file_exists($dir."/".$graphfiles[$key]['file']) && filemtime($dir."/".$graphfiles[$key]['file'])) $dategenerated=$langs->trans("GeneratedOn", dol_print_date(filemtime($dir."/".$graphfiles[$key]['file']), "dayhour")); - else $dategenerated=$langs->trans("GeneratedOn", dol_print_date(dol_now(), "dayhour")); + if (file_exists($dir."/".$graphfiles[$key]['file']) && filemtime($dir."/".$graphfiles[$key]['file'])) $dategenerated = $langs->trans("GeneratedOn", dol_print_date(filemtime($dir."/".$graphfiles[$key]['file']), "dayhour")); + else $dategenerated = $langs->trans("GeneratedOn", dol_print_date(dol_now(), "dayhour")); } else { - $dategenerated=($mesg?''.$mesg.'':$langs->trans("ChartNotGenerated")); + $dategenerated = ($mesg ? ''.$mesg.'' : $langs->trans("ChartNotGenerated")); } - $linktoregenerate='id).((string) $type != ''?'&type='.$type:'').'&action=recalcul&mode='.$mode.'&search_year='.$search_year.'&search_categ='.$search_categ.'">'.img_picto($langs->trans("ReCalculate").' ('.$dategenerated.')', 'refresh').''; + $linktoregenerate = 'id).((string) $type != '' ? '&type='.$type : '').'&action=recalcul&mode='.$mode.'&search_year='.$search_year.'&search_categ='.$search_categ.'">'.img_picto($langs->trans("ReCalculate").' ('.$dategenerated.')', 'refresh').''; // Show graph - print '
    '; + print '
    '; // Label print '"; // Last movement @@ -450,9 +450,9 @@ else } // Other attributes - include DOL_DOCUMENT_ROOT . '/core/tpl/extrafields_view.tpl.php'; + include DOL_DOCUMENT_ROOT.'/core/tpl/extrafields_view.tpl.php'; // Categories - if($conf->categorie->enabled) { + if ($conf->categorie->enabled) { print '"; @@ -476,8 +476,8 @@ else print "
    \n"; - $parameters=array(); - $reshook=$hookmanager->executeHooks('addMoreActionsButtons', $parameters, $object, $action); // Note that $action and $object may have been modified by hook + $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($action)) @@ -504,7 +504,7 @@ else /* ************************************************************************** */ print '
    '; - print '
    '; print $graphfiles[$key]['label']; @@ -436,7 +436,7 @@ if ($result || empty($id)) } } -if (! $id) +if (!$id) { dol_fiche_end(); } diff --git a/htdocs/product/stock/card.php b/htdocs/product/stock/card.php index 6ccc5d891a1..034e0076f09 100644 --- a/htdocs/product/stock/card.php +++ b/htdocs/product/stock/card.php @@ -33,28 +33,28 @@ require_once DOL_DOCUMENT_ROOT.'/core/lib/stock.lib.php'; require_once DOL_DOCUMENT_ROOT.'/core/lib/product.lib.php'; require_once DOL_DOCUMENT_ROOT.'/core/class/html.formcompany.class.php'; require_once DOL_DOCUMENT_ROOT.'/product/class/html.formproduct.class.php'; -require_once DOL_DOCUMENT_ROOT . '/core/class/extrafields.class.php'; +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->loadLangs(array('products', 'stocks', 'companies', 'categories')); -$action=GETPOST('action', 'aZ09'); -$cancel=GETPOST('cancel', 'alpha'); -$confirm=GETPOST('confirm'); +$action = GETPOST('action', 'aZ09'); +$cancel = GETPOST('cancel', 'alpha'); +$confirm = GETPOST('confirm'); $id = GETPOST('id', 'int'); $ref = GETPOST('ref', 'alpha'); $sortfield = GETPOST("sortfield", 'alpha'); $sortorder = GETPOST("sortorder", 'alpha'); -if (! $sortfield) $sortfield="p.ref"; -if (! $sortorder) $sortorder="DESC"; +if (!$sortfield) $sortfield = "p.ref"; +if (!$sortorder) $sortorder = "DESC"; -$backtopage=GETPOST('backtopage', 'alpha'); +$backtopage = GETPOST('backtopage', 'alpha'); // Security check //$result=restrictedArea($user,'stock', $id, 'entrepot&stock'); -$result=restrictedArea($user, 'stock'); +$result = restrictedArea($user, 'stock'); // Initialize technical object to manage hooks of page. Note that conf->hooks_modules contains array of hook context $hookmanager->initHooks(array('warehousecard', 'globalcard')); @@ -66,7 +66,7 @@ $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(); @@ -87,8 +87,8 @@ $usercanread = (($user->rights->stock->lire)); $usercancreate = (($user->rights->stock->creer)); $usercandelete = (($user->rights->stock->supprimer)); -$parameters=array('id'=>$id, 'ref'=>$ref); -$reshook=$hookmanager->executeHooks('doActions', $parameters, $object, $action); // Note that $action and $object may have been modified by some hooks +$parameters = array('id'=>$id, 'ref'=>$ref); +$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)) { @@ -106,7 +106,7 @@ if (empty($reshook)) $object->town = GETPOST("town"); $object->country_id = GETPOST("country_id"); - if (! empty($object->libelle)) + if (!empty($object->libelle)) { // Fill array 'array_options' with data from add form $ret = $extrafields->setOptionalsFromPost(null, $object); @@ -115,7 +115,7 @@ if (empty($reshook)) $action = 'create'; } - if (! $error) { + if (!$error) { $id = $object->create($user); if ($id > 0) { setEventMessages($langs->trans("RecordSaved"), null, 'mesgs'); @@ -123,10 +123,10 @@ if (empty($reshook)) $categories = GETPOST('categories', 'array'); $object->setCategories($categories); if (!empty($backtopage)) { - header("Location: " . $backtopage); + header("Location: ".$backtopage); exit; } else { - header("Location: card.php?id=" . $id); + header("Location: card.php?id=".$id); exit; } } else { @@ -138,7 +138,7 @@ if (empty($reshook)) else { setEventMessages($langs->trans("ErrorWarehouseRefRequired"), null, 'errors'); - $action="create"; // Force retour sur page creation + $action = "create"; // Force retour sur page creation } } @@ -146,7 +146,7 @@ if (empty($reshook)) if ($action == 'confirm_delete' && $confirm == 'yes' && $user->rights->stock->supprimer) { $object->fetch(GETPOST('id', 'int')); - $result=$object->delete($user); + $result = $object->delete($user); if ($result > 0) { setEventMessages($langs->trans("RecordDeleted"), null, 'mesgs'); @@ -156,7 +156,7 @@ if (empty($reshook)) else { setEventMessages($object->error, $object->errors, 'errors'); - $action=''; + $action = ''; } } @@ -179,7 +179,7 @@ if (empty($reshook)) $ret = $extrafields->setOptionalsFromPost(null, $object); if ($ret < 0) $error++; - if (! $error) { + if (!$error) { $ret = $object->update($id, $user); if ($ret < 0) $error++; } @@ -205,7 +205,7 @@ if (empty($reshook)) // Fill array 'array_options' with data from update form $ret = $extrafields->setOptionalsFromPost(null, $object, GETPOST('attribute', 'none')); if ($ret < 0) $error++; - if (! $error) { + if (!$error) { $result = $object->insertExtraFields(); if ($result < 0) { setEventMessages($object->error, $object->errors, 'errors'); @@ -232,13 +232,13 @@ if (empty($reshook)) * View */ -$productstatic=new Product($db); -$form=new Form($db); -$formproduct=new FormProduct($db); -$formcompany=new FormCompany($db); +$productstatic = new Product($db); +$form = new Form($db); +$formproduct = new FormProduct($db); +$formcompany = new FormCompany($db); $formfile = new FormFile($db); -$help_url='EN:Module_Stocks_En|FR:Module_Stock|ES:Módulo_Stocks'; +$help_url = 'EN:Module_Stocks_En|FR:Module_Stock|ES:Módulo_Stocks'; llxHeader("", $langs->trans("WarehouseCard"), $help_url); @@ -255,12 +255,12 @@ if ($action == 'create') dol_fiche_head(); - print ''; + print '
    '; // Ref print ''; - print ''; + print ''; // Parent entrepot print ''; print ''; // Zip / Town print ''; print ''; // Country print ''; // Status @@ -310,7 +310,7 @@ if ($action == 'create') print ''; // Other attributes - include DOL_DOCUMENT_ROOT . '/core/tpl/extrafields_add.tpl.php'; + include DOL_DOCUMENT_ROOT.'/core/tpl/extrafields_add.tpl.php'; if ($conf->categorie->enabled) { // Categories @@ -324,16 +324,16 @@ if ($action == 'create') dol_fiche_end(); print '
    '; - print ''; + print ''; print '     '; - print ''; + print ''; print '
    '; print ''; } else { - $id=GETPOST("id", 'int'); + $id = GETPOST("id", 'int'); if ($id > 0 || $ref) { $object = new Entrepot($db); @@ -364,8 +364,8 @@ else // Call Hook formConfirm $parameters = array(); $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; @@ -386,7 +386,7 @@ else print '
    '; print '
    '; - print '
    '.$langs->trans("Ref").'
    '.$langs->trans("LocationSummary").'
    '.$langs->trans("LocationSummary").'
    '.$langs->trans("AddIn").''; @@ -271,25 +271,25 @@ if ($action == 'create') print '
    '.$langs->trans("Description").''; // Editeur wysiwyg require_once DOL_DOCUMENT_ROOT.'/core/class/doleditor.class.php'; - $doleditor=new DolEditor('desc', (!empty($object->description)?$object->description:''), '', 180, 'dolibarr_notes', 'In', false, true, $conf->fckeditor->enabled, ROWS_5, '90%'); + $doleditor = new DolEditor('desc', (!empty($object->description) ? $object->description : ''), '', 180, 'dolibarr_notes', 'In', false, true, $conf->fckeditor->enabled, ROWS_5, '90%'); $doleditor->Create(); print '
    '.$langs->trans('Address').'
    '.$langs->trans('Zip').''; - print $formcompany->select_ziptown((!empty($object->zip)?$object->zip:''), 'zipcode', array('town','selectcountry_id','state_id'), 6); + print $formcompany->select_ziptown((!empty($object->zip) ? $object->zip : ''), 'zipcode', array('town', 'selectcountry_id', 'state_id'), 6); print '
    '.$langs->trans('Town').''; - print $formcompany->select_ziptown((!empty($object->town)?$object->town:''), 'town', array('zipcode','selectcountry_id','state_id')); + print $formcompany->select_ziptown((!empty($object->town) ? $object->town : ''), 'town', array('zipcode', 'selectcountry_id', 'state_id')); print '
    '.$langs->trans('Country').''; - print $form->select_country((!empty($object->country_id)?$object->country_id:$mysoc->country_code), 'country_id'); + print $form->select_country((!empty($object->country_id) ? $object->country_id : $mysoc->country_code), 'country_id'); if ($user->admin) print info_admin($langs->trans("YouCanChangeValuesForThisListFromDictionarySetup"), 1); print '
    '; + print '
    '; // Parent entrepot $e = new Entrepot($db); @@ -399,18 +399,18 @@ else // Description print ''; - $calcproductsunique=$object->nb_different_products(); - $calcproducts=$object->nb_products(); + $calcproductsunique = $object->nb_different_products(); + $calcproducts = $object->nb_products(); // Total nb of different products print '"; // Nb of products print '"; print '
    '.$langs->trans("Description").''.nl2br($object->description).'
    '.$langs->trans("NumberOfDifferentProducts").''; - print empty($calcproductsunique['nb'])?'0':$calcproductsunique['nb']; + print empty($calcproductsunique['nb']) ? '0' : $calcproductsunique['nb']; print "
    '.$langs->trans("NumberOfProducts").''; - $valtoshow=price2num($calcproducts['nb'], 'MS'); - print empty($valtoshow)?'0':$valtoshow; + $valtoshow = price2num($calcproducts['nb'], 'MS'); + print empty($valtoshow) ? '0' : $valtoshow; print "
    '; @@ -424,7 +424,7 @@ else // Value print '
    '.$langs->trans("EstimatedStockValueShort").''; - print price((empty($calcproducts['value'])?'0':price2num($calcproducts['value'], 'MT')), 0, $langs, 0, -1, -1, $conf->currency); + print price((empty($calcproducts['value']) ? '0' : price2num($calcproducts['value'], 'MT')), 0, $langs, 0, -1, -1, $conf->currency); print "
    '.$langs->trans("Categories").''; print $form->showCategories($object->id, 'warehouse', 1); print "
    '; + print '
    '; print ""; print_liste_field_titre("Product", "", "p.ref", "&id=".$id, "", "", $sortfield, $sortorder); print_liste_field_titre("Label", "", "p.label", "&id=".$id, "", "", $sortfield, $sortorder); @@ -525,16 +525,16 @@ else } print "\n"; - $totalunit=0; - $totalvalue=$totalvaluesell=0; + $totalunit = 0; + $totalvalue = $totalvaluesell = 0; $sql = "SELECT p.rowid as rowid, p.ref, p.label as produit, p.tobatch, p.fk_product_type as type, p.pmp as ppmp, p.price, p.price_ttc, p.entity,"; - $sql.= " ps.reel as value"; - $sql.= " FROM ".MAIN_DB_PREFIX."product_stock as ps, ".MAIN_DB_PREFIX."product as p"; - $sql.= " WHERE ps.fk_product = p.rowid"; - $sql.= " AND ps.reel <> 0"; // We do not show if stock is 0 (no product in this warehouse) - $sql.= " AND ps.fk_entrepot = ".$object->id; - $sql.= $db->order($sortfield, $sortorder); + $sql .= " ps.reel as value"; + $sql .= " FROM ".MAIN_DB_PREFIX."product_stock as ps, ".MAIN_DB_PREFIX."product as p"; + $sql .= " WHERE ps.fk_product = p.rowid"; + $sql .= " AND ps.reel <> 0"; // We do not show if stock is 0 (no product in this warehouse) + $sql .= " AND ps.fk_entrepot = ".$object->id; + $sql .= $db->order($sortfield, $sortorder); dol_syslog('List products', LOG_DEBUG); $resql = $db->query($sql); @@ -547,13 +547,13 @@ else $objp = $db->fetch_object($resql); // Multilangs - if (! empty($conf->global->MAIN_MULTILANGS)) // si l'option est active + if (!empty($conf->global->MAIN_MULTILANGS)) // si l'option est active { $sql = "SELECT label"; - $sql.= " FROM ".MAIN_DB_PREFIX."product_lang"; - $sql.= " WHERE fk_product=".$objp->rowid; - $sql.= " AND lang='". $langs->getDefaultLang() ."'"; - $sql.= " LIMIT 1"; + $sql .= " FROM ".MAIN_DB_PREFIX."product_lang"; + $sql .= " WHERE fk_product=".$objp->rowid; + $sql .= " AND lang='".$langs->getDefaultLang()."'"; + $sql .= " LIMIT 1"; $result = $db->query($sql); if ($result) @@ -567,12 +567,12 @@ else //print ''; print ''; print "'; @@ -580,31 +580,31 @@ else print ''; print ''; - $totalunit+=$objp->value; + $totalunit += $objp->value; // Price buy PMP print ''; // Total PMP - print ''; - $totalvalue+=price2num($objp->ppmp*$objp->value, 'MT'); + print ''; + $totalvalue += price2num($objp->ppmp * $objp->value, 'MT'); // Price sell min if (empty($conf->global->PRODUIT_MULTIPRICES)) { - $pricemin=$objp->price; + $pricemin = $objp->price; print ''; // Total sell min print ''; } - $totalvaluesell+=price2num($pricemin*$objp->value, 'MT'); + $totalvaluesell += price2num($pricemin * $objp->value, 'MT'); if ($user->rights->stock->mouvement->creer) { @@ -627,8 +627,8 @@ else print ''; print ''; print ''; print ''; @@ -665,7 +665,7 @@ else dol_fiche_head($head, 'card', $langs->trans("Warehouse"), 0, 'stock'); - print '
    '.dol_print_date($objp->datem).'
    "; - $productstatic->id=$objp->rowid; + $productstatic->id = $objp->rowid; $productstatic->ref = $objp->ref; $productstatic->label = $objp->produit; - $productstatic->type=$objp->type; - $productstatic->entity=$objp->entity; - $productstatic->status_batch=$objp->tobatch; + $productstatic->type = $objp->type; + $productstatic->entity = $objp->entity; + $productstatic->status_batch = $objp->tobatch; print $productstatic->getNomUrl(1, 'stock', 16); print ''.$objp->produit.''; - $valtoshow=price(price2num($objp->value, 'MS'), 0, '', 0, 0); // TODO replace with a qty() function - print empty($valtoshow)?'0':$valtoshow; + $valtoshow = price(price2num($objp->value, 'MS'), 0, '', 0, 0); // TODO replace with a qty() function + print empty($valtoshow) ? '0' : $valtoshow; print ''.price(price2num($objp->ppmp, 'MU')).''.price(price2num($objp->ppmp*$objp->value, 'MT')).''.price(price2num($objp->ppmp * $objp->value, 'MT')).''; print price(price2num($pricemin, 'MU'), 1); print ''; - print price(price2num($pricemin*$objp->value, 'MT'), 1); + print price(price2num($pricemin * $objp->value, 'MT'), 1); print '
    '.$langs->trans("Total").''; - $valtoshow=price2num($totalunit, 'MS'); - print empty($valtoshow)?'0':$valtoshow; + $valtoshow = price2num($totalunit, 'MS'); + print empty($valtoshow) ? '0' : $valtoshow; print ' '.price(price2num($totalvalue, 'MT')).'
    '; + print '
    '; // Ref print ''; @@ -681,7 +681,7 @@ else print ''; @@ -691,15 +691,15 @@ else // Zip / Town print ''; print ''; // Country print ''; @@ -721,12 +721,12 @@ else print ''; // Other attributes - $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 + $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)) { - print $object->showOptionals($extrafields, 'edit'); + print $object->showOptionals($extrafields, 'edit', $parameters); } // Tags-Categories if ($conf->categorie->enabled) @@ -735,8 +735,8 @@ else $cate_arbo = $form->select_all_categories(Categorie::TYPE_WAREHOUSE, '', 'parent', 64, 0, 1); $c = new Categorie($db); $cats = $c->containing($object->id, Categorie::TYPE_WAREHOUSE); - $arrayselected=array(); - foreach($cats as $cat) { + $arrayselected = array(); + foreach ($cats as $cat) { $arrayselected[] = $cat->id; } print $form->multiselectarray('categories', $cate_arbo, $arrayselected, '', 0, '', 0, '100%'); @@ -763,7 +763,7 @@ else if ($conf->global->MAIN_FEATURES_LEVEL >= 2) { - $modulepart='stock'; + $modulepart = 'stock'; if ($action != 'create' && $action != 'edit' && $action != 'delete') { @@ -773,28 +773,28 @@ if ($conf->global->MAIN_FEATURES_LEVEL >= 2) // Documents $objectref = dol_sanitizeFileName($object->ref); - $relativepath = $comref . '/' . $objectref . '.pdf'; - $filedir = $conf->stock->dir_output . '/' . $objectref; - $urlsource=$_SERVER["PHP_SELF"]."?id=".$object->id; - $genallowed=$usercanread; - $delallowed=$usercancreate; + $relativepath = $comref.'/'.$objectref.'.pdf'; + $filedir = $conf->stock->dir_output.'/'.$objectref; + $urlsource = $_SERVER["PHP_SELF"]."?id=".$object->id; + $genallowed = $usercanread; + $delallowed = $usercancreate; $modulepart = 'stock'; print $formfile->showdocuments($modulepart, $object->ref, $filedir, $urlsource, $genallowed, $delallowed, '', 0, 0, 0, 28, 0, '', 0, '', $object->default_lang, '', $object); - $somethingshown=$formfile->numoffiles; + $somethingshown = $formfile->numoffiles; print '
    '; $MAXEVENT = 10; $morehtmlright = ''; - $morehtmlright.= $langs->trans("SeeAll"); - $morehtmlright.= ''; + $morehtmlright .= $langs->trans("SeeAll"); + $morehtmlright .= ''; // List of actions on element - include_once DOL_DOCUMENT_ROOT . '/core/class/html.formactions.class.php'; + include_once DOL_DOCUMENT_ROOT.'/core/class/html.formactions.class.php'; $formactions = new FormActions($db); - $somethingshown = $formactions->showactions($object, 'stock', 0, 1, '', $MAXEVENT, '', $morehtmlright); // Show all action for product + $somethingshown = $formactions->showactions($object, 'stock', 0, 1, '', $MAXEVENT, '', $morehtmlright); // Show all action for product print '
    '; } diff --git a/htdocs/product/stock/class/productlot.class.php b/htdocs/product/stock/class/productlot.class.php index dbd0354cea3..e2d954b2847 100644 --- a/htdocs/product/stock/class/productlot.class.php +++ b/htdocs/product/stock/class/productlot.class.php @@ -26,7 +26,7 @@ */ // Put here all includes required by your class file -require_once DOL_DOCUMENT_ROOT . '/core/class/commonobject.class.php'; +require_once DOL_DOCUMENT_ROOT.'/core/class/commonobject.class.php'; //require_once DOL_DOCUMENT_ROOT . '/societe/class/societe.class.php'; //require_once DOL_DOCUMENT_ROOT . '/product/class/product.class.php'; @@ -48,7 +48,7 @@ class Productlot extends CommonObject /** * @var string String with name of icon for myobject. Must be the part after the 'object_' into object_myobject.png */ - public $picto='barcode'; + public $picto = 'barcode'; /** * 0=No test on entity, 1=Test with field entity, 2=Test with link by societe @@ -59,14 +59,14 @@ class Productlot extends CommonObject /** * @var array Array with all fields and their property. Do not use it as a static var. It may be modified by constructor. */ - public $fields=array( + public $fields = array( 'rowid' => array('type'=>'integer', 'label'=>'TechnicalID', 'enabled'=>1, 'visible'=>-2, 'notnull'=>1, 'index'=>1, 'position'=>1, 'comment'=>'Id'), - 'batch' =>array('type'=>'varchar(30)', 'label'=>'Batch', 'enabled'=>1, 'visible'=>1, 'notnull'=>0, 'showoncombobox'=>1, 'index'=>1, 'position'=>10, 'comment'=>'Batch'), - 'entity' =>array('type'=>'integer', 'label'=>'Entity', 'enabled'=>1, 'visible'=>0, 'default'=>1, 'notnull'=>1, 'index'=>1, 'position'=>20), - 'datec' =>array('type'=>'datetime', 'label'=>'DateCreation', 'enabled'=>1, 'visible'=>-2, 'notnull'=>1, 'position'=>500), - 'tms' =>array('type'=>'timestamp', 'label'=>'DateModification', 'enabled'=>1, 'visible'=>-2, 'notnull'=>1, 'position'=>501), - 'fk_user_author'=>array('type'=>'integer', 'label'=>'UserAuthor', 'enabled'=>1, 'visible'=>-2, 'notnull'=>1, 'position'=>510, 'foreignkey'=>'llx_user.rowid'), - 'fk_user_modif' =>array('type'=>'integer', 'label'=>'UserModif', 'enabled'=>1, 'visible'=>-2, 'notnull'=>-1, 'position'=>511) + 'batch' =>array('type'=>'varchar(30)', 'label'=>'Batch', 'enabled'=>1, 'visible'=>1, 'notnull'=>0, 'showoncombobox'=>1, 'index'=>1, 'position'=>10, 'comment'=>'Batch'), + 'entity' =>array('type'=>'integer', 'label'=>'Entity', 'enabled'=>1, 'visible'=>0, 'default'=>1, 'notnull'=>1, 'index'=>1, 'position'=>20), + 'datec' =>array('type'=>'datetime', 'label'=>'DateCreation', 'enabled'=>1, 'visible'=>-2, 'notnull'=>1, 'position'=>500), + 'tms' =>array('type'=>'timestamp', 'label'=>'DateModification', 'enabled'=>1, 'visible'=>-2, 'notnull'=>1, 'position'=>501), + 'fk_user_creat'=>array('type'=>'integer', 'label'=>'UserAuthor', 'enabled'=>1, 'visible'=>-2, 'notnull'=>1, 'position'=>510, 'foreignkey'=>'llx_user.rowid'), + 'fk_user_modif' =>array('type'=>'integer', 'label'=>'UserModif', 'enabled'=>1, 'visible'=>-2, 'notnull'=>-1, 'position'=>511) ); /** @@ -150,56 +150,56 @@ class Productlot extends CommonObject // Put here code to add control on parameters values // Insert request - $sql = 'INSERT INTO ' . MAIN_DB_PREFIX . $this->table_element . '('; - $sql.= 'entity,'; - $sql.= 'fk_product,'; - $sql.= 'batch,'; - $sql.= 'eatby,'; - $sql.= 'sellby,'; - $sql.= 'datec,'; - $sql.= 'fk_user_creat,'; - $sql.= 'fk_user_modif,'; - $sql.= 'import_key'; + $sql = 'INSERT INTO '.MAIN_DB_PREFIX.$this->table_element.'('; + $sql .= 'entity,'; + $sql .= 'fk_product,'; + $sql .= 'batch,'; + $sql .= 'eatby,'; + $sql .= 'sellby,'; + $sql .= 'datec,'; + $sql .= 'fk_user_creat,'; + $sql .= 'fk_user_modif,'; + $sql .= 'import_key'; $sql .= ') VALUES ('; - $sql .= ' '.(! isset($this->entity)?$conf->entity:$this->entity).','; - $sql .= ' '.(! isset($this->fk_product)?'NULL':$this->fk_product).','; - $sql .= ' '.(! isset($this->batch)?'NULL':"'".$this->db->escape($this->batch)."'").','; - $sql .= ' '.(! isset($this->eatby) || dol_strlen($this->eatby)==0?'NULL':"'".$this->db->idate($this->eatby)."'").','; - $sql .= ' '.(! isset($this->sellby) || dol_strlen($this->sellby)==0?'NULL':"'".$this->db->idate($this->sellby)."'").','; + $sql .= ' '.(!isset($this->entity) ? $conf->entity : $this->entity).','; + $sql .= ' '.(!isset($this->fk_product) ? 'NULL' : $this->fk_product).','; + $sql .= ' '.(!isset($this->batch) ? 'NULL' : "'".$this->db->escape($this->batch)."'").','; + $sql .= ' '.(!isset($this->eatby) || dol_strlen($this->eatby) == 0 ? 'NULL' : "'".$this->db->idate($this->eatby)."'").','; + $sql .= ' '.(!isset($this->sellby) || dol_strlen($this->sellby) == 0 ? 'NULL' : "'".$this->db->idate($this->sellby)."'").','; $sql .= ' '."'".$this->db->idate(dol_now())."'".','; - $sql .= ' '.(! isset($this->fk_user_creat)?'NULL':$this->fk_user_creat).','; - $sql .= ' '.(! isset($this->fk_user_modif)?'NULL':$this->fk_user_modif).','; - $sql .= ' '.(! isset($this->import_key)?'NULL':$this->import_key); + $sql .= ' '.(!isset($this->fk_user_creat) ? 'NULL' : $this->fk_user_creat).','; + $sql .= ' '.(!isset($this->fk_user_modif) ? 'NULL' : $this->fk_user_modif).','; + $sql .= ' '.(!isset($this->import_key) ? 'NULL' : $this->import_key); $sql .= ')'; $this->db->begin(); $resql = $this->db->query($sql); if (!$resql) { - $error ++; - $this->errors[] = 'Error ' . $this->db->lasterror(); - dol_syslog(__METHOD__ . ' ' . join(',', $this->errors), LOG_ERR); + $error++; + $this->errors[] = 'Error '.$this->db->lasterror(); + dol_syslog(__METHOD__.' '.join(',', $this->errors), LOG_ERR); } if (!$error) { - $this->id = $this->db->last_insert_id(MAIN_DB_PREFIX . $this->table_element); + $this->id = $this->db->last_insert_id(MAIN_DB_PREFIX.$this->table_element); // Actions on extra fields if (empty($conf->global->MAIN_EXTRAFIELDS_DISABLED)) // For avoid conflicts if trigger used { - $result=$this->insertExtraFields(); + $result = $this->insertExtraFields(); if ($result < 0) { $error++; } } - if (! $error && ! $notrigger) { + if (!$error && !$notrigger) { // Uncomment this and change MYOBJECT to your own tag if you // want this action to call a trigger. // Call triggers - $result=$this->call_trigger('PRODUCTLOT_CREATE', $user); + $result = $this->call_trigger('PRODUCTLOT_CREATE', $user); if ($result < 0) $error++; // End call triggers } @@ -209,7 +209,7 @@ class Productlot extends CommonObject if ($error) { $this->db->rollback(); - return - 1 * $error; + return -1 * $error; } else { $this->db->commit(); @@ -243,11 +243,11 @@ class Productlot extends CommonObject $sql .= " t.fk_user_creat,"; $sql .= " t.fk_user_modif,"; $sql .= " t.import_key"; - $sql .= ' FROM ' . MAIN_DB_PREFIX . $this->table_element . ' as t'; + $sql .= ' FROM '.MAIN_DB_PREFIX.$this->table_element.' as t'; if ($product_id > 0 && $batch != '') { - $sql .= " WHERE t.batch = '". $this->db->escape($batch) . "' AND t.fk_product = " . $product_id; + $sql .= " WHERE t.batch = '".$this->db->escape($batch)."' AND t.fk_product = ".$product_id; } else { - $sql .= ' WHERE t.rowid = ' . $id; + $sql .= ' WHERE t.rowid = '.$id; } $resql = $this->db->query($sql); @@ -261,7 +261,7 @@ class Productlot extends CommonObject //$this->ref = $obj->fk_product.'_'.$obj->batch; $this->batch = $obj->batch; - $this->entity = (!empty($obj->entity)?$obj->entity:$conf->entity); // Prevent "null" entity + $this->entity = (!empty($obj->entity) ? $obj->entity : $conf->entity); // Prevent "null" entity $this->fk_product = $obj->fk_product; $this->eatby = $this->db->jdate($obj->eatby); $this->sellby = $this->db->jdate($obj->sellby); @@ -283,10 +283,10 @@ class Productlot extends CommonObject return 0; } } else { - $this->errors[] = 'Error ' . $this->db->lasterror(); - dol_syslog(__METHOD__ . ' ' . join(',', $this->errors), LOG_ERR); + $this->errors[] = 'Error '.$this->db->lasterror(); + dol_syslog(__METHOD__.' '.join(',', $this->errors), LOG_ERR); - return - 1; + return -1; } } @@ -330,38 +330,38 @@ class Productlot extends CommonObject if (empty($this->oldcopy)) { - $org=new self($this->db); + $org = new self($this->db); $org->fetch($this->id); - $this->oldcopy=$org; + $this->oldcopy = $org; } // Update request - $sql = 'UPDATE ' . MAIN_DB_PREFIX . $this->table_element . ' SET'; - $sql .= ' entity = '.(isset($this->entity)?$this->entity:"null").','; - $sql .= ' fk_product = '.(isset($this->fk_product)?$this->fk_product:"null").','; - $sql .= ' batch = '.(isset($this->batch)?"'".$this->db->escape($this->batch)."'":"null").','; - $sql .= ' eatby = '.(! isset($this->eatby) || dol_strlen($this->eatby) != 0 ? "'".$this->db->idate($this->eatby)."'" : 'null').','; - $sql .= ' sellby = '.(! isset($this->sellby) || dol_strlen($this->sellby) != 0 ? "'".$this->db->idate($this->sellby)."'" : 'null').','; - $sql .= ' datec = '.(! isset($this->datec) || dol_strlen($this->datec) != 0 ? "'".$this->db->idate($this->datec)."'" : 'null').','; + $sql = 'UPDATE '.MAIN_DB_PREFIX.$this->table_element.' SET'; + $sql .= ' entity = '.(isset($this->entity) ? $this->entity : "null").','; + $sql .= ' fk_product = '.(isset($this->fk_product) ? $this->fk_product : "null").','; + $sql .= ' batch = '.(isset($this->batch) ? "'".$this->db->escape($this->batch)."'" : "null").','; + $sql .= ' eatby = '.(!isset($this->eatby) || dol_strlen($this->eatby) != 0 ? "'".$this->db->idate($this->eatby)."'" : 'null').','; + $sql .= ' sellby = '.(!isset($this->sellby) || dol_strlen($this->sellby) != 0 ? "'".$this->db->idate($this->sellby)."'" : 'null').','; + $sql .= ' datec = '.(!isset($this->datec) || dol_strlen($this->datec) != 0 ? "'".$this->db->idate($this->datec)."'" : 'null').','; $sql .= ' tms = '.(dol_strlen($this->tms) != 0 ? "'".$this->db->idate($this->tms)."'" : "'".$this->db->idate(dol_now())."'").','; - $sql .= ' fk_user_creat = '.(isset($this->fk_user_creat)?$this->fk_user_creat:"null").','; - $sql .= ' fk_user_modif = '.(isset($this->fk_user_modif)?$this->fk_user_modif:"null").','; - $sql .= ' import_key = '.(isset($this->import_key)?$this->import_key:"null"); - $sql .= ' WHERE rowid=' . $this->id; + $sql .= ' fk_user_creat = '.(isset($this->fk_user_creat) ? $this->fk_user_creat : "null").','; + $sql .= ' fk_user_modif = '.(isset($this->fk_user_modif) ? $this->fk_user_modif : "null").','; + $sql .= ' import_key = '.(isset($this->import_key) ? $this->import_key : "null"); + $sql .= ' WHERE rowid='.$this->id; $this->db->begin(); $resql = $this->db->query($sql); if (!$resql) { - $error ++; - $this->errors[] = 'Error ' . $this->db->lasterror(); - dol_syslog(__METHOD__ . ' ' . join(',', $this->errors), LOG_ERR); + $error++; + $this->errors[] = 'Error '.$this->db->lasterror(); + dol_syslog(__METHOD__.' '.join(',', $this->errors), LOG_ERR); } // Actions on extra fields if (empty($conf->global->MAIN_EXTRAFIELDS_DISABLED)) // For avoid conflicts if trigger used { - $result=$this->insertExtraFields(); + $result = $this->insertExtraFields(); if ($result < 0) { $error++; @@ -370,7 +370,7 @@ class Productlot extends CommonObject if (!$error && !$notrigger) { // Call triggers - $result=$this->call_trigger('PRODUCTLOT_MODIFY', $user); + $result = $this->call_trigger('PRODUCTLOT_MODIFY', $user); if ($result < 0) { $error++; } // End call triggers } @@ -379,7 +379,7 @@ class Productlot extends CommonObject if ($error) { $this->db->rollback(); - return - 1 * $error; + return -1 * $error; } else { $this->db->commit(); @@ -416,14 +416,14 @@ class Productlot extends CommonObject //} if (!$error) { - $sql = 'DELETE FROM ' . MAIN_DB_PREFIX . $this->table_element; - $sql .= ' WHERE rowid=' . $this->id; + $sql = 'DELETE FROM '.MAIN_DB_PREFIX.$this->table_element; + $sql .= ' WHERE rowid='.$this->id; $resql = $this->db->query($sql); if (!$resql) { - $error ++; - $this->errors[] = 'Error ' . $this->db->lasterror(); - dol_syslog(__METHOD__ . ' ' . join(',', $this->errors), LOG_ERR); + $error++; + $this->errors[] = 'Error '.$this->db->lasterror(); + dol_syslog(__METHOD__.' '.join(',', $this->errors), LOG_ERR); } } @@ -431,7 +431,7 @@ class Productlot extends CommonObject if ($error) { $this->db->rollback(); - return - 1 * $error; + return -1 * $error; } else { $this->db->commit(); @@ -469,9 +469,9 @@ class Productlot extends CommonObject // Other options if ($result < 0) { - $error ++; + $error++; $this->errors = $object->errors; - dol_syslog(__METHOD__ . ' ' . join(',', $this->errors), LOG_ERR); + dol_syslog(__METHOD__.' '.join(',', $this->errors), LOG_ERR); } unset($object->context['createfromclone']); @@ -484,7 +484,7 @@ class Productlot extends CommonObject } else { $this->db->rollback(); - return - 1; + return -1; } } @@ -539,16 +539,16 @@ class Productlot extends CommonObject $result = ''; - $label = '' . $langs->trans("Batch") . ''; - $label.= '
    '; - $label.= '' . $langs->trans('Batch') . ': ' . $this->batch; + $label = ''.$langs->trans("Batch").''; + $label .= '
    '; + $label .= ''.$langs->trans('Batch').': '.$this->batch; if ($this->eatby) { - $label.= '
    ' . $langs->trans('EatByDate') . ': ' . dol_print_date($this->eatby, 'day'); + $label .= '
    '.$langs->trans('EatByDate').': '.dol_print_date($this->eatby, 'day'); } if ($this->sellby) { - $label.= '
    ' . $langs->trans('SellByDate') . ': ' . dol_print_date($this->sellby, 'day'); + $label .= '
    '.$langs->trans('SellByDate').': '.dol_print_date($this->sellby, 'day'); } $url = DOL_URL_ROOT.'/product/stock/productlot_card.php?id='.$this->id; @@ -556,31 +556,31 @@ class Productlot extends CommonObject 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'; + $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=''; + $linkclose = ''; if (empty($notooltip)) { - if (! empty($conf->global->MAIN_OPTIMIZEFORTEXTBROWSER)) + if (!empty($conf->global->MAIN_OPTIMIZEFORTEXTBROWSER)) { - $label=$langs->trans("ShowMyObject"); - $linkclose.=' alt="'.dol_escape_htmltag($label, 1).'"'; + $label = $langs->trans("ShowMyObject"); + $linkclose .= ' alt="'.dol_escape_htmltag($label, 1).'"'; } - $linkclose.=' title="'.dol_escape_htmltag($label, 1).'"'; - $linkclose.=' class="classfortooltip'.($morecss?' '.$morecss:'').'"'; + $linkclose .= ' title="'.dol_escape_htmltag($label, 1).'"'; + $linkclose .= ' class="classfortooltip'.($morecss ? ' '.$morecss : '').'"'; } - else $linkclose = ($morecss?' class="'.$morecss.'"':''); + else $linkclose = ($morecss ? ' class="'.$morecss.'"' : ''); $linkstart = ''; - $linkend=''; + $linkstart .= $linkclose.'>'; + $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->batch; + 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->batch; $result .= $linkend; return $result; diff --git a/htdocs/product/stock/fiche-valo.php b/htdocs/product/stock/fiche-valo.php index c6eed274793..838c01b7b6f 100644 --- a/htdocs/product/stock/fiche-valo.php +++ b/htdocs/product/stock/fiche-valo.php @@ -60,7 +60,7 @@ if ($_GET["id"]) dol_fiche_head($head, 'value', $langs->trans("Warehouse"), 0, 'stock'); - print '
    '.$langs->trans("Ref").'
    '.$langs->trans("Description").''; // Editeur wysiwyg require_once DOL_DOCUMENT_ROOT.'/core/class/doleditor.class.php'; - $doleditor=new DolEditor('desc', $object->description, '', 180, 'dolibarr_notes', 'In', false, true, $conf->fckeditor->enabled, ROWS_5, '90%'); + $doleditor = new DolEditor('desc', $object->description, '', 180, 'dolibarr_notes', 'In', false, true, $conf->fckeditor->enabled, ROWS_5, '90%'); $doleditor->Create(); print '
    '.$langs->trans('Zip').''; - print $formcompany->select_ziptown($object->zip, 'zipcode', array('town','selectcountry_id','state_id'), 6); + print $formcompany->select_ziptown($object->zip, 'zipcode', array('town', 'selectcountry_id', 'state_id'), 6); print '
    '.$langs->trans('Town').''; - print $formcompany->select_ziptown($object->town, 'town', array('zipcode','selectcountry_id','state_id')); + print $formcompany->select_ziptown($object->town, 'town', array('zipcode', 'selectcountry_id', 'state_id')); print '
    '.$langs->trans('Country').''; - print $form->select_country($object->country_id?$object->country_id:$mysoc->country_code, 'country_id'); + print $form->select_country($object->country_id ? $object->country_id : $mysoc->country_code, 'country_id'); if ($user->admin) print info_admin($langs->trans("YouCanChangeValuesForThisListFromDictionarySetup"), 1); print '
    '; + print '
    '; // Ref print '
    '.$langs->trans("Ref").''; diff --git a/htdocs/product/stock/index.php b/htdocs/product/stock/index.php index 496d4b4f109..ea39a0caf42 100644 --- a/htdocs/product/stock/index.php +++ b/htdocs/product/stock/index.php @@ -62,7 +62,7 @@ if (! empty($conf->global->MAIN_SEARCH_FORM_ON_HOME_AREAS)) // This is usele print '
    '; print ''; print '
    '; - print ''; + print '
    '; print ""; print ''; print "
    '.$langs->trans("Search").'
    "; @@ -87,7 +87,7 @@ if ($result) $i = 0; print '
    '; - print ''; + print '
    '; print ''; if ($num) @@ -141,7 +141,7 @@ if ($resql) $num = $db->num_rows($resql); print '
    '; - print '
    '.$langs->trans("Warehouses").'
    '; + print '
    '; print ""; print ''; print ''; diff --git a/htdocs/product/stock/list.php b/htdocs/product/stock/list.php index a87f1a28621..23efeb0cf6d 100644 --- a/htdocs/product/stock/list.php +++ b/htdocs/product/stock/list.php @@ -28,25 +28,25 @@ require '../../main.inc.php'; require_once DOL_DOCUMENT_ROOT.'/product/stock/class/entrepot.class.php'; // Load translation files required by the page -$langs->loadLangs(array("stocks","other")); +$langs->loadLangs(array("stocks", "other")); -$action = GETPOST('action', 'aZ09')?GETPOST('action', 'aZ09'):'view'; // The action 'add', 'create', 'edit', 'update', 'view', ... -$massaction = GETPOST('massaction', 'alpha'); // The bulk action (combo box choice into lists) -$show_files = GETPOST('show_files', 'int'); // Show files area generated by bulk actions ? -$confirm = GETPOST('confirm', 'alpha'); // Result of a confirmation -$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'):'stocklist'; // 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') +$action = GETPOST('action', 'aZ09') ?GETPOST('action', 'aZ09') : 'view'; // The action 'add', 'create', 'edit', 'update', 'view', ... +$massaction = GETPOST('massaction', 'alpha'); // The bulk action (combo box choice into lists) +$show_files = GETPOST('show_files', 'int'); // Show files area generated by bulk actions ? +$confirm = GETPOST('confirm', 'alpha'); // Result of a confirmation +$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') : 'stocklist'; // 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') -$search_all=trim((GETPOST('search_all', 'alphanohtml')!='')?GETPOST('search_all', 'alphanohtml'):GETPOST('sall', 'alphanohtml')); -$search_ref=GETPOST("sref", "alpha")?GETPOST("sref", "alpha"):GETPOST("search_ref", "alpha"); -$search_label=GETPOST("snom", "alpha")?GETPOST("snom", "alpha"):GETPOST("search_label", "alpha"); -$search_status=GETPOST("search_status", "int"); +$search_all = trim((GETPOST('search_all', 'alphanohtml') != '') ?GETPOST('search_all', 'alphanohtml') : GETPOST('sall', 'alphanohtml')); +$search_ref = GETPOST("sref", "alpha") ?GETPOST("sref", "alpha") : GETPOST("search_ref", "alpha"); +$search_label = GETPOST("snom", "alpha") ?GETPOST("snom", "alpha") : GETPOST("search_label", "alpha"); +$search_status = GETPOST("search_status", "int"); // Load variable for pagination -$limit = GETPOST('limit', 'int')?GETPOST('limit', 'int'):$conf->liste_limit; +$limit = GETPOST('limit', 'int') ?GETPOST('limit', 'int') : $conf->liste_limit; $sortfield = GETPOST('sortfield', 'alpha'); $sortorder = GETPOST('sortorder', 'alpha'); $page = GETPOST('page', 'int'); @@ -54,11 +54,11 @@ if (empty($page) || $page == -1 || GETPOST('button_search', 'alpha') || GETPOST( $offset = $limit * $page; $pageprev = $page - 1; $pagenext = $page + 1; -if (! $sortfield) $sortfield="e.ref"; -if (! $sortorder) $sortorder="ASC"; +if (!$sortfield) $sortfield = "e.ref"; +if (!$sortorder) $sortorder = "ASC"; // Security check -$result=restrictedArea($user, 'stock'); +$result = restrictedArea($user, 'stock'); $year = strftime("%Y", time()); @@ -66,13 +66,13 @@ $year = strftime("%Y", time()); // Initialize technical object to manage hooks of page. Note that conf->hooks_modules contains array of hook context $object = new Entrepot($db); $extrafields = new ExtraFields($db); -$diroutputmassaction=$conf->inventory->dir_output . '/temp/massgeneration/'.$user->id; +$diroutputmassaction = $conf->inventory->dir_output.'/temp/massgeneration/'.$user->id; $hookmanager->initHooks(array('stocklist')); // Fetch optionals attributes and labels $extrafields->fetch_name_optionals_label($object->table_element); -$search_array_options=$extrafields->getOptionalsFromPost($object->table_element, '', 'search_'); +$search_array_options = $extrafields->getOptionalsFromPost($object->table_element, '', 'search_'); // List of fields to search into when doing a "search in all" @@ -86,23 +86,23 @@ $fieldstosearchall = array( ); // Definition of fields for list -$arrayfields=array( +$arrayfields = array( 'stockqty'=>array('type'=>'float', 'label'=>'PhysicalStock', 'enabled'=>1, 'visible'=>-2, 'position'=>70), 'estimatedvalue'=>array('type'=>'float', 'label'=>'EstimatedStockValue', 'enabled'=>1, 'visible'=>-2, 'position'=>71), 'sellvalue'=>array('type'=>'float', 'label'=>'EstimatedStockValueSell', 'enabled'=>1, 'visible'=>-2, 'position'=>72), ); -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) + 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], 'checked'=>(($extrafields->attributes[$object->table_element]['list'][$key]<0)?0:1), 'position'=>$extrafields->attributes[$object->table_element]['pos'][$key], 'enabled'=>(abs($extrafields->attributes[$object->table_element]['list'][$key])!=3 && $extrafields->attributes[$object->table_element]['perms'][$key])); + if (!empty($extrafields->attributes[$object->table_element]['list'][$key])) + $arrayfields["ef.".$key] = array('label'=>$extrafields->attributes[$object->table_element]['label'][$key], 'checked'=>(($extrafields->attributes[$object->table_element]['list'][$key] < 0) ? 0 : 1), 'position'=>$extrafields->attributes[$object->table_element]['pos'][$key], 'enabled'=>(abs($extrafields->attributes[$object->table_element]['list'][$key]) != 3 && $extrafields->attributes[$object->table_element]['perms'][$key])); } } $object->fields = dol_sort_array($object->fields, 'position'); @@ -113,11 +113,11 @@ $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(); -$reshook=$hookmanager->executeHooks('doActions', $parameters, $object, $action); // Note that $action and $object may have been modified by some hooks +$parameters = array(); +$reshook = $hookmanager->executeHooks('doActions', $parameters, $object, $action); // Note that $action and $object may have been modified by some hooks if ($reshook < 0) setEventMessages($hookmanager->error, $hookmanager->errors, 'errors'); if (empty($reshook)) @@ -126,24 +126,24 @@ if (empty($reshook)) 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=""; - $sall=""; - $search_label=""; - $search_status=""; - $toselect=''; - $search_array_options=array(); + $search_ref = ""; + $sall = ""; + $search_label = ""; + $search_status = ""; + $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')) { - $massaction=''; // Protection to avoid mass action if we force a new search during a mass action confirmation + $massaction = ''; // Protection to avoid mass action if we force a new search during a mass action confirmation } // Mass actions - $objectclass='Entrepot'; - $objectlabel='Warehouse'; + $objectclass = 'Entrepot'; + $objectlabel = 'Warehouse'; $permissiontoread = $user->rights->stock->lire; $permissiontodelete = $user->rights->stock->supprimer; $uploaddir = $conf->stock->dir_output; @@ -155,48 +155,48 @@ if (empty($reshook)) * View */ -$form=new Form($db); -$warehouse=new Entrepot($db); +$form = new Form($db); +$warehouse = new Entrepot($db); -$now=dol_now(); +$now = dol_now(); -$help_url='EN:Module_Stocks_En|FR:Module_Stock|ES:Módulo_Stocks'; +$help_url = 'EN:Module_Stocks_En|FR:Module_Stock|ES:Módulo_Stocks'; $title = $langs->trans("ListOfWarehouses"); // Build and execute select // -------------------------------------------------------------------- $sql = "SELECT e.rowid, e.ref, e.statut, e.lieu, e.address, e.zip, e.town, e.fk_pays, e.fk_parent,"; -$sql.= " SUM(p.pmp * ps.reel) as estimatedvalue, SUM(p.price * ps.reel) as sellvalue, SUM(ps.reel) as stockqty"; +$sql .= " SUM(p.pmp * ps.reel) as estimatedvalue, SUM(p.price * ps.reel) as sellvalue, SUM(ps.reel) as stockqty"; // Add fields from extrafields -if (! empty($extrafields->attributes[$object->table_element]['label'])) { +if (!empty($extrafields->attributes[$object->table_element]['label'])) { foreach ($extrafields->attributes[$object->table_element]['label'] as $key => $val) { - $sql.=($extrafields->attributes[$object->table_element]['type'][$key] != 'separate' ? ", ef.".$key.' as options_'.$key : ''); + $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, $object); // Note that $action and $object may have been modified by hook -$sql.=$hookmanager->resPrint; -$sql=preg_replace('/,\s*$/', '', $sql); -$sql.= " FROM ".MAIN_DB_PREFIX.$object->table_element." as e"; -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 (e.rowid = ef.fk_object)"; -$sql.= " LEFT JOIN ".MAIN_DB_PREFIX."product_stock as ps ON e.rowid = ps.fk_entrepot"; -$sql.= " LEFT JOIN ".MAIN_DB_PREFIX."product as p ON ps.fk_product = p.rowid"; -$sql.= " WHERE e.entity IN (".getEntity('stock').")"; -if ($search_ref) $sql.= natural_search("e.ref", $search_ref); // ref -if ($search_label) $sql.= natural_search("e.lieu", $search_label); // label -if ($search_status != '' && $search_status >= 0) $sql.= " AND e.statut = ".$search_status; +$parameters = array(); +$reshook = $hookmanager->executeHooks('printFieldListSelect', $parameters, $object); // Note that $action and $object may have been modified by hook +$sql .= $hookmanager->resPrint; +$sql = preg_replace('/,\s*$/', '', $sql); +$sql .= " FROM ".MAIN_DB_PREFIX.$object->table_element." as e"; +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 (e.rowid = ef.fk_object)"; +$sql .= " LEFT JOIN ".MAIN_DB_PREFIX."product_stock as ps ON e.rowid = ps.fk_entrepot"; +$sql .= " LEFT JOIN ".MAIN_DB_PREFIX."product as p ON ps.fk_product = p.rowid"; +$sql .= " WHERE e.entity IN (".getEntity('stock').")"; +if ($search_ref) $sql .= natural_search("e.ref", $search_ref); // ref +if ($search_label) $sql .= natural_search("e.lieu", $search_label); // label +if ($search_status != '' && $search_status >= 0) $sql .= " AND e.statut = ".$search_status; 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 -$parameters=array(); -$reshook=$hookmanager->executeHooks('printFieldListWhere', $parameters, $object); // Note that $action and $object may have been modified by hook -$sql.=$hookmanager->resPrint; -$sql.= " GROUP BY e.rowid, e.ref, e.statut, e.lieu, e.address, e.zip, e.town, e.fk_pays, e.fk_parent"; -$totalnboflines=0; -$result=$db->query($sql); +$parameters = array(); +$reshook = $hookmanager->executeHooks('printFieldListWhere', $parameters, $object); // Note that $action and $object may have been modified by hook +$sql .= $hookmanager->resPrint; +$sql .= " GROUP BY e.rowid, e.ref, e.statut, e.lieu, e.address, e.zip, e.town, e.fk_pays, e.fk_parent"; +$totalnboflines = 0; +$result = $db->query($sql); if ($result) { $totalnboflines = $db->num_rows($result); @@ -211,7 +211,7 @@ if ($result) $line++; } } -$sql.= $db->order($sortfield, $sortorder); +$sql .= $db->order($sortfield, $sortorder); // Count total nb of records $nbtotalofrecords = ''; @@ -232,10 +232,10 @@ if (is_numeric($nbtotalofrecords) && $limit > $nbtotalofrecords) } else { - $sql.= $db->plimit($limit+1, $offset); + $sql .= $db->plimit($limit + 1, $offset); - $resql=$db->query($sql); - if (! $resql) + $resql = $db->query($sql); + if (!$resql) { dol_print_error($db); exit; @@ -245,7 +245,7 @@ else } // Direct jump if only one record found -if ($num == 1 && ! empty($conf->global->MAIN_SEARCH_DIRECT_OPEN_IF_ONLY_ONE) && $search_all) +if ($num == 1 && !empty($conf->global->MAIN_SEARCH_DIRECT_OPEN_IF_ONLY_ONE) && $search_all) { $obj = $db->fetch_object($resql); $id = $obj->rowid; @@ -259,27 +259,27 @@ if ($num == 1 && ! empty($conf->global->MAIN_SEARCH_DIRECT_OPEN_IF_ONLY_ONE) && llxHeader('', $title, $help_url); -$arrayofselected=is_array($toselect)?$toselect:array(); +$arrayofselected = is_array($toselect) ? $toselect : array(); -$param=''; -if (! empty($contextpage) && $contextpage != $_SERVER["PHP_SELF"]) $param.='&contextpage='.urlencode($contextpage); -if ($limit > 0 && $limit != $conf->liste_limit) $param.='&limit='.urlencode($limit); -if ($search_ref) $param.="&search_ref=".urlencode($search_ref); -if ($search_label) $param.="&search_label=".urlencode($search_label); -if ($search_status) $param.="&search_status=".urlencode($search_status); -if ($search_all) $param.="&search_all=".urlencode($search_all); -if ($optioncss != '') $param.='&optioncss='.urlencode($optioncss); +$param = ''; +if (!empty($contextpage) && $contextpage != $_SERVER["PHP_SELF"]) $param .= '&contextpage='.urlencode($contextpage); +if ($limit > 0 && $limit != $conf->liste_limit) $param .= '&limit='.urlencode($limit); +if ($search_ref) $param .= "&search_ref=".urlencode($search_ref); +if ($search_label) $param .= "&search_label=".urlencode($search_label); +if ($search_status) $param .= "&search_status=".urlencode($search_status); +if ($search_all) $param .= "&search_all=".urlencode($search_all); +if ($optioncss != '') $param .= '&optioncss='.urlencode($optioncss); // Add $param from extra fields include DOL_DOCUMENT_ROOT.'/core/tpl/extrafields_list_search_param.tpl.php'; // List of mass actions available -$arrayofmassactions = array( +$arrayofmassactions = array( //'presend'=>$langs->trans("SendByMail"), //'builddoc'=>$langs->trans("PDFMerge"), ); //if ($user->rights->stock->supprimer) $arrayofmassactions['predelete']=''.$langs->trans("Delete"); -if (GETPOST('nomassaction', 'int') || in_array($massaction, array('presend','predelete'))) $arrayofmassactions=array(); -$massactionbutton=$form->selectMassAction('', $arrayofmassactions); +if (GETPOST('nomassaction', 'int') || in_array($massaction, array('presend', 'predelete'))) $arrayofmassactions = array(); +$massactionbutton = $form->selectMassAction('', $arrayofmassactions); print ''; if ($optioncss != '') print ''; @@ -296,17 +296,17 @@ $newcardbutton = dolGetButtonTitle($langs->trans('MenuNewWarehouse'), '', 'fa fa print_barre_liste($title, $page, $_SERVER["PHP_SELF"], $param, $sortfield, $sortorder, $massactionbutton, $num, $nbtotalofrecords, 'generic', 0, $newcardbutton, '', $limit); // Add code for pre mass action (confirmation or email presend form) -$topicmail="Information"; -$modelmail="warehouse"; -$objecttmp=new Entrepot($db); -$trackid='ware'.$object->id; +$topicmail = "Information"; +$modelmail = "warehouse"; +$objecttmp = new Entrepot($db); +$trackid = 'ware'.$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); - print '
    '.$langs->trans("FilterOnInto", $sall) . join(', ', $fieldstosearchall).'
    '; + foreach ($fieldstosearchall as $key => $val) $fieldstosearchall[$key] = $langs->trans($val); + print '
    '.$langs->trans("FilterOnInto", $sall).join(', ', $fieldstosearchall).'
    '; } $moreforfilter = ''; @@ -314,24 +314,24 @@ $moreforfilter = ''; $moreforfilter.= $langs->trans('MyFilter') . ': '; $moreforfilter.= '';*/ -$parameters=array(); -$reshook=$hookmanager->executeHooks('printFieldPreListTitle', $parameters, $object); // Note that $action and $object may have been modified by hook +$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($moreforfilter)) +if (!empty($moreforfilter)) { print '
    '; print $moreforfilter; print '
    '; } -$varpage=empty($contextpage)?$_SERVER["PHP_SELF"]:$contextpage; -$selectedfields=$form->multiSelectArrayWithCheckbox('selectedfields', $arrayfields, $varpage); // This also change content of $arrayfields -$selectedfields.=(count($arrayofmassactions) ? $form->showCheckAddButtons('checkforselect', 1) : ''); +$varpage = empty($contextpage) ? $_SERVER["PHP_SELF"] : $contextpage; +$selectedfields = $form->multiSelectArrayWithCheckbox('selectedfields', $arrayfields, $varpage); // This also change content of $arrayfields +$selectedfields .= (count($arrayofmassactions) ? $form->showCheckAddButtons('checkforselect', 1) : ''); -print '
    '; // You can use div-table-responsive-no-min if you dont need reserved height for your table -print '
    '.$langs->trans("LastMovements", min($num, $max)).''.$langs->trans("Product").'
    '."\n"; +print '
    '; // You can use div-table-responsive-no-min if you dont need reserved height for your table +print '
    '."\n"; // Fields title search // -------------------------------------------------------------------- @@ -352,8 +352,8 @@ print ''; // Extra fields include DOL_DOCUMENT_ROOT.'/core/tpl/extrafields_list_search_input.tpl.php'; // Fields from hook -$parameters=array('arrayfields'=>$arrayfields); -$reshook=$hookmanager->executeHooks('printFieldListOption', $parameters, $object); // Note that $action and $object may have been modified by hook +$parameters = array('arrayfields'=>$arrayfields); +$reshook = $hookmanager->executeHooks('printFieldListOption', $parameters, $object); // Note that $action and $object may have been modified by hook print $hookmanager->resPrint; // Status @@ -363,7 +363,7 @@ print ''; // Action column print ''; print ''."\n"; @@ -379,8 +379,8 @@ print_liste_field_titre("EstimatedStockValueSell", $_SERVER["PHP_SELF"], "", '', // 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, $object); // Note that $action and $object may have been modified by hook +$parameters = array('arrayfields'=>$arrayfields, 'param'=>$param, 'sortfield'=>$sortfield, 'sortorder'=>$sortorder); +$reshook = $hookmanager->executeHooks('printFieldListTitle', $parameters, $object); // Note that $action and $object may have been modified by hook print $hookmanager->resPrint; print_liste_field_titre("Status", $_SERVER["PHP_SELF"], "e.statut", '', $param, '', $sortfield, $sortorder, 'right '); // Action column @@ -389,17 +389,17 @@ print ''."\n"; // Loop on record // -------------------------------------------------------------------- -$i=0; -$totalarray=array(); +$i = 0; +$totalarray = array(); if ($num) { - $warehouse=new Entrepot($db); + $warehouse = new Entrepot($db); - $totalarray=array(); + $totalarray = array(); while ($i < min($num, $limit)) { $obj = $db->fetch_object($resql); - if (empty($obj)) break; // Should not happen + if (empty($obj)) break; // Should not happen $warehouse->id = $obj->rowid; $warehouse->ref = $obj->ref; @@ -410,55 +410,55 @@ if ($num) // Show here line of result print ''; - print ''; - if (! $i) $totalarray['nbfield']++; + print ''; + if (!$i) $totalarray['nbfield']++; // Location print ''; - if (! $i) $totalarray['nbfield']++; + if (!$i) $totalarray['nbfield']++; // Stock qty print ''; - if (! $i) $totalarray['nbfield']++; + if (!$i) $totalarray['nbfield']++; // PMP value print ''; - if (! $i) $totalarray['nbfield']++; + if (!$i) $totalarray['nbfield']++; // Selling value print ''; - if (! $i) $totalarray['nbfield']++; + if (!$i) $totalarray['nbfield']++; // Extra fields include DOL_DOCUMENT_ROOT.'/core/tpl/extrafields_list_print_fields.tpl.php'; // Fields from hook - $parameters=array('arrayfields'=>$arrayfields, 'obj'=>$obj); - $reshook=$hookmanager->executeHooks('printFieldListValue', $parameters, $object); // Note that $action and $object may have been modified by hook + $parameters = array('arrayfields'=>$arrayfields, 'obj'=>$obj); + $reshook = $hookmanager->executeHooks('printFieldListValue', $parameters, $object); // Note that $action and $object may have been modified by hook print $hookmanager->resPrint; // Status print ''; - if (! $i) $totalarray['nbfield']++; + if (!$i) $totalarray['nbfield']++; // Action column print ''; - if (! $i) $totalarray['nbfield']++; + if (!$i) $totalarray['nbfield']++; print ''."\n"; @@ -466,7 +466,7 @@ if ($num) $i++; } - if ($totalnboflines-$offset <= $limit) + if ($totalnboflines - $offset <= $limit) { print ''; print ''; @@ -476,7 +476,7 @@ if ($num) if (empty($conf->global->PRODUIT_MULTIPRICES)) print price(price2num($totalsell, 'MT'), 1, $langs, 0, 0, -1, $conf->currency); else { - $htmltext=$langs->trans("OptionMULTIPRICESIsOn"); + $htmltext = $langs->trans("OptionMULTIPRICESIsOn"); print $form->textwithtooltip($langs->trans("Variable"), $htmltext); } print ''; @@ -488,8 +488,8 @@ if ($num) $db->free($resql); -$parameters=array('arrayfields'=>$arrayfields, 'sql'=>$sql); -$reshook=$hookmanager->executeHooks('printFieldListFooter', $parameters, $object); // Note that $action and $object may have been modified by hook +$parameters = array('arrayfields'=>$arrayfields, 'sql'=>$sql); +$reshook = $hookmanager->executeHooks('printFieldListFooter', $parameters, $object); // Note that $action and $object may have been modified by hook print $hookmanager->resPrint; print '
    '; -$searchpicto=$form->showFilterButtons(); +$searchpicto = $form->showFilterButtons(); print $searchpicto; print '
    ' . $warehouse->getNomUrl(1) . ''.$warehouse->getNomUrl(1).''.$obj->lieu.''.price2num($obj->stockqty, 5).''; if (price2num($obj->estimatedvalue, 'MT')) print price(price2num($obj->estimatedvalue, 'MT'), 1); else print ''; print ''; if (empty($conf->global->PRODUIT_MULTIPRICES)) print price(price2num($obj->sellvalue, 'MT'), 1); else { - $htmltext=$langs->trans("OptionMULTIPRICESIsOn"); + $htmltext = $langs->trans("OptionMULTIPRICESIsOn"); print $form->textwithtooltip($langs->trans("Variable"), $htmltext); } print ''.$warehouse->LibStatut($obj->statut, 5).''; if ($massactionbutton || $massaction) // If we are in select mode (massactionbutton defined) or if we have already selected and sent an action ($massaction) defined { - $selected=0; - if (in_array($obj->rowid, $arrayofselected)) $selected=1; - print ''; + $selected = 0; + if (in_array($obj->rowid, $arrayofselected)) $selected = 1; + print ''; } print '
    '.$langs->trans("Total").'
    '."\n"; @@ -499,19 +499,19 @@ print ''."\n"; if (in_array('builddoc', $arrayofmassactions) && ($nbtotalofrecords === '' || $nbtotalofrecords)) { - $hidegeneratedfilelistifempty=1; - if ($massaction == 'builddoc' || $action == 'remove_file' || $show_files) $hidegeneratedfilelistifempty=0; + $hidegeneratedfilelistifempty = 1; + 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); // Show list of available documents - $urlsource=$_SERVER['PHP_SELF'].'?sortfield='.$sortfield.'&sortorder='.$sortorder; - $urlsource.=str_replace('&', '&', $param); + $urlsource = $_SERVER['PHP_SELF'].'?sortfield='.$sortfield.'&sortorder='.$sortorder; + $urlsource .= str_replace('&', '&', $param); - $filedir=$diroutputmassaction; - $genallowed=$user->rights->mymodule->read; - $delallowed=$user->rights->mymodule->create; + $filedir = $diroutputmassaction; + $genallowed = $user->rights->mymodule->read; + $delallowed = $user->rights->mymodule->create; print $formfile->showdocuments('massfilesarea_mymodule', '', $filedir, $urlsource, 0, $delallowed, '', 1, 1, 0, 48, 1, $param, $title, '', '', '', null, $hidegeneratedfilelistifempty); } diff --git a/htdocs/product/stock/massstockmove.php b/htdocs/product/stock/massstockmove.php index 0f4e5476fd2..22c8787348a 100644 --- a/htdocs/product/stock/massstockmove.php +++ b/htdocs/product/stock/massstockmove.php @@ -38,7 +38,7 @@ $langs->loadLangs(array('products', 'stocks', 'orders', 'productbatch')); if ($user->socid) { $socid = $user->socid; } -$result=restrictedArea($user, 'produit|service'); +$result = restrictedArea($user, 'produit|service'); //checks if a product has been ordered @@ -62,11 +62,11 @@ if (!$sortfield) { if (!$sortorder) { $sortorder = 'ASC'; } -$limit = GETPOST('limit', 'int')?GETPOST('limit', 'int'):$conf->liste_limit; -$offset = $limit * $page ; +$limit = GETPOST('limit', 'int') ?GETPOST('limit', 'int') : $conf->liste_limit; +$offset = $limit * $page; -$listofdata=array(); -if (! empty($_SESSION['massstockmove'])) $listofdata=json_decode($_SESSION['massstockmove'], true); +$listofdata = array(); +if (!empty($_SESSION['massstockmove'])) $listofdata = json_decode($_SESSION['massstockmove'], true); /* @@ -75,17 +75,17 @@ if (! empty($_SESSION['massstockmove'])) $listofdata=json_decode($_SESSION['mass if ($action == 'addline') { - if (! ($id_product > 0)) + if (!($id_product > 0)) { $error++; setEventMessages($langs->trans("ErrorFieldRequired", $langs->transnoentitiesnoconv("Product")), null, 'errors'); } - if (! ($id_sw > 0)) + if (!($id_sw > 0)) { $error++; setEventMessages($langs->trans("ErrorFieldRequired", $langs->transnoentitiesnoconv("WarehouseSource")), null, 'errors'); } - if (! ($id_tw > 0)) + if (!($id_tw > 0)) { $error++; setEventMessages($langs->trans("ErrorFieldRequired", $langs->transnoentitiesnoconv("WarehouseTarget")), null, 'errors'); @@ -96,16 +96,16 @@ if ($action == 'addline') $langs->load("errors"); setEventMessages($langs->trans("ErrorWarehouseMustDiffers"), null, 'errors'); } - if (! $qty) + if (!$qty) { $error++; setEventMessages($langs->trans("ErrorFieldRequired", $langs->transnoentitiesnoconv("Qty")), null, 'errors'); } // Check a batch number is provided if product need it - if (! $error) + if (!$error) { - $producttmp=new Product($db); + $producttmp = new Product($db); $producttmp->fetch($id_product); if ($producttmp->hasbatch()) { @@ -120,7 +120,7 @@ if ($action == 'addline') // TODO Check qty is ok for stock move. Note qty may not be enough yet, but we make a check now to report a warning. // What is important is to have qty when doing action 'createmovements' - if (! $error) + if (!$error) { // Warning, don't forget lines already added into the $_SESSION['massstockmove'] if ($producttmp->hasbatch()) @@ -131,12 +131,12 @@ if ($action == 'addline') } } - if (! $error) + if (!$error) { - if (count(array_keys($listofdata)) > 0) $id=max(array_keys($listofdata)) + 1; - else $id=1; - $listofdata[$id]=array('id'=>$id, 'id_product'=>$id_product, 'qty'=>$qty, 'id_sw'=>$id_sw, 'id_tw'=>$id_tw, 'batch'=>$batch); - $_SESSION['massstockmove']=json_encode($listofdata); + if (count(array_keys($listofdata)) > 0) $id = max(array_keys($listofdata)) + 1; + else $id = 1; + $listofdata[$id] = array('id'=>$id, 'id_product'=>$id_product, 'qty'=>$qty, 'id_sw'=>$id_sw, 'id_tw'=>$id_tw, 'batch'=>$batch); + $_SESSION['massstockmove'] = json_encode($listofdata); unset($id_product); //unset($id_sw); @@ -147,16 +147,16 @@ if ($action == 'addline') if ($action == 'delline' && $idline != '') { - if (! empty($listofdata[$idline])) unset($listofdata[$idline]); - if (count($listofdata) > 0) $_SESSION['massstockmove']=json_encode($listofdata); + if (!empty($listofdata[$idline])) unset($listofdata[$idline]); + if (count($listofdata) > 0) $_SESSION['massstockmove'] = json_encode($listofdata); else unset($_SESSION['massstockmove']); } if ($action == 'createmovements') { - $error=0; + $error = 0; - if (! GETPOST("label")) + if (!GETPOST("label")) { $error++; setEventMessages($langs->trans("ErrorFieldRequired"), $langs->transnoentitiesnoconv("MovementLabel"), null, 'errors'); @@ -164,38 +164,38 @@ if ($action == 'createmovements') $db->begin(); - if (! $error) + if (!$error) { $product = new Product($db); - foreach($listofdata as $key => $val) // Loop on each movement to do + foreach ($listofdata as $key => $val) // Loop on each movement to do { - $id=$val['id']; - $id_product=$val['id_product']; - $id_sw=$val['id_sw']; - $id_tw=$val['id_tw']; - $qty=price2num($val['qty']); - $batch=$val['batch']; - $dlc=-1; // They are loaded later from serial - $dluo=-1; // They are loaded later from serial + $id = $val['id']; + $id_product = $val['id_product']; + $id_sw = $val['id_sw']; + $id_tw = $val['id_tw']; + $qty = price2num($val['qty']); + $batch = $val['batch']; + $dlc = -1; // They are loaded later from serial + $dluo = -1; // They are loaded later from serial - if (! $error && $id_sw <> $id_tw && is_numeric($qty) && $id_product) + if (!$error && $id_sw <> $id_tw && is_numeric($qty) && $id_product) { - $result=$product->fetch($id_product); + $result = $product->fetch($id_product); - $product->load_stock('novirtual'); // Load array product->stock_warehouse + $product->load_stock('novirtual'); // Load array product->stock_warehouse // Define value of products moved - $pricesrc=0; - if (! empty($product->pmp)) $pricesrc=$product->pmp; - $pricedest=$pricesrc; + $pricesrc = 0; + if (!empty($product->pmp)) $pricesrc = $product->pmp; + $pricedest = $pricesrc; //print 'price src='.$pricesrc.', price dest='.$pricedest;exit; - if (empty($conf->productbatch->enabled) || ! $product->hasbatch()) // If product does not need lot/serial + if (empty($conf->productbatch->enabled) || !$product->hasbatch()) // If product does not need lot/serial { // Remove stock - $result1=$product->correct_stock( + $result1 = $product->correct_stock( $user, $id_sw, $qty, @@ -211,7 +211,7 @@ if ($action == 'createmovements') } // Add stock - $result2=$product->correct_stock( + $result2 = $product->correct_stock( $user, $id_tw, $qty, @@ -228,22 +228,22 @@ if ($action == 'createmovements') } else { - $arraybatchinfo=$product->loadBatchInfo($batch); + $arraybatchinfo = $product->loadBatchInfo($batch); if (count($arraybatchinfo) > 0) { $firstrecord = array_shift($arraybatchinfo); - $dlc=$firstrecord['eatby']; - $dluo=$firstrecord['sellby']; + $dlc = $firstrecord['eatby']; + $dluo = $firstrecord['sellby']; //var_dump($batch); var_dump($arraybatchinfo); var_dump($firstrecord); var_dump($dlc); var_dump($dluo); exit; } else { - $dlc=''; - $dluo=''; + $dlc = ''; + $dluo = ''; } // Remove stock - $result1=$product->correct_stock_batch( + $result1 = $product->correct_stock_batch( $user, $id_sw, $qty, @@ -262,7 +262,7 @@ if ($action == 'createmovements') } // Add stock - $result2=$product->correct_stock_batch( + $result2 = $product->correct_stock_batch( $user, $id_tw, $qty, @@ -289,13 +289,13 @@ if ($action == 'createmovements') } } - if (! $error) + if (!$error) { unset($_SESSION['massstockmove']); $db->commit(); setEventMessages($langs->trans("StockMovementRecorded"), null, 'mesgs'); - header("Location: ".DOL_URL_ROOT.'/product/stock/index.php'); // Redirect to avoid pb when using back + header("Location: ".DOL_URL_ROOT.'/product/stock/index.php'); // Redirect to avoid pb when using back exit; } else @@ -311,10 +311,10 @@ if ($action == 'createmovements') * View */ -$now=dol_now(); +$now = dol_now(); -$form=new Form($db); -$formproduct=new FormProduct($db); +$form = new Form($db); +$formproduct = new FormProduct($db); $productstatic = new Product($db); $warehousestatics = new Entrepot($db); $warehousestatict = new Entrepot($db); @@ -325,24 +325,24 @@ llxHeader('', $title); print load_fiche_titre($langs->trans("MassStockTransferShort")); -$titletoadd=$langs->trans("Select"); -$buttonrecord=$langs->trans("RecordMovement"); -$titletoaddnoent=$langs->transnoentitiesnoconv("Select"); -$buttonrecordnoent=$langs->transnoentitiesnoconv("RecordMovement"); +$titletoadd = $langs->trans("Select"); +$buttonrecord = $langs->trans("RecordMovement"); +$titletoaddnoent = $langs->transnoentitiesnoconv("Select"); +$buttonrecordnoent = $langs->transnoentitiesnoconv("RecordMovement"); print ''.$langs->trans("SelectProductInAndOutWareHouse", $titletoaddnoent, $buttonrecordnoent).'
    '; print '
    '."\n"; // Form to add a line print '
    '; -print ''; +print ''; print ''; print '
    '; -print ''; +print '
    '; //print '
    '; -$param=''; +$param = ''; print '
    '; print getTitleFieldOfList($langs->trans('ProductRef'), 0, $_SERVER["PHP_SELF"], '', $param, '', '', $sortfield, $sortorder, 'tagtd maxwidthonsmartphone '); @@ -359,10 +359,10 @@ print ''; print ''; // Product print '
    '; -$filtertype=0; -if (! empty($conf->global->STOCK_SUPPORTS_SERVICES)) $filtertype=''; +$filtertype = 0; +if (!empty($conf->global->STOCK_SUPPORTS_SERVICES)) $filtertype = ''; if ($conf->global->PRODUIT_LIMIT_SIZE <= 0) { - $limit=''; + $limit = ''; } else { @@ -394,7 +394,7 @@ print ''; -foreach($listofdata as $key => $val) +foreach ($listofdata as $key => $val) { $productstatic->fetch($val['id_product']); $warehousestatics->fetch($val['id_sw']); @@ -432,14 +432,14 @@ print '
    '; print ''; -print ''; +print ''; print ''; // Button to record mass movement -$codemove=(isset($_POST["codemove"])?GETPOST("codemove", 'alpha'):dol_print_date(dol_now(), '%Y%m%d%H%M%S')); -$labelmovement=GETPOST("label")?GETPOST('label'):$langs->trans("StockTransfer").' '.dol_print_date($now, '%Y-%m-%d %H:%M'); +$codemove = (isset($_POST["codemove"]) ?GETPOST("codemove", 'alpha') : dol_print_date(dol_now(), '%Y%m%d%H%M%S')); +$labelmovement = GETPOST("label") ?GETPOST('label') : $langs->trans("StockTransfer").' '.dol_print_date($now, '%Y-%m-%d %H:%M'); -print ''; +print '
    '; print ''; print ''; print '"; // Last movement @@ -619,7 +619,7 @@ if ($resql) if ($resqlbis) { $obj = $db->fetch_object($resqlbis); - $lastmovementdate=$db->jdate($obj->datem); + $lastmovementdate = $db->jdate($obj->datem); } else { @@ -691,32 +691,32 @@ if ($resql) print '
    '; } - $param=''; - if (! empty($contextpage) && $contextpage != $_SERVER["PHP_SELF"]) $param.='&contextpage='.urlencode($contextpage); - if ($limit > 0 && $limit != $conf->liste_limit) $param.='&limit='.urlencode($limit); - if ($id > 0) $param.='&id='.urlencode($id); - if ($search_movement) $param.='&search_movement='.urlencode($search_movement); - if ($search_inventorycode) $param.='&search_inventorycode='.urlencode($search_inventorycode); - if ($search_type_mouvement) $param.='&search_type_mouvement='.urlencode($search_type_mouvement); - if ($search_product_ref) $param.='&search_product_ref='.urlencode($search_product_ref); - if ($search_product) $param.='&search_product='.urlencode($search_product); - if ($search_batch) $param.='&search_batch='.urlencode($search_batch); - if ($search_warehouse > 0) $param.='&search_warehouse='.urlencode($search_warehouse); - if (!empty($sref)) $param.='&sref='.urlencode($sref); // FIXME $sref is not defined - if (!empty($snom)) $param.='&snom='.urlencode($snom); // FIXME $snom is not defined - if ($search_user) $param.='&search_user='.urlencode($search_user); - if ($idproduct > 0) $param.='&idproduct='.urlencode($idproduct); + $param = ''; + if (!empty($contextpage) && $contextpage != $_SERVER["PHP_SELF"]) $param .= '&contextpage='.urlencode($contextpage); + if ($limit > 0 && $limit != $conf->liste_limit) $param .= '&limit='.urlencode($limit); + if ($id > 0) $param .= '&id='.urlencode($id); + if ($search_movement) $param .= '&search_movement='.urlencode($search_movement); + if ($search_inventorycode) $param .= '&search_inventorycode='.urlencode($search_inventorycode); + if ($search_type_mouvement) $param .= '&search_type_mouvement='.urlencode($search_type_mouvement); + if ($search_product_ref) $param .= '&search_product_ref='.urlencode($search_product_ref); + if ($search_product) $param .= '&search_product='.urlencode($search_product); + if ($search_batch) $param .= '&search_batch='.urlencode($search_batch); + if ($search_warehouse > 0) $param .= '&search_warehouse='.urlencode($search_warehouse); + if (!empty($sref)) $param .= '&sref='.urlencode($sref); // FIXME $sref is not defined + if (!empty($snom)) $param .= '&snom='.urlencode($snom); // FIXME $snom is not defined + if ($search_user) $param .= '&search_user='.urlencode($search_user); + if ($idproduct > 0) $param .= '&idproduct='.urlencode($idproduct); // Add $param from extra fields include DOL_DOCUMENT_ROOT.'/core/tpl/extrafields_list_search_param.tpl.php'; // List of mass actions available - $arrayofmassactions = array( + $arrayofmassactions = array( // 'presend'=>$langs->trans("SendByMail"), // 'builddoc'=>$langs->trans("PDFMerge"), ); //if ($user->rights->stock->supprimer) $arrayofmassactions['predelete']=''.$langs->trans("Delete"); - if (in_array($massaction, array('presend','predelete'))) $arrayofmassactions=array(); - $massactionbutton=$form->selectMassAction('', $arrayofmassactions); + if (in_array($massaction, array('presend', 'predelete'))) $arrayofmassactions = array(); + $massactionbutton = $form->selectMassAction('', $arrayofmassactions); print ''; if ($optioncss != '') print ''; @@ -735,140 +735,140 @@ if ($resql) if ($sall) { - foreach($fieldstosearchall as $key => $val) $fieldstosearchall[$key]=$langs->trans($val); - print '
    '.$langs->trans("FilterOnInto", $sall) . join(', ', $fieldstosearchall).'
    '; + foreach ($fieldstosearchall as $key => $val) $fieldstosearchall[$key] = $langs->trans($val); + print '
    '.$langs->trans("FilterOnInto", $sall).join(', ', $fieldstosearchall).'
    '; } - $moreforfilter=''; + $moreforfilter = ''; - $parameters=array(); - $reshook=$hookmanager->executeHooks('printFieldPreListTitle', $parameters); // Note that $action and $object may have been modified by hook + $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($moreforfilter)) + if (!empty($moreforfilter)) { print '
    '; print $moreforfilter; print '
    '; } - $varpage=empty($contextpage)?$_SERVER["PHP_SELF"]:$contextpage; - $selectedfields=$form->multiSelectArrayWithCheckbox('selectedfields', $arrayfields, $varpage); // This also change content of $arrayfields + $varpage = empty($contextpage) ? $_SERVER["PHP_SELF"] : $contextpage; + $selectedfields = $form->multiSelectArrayWithCheckbox('selectedfields', $arrayfields, $varpage); // This also change content of $arrayfields print '
    '; - print '
    '.$langs->trans("InventoryCode").''; diff --git a/htdocs/product/stock/movement_card.php b/htdocs/product/stock/movement_card.php index e640c346eec..9d10e08be9a 100644 --- a/htdocs/product/stock/movement_card.php +++ b/htdocs/product/stock/movement_card.php @@ -37,25 +37,25 @@ require_once DOL_DOCUMENT_ROOT.'/product/class/html.formproduct.class.php'; require_once DOL_DOCUMENT_ROOT.'/core/lib/stock.lib.php'; require_once DOL_DOCUMENT_ROOT.'/core/lib/product.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.'/core/class/html.formprojet.class.php'; require_once DOL_DOCUMENT_ROOT.'/projet/class/project.class.php'; } // Load translation files required by the page $langs->loadLangs(array('products', 'stocks', 'orders')); -if (! empty($conf->productbatch->enabled)) $langs->load("productbatch"); +if (!empty($conf->productbatch->enabled)) $langs->load("productbatch"); // Security check -$result=restrictedArea($user, 'stock'); +$result = restrictedArea($user, 'stock'); -$id=GETPOST('id', 'int'); +$id = GETPOST('id', 'int'); $ref = GETPOST('ref', 'alpha'); -$msid=GETPOST('msid', 'int'); -$product_id=GETPOST("product_id", 'int'); -$action=GETPOST('action', 'aZ09'); -$cancel=GETPOST('cancel', 'alpha'); -$contextpage=GETPOST('contextpage', 'aZ')?GETPOST('contextpage', 'aZ'):'movementlist'; +$msid = GETPOST('msid', 'int'); +$product_id = GETPOST("product_id", 'int'); +$action = GETPOST('action', 'aZ09'); +$cancel = GETPOST('cancel', 'alpha'); +$contextpage = GETPOST('contextpage', 'aZ') ?GETPOST('contextpage', 'aZ') : 'movementlist'; $idproduct = GETPOST('idproduct', 'int'); $year = GETPOST("year", 'int'); @@ -69,18 +69,18 @@ $search_inventorycode = trim(GETPOST("search_inventorycode", 'alpha')); $search_user = trim(GETPOST("search_user", 'alpha')); $search_batch = trim(GETPOST("search_batch", 'alpha')); $search_qty = trim(GETPOST("search_qty", 'alpha')); -$search_type_mouvement=GETPOST('search_type_mouvement', 'int'); +$search_type_mouvement = GETPOST('search_type_mouvement', 'int'); -$limit = GETPOST('limit', 'int')?GETPOST('limit', 'int'):$conf->liste_limit; +$limit = GETPOST('limit', 'int') ?GETPOST('limit', 'int') : $conf->liste_limit; $page = GETPOST("page", 'int'); $sortfield = GETPOST("sortfield", 'alpha'); $sortorder = GETPOST("sortorder", 'alpha'); if (empty($page) || $page == -1) { $page = 0; } // If $page is not defined, or '' or -1 $offset = $limit * $page; -if (! $sortfield) $sortfield="m.datem"; -if (! $sortorder) $sortorder="DESC"; +if (!$sortfield) $sortfield = "m.datem"; +if (!$sortorder) $sortorder = "DESC"; -$pdluoid=GETPOST('pdluoid', 'int'); +$pdluoid = GETPOST('pdluoid', 'int'); // Initialize technical object to manage hooks of page. Note that conf->hooks_modules contains array of hook context $object = new MouvementStock($db); @@ -91,17 +91,17 @@ $formfile = new FormFile($db); // fetch optionals attributes and labels $extrafields->fetch_name_optionals_label($object->table_element); -$search_array_options=$extrafields->getOptionalsFromPost($object->table_element, '', 'search_'); +$search_array_options = $extrafields->getOptionalsFromPost($object->table_element, '', 'search_'); -$arrayfields=array( +$arrayfields = array( 'm.rowid'=>array('label'=>$langs->trans("Ref"), 'checked'=>1), 'm.datem'=>array('label'=>$langs->trans("Date"), 'checked'=>1), 'p.ref'=>array('label'=>$langs->trans("ProductRef"), 'checked'=>1, 'css'=>'maxwidth100'), 'p.label'=>array('label'=>$langs->trans("ProductLabel"), 'checked'=>1), - 'm.batch'=>array('label'=>$langs->trans("BatchNumberShort"), 'checked'=>1, 'enabled'=>(! empty($conf->productbatch->enabled))), - 'pl.eatby'=>array('label'=>$langs->trans("EatByDate"), 'checked'=>0, 'enabled'=>(! empty($conf->productbatch->enabled))), - 'pl.sellby'=>array('label'=>$langs->trans("SellByDate"), 'checked'=>0, 'position'=>10, 'enabled'=>(! empty($conf->productbatch->enabled))), - 'e.ref'=>array('label'=>$langs->trans("Warehouse"), 'checked'=>1, 'enabled'=>(! $id > 0)), // If we are on specific warehouse, we hide it + 'm.batch'=>array('label'=>$langs->trans("BatchNumberShort"), 'checked'=>1, 'enabled'=>(!empty($conf->productbatch->enabled))), + 'pl.eatby'=>array('label'=>$langs->trans("EatByDate"), 'checked'=>0, 'enabled'=>(!empty($conf->productbatch->enabled))), + 'pl.sellby'=>array('label'=>$langs->trans("SellByDate"), 'checked'=>0, 'position'=>10, 'enabled'=>(!empty($conf->productbatch->enabled))), + 'e.ref'=>array('label'=>$langs->trans("Warehouse"), 'checked'=>1, 'enabled'=>(!$id > 0)), // If we are on specific warehouse, we hide it 'm.fk_user_author'=>array('label'=>$langs->trans("Author"), 'checked'=>0), 'm.inventorycode'=>array('label'=>$langs->trans("InventoryCodeShort"), 'checked'=>1), 'm.label'=>array('label'=>$langs->trans("MovementLabel"), 'checked'=>1), @@ -123,8 +123,8 @@ $usercanread = (($user->rights->stock->mouvement->lire)); $usercancreate = (($user->rights->stock->mouvement->creer)); $usercandelete = (($user->rights->stock->mouvement->supprimer)); -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 @@ -135,45 +135,45 @@ 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')) // Both test are required to be compatible with all browsers { - $year=''; - $month=''; - $search_ref=''; - $search_movement=""; - $search_type_mouvement=""; - $search_inventorycode=""; - $search_product_ref=""; - $search_product=""; - $search_warehouse=""; - $search_user=""; - $search_batch=""; - $search_qty=''; - $sall=""; - $toselect=''; - $search_array_options=array(); + $year = ''; + $month = ''; + $search_ref = ''; + $search_movement = ""; + $search_type_mouvement = ""; + $search_inventorycode = ""; + $search_product_ref = ""; + $search_product = ""; + $search_warehouse = ""; + $search_user = ""; + $search_batch = ""; + $search_qty = ''; + $sall = ""; + $toselect = ''; + $search_array_options = array(); } // Correct stock if ($action == "correct_stock") { $product = new Product($db); - if (! empty($product_id)) $result=$product->fetch($product_id); + if (!empty($product_id)) $result = $product->fetch($product_id); - $error=0; + $error = 0; if (empty($product_id)) { $error++; setEventMessages($langs->trans("ErrorFieldRequired", $langs->transnoentitiesnoconv("Product")), null, 'errors'); - $action='correction'; + $action = 'correction'; } - if (! is_numeric($_POST["nbpiece"])) + if (!is_numeric($_POST["nbpiece"])) { $error++; setEventMessages($langs->trans("ErrorFieldMustBeANumeric", $langs->transnoentitiesnoconv("NumberOfUnit")), null, 'errors'); - $action='correction'; + $action = 'correction'; } - if (! $error) + if (!$error) { $origin_element = ''; $origin_id = null; @@ -186,14 +186,14 @@ if ($action == "correct_stock") if ($product->hasbatch()) { - $batch=GETPOST('batch_number', 'alpha'); + $batch = GETPOST('batch_number', 'alpha'); //$eatby=GETPOST('eatby'); //$sellby=GETPOST('sellby'); - $eatby=dol_mktime(0, 0, 0, GETPOST('eatbymonth', 'int'), GETPOST('eatbyday', 'int'), GETPOST('eatbyyear', 'int')); - $sellby=dol_mktime(0, 0, 0, GETPOST('sellbymonth', 'int'), GETPOST('sellbyday', 'int'), GETPOST('sellbyyear', 'int')); + $eatby = dol_mktime(0, 0, 0, GETPOST('eatbymonth', 'int'), GETPOST('eatbyday', 'int'), GETPOST('eatbyyear', 'int')); + $sellby = dol_mktime(0, 0, 0, GETPOST('sellbymonth', 'int'), GETPOST('sellbyday', 'int'), GETPOST('sellbyyear', 'int')); - $result=$product->correct_stock_batch( + $result = $product->correct_stock_batch( $user, $id, GETPOST("nbpiece", 'int'), @@ -206,11 +206,11 @@ if ($action == "correct_stock") GETPOST('inventorycode', 'alpha'), $origin_element, $origin_id - ); // We do not change value of stock for a correction + ); // We do not change value of stock for a correction } else { - $result=$product->correct_stock( + $result = $product->correct_stock( $user, $id, GETPOST("nbpiece", 'int'), @@ -220,7 +220,7 @@ if ($action == "correct_stock") GETPOST('inventorycode', 'alpha'), $origin_element, $origin_id - ); // We do not change value of stock for a correction + ); // We do not change value of stock for a correction } if ($result > 0) @@ -232,72 +232,72 @@ if ($action == "correct_stock") { $error++; setEventMessages($product->error, $product->errors, 'errors'); - $action='correction'; + $action = 'correction'; } } - if (! $error) $action=''; + if (!$error) $action = ''; } // Transfer stock from a warehouse to another warehouse -if ($action == "transfert_stock" && ! $cancel) +if ($action == "transfert_stock" && !$cancel) { $product = new Product($db); - if (! empty($product_id)) $result=$product->fetch($product_id); + if (!empty($product_id)) $result = $product->fetch($product_id); - if (! (GETPOST("id_entrepot_destination", 'int') > 0)) + if (!(GETPOST("id_entrepot_destination", 'int') > 0)) { setEventMessages($langs->trans("ErrorFieldRequired", $langs->transnoentitiesnoconv("Warehouse")), null, 'errors'); $error++; - $action='transfert'; + $action = 'transfert'; } if (empty($product_id)) { $error++; setEventMessages($langs->trans("ErrorFieldRequired", $langs->transnoentitiesnoconv("Product")), null, 'errors'); - $action='transfert'; + $action = 'transfert'; } - if (! GETPOST("nbpiece", 'int')) + if (!GETPOST("nbpiece", 'int')) { setEventMessages($langs->trans("ErrorFieldRequired", $langs->transnoentitiesnoconv("NumberOfUnit")), null, 'errors'); $error++; - $action='transfert'; + $action = 'transfert'; } if ($id == GETPOST("id_entrepot_destination", 'int')) { setEventMessages($langs->trans("ErrorSrcAndTargetWarehouseMustDiffers"), null, 'errors'); $error++; - $action='transfert'; + $action = 'transfert'; } - if (! empty($conf->productbatch->enabled)) + if (!empty($conf->productbatch->enabled)) { $product = new Product($db); - $result=$product->fetch($product_id); + $result = $product->fetch($product_id); - if ($product->hasbatch() && ! GETPOST("batch_number", 'alpha')) + if ($product->hasbatch() && !GETPOST("batch_number", 'alpha')) { setEventMessages($langs->trans("ErrorFieldRequired", $langs->transnoentitiesnoconv("batch_number")), null, 'errors'); $error++; - $action='transfert'; + $action = 'transfert'; } } - if (! $error) + if (!$error) { if ($id) { $object = new Entrepot($db); - $result=$object->fetch($id); + $result = $object->fetch($id); $db->begin(); - $product->load_stock('novirtual'); // Load array product->stock_warehouse + $product->load_stock('novirtual'); // Load array product->stock_warehouse // Define value of products moved - $pricesrc=0; - if (isset($product->pmp)) $pricesrc=$product->pmp; - $pricedest=$pricesrc; + $pricesrc = 0; + if (isset($product->pmp)) $pricesrc = $product->pmp; + $pricedest = $pricesrc; if ($product->hasbatch()) { @@ -305,13 +305,13 @@ if ($action == "transfert_stock" && ! $cancel) if ($pdluoid > 0) { - $result=$pdluo->fetch($pdluoid); + $result = $pdluo->fetch($pdluoid); if ($result) { - $srcwarehouseid=$pdluo->warehouseid; - $batch=$pdluo->batch; - $eatby=$pdluo->eatby; - $sellby=$pdluo->sellby; + $srcwarehouseid = $pdluo->warehouseid; + $batch = $pdluo->batch; + $eatby = $pdluo->eatby; + $sellby = $pdluo->sellby; } else { @@ -321,16 +321,16 @@ if ($action == "transfert_stock" && ! $cancel) } else { - $srcwarehouseid=$id; - $batch=GETPOST('batch_number', 'alpha'); - $eatby=$d_eatby; - $sellby=$d_sellby; + $srcwarehouseid = $id; + $batch = GETPOST('batch_number', 'alpha'); + $eatby = $d_eatby; + $sellby = $d_sellby; } - if (! $error) + if (!$error) { // Remove stock - $result1=$product->correct_stock_batch( + $result1 = $product->correct_stock_batch( $user, $srcwarehouseid, GETPOST("nbpiece", 'int'), @@ -343,7 +343,7 @@ if ($action == "transfert_stock" && ! $cancel) GETPOST('inventorycode', 'alpha') ); // Add stock - $result2=$product->correct_stock_batch( + $result2 = $product->correct_stock_batch( $user, GETPOST("id_entrepot_destination", 'int'), GETPOST("nbpiece", 'int'), @@ -360,7 +360,7 @@ if ($action == "transfert_stock" && ! $cancel) else { // Remove stock - $result1=$product->correct_stock( + $result1 = $product->correct_stock( $user, $id, GETPOST("nbpiece", 'int'), @@ -371,7 +371,7 @@ if ($action == "transfert_stock" && ! $cancel) ); // Add stock - $result2=$product->correct_stock( + $result2 = $product->correct_stock( $user, GETPOST("id_entrepot_destination"), GETPOST("nbpiece", 'int'), @@ -381,7 +381,7 @@ if ($action == "transfert_stock" && ! $cancel) GETPOST('inventorycode', 'alpha') ); } - if (! $error && $result1 >= 0 && $result2 >= 0) + if (!$error && $result1 >= 0 && $result2 >= 0) { $db->commit(); @@ -400,7 +400,7 @@ if ($action == "transfert_stock" && ! $cancel) { setEventMessages($product->error, $product->errors, 'errors'); $db->rollback(); - $action='transfert'; + $action = 'transfert'; } } } @@ -433,62 +433,62 @@ if (empty($reshook) && $action != 'remove_file') * View */ -$productlot=new ProductLot($db); -$productstatic=new Product($db); -$warehousestatic=new Entrepot($db); -$movement=new MouvementStock($db); -$userstatic=new User($db); -$form=new Form($db); -$formother=new FormOther($db); -$formproduct=new FormProduct($db); -if (!empty($conf->projet->enabled)) $formproject=new FormProjets($db); +$productlot = new ProductLot($db); +$productstatic = new Product($db); +$warehousestatic = new Entrepot($db); +$movement = new MouvementStock($db); +$userstatic = new User($db); +$form = new Form($db); +$formother = new FormOther($db); +$formproduct = new FormProduct($db); +if (!empty($conf->projet->enabled)) $formproject = new FormProjets($db); $sql = "SELECT p.rowid, p.ref as product_ref, p.label as produit, p.tobatch, p.fk_product_type as type, p.entity,"; -$sql.= " e.ref as warehouse_ref, e.rowid as entrepot_id, e.lieu,"; -$sql.= " m.rowid as mid, m.value as qty, m.datem, m.fk_user_author, m.label, m.inventorycode, m.fk_origin, m.origintype,"; -$sql.= " m.batch, m.price,"; -$sql.= " m.type_mouvement,"; -$sql.= " pl.rowid as lotid, pl.eatby, pl.sellby,"; -$sql.= " u.login, u.photo, u.lastname, u.firstname"; +$sql .= " e.ref as warehouse_ref, e.rowid as entrepot_id, e.lieu,"; +$sql .= " m.rowid as mid, m.value as qty, m.datem, m.fk_user_author, m.label, m.inventorycode, m.fk_origin, m.origintype,"; +$sql .= " m.batch, m.price,"; +$sql .= " m.type_mouvement,"; +$sql .= " pl.rowid as lotid, pl.eatby, pl.sellby,"; +$sql .= " u.login, u.photo, u.lastname, u.firstname"; // 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 : ''); +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 : ''); } // 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."entrepot as e,"; -$sql.= " ".MAIN_DB_PREFIX."product as p,"; -$sql.= " ".MAIN_DB_PREFIX."stock_mouvement as m"; -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 (m.rowid = ef.fk_object)"; -$sql.= " LEFT JOIN ".MAIN_DB_PREFIX."user as u ON m.fk_user_author = u.rowid"; -$sql.= " LEFT JOIN ".MAIN_DB_PREFIX."product_lot as pl ON m.batch = pl.batch AND m.fk_product = pl.fk_product"; -$sql.= " WHERE m.fk_product = p.rowid"; +$reshook = $hookmanager->executeHooks('printFieldListSelect', $parameters); // Note that $action and $object may have been modified by hook +$sql .= $hookmanager->resPrint; +$sql .= " FROM ".MAIN_DB_PREFIX."entrepot as e,"; +$sql .= " ".MAIN_DB_PREFIX."product as p,"; +$sql .= " ".MAIN_DB_PREFIX."stock_mouvement as m"; +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 (m.rowid = ef.fk_object)"; +$sql .= " LEFT JOIN ".MAIN_DB_PREFIX."user as u ON m.fk_user_author = u.rowid"; +$sql .= " LEFT JOIN ".MAIN_DB_PREFIX."product_lot as pl ON m.batch = pl.batch AND m.fk_product = pl.fk_product"; +$sql .= " WHERE m.fk_product = p.rowid"; if ($msid > 0) $sql .= " AND m.rowid = ".$msid; -$sql.= " AND m.fk_entrepot = e.rowid"; -$sql.= " AND e.entity IN (".getEntity('stock').")"; -if (empty($conf->global->STOCK_SUPPORTS_SERVICES)) $sql.= " AND p.fk_product_type = 0"; -if ($id > 0) $sql.= " AND e.rowid ='".$id."'"; -$sql.= dolSqlDateFilter('m.datem', 0, $month, $year); -if ($idproduct > 0) $sql.= " AND p.rowid = '".$idproduct."'"; -if (! empty($search_ref)) $sql.= natural_search('m.rowid', $search_ref, 1); -if (! empty($search_movement)) $sql.= natural_search('m.label', $search_movement); -if (! empty($search_inventorycode)) $sql.= natural_search('m.inventorycode', $search_inventorycode); -if (! empty($search_product_ref)) $sql.= natural_search('p.ref', $search_product_ref); -if (! empty($search_product)) $sql.= natural_search('p.label', $search_product); -if ($search_warehouse != '' && $search_warehouse != '-1') $sql.= natural_search('e.rowid', $search_warehouse, 2); -if (! empty($search_user)) $sql.= natural_search('u.login', $search_user); -if (! empty($search_batch)) $sql.= natural_search('m.batch', $search_batch); -if ($search_qty != '') $sql.= natural_search('m.value', $search_qty, 1); -if ($search_type_mouvement != '' && $search_type_mouvement != '-1') $sql.= natural_search('m.type_mouvement', $search_type_mouvement, 2); +$sql .= " AND m.fk_entrepot = e.rowid"; +$sql .= " AND e.entity IN (".getEntity('stock').")"; +if (empty($conf->global->STOCK_SUPPORTS_SERVICES)) $sql .= " AND p.fk_product_type = 0"; +if ($id > 0) $sql .= " AND e.rowid ='".$id."'"; +$sql .= dolSqlDateFilter('m.datem', 0, $month, $year); +if ($idproduct > 0) $sql .= " AND p.rowid = '".$idproduct."'"; +if (!empty($search_ref)) $sql .= natural_search('m.rowid', $search_ref, 1); +if (!empty($search_movement)) $sql .= natural_search('m.label', $search_movement); +if (!empty($search_inventorycode)) $sql .= natural_search('m.inventorycode', $search_inventorycode); +if (!empty($search_product_ref)) $sql .= natural_search('p.ref', $search_product_ref); +if (!empty($search_product)) $sql .= natural_search('p.label', $search_product); +if ($search_warehouse != '' && $search_warehouse != '-1') $sql .= natural_search('e.rowid', $search_warehouse, 2); +if (!empty($search_user)) $sql .= natural_search('u.login', $search_user); +if (!empty($search_batch)) $sql .= natural_search('m.batch', $search_batch); +if ($search_qty != '') $sql .= natural_search('m.value', $search_qty, 1); +if ($search_type_mouvement != '' && $search_type_mouvement != '-1') $sql .= natural_search('m.type_mouvement', $search_type_mouvement, 2); // Add where from extra fields include DOL_DOCUMENT_ROOT.'/core/tpl/extrafields_list_search_sql.tpl.php'; // Add where from hooks -$parameters=array(); -$reshook=$hookmanager->executeHooks('printFieldListWhere', $parameters); // Note that $action and $object may have been modified by hook -$sql.=$hookmanager->resPrint; -$sql.= $db->order($sortfield, $sortorder); +$parameters = array(); +$reshook = $hookmanager->executeHooks('printFieldListWhere', $parameters); // Note that $action and $object may have been modified by hook +$sql .= $hookmanager->resPrint; +$sql .= $db->order($sortfield, $sortorder); $nbtotalofrecords = ''; if (empty($conf->global->MAIN_DISABLE_FULL_SCANLIST)) @@ -502,9 +502,9 @@ if (empty($conf->global->MAIN_DISABLE_FULL_SCANLIST)) } } -if(empty($search_inventorycode)) +if (empty($search_inventorycode)) { - $sql.= $db->plimit($limit+1, $offset); + $sql .= $db->plimit($limit + 1, $offset); } else { @@ -515,7 +515,7 @@ else $resql = $db->query($sql); -if(!empty($search_inventorycode)) $limit = $db->num_rows($resql); +if (!empty($search_inventorycode)) $limit = $db->num_rows($resql); if ($resql) { @@ -537,16 +537,16 @@ if ($resql) $num = $db->num_rows($resql); - $arrayofselected=is_array($toselect)?$toselect:array(); + $arrayofselected = is_array($toselect) ? $toselect : array(); $i = 0; - $help_url='EN:Module_Stocks_En|FR:Module_Stock|ES:Módulo_Stocks'; + $help_url = 'EN:Module_Stocks_En|FR:Module_Stock|ES:Módulo_Stocks'; if ($msid) $texte = $langs->trans('StockMovementForId', $msid); else { $texte = $langs->trans("ListOfStockMovements"); - if ($id) $texte.=' ('.$langs->trans("ForThisWarehouse").')'; + if ($id) $texte .= ' ('.$langs->trans("ForThisWarehouse").')'; } llxHeader("", $texte, $help_url); @@ -562,12 +562,12 @@ if ($resql) $linkback = ''.$langs->trans("BackToList").''; - $morehtmlref='
    '; - $morehtmlref.=$langs->trans("LocationSummary").' : '.$object->lieu; - $morehtmlref.='
    '; + $morehtmlref = '
    '; + $morehtmlref .= $langs->trans("LocationSummary").' : '.$object->lieu; + $morehtmlref .= '
    '; $shownav = 1; - if ($user->socid && ! in_array('stock', explode(',', $conf->global->MAIN_MODULES_FOR_EXTERNAL))) $shownav=0; + if ($user->socid && !in_array('stock', explode(',', $conf->global->MAIN_MODULES_FOR_EXTERNAL))) $shownav = 0; dol_banner_tab($object, 'ref', $linkback, $shownav, 'ref', 'ref', $morehtmlref); @@ -576,25 +576,25 @@ if ($resql) print '
    '; print '
    '; - print ''; + print '
    '; print ''; // Description print ''; - $calcproductsunique=$object->nb_different_products(); - $calcproducts=$object->nb_products(); + $calcproductsunique = $object->nb_different_products(); + $calcproducts = $object->nb_products(); // Total nb of different products print '"; // Nb of products print '"; print '
    '.$langs->trans("Description").''.dol_htmlentitiesbr($object->description).'
    '.$langs->trans("NumberOfDifferentProducts").''; - print empty($calcproductsunique['nb'])?'0':$calcproductsunique['nb']; + print empty($calcproductsunique['nb']) ? '0' : $calcproductsunique['nb']; print "
    '.$langs->trans("NumberOfProducts").''; - $valtoshow=price2num($calcproducts['nb'], 'MS'); - print empty($valtoshow)?'0':$valtoshow; + $valtoshow = price2num($calcproducts['nb'], 'MS'); + print empty($valtoshow) ? '0' : $valtoshow; print "
    '; @@ -608,7 +608,7 @@ if ($resql) // Value print '
    '.$langs->trans("EstimatedStockValueShort").''; - print price((empty($calcproducts['value'])?'0':price2num($calcproducts['value'], 'MT')), 0, $langs, 0, -1, -1, $conf->currency); + print price((empty($calcproducts['value']) ? '0' : price2num($calcproducts['value'], 'MT')), 0, $langs, 0, -1, -1, $conf->currency); print "
    '."\n"; + print '
    '."\n"; // Fields title search print ''; - if (! empty($arrayfields['m.rowid']['checked'])) + if (!empty($arrayfields['m.rowid']['checked'])) { // Ref print ''; } - if (! empty($arrayfields['m.datem']['checked'])) + if (!empty($arrayfields['m.datem']['checked'])) { print ''; } - if (! empty($arrayfields['p.ref']['checked'])) + if (!empty($arrayfields['p.ref']['checked'])) { // Product Ref print ''; } - if (! empty($arrayfields['p.label']['checked'])) + if (!empty($arrayfields['p.label']['checked'])) { // Product label print ''; } // Batch - if (! empty($arrayfields['m.batch']['checked'])) + if (!empty($arrayfields['m.batch']['checked'])) { print ''; } - if (! empty($arrayfields['pl.eatby']['checked'])) + if (!empty($arrayfields['pl.eatby']['checked'])) { print ''; } - if (! empty($arrayfields['pl.sellby']['checked'])) + if (!empty($arrayfields['pl.sellby']['checked'])) { print ''; } // Warehouse - if (! empty($arrayfields['e.ref']['checked'])) + if (!empty($arrayfields['e.ref']['checked'])) { print ''; } - if (! empty($arrayfields['m.fk_user_author']['checked'])) + if (!empty($arrayfields['m.fk_user_author']['checked'])) { // Author print ''; } - if (! empty($arrayfields['m.inventorycode']['checked'])) + if (!empty($arrayfields['m.inventorycode']['checked'])) { // Inventory code print ''; } - if (! empty($arrayfields['m.label']['checked'])) + if (!empty($arrayfields['m.label']['checked'])) { // Label of movement print ''; } - if (! empty($arrayfields['m.type_mouvement']['checked'])) + if (!empty($arrayfields['m.type_mouvement']['checked'])) { // Type of movement print ''; } - if (! empty($arrayfields['origin']['checked'])) + if (!empty($arrayfields['origin']['checked'])) { // Origin of movement print ''; } - if (! empty($arrayfields['m.value']['checked'])) + if (!empty($arrayfields['m.value']['checked'])) { // Qty print ''; } - if (! empty($arrayfields['m.price']['checked'])) + if (!empty($arrayfields['m.price']['checked'])) { // Price print ''; } // Date modification - if (! empty($arrayfields['m.tms']['checked'])) + if (!empty($arrayfields['m.tms']['checked'])) { print ''; } // Actions print ''; print "\n"; print ''; - if (! empty($arrayfields['m.rowid']['checked'])) + if (!empty($arrayfields['m.rowid']['checked'])) print_liste_field_titre($arrayfields['m.rowid']['label'], $_SERVER["PHP_SELF"], 'm.rowid', '', $param, '', $sortfield, $sortorder); - if (! empty($arrayfields['m.datem']['checked'])) + if (!empty($arrayfields['m.datem']['checked'])) print_liste_field_titre($arrayfields['m.datem']['label'], $_SERVER["PHP_SELF"], 'm.datem', '', $param, '', $sortfield, $sortorder); - if (! empty($arrayfields['p.ref']['checked'])) + 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.label']['checked'])) + if (!empty($arrayfields['p.label']['checked'])) print_liste_field_titre($arrayfields['p.label']['label'], $_SERVER["PHP_SELF"], 'p.label', '', $param, '', $sortfield, $sortorder); - if (! empty($arrayfields['m.batch']['checked'])) + if (!empty($arrayfields['m.batch']['checked'])) print_liste_field_titre($arrayfields['m.batch']['label'], $_SERVER["PHP_SELF"], 'm.batch', '', $param, '', $sortfield, $sortorder, 'center '); - if (! empty($arrayfields['pl.eatby']['checked'])) + if (!empty($arrayfields['pl.eatby']['checked'])) print_liste_field_titre($arrayfields['pl.eatby']['label'], $_SERVER["PHP_SELF"], 'pl.eatby', '', $param, '', $sortfield, $sortorder, 'center '); - if (! empty($arrayfields['pl.sellby']['checked'])) + if (!empty($arrayfields['pl.sellby']['checked'])) print_liste_field_titre($arrayfields['pl.sellby']['label'], $_SERVER["PHP_SELF"], 'pl.sellby', '', $param, '', $sortfield, $sortorder, 'center '); - if (! empty($arrayfields['e.ref']['checked'])) { + if (!empty($arrayfields['e.ref']['checked'])) { // We are on a specific warehouse card, no filter on other should be possible print_liste_field_titre($arrayfields['e.ref']['label'], $_SERVER["PHP_SELF"], "e.ref", "", $param, "", $sortfield, $sortorder); } - if (! empty($arrayfields['m.fk_user_author']['checked'])) + if (!empty($arrayfields['m.fk_user_author']['checked'])) print_liste_field_titre($arrayfields['m.fk_user_author']['label'], $_SERVER["PHP_SELF"], "m.fk_user_author", "", $param, "", $sortfield, $sortorder); - if (! empty($arrayfields['m.inventorycode']['checked'])) + if (!empty($arrayfields['m.inventorycode']['checked'])) print_liste_field_titre($arrayfields['m.inventorycode']['label'], $_SERVER["PHP_SELF"], "m.inventorycode", "", $param, "", $sortfield, $sortorder); - if (! empty($arrayfields['m.label']['checked'])) + if (!empty($arrayfields['m.label']['checked'])) print_liste_field_titre($arrayfields['m.label']['label'], $_SERVER["PHP_SELF"], "m.label", "", $param, "", $sortfield, $sortorder); - if (! empty($arrayfields['m.type_mouvement']['checked'])) + if (!empty($arrayfields['m.type_mouvement']['checked'])) print_liste_field_titre($arrayfields['m.type_mouvement']['label'], $_SERVER["PHP_SELF"], "m.type_mouvement", "", $param, '', $sortfield, $sortorder, 'center '); - if (! empty($arrayfields['origin']['checked'])) + if (!empty($arrayfields['origin']['checked'])) print_liste_field_titre($arrayfields['origin']['label'], $_SERVER["PHP_SELF"], "", "", $param, "", $sortfield, $sortorder); - if (! empty($arrayfields['m.value']['checked'])) + if (!empty($arrayfields['m.value']['checked'])) print_liste_field_titre($arrayfields['m.value']['label'], $_SERVER["PHP_SELF"], "m.value", "", $param, '', $sortfield, $sortorder, 'right '); - if (! empty($arrayfields['m.price']['checked'])) + if (!empty($arrayfields['m.price']['checked'])) print_liste_field_titre($arrayfields['m.price']['label'], $_SERVER["PHP_SELF"], "m.price", "", $param, '', $sortfield, $sortorder, 'right '); // 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 + $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['m.datec']['checked'])) { + if (!empty($arrayfields['m.datec']['checked'])) { print_liste_field_titre($arrayfields['p.datec']['label'], $_SERVER["PHP_SELF"], "p.datec", "", $param, '', $sortfield, $sortorder, 'center nowrap '); } - if (! empty($arrayfields['m.tms']['checked'])) { + if (!empty($arrayfields['m.tms']['checked'])) { print_liste_field_titre($arrayfields['p.tms']['label'], $_SERVER["PHP_SELF"], "p.tms", "", $param, '', $sortfield, $sortorder, 'center nowrap '); } print_liste_field_titre($selectedfields, $_SERVER["PHP_SELF"], "", '', '', '', $sortfield, $sortorder, 'center maxwidthsearch '); print "\n"; - $arrayofuniqueproduct=array(); + $arrayofuniqueproduct = array(); while ($i < min($num, $limit)) { $objp = $db->fetch_object($resql); - $userstatic->id=$objp->fk_user_author; - $userstatic->login=$objp->login; - $userstatic->lastname=$objp->lastname; - $userstatic->firstname=$objp->firstname; - $userstatic->photo=$objp->photo; + $userstatic->id = $objp->fk_user_author; + $userstatic->login = $objp->login; + $userstatic->lastname = $objp->lastname; + $userstatic->firstname = $objp->firstname; + $userstatic->photo = $objp->photo; - $productstatic->id=$objp->rowid; - $productstatic->ref=$objp->product_ref; - $productstatic->label=$objp->produit; - $productstatic->type=$objp->type; - $productstatic->entity=$objp->entity; - $productstatic->status_batch=$objp->tobatch; + $productstatic->id = $objp->rowid; + $productstatic->ref = $objp->product_ref; + $productstatic->label = $objp->produit; + $productstatic->type = $objp->type; + $productstatic->entity = $objp->entity; + $productstatic->status_batch = $objp->tobatch; $productlot->id = $objp->lotid; - $productlot->batch= $objp->batch; - $productlot->eatby= $objp->eatby; - $productlot->sellby= $objp->sellby; + $productlot->batch = $objp->batch; + $productlot->eatby = $objp->eatby; + $productlot->sellby = $objp->sellby; - $warehousestatic->id=$objp->entrepot_id; - $warehousestatic->libelle=$objp->warehouse_ref; // deprecated - $warehousestatic->label=$objp->warehouse_ref; - $warehousestatic->lieu=$objp->lieu; + $warehousestatic->id = $objp->entrepot_id; + $warehousestatic->libelle = $objp->warehouse_ref; // deprecated + $warehousestatic->label = $objp->warehouse_ref; + $warehousestatic->lieu = $objp->lieu; - $arrayofuniqueproduct[$objp->rowid]=$objp->produit; + $arrayofuniqueproduct[$objp->rowid] = $objp->produit; if (!empty($objp->fk_origin)) { $origin = $movement->get_origin($objp->fk_origin, $objp->origintype); } else { @@ -991,24 +991,24 @@ if ($resql) print ''; // Id movement - if (! empty($arrayfields['m.rowid']['checked'])) + if (!empty($arrayfields['m.rowid']['checked'])) { // This is primary not movement id print ''; } - if (! empty($arrayfields['m.datem']['checked'])) + if (!empty($arrayfields['m.datem']['checked'])) { // Date print ''; } - if (! empty($arrayfields['p.ref']['checked'])) + if (!empty($arrayfields['p.ref']['checked'])) { // Product ref print '\n"; } - if (! empty($arrayfields['p.label']['checked'])) + if (!empty($arrayfields['p.label']['checked'])) { // Product label print '\n"; } - if (! empty($arrayfields['m.batch']['checked'])) + if (!empty($arrayfields['m.batch']['checked'])) { print ''; } - if (! empty($arrayfields['pl.eatby']['checked'])) + if (!empty($arrayfields['pl.eatby']['checked'])) { - print ''; + print ''; } - if (! empty($arrayfields['pl.sellby']['checked'])) + if (!empty($arrayfields['pl.sellby']['checked'])) { - print ''; + print ''; } // Warehouse - if (! empty($arrayfields['e.ref']['checked'])) + if (!empty($arrayfields['e.ref']['checked'])) { print '\n"; } // Author - if (! empty($arrayfields['m.fk_user_author']['checked'])) + if (!empty($arrayfields['m.fk_user_author']['checked'])) { print '\n"; } - if (! empty($arrayfields['m.inventorycode']['checked'])) + if (!empty($arrayfields['m.inventorycode']['checked'])) { // Inventory code print ''; } - if (! empty($arrayfields['m.type_mouvement']['checked'])) + if (!empty($arrayfields['m.type_mouvement']['checked'])) { // Type of movement - switch($objp->type_mouvement) { + switch ($objp->type_mouvement) { case "0": print ''; break; @@ -1084,12 +1084,12 @@ if ($resql) break; } } - if (! empty($arrayfields['origin']['checked'])) + if (!empty($arrayfields['origin']['checked'])) { // Origin of movement print ''; } - if (! empty($arrayfields['m.value']['checked'])) + if (!empty($arrayfields['m.value']['checked'])) { // Qty print ''; } - if (! empty($arrayfields['m.price']['checked'])) + if (!empty($arrayfields['m.price']['checked'])) { // Price print ''; - if (! $i) $totalarray['nbfield']++; + if (!$i) $totalarray['nbfield']++; print "\n"; $i++; @@ -1129,15 +1129,15 @@ if ($resql) { print "
    "; - $productidselected=0; + $productidselected = 0; foreach ($arrayofuniqueproduct as $key => $val) { - $productidselected=$key; - $productlabelselected=$val; + $productidselected = $key; + $productlabelselected = $val; } - $datebefore=dol_get_first_day($year?$year:strftime("%Y", time()), $month?$month:1, true); - $dateafter=dol_get_last_day($year?$year:strftime("%Y", time()), $month?$month:12, true); - $balancebefore=$movement->calculateBalanceForProductBefore($productidselected, $datebefore); - $balanceafter=$movement->calculateBalanceForProductBefore($productidselected, $dateafter); + $datebefore = dol_get_first_day($year ? $year : strftime("%Y", time()), $month ? $month : 1, true); + $dateafter = dol_get_last_day($year ? $year : strftime("%Y", time()), $month ? $month : 12, true); + $balancebefore = $movement->calculateBalanceForProductBefore($productidselected, $datebefore); + $balanceafter = $movement->calculateBalanceForProductBefore($productidselected, $dateafter); //print '"; // Last movement @@ -601,7 +601,7 @@ if ($resql) if ($resqlbis) { $obj = $db->fetch_object($resqlbis); - $lastmovementdate=$db->jdate($obj->datem); + $lastmovementdate = $db->jdate($obj->datem); } else { @@ -673,32 +673,32 @@ if ($resql) print '
    '; } - $param=''; - if (! empty($contextpage) && $contextpage != $_SERVER["PHP_SELF"]) $param.='&contextpage='.$contextpage; - if ($limit > 0 && $limit != $conf->liste_limit) $param.='&limit='.$limit; - if ($id > 0) $param.='&id='.$id; - if ($search_movement) $param.='&search_movement='.urlencode($search_movement); - if ($search_inventorycode) $param.='&search_inventorycode='.urlencode($search_inventorycode); - if ($search_type_mouvement) $param.='&search_type_mouvement='.urlencode($search_type_mouvement); - if ($search_product_ref) $param.='&search_product_ref='.urlencode($search_product_ref); - if ($search_product) $param.='&search_product='.urlencode($search_product); - if ($search_batch) $param.='&search_batch='.urlencode($search_batch); - if ($search_warehouse > 0) $param.='&search_warehouse='.urlencode($search_warehouse); - if (!empty($sref)) $param.='&sref='.urlencode($sref); // FIXME $sref is not defined - if (!empty($snom)) $param.='&snom='.urlencode($snom); // FIXME $snom is not defined - if ($search_user) $param.='&search_user='.urlencode($search_user); - if ($idproduct > 0) $param.='&idproduct='.$idproduct; + $param = ''; + if (!empty($contextpage) && $contextpage != $_SERVER["PHP_SELF"]) $param .= '&contextpage='.$contextpage; + if ($limit > 0 && $limit != $conf->liste_limit) $param .= '&limit='.$limit; + if ($id > 0) $param .= '&id='.$id; + if ($search_movement) $param .= '&search_movement='.urlencode($search_movement); + if ($search_inventorycode) $param .= '&search_inventorycode='.urlencode($search_inventorycode); + if ($search_type_mouvement) $param .= '&search_type_mouvement='.urlencode($search_type_mouvement); + if ($search_product_ref) $param .= '&search_product_ref='.urlencode($search_product_ref); + if ($search_product) $param .= '&search_product='.urlencode($search_product); + if ($search_batch) $param .= '&search_batch='.urlencode($search_batch); + if ($search_warehouse > 0) $param .= '&search_warehouse='.urlencode($search_warehouse); + if (!empty($sref)) $param .= '&sref='.urlencode($sref); // FIXME $sref is not defined + if (!empty($snom)) $param .= '&snom='.urlencode($snom); // FIXME $snom is not defined + if ($search_user) $param .= '&search_user='.urlencode($search_user); + if ($idproduct > 0) $param .= '&idproduct='.$idproduct; // Add $param from extra fields include DOL_DOCUMENT_ROOT.'/core/tpl/extrafields_list_search_param.tpl.php'; // List of mass actions available - $arrayofmassactions = array( + $arrayofmassactions = array( // 'presend'=>$langs->trans("SendByMail"), // 'builddoc'=>$langs->trans("PDFMerge"), ); //if ($user->rights->stock->supprimer) $arrayofmassactions['predelete']=''.$langs->trans("Delete"); - if (in_array($massaction, array('presend','predelete'))) $arrayofmassactions=array(); - $massactionbutton=$form->selectMassAction('', $arrayofmassactions); + if (in_array($massaction, array('presend', 'predelete'))) $arrayofmassactions = array(); + $massactionbutton = $form->selectMassAction('', $arrayofmassactions); print ''; if ($optioncss != '') print ''; @@ -717,147 +717,147 @@ if ($resql) if ($sall) { - foreach($fieldstosearchall as $key => $val) $fieldstosearchall[$key]=$langs->trans($val); - print '
    '.$langs->trans("FilterOnInto", $sall) . join(', ', $fieldstosearchall).'
    '; + foreach ($fieldstosearchall as $key => $val) $fieldstosearchall[$key] = $langs->trans($val); + print '
    '.$langs->trans("FilterOnInto", $sall).join(', ', $fieldstosearchall).'
    '; } - $moreforfilter=''; + $moreforfilter = ''; - $parameters=array(); - $reshook=$hookmanager->executeHooks('printFieldPreListTitle', $parameters); // Note that $action and $object may have been modified by hook + $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($moreforfilter)) + if (!empty($moreforfilter)) { print '
    '; print $moreforfilter; print '
    '; } - $varpage=empty($contextpage)?$_SERVER["PHP_SELF"]:$contextpage; - $selectedfields=$form->multiSelectArrayWithCheckbox('selectedfields', $arrayfields, $varpage); // This also change content of $arrayfields + $varpage = empty($contextpage) ? $_SERVER["PHP_SELF"] : $contextpage; + $selectedfields = $form->multiSelectArrayWithCheckbox('selectedfields', $arrayfields, $varpage); // This also change content of $arrayfields print '
    '; - print '
    '; print ''; print ''; print ''; if (empty($conf->productbatch->enabled)) print ' '; //else print '
    '; - $syear = $year?$year:-1; + $syear = $year ? $year : -1; print ''; //print $formother->selectyear($syear,'year',1, 20, 5); print '
    '; - print ''; + print ''; print ''; - print ''; + print ''; print ''; print ''; print ''; //print ''; print $formproduct->selectWarehouses($search_warehouse, 'search_warehouse', 'warehouseopen,warehouseinternal', 1, 0, 0, '', 0, 0, null, 'maxwidth200'); print ''; print ''; print ''; print ''; print ''; print ''; print ''; //print ''; print ''; print ajax_combobox('search_type_mouvement'); // TODO: add new function $formentrepot->selectTypeOfMovement(...) like // print $formproduct->selectWarehouses($search_warehouse, 'search_warehouse', 'warehouseopen,warehouseinternal', 1, 0, 0, '', 0, 0, null, 'maxwidth200'); print ''; print '  '; print ''; print ''; print ''; @@ -881,108 +881,108 @@ if ($resql) include DOL_DOCUMENT_ROOT.'/core/tpl/extrafields_list_search_input.tpl.php'; // Fields from hook - $parameters=array('arrayfields'=>$arrayfields); - $reshook=$hookmanager->executeHooks('printFieldListOption', $parameters); // Note that $action and $object may have been modified by hook + $parameters = array('arrayfields'=>$arrayfields); + $reshook = $hookmanager->executeHooks('printFieldListOption', $parameters); // Note that $action and $object may have been modified by hook print $hookmanager->resPrint; // Date creation - if (! empty($arrayfields['m.datec']['checked'])) + if (!empty($arrayfields['m.datec']['checked'])) { print ''; print ''; print ''; - $searchpicto=$form->showFilterAndCheckAddButtons(0); + $searchpicto = $form->showFilterAndCheckAddButtons(0); print $searchpicto; print '
    '.$objp->mid.''.dol_print_date($db->jdate($objp->datem), 'dayhour').''; print $productstatic->getNomUrl(1, 'stock', 16); print "'; @@ -1019,36 +1019,36 @@ if ($resql) print $productstatic->label; print "'; if ($productlot->id > 0) print $productlot->getNomUrl(1); - else print $productlot->batch; // the id may not be defined if movement was entered when lot was not saved or if lot was removed after movement. + else print $productlot->batch; // the id may not be defined if movement was entered when lot was not saved or if lot was removed after movement. print ''. dol_print_date($objp->eatby, 'day') .''.dol_print_date($objp->eatby, 'day').''. dol_print_date($objp->sellby, 'day') .''.dol_print_date($objp->sellby, 'day').''; print $warehousestatic->getNomUrl(1); print "'; print $userstatic->getNomUrl(-1); print "'.$objp->label.''.$langs->trans('StockIncreaseAfterCorrectTransfer').''.$origin.''; @@ -1097,7 +1097,7 @@ if ($resql) print $objp->qty; print ''; @@ -1108,12 +1108,12 @@ if ($resql) print ''; if ($massactionbutton || $massaction) // If we are in select mode (massactionbutton defined) or if we have already selected and sent an action ($massaction) defined { - $selected=0; - if (in_array($obj->rowid, $arrayofselected)) $selected=1; - print ''; + $selected = 0; + if (in_array($obj->rowid, $arrayofselected)) $selected = 1; + print ''; } print '
    '; print $langs->trans("NbOfProductBeforePeriod", $productlabelselected, dol_print_date($datebefore, 'day', 'gmt')); @@ -1166,9 +1166,9 @@ else * Documents generes */ //Area for doc and last events of warehouse are stored on the main card of warehouse -$modulepart='movement'; +$modulepart = 'movement'; -if ($action != 'create' && $action != 'edit' && $action != 'delete' && $id>0) +if ($action != 'create' && $action != 'edit' && $action != 'delete' && $id > 0) { print '
    '; print '
    '; @@ -1177,33 +1177,33 @@ if ($action != 'create' && $action != 'edit' && $action != 'delete' && $id>0) // Documents $objectref = dol_sanitizeFileName($object->ref); // Add inventorycode & type_mouvement to filename of the pdf - if(!empty($search_inventorycode)) $objectref.="_".$id."_".$search_inventorycode; - if($search_type_mouvement) $objectref.="_".$search_type_mouvement; - $relativepath = $comref . '/' . $objectref . '.pdf'; - $filedir = $conf->stock->dir_output . '/movement/' . $objectref; + if (!empty($search_inventorycode)) $objectref .= "_".$id."_".$search_inventorycode; + if ($search_type_mouvement) $objectref .= "_".$search_type_mouvement; + $relativepath = $comref.'/'.$objectref.'.pdf'; + $filedir = $conf->stock->dir_output.'/movement/'.$objectref; - $urlsource=$_SERVER["PHP_SELF"]."?id=".$object->id."&search_inventorycode=".$search_inventorycode."&search_type_mouvement=$search_type_mouvement"; - $genallowed=$usercanread; - $delallowed=$usercancreate; + $urlsource = $_SERVER["PHP_SELF"]."?id=".$object->id."&search_inventorycode=".$search_inventorycode."&search_type_mouvement=$search_type_mouvement"; + $genallowed = $usercanread; + $delallowed = $usercancreate; - $genallowed=$user->rights->stock->lire; - $delallowed=$user->rights->stock->creer; + $genallowed = $user->rights->stock->lire; + $delallowed = $user->rights->stock->creer; print $formfile->showdocuments($modulepart, $objectref, $filedir, $urlsource, $genallowed, $delallowed, '', 0, 0, 0, 28, 0, '', 0, '', $object->default_lang, '', $object); - $somethingshown=$formfile->numoffiles; + $somethingshown = $formfile->numoffiles; print '
    '; $MAXEVENT = 10; $morehtmlright = ''; - $morehtmlright.= $langs->trans("SeeAll"); - $morehtmlright.= ''; + $morehtmlright .= $langs->trans("SeeAll"); + $morehtmlright .= ''; // List of actions on element - include_once DOL_DOCUMENT_ROOT . '/core/class/html.formactions.class.php'; + include_once DOL_DOCUMENT_ROOT.'/core/class/html.formactions.class.php'; $formactions = new FormActions($db); - $somethingshown = $formactions->showactions($object, 'mouvement', 0, 1, '', $MAXEVENT, '', $morehtmlright); // Show all action for product + $somethingshown = $formactions->showactions($object, 'mouvement', 0, 1, '', $MAXEVENT, '', $morehtmlright); // Show all action for product print '
    '; } diff --git a/htdocs/product/stock/movement_list.php b/htdocs/product/stock/movement_list.php index 85f40a9d214..09273ee947d 100644 --- a/htdocs/product/stock/movement_list.php +++ b/htdocs/product/stock/movement_list.php @@ -37,29 +37,29 @@ require_once DOL_DOCUMENT_ROOT.'/product/class/html.formproduct.class.php'; require_once DOL_DOCUMENT_ROOT.'/core/lib/stock.lib.php'; require_once DOL_DOCUMENT_ROOT.'/core/lib/product.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.'/core/class/html.formprojet.class.php'; require_once DOL_DOCUMENT_ROOT.'/projet/class/project.class.php'; } // Load translation files required by the page $langs->loadLangs(array('products', 'stocks', 'orders')); -if (! empty($conf->productbatch->enabled)) $langs->load("productbatch"); +if (!empty($conf->productbatch->enabled)) $langs->load("productbatch"); // Security check -$result=restrictedArea($user, 'stock'); +$result = restrictedArea($user, 'stock'); -$id=GETPOST('id', 'int'); +$id = GETPOST('id', 'int'); $ref = GETPOST('ref', 'alpha'); -$msid=GETPOST('msid', 'int'); -$product_id=GETPOST("product_id", 'int'); -$action=GETPOST('action', 'aZ09'); -$cancel=GETPOST('cancel', 'alpha'); -$contextpage=GETPOST('contextpage', 'aZ')?GETPOST('contextpage', 'aZ'):'movementlist'; +$msid = GETPOST('msid', 'int'); +$product_id = GETPOST("product_id", 'int'); +$action = GETPOST('action', 'aZ09'); +$cancel = GETPOST('cancel', 'alpha'); +$contextpage = GETPOST('contextpage', 'aZ') ?GETPOST('contextpage', 'aZ') : 'movementlist'; // Security check //$result=restrictedArea($user, 'stock', $id, 'entrepot&stock'); -$result=restrictedArea($user, 'stock'); +$result = restrictedArea($user, 'stock'); $idproduct = GETPOST('idproduct', 'int'); $year = GETPOST("year"); @@ -73,18 +73,18 @@ $search_inventorycode = trim(GETPOST("search_inventorycode")); $search_user = trim(GETPOST("search_user")); $search_batch = trim(GETPOST("search_batch")); $search_qty = trim(GETPOST("search_qty")); -$search_type_mouvement=GETPOST('search_type_mouvement', 'int'); +$search_type_mouvement = GETPOST('search_type_mouvement', 'int'); -$limit = GETPOST('limit', 'int')?GETPOST('limit', 'int'):$conf->liste_limit; +$limit = GETPOST('limit', 'int') ?GETPOST('limit', 'int') : $conf->liste_limit; $page = GETPOST("page", 'int'); $sortfield = GETPOST("sortfield", 'alpha'); $sortorder = GETPOST("sortorder", 'alpha'); if (empty($page) || $page == -1) { $page = 0; } // If $page is not defined, or '' or -1 $offset = $limit * $page; -if (! $sortfield) $sortfield="m.datem"; -if (! $sortorder) $sortorder="DESC"; +if (!$sortfield) $sortfield = "m.datem"; +if (!$sortorder) $sortorder = "DESC"; -$pdluoid=GETPOST('pdluoid', 'int'); +$pdluoid = GETPOST('pdluoid', 'int'); // Initialize technical object to manage hooks of page. Note that conf->hooks_modules contains array of hook context $object = new MouvementStock($db); @@ -95,17 +95,17 @@ $formfile = new FormFile($db); // fetch optionals attributes and labels $extrafields->fetch_name_optionals_label($object->table_element); -$search_array_options=$extrafields->getOptionalsFromPost($object->table_element, '', 'search_'); +$search_array_options = $extrafields->getOptionalsFromPost($object->table_element, '', 'search_'); -$arrayfields=array( +$arrayfields = array( 'm.rowid'=>array('label'=>$langs->trans("Ref"), 'checked'=>1), 'm.datem'=>array('label'=>$langs->trans("Date"), 'checked'=>1), 'p.ref'=>array('label'=>$langs->trans("ProductRef"), 'checked'=>1, 'css'=>'maxwidth100'), 'p.label'=>array('label'=>$langs->trans("ProductLabel"), 'checked'=>1), - 'm.batch'=>array('label'=>$langs->trans("BatchNumberShort"), 'checked'=>1, 'enabled'=>(! empty($conf->productbatch->enabled))), - 'pl.eatby'=>array('label'=>$langs->trans("EatByDate"), 'checked'=>0, 'enabled'=>(! empty($conf->productbatch->enabled))), - 'pl.sellby'=>array('label'=>$langs->trans("SellByDate"), 'checked'=>0, 'position'=>10, 'enabled'=>(! empty($conf->productbatch->enabled))), - 'e.ref'=>array('label'=>$langs->trans("Warehouse"), 'checked'=>1, 'enabled'=>(! $id > 0)), // If we are on specific warehouse, we hide it + 'm.batch'=>array('label'=>$langs->trans("BatchNumberShort"), 'checked'=>1, 'enabled'=>(!empty($conf->productbatch->enabled))), + 'pl.eatby'=>array('label'=>$langs->trans("EatByDate"), 'checked'=>0, 'enabled'=>(!empty($conf->productbatch->enabled))), + 'pl.sellby'=>array('label'=>$langs->trans("SellByDate"), 'checked'=>0, 'position'=>10, 'enabled'=>(!empty($conf->productbatch->enabled))), + 'e.ref'=>array('label'=>$langs->trans("Warehouse"), 'checked'=>1, 'enabled'=>(!$id > 0)), // If we are on specific warehouse, we hide it 'm.fk_user_author'=>array('label'=>$langs->trans("Author"), 'checked'=>0), 'm.inventorycode'=>array('label'=>$langs->trans("InventoryCodeShort"), 'checked'=>1), 'm.label'=>array('label'=>$langs->trans("MovementLabel"), 'checked'=>1), @@ -132,11 +132,11 @@ $usercanread = (($user->rights->stock->mouvement->lire)); $usercancreate = (($user->rights->stock->mouvement->creer)); $usercandelete = (($user->rights->stock->mouvement->supprimer)); -if (GETPOST('cancel', 'alpha')) { $action='list'; $massaction=''; } -if (! GETPOST('confirmmassaction', 'alpha') && $massaction != 'presend' && $massaction != 'confirm_presend') { $massaction=''; } +if (GETPOST('cancel', 'alpha')) { $action = 'list'; $massaction = ''; } +if (!GETPOST('confirmmassaction', 'alpha') && $massaction != 'presend' && $massaction != 'confirm_presend') { $massaction = ''; } -$parameters=array(); -$reshook=$hookmanager->executeHooks('doActions', $parameters, $object, $action); // Note that $action and $object may have been modified by some hooks +$parameters = array(); +$reshook = $hookmanager->executeHooks('doActions', $parameters, $object, $action); // Note that $action and $object may have been modified by some hooks if ($reshook < 0) setEventMessages($hookmanager->error, $hookmanager->errors, 'errors'); include DOL_DOCUMENT_ROOT.'/core/actions_changeselectedfields.inc.php'; @@ -144,45 +144,45 @@ 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')) // Both test are required to be compatible with all browsers { - $year=''; - $month=''; - $search_ref=''; - $search_movement=""; - $search_type_mouvement=""; - $search_inventorycode=""; - $search_product_ref=""; - $search_product=""; - $search_warehouse=""; - $search_user=""; - $search_batch=""; - $search_qty=''; - $sall=""; - $toselect=''; - $search_array_options=array(); + $year = ''; + $month = ''; + $search_ref = ''; + $search_movement = ""; + $search_type_mouvement = ""; + $search_inventorycode = ""; + $search_product_ref = ""; + $search_product = ""; + $search_warehouse = ""; + $search_user = ""; + $search_batch = ""; + $search_qty = ''; + $sall = ""; + $toselect = ''; + $search_array_options = array(); } // Correct stock if ($action == "correct_stock") { $product = new Product($db); - if (! empty($product_id)) $result=$product->fetch($product_id); + if (!empty($product_id)) $result = $product->fetch($product_id); - $error=0; + $error = 0; if (empty($product_id)) { $error++; setEventMessages($langs->trans("ErrorFieldRequired", $langs->transnoentitiesnoconv("Product")), null, 'errors'); - $action='correction'; + $action = 'correction'; } - if (! is_numeric($_POST["nbpiece"])) + if (!is_numeric($_POST["nbpiece"])) { $error++; setEventMessages($langs->trans("ErrorFieldMustBeANumeric", $langs->transnoentitiesnoconv("NumberOfUnit")), null, 'errors'); - $action='correction'; + $action = 'correction'; } - if (! $error) + if (!$error) { $origin_element = ''; $origin_id = null; @@ -227,7 +227,7 @@ if ($action == "correct_stock") GETPOST('inventorycode'), $origin_element, $origin_id - ); // We do not change value of stock for a correction + ); // We do not change value of stock for a correction } if ($result > 0) @@ -239,72 +239,72 @@ if ($action == "correct_stock") { $error++; setEventMessages($product->error, $product->errors, 'errors'); - $action='correction'; + $action = 'correction'; } } - if (! $error) $action=''; + if (!$error) $action = ''; } // Transfer stock from a warehouse to another warehouse -if ($action == "transfert_stock" && ! $cancel) +if ($action == "transfert_stock" && !$cancel) { $product = new Product($db); - if (! empty($product_id)) $result=$product->fetch($product_id); + if (!empty($product_id)) $result = $product->fetch($product_id); - if (! (GETPOST("id_entrepot_destination", 'int') > 0)) + if (!(GETPOST("id_entrepot_destination", 'int') > 0)) { setEventMessages($langs->trans("ErrorFieldRequired", $langs->transnoentitiesnoconv("Warehouse")), null, 'errors'); $error++; - $action='transfert'; + $action = 'transfert'; } if (empty($product_id)) { $error++; setEventMessages($langs->trans("ErrorFieldRequired", $langs->transnoentitiesnoconv("Product")), null, 'errors'); - $action='transfert'; + $action = 'transfert'; } - if (! GETPOST("nbpiece", 'int')) + if (!GETPOST("nbpiece", 'int')) { setEventMessages($langs->trans("ErrorFieldRequired", $langs->transnoentitiesnoconv("NumberOfUnit")), null, 'errors'); $error++; - $action='transfert'; + $action = 'transfert'; } if ($id == GETPOST("id_entrepot_destination", 'int')) { setEventMessages($langs->trans("ErrorSrcAndTargetWarehouseMustDiffers"), null, 'errors'); $error++; - $action='transfert'; + $action = 'transfert'; } - if (! empty($conf->productbatch->enabled)) + if (!empty($conf->productbatch->enabled)) { $product = new Product($db); - $result=$product->fetch($product_id); + $result = $product->fetch($product_id); - if ($product->hasbatch() && ! GETPOST("batch_number")) + if ($product->hasbatch() && !GETPOST("batch_number")) { setEventMessages($langs->trans("ErrorFieldRequired", $langs->transnoentitiesnoconv("batch_number")), null, 'errors'); $error++; - $action='transfert'; + $action = 'transfert'; } } - if (! $error) + if (!$error) { if ($id) { $object = new Entrepot($db); - $result=$object->fetch($id); + $result = $object->fetch($id); $db->begin(); - $product->load_stock('novirtual'); // Load array product->stock_warehouse + $product->load_stock('novirtual'); // Load array product->stock_warehouse // Define value of products moved - $pricesrc=0; - if (isset($product->pmp)) $pricesrc=$product->pmp; - $pricedest=$pricesrc; + $pricesrc = 0; + if (isset($product->pmp)) $pricesrc = $product->pmp; + $pricedest = $pricesrc; if ($product->hasbatch()) { @@ -312,13 +312,13 @@ if ($action == "transfert_stock" && ! $cancel) if ($pdluoid > 0) { - $result=$pdluo->fetch($pdluoid); + $result = $pdluo->fetch($pdluoid); if ($result) { - $srcwarehouseid=$pdluo->warehouseid; - $batch=$pdluo->batch; - $eatby=$pdluo->eatby; - $sellby=$pdluo->sellby; + $srcwarehouseid = $pdluo->warehouseid; + $batch = $pdluo->batch; + $eatby = $pdluo->eatby; + $sellby = $pdluo->sellby; } else { @@ -328,16 +328,16 @@ if ($action == "transfert_stock" && ! $cancel) } else { - $srcwarehouseid=$id; - $batch=GETPOST('batch_number'); - $eatby=$d_eatby; - $sellby=$d_sellby; + $srcwarehouseid = $id; + $batch = GETPOST('batch_number'); + $eatby = $d_eatby; + $sellby = $d_sellby; } - if (! $error) + if (!$error) { // Remove stock - $result1=$product->correct_stock_batch( + $result1 = $product->correct_stock_batch( $user, $srcwarehouseid, GETPOST("nbpiece", 'int'), @@ -348,7 +348,7 @@ if ($action == "transfert_stock" && ! $cancel) GETPOST('inventorycode') ); // Add stock - $result2=$product->correct_stock_batch( + $result2 = $product->correct_stock_batch( $user, GETPOST("id_entrepot_destination", 'int'), GETPOST("nbpiece", 'int'), @@ -363,7 +363,7 @@ if ($action == "transfert_stock" && ! $cancel) else { // Remove stock - $result1=$product->correct_stock( + $result1 = $product->correct_stock( $user, $id, GETPOST("nbpiece"), @@ -374,7 +374,7 @@ if ($action == "transfert_stock" && ! $cancel) ); // Add stock - $result2=$product->correct_stock( + $result2 = $product->correct_stock( $user, GETPOST("id_entrepot_destination"), GETPOST("nbpiece"), @@ -384,7 +384,7 @@ if ($action == "transfert_stock" && ! $cancel) GETPOST('inventorycode') ); } - if (! $error && $result1 >= 0 && $result2 >= 0) + if (!$error && $result1 >= 0 && $result2 >= 0) { $db->commit(); @@ -403,7 +403,7 @@ if ($action == "transfert_stock" && ! $cancel) { setEventMessages($product->error, $product->errors, 'errors'); $db->rollback(); - $action='transfert'; + $action = 'transfert'; } } } @@ -484,9 +484,9 @@ if (empty($conf->global->MAIN_DISABLE_FULL_SCANLIST)) } } -if(empty($search_inventorycode)) +if (empty($search_inventorycode)) { - $sql.= $db->plimit($limit+1, $offset); + $sql .= $db->plimit($limit + 1, $offset); } else { @@ -497,7 +497,7 @@ else $resql = $db->query($sql); -if(!empty($search_inventorycode)) $limit = $db->num_rows($resql); +if (!empty($search_inventorycode)) $limit = $db->num_rows($resql); if ($resql) { @@ -519,16 +519,16 @@ if ($resql) $num = $db->num_rows($resql); - $arrayofselected=is_array($toselect)?$toselect:array(); + $arrayofselected = is_array($toselect) ? $toselect : array(); $i = 0; - $help_url='EN:Module_Stocks_En|FR:Module_Stock|ES:Módulo_Stocks'; + $help_url = 'EN:Module_Stocks_En|FR:Module_Stock|ES:Módulo_Stocks'; if ($msid) $texte = $langs->trans('StockMovementForId', $msid); else { $texte = $langs->trans("ListOfStockMovements"); - if ($id) $texte.=' ('.$langs->trans("ForThisWarehouse").')'; + if ($id) $texte .= ' ('.$langs->trans("ForThisWarehouse").')'; } llxHeader("", $texte, $help_url); @@ -558,25 +558,25 @@ if ($resql) print '
    '; print '
    '; - print ''; + print '
    '; print ''; // Description print ''; - $calcproductsunique=$object->nb_different_products(); - $calcproducts=$object->nb_products(); + $calcproductsunique = $object->nb_different_products(); + $calcproducts = $object->nb_products(); // Total nb of different products print '"; // Nb of products print '"; print '
    '.$langs->trans("Description").''.dol_htmlentitiesbr($object->description).'
    '.$langs->trans("NumberOfDifferentProducts").''; - print empty($calcproductsunique['nb'])?'0':$calcproductsunique['nb']; + print empty($calcproductsunique['nb']) ? '0' : $calcproductsunique['nb']; print "
    '.$langs->trans("NumberOfProducts").''; - $valtoshow=price2num($calcproducts['nb'], 'MS'); - print empty($valtoshow)?'0':$valtoshow; + $valtoshow = price2num($calcproducts['nb'], 'MS'); + print empty($valtoshow) ? '0' : $valtoshow; print "
    '; @@ -590,7 +590,7 @@ if ($resql) // Value print '
    '.$langs->trans("EstimatedStockValueShort").''; - print price((empty($calcproducts['value'])?'0':price2num($calcproducts['value'], 'MT')), 0, $langs, 0, -1, -1, $conf->currency); + print price((empty($calcproducts['value']) ? '0' : price2num($calcproducts['value'], 'MT')), 0, $langs, 0, -1, -1, $conf->currency); print "
    '."\n"; + print '
    '."\n"; // Fields title search print ''; - if (! empty($arrayfields['m.rowid']['checked'])) + if (!empty($arrayfields['m.rowid']['checked'])) { // Ref print ''; } - if (! empty($arrayfields['m.datem']['checked'])) + if (!empty($arrayfields['m.datem']['checked'])) { print ''; } - if (! empty($arrayfields['p.ref']['checked'])) + if (!empty($arrayfields['p.ref']['checked'])) { // Product Ref print ''; } - if (! empty($arrayfields['p.label']['checked'])) + if (!empty($arrayfields['p.label']['checked'])) { // Product label print ''; } // Batch - if (! empty($arrayfields['m.batch']['checked'])) + if (!empty($arrayfields['m.batch']['checked'])) { print ''; } - if (! empty($arrayfields['pl.eatby']['checked'])) + if (!empty($arrayfields['pl.eatby']['checked'])) { print ''; } - if (! empty($arrayfields['pl.sellby']['checked'])) + if (!empty($arrayfields['pl.sellby']['checked'])) { print ''; } // Warehouse - if (! empty($arrayfields['e.ref']['checked'])) + if (!empty($arrayfields['e.ref']['checked'])) { print ''; } - if (! empty($arrayfields['m.fk_user_author']['checked'])) + if (!empty($arrayfields['m.fk_user_author']['checked'])) { // Author print ''; } - if (! empty($arrayfields['m.inventorycode']['checked'])) + if (!empty($arrayfields['m.inventorycode']['checked'])) { // Inventory code print ''; } - if (! empty($arrayfields['m.label']['checked'])) + if (!empty($arrayfields['m.label']['checked'])) { // Label of movement print ''; } - if (! empty($arrayfields['m.type_mouvement']['checked'])) + if (!empty($arrayfields['m.type_mouvement']['checked'])) { // Type of movement print ''; } - if (! empty($arrayfields['origin']['checked'])) + if (!empty($arrayfields['origin']['checked'])) { // Origin of movement print ''; } - if (! empty($arrayfields['m.value']['checked'])) + if (!empty($arrayfields['m.value']['checked'])) { // Qty print ''; } - if (! empty($arrayfields['m.price']['checked'])) + if (!empty($arrayfields['m.price']['checked'])) { // Price print ''; } - if (! empty($arrayfields['m.fk_projet']['checked'])) + if (!empty($arrayfields['m.fk_projet']['checked'])) { // fk_project print ''; } // Date modification - if (! empty($arrayfields['m.tms']['checked'])) + if (!empty($arrayfields['m.tms']['checked'])) { print ''; } // Actions print ''; print "\n"; print ''; - if (! empty($arrayfields['m.rowid']['checked'])) { + if (!empty($arrayfields['m.rowid']['checked'])) { print_liste_field_titre($arrayfields['m.rowid']['label'], $_SERVER["PHP_SELF"], 'm.rowid', '', $param, '', $sortfield, $sortorder); } - if (! empty($arrayfields['m.datem']['checked'])) { + if (!empty($arrayfields['m.datem']['checked'])) { print_liste_field_titre($arrayfields['m.datem']['label'], $_SERVER["PHP_SELF"], 'm.datem', '', $param, '', $sortfield, $sortorder); } - if (! empty($arrayfields['p.ref']['checked'])) { + 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.label']['checked'])) { + if (!empty($arrayfields['p.label']['checked'])) { print_liste_field_titre($arrayfields['p.label']['label'], $_SERVER["PHP_SELF"], 'p.label', '', $param, '', $sortfield, $sortorder); } - if (! empty($arrayfields['m.batch']['checked'])) { + if (!empty($arrayfields['m.batch']['checked'])) { print_liste_field_titre($arrayfields['m.batch']['label'], $_SERVER["PHP_SELF"], 'm.batch', '', $param, '', $sortfield, $sortorder, 'center '); } - if (! empty($arrayfields['pl.eatby']['checked'])) { + if (!empty($arrayfields['pl.eatby']['checked'])) { print_liste_field_titre($arrayfields['pl.eatby']['label'], $_SERVER["PHP_SELF"], 'pl.eatby', '', $param, '', $sortfield, $sortorder, 'center '); } - if (! empty($arrayfields['pl.sellby']['checked'])) { + if (!empty($arrayfields['pl.sellby']['checked'])) { print_liste_field_titre($arrayfields['pl.sellby']['label'], $_SERVER["PHP_SELF"], 'pl.sellby', '', $param, '', $sortfield, $sortorder, 'center '); } - if (! empty($arrayfields['e.ref']['checked'])) { + if (!empty($arrayfields['e.ref']['checked'])) { // We are on a specific warehouse card, no filter on other should be possible print_liste_field_titre($arrayfields['e.ref']['label'], $_SERVER["PHP_SELF"], "e.ref", "", $param, "", $sortfield, $sortorder); } - if (! empty($arrayfields['m.fk_user_author']['checked'])) { + if (!empty($arrayfields['m.fk_user_author']['checked'])) { print_liste_field_titre($arrayfields['m.fk_user_author']['label'], $_SERVER["PHP_SELF"], "m.fk_user_author", "", $param, "", $sortfield, $sortorder); } - if (! empty($arrayfields['m.inventorycode']['checked'])) { + if (!empty($arrayfields['m.inventorycode']['checked'])) { print_liste_field_titre($arrayfields['m.inventorycode']['label'], $_SERVER["PHP_SELF"], "m.inventorycode", "", $param, "", $sortfield, $sortorder); } - if (! empty($arrayfields['m.label']['checked'])) { + if (!empty($arrayfields['m.label']['checked'])) { print_liste_field_titre($arrayfields['m.label']['label'], $_SERVER["PHP_SELF"], "m.label", "", $param, "", $sortfield, $sortorder); } - if (! empty($arrayfields['m.type_mouvement']['checked'])) { + if (!empty($arrayfields['m.type_mouvement']['checked'])) { print_liste_field_titre($arrayfields['m.type_mouvement']['label'], $_SERVER["PHP_SELF"], "m.type_mouvement", "", $param, '', $sortfield, $sortorder, 'center '); } - if (! empty($arrayfields['origin']['checked'])) { + if (!empty($arrayfields['origin']['checked'])) { print_liste_field_titre($arrayfields['origin']['label'], $_SERVER["PHP_SELF"], "", "", $param, "", $sortfield, $sortorder); } - if (! empty($arrayfields['m.value']['checked'])) { + if (!empty($arrayfields['m.value']['checked'])) { print_liste_field_titre($arrayfields['m.value']['label'], $_SERVER["PHP_SELF"], "m.value", "", $param, '', $sortfield, $sortorder, 'right '); } - if (! empty($arrayfields['m.price']['checked'])) { + if (!empty($arrayfields['m.price']['checked'])) { print_liste_field_titre($arrayfields['m.price']['label'], $_SERVER["PHP_SELF"], "m.price", "", $param, '', $sortfield, $sortorder, 'right '); } - if (! empty($arrayfields['m.fk_projet']['checked'])) { + if (!empty($arrayfields['m.fk_projet']['checked'])) { print_liste_field_titre($arrayfields['m.fk_projet']['label'], $_SERVER["PHP_SELF"], "m.fk_projet", "", $param, 'align="right"', $sortfield, $sortorder); } @@ -1001,23 +1001,23 @@ if ($resql) print ''; // Id movement - if (! empty($arrayfields['m.rowid']['checked'])) + if (!empty($arrayfields['m.rowid']['checked'])) { - print ''; // This is primary not movement id + print ''; // This is primary not movement id } - if (! empty($arrayfields['m.datem']['checked'])) + if (!empty($arrayfields['m.datem']['checked'])) { // Date print ''; } - if (! empty($arrayfields['p.ref']['checked'])) + if (!empty($arrayfields['p.ref']['checked'])) { // Product ref print '\n"; } - if (! empty($arrayfields['p.label']['checked'])) + if (!empty($arrayfields['p.label']['checked'])) { // Product label print '\n"; } - if (! empty($arrayfields['m.batch']['checked'])) + if (!empty($arrayfields['m.batch']['checked'])) { print ''; } - if (! empty($arrayfields['pl.eatby']['checked'])) + if (!empty($arrayfields['pl.eatby']['checked'])) { - print ''; + print ''; } - if (! empty($arrayfields['pl.sellby']['checked'])) + if (!empty($arrayfields['pl.sellby']['checked'])) { - print ''; + print ''; } // Warehouse - if (! empty($arrayfields['e.ref']['checked'])) + if (!empty($arrayfields['e.ref']['checked'])) { print '\n"; } // Author - if (! empty($arrayfields['m.fk_user_author']['checked'])) + if (!empty($arrayfields['m.fk_user_author']['checked'])) { print '\n"; } - if (! empty($arrayfields['m.inventorycode']['checked'])) + if (!empty($arrayfields['m.inventorycode']['checked'])) { // Inventory code print ''; } - if (! empty($arrayfields['m.type_mouvement']['checked'])) + if (!empty($arrayfields['m.type_mouvement']['checked'])) { // Type of movement - switch($objp->type_mouvement){ + switch ($objp->type_mouvement) { case "0": print ''; break; @@ -1093,12 +1093,12 @@ if ($resql) break; } } - if (! empty($arrayfields['origin']['checked'])) + if (!empty($arrayfields['origin']['checked'])) { // Origin of movement print ''; } - if (! empty($arrayfields['m.value']['checked'])) + if (!empty($arrayfields['m.value']['checked'])) { // Qty print ''; } - if (! empty($arrayfields['m.price']['checked'])) + if (!empty($arrayfields['m.price']['checked'])) { // Price print ''; } - if (! empty($arrayfields['m.fk_projet']['checked'])) + if (!empty($arrayfields['m.fk_projet']['checked'])) { // fk_project print ''; - if (! $i) $totalarray['nbfield']++; + if (!$i) $totalarray['nbfield']++; print "\n"; $i++; @@ -1145,16 +1145,16 @@ if ($resql) { print "
    "; - $productidselected=0; + $productidselected = 0; foreach ($arrayofuniqueproduct as $key => $val) { - $productidselected=$key; - $productlabelselected=$val; + $productidselected = $key; + $productlabelselected = $val; } - $datebefore=dol_get_first_day($year?$year:strftime("%Y", time()), $month?$month:1, true); - $dateafter=dol_get_last_day($year?$year:strftime("%Y", time()), $month?$month:12, true); - $balancebefore=$movement->calculateBalanceForProductBefore($productidselected, $datebefore); - $balanceafter=$movement->calculateBalanceForProductBefore($productidselected, $dateafter); + $datebefore = dol_get_first_day($year ? $year : strftime("%Y", time()), $month ? $month : 1, true); + $dateafter = dol_get_last_day($year ? $year : strftime("%Y", time()), $month ? $month : 12, true); + $balancebefore = $movement->calculateBalanceForProductBefore($productidselected, $datebefore); + $balanceafter = $movement->calculateBalanceForProductBefore($productidselected, $dateafter); //print ''; @@ -342,10 +342,10 @@ if ($socid && ! $projectid && ! $project_ref && $user->rights->societe->lire) { // Supplier code if ($socstat->fournisseur && !empty($socstat->code_fournisseur)) { print ''; @@ -380,21 +380,21 @@ if ($projectid > 0 || $project_ref) { $linkback = ''.$langs->trans("BackToList").''; - $morehtmlref='
    '; + $morehtmlref = '
    '; // Title - $morehtmlref.=$object->title; + $morehtmlref .= $object->title; // Thirdparty if ($object->thirdparty->id > 0) { - $morehtmlref.='
    '.$langs->trans('ThirdParty') . ' : ' . $object->thirdparty->getNomUrl(1, 'project'); + $morehtmlref .= '
    '.$langs->trans('ThirdParty').' : '.$object->thirdparty->getNomUrl(1, 'project'); } - $morehtmlref.='
    '; + $morehtmlref .= '
    '; // Define a complementary filter for search of next/prev ref. - if (! $user->rights->projet->all->lire) + if (!$user->rights->projet->all->lire) { $objectsListId = $object->getProjectsAuthorizedForUser($user, 0, 0); - $object->next_prev_filter=" rowid in (".(count($objectsListId)?join(',', array_keys($objectsListId)):'0').")"; + $object->next_prev_filter = " rowid in (".(count($objectsListId) ?join(',', array_keys($objectsListId)) : '0').")"; } dol_banner_tab($object, 'project_ref', $linkback, 1, 'ref', 'ref', $morehtmlref); @@ -405,7 +405,7 @@ if ($projectid > 0 || $project_ref) { print '
    '; print ''; print ''; print ''; if (empty($conf->productbatch->enabled)) print ' '; //else print '
    '; - $syear = $year?$year:-1; + $syear = $year ? $year : -1; print ''; //print $formother->selectyear($syear,'year',1, 20, 5); print '
    '; - print ''; + print ''; print ''; - print ''; + print ''; print ''; print ''; print ''; //print ''; print $formproduct->selectWarehouses($search_warehouse, 'search_warehouse', 'warehouseopen,warehouseinternal', 1, 0, 0, '', 0, 0, null, 'maxwidth200'); print ''; print ''; print ''; print ''; print ''; print ''; print ''; //print ''; print ''; print ajax_combobox('search_type_mouvement'); // TODO: add new function $formentrepot->selectTypeOfMovement(...) like // print $formproduct->selectWarehouses($search_warehouse, 'search_warehouse', 'warehouseopen,warehouseinternal', 1, 0, 0, '', 0, 0, null, 'maxwidth200'); print ''; print '  '; print ''; print ''; print ''; print '  '; print ''; @@ -870,76 +870,76 @@ if ($resql) include DOL_DOCUMENT_ROOT.'/core/tpl/extrafields_list_search_input.tpl.php'; // Fields from hook - $parameters=array('arrayfields'=>$arrayfields); - $reshook=$hookmanager->executeHooks('printFieldListOption', $parameters); // Note that $action and $object may have been modified by hook + $parameters = array('arrayfields'=>$arrayfields); + $reshook = $hookmanager->executeHooks('printFieldListOption', $parameters); // Note that $action and $object may have been modified by hook print $hookmanager->resPrint; // Date creation - if (! empty($arrayfields['m.datec']['checked'])) + if (!empty($arrayfields['m.datec']['checked'])) { print ''; print ''; print ''; - $searchpicto=$form->showFilterAndCheckAddButtons(0); + $searchpicto = $form->showFilterAndCheckAddButtons(0); print $searchpicto; print '
    '.$objp->mid.''.$objp->mid.''.dol_print_date($db->jdate($objp->datem), 'dayhour').''; print $productstatic->getNomUrl(1, 'stock', 16); print "'; @@ -1028,36 +1028,36 @@ if ($resql) print $productstatic->label; print "'; if ($productlot->id > 0) print $productlot->getNomUrl(1); - else print $productlot->batch; // the id may not be defined if movement was entered when lot was not saved or if lot was removed after movement. + else print $productlot->batch; // the id may not be defined if movement was entered when lot was not saved or if lot was removed after movement. print ''. dol_print_date($objp->eatby, 'day') .''.dol_print_date($objp->eatby, 'day').''. dol_print_date($objp->sellby, 'day') .''.dol_print_date($objp->sellby, 'day').''; print $warehousestatic->getNomUrl(1); print "'; print $userstatic->getNomUrl(-1); print "'.''.$objp->label.''.$langs->trans('StockIncreaseAfterCorrectTransfer').''.$origin.''; @@ -1106,14 +1106,14 @@ if ($resql) print $objp->qty; print ''; if ($objp->price != 0) print price($objp->price); print ''; @@ -1124,12 +1124,12 @@ if ($resql) print ''; if ($massactionbutton || $massaction) // If we are in select mode (massactionbutton defined) or if we have already selected and sent an action ($massaction) defined { - $selected=0; - if (in_array($obj->rowid, $arrayofselected)) $selected=1; - print ''; + $selected = 0; + if (in_array($obj->rowid, $arrayofselected)) $selected = 1; + print ''; } print '
    '; print $langs->trans("NbOfProductBeforePeriod", $productlabelselected, dol_print_date($datebefore, 'day', 'gmt')); diff --git a/htdocs/product/stock/product.php b/htdocs/product/stock/product.php index 3428b75f395..e6f288d2a52 100644 --- a/htdocs/product/stock/product.php +++ b/htdocs/product/stock/product.php @@ -38,46 +38,46 @@ require_once DOL_DOCUMENT_ROOT.'/fourn/class/fournisseur.product.class.php'; require_once DOL_DOCUMENT_ROOT.'/core/lib/product.lib.php'; require_once DOL_DOCUMENT_ROOT.'/product/class/html.formproduct.class.php'; require_once DOL_DOCUMENT_ROOT.'/product/stock/class/productstockentrepot.class.php'; -if (! empty($conf->productbatch->enabled)) { +if (!empty($conf->productbatch->enabled)) { require_once DOL_DOCUMENT_ROOT.'/product/class/productbatch.class.php'; } -if (! empty($conf->projet->enabled)) { +if (!empty($conf->projet->enabled)) { require_once DOL_DOCUMENT_ROOT.'/core/class/html.formprojet.class.php'; require_once DOL_DOCUMENT_ROOT.'/projet/class/project.class.php'; } -if (! empty($conf->variants->enabled)) { - require_once DOL_DOCUMENT_ROOT . '/variants/class/ProductAttribute.class.php'; - require_once DOL_DOCUMENT_ROOT . '/variants/class/ProductAttributeValue.class.php'; - require_once DOL_DOCUMENT_ROOT . '/variants/class/ProductCombination.class.php'; - require_once DOL_DOCUMENT_ROOT . '/variants/class/ProductCombination2ValuePair.class.php'; +if (!empty($conf->variants->enabled)) { + require_once DOL_DOCUMENT_ROOT.'/variants/class/ProductAttribute.class.php'; + require_once DOL_DOCUMENT_ROOT.'/variants/class/ProductAttributeValue.class.php'; + require_once DOL_DOCUMENT_ROOT.'/variants/class/ProductCombination.class.php'; + require_once DOL_DOCUMENT_ROOT.'/variants/class/ProductCombination2ValuePair.class.php'; } // Load translation files required by the page $langs->loadlangs(array('products', 'orders', 'bills', 'stocks', 'sendings')); -if (! empty($conf->productbatch->enabled)) $langs->load("productbatch"); +if (!empty($conf->productbatch->enabled)) $langs->load("productbatch"); -$backtopage=GETPOST('backtopage', 'alpha'); -$action=GETPOST('action', 'aZ09'); -$cancel=GETPOST('cancel', 'alpha'); +$backtopage = GETPOST('backtopage', 'alpha'); +$action = GETPOST('action', 'aZ09'); +$cancel = GETPOST('cancel', 'alpha'); -$id=GETPOST('id', 'int'); -$ref=GETPOST('ref', 'alpha'); +$id = GETPOST('id', 'int'); +$ref = GETPOST('ref', 'alpha'); $stocklimit = GETPOST('seuil_stock_alerte'); $desiredstock = GETPOST('desiredstock'); $cancel = GETPOST('cancel', 'alpha'); -$fieldid = isset($_GET["ref"])?'ref':'rowid'; -$d_eatby=dol_mktime(0, 0, 0, $_POST['eatbymonth'], $_POST['eatbyday'], $_POST['eatbyyear']); -$d_sellby=dol_mktime(0, 0, 0, $_POST['sellbymonth'], $_POST['sellbyday'], $_POST['sellbyyear']); -$pdluoid=GETPOST('pdluoid', 'int'); -$batchnumber=GETPOST('batch_number', 'san_alpha'); +$fieldid = isset($_GET["ref"]) ? 'ref' : 'rowid'; +$d_eatby = dol_mktime(0, 0, 0, $_POST['eatbymonth'], $_POST['eatbyday'], $_POST['eatbyyear']); +$d_sellby = dol_mktime(0, 0, 0, $_POST['sellbymonth'], $_POST['sellbyday'], $_POST['sellbyyear']); +$pdluoid = GETPOST('pdluoid', 'int'); +$batchnumber = GETPOST('batch_number', 'san_alpha'); if (!empty($batchnumber)) { - $batchnumber=trim($batchnumber); + $batchnumber = trim($batchnumber); } // Security check -if ($user->socid) $socid=$user->socid; -$result=restrictedArea($user, 'produit&stock', $id, 'product&product', '', '', $fieldid); +if ($user->socid) $socid = $user->socid; +$result = restrictedArea($user, 'produit&stock', $id, 'product&product', '', '', $fieldid); $object = new Product($db); @@ -86,19 +86,19 @@ $extrafields = new ExtraFields($db); // fetch optionals attributes and labels $extrafields->fetch_name_optionals_label($object->table_element); -if ($id > 0 || ! empty($ref)) +if ($id > 0 || !empty($ref)) { $result = $object->fetch($id, $ref); } -if(empty($id) && !empty($object->id)) $id = $object->id; +if (empty($id) && !empty($object->id)) $id = $object->id; -$modulepart='product'; +$modulepart = 'product'; // Get object canvas (By default, this is not defined, so standard usage of dolibarr) -$canvas = !empty($object->canvas)?$object->canvas:GETPOST("canvas"); -$objcanvas=null; -if (! empty($canvas)) +$canvas = !empty($object->canvas) ? $object->canvas : GETPOST("canvas"); +$objcanvas = null; +if (!empty($canvas)) { require_once DOL_DOCUMENT_ROOT.'/core/class/canvas.class.php'; $objcanvas = new Canvas($db, $action); @@ -106,17 +106,17 @@ if (! empty($canvas)) } // Initialize technical object to manage hooks of page. Note that conf->hooks_modules contains array of hook context -$hookmanager->initHooks(array('stockproductcard','globalcard')); +$hookmanager->initHooks(array('stockproductcard', 'globalcard')); /* * Actions */ -if ($cancel) $action=''; +if ($cancel) $action = ''; -$parameters=array('id'=>$id, 'ref'=>$ref, 'objcanvas'=>$objcanvas); -$reshook=$hookmanager->executeHooks('doActions', $parameters, $object, $action); // Note that $action and $object may have been modified by some hooks +$parameters = array('id'=>$id, 'ref'=>$ref, '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 ($action == 'addlimitstockwarehouse' && !empty($user->rights->produit->creer)) @@ -125,29 +125,29 @@ if ($action == 'addlimitstockwarehouse' && !empty($user->rights->produit->creer) $desiredstock = GETPOST('desiredstock'); $maj_ok = true; - if($seuil_stock_alerte == '') { + if ($seuil_stock_alerte == '') { setEventMessages($langs->trans("ErrorFieldRequired", $langs->transnoentitiesnoconv("StockLimit")), null, 'errors'); $maj_ok = false; } - if($desiredstock == '') { + if ($desiredstock == '') { setEventMessages($langs->trans("ErrorFieldRequired", $langs->transnoentitiesnoconv("DesiredStock")), null, 'errors'); $maj_ok = false; } - if($maj_ok) { + if ($maj_ok) { $pse = new ProductStockEntrepot($db); if ($pse->fetch(0, $id, GETPOST('fk_entrepot', 'int')) > 0) { // Update $pse->seuil_stock_alerte = $seuil_stock_alerte; - $pse->desiredstock = $desiredstock; - if($pse->update($user) > 0) setEventMessages($langs->trans('ProductStockWarehouseUpdated'), null, 'mesgs'); + $pse->desiredstock = $desiredstock; + if ($pse->update($user) > 0) setEventMessages($langs->trans('ProductStockWarehouseUpdated'), null, 'mesgs'); } else { // Create - $pse->fk_entrepot = GETPOST('fk_entrepot'); + $pse->fk_entrepot = GETPOST('fk_entrepot'); $pse->fk_product = $id; $pse->seuil_stock_alerte = GETPOST('seuil_stock_alerte'); $pse->desiredstock = GETPOST('desiredstock'); - if($pse->create($user) > 0) setEventMessages($langs->trans('ProductStockWarehouseCreated'), null, 'mesgs'); + if ($pse->create($user) > 0) setEventMessages($langs->trans('ProductStockWarehouseCreated'), null, 'mesgs'); } } @@ -155,7 +155,7 @@ if ($action == 'addlimitstockwarehouse' && !empty($user->rights->produit->creer) exit; } -if($action == 'delete_productstockwarehouse' && !empty($user->rights->produit->creer)) +if ($action == 'delete_productstockwarehouse' && !empty($user->rights->produit->creer)) { $pse = new ProductStockEntrepot($db); @@ -169,61 +169,61 @@ if($action == 'delete_productstockwarehouse' && !empty($user->rights->produit->c if ($action == 'setseuil_stock_alerte' && !empty($user->rights->produit->creer)) { $object = new Product($db); - $result=$object->fetch($id); - $object->seuil_stock_alerte=$stocklimit; - $result=$object->update($object->id, $user, 0, 'update'); + $result = $object->fetch($id); + $object->seuil_stock_alerte = $stocklimit; + $result = $object->update($object->id, $user, 0, 'update'); if ($result < 0) setEventMessages($object->error, $object->errors, 'errors'); //else // setEventMessages($lans->trans("SavedRecordSuccessfully"), null, 'mesgs'); - $action=''; + $action = ''; } // Set desired stock if ($action == 'setdesiredstock' && !empty($user->rights->produit->creer)) { $object = new Product($db); - $result=$object->fetch($id); - $object->desiredstock=$desiredstock; - $result=$object->update($object->id, $user, 0, 'update'); + $result = $object->fetch($id); + $object->desiredstock = $desiredstock; + $result = $object->update($object->id, $user, 0, 'update'); if ($result < 0) setEventMessages($object->error, $object->errors, 'errors'); - $action=''; + $action = ''; } // Correct stock -if ($action == "correct_stock" && ! $cancel) +if ($action == "correct_stock" && !$cancel) { - if (! (GETPOST("id_entrepot") > 0)) + if (!(GETPOST("id_entrepot") > 0)) { setEventMessages($langs->trans("ErrorFieldRequired", $langs->transnoentitiesnoconv("Warehouse")), null, 'errors'); $error++; - $action='correction'; + $action = 'correction'; } - if (! GETPOST("nbpiece")) + if (!GETPOST("nbpiece")) { setEventMessages($langs->trans("ErrorFieldRequired", $langs->transnoentitiesnoconv("NumberOfUnit")), null, 'errors'); $error++; - $action='correction'; + $action = 'correction'; } - if (! empty($conf->productbatch->enabled)) + if (!empty($conf->productbatch->enabled)) { $object = new Product($db); - $result=$object->fetch($id); + $result = $object->fetch($id); - if ($object->hasbatch() && ! $batchnumber) + if ($object->hasbatch() && !$batchnumber) { setEventMessages($langs->trans("ErrorFieldRequired", $langs->transnoentitiesnoconv("batch_number")), null, 'errors'); $error++; - $action='correction'; + $action = 'correction'; } } - if (! $error) + if (!$error) { - $priceunit=price2num(GETPOST("unitprice")); + $priceunit = price2num(GETPOST("unitprice")); if (is_numeric(GETPOST("nbpiece")) && $id) { $origin_element = ''; @@ -237,16 +237,16 @@ if ($action == "correct_stock" && ! $cancel) if (empty($object)) { $object = new Product($db); - $result=$object->fetch($id); + $result = $object->fetch($id); } if ($object->hasbatch()) { - $result=$object->correct_stock_batch( + $result = $object->correct_stock_batch( $user, GETPOST("id_entrepot"), GETPOST("nbpiece"), GETPOST("mouvement"), - GETPOST("label"), // label movement + GETPOST("label"), // label movement $priceunit, $d_eatby, $d_sellby, @@ -254,11 +254,11 @@ if ($action == "correct_stock" && ! $cancel) GETPOST('inventorycode'), $origin_element, $origin_id - ); // We do not change value of stock for a correction + ); // We do not change value of stock for a correction } else { - $result=$object->correct_stock( + $result = $object->correct_stock( $user, GETPOST("id_entrepot"), GETPOST("nbpiece"), @@ -268,7 +268,7 @@ if ($action == "correct_stock" && ! $cancel) GETPOST('inventorycode'), $origin_element, $origin_id - ); // We do not change value of stock for a correction + ); // We do not change value of stock for a correction } if ($result > 0) @@ -287,61 +287,61 @@ if ($action == "correct_stock" && ! $cancel) else { setEventMessages($object->error, $object->errors, 'errors'); - $action='correction'; + $action = 'correction'; } } } } // Transfer stock from a warehouse to another warehouse -if ($action == "transfert_stock" && ! $cancel) +if ($action == "transfert_stock" && !$cancel) { - if (! (GETPOST("id_entrepot", 'int') > 0) || ! (GETPOST("id_entrepot_destination", 'int') > 0)) + if (!(GETPOST("id_entrepot", 'int') > 0) || !(GETPOST("id_entrepot_destination", 'int') > 0)) { setEventMessages($langs->trans("ErrorFieldRequired", $langs->transnoentitiesnoconv("Warehouse")), null, 'errors'); $error++; - $action='transfert'; + $action = 'transfert'; } - if (! GETPOST("nbpiece", 'int')) + if (!GETPOST("nbpiece", 'int')) { setEventMessages($langs->trans("ErrorFieldRequired", $langs->transnoentitiesnoconv("NumberOfUnit")), null, 'errors'); $error++; - $action='transfert'; + $action = 'transfert'; } if (GETPOST("id_entrepot", 'int') == GETPOST("id_entrepot_destination", 'int')) { setEventMessages($langs->trans("ErrorSrcAndTargetWarehouseMustDiffers"), null, 'errors'); $error++; - $action='transfert'; + $action = 'transfert'; } - if (! empty($conf->productbatch->enabled)) + if (!empty($conf->productbatch->enabled)) { $object = new Product($db); - $result=$object->fetch($id); + $result = $object->fetch($id); - if ($object->hasbatch() && ! $batchnumber) + if ($object->hasbatch() && !$batchnumber) { setEventMessages($langs->trans("ErrorFieldRequired", $langs->transnoentitiesnoconv("batch_number")), null, 'errors'); $error++; - $action='transfert'; + $action = 'transfert'; } } - if (! $error) + if (!$error) { if ($id) { $object = new Product($db); - $result=$object->fetch($id); + $result = $object->fetch($id); $db->begin(); - $object->load_stock('novirtual'); // Load array product->stock_warehouse + $object->load_stock('novirtual'); // Load array product->stock_warehouse // Define value of products moved - $pricesrc=0; - if (isset($object->pmp)) $pricesrc=$object->pmp; - $pricedest=$pricesrc; + $pricesrc = 0; + if (isset($object->pmp)) $pricesrc = $object->pmp; + $pricedest = $pricesrc; if ($object->hasbatch()) { @@ -349,13 +349,13 @@ if ($action == "transfert_stock" && ! $cancel) if ($pdluoid > 0) { - $result=$pdluo->fetch($pdluoid); + $result = $pdluo->fetch($pdluoid); if ($result) { - $srcwarehouseid=$pdluo->warehouseid; - $batch=$pdluo->batch; - $eatby=$pdluo->eatby; - $sellby=$pdluo->sellby; + $srcwarehouseid = $pdluo->warehouseid; + $batch = $pdluo->batch; + $eatby = $pdluo->eatby; + $sellby = $pdluo->sellby; } else { @@ -365,16 +365,16 @@ if ($action == "transfert_stock" && ! $cancel) } else { - $srcwarehouseid=GETPOST('id_entrepot', 'int'); - $batch=$batchnumber; - $eatby=$d_eatby; - $sellby=$d_sellby; + $srcwarehouseid = GETPOST('id_entrepot', 'int'); + $batch = $batchnumber; + $eatby = $d_eatby; + $sellby = $d_sellby; } - if (! $error) + if (!$error) { // Remove stock - $result1=$object->correct_stock_batch( + $result1 = $object->correct_stock_batch( $user, $srcwarehouseid, GETPOST("nbpiece", 'int'), @@ -386,10 +386,10 @@ if ($action == "transfert_stock" && ! $cancel) ); if ($result1 < 0) $error++; } - if (! $error) + if (!$error) { // Add stock - $result2=$object->correct_stock_batch( + $result2 = $object->correct_stock_batch( $user, GETPOST("id_entrepot_destination", 'int'), GETPOST("nbpiece", 'int'), @@ -404,10 +404,10 @@ if ($action == "transfert_stock" && ! $cancel) } else { - if (! $error) + if (!$error) { // Remove stock - $result1=$object->correct_stock( + $result1 = $object->correct_stock( $user, GETPOST("id_entrepot"), GETPOST("nbpiece"), @@ -418,10 +418,10 @@ if ($action == "transfert_stock" && ! $cancel) ); if ($result1 < 0) $error++; } - if (! $error) + if (!$error) { // Add stock - $result2=$object->correct_stock( + $result2 = $object->correct_stock( $user, GETPOST("id_entrepot_destination"), GETPOST("nbpiece"), @@ -435,7 +435,7 @@ if ($action == "transfert_stock" && ! $cancel) } - if (! $error && $result1 >= 0 && $result2 >= 0) + if (!$error && $result1 >= 0 && $result2 >= 0) { $db->commit(); @@ -454,7 +454,7 @@ if ($action == "transfert_stock" && ! $cancel) { setEventMessages($object->error, $object->errors, 'errors'); $db->rollback(); - $action='transfert'; + $action = 'transfert'; } } } @@ -464,24 +464,24 @@ if ($action == "transfert_stock" && ! $cancel) if ($action == 'updateline' && GETPOST('save') == $langs->trans('Save')) { $pdluo = new Productbatch($db); - $result=$pdluo->fetch(GETPOST('pdluoid', 'int')); + $result = $pdluo->fetch(GETPOST('pdluoid', 'int')); - if ($result>0) + if ($result > 0) { if ($pdluo->id) { - if ((! GETPOST("sellby")) && (! GETPOST("eatby")) && (! $batchnumber)) { + if ((!GETPOST("sellby")) && (!GETPOST("eatby")) && (!$batchnumber)) { setEventMessages($langs->trans("ErrorFieldRequired", $langs->transnoentitiesnoconv("atleast1batchfield")), null, 'errors'); } else { - $d_eatby=dol_mktime(0, 0, 0, $_POST['eatbymonth'], $_POST['eatbyday'], $_POST['eatbyyear']); - $d_sellby=dol_mktime(0, 0, 0, $_POST['sellbymonth'], $_POST['sellbyday'], $_POST['sellbyyear']); - $pdluo->batch=$batchnumber; - $pdluo->eatby=$d_eatby; - $pdluo->sellby=$d_sellby; - $result=$pdluo->update($user); - if ($result<0) + $d_eatby = dol_mktime(0, 0, 0, $_POST['eatbymonth'], $_POST['eatbyday'], $_POST['eatbyyear']); + $d_sellby = dol_mktime(0, 0, 0, $_POST['sellbymonth'], $_POST['sellbyday'], $_POST['sellbyyear']); + $pdluo->batch = $batchnumber; + $pdluo->eatby = $d_eatby; + $pdluo->sellby = $d_sellby; + $result = $pdluo->update($user); + if ($result < 0) { setEventMessages($pdluo->error, $pdluo->errors, 'errors'); } @@ -507,8 +507,8 @@ if ($action == 'updateline' && GETPOST('save') == $langs->trans('Save')) */ $form = new Form($db); -$formproduct=new FormProduct($db); -if (! empty($conf->projet->enabled)) $formproject=new FormProjets($db); +$formproduct = new FormProduct($db); +if (!empty($conf->projet->enabled)) $formproject = new FormProjets($db); if ($id > 0 || $ref) { @@ -524,22 +524,22 @@ if ($id > 0 || $ref) $shortlabel = dol_trunc($object->label, 16); if (GETPOST("type") == '0' || ($object->type == Product::TYPE_PRODUCT)) { - $title = $langs->trans('Product')." ". $shortlabel ." - ".$langs->trans('Stock'); - $helpurl='EN:Module_Products|FR:Module_Produits|ES:Módulo_Productos'; + $title = $langs->trans('Product')." ".$shortlabel." - ".$langs->trans('Stock'); + $helpurl = 'EN:Module_Products|FR:Module_Produits|ES:Módulo_Productos'; } if (GETPOST("type") == '1' || ($object->type == Product::TYPE_SERVICE)) { - $title = $langs->trans('Service')." ". $shortlabel ." - ".$langs->trans('Stock'); - $helpurl='EN:Module_Services_En|FR:Module_Services|ES:Módulo_Servicios'; + $title = $langs->trans('Service')." ".$shortlabel." - ".$langs->trans('Stock'); + $helpurl = 'EN:Module_Services_En|FR:Module_Services|ES:Módulo_Servicios'; } llxHeader('', $title, $helpurl); if ($result > 0) { - $head=product_prepare_head($object); - $titre=$langs->trans("CardProduct".$object->type); - $picto=($object->type==Product::TYPE_SERVICE?'service':'product'); + $head = product_prepare_head($object); + $titre = $langs->trans("CardProduct".$object->type); + $picto = ($object->type == Product::TYPE_SERVICE ? 'service' : 'product'); dol_fiche_head($head, 'stock', $titre, -1, $picto); @@ -548,7 +548,7 @@ if ($id > 0 || $ref) $linkback = ''.$langs->trans("BackToList").''; $shownav = 1; - if ($user->socid && ! in_array('stock', explode(',', $conf->global->MAIN_MODULES_FOR_EXTERNAL))) $shownav=0; + if ($user->socid && !in_array('stock', explode(',', $conf->global->MAIN_MODULES_FOR_EXTERNAL))) $shownav = 0; dol_banner_tab($object, 'ref', $linkback, $shownav, 'ref'); @@ -557,22 +557,22 @@ if ($id > 0 || $ref) print '
    '; print ''; - if (! $variants) { + if (!$variants) { if ($conf->productbatch->enabled) { - print ''; } // PMP - print ''; + print ''; print ''; print ''; // Minimum Price - print ''; + print ''; print ''; // Price minimum - print ''; } else { // Price - print ''; // Price minimum - print ''; } // Stock alert threshold - print ''; // Hook formObject $parameters = array(); - $reshook = $hookmanager->executeHooks('formObjectOptions', $parameters, $object, $action); // Note that $action and $object may have been modified by hook + $reshook = $hookmanager->executeHooks('formObjectOptions', $parameters, $object, $action); // Note that $action and $object may have been modified by hook print $hookmanager->resPrint; // Desired stock - print ''; // Real stock - $text_stock_options = $langs->trans("RealStockDesc") . '
    '; - $text_stock_options .= $langs->trans("RealStockWillAutomaticallyWhen") . '
    '; - $text_stock_options .= (!empty($conf->global->STOCK_CALCULATE_ON_SHIPMENT) || !empty($conf->global->STOCK_CALCULATE_ON_SHIPMENT_CLOSE) ? $langs->trans("DeStockOnShipment") . '
    ' : ''); - $text_stock_options .= (!empty($conf->global->STOCK_CALCULATE_ON_VALIDATE_ORDER) ? $langs->trans("DeStockOnValidateOrder") . '
    ' : ''); - $text_stock_options .= (!empty($conf->global->STOCK_CALCULATE_ON_BILL) ? $langs->trans("DeStockOnBill") . '
    ' : ''); - $text_stock_options .= (!empty($conf->global->STOCK_CALCULATE_ON_SUPPLIER_BILL) ? $langs->trans("ReStockOnBill") . '
    ' : ''); - $text_stock_options .= (!empty($conf->global->STOCK_CALCULATE_ON_SUPPLIER_VALIDATE_ORDER) ? $langs->trans("ReStockOnValidateOrder") . '
    ' : ''); - $text_stock_options .= (!empty($conf->global->STOCK_CALCULATE_ON_SUPPLIER_DISPATCH_ORDER) ? $langs->trans("ReStockOnDispatchOrder") . '
    ' : ''); - $text_stock_options.= (! empty($conf->global->STOCK_CALCULATE_ON_RECEPTION) || ! empty($conf->global->STOCK_CALCULATE_ON_RECEPTION_CLOSE)?$langs->trans("StockOnReception").'
    ':''); + $text_stock_options = $langs->trans("RealStockDesc").'
    '; + $text_stock_options .= $langs->trans("RealStockWillAutomaticallyWhen").'
    '; + $text_stock_options .= (!empty($conf->global->STOCK_CALCULATE_ON_SHIPMENT) || !empty($conf->global->STOCK_CALCULATE_ON_SHIPMENT_CLOSE) ? $langs->trans("DeStockOnShipment").'
    ' : ''); + $text_stock_options .= (!empty($conf->global->STOCK_CALCULATE_ON_VALIDATE_ORDER) ? $langs->trans("DeStockOnValidateOrder").'
    ' : ''); + $text_stock_options .= (!empty($conf->global->STOCK_CALCULATE_ON_BILL) ? $langs->trans("DeStockOnBill").'
    ' : ''); + $text_stock_options .= (!empty($conf->global->STOCK_CALCULATE_ON_SUPPLIER_BILL) ? $langs->trans("ReStockOnBill").'
    ' : ''); + $text_stock_options .= (!empty($conf->global->STOCK_CALCULATE_ON_SUPPLIER_VALIDATE_ORDER) ? $langs->trans("ReStockOnValidateOrder").'
    ' : ''); + $text_stock_options .= (!empty($conf->global->STOCK_CALCULATE_ON_SUPPLIER_DISPATCH_ORDER) ? $langs->trans("ReStockOnDispatchOrder").'
    ' : ''); + $text_stock_options .= (!empty($conf->global->STOCK_CALCULATE_ON_RECEPTION) || !empty($conf->global->STOCK_CALCULATE_ON_RECEPTION_CLOSE) ? $langs->trans("StockOnReception").'
    ' : ''); print ''; - print ''; print ''; $stocktheo = price2num($object->stock_theorique, 'MS'); $found = 0; - $helpondiff = '' . $langs->trans("StockDiffPhysicTeoric") . ':
    '; + $helpondiff = ''.$langs->trans("StockDiffPhysicTeoric").':
    '; // Number of customer orders running if (!empty($conf->commande->enabled)) { if ($found) $helpondiff .= '
    '; else $found = 1; - $helpondiff .= $langs->trans("ProductQtyInCustomersOrdersRunning") . ': ' . $object->stats_commande['qty']; + $helpondiff .= $langs->trans("ProductQtyInCustomersOrdersRunning").': '.$object->stats_commande['qty']; $result = $object->load_stats_commande(0, '0', 1); if ($result < 0) dol_print_error($db, $object->error); - $helpondiff .= ' (' . $langs->trans("ProductQtyInDraft") . ': ' . $object->stats_commande['qty'] . ')'; + $helpondiff .= ' ('.$langs->trans("ProductQtyInDraft").': '.$object->stats_commande['qty'].')'; } // Number of product from customer order already sent (partial shipping) if (!empty($conf->expedition->enabled)) { + require_once DOL_DOCUMENT_ROOT . '/expedition/class/expedition.class.php'; + $filterShipmentStatus = ''; + if (!empty($conf->global->STOCK_CALCULATE_ON_SHIPMENT)) { + $filterShipmentStatus = Expedition::STATUS_VALIDATED . ',' . Expedition::STATUS_CLOSED; + } elseif (!empty($conf->global->STOCK_CALCULATE_ON_SHIPMENT_CLOSE)) { + $filterShipmentStatus = Expedition::STATUS_CLOSED; + } if ($found) $helpondiff .= '
    '; else $found = 1; - $result = $object->load_stats_sending(0, '2', 1); - $helpondiff .= $langs->trans("ProductQtyInShipmentAlreadySent") . ': ' . $object->stats_expedition['qty']; + $result = $object->load_stats_sending(0, '2', 1, $filterShipmentStatus); + $helpondiff .= $langs->trans("ProductQtyInShipmentAlreadySent").': '.$object->stats_expedition['qty']; } // Number of supplier order running if (!empty($conf->fournisseur->enabled)) { if ($found) $helpondiff .= '
    '; else $found = 1; $result = $object->load_stats_commande_fournisseur(0, '3,4', 1); - $helpondiff .= $langs->trans("ProductQtyInSuppliersOrdersRunning") . ': ' . $object->stats_commande_fournisseur['qty']; + $helpondiff .= $langs->trans("ProductQtyInSuppliersOrdersRunning").': '.$object->stats_commande_fournisseur['qty']; $result = $object->load_stats_commande_fournisseur(0, '0,1,2', 1); if ($result < 0) dol_print_error($db, $object->error); - $helpondiff .= ' (' . $langs->trans("ProductQtyInDraftOrWaitingApproved") . ': ' . $object->stats_commande_fournisseur['qty'] . ')'; + $helpondiff .= ' ('.$langs->trans("ProductQtyInDraftOrWaitingApproved").': '.$object->stats_commande_fournisseur['qty'].')'; } // Number of product from supplier order already received (partial receipt) if (!empty($conf->fournisseur->enabled)) { if ($found) $helpondiff .= '
    '; else $found = 1; - $helpondiff .= $langs->trans("ProductQtyInSuppliersShipmentAlreadyRecevied") . ': ' . $object->stats_reception['qty']; + $helpondiff .= $langs->trans("ProductQtyInSuppliersShipmentAlreadyRecevied").': '.$object->stats_reception['qty']; } // Calculating a theorical value @@ -689,7 +696,7 @@ if ($id > 0 || $ref) print "'; print ''; @@ -697,8 +704,8 @@ if ($id > 0 || $ref) if (!empty($user->rights->stock->mouvement->lire)) { $sql = "SELECT max(m.datem) as datem"; - $sql .= " FROM " . MAIN_DB_PREFIX . "stock_mouvement as m"; - $sql .= " WHERE m.fk_product = '" . $object->id . "'"; + $sql .= " FROM ".MAIN_DB_PREFIX."stock_mouvement as m"; + $sql .= " WHERE m.fk_product = '".$object->id."'"; $resqlbis = $db->query($sql); if ($resqlbis) { $obj = $db->fetch_object($resqlbis); @@ -706,12 +713,12 @@ if ($id > 0 || $ref) } else { dol_print_error($db); } - print '"; } @@ -750,9 +757,9 @@ else /* */ /* ************************************************************************** */ -$parameters=array(); +$parameters = array(); -$reshook=$hookmanager->executeHooks('addMoreActionsButtons', $parameters, $object, $action); // Note that $action and $object may have been modified by hook +$reshook = $hookmanager->executeHooks('addMoreActionsButtons', $parameters, $object, $action); // Note that $action and $object may have been modified by hook if (empty($reshook)) { if (empty($action) && $object->id) @@ -761,33 +768,33 @@ if (empty($reshook)) if ($user->rights->stock->mouvement->creer) { - if (! $variants || ! empty($conf->global->VARIANT_ALLOW_STOCK_MOVEMENT_ON_VARIANT_PARENT)) { - print '' . $langs->trans("CorrectStock") . ''; + if (!$variants || !empty($conf->global->VARIANT_ALLOW_STOCK_MOVEMENT_ON_VARIANT_PARENT)) { + print ''.$langs->trans("CorrectStock").''; } else { - print '' . $langs->trans("CorrectStock") . ''; + print ''.$langs->trans("CorrectStock").''; } } else { - print '' . $langs->trans("CorrectStock") . ''; + print ''.$langs->trans("CorrectStock").''; } //if (($user->rights->stock->mouvement->creer) && ! $object->hasbatch()) if ($user->rights->stock->mouvement->creer) { - if (! $variants || ! empty($conf->global->VARIANT_ALLOW_STOCK_MOVEMENT_ON_VARIANT_PARENT)) { - print '' . $langs->trans("TransferStock") . ''; + if (!$variants || !empty($conf->global->VARIANT_ALLOW_STOCK_MOVEMENT_ON_VARIANT_PARENT)) { + print ''.$langs->trans("TransferStock").''; } else { - print '' . $langs->trans("TransferStock") . ''; + print ''.$langs->trans("TransferStock").''; } } else { - print '' . $langs->trans("CorrectStock") . ''; + print ''.$langs->trans("CorrectStock").''; } print ''; @@ -795,7 +802,7 @@ if (empty($reshook)) } -if (! $variants) { +if (!$variants) { /* * Stock detail (by warehouse). May go down into batch details. */ @@ -804,18 +811,18 @@ if (! $variants) { print '
    ' . $langs->trans("ManageLotSerial") . ''; + print '
    '.$langs->trans("ManageLotSerial").''; print $object->getLibStatut(0, 2); print '
    ' . $langs->trans("AverageUnitPricePMP") . '
    '.$langs->trans("AverageUnitPricePMP").''; - if ($object->pmp > 0) print price($object->pmp) . ' ' . $langs->trans("HT"); + if ($object->pmp > 0) print price($object->pmp).' '.$langs->trans("HT"); print '
    ' . $langs->trans("BuyingPriceMin") . '
    '.$langs->trans("BuyingPriceMin").''; $product_fourn = new ProductFournisseur($db); if ($product_fourn->find_min_price_product_fournisseur($object->id) > 0) { @@ -583,103 +583,110 @@ if ($id > 0 || $ref) if (empty($conf->global->PRODUIT_MULTIPRICES)) { // Price - print '
    ' . $langs->trans("SellingPrice") . ''; + print '
    '.$langs->trans("SellingPrice").''; if ($object->price_base_type == 'TTC') { - print price($object->price_ttc) . ' ' . $langs->trans($object->price_base_type); + print price($object->price_ttc).' '.$langs->trans($object->price_base_type); } else { - print price($object->price) . ' ' . $langs->trans($object->price_base_type); + print price($object->price).' '.$langs->trans($object->price_base_type); } print '
    ' . $langs->trans("MinPrice") . ''; + print '
    '.$langs->trans("MinPrice").''; if ($object->price_base_type == 'TTC') { - print price($object->price_min_ttc) . ' ' . $langs->trans($object->price_base_type); + print price($object->price_min_ttc).' '.$langs->trans($object->price_base_type); } else { - print price($object->price_min) . ' ' . $langs->trans($object->price_base_type); + print price($object->price_min).' '.$langs->trans($object->price_base_type); } print '
    ' . $langs->trans("SellingPrice") . ''; + print '
    '.$langs->trans("SellingPrice").''; print $langs->trans("Variable"); print '
    ' . $langs->trans("MinPrice") . ''; + print '
    '.$langs->trans("MinPrice").''; print $langs->trans("Variable"); print '
    ' . $form->editfieldkey($form->textwithpicto($langs->trans("StockLimit"), $langs->trans("StockLimitDesc"), 1), 'seuil_stock_alerte', $object->seuil_stock_alerte, $object, $user->rights->produit->creer) . ''; + print '
    '.$form->editfieldkey($form->textwithpicto($langs->trans("StockLimit"), $langs->trans("StockLimitDesc"), 1), 'seuil_stock_alerte', $object->seuil_stock_alerte, $object, $user->rights->produit->creer).''; print $form->editfieldval("StockLimit", 'seuil_stock_alerte', $object->seuil_stock_alerte, $object, $user->rights->produit->creer, 'string'); print '
    ' . $form->editfieldkey($form->textwithpicto($langs->trans("DesiredStock"), $langs->trans("DesiredStockDesc"), 1), 'desiredstock', $object->desiredstock, $object, $user->rights->produit->creer); + print '
    '.$form->editfieldkey($form->textwithpicto($langs->trans("DesiredStock"), $langs->trans("DesiredStockDesc"), 1), 'desiredstock', $object->desiredstock, $object, $user->rights->produit->creer); print ''; print $form->editfieldval("DesiredStock", 'desiredstock', $object->desiredstock, $object, $user->rights->produit->creer, 'string'); print '
    '; print $form->textwithpicto($langs->trans("PhysicalStock"), $text_stock_options, 1); print '' . price2num($object->stock_reel, 'MS'); - if ($object->seuil_stock_alerte != '' && ($object->stock_reel < $object->seuil_stock_alerte)) print ' ' . img_warning($langs->trans("StockLowerThanLimit", $object->seuil_stock_alerte)); + print ''.price2num($object->stock_reel, 'MS'); + if ($object->seuil_stock_alerte != '' && ($object->stock_reel < $object->seuil_stock_alerte)) print ' '.img_warning($langs->trans("StockLowerThanLimit", $object->seuil_stock_alerte)); print '
    "; //print (empty($stocktheo)?0:$stocktheo); print $form->textwithpicto((empty($stocktheo) ? 0 : $stocktheo), $helpondiff); - if ($object->seuil_stock_alerte != '' && ($object->stock_theorique < $object->seuil_stock_alerte)) print ' ' . img_warning($langs->trans("StockLowerThanLimit", $object->seuil_stock_alerte)); + if ($object->seuil_stock_alerte != '' && ($object->stock_theorique < $object->seuil_stock_alerte)) print ' '.img_warning($langs->trans("StockLowerThanLimit", $object->seuil_stock_alerte)); print '
    ' . $langs->trans("LastMovement") . ''; + print '
    '.$langs->trans("LastMovement").''; if ($lastmovementdate) { - print dol_print_date($lastmovementdate, 'dayhour') . ' '; - print '(' . $langs->trans("FullList") . ')'; + print dol_print_date($lastmovementdate, 'dayhour').' '; + print '('.$langs->trans("FullList").')'; } else { - print '' . $langs->trans("None") . ''; + print ''.$langs->trans("None").''; } print "
    '; print ''; - print ''; - print ''; - print ''; - print ''; - print ''; - print ''; + print ''; + print ''; + print ''; + print ''; + print ''; + print ''; print ''; if ((!empty($conf->productbatch->enabled)) && $object->hasbatch()) { print ''; - print ''; - print ''; - print ''; + print ''; + print ''; + print ''; print ''; print ''; print ''; @@ -825,13 +832,13 @@ if (! $variants) { } $sql = "SELECT e.rowid, e.ref, e.lieu, e.fk_parent, e.statut, ps.reel, ps.rowid as product_stock_id, p.pmp"; - $sql .= " FROM " . MAIN_DB_PREFIX . "entrepot as e,"; - $sql .= " " . MAIN_DB_PREFIX . "product_stock as ps"; - $sql .= " LEFT JOIN " . MAIN_DB_PREFIX . "product as p ON p.rowid = ps.fk_product"; + $sql .= " FROM ".MAIN_DB_PREFIX."entrepot as e,"; + $sql .= " ".MAIN_DB_PREFIX."product_stock as ps"; + $sql .= " LEFT JOIN ".MAIN_DB_PREFIX."product as p ON p.rowid = ps.fk_product"; $sql .= " WHERE ps.reel != 0"; $sql .= " AND ps.fk_entrepot = e.rowid"; - $sql .= " AND e.entity IN (" . getEntity('stock') . ")"; - $sql .= " AND ps.fk_product = " . $object->id; + $sql .= " AND e.entity IN (".getEntity('stock').")"; + $sql .= " AND ps.fk_product = ".$object->id; $sql .= " ORDER BY e.ref"; $entrepotstatic = new Entrepot($db); @@ -859,12 +866,12 @@ if (! $variants) { $stock_real = price2num($obj->reel, 'MS'); print ''; - print ''; - print ''; + print ''; + print ''; // PMP - print ''; + print ''; // Value purchase - print ''; + print ''; // Sell price print ''; // Value sell print ''; + if (empty($conf->global->PRODUIT_MULTIPRICES)) print price(price2num($object->price * $obj->reel, 'MT'), 1).''; else print $langs->trans("Variable"); print ''; $total += $obj->reel; @@ -890,27 +897,27 @@ if (! $variants) { $product_lot_static->sellby = $pdluo->sellby; if ($action == 'editline' && GETPOST('lineid', 'int') == $pdluo->id) { //Current line edit - print "\n" . ''; + print "\n".''; print ''; } else { - print "\n" . ''; - print ''; - print ''; - print ''; + print ''; + print ''; + print ''; print ''; print ''; } @@ -931,10 +938,10 @@ if (! $variants) { } else dol_print_error($db); // Total line - print ''; - print ''; + print ''; + print ''; print ''; // Value purchase print 'special_code == "4") { - $htmlforlines.= ' order'; + $htmlforlines .= ' order'; } - $htmlforlines.= '" id="' . $line->id . '">'; - $htmlforlines.= ''; - $htmlforlines.= ''; - $htmlforlines.= ''; - $htmlforlines.= ''; + $htmlforlines .= ''; + $htmlforlines .= ''; + $htmlforlines .= ''; + $htmlforlines .= ''; } - $htmlforlines.= ''."\n"; + $htmlforlines .= ''."\n"; print $htmlforlines; } @@ -733,7 +743,7 @@ print '
    ' . $langs->trans("Warehouse") . '' . $langs->trans("NumberOfUnit") . '' . $langs->trans("AverageUnitPricePMPShort") . '' . $langs->trans("EstimatedStockValueShort") . '' . $langs->trans("SellPriceMin") . '' . $langs->trans("EstimatedStockValueSellShort") . ''.$langs->trans("Warehouse").''.$langs->trans("NumberOfUnit").''.$langs->trans("AverageUnitPricePMPShort").''.$langs->trans("EstimatedStockValueShort").''.$langs->trans("SellPriceMin").''.$langs->trans("EstimatedStockValueSellShort").'
    ' . $langs->trans("batch_number") . '' . $langs->trans("EatByDate") . '' . $langs->trans("SellByDate") . ''.$langs->trans("batch_number").''.$langs->trans("EatByDate").''.$langs->trans("SellByDate").'
    ' . $entrepotstatic->getNomUrl(1) . '' . $stock_real . ($stock_real < 0 ? ' ' . img_warning() : '') . ''.$entrepotstatic->getNomUrl(1).''.$stock_real.($stock_real < 0 ? ' '.img_warning() : '').'' . (price2num($object->pmp) ? price2num($object->pmp, 'MU') : '') . ''.(price2num($object->pmp) ? price2num($object->pmp, 'MU') : '').'' . (price2num($object->pmp) ? price(price2num($object->pmp * $obj->reel, 'MT')) : '') . ''.(price2num($object->pmp) ? price(price2num($object->pmp * $obj->reel, 'MT')) : '').''; if (empty($conf->global->PRODUIT_MULTIPRICES)) print price(price2num($object->price, 'MU'), 1); @@ -872,7 +879,7 @@ if (! $variants) { print ''; - if (empty($conf->global->PRODUIT_MULTIPRICES)) print price(price2num($object->price * $obj->reel, 'MT'), 1) . '
    '; - print ''; - print ''; - print ''; + print ''; + print '
    '; + print ''; print ''; print ''; - print ''; - print ''; + print ''; + print ''; print '
    '; print $form->selectDate($pdluo->eatby, 'eatby', '', '', 1, '', 1, 0); print ''; print $form->selectDate($pdluo->sellby, 'sellby', '', '', 1, '', 1, 0); print '' . $pdluo->qty . ($pdluo->qty < 0 ? ' ' . img_warning() : '') . ''; - print '
    '.$pdluo->qty.($pdluo->qty < 0 ? ' '.img_warning() : '').''; + print '
    '; print ''; print '
    '; - print img_picto($langs->trans("Tranfer"), 'uparrow', 'class="hideonsmartphone"') . ' '; - print 'id . '">' . $langs->trans("TransferStock") . ''; + print "\n".'
    '; + print img_picto($langs->trans("Tranfer"), 'uparrow', 'class="hideonsmartphone"').' '; + print 'id.'">'.$langs->trans("TransferStock").''; // Disabled, because edition of stock content must use the "Correct stock menu". // Do not use this, or data will be wrong (bad tracking of movement label, inventory code, ... //print 'id.'#'.$pdluo->id.'">'; @@ -918,9 +925,9 @@ if (! $variants) { print ''; print $product_lot_static->getNomUrl(1); print '' . dol_print_date($pdluo->eatby, 'day') . '' . dol_print_date($pdluo->sellby, 'day') . '' . $pdluo->qty . ($pdluo->qty < 0 ? ' ' . img_warning() : '') . ''.dol_print_date($pdluo->eatby, 'day').''.dol_print_date($pdluo->sellby, 'day').''.$pdluo->qty.($pdluo->qty < 0 ? ' '.img_warning() : '').'
    ' . $langs->trans("Total") . ':' . price2num($total, 'MS') . '
    '.$langs->trans("Total").':'.price2num($total, 'MS').''; - print ($totalwithpmp ? price(price2num($totalvalue / $totalwithpmp, 'MU')) : ' '); // This value may have rounding errors + print ($totalwithpmp ? price(price2num($totalvalue / $totalwithpmp, 'MU')) : ' '); // This value may have rounding errors print ''; @@ -959,21 +966,21 @@ if (! $variants) { print load_fiche_titre($langs->trans('AddNewProductStockWarehouse')); if (!empty($user->rights->produit->creer)) { - print '
    '; + print ''; print ''; - print ''; + print ''; } - print ''; + print '
    '; if (!empty($user->rights->produit->creer)) { - print ''; - print ''; - print ''; - print ''; + print ''; + print ''; + print ''; + print ''; print ''; } else { - print ''; - print ''; - print ''; + print ''; + print ''; + print ''; print ''; } @@ -985,11 +992,11 @@ if (! $variants) { foreach ($lines as $line) { $ent = new Entrepot($db); $ent->fetch($line['fk_entrepot']); - print ''; - print ''; - print ''; + print ''; + print ''; + print ''; if (!empty($user->rights->produit->creer)) { - print ''; + print ''; } print ''; } @@ -1035,12 +1042,12 @@ if (! $variants) { if (count($productCombinations)) { - $stock_total= 0; + $stock_total = 0; foreach ($productCombinations as $currcomb) { $prodstatic->fetch($currcomb->fk_product_child); $prodstatic->load_stock(); - $stock_total+=$prodstatic->stock_reel; + $stock_total += $prodstatic->stock_reel; ?> diff --git a/htdocs/product/stock/productlot_card.php b/htdocs/product/stock/productlot_card.php index d65f311acbb..c4ec988b269 100644 --- a/htdocs/product/stock/productlot_card.php +++ b/htdocs/product/stock/productlot_card.php @@ -35,21 +35,21 @@ require_once DOL_DOCUMENT_ROOT.'/product/stock/class/productlot.class.php'; $langs->loadLangs(array('stock', 'other', 'productbatch')); // Get parameters -$id = GETPOST('id', 'int'); +$id = GETPOST('id', 'int'); $action = GETPOST('action', 'alpha'); $backtopage = GETPOST('backtopage', 'alpha'); $batch = GETPOST('batch', 'alpha'); $productid = GETPOST('productid', 'int'); -$ref = GETPOST('ref', 'alpha'); // ref is productid_batch +$ref = GETPOST('ref', 'alpha'); // ref is productid_batch -$search_entity=GETPOST('search_entity', 'int'); -$search_fk_product=GETPOST('search_fk_product', 'int'); -$search_batch=GETPOST('search_batch', 'alpha'); -$search_fk_user_creat=GETPOST('search_fk_user_creat', 'int'); -$search_fk_user_modif=GETPOST('search_fk_user_modif', 'int'); -$search_import_key=GETPOST('search_import_key', 'int'); +$search_entity = GETPOST('search_entity', 'int'); +$search_fk_product = GETPOST('search_fk_product', 'int'); +$search_batch = GETPOST('search_batch', 'alpha'); +$search_fk_user_creat = GETPOST('search_fk_user_creat', 'int'); +$search_fk_user_modif = GETPOST('search_fk_user_modif', 'int'); +$search_import_key = GETPOST('search_import_key', 'int'); -if (empty($action) && empty($id) && empty($ref)) $action='list'; +if (empty($action) && empty($id) && empty($ref)) $action = 'list'; // Protection if external user @@ -73,21 +73,21 @@ if ($id || $ref) { if ($ref) { - $tmp=explode('_', $ref); - $productid=$tmp[0]; - $batch=$tmp[1]; + $tmp = explode('_', $ref); + $productid = $tmp[0]; + $batch = $tmp[1]; } $object->fetch($id, $productid, $batch); $object->ref = $object->batch; // For document management ( it use $object->ref) } // Initialize technical object to manage hooks of modules. Note that conf->hooks_modules contains array array -$hookmanager->initHooks(array('productlotcard','globalcard')); +$hookmanager->initHooks(array('productlotcard', 'globalcard')); -$permissionnote = $user->rights->stock->creer; // Used by the include of actions_setnotes.inc.php -$permissiondellink = $user->rights->stock->creer; // Used by the include of actions_dellink.inc.php -$permissiontoadd = $user->rights->stock->creer; // Used by the include of actions_addupdatedelete.inc.php and actions_lineupdown.inc.php +$permissionnote = $user->rights->stock->creer; // Used by the include of actions_setnotes.inc.php +$permissiondellink = $user->rights->stock->creer; // Used by the include of actions_dellink.inc.php +$permissiontoadd = $user->rights->stock->creer; // Used by the include of actions_addupdatedelete.inc.php and actions_lineupdown.inc.php $usercanread = $user->rights->produit->lire; $usercancreate = $user->rights->produit->creer; @@ -97,8 +97,8 @@ $usercandelete = $user->rights->produit->supprimer; * Actions */ -$parameters=array(); -$reshook=$hookmanager->executeHooks('doActions', $parameters, $object, $action); // Note that $action and $object may have been modified by some hooks +$parameters = array(); +$reshook = $hookmanager->executeHooks('doActions', $parameters, $object, $action); // Note that $action and $object may have been modified by some hooks if ($reshook < 0) setEventMessages($hookmanager->error, $hookmanager->errors, 'errors'); if (empty($reshook)) @@ -112,7 +112,7 @@ if (empty($reshook)) if ($action == 'setsellby' && $user->rights->stock->creer) { - $newvalue=dol_mktime(12, 0, 0, $_POST['sellbymonth'], $_POST['sellbyday'], $_POST['sellbyyear']); + $newvalue = dol_mktime(12, 0, 0, $_POST['sellbymonth'], $_POST['sellbyday'], $_POST['sellbyyear']); $result = $object->setValueFrom('sellby', $newvalue, '', null, 'date', '', $user, 'PRODUCTLOT_MODIFY'); if ($result < 0) dol_print_error($db, $object->error); } @@ -125,7 +125,7 @@ if (empty($reshook)) $ret = $extrafields->setOptionalsFromPost(null, $object, GETPOST('attribute', 'none')); if ($ret < 0) $error++; - if (! $error) + if (!$error) { // Actions on extra fields $result = $object->insertExtraFields('PRODUCT_LOT_MODIFY'); @@ -145,21 +145,21 @@ if (empty($reshook)) { if (GETPOST('cancel', 'alpha')) { - $urltogo=$backtopage?$backtopage:dol_buildpath('/stock/list.php', 1); + $urltogo = $backtopage ? $backtopage : dol_buildpath('/stock/list.php', 1); header("Location: ".$urltogo); exit; } - $error=0; + $error = 0; /* object_prop_getpost_prop */ - $object->entity=GETPOST('entity', 'int'); - $object->fk_product=GETPOST('fk_product', 'int'); - $object->batch=GETPOST('batch', 'alpha'); - $object->fk_user_creat=GETPOST('fk_user_creat', 'int'); - $object->fk_user_modif=GETPOST('fk_user_modif', 'int'); - $object->import_key=GETPOST('import_key', 'int'); + $object->entity = GETPOST('entity', 'int'); + $object->fk_product = GETPOST('fk_product', 'int'); + $object->batch = GETPOST('batch', 'alpha'); + $object->fk_user_creat = GETPOST('fk_user_creat', 'int'); + $object->fk_user_modif = GETPOST('fk_user_modif', 'int'); + $object->import_key = GETPOST('import_key', 'int'); if (empty($object->ref)) { @@ -167,43 +167,43 @@ if (empty($reshook)) setEventMessages($langs->trans("ErrorFieldRequired", $langs->transnoentitiesnoconv("Ref")), null, 'errors'); } - if (! $error) + if (!$error) { - $result=$object->create($user); + $result = $object->create($user); if ($result > 0) { // Creation OK - $urltogo=$backtopage?$backtopage:dol_buildpath('/stock/list.php', 1); + $urltogo = $backtopage ? $backtopage : dol_buildpath('/stock/list.php', 1); header("Location: ".$urltogo); exit; } { // Creation KO - if (! empty($object->errors)) setEventMessages(null, $object->errors, 'errors'); + if (!empty($object->errors)) setEventMessages(null, $object->errors, 'errors'); else setEventMessages($object->error, null, 'errors'); - $action='create'; + $action = 'create'; } } else { - $action='create'; + $action = 'create'; } } // Cancel - if ($action == 'update' && GETPOST('cancel', 'alpha')) $action='view'; + if ($action == 'update' && GETPOST('cancel', 'alpha')) $action = 'view'; // Action to update record - if ($action == 'update' && ! GETPOST('cancel', 'alpha')) + if ($action == 'update' && !GETPOST('cancel', 'alpha')) { - $error=0; + $error = 0; - $object->entity=GETPOST('entity', 'int'); - $object->fk_product=GETPOST('fk_product', 'int'); - $object->batch=GETPOST('batch', 'alpha'); - $object->fk_user_creat=GETPOST('fk_user_creat', 'int'); - $object->fk_user_modif=GETPOST('fk_user_modif', 'int'); - $object->import_key=GETPOST('import_key', 'int'); + $object->entity = GETPOST('entity', 'int'); + $object->fk_product = GETPOST('fk_product', 'int'); + $object->batch = GETPOST('batch', 'alpha'); + $object->fk_user_creat = GETPOST('fk_user_creat', 'int'); + $object->fk_user_modif = GETPOST('fk_user_modif', 'int'); + $object->import_key = GETPOST('import_key', 'int'); if (empty($object->ref)) { @@ -211,31 +211,31 @@ if (empty($reshook)) setEventMessages($langs->transnoentitiesnoconv("ErrorFieldRequired", $langs->transnoentitiesnoconv("Ref")), null, 'errors'); } - if (! $error) + if (!$error) { - $result=$object->update($user); + $result = $object->update($user); if ($result > 0) { - $action='view'; + $action = 'view'; } else { // Creation KO - if (! empty($object->errors)) setEventMessages(null, $object->errors, 'errors'); + if (!empty($object->errors)) setEventMessages(null, $object->errors, 'errors'); else setEventMessages($object->error, null, 'errors'); - $action='edit'; + $action = 'edit'; } } else { - $action='edit'; + $action = 'edit'; } } // Action to delete if ($action == 'confirm_delete') { - $result=$object->delete($user); + $result = $object->delete($user); if ($result > 0) { // Delete OK @@ -245,7 +245,7 @@ if (empty($reshook)) } else { - if (! empty($object->errors)) setEventMessages(null, $object->errors, 'errors'); + if (!empty($object->errors)) setEventMessages(null, $object->errors, 'errors'); else setEventMessages($object->error, null, 'errors'); } } @@ -265,7 +265,7 @@ if (empty($reshook)) llxHeader('', 'ProductLot', ''); -$form=new Form($db); +$form = new Form($db); // Part to create @@ -310,15 +310,15 @@ if ($object->id > 0 && (empty($action) || ($action != 'edit' && $action != 'crea if ($action == 'delete') { - $formconfirm = $form->formconfirm($_SERVER["PHP_SELF"] . '?id=' . $object->id, $langs->trans('DeleteBatch'), $langs->trans('ConfirmDeleteBatch'), 'confirm_delete', '', 0, 1); + $formconfirm = $form->formconfirm($_SERVER["PHP_SELF"].'?id='.$object->id, $langs->trans('DeleteBatch'), $langs->trans('ConfirmDeleteBatch'), 'confirm_delete', '', 0, 1); print $formconfirm; } - $linkback = '' . $langs->trans("BackToList") . ''; + $linkback = ''.$langs->trans("BackToList").''; $shownav = 1; - if ($user->socid && ! in_array('batch', explode(',', $conf->global->MAIN_MODULES_FOR_EXTERNAL))) $shownav=0; + if ($user->socid && !in_array('batch', explode(',', $conf->global->MAIN_MODULES_FOR_EXTERNAL))) $shownav = 0; dol_banner_tab($object, 'id', $linkback, $shownav, 'rowid', 'batch'); @@ -352,7 +352,7 @@ if ($object->id > 0 && (empty($action) || ($action != 'edit' && $action != 'crea // Other attributes $cols = 2; - include DOL_DOCUMENT_ROOT . '/core/tpl/extrafields_view.tpl.php'; + include DOL_DOCUMENT_ROOT.'/core/tpl/extrafields_view.tpl.php'; print '
    ' . $formproduct->selectWarehouses('', 'fk_entrepot') . '
    '.$formproduct->selectWarehouses('', 'fk_entrepot').'
    ' . $langs->trans("Warehouse") . '' . $langs->trans("StockLimit") . '' . $langs->trans("DesiredStock") . '
    '.$langs->trans("Warehouse").''.$langs->trans("StockLimit").''.$langs->trans("DesiredStock").'
    ' . $ent->getNomUrl(3) . '' . $line['seuil_stock_alerte'] . '' . $line['desiredstock'] . '
    '.$ent->getNomUrl(3).''.$line['seuil_stock_alerte'].''.$line['desiredstock'].'' . img_delete() . ''.img_delete().'
    getNomUrl(1) ?>
    '; @@ -363,8 +363,8 @@ if ($object->id > 0 && (empty($action) || ($action != 'edit' && $action != 'crea // Buttons print '
    '."\n"; - $parameters=array(); - $reshook=$hookmanager->executeHooks('addMoreActionsButtons', $parameters, $object, $action); // Note that $action and $object may have been modified by hook + $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)) @@ -403,12 +403,12 @@ if (empty($action)) // 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; + $urlsource = $_SERVER["PHP_SELF"]."?id=".$object->id; + $genallowed = $usercanread; + $delallowed = $usercancreate; 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; + $somethingshown = $formfile->numoffiles; print '
    '; } diff --git a/htdocs/product/stock/productlot_list.php b/htdocs/product/stock/productlot_list.php index 4c306dc1702..d832a0406ee 100644 --- a/htdocs/product/stock/productlot_list.php +++ b/htdocs/product/stock/productlot_list.php @@ -42,19 +42,19 @@ $myparam = GETPOST('myparam', 'alpha'); $toselect = GETPOST('toselect', 'array'); -$search_entity=GETPOST('search_entity', 'int'); -$search_product=GETPOST('search_product', 'alpha'); -$search_batch=GETPOST('search_batch', 'alpha'); -$search_fk_user_creat=GETPOST('search_fk_user_creat', 'int'); -$search_fk_user_modif=GETPOST('search_fk_user_modif', 'int'); -$search_import_key=GETPOST('search_import_key', 'int'); +$search_entity = GETPOST('search_entity', 'int'); +$search_product = GETPOST('search_product', 'alpha'); +$search_batch = GETPOST('search_batch', 'alpha'); +$search_fk_user_creat = GETPOST('search_fk_user_creat', 'int'); +$search_fk_user_modif = GETPOST('search_fk_user_modif', 'int'); +$search_import_key = GETPOST('search_import_key', 'int'); -$search_myfield=GETPOST('search_myfield'); +$search_myfield = GETPOST('search_myfield'); $optioncss = GETPOST('optioncss', 'alpha'); // Load variable for pagination -$limit = GETPOST('limit', 'int')?GETPOST('limit', 'int'):$conf->liste_limit; +$limit = GETPOST('limit', 'int') ?GETPOST('limit', 'int') : $conf->liste_limit; $sortfield = GETPOST('sortfield', 'alpha'); $sortorder = GETPOST('sortorder', 'alpha'); $page = GETPOST('page', 'int'); @@ -62,11 +62,11 @@ if (empty($page) || $page == -1) { $page = 0; } // If $page is not defined, $offset = $limit * $page; $pageprev = $page - 1; $pagenext = $page + 1; -if (! $sortfield) $sortfield="t.batch"; // Set here default search field -if (! $sortorder) $sortorder="ASC"; +if (!$sortfield) $sortfield = "t.batch"; // Set here default search field +if (!$sortorder) $sortorder = "ASC"; // Protection if external user -$socid=0; +$socid = 0; if ($user->socid > 0) { $socid = $user->socid; @@ -81,7 +81,7 @@ $extrafields = new ExtraFields($db); // fetch optionals attributes and labels $extrafields->fetch_name_optionals_label($object->table_element); -$search_array_options=$extrafields->getOptionalsFromPost($object->table_element, '', 'search_'); +$search_array_options = $extrafields->getOptionalsFromPost($object->table_element, '', 'search_'); // List of fields to search into when doing a "search in all" $fieldstosearchall = array( @@ -90,7 +90,7 @@ $fieldstosearchall = array( ); // Definition of fields for list -$arrayfields=array( +$arrayfields = array( //'t.entity'=>array('label'=>$langs->trans("Fieldentity"), 'checked'=>1), 't.batch'=>array('label'=>$langs->trans("Batch"), 'checked'=>1), 't.fk_product'=>array('label'=>$langs->trans("Product"), 'checked'=>1), @@ -107,19 +107,19 @@ $arrayfields=array( // 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) + 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], 'checked'=>(($extrafields->attributes[$object->table_element]['list'][$key]<0)?0:1), 'position'=>$extrafields->attributes[$object->table_element]['pos'][$key], 'enabled'=>(abs($extrafields->attributes[$object->table_element]['list'][$key])!=3 && $extrafields->attributes[$object->table_element]['perms'][$key])); + if (!empty($extrafields->attributes[$object->table_element]['list'][$key])) + $arrayfields["ef.".$key] = array('label'=>$extrafields->attributes[$object->table_element]['label'][$key], 'checked'=>(($extrafields->attributes[$object->table_element]['list'][$key] < 0) ? 0 : 1), 'position'=>$extrafields->attributes[$object->table_element]['pos'][$key], 'enabled'=>(abs($extrafields->attributes[$object->table_element]['list'][$key]) != 3 && $extrafields->attributes[$object->table_element]['perms'][$key])); } } $object->fields = dol_sort_array($object->fields, 'position'); $arrayfields = dol_sort_array($arrayfields, 'position'); // Load object if id or ref is provided as parameter -if (($id > 0 || ! empty($ref)) && $action != 'add') +if (($id > 0 || !empty($ref)) && $action != 'add') { - $result=$object->fetch($id, $ref); + $result = $object->fetch($id, $ref); if ($result < 0) dol_print_error($db); } @@ -129,35 +129,35 @@ if (($id > 0 || ! empty($ref)) && $action != 'add') * Actions */ -if (GETPOST('cancel', 'alpha')) { $action='list'; $massaction=''; } -if (! GETPOST('confirmmassaction', 'alpha') && $massaction != 'confirm_presend') { $massaction=''; } +if (GETPOST('cancel', 'alpha')) { $action = 'list'; $massaction = ''; } +if (!GETPOST('confirmmassaction', 'alpha') && $massaction != 'confirm_presend') { $massaction = ''; } -$parameters=array(); -$reshook=$hookmanager->executeHooks('doActions', $parameters, $object, $action); // Note that $action and $object may have been modified by some hooks +$parameters = array(); +$reshook = $hookmanager->executeHooks('doActions', $parameters, $object, $action); // Note that $action and $object may have been modified by some hooks if ($reshook < 0) setEventMessages($hookmanager->error, $hookmanager->errors, 'errors'); 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_entity=''; - $search_product=''; - $search_batch=''; - $search_fk_user_creat=''; - $search_fk_user_modif=''; - $search_import_key=''; - $search_date_creation=''; - $search_date_update=''; - $toselect=array(); - $search_array_options=array(); + $search_entity = ''; + $search_product = ''; + $search_batch = ''; + $search_fk_user_creat = ''; + $search_fk_user_modif = ''; + $search_import_key = ''; + $search_date_creation = ''; + $search_date_update = ''; + $toselect = array(); + $search_array_options = array(); } if (empty($reshook)) { - $objectclass='ProductLot'; - $objectlabel='LotSerial'; + $objectclass = 'ProductLot'; + $objectlabel = 'LotSerial'; $permissiontoread = $user->rights->stock->read; $permissiontodelete = $user->rights->stock->delete; $uploaddir = $conf->stock->dir_output; @@ -171,13 +171,13 @@ if (empty($reshook)) * VIEW */ -$now=dol_now(); +$now = dol_now(); -$form=new Form($db); -$productstatic=new Product($db); +$form = new Form($db); +$productstatic = new Product($db); //$help_url="EN:Module_Customers_Orders|FR:Module_Commandes_Clients|ES:Módulo_Pedidos_de_clientes"; -$help_url=''; +$help_url = ''; $title = $langs->trans('LotSerialList'); llxHeader('', $title, $help_url); @@ -259,37 +259,37 @@ if (empty($conf->global->MAIN_DISABLE_FULL_SCANLIST)) } } -$sql.= $db->plimit($limit+1, $offset); +$sql .= $db->plimit($limit + 1, $offset); dol_syslog($script_file, LOG_DEBUG); -$resql=$db->query($sql); +$resql = $db->query($sql); if ($resql) { $num = $db->num_rows($resql); - $arrayofselected=is_array($toselect)?$toselect:array(); + $arrayofselected = is_array($toselect) ? $toselect : array(); - $param=''; - if (! empty($contextpage) && $contextpage != $_SERVER["PHP_SELF"]) $param.='&contextpage='.$contextpage; - if ($limit > 0 && $limit != $conf->liste_limit) $param.='&limit='.$limit; - if ($search_entity != '') $param.= '&search_entity='.urlencode($search_entity); - if ($search_product != '') $param.= '&search_product='.urlencode($search_product); - if ($search_batch != '') $param.= '&search_batch='.urlencode($search_batch); - if ($search_fk_user_creat != '') $param.= '&search_fk_user_creat='.urlencode($search_fk_user_creat); - if ($search_fk_user_modif != '') $param.= '&search_fk_user_modif='.urlencode($search_fk_user_modif); - if ($search_import_key != '') $param.= '&search_import_key='.urlencode($search_import_key); - if ($optioncss != '') $param.='&optioncss='.$optioncss; + $param = ''; + if (!empty($contextpage) && $contextpage != $_SERVER["PHP_SELF"]) $param .= '&contextpage='.$contextpage; + if ($limit > 0 && $limit != $conf->liste_limit) $param .= '&limit='.$limit; + if ($search_entity != '') $param .= '&search_entity='.urlencode($search_entity); + if ($search_product != '') $param .= '&search_product='.urlencode($search_product); + if ($search_batch != '') $param .= '&search_batch='.urlencode($search_batch); + if ($search_fk_user_creat != '') $param .= '&search_fk_user_creat='.urlencode($search_fk_user_creat); + if ($search_fk_user_modif != '') $param .= '&search_fk_user_modif='.urlencode($search_fk_user_modif); + if ($search_import_key != '') $param .= '&search_import_key='.urlencode($search_import_key); + if ($optioncss != '') $param .= '&optioncss='.$optioncss; // Add $param from extra fields include DOL_DOCUMENT_ROOT.'/core/tpl/extrafields_list_search_param.tpl.php'; - $arrayofmassactions = array( + $arrayofmassactions = array( //'presend'=>$langs->trans("SendByMail"), //'builddoc'=>$langs->trans("PDFMerge"), ); //if ($user->rights->stock->supprimer) $arrayofmassactions['predelete']=''.$langs->trans("Delete"); - if (in_array($massaction, array('presend','predelete'))) $arrayofmassactions=array(); - $massactionbutton=$form->selectMassAction('', $arrayofmassactions); + if (in_array($massaction, array('presend', 'predelete'))) $arrayofmassactions = array(); + $massactionbutton = $form->selectMassAction('', $arrayofmassactions); print ''; if ($optioncss != '') print ''; @@ -302,16 +302,16 @@ if ($resql) print_barre_liste($title, $page, $_SERVER["PHP_SELF"], $param, $sortfield, $sortorder, '', $num, $nbtotalofrecords, 'products', 0, '', '', $limit); - $topicmail="Information"; - $modelmail="productlot"; - $objecttmp=new Productlot($db); - $trackid='lot'.$object->id; + $topicmail = "Information"; + $modelmail = "productlot"; + $objecttmp = new Productlot($db); + $trackid = 'lot'.$object->id; include DOL_DOCUMENT_ROOT.'/core/tpl/massactions_pre.tpl.php'; if ($sall) { - foreach($fieldstosearchall as $key => $val) $fieldstosearchall[$key]=$langs->trans($val); - print '
    '.$langs->trans("FilterOnInto", $sall) . join(', ', $fieldstosearchall).'
    '; + foreach ($fieldstosearchall as $key => $val) $fieldstosearchall[$key] = $langs->trans($val); + print '
    '.$langs->trans("FilterOnInto", $sall).join(', ', $fieldstosearchall).'
    '; } /*$moreforfilter = ''; @@ -319,48 +319,48 @@ if ($resql) $moreforfilter.= $langs->trans('MyFilter') . ': '; $moreforfilter.= '';*/ - $parameters=array(); - $reshook=$hookmanager->executeHooks('printFieldPreListTitle', $parameters); // Note that $action and $object may have been modified by hook + $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($moreforfilter)) + if (!empty($moreforfilter)) { print '
    '; print $moreforfilter; print '
    '; } - $varpage=empty($contextpage)?$_SERVER["PHP_SELF"]:$contextpage; - $selectedfields=$form->multiSelectArrayWithCheckbox('selectedfields', $arrayfields, $varpage); // This also change content of $arrayfields + $varpage = empty($contextpage) ? $_SERVER["PHP_SELF"] : $contextpage; + $selectedfields = $form->multiSelectArrayWithCheckbox('selectedfields', $arrayfields, $varpage); // This also change content of $arrayfields print '
    '; - print ''."\n"; + print '
    '."\n"; // Fields title search print ''; - if (! empty($arrayfields['t.entity']['checked'])) print ''; - if (! empty($arrayfields['t.batch']['checked'])) print ''; - if (! empty($arrayfields['t.fk_product']['checked'])) print ''; - if (! empty($arrayfields['t.sellby']['checked'])) print ''; - if (! empty($arrayfields['t.eatby']['checked'])) print ''; - if (! empty($arrayfields['t.fk_user_creat']['checked'])) print ''; - if (! empty($arrayfields['t.fk_user_modif']['checked'])) print ''; - if (! empty($arrayfields['t.import_key']['checked'])) print ''; + if (!empty($arrayfields['t.entity']['checked'])) print ''; + if (!empty($arrayfields['t.batch']['checked'])) print ''; + if (!empty($arrayfields['t.fk_product']['checked'])) print ''; + if (!empty($arrayfields['t.sellby']['checked'])) print ''; + if (!empty($arrayfields['t.eatby']['checked'])) print ''; + if (!empty($arrayfields['t.fk_user_creat']['checked'])) print ''; + if (!empty($arrayfields['t.fk_user_modif']['checked'])) print ''; + if (!empty($arrayfields['t.import_key']['checked'])) print ''; // Extra fields include DOL_DOCUMENT_ROOT.'/core/tpl/extrafields_list_search_input.tpl.php'; // Fields from hook - $parameters=array('arrayfields'=>$arrayfields); - $reshook=$hookmanager->executeHooks('printFieldListOption', $parameters); // Note that $action and $object may have been modified by hook + $parameters = array('arrayfields'=>$arrayfields); + $reshook = $hookmanager->executeHooks('printFieldListOption', $parameters); // Note that $action and $object may have been modified by hook print $hookmanager->resPrint; - if (! empty($arrayfields['t.datec']['checked'])) + if (!empty($arrayfields['t.datec']['checked'])) { // Date creation print ''; } - if (! empty($arrayfields['t.tms']['checked'])) + if (!empty($arrayfields['t.tms']['checked'])) { // Date modification print ''; print ''."\n"; // Fields title print ''; - if (! empty($arrayfields['t.entity']['checked'])) print_liste_field_titre($arrayfields['t.entity']['label'], $_SERVER['PHP_SELF'], 't.entity', '', $param, '', $sortfield, $sortorder); - if (! empty($arrayfields['t.batch']['checked'])) print_liste_field_titre($arrayfields['t.batch']['label'], $_SERVER['PHP_SELF'], 't.batch', '', $param, '', $sortfield, $sortorder); - if (! empty($arrayfields['t.fk_product']['checked'])) print_liste_field_titre($arrayfields['t.fk_product']['label'], $_SERVER['PHP_SELF'], 't.fk_product', '', $param, '', $sortfield, $sortorder); - if (! empty($arrayfields['t.sellby']['checked'])) print_liste_field_titre($arrayfields['t.sellby']['label'], $_SERVER['PHP_SELF'], 't.sellby', '', $param, '', $sortfield, $sortorder); - if (! empty($arrayfields['t.eatby']['checked'])) print_liste_field_titre($arrayfields['t.eatby']['label'], $_SERVER['PHP_SELF'], 't.eatby', '', $param, '', $sortfield, $sortorder); - if (! empty($arrayfields['t.fk_user_creat']['checked'])) print_liste_field_titre($arrayfields['t.fk_user_creat']['label'], $_SERVER['PHP_SELF'], 't.fk_user_creat', '', $param, '', $sortfield, $sortorder); - if (! empty($arrayfields['t.fk_user_modif']['checked'])) print_liste_field_titre($arrayfields['t.fk_user_modif']['label'], $_SERVER['PHP_SELF'], 't.fk_user_modif', '', $param, '', $sortfield, $sortorder); - if (! empty($arrayfields['t.import_key']['checked'])) print_liste_field_titre($arrayfields['t.import_key']['label'], $_SERVER['PHP_SELF'], 't.import_key', '', $param, '', $sortfield, $sortorder); + if (!empty($arrayfields['t.entity']['checked'])) print_liste_field_titre($arrayfields['t.entity']['label'], $_SERVER['PHP_SELF'], 't.entity', '', $param, '', $sortfield, $sortorder); + if (!empty($arrayfields['t.batch']['checked'])) print_liste_field_titre($arrayfields['t.batch']['label'], $_SERVER['PHP_SELF'], 't.batch', '', $param, '', $sortfield, $sortorder); + if (!empty($arrayfields['t.fk_product']['checked'])) print_liste_field_titre($arrayfields['t.fk_product']['label'], $_SERVER['PHP_SELF'], 't.fk_product', '', $param, '', $sortfield, $sortorder); + if (!empty($arrayfields['t.sellby']['checked'])) print_liste_field_titre($arrayfields['t.sellby']['label'], $_SERVER['PHP_SELF'], 't.sellby', '', $param, '', $sortfield, $sortorder); + if (!empty($arrayfields['t.eatby']['checked'])) print_liste_field_titre($arrayfields['t.eatby']['label'], $_SERVER['PHP_SELF'], 't.eatby', '', $param, '', $sortfield, $sortorder); + if (!empty($arrayfields['t.fk_user_creat']['checked'])) print_liste_field_titre($arrayfields['t.fk_user_creat']['label'], $_SERVER['PHP_SELF'], 't.fk_user_creat', '', $param, '', $sortfield, $sortorder); + if (!empty($arrayfields['t.fk_user_modif']['checked'])) print_liste_field_titre($arrayfields['t.fk_user_modif']['label'], $_SERVER['PHP_SELF'], 't.fk_user_modif', '', $param, '', $sortfield, $sortorder); + if (!empty($arrayfields['t.import_key']['checked'])) print_liste_field_titre($arrayfields['t.import_key']['label'], $_SERVER['PHP_SELF'], 't.import_key', '', $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 + $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['t.datec']['checked'])) { + if (!empty($arrayfields['t.datec']['checked'])) { print_liste_field_titre($arrayfields['t.datec']['label'], $_SERVER["PHP_SELF"], "t.datec", "", $param, '', $sortfield, $sortorder, 'center nowrap '); } - if (! empty($arrayfields['t.tms']['checked'])) { + if (!empty($arrayfields['t.tms']['checked'])) { print_liste_field_titre($arrayfields['t.tms']['label'], $_SERVER["PHP_SELF"], "t.tms", "", $param, '', $sortfield, $sortorder, 'center nowrap '); } //if (! empty($arrayfields['t.status']['checked'])) { @@ -410,8 +410,8 @@ if ($resql) $productlot = new Productlot($db); - $i=0; - $totalarray=array(); + $i = 0; + $totalarray = array(); while ($i < min($num, $limit)) { $obj = $db->fetch_object($resql); @@ -422,72 +422,72 @@ if ($resql) // You can use here results print ''; - if (! empty($arrayfields['t.entity']['checked'])) + if (!empty($arrayfields['t.entity']['checked'])) { print ''; - if (! $i) $totalarray['nbfield']++; + if (!$i) $totalarray['nbfield']++; } - if (! empty($arrayfields['t.batch']['checked'])) + if (!empty($arrayfields['t.batch']['checked'])) { print ''; - if (! $i) $totalarray['nbfield']++; + if (!$i) $totalarray['nbfield']++; } - if (! empty($arrayfields['t.fk_product']['checked'])) + if (!empty($arrayfields['t.fk_product']['checked'])) { - $productstatic->id=$obj->fk_product; - $productstatic->type=$obj->product_type; - $productstatic->ref=$obj->product_ref; - $productstatic->label=$obj->product_label; + $productstatic->id = $obj->fk_product; + $productstatic->type = $obj->product_type; + $productstatic->ref = $obj->product_ref; + $productstatic->label = $obj->product_label; $productstatic->status_batch = $obj->tobatch; print ''; - if (! $i) $totalarray['nbfield']++; + if (!$i) $totalarray['nbfield']++; } - if (! empty($arrayfields['t.sellby']['checked'])) + if (!empty($arrayfields['t.sellby']['checked'])) { print ''; - if (! $i) $totalarray['nbfield']++; + if (!$i) $totalarray['nbfield']++; } - if (! empty($arrayfields['t.eatby']['checked'])) + if (!empty($arrayfields['t.eatby']['checked'])) { print ''; - if (! $i) $totalarray['nbfield']++; + if (!$i) $totalarray['nbfield']++; } - if (! empty($arrayfields['t.fk_user_creat']['checked'])) + if (!empty($arrayfields['t.fk_user_creat']['checked'])) { print ''; - if (! $i) $totalarray['nbfield']++; + if (!$i) $totalarray['nbfield']++; } - if (! empty($arrayfields['t.fk_user_modif']['checked'])) + if (!empty($arrayfields['t.fk_user_modif']['checked'])) { print ''; - if (! $i) $totalarray['nbfield']++; + if (!$i) $totalarray['nbfield']++; } - if (! empty($arrayfields['t.import_key']['checked'])) + if (!empty($arrayfields['t.import_key']['checked'])) { print ''; - if (! $i) $totalarray['nbfield']++; + if (!$i) $totalarray['nbfield']++; } // Extra fields include DOL_DOCUMENT_ROOT.'/core/tpl/extrafields_list_print_fields.tpl.php'; // Fields from hook - $parameters=array('arrayfields'=>$arrayfields, 'obj'=>$obj); - $reshook=$hookmanager->executeHooks('printFieldListValue', $parameters); // Note that $action and $object may have been modified by hook + $parameters = array('arrayfields'=>$arrayfields, 'obj'=>$obj); + $reshook = $hookmanager->executeHooks('printFieldListValue', $parameters); // Note that $action and $object may have been modified by hook print $hookmanager->resPrint; // Date creation - if (! empty($arrayfields['t.datec']['checked'])) + if (!empty($arrayfields['t.datec']['checked'])) { print ''; - if (! $i) $totalarray['nbfield']++; + if (!$i) $totalarray['nbfield']++; } // Date modification - if (! empty($arrayfields['t.tms']['checked'])) + if (!empty($arrayfields['t.tms']['checked'])) { print ''; - if (! $i) $totalarray['nbfield']++; + if (!$i) $totalarray['nbfield']++; } // Status /* @@ -501,12 +501,12 @@ if ($resql) print ''; - if (! $i) $totalarray['nbfield']++; + if (!$i) $totalarray['nbfield']++; print ''; } @@ -518,8 +518,8 @@ if ($resql) $db->free($resql); - $parameters=array('arrayfields'=>$arrayfields, 'sql'=>$sql); - $reshook=$hookmanager->executeHooks('printFieldListFooter', $parameters); // Note that $action and $object may have been modified by hook + $parameters = array('arrayfields'=>$arrayfields, 'sql'=>$sql); + $reshook = $hookmanager->executeHooks('printFieldListFooter', $parameters); // Note that $action and $object may have been modified by hook print $hookmanager->resPrint; print '
    '; print ''; @@ -375,31 +375,31 @@ if ($resql) }*/ // Action column print ''; - $searchpicto=$form->showFilterAndCheckAddButtons($massactionbutton?1:0, 'checkforselect', 1); + $searchpicto = $form->showFilterAndCheckAddButtons($massactionbutton ? 1 : 0, 'checkforselect', 1); print $searchpicto; print '
    '.$obj->entity.''.$productlot->getNomUrl(1).''.$productstatic->getNomUrl(1).''.dol_print_date($db->jdate($obj->sellby), 'day').''.dol_print_date($db->jdate($obj->eatby), 'day').''.$obj->fk_user_creat.''.$obj->fk_user_modif.''.$obj->import_key.''; 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 ($massactionbutton || $massaction) // If we are in select mode (massactionbutton defined) or if we have already selected and sent an action ($massaction) defined { - $selected=0; - if (in_array($obj->rowid, $arrayofselected)) $selected=1; - print ''; + $selected = 0; + if (in_array($obj->rowid, $arrayofselected)) $selected = 1; + print ''; } print '
    '."\n"; diff --git a/htdocs/product/stock/replenish.php b/htdocs/product/stock/replenish.php index 168ed5e54f9..1d8b709f662 100644 --- a/htdocs/product/stock/replenish.php +++ b/htdocs/product/stock/replenish.php @@ -41,7 +41,7 @@ $langs->loadLangs(array('products', 'stocks', 'orders')); if ($user->socid) { $socid = $user->socid; } -$result=restrictedArea($user, 'produit|service'); +$result = restrictedArea($user, 'produit|service'); // Initialize technical object to manage hooks of page. Note that conf->hooks_modules contains array of hook context $hookmanager->initHooks(array('stockreplenishlist')); @@ -51,7 +51,7 @@ $hookmanager->initHooks(array('stockreplenishlist')); $action = GETPOST('action', 'alpha'); $sref = GETPOST('sref', 'alpha'); $snom = GETPOST('snom', 'alpha'); -$sall = trim((GETPOST('search_all', 'alphanohtml')!='')?GETPOST('search_all', 'alphanohtml'):GETPOST('sall', 'alphanohtml')); +$sall = trim((GETPOST('search_all', 'alphanohtml') != '') ?GETPOST('search_all', 'alphanohtml') : GETPOST('sall', 'alphanohtml')); $type = GETPOST('type', 'int'); $tobuy = GETPOST('tobuy', 'int'); $salert = GETPOST('salert', 'alpha'); @@ -68,8 +68,8 @@ $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 -$limit = GETPOST('limit', 'int')?GETPOST('limit', 'int'):$conf->liste_limit; -$offset = $limit * $page ; +$limit = GETPOST('limit', 'int') ?GETPOST('limit', 'int') : $conf->liste_limit; +$offset = $limit * $page; if (!$sortfield) { $sortfield = 'p.ref'; @@ -80,20 +80,20 @@ if (!$sortorder) { } // Define virtualdiffersfromphysical -$virtualdiffersfromphysical=0; -if (! empty($conf->global->STOCK_CALCULATE_ON_SHIPMENT) -|| ! empty($conf->global->STOCK_CALCULATE_ON_SUPPLIER_DISPATCH_ORDER) -|| ! empty($conf->global->STOCK_CALCULATE_ON_SHIPMENT_CLOSE) +$virtualdiffersfromphysical = 0; +if (!empty($conf->global->STOCK_CALCULATE_ON_SHIPMENT) +|| !empty($conf->global->STOCK_CALCULATE_ON_SUPPLIER_DISPATCH_ORDER) +|| !empty($conf->global->STOCK_CALCULATE_ON_SHIPMENT_CLOSE) || !empty($conf->global->STOCK_CALCULATE_ON_RECEPTION) || !empty($conf->global->STOCK_CALCULATE_ON_RECEPTION_CLOSE)) { - $virtualdiffersfromphysical=1; // According to increase/decrease stock options, virtual and physical stock may differs. + $virtualdiffersfromphysical = 1; // According to increase/decrease stock options, virtual and physical stock may differs. } -$usevirtualstock=0; -if ($mode == 'virtual') $usevirtualstock=1; +$usevirtualstock = 0; +if ($mode == 'virtual') $usevirtualstock = 1; -$parameters=array(); -$reshook=$hookmanager->executeHooks('doActions', $parameters, $object, $action); // Note that $action and $object may have been modified by some hooks +$parameters = array(); +$reshook = $hookmanager->executeHooks('doActions', $parameters, $object, $action); // Note that $action and $object may have been modified by some hooks if ($reshook < 0) setEventMessages($hookmanager->error, $hookmanager->errors, 'errors'); /* @@ -106,9 +106,9 @@ if (GETPOST('button_removefilter_x', 'alpha') || GETPOST('button_removefilter.x' $snom = ''; $sal = ''; $salert = ''; - $draftorder=''; + $draftorder = ''; } -if($draftorder == 'on') $draftchecked = "checked"; +if ($draftorder == 'on') $draftchecked = "checked"; // Create orders if ($action == 'order' && isset($_POST['valid'])) @@ -122,19 +122,19 @@ if ($action == 'order' && isset($_POST['valid'])) $db->begin(); $suppliers = array(); - require_once DOL_DOCUMENT_ROOT . '/fourn/class/fournisseur.product.class.php'; + require_once DOL_DOCUMENT_ROOT.'/fourn/class/fournisseur.product.class.php'; $productsupplier = new ProductFournisseur($db); for ($i = 0; $i < $linecount; $i++) { - if (GETPOST('choose' . $i, 'alpha') === 'on' && GETPOST('fourn' . $i, 'int') > 0) + if (GETPOST('choose'.$i, 'alpha') === 'on' && GETPOST('fourn'.$i, 'int') > 0) { //one line $box = $i; $supplierpriceid = GETPOST('fourn'.$i, 'int'); //get all the parameters needed to create a line $qty = GETPOST('tobuy'.$i, 'int'); - $idprod=$productsupplier->get_buyprice($supplierpriceid, $qty); - $res=$productsupplier->fetch($idprod); + $idprod = $productsupplier->get_buyprice($supplierpriceid, $qty); + $res = $productsupplier->fetch($idprod); if ($res && $idprod > 0) { if ($qty) @@ -146,12 +146,12 @@ if ($action == 'order' && isset($_POST['valid'])) //$product = new Product($db); //$product->fetch($obj->fk_product); - if (! empty($conf->global->MAIN_MULTILANGS)) + if (!empty($conf->global->MAIN_MULTILANGS)) { $productsupplier->getMultiLangs(); } $line->desc = $productsupplier->description; - if (! empty($conf->global->MAIN_MULTILANGS)) + if (!empty($conf->global->MAIN_MULTILANGS)) { // TODO Get desc in language of thirdparty } @@ -175,11 +175,11 @@ if ($action == 'order' && isset($_POST['valid'])) } else { - $error=$db->lasterror(); + $error = $db->lasterror(); dol_print_error($db); } - unset($_POST['fourn' . $i]); + unset($_POST['fourn'.$i]); } unset($_POST[$i]); } @@ -193,12 +193,12 @@ if ($action == 'order' && isset($_POST['valid'])) $order = new CommandeFournisseur($db); // Check if an order for the supplier exists $sql = "SELECT rowid FROM ".MAIN_DB_PREFIX."commande_fournisseur"; - $sql.= " WHERE fk_soc = ".$suppliersid[$i]; - $sql.= " AND source = 42 AND fk_statut = 0"; - $sql.= " AND entity IN (".getEntity('commande_fournisseur').")"; - $sql.= " ORDER BY date_creation DESC"; + $sql .= " WHERE fk_soc = ".$suppliersid[$i]; + $sql .= " AND source = 42 AND fk_statut = 0"; + $sql .= " AND entity IN (".getEntity('commande_fournisseur').")"; + $sql .= " ORDER BY date_creation DESC"; $resql = $db->query($sql); - if($resql && $db->num_rows($resql) > 0) { + if ($resql && $db->num_rows($resql) > 0) { $obj = $db->fetch_object($resql); $order->fetch($obj->rowid); foreach ($supplier['lines'] as $line) { @@ -226,7 +226,7 @@ if ($action == 'order' && isset($_POST['valid'])) } if ($result < 0) { $fail++; - $msg = $langs->trans('OrderFail') . " : "; + $msg = $langs->trans('OrderFail')." : "; $msg .= $order->error; setEventMessages($msg, null, 'errors'); } else { @@ -245,7 +245,7 @@ if ($action == 'order' && isset($_POST['valid'])) $id = $order->create($user); if ($id < 0) { $fail++; - $msg = $langs->trans('OrderFail') . " : "; + $msg = $langs->trans('OrderFail')." : "; $msg .= $order->error; setEventMessages($msg, null, 'errors'); } @@ -253,9 +253,9 @@ if ($action == 'order' && isset($_POST['valid'])) } } - if($errorQty) setEventMessages($langs->trans('ErrorOrdersNotCreatedQtyTooLow'), null, 'warnings'); + if ($errorQty) setEventMessages($langs->trans('ErrorOrdersNotCreatedQtyTooLow'), null, 'warnings'); - if (! $fail && $id) + if (!$fail && $id) { $db->commit(); @@ -286,45 +286,45 @@ $prod = new Product($db); $title = $langs->trans('Status'); if (!empty($conf->global->STOCK_ALLOW_ADD_LIMIT_STOCK_BY_WAREHOUSE) && $fk_entrepot > 0) { - $sqldesiredtock=$db->ifsql("pse.desiredstock IS NULL", "p.desiredstock", "pse.desiredstock"); - $sqlalertstock=$db->ifsql("pse.seuil_stock_alerte IS NULL", "p.seuil_stock_alerte", "pse.seuil_stock_alerte"); + $sqldesiredtock = $db->ifsql("pse.desiredstock IS NULL", "p.desiredstock", "pse.desiredstock"); + $sqlalertstock = $db->ifsql("pse.seuil_stock_alerte IS NULL", "p.seuil_stock_alerte", "pse.seuil_stock_alerte"); } else { - $sqldesiredtock='p.desiredstock'; - $sqlalertstock='p.seuil_stock_alerte'; + $sqldesiredtock = 'p.desiredstock'; + $sqlalertstock = 'p.seuil_stock_alerte'; } $sql = 'SELECT p.rowid, p.ref, p.label, p.description, p.price,'; -$sql.= ' p.price_ttc, p.price_base_type,p.fk_product_type,'; -$sql.= ' p.tms as datem, p.duration, p.tobuy,'; -$sql.= ' p.desiredstock, p.seuil_stock_alerte,'; +$sql .= ' p.price_ttc, p.price_base_type,p.fk_product_type,'; +$sql .= ' p.tms as datem, p.duration, p.tobuy,'; +$sql .= ' p.desiredstock, p.seuil_stock_alerte,'; if (!empty($conf->global->STOCK_ALLOW_ADD_LIMIT_STOCK_BY_WAREHOUSE) && $fk_entrepot > 0) { - $sql.= ' pse.desiredstock as desiredstockpse, pse.seuil_stock_alerte as seuil_stock_alertepse,'; + $sql .= ' pse.desiredstock as desiredstockpse, pse.seuil_stock_alerte as seuil_stock_alertepse,'; } -$sql.= ' '.$sqldesiredtock.' as desiredstockcombined, '.$sqlalertstock.' as seuil_stock_alertecombined,'; -$sql.= ' SUM('.$db->ifsql("s.reel IS NULL", "0", "s.reel").') as stock_physique'; +$sql .= ' '.$sqldesiredtock.' as desiredstockcombined, '.$sqlalertstock.' as seuil_stock_alertecombined,'; +$sql .= ' SUM('.$db->ifsql("s.reel IS NULL", "0", "s.reel").') as stock_physique'; // Add fields from hooks -$parameters=array(); -$reshook=$hookmanager->executeHooks('printFieldListSelect', $parameters); // Note that $action and $object may have been modified by hook -$sql.=$hookmanager->resPrint; +$parameters = array(); +$reshook = $hookmanager->executeHooks('printFieldListSelect', $parameters); // Note that $action and $object may have been modified by hook +$sql .= $hookmanager->resPrint; -$sql.= ' FROM ' . MAIN_DB_PREFIX . 'product as p'; -$sql.= ' LEFT JOIN ' . MAIN_DB_PREFIX . 'product_stock as s'; -$sql.= ' ON (p.rowid = s.fk_product AND s.fk_entrepot IN (SELECT ent.rowid FROM '.MAIN_DB_PREFIX.'entrepot AS ent WHERE ent.entity IN('.getEntity('stock').')))'; +$sql .= ' FROM '.MAIN_DB_PREFIX.'product as p'; +$sql .= ' LEFT JOIN '.MAIN_DB_PREFIX.'product_stock as s'; +$sql .= ' ON (p.rowid = s.fk_product AND s.fk_entrepot IN (SELECT ent.rowid FROM '.MAIN_DB_PREFIX.'entrepot AS ent WHERE ent.entity IN('.getEntity('stock').')))'; if ($fk_supplier > 0) { - $sql.= ' INNER JOIN '.MAIN_DB_PREFIX.'product_fournisseur_price pfp ON (pfp.fk_product = p.rowid AND pfp.fk_soc = '.$fk_supplier.')'; + $sql .= ' INNER JOIN '.MAIN_DB_PREFIX.'product_fournisseur_price pfp ON (pfp.fk_product = p.rowid AND pfp.fk_soc = '.$fk_supplier.')'; } if (!empty($conf->global->STOCK_ALLOW_ADD_LIMIT_STOCK_BY_WAREHOUSE) && $fk_entrepot > 0) { - $sql.= ' LEFT JOIN '.MAIN_DB_PREFIX.'product_warehouse_properties AS pse ON (p.rowid = pse.fk_product AND pse.fk_entrepot = '.$fk_entrepot.')'; + $sql .= ' LEFT JOIN '.MAIN_DB_PREFIX.'product_warehouse_properties AS pse ON (p.rowid = pse.fk_product AND pse.fk_entrepot = '.$fk_entrepot.')'; } // Add fields from hooks -$parameters=array(); -$reshook=$hookmanager->executeHooks('printFieldListJoin', $parameters); // Note that $action and $object may have been modified by hook -$sql.=$hookmanager->resPrint; +$parameters = array(); +$reshook = $hookmanager->executeHooks('printFieldListJoin', $parameters); // Note that $action and $object may have been modified by hook +$sql .= $hookmanager->resPrint; -$sql.= ' WHERE p.entity IN (' . getEntity('product') . ')'; +$sql .= ' WHERE p.entity IN ('.getEntity('product').')'; if ($sall) $sql .= natural_search(array('p.ref', 'p.label', 'p.description', 'p.note'), $sall); // if the type is not 1, we show all products (type = 0,2,3) if (dol_strlen($type)) { @@ -334,83 +334,83 @@ if (dol_strlen($type)) { $sql .= ' AND p.fk_product_type <> 1'; } } -if ($sref) $sql.=natural_search('p.ref', $sref); -if ($snom) $sql.=natural_search('p.label', $snom); -$sql.= ' AND p.tobuy = 1'; -if (!empty($canvas)) $sql .= ' AND p.canvas = "' . $db->escape($canvas) . '"'; -$sql.= ' GROUP BY p.rowid, p.ref, p.label, p.description, p.price'; -$sql.= ', p.price_ttc, p.price_base_type,p.fk_product_type, p.tms'; -$sql.= ', p.duration, p.tobuy'; -$sql.= ', p.desiredstock'; -$sql.= ', p.seuil_stock_alerte'; +if ($sref) $sql .= natural_search('p.ref', $sref); +if ($snom) $sql .= natural_search('p.label', $snom); +$sql .= ' AND p.tobuy = 1'; +if (!empty($canvas)) $sql .= ' AND p.canvas = "'.$db->escape($canvas).'"'; +$sql .= ' GROUP BY p.rowid, p.ref, p.label, p.description, p.price'; +$sql .= ', p.price_ttc, p.price_base_type,p.fk_product_type, p.tms'; +$sql .= ', p.duration, p.tobuy'; +$sql .= ', p.desiredstock'; +$sql .= ', p.seuil_stock_alerte'; if (!empty($conf->global->STOCK_ALLOW_ADD_LIMIT_STOCK_BY_WAREHOUSE) && $fk_entrepot > 0) { - $sql.= ', pse.desiredstock' ; - $sql.= ', pse.seuil_stock_alerte' ; + $sql .= ', pse.desiredstock'; + $sql .= ', pse.seuil_stock_alerte'; } -$sql.= ', s.fk_product'; +$sql .= ', s.fk_product'; if ($usevirtualstock) { $sqlCommandesCli = "(SELECT ".$db->ifsql("SUM(cd.qty) IS NULL", "0", "SUM(cd.qty)")." as qty"; - $sqlCommandesCli.= " FROM ".MAIN_DB_PREFIX."commandedet as cd"; - $sqlCommandesCli.= " LEFT JOIN ".MAIN_DB_PREFIX."commande as c ON (c.rowid = cd.fk_commande)"; - $sqlCommandesCli.= " WHERE c.entity IN (".getEntity('commande').")"; - $sqlCommandesCli.= " AND cd.fk_product = p.rowid"; - $sqlCommandesCli.= " AND c.fk_statut IN (1,2))"; + $sqlCommandesCli .= " FROM ".MAIN_DB_PREFIX."commandedet as cd"; + $sqlCommandesCli .= " LEFT JOIN ".MAIN_DB_PREFIX."commande as c ON (c.rowid = cd.fk_commande)"; + $sqlCommandesCli .= " WHERE c.entity IN (".getEntity('commande').")"; + $sqlCommandesCli .= " AND cd.fk_product = p.rowid"; + $sqlCommandesCli .= " AND c.fk_statut IN (1,2))"; $sqlExpeditionsCli = "(SELECT ".$db->ifsql("SUM(ed.qty) IS NULL", "0", "SUM(ed.qty)")." as qty"; - $sqlExpeditionsCli.= " FROM ".MAIN_DB_PREFIX."expedition as e"; - $sqlExpeditionsCli.= " LEFT JOIN ".MAIN_DB_PREFIX."expeditiondet as ed ON (ed.fk_expedition = e.rowid)"; - $sqlExpeditionsCli.= " LEFT JOIN ".MAIN_DB_PREFIX."commandedet as cd ON (cd.rowid = ed.fk_origin_line)"; - $sqlExpeditionsCli.= " LEFT JOIN ".MAIN_DB_PREFIX."commande as c ON (c.rowid = cd.fk_commande)"; - $sqlExpeditionsCli.= " WHERE e.entity IN (".getEntity('expedition').")"; - $sqlExpeditionsCli.= " AND cd.fk_product = p.rowid"; - $sqlExpeditionsCli.= " AND c.fk_statut IN (1,2))"; + $sqlExpeditionsCli .= " FROM ".MAIN_DB_PREFIX."expedition as e"; + $sqlExpeditionsCli .= " LEFT JOIN ".MAIN_DB_PREFIX."expeditiondet as ed ON (ed.fk_expedition = e.rowid)"; + $sqlExpeditionsCli .= " LEFT JOIN ".MAIN_DB_PREFIX."commandedet as cd ON (cd.rowid = ed.fk_origin_line)"; + $sqlExpeditionsCli .= " LEFT JOIN ".MAIN_DB_PREFIX."commande as c ON (c.rowid = cd.fk_commande)"; + $sqlExpeditionsCli .= " WHERE e.entity IN (".getEntity('expedition').")"; + $sqlExpeditionsCli .= " AND cd.fk_product = p.rowid"; + $sqlExpeditionsCli .= " AND c.fk_statut IN (1,2))"; $sqlCommandesFourn = "(SELECT ".$db->ifsql("SUM(cd.qty) IS NULL", "0", "SUM(cd.qty)")." as qty"; - $sqlCommandesFourn.= " FROM ".MAIN_DB_PREFIX."commande_fournisseurdet as cd"; - $sqlCommandesFourn.= ", ".MAIN_DB_PREFIX."commande_fournisseur as c"; - $sqlCommandesFourn.= " WHERE c.rowid = cd.fk_commande"; - $sqlCommandesFourn.= " AND c.entity IN (".getEntity('supplier_order').")"; - $sqlCommandesFourn.= " AND cd.fk_product = p.rowid"; - $sqlCommandesFourn.= " AND c.fk_statut IN (3,4))"; + $sqlCommandesFourn .= " FROM ".MAIN_DB_PREFIX."commande_fournisseurdet as cd"; + $sqlCommandesFourn .= ", ".MAIN_DB_PREFIX."commande_fournisseur as c"; + $sqlCommandesFourn .= " WHERE c.rowid = cd.fk_commande"; + $sqlCommandesFourn .= " AND c.entity IN (".getEntity('supplier_order').")"; + $sqlCommandesFourn .= " AND cd.fk_product = p.rowid"; + $sqlCommandesFourn .= " AND c.fk_statut IN (3,4))"; $sqlReceptionFourn = "(SELECT ".$db->ifsql("SUM(fd.qty) IS NULL", "0", "SUM(fd.qty)")." as qty"; - $sqlReceptionFourn.= " FROM ".MAIN_DB_PREFIX."commande_fournisseur as cf"; - $sqlReceptionFourn.= " LEFT JOIN ".MAIN_DB_PREFIX."commande_fournisseur_dispatch as fd ON (fd.fk_commande = cf.rowid)"; - $sqlReceptionFourn.= " WHERE cf.entity IN (".getEntity('supplier_order').")"; - $sqlReceptionFourn.= " AND fd.fk_product = p.rowid"; - $sqlReceptionFourn.= " AND cf.fk_statut IN (3,4))"; + $sqlReceptionFourn .= " FROM ".MAIN_DB_PREFIX."commande_fournisseur as cf"; + $sqlReceptionFourn .= " LEFT JOIN ".MAIN_DB_PREFIX."commande_fournisseur_dispatch as fd ON (fd.fk_commande = cf.rowid)"; + $sqlReceptionFourn .= " WHERE cf.entity IN (".getEntity('supplier_order').")"; + $sqlReceptionFourn .= " AND fd.fk_product = p.rowid"; + $sqlReceptionFourn .= " AND cf.fk_statut IN (3,4))"; - $sql.= ' HAVING (('.$sqldesiredtock.' >= 0 AND ('.$sqldesiredtock.' > SUM('.$db->ifsql("s.reel IS NULL", "0", "s.reel").')'; - $sql.= ' - ('.$sqlCommandesCli.' - '.$sqlExpeditionsCli.') + ('.$sqlCommandesFourn.' - '.$sqlReceptionFourn.')))'; - $sql.= ' OR ('.$sqlalertstock.' >= 0 AND ('.$sqlalertstock.' > SUM('.$db->ifsql("s.reel IS NULL", "0", "s.reel").')'; - $sql.= ' - ('.$sqlCommandesCli.' - '.$sqlExpeditionsCli.') + ('.$sqlCommandesFourn.' - '.$sqlReceptionFourn.'))))'; + $sql .= ' HAVING (('.$sqldesiredtock.' >= 0 AND ('.$sqldesiredtock.' > SUM('.$db->ifsql("s.reel IS NULL", "0", "s.reel").')'; + $sql .= ' - ('.$sqlCommandesCli.' - '.$sqlExpeditionsCli.') + ('.$sqlCommandesFourn.' - '.$sqlReceptionFourn.')))'; + $sql .= ' OR ('.$sqlalertstock.' >= 0 AND ('.$sqlalertstock.' > SUM('.$db->ifsql("s.reel IS NULL", "0", "s.reel").')'; + $sql .= ' - ('.$sqlCommandesCli.' - '.$sqlExpeditionsCli.') + ('.$sqlCommandesFourn.' - '.$sqlReceptionFourn.'))))'; if ($salert == 'on') // Option to see when stock is lower than alert { - $sql.= ' AND ('.$sqlalertstock.' >= 0 AND ('.$sqlalertstock.' > SUM('.$db->ifsql("s.reel IS NULL", "0", "s.reel").')'; - $sql.= ' - ('.$sqlCommandesCli.' - '.$sqlExpeditionsCli.') + ('.$sqlCommandesFourn.' - '.$sqlReceptionFourn.')))'; + $sql .= ' AND ('.$sqlalertstock.' >= 0 AND ('.$sqlalertstock.' > SUM('.$db->ifsql("s.reel IS NULL", "0", "s.reel").')'; + $sql .= ' - ('.$sqlCommandesCli.' - '.$sqlExpeditionsCli.') + ('.$sqlCommandesFourn.' - '.$sqlReceptionFourn.')))'; $alertchecked = 'checked'; } } else { - $sql.= ' HAVING (('.$sqldesiredtock.' >= 0 AND ('.$sqldesiredtock.' > SUM('.$db->ifsql("s.reel IS NULL", "0", "s.reel").')))'; - $sql.= ' OR ('.$sqlalertstock.' >= 0 AND ('.$sqlalertstock.' > SUM('.$db->ifsql("s.reel IS NULL", "0", "s.reel").'))))'; + $sql .= ' HAVING (('.$sqldesiredtock.' >= 0 AND ('.$sqldesiredtock.' > SUM('.$db->ifsql("s.reel IS NULL", "0", "s.reel").')))'; + $sql .= ' OR ('.$sqlalertstock.' >= 0 AND ('.$sqlalertstock.' > SUM('.$db->ifsql("s.reel IS NULL", "0", "s.reel").'))))'; if ($salert == 'on') // Option to see when stock is lower than alert { - $sql.= ' AND ('.$sqlalertstock.' >= 0 AND ('.$sqlalertstock.' > SUM('.$db->ifsql("s.reel IS NULL", "0", "s.reel").')))'; + $sql .= ' AND ('.$sqlalertstock.' >= 0 AND ('.$sqlalertstock.' > SUM('.$db->ifsql("s.reel IS NULL", "0", "s.reel").')))'; $alertchecked = 'checked'; } } // Add where from hooks -$parameters=array(); -$reshook=$hookmanager->executeHooks('printFieldListWhere', $parameters); // Note that $action and $object may have been modified by hook -$sql.=$hookmanager->resPrint; +$parameters = array(); +$reshook = $hookmanager->executeHooks('printFieldListWhere', $parameters); // Note that $action and $object may have been modified by hook +$sql .= $hookmanager->resPrint; -$sql.= $db->order($sortfield, $sortorder); -$sql.= $db->plimit($limit + 1, $offset); +$sql .= $db->order($sortfield, $sortorder); +$sql .= $db->plimit($limit + 1, $offset); //print $sql; $resql = $db->query($sql); @@ -473,8 +473,8 @@ print '
    '; print $langs->trans('Supplier').' '.$form->select_company($fk_supplier, 'fk_supplier', 'fournisseur=1', 1); print '
    '; -$parameters=array(); -$reshook=$hookmanager->executeHooks('printFieldPreListTitle', $parameters); // Note that $action and $object may have been modified by hook +$parameters = array(); +$reshook = $hookmanager->executeHooks('printFieldPreListTitle', $parameters); // Note that $action and $object may have been modified by hook if (empty($reshook)) print $hookmanager->resPrint; print '
    '; @@ -484,13 +484,13 @@ print '
    '; print ''; if ($sref || $snom || $sall || $salert || $draftorder || GETPOST('search', 'alpha')) { - $filters = '&sref=' . $sref . '&snom=' . $snom; - $filters .= '&sall=' . $sall; - $filters .= '&salert=' . $salert; - $filters .= '&draftorder=' . $draftorder; - $filters .= '&mode=' . $mode; - $filters .= '&fk_supplier=' . $fk_supplier; - $filters .= '&fk_entrepot=' . $fk_entrepot; + $filters = '&sref='.$sref.'&snom='.$snom; + $filters .= '&sall='.$sall; + $filters .= '&salert='.$salert; + $filters .= '&draftorder='.$draftorder; + $filters .= '&mode='.$mode; + $filters .= '&fk_supplier='.$fk_supplier; + $filters .= '&fk_entrepot='.$fk_entrepot; print_barre_liste( $texte, $page, @@ -502,14 +502,14 @@ if ($sref || $snom || $sall || $salert || $draftorder || GETPOST('search', 'alph $num ); } else { - $filters = '&sref=' . $sref . '&snom=' . $snom; - $filters .= '&fourn_id=' . $fourn_id; - $filters .= (isset($type)?'&type=' . $type:''); - $filters .= '&=' . $salert; - $filters .= '&draftorder=' . $draftorder; - $filters .= '&mode=' . $mode; - $filters .= '&fk_supplier=' . $fk_supplier; - $filters .= '&fk_entrepot=' . $fk_entrepot; + $filters = '&sref='.$sref.'&snom='.$snom; + $filters .= '&fourn_id='.$fourn_id; + $filters .= (isset($type) ? '&type='.$type : ''); + $filters .= '&='.$salert; + $filters .= '&draftorder='.$draftorder; + $filters .= '&mode='.$mode; + $filters .= '&fk_supplier='.$fk_supplier; + $filters .= '&fk_entrepot='.$fk_entrepot; print_barre_liste( $texte, $page, @@ -522,33 +522,33 @@ if ($sref || $snom || $sall || $salert || $draftorder || GETPOST('search', 'alph ); } -print '
    '; // You can use div-table-responsive-no-min if you dont need reserved height for your table -print ''; +print '
    '; // You can use div-table-responsive-no-min if you dont need reserved height for your table +print '
    '; -$param = (isset($type)? '&type=' . $type : ''); -$param .= '&fourn_id=' . $fourn_id . '&snom='. $snom . '&salert=' . $salert . '&draftorder='.$draftorder; -$param .= '&sref=' . $sref; -$param .= '&mode=' . $mode; -$param .= '&fk_supplier=' . $fk_supplier; -$param .= '&fk_entrepot=' . $fk_entrepot; +$param = (isset($type) ? '&type='.$type : ''); +$param .= '&fourn_id='.$fourn_id.'&snom='.$snom.'&salert='.$salert.'&draftorder='.$draftorder; +$param .= '&sref='.$sref; +$param .= '&mode='.$mode; +$param .= '&fk_supplier='.$fk_supplier; +$param .= '&fk_entrepot='.$fk_entrepot; $stocklabel = $langs->trans('Stock'); if ($usevirtualstock == 1) $stocklabel = $langs->trans('VirtualStock'); if ($usevirtualstock == 0) $stocklabel = $langs->trans('PhysicalStock'); if (!empty($conf->global->STOCK_ALLOW_ADD_LIMIT_STOCK_BY_WAREHOUSE) && $fk_entrepot > 0) { - $stocklabel.=' ('.$langs->trans("AllWarehouses").')'; + $stocklabel .= ' ('.$langs->trans("AllWarehouses").')'; } print ''. - ''. - ''. - ''. - ''. - ''. - ''. - ''. + ''. + ''. + ''. + ''. + ''. + ''. + ''. ''. - ''; + ''; // Fields title search print ''; @@ -558,16 +558,16 @@ print ''; print ''; print ''; -print ''; -print ''; +print ''; +print ''; print ''; // Fields from hook -$parameters=array('param'=>$param,'sortfield'=>$sortfield,'sortorder'=>$sortorder); -$reshook=$hookmanager->executeHooks('printFieldListOption', $parameters); // Note that $action and $object may have been modified by hook +$parameters = array('param'=>$param, 'sortfield'=>$sortfield, 'sortorder'=>$sortorder); +$reshook = $hookmanager->executeHooks('printFieldListOption', $parameters); // Note that $action and $object may have been modified by hook print $hookmanager->resPrint; print ''; print ''; @@ -586,8 +586,8 @@ print_liste_field_titre('StockToBuy', $_SERVER["PHP_SELF"], '', $param, '', '', print_liste_field_titre('SupplierRef', $_SERVER["PHP_SELF"], '', $param, '', '', $sortfield, $sortorder, 'right '); // Hook fields -$parameters=array('param'=>$param,'sortfield'=>$sortfield,'sortorder'=>$sortorder); -$reshook=$hookmanager->executeHooks('printFieldListTitle', $parameters); // Note that $action and $object may have been modified by hook +$parameters = array('param'=>$param, 'sortfield'=>$sortfield, 'sortorder'=>$sortorder); +$reshook = $hookmanager->executeHooks('printFieldListTitle', $parameters); // Note that $action and $object may have been modified by hook print $hookmanager->resPrint; print "\n"; @@ -596,18 +596,18 @@ while ($i < ($limit ? min($num, $limit) : $num)) { $objp = $db->fetch_object($resql); - if (! empty($conf->global->STOCK_SUPPORTS_SERVICES) || $objp->fk_product_type == 0) + if (!empty($conf->global->STOCK_SUPPORTS_SERVICES) || $objp->fk_product_type == 0) { $prod->fetch($objp->rowid); $prod->load_stock('warehouseopen, warehouseinternal'); // Multilangs - if (! empty($conf->global->MAIN_MULTILANGS)) + if (!empty($conf->global->MAIN_MULTILANGS)) { $sql = 'SELECT label,description'; - $sql .= ' FROM ' . MAIN_DB_PREFIX . 'product_lang'; - $sql .= ' WHERE fk_product = ' . $objp->rowid; - $sql .= ' AND lang = "' . $langs->getDefaultLang() . '"'; + $sql .= ' FROM '.MAIN_DB_PREFIX.'product_lang'; + $sql .= ' WHERE fk_product = '.$objp->rowid; + $sql .= ' AND lang = "'.$langs->getDefaultLang().'"'; $sql .= ' LIMIT 1'; $resqlm = $db->query($sql); @@ -630,25 +630,25 @@ while ($i < ($limit ? min($num, $limit) : $num)) } // Force call prod->load_stats_xxx to choose status to count (otherwise it is loaded by load_stock function) - if(isset($draftchecked)){ - $result=$prod->load_stats_commande_fournisseur(0, '0,1,2,3,4'); - }else { - $result=$prod->load_stats_commande_fournisseur(0, '1,2,3,4'); + if (isset($draftchecked)) { + $result = $prod->load_stats_commande_fournisseur(0, '0,1,2,3,4'); + } else { + $result = $prod->load_stats_commande_fournisseur(0, '1,2,3,4'); } - $result=$prod->load_stats_reception(0, '4'); + $result = $prod->load_stats_reception(0, '4'); //print $prod->stats_commande_fournisseur['qty'].'
    '."\n"; //print $prod->stats_reception['qty']; $ordered = $prod->stats_commande_fournisseur['qty'] - $prod->stats_reception['qty']; - $desiredstock=($objp->desiredstockpse ? $objp->desiredstockpse : $objp->desiredstock); - $alertstock=($objp->seuil_stock_alertepse ? $objp->seuil_stock_alertepse : $objp->seuil_stock_alerte); + $desiredstock = ($objp->desiredstockpse ? $objp->desiredstockpse : $objp->desiredstock); + $alertstock = ($objp->seuil_stock_alertepse ? $objp->seuil_stock_alertepse : $objp->seuil_stock_alerte); - $warning=''; + $warning = ''; if ($alertstock && ($stock < $alertstock)) { - $warning = img_warning($langs->trans('StockTooLow')) . ' '; + $warning = img_warning($langs->trans('StockTooLow')).' '; } //depending on conf, use either physical stock or @@ -679,18 +679,18 @@ while ($i < ($limit ? min($num, $limit) : $num)) print ''; - print ''; if (!empty($conf->service->enabled) && $type == 1) { if (preg_match('/([0-9]+)y/i', $objp->duration, $regs)) { - $duration = $regs[1] . ' ' . $langs->trans('DurationYear'); + $duration = $regs[1].' '.$langs->trans('DurationYear'); } elseif (preg_match('/([0-9]+)m/i', $objp->duration, $regs)) { - $duration = $regs[1] . ' ' . $langs->trans('DurationMonth'); + $duration = $regs[1].' '.$langs->trans('DurationMonth'); } elseif (preg_match('/([0-9]+)d/i', $objp->duration, $regs)) { - $duration = $regs[1] . ' ' . $langs->trans('DurationDay'); + $duration = $regs[1].' '.$langs->trans('DurationDay'); } else { $duration = $objp->duration; } @@ -698,27 +698,27 @@ while ($i < ($limit ? min($num, $limit) : $num)) } // Desired stock - print ''; + print ''; // Limit stock for alert - print ''; + print ''; // Current stock (all warehouses) - print ''; + print ''; // Already ordered - print ''; + print ''; // To order //print ''; print ''; // Supplier - print ''; + print ''; // Fields from hook - $parameters=array( 'objp'=>$objp); - $reshook=$hookmanager->executeHooks('printFieldListValue', $parameters); // Note that $action and $object may have been modified by hook + $parameters = array('objp'=>$objp); + $reshook = $hookmanager->executeHooks('printFieldListValue', $parameters); // Note that $action and $object may have been modified by hook print $hookmanager->resPrint; print ''; @@ -726,8 +726,8 @@ while ($i < ($limit ? min($num, $limit) : $num)) $i++; } -$parameters=array('sql'=>$sql); -$reshook=$hookmanager->executeHooks('printFieldListFooter', $parameters); // Note that $action and $object may have been modified by hook +$parameters = array('sql'=>$sql); +$reshook = $hookmanager->executeHooks('printFieldListFooter', $parameters); // Note that $action and $object may have been modified by hook print $hookmanager->resPrint; print '
    service->enabled) && $type == 1) print '   ' . $langs->trans('AlertOnly') . ' ' . $langs->trans('IncludeAlsoDraftOrders') . ' '.$langs->trans('AlertOnly').' '.$langs->trans('IncludeAlsoDraftOrders').'  '; -$searchpicto=$form->showFilterAndCheckAddButtons(0); +$searchpicto = $form->showFilterAndCheckAddButtons(0); print $searchpicto; print '
    '.$prod->getNomUrl(1, '').''.$objp->label ; - print ''; // TODO Remove this and make a fetch to get description when creating order instead of a GETPOST + print ''.$objp->label; + print ''; // TODO Remove this and make a fetch to get description when creating order instead of a GETPOST print '' . $desiredstock . ''.$desiredstock.'' . $alertstock . ''.$alertstock.''. $warning . $stock. ''.$warning.$stock.''. $ordered . ' ' . $picto. ''.$ordered.' '.$picto.''. $form->select_product_fourn_price($prod->id, 'fourn'.$i, $fk_supplier).''.$form->select_product_fourn_price($prod->id, 'fourn'.$i, $fk_supplier).'
    '; @@ -738,7 +738,7 @@ $db->free($resql); dol_fiche_end(); -$value=$langs->trans("CreateOrders"); +$value = $langs->trans("CreateOrders"); print '
    '; diff --git a/htdocs/product/stock/replenishorders.php b/htdocs/product/stock/replenishorders.php index 27834923a0e..13f7cca301f 100644 --- a/htdocs/product/stock/replenishorders.php +++ b/htdocs/product/stock/replenishorders.php @@ -170,7 +170,7 @@ if ($resql) print ''; - print ''; + print '
    '; print ''; print '
    '. diff --git a/htdocs/product/stock/tpl/stockcorrection.tpl.php b/htdocs/product/stock/tpl/stockcorrection.tpl.php index 63b80636d67..9f0c4dd376e 100644 --- a/htdocs/product/stock/tpl/stockcorrection.tpl.php +++ b/htdocs/product/stock/tpl/stockcorrection.tpl.php @@ -62,7 +62,7 @@ if (empty($conf) || ! is_object($conf)) { print ''; print ''; print ''; - print ''; + print '
    '; // Warehouse or product print ''; diff --git a/htdocs/product/stock/tpl/stocktransfer.tpl.php b/htdocs/product/stock/tpl/stocktransfer.tpl.php index dc814e54790..f796827587e 100644 --- a/htdocs/product/stock/tpl/stocktransfer.tpl.php +++ b/htdocs/product/stock/tpl/stocktransfer.tpl.php @@ -66,7 +66,7 @@ if ($pdluoid) { print ''; } - print '
    '; + print '
    '; // Source warehouse or product print ''; diff --git a/htdocs/product/stock/valo.php b/htdocs/product/stock/valo.php index 341e2e3ec45..32ffebdba76 100644 --- a/htdocs/product/stock/valo.php +++ b/htdocs/product/stock/valo.php @@ -83,7 +83,7 @@ if ($result) print_barre_liste($langs->trans("EnhancedValueOfWarehouses"), $page, $_SERVER["PHP_SELF"], "", $sortfield, $sortorder, '', $num); - print '
    '; + print '
    '; print ""; print_liste_field_titre("Ref", $_SERVER["PHP_SELF"], "e.ref", "", "", "", $sortfield, $sortorder); print_liste_field_titre("LocationSummary", $_SERVER["PHP_SELF"], "e.lieu", "", "", "", $sortfield, $sortorder); diff --git a/htdocs/product/traduction.php b/htdocs/product/traduction.php index 19a23e1e9d2..bab78114fed 100644 --- a/htdocs/product/traduction.php +++ b/htdocs/product/traduction.php @@ -36,14 +36,14 @@ $langs->loadLangs(array('products', 'languages')); $id = GETPOST('id', 'int'); $ref = GETPOST('ref', 'alpha'); -$action=GETPOST('action', 'alpha'); -$cancel=GETPOST('cancel', 'alpha'); +$action = GETPOST('action', 'alpha'); +$cancel = GETPOST('cancel', 'alpha'); // Security check -$fieldvalue = (! empty($id) ? $id : (! empty($ref) ? $ref : '')); -$fieldtype = (! empty($ref) ? 'ref' : 'rowid'); -if ($user->socid) $socid=$user->socid; -$result=restrictedArea($user, 'produit|service', $fieldvalue, 'product&product', '', '', $fieldtype); +$fieldvalue = (!empty($id) ? $id : (!empty($ref) ? $ref : '')); +$fieldtype = (!empty($ref) ? 'ref' : 'rowid'); +if ($user->socid) $socid = $user->socid; +$result = restrictedArea($user, 'produit|service', $fieldvalue, 'product&product', '', '', $fieldtype); /* @@ -73,21 +73,21 @@ $cancel != $langs->trans("Cancel") && $current_lang = $langs->getDefaultLang(); // update de l'objet - if ( $_POST["forcelangprod"] == $current_lang ) + if ($_POST["forcelangprod"] == $current_lang) { $object->label = $_POST["libelle"]; - $object->description = dol_htmlcleanlastbr($_POST["desc"]); + $object->description = dol_htmlcleanlastbr($_POST["desc"]); $object->other = dol_htmlcleanlastbr($_POST["other"]); } else { $object->multilangs[$_POST["forcelangprod"]]["label"] = $_POST["libelle"]; - $object->multilangs[$_POST["forcelangprod"]]["description"] = dol_htmlcleanlastbr($_POST["desc"]); + $object->multilangs[$_POST["forcelangprod"]]["description"] = dol_htmlcleanlastbr($_POST["desc"]); $object->multilangs[$_POST["forcelangprod"]]["other"] = dol_htmlcleanlastbr($_POST["other"]); } // sauvegarde en base - if ( $object->setMultiLangs($user) > 0 ) + if ($object->setMultiLangs($user) > 0) { $action = ''; } @@ -109,21 +109,21 @@ $cancel != $langs->trans("Cancel") && foreach ($object->multilangs as $key => $value) // enregistrement des nouvelles valeurs dans l'objet { - if ( $key == $current_lang ) + if ($key == $current_lang) { $object->label = $_POST["libelle-".$key]; - $object->description = dol_htmlcleanlastbr($_POST["desc-".$key]); + $object->description = dol_htmlcleanlastbr($_POST["desc-".$key]); $object->other = dol_htmlcleanlastbr($_POST["other-".$key]); } else { $object->multilangs[$key]["label"] = $_POST["libelle-".$key]; - $object->multilangs[$key]["description"] = dol_htmlcleanlastbr($_POST["desc-".$key]); + $object->multilangs[$key]["description"] = dol_htmlcleanlastbr($_POST["desc-".$key]); $object->multilangs[$key]["other"] = dol_htmlcleanlastbr($_POST["other-".$key]); } } - if ( $object->setMultiLangs($user) > 0 ) + if ($object->setMultiLangs($user) > 0) { $action = ''; } @@ -141,10 +141,10 @@ $cancel != $langs->trans("Cancel") && { $object = new Product($db); $object->fetch($id); - $langtodelete=GETPOST('langdel', 'alpha'); + $langtodelete = GETPOST('langdel', 'alpha'); - if ( $object->delMultiLangs($langtodelete, $user) > 0 ) + if ($object->delMultiLangs($langtodelete, $user) > 0) { $action = ''; } @@ -168,28 +168,28 @@ $helpurl = ''; $shortlabel = dol_trunc($object->label, 16); if (GETPOST("type") == '0' || ($object->type == Product::TYPE_PRODUCT)) { - $title = $langs->trans('Product')." ". $shortlabel ." - ".$langs->trans('Translation'); - $helpurl='EN:Module_Products|FR:Module_Produits|ES:Módulo_Productos'; + $title = $langs->trans('Product')." ".$shortlabel." - ".$langs->trans('Translation'); + $helpurl = 'EN:Module_Products|FR:Module_Produits|ES:Módulo_Productos'; } if (GETPOST("type") == '1' || ($object->type == Product::TYPE_SERVICE)) { - $title = $langs->trans('Service')." ". $shortlabel ." - ".$langs->trans('Translation'); - $helpurl='EN:Module_Services_En|FR:Module_Services|ES:Módulo_Servicios'; + $title = $langs->trans('Service')." ".$shortlabel." - ".$langs->trans('Translation'); + $helpurl = 'EN:Module_Services_En|FR:Module_Services|ES:Módulo_Servicios'; } llxHeader('', $title, $helpurl); $form = new Form($db); -$formadmin=new FormAdmin($db); +$formadmin = new FormAdmin($db); -$head=product_prepare_head($object); -$titre=$langs->trans("CardProduct".$object->type); -$picto=($object->type==Product::TYPE_SERVICE?'service':'product'); +$head = product_prepare_head($object); +$titre = $langs->trans("CardProduct".$object->type); +$picto = ($object->type == Product::TYPE_SERVICE ? 'service' : 'product'); // Calculate $cnt_trans $cnt_trans = 0; -if (! empty($object->multilangs)) +if (!empty($object->multilangs)) { foreach ($object->multilangs as $key => $value) { @@ -203,7 +203,7 @@ dol_fiche_head($head, 'translation', $titre, 0, $picto); $linkback = ''.$langs->trans("BackToList").''; $shownav = 1; -if ($user->socid && ! in_array('product', explode(',', $conf->global->MAIN_MODULES_FOR_EXTERNAL))) $shownav=0; +if ($user->socid && !in_array('product', explode(',', $conf->global->MAIN_MODULES_FOR_EXTERNAL))) $shownav = 0; dol_banner_tab($object, 'ref', $linkback, $shownav, 'ref', '', '', '', 0, '', '', 1); @@ -242,21 +242,21 @@ if ($action == 'edit') print ''; print ''; - if (! empty($object->multilangs)) + if (!empty($object->multilangs)) { foreach ($object->multilangs as $key => $value) { - $s=picto_from_langcode($key); - print "
    ".($s?$s.' ':'')." ".$langs->trans('Language_'.$key).": ".''.img_delete('', 'class="valigntextbottom"')."
    "; + $s = picto_from_langcode($key); + print "
    ".($s ? $s.' ' : '')." ".$langs->trans('Language_'.$key).": ".''.img_delete('', 'class="valigntextbottom"')."
    "; print '
    '; - print '
    '; + print '
    '; print ''; print ''; - if (! empty($conf->global->PRODUCT_USE_OTHER_FIELD_IN_TRANSLATION)) + if (!empty($conf->global->PRODUCT_USE_OTHER_FIELD_IN_TRANSLATION)) { print ''; - $htmlforlines.= ''; - $htmlforlines.= ''."\n"; + $htmlforlines .= ''; + $htmlforlines .= ''; + $htmlforlines .= ''."\n"; } - $htmlforlines.= '
    '.$langs->trans('Label').'
    '.$langs->trans('Description').''; $doleditor = new DolEditor("desc-$key", $object->multilangs[$key]["description"], '', 160, 'dolibarr_notes', '', false, true, $conf->global->FCKEDITOR_ENABLE_PRODUCTDESC, ROWS_3, '90%'); $doleditor->Create(); print '
    '.$langs->trans('Other').' ('.$langs->trans("NotUsed").')'; $doleditor = new DolEditor("other-$key", $object->multilangs[$key]["other"], '', 160, 'dolibarr_notes', '', false, true, $conf->global->FCKEDITOR_ENABLE_PRODUCTDESC, ROWS_3, '90%'); @@ -279,19 +279,19 @@ if ($action == 'edit') } elseif ($action != 'add') { - if (! empty($object->multilangs)) + if (!empty($object->multilangs)) { foreach ($object->multilangs as $key => $value) { - $s=picto_from_langcode($key); - print ($s?$s.' ':'')." ".$langs->trans('Language_'.$key).": ".''.img_delete('', 'class="valigntextbottom"').''; + $s = picto_from_langcode($key); + print ($s ? $s.' ' : '')." ".$langs->trans('Language_'.$key).": ".''.img_delete('', 'class="valigntextbottom"').''; print '
    '; print '
    '; - print ''; + print '
    '; print ''; print ''; - if (! empty($conf->global->PRODUCT_USE_OTHER_FIELD_IN_TRANSLATION)) + if (!empty($conf->global->PRODUCT_USE_OTHER_FIELD_IN_TRANSLATION)) { print ''; } @@ -299,7 +299,7 @@ elseif ($action != 'add') print ''; } } - if (! $cnt_trans && $action != 'add') print '
    '. $langs->trans('NoTranslation').'
    '; + if (!$cnt_trans && $action != 'add') print '
    '.$langs->trans('NoTranslation').'
    '; } @@ -321,7 +321,7 @@ if ($action == 'add' && ($user->rights->produit->creer || $user->rights->service dol_fiche_head(); - print '
    '.$langs->trans('Label').''.$object->multilangs[$key]["label"].'
    '.$langs->trans('Description').''.$object->multilangs[$key]["description"].'
    '.$langs->trans('Other').' ('.$langs->trans("NotUsed").')'.$object->multilangs[$key]["other"].'
    '; + print '
    '; print ''; @@ -331,7 +331,7 @@ if ($action == 'add' && ($user->rights->produit->creer || $user->rights->service $doleditor->Create(); print ''; // Other field (not used) - if (! empty($conf->global->PRODUCT_USE_OTHER_FIELD_IN_TRANSLATION)) + if (!empty($conf->global->PRODUCT_USE_OTHER_FIELD_IN_TRANSLATION)) { print '
    '.$langs->trans('Language').''; print $formadmin->select_language('', 'forcelangprod', 0, $object->multilangs, 1); print '
    '.$langs->trans('Other').' ('.$langs->trans("NotUsed").''; $doleditor = new DolEditor('other', '', '', 160, 'dolibarr_notes', '', false, true, $conf->global->FCKEDITOR_ENABLE_PRODUCTDESC, ROWS_3, '90%'); diff --git a/htdocs/projet/activity/index.php b/htdocs/projet/activity/index.php index cf1249aa9eb..11c2e91b233 100644 --- a/htdocs/projet/activity/index.php +++ b/htdocs/projet/activity/index.php @@ -31,12 +31,12 @@ require_once DOL_DOCUMENT_ROOT.'/core/lib/project.lib.php'; require_once DOL_DOCUMENT_ROOT.'/core/lib/date.lib.php'; $search_project_user = GETPOST('search_project_user', 'int'); -$mine = GETPOST('mode', 'aZ09')=='mine' ? 1 : 0; +$mine = GETPOST('mode', 'aZ09') == 'mine' ? 1 : 0; if ($search_project_user == $user->id) $mine = 1; // Security check -$socid=0; -if ($user->socid > 0) $socid=$user->socid; +$socid = 0; +if ($user->socid > 0) $socid = $user->socid; //$result = restrictedArea($user, 'projet', $projectid); if (!$user->rights->projet->lire) accessforbidden(); @@ -54,36 +54,36 @@ $langs->load("projects"); */ $now = dol_now(); -$tmp=dol_getdate($now); -$day=$tmp['mday']; -$month=$tmp['mon']; -$year=$tmp['year']; +$tmp = dol_getdate($now); +$day = $tmp['mday']; +$month = $tmp['mon']; +$year = $tmp['year']; -$projectstatic=new Project($db); -$taskstatic=new Task($db); -$projectsListId = $projectstatic->getProjectsAuthorizedForUser($user, 0, 1); // Return all projects I have permission on because I want my tasks and some of my task may be on a public projet that is not my project -$taskstatic=new Task($db); -$tasktmp=new Task($db); +$projectstatic = new Project($db); +$taskstatic = new Task($db); +$projectsListId = $projectstatic->getProjectsAuthorizedForUser($user, 0, 1); // Return all projects I have permission on because I want my tasks and some of my task may be on a public projet that is not my project +$taskstatic = new Task($db); +$tasktmp = new Task($db); -$title=$langs->trans("Activities"); +$title = $langs->trans("Activities"); //if ($mine) $title=$langs->trans("MyActivities"); llxHeader("", $title); // Title for combo list see all projects -$titleall=$langs->trans("AllAllowedProjects"); -if (! empty($user->rights->projet->all->lire) && ! $socid) $titleall=$langs->trans("AllProjects"); -else $titleall=$langs->trans("AllAllowedProjects").'

    '; +$titleall = $langs->trans("AllAllowedProjects"); +if (!empty($user->rights->projet->all->lire) && !$socid) $titleall = $langs->trans("AllProjects"); +else $titleall = $langs->trans("AllAllowedProjects").'

    '; -$morehtml=''; -$morehtml.=''; -$morehtml.=''; -$morehtml.=''; +$morehtml = ''; +$morehtml .= ''; +$morehtml .= ''; +$morehtml .= ''; print_barre_liste($title, 0, $_SERVER["PHP_SELF"], '', '', '', '', 0, -1, 'project', 0, $morehtml); //print load_fiche_titre($title, '', 'project'); @@ -91,7 +91,7 @@ print_barre_liste($title, 0, $_SERVER["PHP_SELF"], '', '', '', '', 0, -1, 'proje if ($mine) print $langs->trans("MyTasksDesc").'

    '; else { - if ($user->rights->projet->all->lire && ! $socid) print $langs->trans("TasksDesc").'

    '; + if ($user->rights->projet->all->lire && !$socid) print $langs->trans("TasksDesc").'

    '; else print $langs->trans("TasksPublicDesc").'

    '; } @@ -99,12 +99,12 @@ else 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 project - if (! empty($conf->projet->enabled) && $user->rights->projet->lire) + if (!empty($conf->projet->enabled) && $user->rights->projet->lire) { - $listofsearchfields['search_task']=array('text'=>'Task'); + $listofsearchfields['search_task'] = array('text'=>'Task'); } if (count($listofsearchfields)) @@ -113,8 +113,8 @@ if (! empty($conf->global->MAIN_SEARCH_FORM_ON_HOME_AREAS)) // This is usele print ''; print '
    '; print ''; - $i=0; - foreach($listofsearchfields as $key => $value) + $i = 0; + foreach ($listofsearchfields as $key => $value) { if ($i == 0) print ''; print ''; @@ -133,37 +133,37 @@ if (! empty($conf->global->MAIN_SEARCH_FORM_ON_HOME_AREAS)) // This is usele /* Affichage de la liste des projets d'aujourd'hui */ print '
    '; -print '
    '.$langs->trans("Search").'
    '; +print '
    '; print ''; print ''; print ''; print "\n"; $sql = "SELECT p.rowid, p.ref, p.title, p.public, SUM(tt.task_duration) as nb"; -$sql.= " FROM ".MAIN_DB_PREFIX."projet as p"; -$sql.= ", ".MAIN_DB_PREFIX."projet_task as t"; -$sql.= ", ".MAIN_DB_PREFIX."projet_task_time as tt"; -$sql.= " WHERE t.fk_projet = p.rowid"; -$sql.= " AND p.entity = ".$conf->entity; -$sql.= " AND tt.fk_task = t.rowid"; -$sql.= " AND tt.fk_user = ".$user->id; -$sql.= " AND task_date BETWEEN '".$db->idate(dol_mktime(0, 0, 0, $month, $day, $year))."' AND '".$db->idate(dol_mktime(23, 59, 59, $month, $day, $year))."'"; -$sql.= " AND p.rowid in (".$projectsListId.")"; -$sql.= " GROUP BY p.rowid, p.ref, p.title, p.public"; +$sql .= " FROM ".MAIN_DB_PREFIX."projet as p"; +$sql .= ", ".MAIN_DB_PREFIX."projet_task as t"; +$sql .= ", ".MAIN_DB_PREFIX."projet_task_time as tt"; +$sql .= " WHERE t.fk_projet = p.rowid"; +$sql .= " AND p.entity = ".$conf->entity; +$sql .= " AND tt.fk_task = t.rowid"; +$sql .= " AND tt.fk_user = ".$user->id; +$sql .= " AND task_date BETWEEN '".$db->idate(dol_mktime(0, 0, 0, $month, $day, $year))."' AND '".$db->idate(dol_mktime(23, 59, 59, $month, $day, $year))."'"; +$sql .= " AND p.rowid in (".$projectsListId.")"; +$sql .= " GROUP BY p.rowid, p.ref, p.title, p.public"; $resql = $db->query($sql); -if ( $resql ) +if ($resql) { - $total=0; + $total = 0; while ($row = $db->fetch_object($resql)) { print ''; print ''; print ''; @@ -190,37 +190,37 @@ print '
    '; /* Affichage de la liste des projets d'hier */ print '
    '; -print '
    '.$langs->trans('ActivityOnProjectToday').''.$langs->trans("Time").'
    '; - $projectstatic->id=$row->rowid; - $projectstatic->ref=$row->ref; - $projectstatic->title=$row->title; - $projectstatic->public=$row->public; + $projectstatic->id = $row->rowid; + $projectstatic->ref = $row->ref; + $projectstatic->title = $row->title; + $projectstatic->public = $row->public; print $projectstatic->getNomUrl(1, '', 1); print ''.convertSecondToTime($row->nb, 'allhourmin').'
    '; +print '
    '; print ''; print ''; print ''; print "\n"; $sql = "SELECT p.rowid, p.ref, p.title, p.public, SUM(tt.task_duration) as nb"; -$sql.= " FROM ".MAIN_DB_PREFIX."projet as p"; -$sql.= ", ".MAIN_DB_PREFIX."projet_task as t"; -$sql.= ", ".MAIN_DB_PREFIX."projet_task_time as tt"; -$sql.= " WHERE t.fk_projet = p.rowid"; -$sql.= " AND p.entity = ".$conf->entity; -$sql.= " AND tt.fk_task = t.rowid"; -$sql.= " AND tt.fk_user = ".$user->id; -$sql.= " AND task_date BETWEEN '".$db->idate(dol_time_plus_duree(dol_mktime(0, 0, 0, $month, $day, $year), -1, 'd'))."' AND '".$db->idate(dol_time_plus_duree(dol_mktime(23, 59, 59, $month, $day, $year), -1, 'd'))."'"; -$sql.= " AND p.rowid in (".$projectsListId.")"; -$sql.= " GROUP BY p.rowid, p.ref, p.title, p.public"; +$sql .= " FROM ".MAIN_DB_PREFIX."projet as p"; +$sql .= ", ".MAIN_DB_PREFIX."projet_task as t"; +$sql .= ", ".MAIN_DB_PREFIX."projet_task_time as tt"; +$sql .= " WHERE t.fk_projet = p.rowid"; +$sql .= " AND p.entity = ".$conf->entity; +$sql .= " AND tt.fk_task = t.rowid"; +$sql .= " AND tt.fk_user = ".$user->id; +$sql .= " AND task_date BETWEEN '".$db->idate(dol_time_plus_duree(dol_mktime(0, 0, 0, $month, $day, $year), -1, 'd'))."' AND '".$db->idate(dol_time_plus_duree(dol_mktime(23, 59, 59, $month, $day, $year), -1, 'd'))."'"; +$sql .= " AND p.rowid in (".$projectsListId.")"; +$sql .= " GROUP BY p.rowid, p.ref, p.title, p.public"; $resql = $db->query($sql); -if ( $resql ) +if ($resql) { - $total=0; + $total = 0; while ($row = $db->fetch_object($resql)) { print ''; print ''; print ''; @@ -250,7 +250,7 @@ if ($db->type != 'pgsql') // Affichage de la liste des projets de la semaine print '
    '; - print '
    '.$langs->trans('ActivityOnProjectYesterday').''.$langs->trans("Time").'
    '; - $projectstatic->id=$row->rowid; - $projectstatic->ref=$row->ref; - $projectstatic->title=$row->title; - $projectstatic->public=$row->public; + $projectstatic->id = $row->rowid; + $projectstatic->ref = $row->ref; + $projectstatic->title = $row->title; + $projectstatic->public = $row->public; print $projectstatic->getNomUrl(1, '', 1); print ''.convertSecondToTime($row->nb, 'allhourmin').'
    '; + print '
    '; print ''; print ''; print ''; @@ -304,37 +304,37 @@ if ($db->type != 'pgsql') */ /* Affichage de la liste des projets du mois */ -if (! empty($conf->global->PROJECT_TASK_TIME_MONTH)) +if (!empty($conf->global->PROJECT_TASK_TIME_MONTH)) { print '
    '; - print '
    '.$langs->trans("ActivityOnProjectThisWeek").''.$langs->trans("Time").'
    '; + print '
    '; print ''; print ''; print ''; print "\n"; $sql = "SELECT p.rowid, p.ref, p.title, p.public, SUM(tt.task_duration) as nb"; - $sql.= " FROM ".MAIN_DB_PREFIX."projet as p"; - $sql.= ", ".MAIN_DB_PREFIX."projet_task as t"; - $sql.= ", ".MAIN_DB_PREFIX."projet_task_time as tt"; - $sql.= " WHERE t.fk_projet = p.rowid"; - $sql.= " AND p.entity = ".$conf->entity; - $sql.= " AND tt.fk_task = t.rowid"; - $sql.= " AND tt.fk_user = ".$user->id; - $sql.= " AND task_date BETWEEN '".$db->idate(dol_get_first_day($year, $month))."' AND '".$db->idate(dol_get_last_day($year, $month))."'"; - $sql.= " AND p.rowid in (".$projectsListId.")"; - $sql.= " GROUP BY p.rowid, p.ref, p.title, p.public"; + $sql .= " FROM ".MAIN_DB_PREFIX."projet as p"; + $sql .= ", ".MAIN_DB_PREFIX."projet_task as t"; + $sql .= ", ".MAIN_DB_PREFIX."projet_task_time as tt"; + $sql .= " WHERE t.fk_projet = p.rowid"; + $sql .= " AND p.entity = ".$conf->entity; + $sql .= " AND tt.fk_task = t.rowid"; + $sql .= " AND tt.fk_user = ".$user->id; + $sql .= " AND task_date BETWEEN '".$db->idate(dol_get_first_day($year, $month))."' AND '".$db->idate(dol_get_last_day($year, $month))."'"; + $sql .= " AND p.rowid in (".$projectsListId.")"; + $sql .= " GROUP BY p.rowid, p.ref, p.title, p.public"; $resql = $db->query($sql); - if ( $resql ) + if ($resql) { while ($row = $db->fetch_object($resql)) { print ''; print ''; print ''; @@ -355,38 +355,38 @@ if (! empty($conf->global->PROJECT_TASK_TIME_MONTH)) } /* Affichage de la liste des projets de l'annee */ -if (! empty($conf->global->PROJECT_TASK_TIME_YEAR)) +if (!empty($conf->global->PROJECT_TASK_TIME_YEAR)) { print '
    '; - print '
    '.$langs->trans("ActivityOnProjectThisMonth").': '.dol_print_date($now, "%B %Y").''.$langs->trans("Time").'
    '; - $projectstatic->id=$row->rowid; - $projectstatic->ref=$row->ref; - $projectstatic->title=$row->title; + $projectstatic->id = $row->rowid; + $projectstatic->ref = $row->ref; + $projectstatic->title = $row->title; print $projectstatic->getNomUrl(1, '', 1); print ''.convertSecondToTime($row->nb, 'allhourmin').'
    '; + print '
    '; print ''; print ''; print ''; print "\n"; $sql = "SELECT p.rowid, p.ref, p.title, p.public, SUM(tt.task_duration) as nb"; - $sql.= " FROM ".MAIN_DB_PREFIX."projet as p"; - $sql.= ", ".MAIN_DB_PREFIX."projet_task as t"; - $sql.= ", ".MAIN_DB_PREFIX."projet_task_time as tt"; - $sql.= " WHERE t.fk_projet = p.rowid"; - $sql.= " AND p.entity = ".$conf->entity; - $sql.= " AND tt.fk_task = t.rowid"; - $sql.= " AND tt.fk_user = ".$user->id; - $sql.= " AND YEAR(task_date) = '".strftime("%Y", $now)."'"; - $sql.= " AND p.rowid in (".$projectsListId.")"; - $sql.= " GROUP BY p.rowid, p.ref, p.title, p.public"; + $sql .= " FROM ".MAIN_DB_PREFIX."projet as p"; + $sql .= ", ".MAIN_DB_PREFIX."projet_task as t"; + $sql .= ", ".MAIN_DB_PREFIX."projet_task_time as tt"; + $sql .= " WHERE t.fk_projet = p.rowid"; + $sql .= " AND p.entity = ".$conf->entity; + $sql .= " AND tt.fk_task = t.rowid"; + $sql .= " AND tt.fk_user = ".$user->id; + $sql .= " AND YEAR(task_date) = '".strftime("%Y", $now)."'"; + $sql .= " AND p.rowid in (".$projectsListId.")"; + $sql .= " GROUP BY p.rowid, p.ref, p.title, p.public"; $resql = $db->query($sql); - if ( $resql ) + if ($resql) { while ($row = $db->fetch_object($resql)) { print ''; print ''; print ''; @@ -406,72 +406,72 @@ if (! empty($conf->global->PROJECT_TASK_TIME_YEAR)) print ''; } -if (empty($conf->global->PROJECT_HIDE_TASKS) && ! empty($conf->global->PROJECT_SHOW_TASK_LIST_ON_PROJECT_AREA)) +if (empty($conf->global->PROJECT_HIDE_TASKS) && !empty($conf->global->PROJECT_SHOW_TASK_LIST_ON_PROJECT_AREA)) { // Get id of types of contacts for projects (This list never contains a lot of elements) - $listofprojectcontacttype=array(); + $listofprojectcontacttype = array(); $sql = "SELECT ctc.rowid, ctc.code FROM ".MAIN_DB_PREFIX."c_type_contact as ctc"; - $sql.= " WHERE ctc.element = '" . $projectstatic->element . "'"; - $sql.= " AND ctc.source = 'internal'"; + $sql .= " WHERE ctc.element = '".$projectstatic->element."'"; + $sql .= " AND ctc.source = 'internal'"; $resql = $db->query($sql); if ($resql) { - while($obj = $db->fetch_object($resql)) + while ($obj = $db->fetch_object($resql)) { - $listofprojectcontacttype[$obj->rowid]=$obj->code; + $listofprojectcontacttype[$obj->rowid] = $obj->code; } } else dol_print_error($db); - if (count($listofprojectcontacttype) == 0) $listofprojectcontacttype[0]='0'; // To avoid sql syntax error if not found + if (count($listofprojectcontacttype) == 0) $listofprojectcontacttype[0] = '0'; // To avoid sql syntax error if not found // Get id of types of contacts for tasks (This list never contains a lot of elements) - $listoftaskcontacttype=array(); + $listoftaskcontacttype = array(); $sql = "SELECT ctc.rowid, ctc.code FROM ".MAIN_DB_PREFIX."c_type_contact as ctc"; - $sql.= " WHERE ctc.element = '" . $taskstatic->element . "'"; - $sql.= " AND ctc.source = 'internal'"; + $sql .= " WHERE ctc.element = '".$taskstatic->element."'"; + $sql .= " AND ctc.source = 'internal'"; $resql = $db->query($sql); if ($resql) { - while($obj = $db->fetch_object($resql)) + while ($obj = $db->fetch_object($resql)) { - $listoftaskcontacttype[$obj->rowid]=$obj->code; + $listoftaskcontacttype[$obj->rowid] = $obj->code; } } else dol_print_error($db); - if (count($listoftaskcontacttype) == 0) $listoftaskcontacttype[0]='0'; // To avoid sql syntax error if not found + if (count($listoftaskcontacttype) == 0) $listoftaskcontacttype[0] = '0'; // To avoid sql syntax error if not found // Tasks for all resources of all opened projects and time spent for each task/resource // This list can be very long, so we don't show it by default on task area. We prefer to use the list page. // Add constant PROJECT_SHOW_TASK_LIST_ON_PROJECT_AREA to show this list - $max = (empty($conf->global->PROJECT_LIMIT_TASK_PROJECT_AREA)?1000:$conf->global->PROJECT_LIMIT_TASK_PROJECT_AREA); + $max = (empty($conf->global->PROJECT_LIMIT_TASK_PROJECT_AREA) ? 1000 : $conf->global->PROJECT_LIMIT_TASK_PROJECT_AREA); $sql = "SELECT p.ref, p.title, p.rowid as projectid, p.fk_statut as status, p.fk_opp_status as opp_status, p.public, p.dateo as projdateo, p.datee as projdatee,"; - $sql.= " t.label, t.rowid as taskid, t.planned_workload, t.duration_effective, t.progress, t.dateo, t.datee, SUM(tasktime.task_duration) as timespent"; - $sql.= " FROM ".MAIN_DB_PREFIX."projet as p"; - $sql.= " LEFT JOIN ".MAIN_DB_PREFIX."societe as s on p.fk_soc = s.rowid"; - $sql.= " LEFT JOIN ".MAIN_DB_PREFIX."projet_task as t on t.fk_projet = p.rowid"; - $sql.= " LEFT JOIN ".MAIN_DB_PREFIX."projet_task_time as tasktime on tasktime.fk_task = t.rowid"; - $sql.= " LEFT JOIN ".MAIN_DB_PREFIX."user as u on tasktime.fk_user = u.rowid"; + $sql .= " t.label, t.rowid as taskid, t.planned_workload, t.duration_effective, t.progress, t.dateo, t.datee, SUM(tasktime.task_duration) as timespent"; + $sql .= " FROM ".MAIN_DB_PREFIX."projet as p"; + $sql .= " LEFT JOIN ".MAIN_DB_PREFIX."societe as s on p.fk_soc = s.rowid"; + $sql .= " LEFT JOIN ".MAIN_DB_PREFIX."projet_task as t on t.fk_projet = p.rowid"; + $sql .= " LEFT JOIN ".MAIN_DB_PREFIX."projet_task_time as tasktime on tasktime.fk_task = t.rowid"; + $sql .= " LEFT JOIN ".MAIN_DB_PREFIX."user as u on tasktime.fk_user = u.rowid"; if ($mine) { - $sql.= ", " . MAIN_DB_PREFIX . "element_contact as ect"; + $sql .= ", ".MAIN_DB_PREFIX."element_contact as ect"; } - $sql.= " WHERE p.entity IN (".getEntity('project').")"; - if ($mine || empty($user->rights->projet->all->lire)) $sql.= " AND p.rowid IN (".$projectsListId.")"; // project i have permission on + $sql .= " WHERE p.entity IN (".getEntity('project').")"; + if ($mine || empty($user->rights->projet->all->lire)) $sql .= " AND p.rowid IN (".$projectsListId.")"; // project i have permission on if ($mine) // this may duplicate record if we are contact twice { - $sql.= " AND ect.fk_c_type_contact IN (".join(',', array_keys($listoftaskcontacttype)).") AND ect.element_id = t.rowid AND ect.fk_socpeople = ".$user->id; + $sql .= " AND ect.fk_c_type_contact IN (".join(',', array_keys($listoftaskcontacttype)).") AND ect.element_id = t.rowid AND ect.fk_socpeople = ".$user->id; } - if ($socid) $sql.= " AND (p.fk_soc IS NULL OR p.fk_soc = 0 OR p.fk_soc = ".$socid.")"; - $sql.= " AND p.fk_statut=1"; - $sql.= " GROUP BY p.ref, p.title, p.rowid, p.fk_statut, p.fk_opp_status, p.public, t.label, t.rowid, t.planned_workload, t.duration_effective, t.progress, t.dateo, t.datee"; - $sql.= " ORDER BY t.dateo desc, t.rowid desc, t.datee"; - $sql.= $db->plimit($max+1); // We want more to know if we have more than limit + if ($socid) $sql .= " AND (p.fk_soc IS NULL OR p.fk_soc = 0 OR p.fk_soc = ".$socid.")"; + $sql .= " AND p.fk_statut=1"; + $sql .= " GROUP BY p.ref, p.title, p.rowid, p.fk_statut, p.fk_opp_status, p.public, t.label, t.rowid, t.planned_workload, t.duration_effective, t.progress, t.dateo, t.datee"; + $sql .= " ORDER BY t.dateo desc, t.rowid desc, t.datee"; + $sql .= $db->plimit($max + 1); // We want more to know if we have more than limit dol_syslog('projet:index.php: affectationpercent', LOG_DEBUG); $resql = $db->query($sql); - if ( $resql ) + if ($resql) { $num = $db->num_rows($resql); $i = 0; @@ -479,11 +479,11 @@ if (empty($conf->global->PROJECT_HIDE_TASKS) && ! empty($conf->global->PROJECT_S //print load_fiche_titre($langs->trans("TasksOnOpenedProject"),'','').'
    '; print '
    '; - print '
    '.$langs->trans("ActivityOnProjectThisYear").': '.strftime("%Y", $now).''.$langs->trans("Time").'
    '; - $projectstatic->id=$row->rowid; - $projectstatic->ref=$row->ref; - $projectstatic->title=$row->title; - $projectstatic->public=$row->public; + $projectstatic->id = $row->rowid; + $projectstatic->ref = $row->ref; + $projectstatic->title = $row->title; + $projectstatic->public = $row->public; print $projectstatic->getNomUrl(1, '', 1); print ''.convertSecondToTime($row->nb, 'allhourmin').'
    '; + print '
    '; print ''; //print ''; print ''; - if (! empty($conf->global->PROJECT_USE_OPPORTUNITIES)) print ''; + if (!empty($conf->global->PROJECT_USE_OPPORTUNITIES)) print ''; print ''; print ''; print ''; @@ -511,11 +511,11 @@ if (empty($conf->global->PROJECT_HIDE_TASKS) && ! empty($conf->global->PROJECT_S $taskstatic->dateo = $db->jdate($obj->dateo); $taskstatic->datee = $db->jdate($obj->datee); - $username=''; + $username = ''; if ($obj->userid && $userstatic->id != $obj->userid) // We have a user and it is not last loaded user { - $result=$userstatic->fetch($obj->userid); - if (! $result) $userstatic->id=0; + $result = $userstatic->fetch($obj->userid); + if (!$result) $userstatic->id = 0; } if ($userstatic->id) $username = $userstatic->getNomUrl(0, 0); @@ -524,7 +524,7 @@ if (empty($conf->global->PROJECT_HIDE_TASKS) && ! empty($conf->global->PROJECT_S print ''; - if (! empty($conf->global->PROJECT_USE_OPPORTUNITIES)) + if (!empty($conf->global->PROJECT_USE_OPPORTUNITIES)) { print ''; } print ''; print ''; print ''; print "\n"; @@ -572,8 +572,8 @@ if (empty($conf->global->PROJECT_HIDE_TASKS) && ! empty($conf->global->PROJECT_S if ($num > $max) { - $colspan=6; - if (! empty($conf->global->PROJECT_USE_OPPORTUNITIES)) $colspan++; + $colspan = 6; + if (!empty($conf->global->PROJECT_USE_OPPORTUNITIES)) $colspan++; print ''; } diff --git a/htdocs/projet/activity/perday.php b/htdocs/projet/activity/perday.php index 77dcaa641d2..fffab036d2d 100644 --- a/htdocs/projet/activity/perday.php +++ b/htdocs/projet/activity/perday.php @@ -115,9 +115,9 @@ $extrafields = new ExtraFields($db); $extrafields->fetch_name_optionals_label($object->table_element); // Definition of fields for list -$arrayfields=array(); -$arrayfields['t.planned_workload']=array('label'=>'PlannedWorkload', 'checked'=>1, 'enabled'=>1, 'position'=>0); -$arrayfields['t.progress']=array('label'=>'ProgressDeclared', 'checked'=>1, 'enabled'=>1, 'position'=>0); +$arrayfields = array(); +$arrayfields['t.planned_workload'] = array('label'=>'PlannedWorkload', 'checked'=>1, 'enabled'=>1, 'position'=>0); +$arrayfields['t.progress'] = array('label'=>'ProgressDeclared', 'checked'=>1, 'enabled'=>1, 'position'=>0); /*$arrayfields=array( // Project 'p.opp_amount'=>array('label'=>$langs->trans("OpportunityAmountShort"), 'checked'=>0, 'enabled'=>($conf->global->PROJECT_USE_OPPORTUNITIES?1:0), 'position'=>103), @@ -130,17 +130,17 @@ $arrayfields['t.progress']=array('label'=>'ProgressDeclared', 'checked'=>1, 'ena // 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) + foreach ($extrafields->attributes[$object->table_element]['label'] as $key => $val) { - if (! empty($extrafields->attributes[$object->table_element]['list'][$key])) - $arrayfields["efpt.".$key]=array('label'=>$extrafields->attributes[$object->table_element]['label'][$key], 'checked'=>(($extrafields->attributes[$object->table_element]['list'][$key]<0)?0:1), 'position'=>$extrafields->attributes[$object->table_element]['pos'][$key], 'enabled'=>(abs($extrafields->attributes[$object->table_element]['list'][$key])!=3 && $extrafields->attributes[$object->table_element]['perms'][$key])); + if (!empty($extrafields->attributes[$object->table_element]['list'][$key])) + $arrayfields["efpt.".$key] = array('label'=>$extrafields->attributes[$object->table_element]['label'][$key], 'checked'=>(($extrafields->attributes[$object->table_element]['list'][$key] < 0) ? 0 : 1), 'position'=>$extrafields->attributes[$object->table_element]['pos'][$key], 'enabled'=>(abs($extrafields->attributes[$object->table_element]['list'][$key]) != 3 && $extrafields->attributes[$object->table_element]['perms'][$key])); } } $arrayfields = dol_sort_array($arrayfields, 'position'); -$search_array_options_project=$extrafields->getOptionalsFromPost($project->table_element, '', 'search_'); -$search_array_options_task=$extrafields->getOptionalsFromPost($object->table_element, '', 'search_task_'); +$search_array_options_project = $extrafields->getOptionalsFromPost($project->table_element, '', 'search_'); +$search_array_options_task = $extrafields->getOptionalsFromPost($object->table_element, '', 'search_task_'); /* @@ -151,7 +151,7 @@ $search_array_options_task=$extrafields->getOptionalsFromPost($object->table_ele 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 { $action = ''; - $search_categ=''; + $search_categ = ''; $search_usertoprocessid = $user->id; $search_task_ref = ''; $search_task_label = ''; @@ -163,7 +163,7 @@ if (GETPOST('button_removefilter_x', 'alpha') || GETPOST('button_removefilter.x' $search_array_options_task = array(); // We redefine $usertoprocess - $usertoprocess=$user; + $usertoprocess = $user; } if (GETPOST("button_search_x", 'alpha') || GETPOST("button_search.x", 'alpha') || GETPOST("button_search", 'alpha')) { @@ -196,35 +196,35 @@ if ($action == 'addtime' && $user->rights->projet->lire && GETPOST('assigntask') setEventMessages($langs->transnoentitiesnoconv("ErrorFieldRequired", $langs->transnoentitiesnoconv("Task")), '', 'errors'); $error++; } - if (! GETPOST('type')) + if (!GETPOST('type')) { setEventMessages($langs->transnoentitiesnoconv("ErrorFieldRequired", $langs->transnoentitiesnoconv("Type")), '', 'errors'); $error++; } - if (! $error) + if (!$error) { - $idfortaskuser=$usertoprocess->id; + $idfortaskuser = $usertoprocess->id; $result = $object->add_contact($idfortaskuser, GETPOST("type"), 'internal'); if ($result >= 0 || $result == -2) // Contact add ok or already contact of task { // Test if we are already contact of the project (should be rare but sometimes we can add as task contact without being contact of project, like when admin user has been removed from contact of project) - $sql='SELECT ec.rowid FROM '.MAIN_DB_PREFIX.'element_contact as ec, '.MAIN_DB_PREFIX.'c_type_contact as tc WHERE tc.rowid = ec.fk_c_type_contact'; - $sql.=' AND ec.fk_socpeople = '.$idfortaskuser." AND ec.element_id = '.$object->fk_project.' AND tc.element = 'project' AND source = 'internal'"; - $resql=$db->query($sql); + $sql = 'SELECT ec.rowid FROM '.MAIN_DB_PREFIX.'element_contact as ec, '.MAIN_DB_PREFIX.'c_type_contact as tc WHERE tc.rowid = ec.fk_c_type_contact'; + $sql .= ' AND ec.fk_socpeople = '.$idfortaskuser." AND ec.element_id = '.$object->fk_project.' AND tc.element = 'project' AND source = 'internal'"; + $resql = $db->query($sql); if ($resql) { - $obj=$db->fetch_object($resql); - if (! $obj) // User is not already linked to project, so we will create link to first type + $obj = $db->fetch_object($resql); + if (!$obj) // User is not already linked to project, so we will create link to first type { $project = new Project($db); $project->fetch($object->fk_project); // Get type - $listofprojcontact=$project->liste_type_contact('internal'); + $listofprojcontact = $project->liste_type_contact('internal'); if (count($listofprojcontact)) { - $typeforprojectcontact=reset(array_keys($listofprojcontact)); + $typeforprojectcontact = reset(array_keys($listofprojcontact)); $result = $project->add_contact($idfortaskuser, $typeforprojectcontact, 'internal'); } } @@ -250,22 +250,22 @@ if ($action == 'addtime' && $user->rights->projet->lire && GETPOST('assigntask') } } - if (! $error) + if (!$error) { setEventMessages("TaskAssignedToEnterTime", null); - $taskid=0; + $taskid = 0; } - $action=''; + $action = ''; } if ($action == 'addtime' && $user->rights->projet->lire && GETPOST('formfilteraction') != 'listafterchangingselectedfields') { - $timespent_duration=array(); + $timespent_duration = array(); if (is_array($_POST)) { - foreach($_POST as $key => $time) + foreach ($_POST as $key => $time) { if (intval($time) > 0) { @@ -276,10 +276,10 @@ if ($action == 'addtime' && $user->rights->projet->lire && GETPOST('formfilterac if ($id > 0) { // We store HOURS in seconds - if($matches[2]=='hour') $timespent_duration[$id] += $time*60*60; + if ($matches[2] == 'hour') $timespent_duration[$id] += $time * 60 * 60; // We store MINUTES in seconds - if($matches[2]=='min') $timespent_duration[$id] += $time*60; + if ($matches[2] == 'min') $timespent_duration[$id] += $time * 60; } } } @@ -288,11 +288,11 @@ if ($action == 'addtime' && $user->rights->projet->lire && GETPOST('formfilterac if (count($timespent_duration) > 0) { - foreach($timespent_duration as $key => $val) + foreach ($timespent_duration as $key => $val) { $object->fetch($key); - if (GETPOSTISSET($taskid . 'progress')) $object->progress = GETPOST($taskid . 'progress', 'int'); + if (GETPOSTISSET($taskid.'progress')) $object->progress = GETPOST($taskid.'progress', 'int'); else unset($object->progress); $object->timespent_duration = $val; @@ -311,7 +311,7 @@ if ($action == 'addtime' && $user->rights->projet->lire && GETPOST('formfilterac if ($object->timespent_date > 0) { - $result=$object->addTimeSpent($user); + $result = $object->addTimeSpent($user); } else { @@ -328,12 +328,12 @@ if ($action == 'addtime' && $user->rights->projet->lire && GETPOST('formfilterac } } - if (! $error) + if (!$error) { setEventMessages($langs->trans("RecordSaved"), null, 'mesgs'); // Redirect to avoid submit twice on back - header('Location: '.$_SERVER["PHP_SELF"].'?'.($projectid?'id='.$projectid:'').($search_usertoprocessid?'&search_usertoprocessid='.$search_usertoprocessid:'').($mode?'&mode='.$mode:'').'&year='.$yearofday.'&month='.$monthofday.'&day='.$dayofday); + header('Location: '.$_SERVER["PHP_SELF"].'?'.($projectid ? 'id='.$projectid : '').($search_usertoprocessid ? '&search_usertoprocessid='.$search_usertoprocessid : '').($mode ? '&mode='.$mode : '').'&year='.$yearofday.'&month='.$monthofday.'&day='.$dayofday); exit; } } @@ -349,11 +349,11 @@ if ($action == 'addtime' && $user->rights->projet->lire && GETPOST('formfilterac * View */ -$form=new Form($db); +$form = new Form($db); $formother = new FormOther($db); -$formcompany=new FormCompany($db); -$formproject=new FormProjets($db); -$projectstatic=new Project($db); +$formcompany = new FormCompany($db); +$formproject = new FormProjets($db); +$projectstatic = new Project($db); $project = new Project($db); $taskstatic = new Task($db); $thirdpartystatic = new Societe($db); @@ -369,9 +369,9 @@ $next_year = $next['year']; $next_month = $next['mon']; $next_day = $next['mday']; -$title=$langs->trans("TimeSpent"); +$title = $langs->trans("TimeSpent"); -$projectsListId = $projectstatic->getProjectsAuthorizedForUser($usertoprocess, (empty($usertoprocess->id)?2:0), 1); // Return all project i have permission on. I want my tasks and some of my task may be on a public projet that is not my project +$projectsListId = $projectstatic->getProjectsAuthorizedForUser($usertoprocess, (empty($usertoprocess->id) ? 2 : 0), 1); // Return all project i have permission on. I want my tasks and some of my task may be on a public projet that is not my project if ($id) { @@ -379,14 +379,14 @@ if ($id) $project->fetch_thirdparty(); } -$onlyopenedproject=1; // or -1 -$morewherefilter=''; +$onlyopenedproject = 1; // or -1 +$morewherefilter = ''; -if ($search_project_ref) $morewherefilter.=natural_search(array("p.ref", "p.title"), $search_project_ref); -if ($search_task_ref) $morewherefilter.=natural_search("t.ref", $search_task_ref); -if ($search_task_label) $morewherefilter.=natural_search(array("t.ref", "t.label"), $search_task_label); -if ($search_thirdparty) $morewherefilter.=natural_search("s.nom", $search_thirdparty); -if ($search_declared_progress) $morewherefilter.=natural_search("t.progress", $search_declared_progress, 1); +if ($search_project_ref) $morewherefilter .= natural_search(array("p.ref", "p.title"), $search_project_ref); +if ($search_task_ref) $morewherefilter .= natural_search("t.ref", $search_task_ref); +if ($search_task_label) $morewherefilter .= natural_search(array("t.ref", "t.label"), $search_task_label); +if ($search_thirdparty) $morewherefilter .= natural_search("s.nom", $search_thirdparty); +if ($search_declared_progress) $morewherefilter .= natural_search("t.progress", $search_declared_progress, 1); $sql = &$morewherefilter; @@ -397,18 +397,18 @@ $extrafieldsobjectkey='projet'; include DOL_DOCUMENT_ROOT.'/core/tpl/extrafields_list_search_sql.tpl.php'; */ $search_array_options = $search_array_options_task; -$extrafieldsobjectprefix='efpt.'; -$search_options_pattern='search_task_options_'; -$extrafieldsobjectkey='projet_task'; +$extrafieldsobjectprefix = 'efpt.'; +$search_options_pattern = 'search_task_options_'; +$extrafieldsobjectkey = 'projet_task'; include DOL_DOCUMENT_ROOT.'/core/tpl/extrafields_list_search_sql.tpl.php'; -$tasksarray=$taskstatic->getTasksArray(0, 0, ($project->id?$project->id:0), $socid, 0, $search_project_ref, $onlyopenedproject, $morewherefilter, ($search_usertoprocessid?$search_usertoprocessid:0), 0, $extrafields); // We want to see all task of opened project i am allowed to see and that match filter, not only my tasks. Later only mine will be editable later. +$tasksarray = $taskstatic->getTasksArray(0, 0, ($project->id ? $project->id : 0), $socid, 0, $search_project_ref, $onlyopenedproject, $morewherefilter, ($search_usertoprocessid ? $search_usertoprocessid : 0), 0, $extrafields); // We want to see all task of opened project i am allowed to see and that match filter, not only my tasks. Later only mine will be editable later. if ($morewherefilter) // Get all task without any filter, so we can show total of time spent for not visible tasks { - $tasksarraywithoutfilter=$taskstatic->getTasksArray(0, 0, ($project->id?$project->id:0), $socid, 0, '', $onlyopenedproject, '', ($search_usertoprocessid?$search_usertoprocessid:0)); // We want to see all task of opened project i am allowed to see and that match filter, not only my tasks. Later only mine will be editable later. + $tasksarraywithoutfilter = $taskstatic->getTasksArray(0, 0, ($project->id ? $project->id : 0), $socid, 0, '', $onlyopenedproject, '', ($search_usertoprocessid ? $search_usertoprocessid : 0)); // We want to see all task of opened project i am allowed to see and that match filter, not only my tasks. Later only mine will be editable later. } -$projectsrole=$taskstatic->getUserRolesForProjectsOrTasks($usertoprocess, 0, ($project->id?$project->id:0), 0, $onlyopenedproject); -$tasksrole=$taskstatic->getUserRolesForProjectsOrTasks(0, $usertoprocess, ($project->id?$project->id:0), 0, $onlyopenedproject); +$projectsrole = $taskstatic->getUserRolesForProjectsOrTasks($usertoprocess, 0, ($project->id ? $project->id : 0), 0, $onlyopenedproject); +$tasksrole = $taskstatic->getUserRolesForProjectsOrTasks(0, $usertoprocess, ($project->id ? $project->id : 0), 0, $onlyopenedproject); //var_dump($usertoprocess); //var_dump($projectsrole); //var_dump($taskrole); @@ -417,33 +417,33 @@ llxHeader("", $title, "", '', '', '', array('/core/js/timesheet.js')); //print_barre_liste($title, $page, $_SERVER["PHP_SELF"], "", $sortfield, $sortorder, "", $num, '', 'project'); -$param=''; -$param.=($mode?'&mode='.urlencode($mode):''); -$param.=($search_project_ref?'&search_project_ref='.urlencode($search_project_ref):''); -$param.=($search_usertoprocessid?'&search_usertoprocessid='.urlencode($search_usertoprocessid):''); -$param.=($search_thirdparty?'&search_thirdparty='.urlencode($search_thirdparty):''); -$param.=($search_task_ref?'&search_task_ref='.urlencode($search_task_ref):''); -$param.=($search_task_label?'&search_task_label='.urlencode($search_task_label):''); +$param = ''; +$param .= ($mode ? '&mode='.urlencode($mode) : ''); +$param .= ($search_project_ref ? '&search_project_ref='.urlencode($search_project_ref) : ''); +$param .= ($search_usertoprocessid ? '&search_usertoprocessid='.urlencode($search_usertoprocessid) : ''); +$param .= ($search_thirdparty ? '&search_thirdparty='.urlencode($search_thirdparty) : ''); +$param .= ($search_task_ref ? '&search_task_ref='.urlencode($search_task_ref) : ''); +$param .= ($search_task_label ? '&search_task_label='.urlencode($search_task_label) : ''); /*$search_array_options=$search_array_options_project; $search_options_pattern='search_options_'; include DOL_DOCUMENT_ROOT.'/core/tpl/extrafields_list_search_param.tpl.php'; */ -$search_array_options=$search_array_options_task; -$search_options_pattern='search_task_options_'; +$search_array_options = $search_array_options_task; +$search_options_pattern = 'search_task_options_'; include DOL_DOCUMENT_ROOT.'/core/tpl/extrafields_list_search_param.tpl.php'; // Show navigation bar -$nav =''.img_previous($langs->trans("Previous"))."\n"; -$nav.=dol_print_date(dol_mktime(0, 0, 0, $month, $day, $year), "%A").' '; -$nav.=" ".dol_print_date(dol_mktime(0, 0, 0, $month, $day, $year), "day")." \n"; -$nav.=''.img_next($langs->trans("Next"))."\n"; -$nav.="   (".$langs->trans("Today").")"; -$nav.='
    '.$form->selectDate(-1, '', 0, 0, 2, "addtime", 1, 0).' '; -$nav.=' '; +$nav = ''.img_previous($langs->trans("Previous"))."\n"; +$nav .= dol_print_date(dol_mktime(0, 0, 0, $month, $day, $year), "%A").' '; +$nav .= " ".dol_print_date(dol_mktime(0, 0, 0, $month, $day, $year), "day")." \n"; +$nav .= ''.img_next($langs->trans("Next"))."\n"; +$nav .= "   (".$langs->trans("Today").")"; +$nav .= '
    '.$form->selectDate(-1, '', 0, 0, 2, "addtime", 1, 0).' '; +$nav .= ' '; -$picto='calendarweek'; +$picto = 'calendarweek'; print 'id > 0 ? '?id='.$project->id : '').'">'; print ''; @@ -456,18 +456,18 @@ print ''; print ''; print ''; -$head=project_timesheet_prepare_head($mode, $usertoprocess); +$head = project_timesheet_prepare_head($mode, $usertoprocess); dol_fiche_head($head, 'inputperday', $langs->trans('TimeSpent'), -1, 'task'); // Show description of content print '
    '; -if ($mine || ($usertoprocess->id == $user->id)) print $langs->trans("MyTasksDesc").'.'.($onlyopenedproject?' '.$langs->trans("OnlyOpenedProject"):'').'
    '; +if ($mine || ($usertoprocess->id == $user->id)) print $langs->trans("MyTasksDesc").'.'.($onlyopenedproject ? ' '.$langs->trans("OnlyOpenedProject") : '').'
    '; else { if (empty($usertoprocess->id) || $usertoprocess->id < 0) { - if ($user->rights->projet->all->lire && ! $socid) print $langs->trans("ProjectsDesc").'.'.($onlyopenedproject?' '.$langs->trans("OnlyOpenedProject"):'').'
    '; - else print $langs->trans("ProjectsPublicTaskDesc").'.'.($onlyopenedproject?' '.$langs->trans("OnlyOpenedProject"):'').'
    '; + if ($user->rights->projet->all->lire && !$socid) print $langs->trans("ProjectsDesc").'.'.($onlyopenedproject ? ' '.$langs->trans("OnlyOpenedProject") : '').'
    '; + else print $langs->trans("ProjectsPublicTaskDesc").'.'.($onlyopenedproject ? ' '.$langs->trans("OnlyOpenedProject") : '').'
    '; } } if ($mine || ($usertoprocess->id == $user->id)) @@ -482,13 +482,13 @@ print '
    '; dol_fiche_end(); -print '
    '.$nav.'
    '; // We move this before the assign to components so, the default submit button is not the assign to. +print '
    '.$nav.'
    '; // We move this before the assign to components so, the default submit button is not the assign to. print '
    '; $titleassigntask = $langs->transnoentities("AssignTaskToMe"); if ($usertoprocess->id != $user->id) $titleassigntask = $langs->transnoentities("AssignTaskToUser", $usertoprocess->getFullName($langs)); print '
    '; -$formproject->selectTasks($socid?$socid:-1, $taskid, 'taskid', 32, 0, 1, 1, 0, 0, '', '', 'all', $usertoprocess); +$formproject->selectTasks($socid ? $socid : -1, $taskid, 'taskid', 32, 0, 1, 1, 0, 0, '', '', 'all', $usertoprocess); print '
    '; print ' '; print $formcompany->selectTypeContact($object, '', 'type', 'internal', 'rowid', 0, 'maxwidth150onsmartphone'); @@ -498,7 +498,7 @@ print '
    '; print '
    '; -$moreforfilter=''; +$moreforfilter = ''; // Filter on categories /*if (! empty($conf->categorie->enabled)) @@ -511,66 +511,66 @@ $moreforfilter=''; }*/ // If the user can view user other than himself -$moreforfilter.='
    '; -$moreforfilter.='
    '.$langs->trans('User'). '
    '; -$includeonly='hierarchyme'; -if (empty($user->rights->user->user->lire)) $includeonly=array($user->id); -$moreforfilter.=$form->select_dolusers($search_usertoprocessid?$search_usertoprocessid:$usertoprocess->id, 'search_usertoprocessid', $user->rights->user->user->lire?0:0, null, 0, $includeonly, null, 0, 0, 0, '', 0, '', 'maxwidth200 marginleftonly'); -$moreforfilter.='
    '; +$moreforfilter .= '
    '; +$moreforfilter .= '
    '.$langs->trans('User').'
    '; +$includeonly = 'hierarchyme'; +if (empty($user->rights->user->user->lire)) $includeonly = array($user->id); +$moreforfilter .= $form->select_dolusers($search_usertoprocessid ? $search_usertoprocessid : $usertoprocess->id, 'search_usertoprocessid', $user->rights->user->user->lire ? 0 : 0, null, 0, $includeonly, null, 0, 0, 0, '', 0, '', 'maxwidth200 marginleftonly'); +$moreforfilter .= '
    '; if (empty($conf->global->PROJECT_TIMESHEET_DISABLEBREAK_ON_PROJECT)) { - $moreforfilter.='
    '; - $moreforfilter.='
    '.$langs->trans('Project'). '
    '; - $moreforfilter.=''; - $moreforfilter.='
    '; + $moreforfilter .= '
    '; + $moreforfilter .= '
    '.$langs->trans('Project').'
    '; + $moreforfilter .= ''; + $moreforfilter .= '
    '; - $moreforfilter.='
    '; - $moreforfilter.='
    '.$langs->trans('ThirdParty'). '
    '; - $moreforfilter.=''; - $moreforfilter.='
    '; + $moreforfilter .= '
    '; + $moreforfilter .= '
    '.$langs->trans('ThirdParty').'
    '; + $moreforfilter .= ''; + $moreforfilter .= '
    '; } -if (! empty($moreforfilter)) +if (!empty($moreforfilter)) { print '
    '; print $moreforfilter; - $parameters=array(); - $reshook=$hookmanager->executeHooks('printFieldPreListTitle', $parameters); // Note that $action and $object may have been modified by hook + $parameters = array(); + $reshook = $hookmanager->executeHooks('printFieldPreListTitle', $parameters); // Note that $action and $object may have been modified by hook print $hookmanager->resPrint; print '
    '; } -$varpage=empty($contextpage)?$_SERVER["PHP_SELF"]:$contextpage; -$selectedfields=$form->multiSelectArrayWithCheckbox('selectedfields', $arrayfields, $varpage); // This also change content of $arrayfields +$varpage = empty($contextpage) ? $_SERVER["PHP_SELF"] : $contextpage; +$selectedfields = $form->multiSelectArrayWithCheckbox('selectedfields', $arrayfields, $varpage); // This also change content of $arrayfields // This must be after the $selectedfields -$addcolspan=0; -if (! empty($arrayfields['t.planned_workload']['checked'])) $addcolspan++; -if (! empty($arrayfields['t.progress']['checked'])) $addcolspan++; +$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++; } print '
    '; -print '
    '.$langs->trans('TaskRessourceLinks').''.$langs->trans('OpenedProjects').''.$langs->trans('OpportunityStatus').''.$langs->trans('OpportunityStatus').''.$langs->trans('Task').''.$langs->trans('DateStart').''.$langs->trans('DateEnd').''; print $projectstatic->getNomUrl(1, '', 0, '', '
    '); print '
    '; $code = dol_getIdFromCode($db, $obj->opp_status, 'c_lead_status', 'rowid', 'code'); @@ -532,7 +532,7 @@ if (empty($conf->global->PROJECT_HIDE_TASKS) && ! empty($conf->global->PROJECT_S print ''; - if (! empty($obj->taskid)) + if (!empty($obj->taskid)) { $tasktmp->id = $obj->taskid; $tasktmp->ref = $obj->ref; @@ -552,18 +552,18 @@ if (empty($conf->global->PROJECT_HIDE_TASKS) && ! empty($conf->global->PROJECT_S print convertSecondToTime($obj->timespent, 'allhourmin'); print ''; - if (! empty($obj->taskid)) + if (!empty($obj->taskid)) { if (empty($obj->planned_workload) > 0) { $percentcompletion = $langs->trans("WorkloadNotDefined"); } else { - $percentcompletion = intval($obj->duration_effective*100/$obj->planned_workload).'%'; + $percentcompletion = intval($obj->duration_effective * 100 / $obj->planned_workload).'%'; } } print $percentcompletion; print ''; - print ($obj->taskid>0)?$obj->progress.'%':''; + print ($obj->taskid > 0) ? $obj->progress.'%' : ''; print '
    '.$langs->trans("WarningTooManyDataPleaseUseMoreFilters").'
    '."\n"; +print '
    '."\n"; print ''; -if (! empty($conf->global->PROJECT_TIMESHEET_DISABLEBREAK_ON_PROJECT)) print ''; -if (! empty($conf->global->PROJECT_TIMESHEET_DISABLEBREAK_ON_PROJECT)) print ''; +if (!empty($conf->global->PROJECT_TIMESHEET_DISABLEBREAK_ON_PROJECT)) print ''; +if (!empty($conf->global->PROJECT_TIMESHEET_DISABLEBREAK_ON_PROJECT)) print ''; print ''; // TASK fields -$search_options_pattern='search_task_options_'; -$extrafieldsobjectkey='projet_task'; -$extrafieldsobjectprefix='efpt.'; +$search_options_pattern = 'search_task_options_'; +$extrafieldsobjectkey = 'projet_task'; +$extrafieldsobjectprefix = 'efpt.'; include DOL_DOCUMENT_ROOT.'/core/tpl/extrafields_list_search_input.tpl.php'; print ''; -if (! empty($arrayfields['t.planned_workload']['checked'])) +if (!empty($arrayfields['t.planned_workload']['checked'])) { print ''; } -if (! empty($arrayfields['t.progress']['checked'])) +if (!empty($arrayfields['t.progress']['checked'])) { print ''; } @@ -580,24 +580,24 @@ print ''; print ''; // Action column print ''; print "\n"; print ''; -if (! empty($conf->global->PROJECT_TIMESHEET_DISABLEBREAK_ON_PROJECT)) print ''; -if (! empty($conf->global->PROJECT_TIMESHEET_DISABLEBREAK_ON_PROJECT)) print ''; +if (!empty($conf->global->PROJECT_TIMESHEET_DISABLEBREAK_ON_PROJECT)) print ''; +if (!empty($conf->global->PROJECT_TIMESHEET_DISABLEBREAK_ON_PROJECT)) print ''; print ''; // TASK fields -$extrafieldsobjectkey='projet_task'; -$extrafieldsobjectprefix='efpt.'; +$extrafieldsobjectkey = 'projet_task'; +$extrafieldsobjectprefix = 'efpt.'; include DOL_DOCUMENT_ROOT.'/core/tpl/extrafields_list_search_title.tpl.php'; -if (! empty($arrayfields['t.planned_workload']['checked'])) +if (!empty($arrayfields['t.planned_workload']['checked'])) { print ''; } -if (! empty($arrayfields['t.progress']['checked'])) +if (!empty($arrayfields['t.progress']['checked'])) { print ''; } @@ -605,17 +605,17 @@ if (! empty($arrayfields['t.progress']['checked'])) if ($usertoprocess->id == $user->id) print ''; else print '';*/ print ''; -print ''; +print ''; print ''; +print ''; print ''; //print ''; print_liste_field_titre($selectedfields, $_SERVER["PHP_SELF"], "", '', '', '', $sortfield, $sortorder, 'center maxwidthsearch '); print "\n"; -$colspan=4+(empty($conf->global->PROJECT_TIMESHEET_DISABLEBREAK_ON_PROJECT)?0:2); +$colspan = 4 + (empty($conf->global->PROJECT_TIMESHEET_DISABLEBREAK_ON_PROJECT) ? 0 : 2); if ($conf->use_javascript_ajax) { print ''; - print ''; print ''; - $tmparray = dol_getdate($daytoparse, true); // detail of current day + $tmparray = dol_getdate($daytoparse, true); // detail of current day $idw = $tmparray['wday']; - $cssweekend=''; + $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. { - $cssweekend='weekend'; + $cssweekend = 'weekend'; } - $cssonholiday=''; - if (! $isavailable[$daytoparse]['morning'] && ! $isavailable[$daytoparse]['afternoon']) $cssonholiday.='onholidayallday '; - elseif (! $isavailable[$daytoparse]['morning']) $cssonholiday.='onholidaymorning '; - elseif (! $isavailable[$daytoparse]['afternoon']) $cssonholiday.='onholidayafternoon '; + $cssonholiday = ''; + if (!$isavailable[$daytoparse]['morning'] && !$isavailable[$daytoparse]['afternoon']) $cssonholiday .= 'onholidayallday '; + elseif (!$isavailable[$daytoparse]['morning']) $cssonholiday .= 'onholidaymorning '; + elseif (!$isavailable[$daytoparse]['afternoon']) $cssonholiday .= 'onholidayafternoon '; - print ''; + print ''; print ''; print ''; @@ -690,32 +690,32 @@ if (count($tasksarray) > 0) //var_dump($tasksarraywithoutfilter); // contains all tasks (if there is a filter, not defined if no filter) //var_dump($tasksrole); - $j=0; - $level=0; + $j = 0; + $level = 0; $totalforvisibletasks = projectLinesPerDay($j, 0, $usertoprocess, $tasksarray, $level, $projectsrole, $tasksrole, $mine, $restrictviewformytask, $daytoparse, $isavailable, 0, $arrayfields, $extrafields); //var_dump($totalforvisibletasks); // Show total for all other tasks // Calculate total for all tasks - $listofdistinctprojectid=array(); // List of all distinct projects + $listofdistinctprojectid = array(); // List of all distinct projects if (is_array($tasksarraywithoutfilter) && count($tasksarraywithoutfilter)) { - foreach($tasksarraywithoutfilter as $tmptask) + foreach ($tasksarraywithoutfilter as $tmptask) { - $listofdistinctprojectid[$tmptask->fk_project]=$tmptask->fk_project; + $listofdistinctprojectid[$tmptask->fk_project] = $tmptask->fk_project; } } //var_dump($listofdistinctprojectid); - $totalforeachday=array(); - foreach($listofdistinctprojectid as $tmpprojectid) + $totalforeachday = array(); + foreach ($listofdistinctprojectid as $tmpprojectid) { - $projectstatic->id=$tmpprojectid; - $projectstatic->loadTimeSpent($daytoparse, 0, $usertoprocess->id); // Load time spent from table projet_task_time for the project into this->weekWorkLoad and this->weekWorkLoadPerTask for all days of a week + $projectstatic->id = $tmpprojectid; + $projectstatic->loadTimeSpent($daytoparse, 0, $usertoprocess->id); // Load time spent from table projet_task_time for the project into this->weekWorkLoad and this->weekWorkLoadPerTask for all days of a week for ($idw = 0; $idw < 7; $idw++) { - $tmpday=dol_time_plus_duree($daytoparse, $idw, 'd'); - $totalforeachday[$tmpday]+=$projectstatic->weekWorkLoad[$tmpday]; + $tmpday = dol_time_plus_duree($daytoparse, $idw, 'd'); + $totalforeachday[$tmpday] += $projectstatic->weekWorkLoad[$tmpday]; } } //var_dump($totalforeachday); @@ -724,10 +724,10 @@ if (count($tasksarray) > 0) $isdiff = 0; if (count($totalforeachday)) { - $timeonothertasks=($totalforeachday[$daytoparse] - $totalforvisibletasks[$daytoparse]); + $timeonothertasks = ($totalforeachday[$daytoparse] - $totalforvisibletasks[$daytoparse]); if ($timeonothertasks) { - $isdiff=1; + $isdiff = 1; } } @@ -735,12 +735,12 @@ if (count($tasksarray) > 0) if ($isdiff) { print ''; - print ''; print ''; print ''; print ''; - $tmparray = dol_getdate($daytoparse, true); // detail of current day + $tmparray = dol_getdate($daytoparse, true); // detail of current day $idw = $tmparray['wday']; - $cssweekend=''; + $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. { - $cssweekend='weekend'; + $cssweekend = 'weekend'; } - $cssonholiday=''; - if (! $isavailable[$daytoparse]['morning'] && ! $isavailable[$daytoparse]['afternoon']) $cssonholiday.='onholidayallday '; - elseif (! $isavailable[$daytoparse]['morning']) $cssonholiday.='onholidaymorning '; - elseif (! $isavailable[$daytoparse]['afternoon']) $cssonholiday.='onholidayafternoon '; + $cssonholiday = ''; + if (!$isavailable[$daytoparse]['morning'] && !$isavailable[$daytoparse]['afternoon']) $cssonholiday .= 'onholidayallday '; + elseif (!$isavailable[$daytoparse]['morning']) $cssonholiday .= 'onholidaymorning '; + elseif (!$isavailable[$daytoparse]['afternoon']) $cssonholiday .= 'onholidayafternoon '; - print ''; + print ''; print ' @@ -794,12 +794,12 @@ print ''; print ''."\n"; print '
    '; -print ''; +print ''; print '
    '; print ''; -$modeinput='hours'; +$modeinput = 'hours'; if ($conf->use_javascript_ajax) { diff --git a/htdocs/projet/activity/perweek.php b/htdocs/projet/activity/perweek.php index 8af733394bf..535f8e17522 100644 --- a/htdocs/projet/activity/perweek.php +++ b/htdocs/projet/activity/perweek.php @@ -97,26 +97,26 @@ $next_month = $next['month']; $next_day = $next['day']; // Define firstdaytoshow and lastdaytoshow (warning: lastdaytoshow is last second to show + 1) -$firstdaytoshow=dol_mktime(0, 0, 0, $first_month, $first_day, $first_year); -$lastdaytoshow=dol_time_plus_duree($firstdaytoshow, 7, 'd'); +$firstdaytoshow = dol_mktime(0, 0, 0, $first_month, $first_day, $first_year); +$lastdaytoshow = dol_time_plus_duree($firstdaytoshow, 7, 'd'); if (empty($search_usertoprocessid) || $search_usertoprocessid == $user->id) { - $usertoprocess=$user; - $search_usertoprocessid=$usertoprocess->id; + $usertoprocess = $user; + $search_usertoprocessid = $usertoprocess->id; } elseif ($search_usertoprocessid > 0) { - $usertoprocess=new User($db); + $usertoprocess = new User($db); $usertoprocess->fetch($search_usertoprocessid); - $search_usertoprocessid=$usertoprocess->id; + $search_usertoprocessid = $usertoprocess->id; } else { - $usertoprocess=new User($db); + $usertoprocess = new User($db); } -$object=new Task($db); +$object = new Task($db); // Extra fields $extrafields = new ExtraFields($db); @@ -125,7 +125,7 @@ $extrafields = new ExtraFields($db); //$extrafields->fetch_name_optionals_label('projet'); $extrafields->fetch_name_optionals_label('projet_task'); -$arrayfields=array(); +$arrayfields = array(); /*$arrayfields=array( // Project 'p.opp_amount'=>array('label'=>$langs->trans("OpportunityAmountShort"), 'checked'=>0, 'enabled'=>($conf->global->PROJECT_USE_OPPORTUNITIES?1:0), 'position'=>103), @@ -134,8 +134,8 @@ $arrayfields=array(); 'p.budget_amount'=>array('label'=>$langs->trans("Budget"), 'checked'=>0, 'position'=>110), 'p.usage_bill_time'=>array('label'=>$langs->trans("BillTimeShort"), 'checked'=>0, 'position'=>115), );*/ -$arrayfields['t.planned_workload']=array('label'=>'PlannedWorkload', 'checked'=>1, 'enabled'=>1, 'position'=>0); -$arrayfields['t.progress']=array('label'=>'ProgressDeclared', 'checked'=>1, 'enabled'=>1, 'position'=>0); +$arrayfields['t.planned_workload'] = array('label'=>'PlannedWorkload', 'checked'=>1, 'enabled'=>1, 'position'=>0); +$arrayfields['t.progress'] = array('label'=>'ProgressDeclared', 'checked'=>1, 'enabled'=>1, 'position'=>0); /*foreach($object->fields as $key => $val) { // If $val['visible']==0, then we never show the field @@ -145,17 +145,17 @@ $arrayfields['t.progress']=array('label'=>'ProgressDeclared', 'checked'=>1, 'ena // Extra fields if (is_array($extrafields->attributes['projet_task']['label']) && count($extrafields->attributes['projet_task']['label']) > 0) { - foreach($extrafields->attributes['projet_task']['label'] as $key => $val) + foreach ($extrafields->attributes['projet_task']['label'] as $key => $val) { - if (! empty($extrafields->attributes['projet_task']['list'][$key])) - $arrayfields["efpt.".$key]=array('label'=>$extrafields->attributes['projet_task']['label'][$key], 'checked'=>(($extrafields->attributes['projet_task']['list'][$key]<0)?0:1), 'position'=>$extrafields->attributes['projet_task']['pos'][$key], 'enabled'=>(abs($extrafields->attributes['projet_task']['list'][$key])!=3 && $extrafields->attributes['projet_task']['perms'][$key])); + if (!empty($extrafields->attributes['projet_task']['list'][$key])) + $arrayfields["efpt.".$key] = array('label'=>$extrafields->attributes['projet_task']['label'][$key], 'checked'=>(($extrafields->attributes['projet_task']['list'][$key] < 0) ? 0 : 1), 'position'=>$extrafields->attributes['projet_task']['pos'][$key], 'enabled'=>(abs($extrafields->attributes['projet_task']['list'][$key]) != 3 && $extrafields->attributes['projet_task']['perms'][$key])); } } $arrayfields = dol_sort_array($arrayfields, 'position'); -$search_array_options=array(); -$search_array_options_project=$extrafields->getOptionalsFromPost('projet', '', 'search_'); -$search_array_options_task=$extrafields->getOptionalsFromPost('projet_task', '', 'search_task_'); +$search_array_options = array(); +$search_array_options_project = $extrafields->getOptionalsFromPost('projet', '', 'search_'); +$search_array_options_task = $extrafields->getOptionalsFromPost('projet_task', '', 'search_task_'); @@ -167,7 +167,7 @@ $search_array_options_task=$extrafields->getOptionalsFromPost('projet_task', '', 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 { $action = ''; - $search_categ=''; + $search_categ = ''; $search_usertoprocessid = $user->id; $search_task_ref = ''; $search_task_label = ''; @@ -179,7 +179,7 @@ if (GETPOST('button_removefilter_x', 'alpha') || GETPOST('button_removefilter.x' $search_array_options_task = array(); // We redefine $usertoprocess - $usertoprocess=$user; + $usertoprocess = $user; } if (GETPOST("button_search_x", 'alpha') || GETPOST("button_search.x", 'alpha') || GETPOST("button_search", 'alpha')) { @@ -209,36 +209,36 @@ if ($action == 'addtime' && $user->rights->projet->lire && GETPOST('assigntask') setEventMessages($langs->transnoentitiesnoconv("ErrorFieldRequired", $langs->transnoentitiesnoconv("Task")), '', 'errors'); $error++; } - if (! GETPOST('type')) + if (!GETPOST('type')) { setEventMessages($langs->transnoentitiesnoconv("ErrorFieldRequired", $langs->transnoentitiesnoconv("Type")), '', 'errors'); $error++; } - if (! $error) + if (!$error) { - $idfortaskuser=$usertoprocess->id; + $idfortaskuser = $usertoprocess->id; $result = $object->add_contact($idfortaskuser, GETPOST("type"), 'internal'); if ($result >= 0 || $result == -2) // Contact add ok or already contact of task { // Test if we are already contact of the project (should be rare but sometimes we can add as task contact without being contact of project, like when admin user has been removed from contact of project) - $sql='SELECT ec.rowid FROM '.MAIN_DB_PREFIX.'element_contact as ec, '.MAIN_DB_PREFIX.'c_type_contact as tc WHERE tc.rowid = ec.fk_c_type_contact'; - $sql.=' AND ec.fk_socpeople = '.$idfortaskuser." AND ec.element_id = '.$object->fk_project.' AND tc.element = 'project' AND source = 'internal'"; - $resql=$db->query($sql); + $sql = 'SELECT ec.rowid FROM '.MAIN_DB_PREFIX.'element_contact as ec, '.MAIN_DB_PREFIX.'c_type_contact as tc WHERE tc.rowid = ec.fk_c_type_contact'; + $sql .= ' AND ec.fk_socpeople = '.$idfortaskuser." AND ec.element_id = '.$object->fk_project.' AND tc.element = 'project' AND source = 'internal'"; + $resql = $db->query($sql); if ($resql) { - $obj=$db->fetch_object($resql); - if (! $obj) // User is not already linked to project, so we will create link to first type + $obj = $db->fetch_object($resql); + if (!$obj) // User is not already linked to project, so we will create link to first type { $project = new Project($db); $project->fetch($object->fk_project); // Get type - $listofprojcontact=$project->liste_type_contact('internal'); + $listofprojcontact = $project->liste_type_contact('internal'); if (count($listofprojcontact)) { - $typeforprojectcontact=reset(array_keys($listofprojcontact)); + $typeforprojectcontact = reset(array_keys($listofprojcontact)); $result = $project->add_contact($idfortaskuser, $typeforprojectcontact, 'internal'); } } @@ -264,43 +264,43 @@ if ($action == 'addtime' && $user->rights->projet->lire && GETPOST('assigntask') } } - if (! $error) + if (!$error) { setEventMessages("TaskAssignedToEnterTime", null); - $taskid=0; + $taskid = 0; } - $action=''; + $action = ''; } if ($action == 'addtime' && $user->rights->projet->lire && GETPOST('formfilteraction') != 'listafterchangingselectedfields') { - $timetoadd=$_POST['task']; + $timetoadd = $_POST['task']; if (empty($timetoadd)) { setEventMessages($langs->trans("ErrorTimeSpentIsEmpty"), null, 'errors'); } else { - foreach($timetoadd as $taskid => $value) // Loop on each task + foreach ($timetoadd as $taskid => $value) // Loop on each task { - $updateoftaskdone=0; - foreach($value as $key => $val) // Loop on each day + $updateoftaskdone = 0; + foreach ($value as $key => $val) // Loop on each day { - $amountoadd=$timetoadd[$taskid][$key]; - if (! empty($amountoadd)) + $amountoadd = $timetoadd[$taskid][$key]; + if (!empty($amountoadd)) { - $tmpduration=explode(':', $amountoadd); - $newduration=0; - if (! empty($tmpduration[0])) $newduration+=($tmpduration[0] * 3600); - if (! empty($tmpduration[1])) $newduration+=($tmpduration[1] * 60); - if (! empty($tmpduration[2])) $newduration+=($tmpduration[2]); + $tmpduration = explode(':', $amountoadd); + $newduration = 0; + if (!empty($tmpduration[0])) $newduration += ($tmpduration[0] * 3600); + if (!empty($tmpduration[1])) $newduration += ($tmpduration[1] * 60); + if (!empty($tmpduration[2])) $newduration += ($tmpduration[2]); if ($newduration > 0) { $object->fetch($taskid); - if (GETPOSTISSET($taskid . 'progress')) $object->progress = GETPOST($taskid . 'progress', 'int'); + if (GETPOSTISSET($taskid.'progress')) $object->progress = GETPOST($taskid.'progress', 'int'); else unset($object->progress); $object->timespent_duration = $newduration; @@ -308,7 +308,7 @@ if ($action == 'addtime' && $user->rights->projet->lire && GETPOST('formfilterac $object->timespent_date = dol_time_plus_duree($firstdaytoshow, $key, 'd'); $object->timespent_datehour = $object->timespent_date; - $result=$object->addTimeSpent($user); + $result = $object->addTimeSpent($user); if ($result < 0) { setEventMessages($object->error, $object->errors, 'errors'); @@ -321,14 +321,14 @@ if ($action == 'addtime' && $user->rights->projet->lire && GETPOST('formfilterac } } - if (! $updateoftaskdone) // Check to update progress if no update were done on task. + if (!$updateoftaskdone) // Check to update progress if no update were done on task. { $object->fetch($taskid); //var_dump($object->progress);var_dump(GETPOST($taskid . 'progress', 'int')); exit; - if ($object->progress != GETPOST($taskid . 'progress', 'int')) + if ($object->progress != GETPOST($taskid.'progress', 'int')) { - $object->progress = GETPOST($taskid . 'progress', 'int'); - $result=$object->update($user); + $object->progress = GETPOST($taskid.'progress', 'int'); + $result = $object->update($user); if ($result < 0) { setEventMessages($object->error, $object->errors, 'errors'); @@ -339,29 +339,29 @@ if ($action == 'addtime' && $user->rights->projet->lire && GETPOST('formfilterac } } - if (! $error) + if (!$error) { setEventMessages($langs->trans("RecordSaved"), null, 'mesgs'); - $param=''; - $param.=($mode?'&mode='.urlencode($mode):''); - $param.=($projectid?'id='.urlencode($projectid):''); - $param.=($search_usertoprocessid?'&search_usertoprocessid='.urlencode($search_usertoprocessid):''); - $param.=($day?'&day='.urlencode($day):'').($month?'&month='.urlencode($month):'').($year?'&year='.urlencode($year):''); - $param.=($search_project_ref?'&search_project_ref='.urlencode($search_project_ref):''); - $param.=($search_usertoprocessid > 0?'&search_usertoprocessid='.urlencode($search_usertoprocessid):''); - $param.=($search_thirdparty?'&search_thirdparty='.urlencode($search_thirdparty):''); - $param.=($search_declared_progress?'&search_declared_progress='.urlencode($search_declared_progress):''); - $param.=($search_task_ref?'&search_task_ref='.urlencode($search_task_ref):''); - $param.=($search_task_label?'&search_task_label='.urlencode($search_task_label):''); + $param = ''; + $param .= ($mode ? '&mode='.urlencode($mode) : ''); + $param .= ($projectid ? 'id='.urlencode($projectid) : ''); + $param .= ($search_usertoprocessid ? '&search_usertoprocessid='.urlencode($search_usertoprocessid) : ''); + $param .= ($day ? '&day='.urlencode($day) : '').($month ? '&month='.urlencode($month) : '').($year ? '&year='.urlencode($year) : ''); + $param .= ($search_project_ref ? '&search_project_ref='.urlencode($search_project_ref) : ''); + $param .= ($search_usertoprocessid > 0 ? '&search_usertoprocessid='.urlencode($search_usertoprocessid) : ''); + $param .= ($search_thirdparty ? '&search_thirdparty='.urlencode($search_thirdparty) : ''); + $param .= ($search_declared_progress ? '&search_declared_progress='.urlencode($search_declared_progress) : ''); + $param .= ($search_task_ref ? '&search_task_ref='.urlencode($search_task_ref) : ''); + $param .= ($search_task_label ? '&search_task_label='.urlencode($search_task_label) : ''); /*$search_array_options=$search_array_options_project; $search_options_pattern='search_options_'; include DOL_DOCUMENT_ROOT.'/core/tpl/extrafields_list_search_param.tpl.php'; */ - $search_array_options=$search_array_options_task; - $search_options_pattern='search_task_options_'; + $search_array_options = $search_array_options_task; + $search_options_pattern = 'search_task_options_'; include DOL_DOCUMENT_ROOT.'/core/tpl/extrafields_list_search_param.tpl.php'; // Redirect to avoid submit twice on back @@ -377,19 +377,19 @@ if ($action == 'addtime' && $user->rights->projet->lire && GETPOST('formfilterac * View */ -$form=new Form($db); -$formother=new FormOther($db); -$formcompany=new FormCompany($db); -$formproject=new FormProjets($db); -$projectstatic=new Project($db); +$form = new Form($db); +$formother = new FormOther($db); +$formcompany = new FormCompany($db); +$formproject = new FormProjets($db); +$projectstatic = new Project($db); $project = new Project($db); $taskstatic = new Task($db); $thirdpartystatic = new Societe($db); $holiday = new Holiday($db); -$title=$langs->trans("TimeSpent"); +$title = $langs->trans("TimeSpent"); -$projectsListId = $projectstatic->getProjectsAuthorizedForUser($usertoprocess, (empty($usertoprocess->id)?2:0), 1); // Return all project i have permission on (assigned to me+public). I want my tasks and some of my task may be on a public projet that is not my project +$projectsListId = $projectstatic->getProjectsAuthorizedForUser($usertoprocess, (empty($usertoprocess->id) ? 2 : 0), 1); // Return all project i have permission on (assigned to me+public). I want my tasks and some of my task may be on a public projet that is not my project //var_dump($projectsListId); if ($id) { @@ -397,14 +397,14 @@ if ($id) $project->fetch_thirdparty(); } -$onlyopenedproject=1; // or -1 -$morewherefilter=''; +$onlyopenedproject = 1; // or -1 +$morewherefilter = ''; -if ($search_project_ref) $morewherefilter.=natural_search(array("p.ref", "p.title"), $search_project_ref); -if ($search_task_ref) $morewherefilter.=natural_search("t.ref", $search_task_ref); -if ($search_task_label) $morewherefilter.=natural_search(array("t.ref", "t.label"), $search_task_label); -if ($search_thirdparty) $morewherefilter.=natural_search("s.nom", $search_thirdparty); -if ($search_declared_progress) $morewherefilter.=natural_search("t.progress", $search_declared_progress, 1); +if ($search_project_ref) $morewherefilter .= natural_search(array("p.ref", "p.title"), $search_project_ref); +if ($search_task_ref) $morewherefilter .= natural_search("t.ref", $search_task_ref); +if ($search_task_label) $morewherefilter .= natural_search(array("t.ref", "t.label"), $search_task_label); +if ($search_thirdparty) $morewherefilter .= natural_search("s.nom", $search_thirdparty); +if ($search_declared_progress) $morewherefilter .= natural_search("t.progress", $search_declared_progress, 1); $sql = &$morewherefilter; @@ -415,18 +415,18 @@ $extrafieldsobjectkey='projet'; include DOL_DOCUMENT_ROOT.'/core/tpl/extrafields_list_search_sql.tpl.php'; */ $search_array_options = $search_array_options_task; -$extrafieldsobjectprefix='efpt.'; -$search_options_pattern='search_task_options_'; -$extrafieldsobjectkey='projet_task'; +$extrafieldsobjectprefix = 'efpt.'; +$search_options_pattern = 'search_task_options_'; +$extrafieldsobjectkey = 'projet_task'; include DOL_DOCUMENT_ROOT.'/core/tpl/extrafields_list_search_sql.tpl.php'; -$tasksarray=$taskstatic->getTasksArray(0, 0, ($project->id?$project->id:0), $socid, 0, $search_project_ref, $onlyopenedproject, $morewherefilter, ($search_usertoprocessid?$search_usertoprocessid:0), 0, $extrafields); // We want to see all tasks of open project i am allowed to see and that match filter, not only my tasks. Later only mine will be editable later. +$tasksarray = $taskstatic->getTasksArray(0, 0, ($project->id ? $project->id : 0), $socid, 0, $search_project_ref, $onlyopenedproject, $morewherefilter, ($search_usertoprocessid ? $search_usertoprocessid : 0), 0, $extrafields); // We want to see all tasks of open project i am allowed to see and that match filter, not only my tasks. Later only mine will be editable later. if ($morewherefilter) // Get all task without any filter, so we can show total of time spent for not visible tasks { - $tasksarraywithoutfilter=$taskstatic->getTasksArray(0, 0, ($project->id?$project->id:0), $socid, 0, '', $onlyopenedproject, '', ($search_usertoprocessid?$search_usertoprocessid:0)); // We want to see all tasks of open project i am allowed to see and that match filter, not only my tasks. Later only mine will be editable later. + $tasksarraywithoutfilter = $taskstatic->getTasksArray(0, 0, ($project->id ? $project->id : 0), $socid, 0, '', $onlyopenedproject, '', ($search_usertoprocessid ? $search_usertoprocessid : 0)); // We want to see all tasks of open project i am allowed to see and that match filter, not only my tasks. Later only mine will be editable later. } -$projectsrole=$taskstatic->getUserRolesForProjectsOrTasks($usertoprocess, 0, ($project->id?$project->id:0), 0, $onlyopenedproject); -$tasksrole=$taskstatic->getUserRolesForProjectsOrTasks(0, $usertoprocess, ($project->id?$project->id:0), 0, $onlyopenedproject); +$projectsrole = $taskstatic->getUserRolesForProjectsOrTasks($usertoprocess, 0, ($project->id ? $project->id : 0), 0, $onlyopenedproject); +$tasksrole = $taskstatic->getUserRolesForProjectsOrTasks(0, $usertoprocess, ($project->id ? $project->id : 0), 0, $onlyopenedproject); //var_dump($tasksarray); //var_dump($projectsrole); //var_dump($taskrole); @@ -436,31 +436,31 @@ llxHeader("", $title, "", '', '', '', array('/core/js/timesheet.js')); //print_barre_liste($title, $page, $_SERVER["PHP_SELF"], "", $sortfield, $sortorder, "", $num, '', 'project'); -$param=''; -$param.=($mode?'&mode='.urlencode($mode):''); -$param.=($search_project_ref?'&search_project_ref='.urlencode($search_project_ref):''); -$param.=($search_usertoprocessid > 0?'&search_usertoprocessid='.urlencode($search_usertoprocessid):''); -$param.=($search_thirdparty?'&search_thirdparty='.urlencode($search_thirdparty):''); -$param.=($search_task_ref?'&search_task_ref='.urlencode($search_task_ref):''); -$param.=($search_task_label?'&search_task_label='.urlencode($search_task_label):''); +$param = ''; +$param .= ($mode ? '&mode='.urlencode($mode) : ''); +$param .= ($search_project_ref ? '&search_project_ref='.urlencode($search_project_ref) : ''); +$param .= ($search_usertoprocessid > 0 ? '&search_usertoprocessid='.urlencode($search_usertoprocessid) : ''); +$param .= ($search_thirdparty ? '&search_thirdparty='.urlencode($search_thirdparty) : ''); +$param .= ($search_task_ref ? '&search_task_ref='.urlencode($search_task_ref) : ''); +$param .= ($search_task_label ? '&search_task_label='.urlencode($search_task_label) : ''); -$search_array_options=$search_array_options_project; -$search_options_pattern='search_options_'; +$search_array_options = $search_array_options_project; +$search_options_pattern = 'search_options_'; include DOL_DOCUMENT_ROOT.'/core/tpl/extrafields_list_search_param.tpl.php'; -$search_array_options=$search_array_options_task; -$search_options_pattern='search_task_options_'; +$search_array_options = $search_array_options_task; +$search_options_pattern = 'search_task_options_'; include DOL_DOCUMENT_ROOT.'/core/tpl/extrafields_list_search_param.tpl.php'; // Show navigation bar -$nav =''.img_previous($langs->trans("Previous"))."\n"; -$nav.=" ".dol_print_date(dol_mktime(0, 0, 0, $first_month, $first_day, $first_year), "%Y").", ".$langs->trans("WeekShort")." ".$week." \n"; -$nav.=''.img_next($langs->trans("Next"))."\n"; -$nav.="   (".$langs->trans("Today").")"; -$nav.='
    '.$form->selectDate(-1, '', 0, 0, 2, "addtime", 1, 0).' '; -$nav.=' '; +$nav = ''.img_previous($langs->trans("Previous"))."\n"; +$nav .= " ".dol_print_date(dol_mktime(0, 0, 0, $first_month, $first_day, $first_year), "%Y").", ".$langs->trans("WeekShort")." ".$week." \n"; +$nav .= ''.img_next($langs->trans("Next"))."\n"; +$nav .= "   (".$langs->trans("Today").")"; +$nav .= '
    '.$form->selectDate(-1, '', 0, 0, 2, "addtime", 1, 0).' '; +$nav .= ' '; -$picto='calendarweek'; +$picto = 'calendarweek'; print ''; print ''; @@ -472,18 +472,18 @@ print ''; print ''; print ''; -$head=project_timesheet_prepare_head($mode, $usertoprocess); +$head = project_timesheet_prepare_head($mode, $usertoprocess); dol_fiche_head($head, 'inputperweek', $langs->trans('TimeSpent'), -1, 'task'); // Show description of content print '
    '; -if ($mine || ($usertoprocess->id == $user->id)) print $langs->trans("MyTasksDesc").'.'.($onlyopenedproject?' '.$langs->trans("OnlyOpenedProject"):'').'
    '; +if ($mine || ($usertoprocess->id == $user->id)) print $langs->trans("MyTasksDesc").'.'.($onlyopenedproject ? ' '.$langs->trans("OnlyOpenedProject") : '').'
    '; else { if (empty($usertoprocess->id) || $usertoprocess->id < 0) { - if ($user->rights->projet->all->lire && ! $socid) print $langs->trans("ProjectsDesc").'.'.($onlyopenedproject?' '.$langs->trans("OnlyOpenedProject"):'').'
    '; - else print $langs->trans("ProjectsPublicTaskDesc").'.'.($onlyopenedproject?' '.$langs->trans("OnlyOpenedProject"):'').'
    '; + if ($user->rights->projet->all->lire && !$socid) print $langs->trans("ProjectsDesc").'.'.($onlyopenedproject ? ' '.$langs->trans("OnlyOpenedProject") : '').'
    '; + else print $langs->trans("ProjectsPublicTaskDesc").'.'.($onlyopenedproject ? ' '.$langs->trans("OnlyOpenedProject") : '').'
    '; } } if ($mine || ($usertoprocess->id == $user->id)) @@ -498,13 +498,13 @@ print '
    '; dol_fiche_end(); -print '
    '.$nav.'
    '; // We move this before the assign to components so, the default submit button is not the assign to. +print '
    '.$nav.'
    '; // We move this before the assign to components so, the default submit button is not the assign to. print '
    '; $titleassigntask = $langs->transnoentities("AssignTaskToMe"); if ($usertoprocess->id != $user->id) $titleassigntask = $langs->transnoentities("AssignTaskToUser", $usertoprocess->getFullName($langs)); print '
    '; -$formproject->selectTasks($socid?$socid:-1, $taskid, 'taskid', 32, 0, 1, 1, 0, 0, '', '', 'all', $usertoprocess); +$formproject->selectTasks($socid ? $socid : -1, $taskid, 'taskid', 32, 0, 1, 1, 0, 0, '', '', 'all', $usertoprocess); print '
    '; print ' '; print $formcompany->selectTypeContact($object, '', 'type', 'internal', 'rowid', 0, 'maxwidth150onsmartphone'); @@ -514,13 +514,13 @@ print '
    '; print '
    '; -$startday=dol_mktime(12, 0, 0, $startdayarray['first_month'], $startdayarray['first_day'], $startdayarray['first_year']); +$startday = dol_mktime(12, 0, 0, $startdayarray['first_month'], $startdayarray['first_day'], $startdayarray['first_year']); // Get if user is available or not for each day -$isavailable=array(); -if (! empty($conf->global->MAIN_DEFAULT_WORKING_DAYS)) +$isavailable = array(); +if (!empty($conf->global->MAIN_DEFAULT_WORKING_DAYS)) { - $tmparray=explode('-', $conf->global->MAIN_DEFAULT_WORKING_DAYS); + $tmparray = explode('-', $conf->global->MAIN_DEFAULT_WORKING_DAYS); if (count($tmparray) >= 2) { $numstartworkingday = $tmparray[0]; @@ -528,9 +528,9 @@ if (! empty($conf->global->MAIN_DEFAULT_WORKING_DAYS)) } } -for ($idw=0; $idw<7; $idw++) +for ($idw = 0; $idw < 7; $idw++) { - $dayinloopfromfirstdaytoshow = dol_time_plus_duree($firstdaytoshow, $idw, 'd'); // $firstdaytoshow is a date with hours = 0 + $dayinloopfromfirstdaytoshow = dol_time_plus_duree($firstdaytoshow, $idw, 'd'); // $firstdaytoshow is a date with hours = 0 $dayinloop = dol_time_plus_duree($startday, $idw, 'd'); // Useless because $dayinloopwithouthours should be same than $dayinloopfromfirstdaytoshow @@ -543,11 +543,11 @@ for ($idw=0; $idw<7; $idw++) $statusofholidaytocheck = '3'; $isavailablefordayanduser = $holiday->verifDateHolidayForTimestamp($usertoprocess->id, $dayinloopfromfirstdaytoshow, $statusofholidaytocheck); - $isavailable[$dayinloopfromfirstdaytoshow]=$isavailablefordayanduser; // in projectLinesPerWeek later, we are using $firstdaytoshow and dol_time_plus_duree to loop on each day + $isavailable[$dayinloopfromfirstdaytoshow] = $isavailablefordayanduser; // in projectLinesPerWeek later, we are using $firstdaytoshow and dol_time_plus_duree to loop on each day } -$moreforfilter=''; +$moreforfilter = ''; // Filter on categories /* @@ -561,96 +561,96 @@ if (! empty($conf->categorie->enabled)) }*/ // If the user can view user other than himself -$moreforfilter.='
    '; -$moreforfilter.='
    '.$langs->trans('User'). '
    '; -$includeonly='hierarchyme'; -if (empty($user->rights->user->user->lire)) $includeonly=array($user->id); -$moreforfilter.=$form->select_dolusers($search_usertoprocessid?$search_usertoprocessid:$usertoprocess->id, 'search_usertoprocessid', $user->rights->user->user->lire?0:0, null, 0, $includeonly, null, 0, 0, 0, '', 0, '', 'maxwidth200'); -$moreforfilter.='
    '; +$moreforfilter .= '
    '; +$moreforfilter .= '
    '.$langs->trans('User').'
    '; +$includeonly = 'hierarchyme'; +if (empty($user->rights->user->user->lire)) $includeonly = array($user->id); +$moreforfilter .= $form->select_dolusers($search_usertoprocessid ? $search_usertoprocessid : $usertoprocess->id, 'search_usertoprocessid', $user->rights->user->user->lire ? 0 : 0, null, 0, $includeonly, null, 0, 0, 0, '', 0, '', 'maxwidth200'); +$moreforfilter .= '
    '; if (empty($conf->global->PROJECT_TIMESHEET_DISABLEBREAK_ON_PROJECT)) { - $moreforfilter.='
    '; - $moreforfilter.='
    '.$langs->trans('Project'). '
    '; - $moreforfilter.=''; - $moreforfilter.='
    '; + $moreforfilter .= '
    '; + $moreforfilter .= '
    '.$langs->trans('Project').'
    '; + $moreforfilter .= ''; + $moreforfilter .= '
    '; - $moreforfilter.='
    '; - $moreforfilter.='
    '.$langs->trans('ThirdParty'). '
    '; - $moreforfilter.=''; - $moreforfilter.='
    '; + $moreforfilter .= '
    '; + $moreforfilter .= '
    '.$langs->trans('ThirdParty').'
    '; + $moreforfilter .= ''; + $moreforfilter .= '
    '; } -if (! empty($moreforfilter)) +if (!empty($moreforfilter)) { print '
    '; print $moreforfilter; - $parameters=array(); - $reshook=$hookmanager->executeHooks('printFieldPreListTitle', $parameters); // Note that $action and $object may have been modified by hook + $parameters = array(); + $reshook = $hookmanager->executeHooks('printFieldPreListTitle', $parameters); // Note that $action and $object may have been modified by hook print $hookmanager->resPrint; print '
    '; } -$varpage=empty($contextpage)?$_SERVER["PHP_SELF"]:$contextpage; +$varpage = empty($contextpage) ? $_SERVER["PHP_SELF"] : $contextpage; -$selectedfields=$form->multiSelectArrayWithCheckbox('selectedfields', $arrayfields, $varpage); // This also change content of $arrayfields +$selectedfields = $form->multiSelectArrayWithCheckbox('selectedfields', $arrayfields, $varpage); // This also change content of $arrayfields // This must be after the $selectedfields -$addcolspan=0; -if (! empty($arrayfields['t.planned_workload']['checked'])) $addcolspan++; -if (! empty($arrayfields['t.progress']['checked'])) $addcolspan++; +$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++; } print '
    '; -print '
    '; -$searchpicto=$form->showFilterAndCheckAddButtons(0); +$searchpicto = $form->showFilterAndCheckAddButtons(0); print $searchpicto; print '
    '.$langs->trans("Project").''.$langs->trans("ThirdParty").''.$langs->trans("Project").''.$langs->trans("ThirdParty").''.$langs->trans("Task").''.$langs->trans("PlannedWorkload").''.$langs->trans("ProgressDeclared").''.$langs->trans("TimeSpentByYou").''.$langs->trans("TimeSpentByUser").''.$langs->trans("TimeSpent").'
    ('.$langs->trans("Everybody").')
    '.$langs->trans("TimeSpent").($usertoprocess->firstname?'
    ('.dol_trunc($usertoprocess->firstname, 10).')':'').'
    '.$langs->trans("TimeSpent").($usertoprocess->firstname ? '
    ('.dol_trunc($usertoprocess->firstname, 10).')' : '').'
    '.$langs->trans("HourStart").''; // By default, we can edit only tasks we are assigned to -$restrictviewformytask=((! isset($conf->global->PROJECT_TIME_SHOW_TASK_NOT_ASSIGNED)) ? 2 : $conf->global->PROJECT_TIME_SHOW_TASK_NOT_ASSIGNED); +$restrictviewformytask = ((!isset($conf->global->PROJECT_TIME_SHOW_TASK_NOT_ASSIGNED)) ? 2 : $conf->global->PROJECT_TIME_SHOW_TASK_NOT_ASSIGNED); // Get if user is available or not for each day -$isavailable=array(); -if (! empty($conf->global->MAIN_DEFAULT_WORKING_DAYS)) +$isavailable = array(); +if (!empty($conf->global->MAIN_DEFAULT_WORKING_DAYS)) { - $tmparray=explode('-', $conf->global->MAIN_DEFAULT_WORKING_DAYS); + $tmparray = explode('-', $conf->global->MAIN_DEFAULT_WORKING_DAYS); if (count($tmparray) >= 2) { $numstartworkingday = $tmparray[0]; @@ -624,59 +624,59 @@ if (! empty($conf->global->MAIN_DEFAULT_WORKING_DAYS)) } $statusofholidaytocheck = '3'; -$isavailablefordayanduser = $holiday->verifDateHolidayForTimestamp($usertoprocess->id, $daytoparse, $statusofholidaytocheck); // $daytoparse is a date with hours = 0 -$isavailable[$daytoparse]=$isavailablefordayanduser; // in projectLinesPerWeek later, we are using $firstdaytoshow and dol_time_plus_duree to loop on each day +$isavailablefordayanduser = $holiday->verifDateHolidayForTimestamp($usertoprocess->id, $daytoparse, $statusofholidaytocheck); // $daytoparse is a date with hours = 0 +$isavailable[$daytoparse] = $isavailablefordayanduser; // in projectLinesPerWeek later, we are using $firstdaytoshow and dol_time_plus_duree to loop on each day -$tmparray = dol_getdate($daytoparse, true); // detail of current day +$tmparray = dol_getdate($daytoparse, true); // detail of current day $idw = $tmparray['wday']; -$cssweekend=''; +$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. { - $cssweekend='weekend'; + $cssweekend = 'weekend'; } -$tmpday=dol_time_plus_duree($firstdaytoshow, $idw, 'd'); +$tmpday = dol_time_plus_duree($firstdaytoshow, $idw, 'd'); -$cssonholiday=''; -if (! $isavailable[$daytoparse]['morning'] && ! $isavailable[$daytoparse]['afternoon']) $cssonholiday.='onholidayallday '; -elseif (! $isavailable[$daytoparse]['morning']) $cssonholiday.='onholidaymorning '; -elseif (! $isavailable[$daytoparse]['afternoon']) $cssonholiday.='onholidayafternoon '; +$cssonholiday = ''; +if (!$isavailable[$daytoparse]['morning'] && !$isavailable[$daytoparse]['afternoon']) $cssonholiday .= 'onholidayallday '; +elseif (!$isavailable[$daytoparse]['morning']) $cssonholiday .= 'onholidaymorning '; +elseif (!$isavailable[$daytoparse]['afternoon']) $cssonholiday .= 'onholidayafternoon '; -print ''.$langs->trans("Duration").''.$langs->trans("Duration").''.$langs->trans("Note").'
    '; + print ''; print $langs->trans("Total"); print ''; //print ' - '.$langs->trans("ExpectedWorkedHours").': '.price($usertoprocess->weeklyhours, 1, $langs, 0, 0).''; print '
     
     
    '; + print ''; print $langs->trans("OtherFilteredTasks"); print ''; - $timeonothertasks=($totalforeachday[$daytoparse] - $totalforvisibletasks[$daytoparse]); + $timeonothertasks = ($totalforeachday[$daytoparse] - $totalforvisibletasks[$daytoparse]); //if ($timeonothertasks) //{ print ''; - print ''; + print ''; print $langs->trans("Total"); print ''; //print ' - '.$langs->trans("ExpectedWorkedHours").': '.price($usertoprocess->weeklyhours, 1, $langs, 0, 0).''; print '
     
     
    '."\n"; +print '
    '."\n"; print ''; -if (! empty($conf->global->PROJECT_TIMESHEET_DISABLEBREAK_ON_PROJECT)) print ''; -if (! empty($conf->global->PROJECT_TIMESHEET_DISABLEBREAK_ON_PROJECT)) print ''; +if (!empty($conf->global->PROJECT_TIMESHEET_DISABLEBREAK_ON_PROJECT)) print ''; +if (!empty($conf->global->PROJECT_TIMESHEET_DISABLEBREAK_ON_PROJECT)) print ''; print ''; // TASK fields -$search_options_pattern='search_task_options_'; -$extrafieldsobjectkey='projet_task'; -$extrafieldsobjectprefix='efpt.'; +$search_options_pattern = 'search_task_options_'; +$extrafieldsobjectkey = 'projet_task'; +$extrafieldsobjectprefix = 'efpt.'; include DOL_DOCUMENT_ROOT.'/core/tpl/extrafields_list_search_input.tpl.php'; print ''; -if (! empty($arrayfields['t.planned_workload']['checked'])) +if (!empty($arrayfields['t.planned_workload']['checked'])) { print ''; } -if (! empty($arrayfields['t.progress']['checked'])) +if (!empty($arrayfields['t.progress']['checked'])) { print ''; } print ''; -for ($idw=0;$idw<7;$idw++) +for ($idw = 0; $idw < 7; $idw++) { print ''; } // Action column print ''; print "\n"; print ''; -if (! empty($conf->global->PROJECT_TIMESHEET_DISABLEBREAK_ON_PROJECT)) print ''; -if (! empty($conf->global->PROJECT_TIMESHEET_DISABLEBREAK_ON_PROJECT)) print ''; +if (!empty($conf->global->PROJECT_TIMESHEET_DISABLEBREAK_ON_PROJECT)) print ''; +if (!empty($conf->global->PROJECT_TIMESHEET_DISABLEBREAK_ON_PROJECT)) print ''; print ''; // TASK fields -$extrafieldsobjectkey='projet_task'; -$extrafieldsobjectprefix='efpt.'; +$extrafieldsobjectkey = 'projet_task'; +$extrafieldsobjectprefix = 'efpt.'; include DOL_DOCUMENT_ROOT.'/core/tpl/extrafields_list_search_title.tpl.php'; -if (! empty($arrayfields['t.planned_workload']['checked'])) +if (!empty($arrayfields['t.planned_workload']['checked'])) { print ''; } -if (! empty($arrayfields['t.progress']['checked'])) +if (!empty($arrayfields['t.progress']['checked'])) { print ''; } @@ -658,27 +658,27 @@ if (! empty($arrayfields['t.progress']['checked'])) if ($usertoprocess->id == $user->id) print ''; else print '';*/ print ''; -print ''; +print ''; -for ($idw=0; $idw<7; $idw++) +for ($idw = 0; $idw < 7; $idw++) { - $dayinloopfromfirstdaytoshow = dol_time_plus_duree($firstdaytoshow, $idw, 'd'); // $firstdaytoshow is a date with hours = 0 + $dayinloopfromfirstdaytoshow = dol_time_plus_duree($firstdaytoshow, $idw, 'd'); // $firstdaytoshow is a date with hours = 0 $dayinloop = dol_time_plus_duree($startday, $idw, 'd'); - $cssweekend=''; + $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. { - $cssweekend='weekend'; + $cssweekend = 'weekend'; } - $tmpday=dol_time_plus_duree($firstdaytoshow, $idw, 'd'); + $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 '; + $cssonholiday = ''; + if (!$isavailable[$tmpday]['morning'] && !$isavailable[$tmpday]['afternoon']) $cssonholiday .= 'onholidayallday '; + elseif (!$isavailable[$tmpday]['morning']) $cssonholiday .= 'onholidaymorning '; + elseif (!$isavailable[$tmpday]['afternoon']) $cssonholiday .= 'onholidayafternoon '; - print ''; + print ''; } //print ''; print_liste_field_titre($selectedfields, $_SERVER["PHP_SELF"], "", '', '', '', $sortfield, $sortorder, 'center maxwidthsearch '); @@ -686,32 +686,32 @@ print_liste_field_titre($selectedfields, $_SERVER["PHP_SELF"], "", '', '', '', $ print "\n"; -$colspan=3+(empty($conf->global->PROJECT_TIMESHEET_DISABLEBREAK_ON_PROJECT)?0:2); +$colspan = 3 + (empty($conf->global->PROJECT_TIMESHEET_DISABLEBREAK_ON_PROJECT) ? 0 : 2); if ($conf->use_javascript_ajax) { print ''; - print ''; for ($idw = 0; $idw < 7; $idw++) { - $cssweekend=''; + $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. { - $cssweekend='weekend'; + $cssweekend = 'weekend'; } - $tmpday=dol_time_plus_duree($firstdaytoshow, $idw, 'd'); + $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 '; + $cssonholiday = ''; + if (!$isavailable[$tmpday]['morning'] && !$isavailable[$tmpday]['afternoon']) $cssonholiday .= 'onholidayallday '; + elseif (!$isavailable[$tmpday]['morning']) $cssonholiday .= 'onholidaymorning '; + elseif (!$isavailable[$tmpday]['afternoon']) $cssonholiday .= 'onholidayafternoon '; - print ''; + print ''; } print ''; print ''; @@ -720,39 +720,39 @@ if ($conf->use_javascript_ajax) // By default, we can edit only tasks we are assigned to -$restrictviewformytask=((! isset($conf->global->PROJECT_TIME_SHOW_TASK_NOT_ASSIGNED)) ? 2 : $conf->global->PROJECT_TIME_SHOW_TASK_NOT_ASSIGNED); +$restrictviewformytask = ((!isset($conf->global->PROJECT_TIME_SHOW_TASK_NOT_ASSIGNED)) ? 2 : $conf->global->PROJECT_TIME_SHOW_TASK_NOT_ASSIGNED); if (count($tasksarray) > 0) { //var_dump($tasksarray); // contains only selected tasks //var_dump($tasksarraywithoutfilter); // contains all tasks (if there is a filter, not defined if no filter) //var_dump($tasksrole); - $j=0; - $level=0; + $j = 0; + $level = 0; $totalforvisibletasks = projectLinesPerWeek($j, $firstdaytoshow, $usertoprocess, 0, $tasksarray, $level, $projectsrole, $tasksrole, $mine, $restrictviewformytask, $isavailable, 0, $arrayfields, $extrafields); //var_dump($totalforvisibletasks); // Show total for all other tasks // Calculate total for all tasks - $listofdistinctprojectid=array(); // List of all distinct projects + $listofdistinctprojectid = array(); // List of all distinct projects if (is_array($tasksarraywithoutfilter) && count($tasksarraywithoutfilter)) { - foreach($tasksarraywithoutfilter as $tmptask) + foreach ($tasksarraywithoutfilter as $tmptask) { - $listofdistinctprojectid[$tmptask->fk_project]=$tmptask->fk_project; + $listofdistinctprojectid[$tmptask->fk_project] = $tmptask->fk_project; } } //var_dump($listofdistinctprojectid); - $totalforeachday=array(); - foreach($listofdistinctprojectid as $tmpprojectid) + $totalforeachday = array(); + foreach ($listofdistinctprojectid as $tmpprojectid) { - $projectstatic->id=$tmpprojectid; - $projectstatic->loadTimeSpent($firstdaytoshow, 0, $usertoprocess->id); // Load time spent from table projet_task_time for the project into this->weekWorkLoad and this->weekWorkLoadPerTask for all days of a week + $projectstatic->id = $tmpprojectid; + $projectstatic->loadTimeSpent($firstdaytoshow, 0, $usertoprocess->id); // Load time spent from table projet_task_time for the project into this->weekWorkLoad and this->weekWorkLoadPerTask for all days of a week for ($idw = 0; $idw < 7; $idw++) { - $tmpday=dol_time_plus_duree($firstdaytoshow, $idw, 'd'); - $totalforeachday[$tmpday]+=$projectstatic->weekWorkLoad[$tmpday]; + $tmpday = dol_time_plus_duree($firstdaytoshow, $idw, 'd'); + $totalforeachday[$tmpday] += $projectstatic->weekWorkLoad[$tmpday]; } } @@ -765,11 +765,11 @@ if (count($tasksarray) > 0) { for ($idw = 0; $idw < 7; $idw++) { - $tmpday=dol_time_plus_duree($firstdaytoshow, $idw, 'd'); - $timeonothertasks=($totalforeachday[$tmpday] - $totalforvisibletasks[$tmpday]); + $tmpday = dol_time_plus_duree($firstdaytoshow, $idw, 'd'); + $timeonothertasks = ($totalforeachday[$tmpday] - $totalforvisibletasks[$tmpday]); if ($timeonothertasks) { - $isdiff=1; + $isdiff = 1; break; } } @@ -779,20 +779,20 @@ if (count($tasksarray) > 0) if ($isdiff) { print ''; - print ''; for ($idw = 0; $idw < 7; $idw++) { - $cssweekend=''; + $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. { - $cssweekend='weekend'; + $cssweekend = 'weekend'; } - print ''; // Categories - if($conf->categorie->enabled) { + if ($conf->categorie->enabled) { print '"; @@ -1095,11 +1095,11 @@ elseif ($object->id > 0) print ''; // Change probability from status - if (! empty($conf->use_javascript_ajax) && ! empty($conf->global->PROJECT_USE_OPPORTUNITIES)) + if (!empty($conf->use_javascript_ajax) && !empty($conf->global->PROJECT_USE_OPPORTUNITIES)) { // Default value to close or not when we set opp to 'WON'. - $defaultcheckedwhenoppclose=1; - if (empty($conf->global->PROJECT_HIDE_TASKS)) $defaultcheckedwhenoppclose=0; + $defaultcheckedwhenoppclose = 1; + if (empty($conf->global->PROJECT_HIDE_TASKS)) $defaultcheckedwhenoppclose = 0; print ''; print ''; print ''."\n"; } -if (! empty($conf->global->MEMBER_NEWFORM_AMOUNT) -|| ! empty($conf->global->MEMBER_NEWFORM_PAYONLINE)) +if (!empty($conf->global->MEMBER_NEWFORM_AMOUNT) +|| !empty($conf->global->MEMBER_NEWFORM_PAYONLINE)) { // $conf->global->MEMBER_NEWFORM_SHOWAMOUNT is an amount - $amount=0; - if (! empty($conf->global->MEMBER_NEWFORM_AMOUNT)) { - $amount=$conf->global->MEMBER_NEWFORM_AMOUNT; + $amount = 0; + if (!empty($conf->global->MEMBER_NEWFORM_AMOUNT)) { + $amount = $conf->global->MEMBER_NEWFORM_AMOUNT; } - if (! empty($conf->global->MEMBER_NEWFORM_PAYONLINE)) + if (!empty($conf->global->MEMBER_NEWFORM_PAYONLINE)) { - $amount=GETPOST('amount')?GETPOST('amount'):$conf->global->MEMBER_NEWFORM_AMOUNT; + $amount = GETPOST('amount') ?GETPOST('amount') : $conf->global->MEMBER_NEWFORM_AMOUNT; } // $conf->global->MEMBER_NEWFORM_PAYONLINE is 'paypal', 'paybox' or 'stripe' print ''; print ''; - if (isset($object->photo) && $object->photo !='') + if (isset($object->photo) && $object->photo != '') { $form = new Form($db); print ''; - $htmlforlines.= ''; - $htmlforlines.= ''."\n"; + $htmlforlines .= ''; + $htmlforlines .= ''; + $htmlforlines .= ''."\n"; } - $htmlforlines.= '
    '; -$searchpicto=$form->showFilterAndCheckAddButtons(0); +$searchpicto = $form->showFilterAndCheckAddButtons(0); print $searchpicto; print '
    '.$langs->trans("Project").''.$langs->trans("ThirdParty").''.$langs->trans("Project").''.$langs->trans("ThirdParty").''.$langs->trans("Task").''.$langs->trans("PlannedWorkload").''.$langs->trans("ProgressDeclared").''.$langs->trans("TimeSpentByYou").''.$langs->trans("TimeSpentByUser").''.$langs->trans("TimeSpent").'
    ('.$langs->trans("Everybody").')
    '.$langs->trans("TimeSpent").($usertoprocess->firstname?'
    ('.dol_trunc($usertoprocess->firstname, 10).')':'').'
    '.$langs->trans("TimeSpent").($usertoprocess->firstname ? '
    ('.dol_trunc($usertoprocess->firstname, 10).')' : '').'
    '.dol_print_date($dayinloopfromfirstdaytoshow, '%a').'
    '.dol_print_date($dayinloopfromfirstdaytoshow, 'dayreduceformat').'
    '.dol_print_date($dayinloopfromfirstdaytoshow, '%a').'
    '.dol_print_date($dayinloopfromfirstdaytoshow, 'dayreduceformat').'
    '; + print ''; print $langs->trans("Total"); print ' - '.$langs->trans("ExpectedWorkedHours").': '.price($usertoprocess->weeklyhours, 1, $langs, 0, 0).''; print '
     
     
     
    '; + print ''; print $langs->trans("OtherFilteredTasks"); print ''; - $tmpday=dol_time_plus_duree($firstdaytoshow, $idw, 'd'); - $timeonothertasks=($totalforeachday[$tmpday] - $totalforvisibletasks[$tmpday]); + print ''; + $tmpday = dol_time_plus_duree($firstdaytoshow, $idw, 'd'); + $timeonothertasks = ($totalforeachday[$tmpday] - $totalforvisibletasks[$tmpday]); if ($timeonothertasks) { print 'use_javascript_ajax) { @@ -865,7 +865,7 @@ if ($conf->use_javascript_ajax) } });'."\n"; - $idw=0; + $idw = 0; while ($idw < 7) { print ' updateTotal('.$idw.',\''.$modeinput.'\');'; diff --git a/htdocs/projet/admin/project.php b/htdocs/projet/admin/project.php index 56998cdfc99..bd6c5eacc47 100644 --- a/htdocs/projet/admin/project.php +++ b/htdocs/projet/admin/project.php @@ -306,7 +306,7 @@ print ''; print ''; print ''; -print ''; +print '
    '; print ''; print "\n"; print ''."\n"; @@ -349,7 +349,7 @@ print '
    '; print load_fiche_titre($langs->trans("ProjectsNumberingModules"), '', ''); -print '
    ".$langs->trans("Parameters")."'.$langs->trans("Value").'
    '; +print '
    '; print ''; print ''; print ''; @@ -450,7 +450,7 @@ if (empty($conf->global->PROJECT_HIDE_TASKS)) // Task numbering module print load_fiche_titre($langs->trans("TasksNumberingModules"), '', ''); - print '
    '.$langs->trans("Name").''.$langs->trans("Description").'
    '; + print '
    '; print ''; print ''; print ''; @@ -867,7 +867,7 @@ print ''; print ''; print ''; -print '
    '.$langs->trans("Name").''.$langs->trans("Description").'
    '; +print '
    '; print ''; print "\n"; print ''."\n"; diff --git a/htdocs/projet/card.php b/htdocs/projet/card.php index 5b3d69777b7..493978f738e 100644 --- a/htdocs/projet/card.php +++ b/htdocs/projet/card.php @@ -36,57 +36,57 @@ require_once DOL_DOCUMENT_ROOT.'/categories/class/categorie.class.php'; // Load translation files required by the page $langs->loadLangs(array('projects', 'companies')); -$id=GETPOST('id', 'int'); -$ref=GETPOST('ref', 'alpha'); -$action=GETPOST('action', 'alpha'); -$backtopage=GETPOST('backtopage', 'alpha'); -$cancel=GETPOST('cancel', 'alpha'); -$confirm=GETPOST('confirm', 'aZ09'); -$status=GETPOST('status', 'int'); -$opp_status=GETPOST('opp_status', 'int'); -$opp_percent=price2num(GETPOST('opp_percent', 'alpha')); +$id = GETPOST('id', 'int'); +$ref = GETPOST('ref', 'alpha'); +$action = GETPOST('action', 'alpha'); +$backtopage = GETPOST('backtopage', 'alpha'); +$cancel = GETPOST('cancel', 'alpha'); +$confirm = GETPOST('confirm', 'aZ09'); +$status = GETPOST('status', 'int'); +$opp_status = GETPOST('opp_status', 'int'); +$opp_percent = price2num(GETPOST('opp_percent', 'alpha')); -if ($id == '' && $ref == '' && ($action != "create" && $action != "add" && $action != "update" && ! $_POST["cancel"])) accessforbidden(); +if ($id == '' && $ref == '' && ($action != "create" && $action != "add" && $action != "update" && !$_POST["cancel"])) accessforbidden(); -$mine = GETPOST('mode')=='mine' ? 1 : 0; +$mine = GETPOST('mode') == 'mine' ? 1 : 0; //if (! $user->rights->projet->all->lire) $mine=1; // Special for projects // Initialize technical object to manage hooks of page. Note that conf->hooks_modules contains array of hook context -$hookmanager->initHooks(array('projectcard','globalcard')); +$hookmanager->initHooks(array('projectcard', 'globalcard')); $object = new Project($db); $extrafields = new ExtraFields($db); // Load object //include DOL_DOCUMENT_ROOT.'/core/actions_fetchobject.inc.php'; // Can't use generic include because when creating a project, ref is defined and we dont want error if fetch fails from ref. -if ($id > 0 || ! empty($ref)) +if ($id > 0 || !empty($ref)) { - $ret = $object->fetch($id, $ref); // If we create project, ref may be defined into POST but record does not yet exists into database + $ret = $object->fetch($id, $ref); // If we create project, ref may be defined into POST but record does not yet exists into database if ($ret > 0) { $object->fetch_thirdparty(); - if(! empty($conf->global->PROJECT_ALLOW_COMMENT_ON_PROJECT) && method_exists($object, 'fetchComments') && empty($object->comments)) $object->fetchComments(); - $id=$object->id; + if (!empty($conf->global->PROJECT_ALLOW_COMMENT_ON_PROJECT) && method_exists($object, 'fetchComments') && empty($object->comments)) $object->fetchComments(); + $id = $object->id; } } // Security check -$socid=GETPOST('socid', 'int'); +$socid = GETPOST('socid', 'int'); //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, 'projet', $object->id, 'projet&project'); // fetch optionals attributes and labels $extrafields->fetch_name_optionals_label($object->table_element); -$date_start=dol_mktime(0, 0, 0, GETPOST('projectstartmonth', 'int'), GETPOST('projectstartday', 'int'), GETPOST('projectstartyear', 'int')); -$date_end=dol_mktime(0, 0, 0, GETPOST('projectendmonth', 'int'), GETPOST('projectendday', 'int'), GETPOST('projectendyear', 'int')); +$date_start = dol_mktime(0, 0, 0, GETPOST('projectstartmonth', 'int'), GETPOST('projectstartday', 'int'), GETPOST('projectstartyear', 'int')); +$date_end = dol_mktime(0, 0, 0, GETPOST('projectendmonth', 'int'), GETPOST('projectendday', 'int'), GETPOST('projectendyear', 'int')); /* * Actions */ -$parameters=array('id'=>$socid, 'objcanvas'=>$objcanvas); -$reshook=$hookmanager->executeHooks('doActions', $parameters, $object, $action); // Note that $action and $object may have been modified by some hooks +$parameters = array('id'=>$socid, '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 (empty($reshook)) @@ -94,9 +94,9 @@ if (empty($reshook)) // Cancel if ($cancel) { - if (GETPOST("comefromclone")==1) + if (GETPOST("comefromclone") == 1) { - $result=$object->delete($user); + $result = $object->delete($user); if ($result > 0) { header("Location: index.php"); @@ -119,7 +119,7 @@ if (empty($reshook)) if ($action == 'add' && $user->rights->projet->creer) { - $error=0; + $error = 0; if (empty($_POST["ref"])) { setEventMessages($langs->trans("ErrorFieldRequired", $langs->transnoentities("Ref")), null, 'errors'); @@ -131,21 +131,21 @@ if (empty($reshook)) $error++; } - if (GETPOST('opp_amount') != '' && ! (GETPOST('opp_status') > 0)) + if (GETPOST('opp_amount') != '' && !(GETPOST('opp_status') > 0)) { $error++; setEventMessages($langs->trans("ErrorOppStatusRequiredIfAmount"), null, 'errors'); } // Create with status validated immediatly - if (! empty($conf->global->PROJECT_CREATE_NO_DRAFT)) + if (!empty($conf->global->PROJECT_CREATE_NO_DRAFT)) { - $status=Project::STATUS_VALIDATED; + $status = Project::STATUS_VALIDATED; } - if (! $error) + if (!$error) { - $error=0; + $error = 0; $db->begin(); @@ -156,23 +156,23 @@ if (empty($reshook)) $object->public = GETPOST('public', 'alpha'); $object->opp_amount = price2num(GETPOST('opp_amount', 'alpha')); $object->budget_amount = price2num(GETPOST('budget_amount', 'alpha')); - $object->date_c = dol_now(); + $object->date_c = dol_now(); $object->date_start = $date_start; $object->date_end = $date_end; $object->statut = $status; $object->opp_status = $opp_status; $object->opp_percent = $opp_percent; - $object->usage_opportunity = (GETPOST('usage_opportunity', 'alpha')=='on'?1:0); - $object->usage_task = (GETPOST('usage_task', 'alpha')=='on'?1:0); - $object->usage_bill_time = (GETPOST('usage_bill_time', 'alpha')=='on'?1:0); - $object->usage_organize_event = (GETPOST('usage_organize_event', 'alpha')=='on'?1:0); + $object->usage_opportunity = (GETPOST('usage_opportunity', 'alpha') == 'on' ? 1 : 0); + $object->usage_task = (GETPOST('usage_task', 'alpha') == 'on' ? 1 : 0); + $object->usage_bill_time = (GETPOST('usage_bill_time', 'alpha') == 'on' ? 1 : 0); + $object->usage_organize_event = (GETPOST('usage_organize_event', 'alpha') == 'on' ? 1 : 0); // Fill array 'array_options' with data from add form $ret = $extrafields->setOptionalsFromPost(null, $object); if ($ret < 0) $error++; $result = $object->create($user); - if (! $error && $result > 0) + if (!$error && $result > 0) { // Add myself as project leader $result = $object->add_contact($user->id, 'PROJECTLEADER', 'internal'); @@ -189,26 +189,26 @@ if (empty($reshook)) setEventMessages($langs->trans($object->error), null, 'errors'); $error++; } - if (! $error && !empty($object->id) > 0) + if (!$error && !empty($object->id) > 0) { // Category association $categories = GETPOST('categories', 'array'); - $result=$object->setCategories($categories); - if ($result<0) { + $result = $object->setCategories($categories); + if ($result < 0) { $langs->load("errors"); setEventMessages($object->error, $object->errors, 'errors'); $error++; } } - if (! $error) + if (!$error) { $db->commit(); - if (! empty($backtopage)) + if (!empty($backtopage)) { - $backtopage = preg_replace('/--IDFORBACKTOPAGE--/', $object->id, $backtopage); // New method to autoselect project after a New on another form object creation - $backtopage = $backtopage.'&projectid='.$object->id; // Old method + $backtopage = preg_replace('/--IDFORBACKTOPAGE--/', $object->id, $backtopage); // New method to autoselect project after a New on another form object creation + $backtopage = $backtopage.'&projectid='.$object->id; // Old method header("Location: ".$backtopage); exit; } @@ -231,9 +231,9 @@ if (empty($reshook)) } } - if ($action == 'update' && ! $_POST["cancel"] && $user->rights->projet->creer) + if ($action == 'update' && !$_POST["cancel"] && $user->rights->projet->creer) { - $error=0; + $error = 0; if (empty($ref)) { @@ -250,7 +250,7 @@ if (empty($reshook)) $db->begin(); - if (! $error) + if (!$error) { $object->oldcopy = clone $object; @@ -260,18 +260,18 @@ if (empty($reshook)) $object->title = GETPOST('title', 'none'); // Do not use 'alpha' here, we want field as it is $object->statut = GETPOST('status', 'int'); $object->socid = GETPOST('socid', 'int'); - $object->description = GETPOST('description', 'none'); // Do not use 'alpha' here, we want field as it is + $object->description = GETPOST('description', 'none'); // Do not use 'alpha' here, we want field as it is $object->public = GETPOST('public', 'alpha'); - $object->date_start = empty($_POST["projectstart"])?'':$date_start; - $object->date_end = empty($_POST["projectend"])?'':$date_end; + $object->date_start = empty($_POST["projectstart"]) ? '' : $date_start; + $object->date_end = empty($_POST["projectend"]) ? '' : $date_end; if (isset($_POST['opp_amount'])) $object->opp_amount = price2num(GETPOST('opp_amount', 'alpha')); - if (isset($_POST['budget_amount'])) $object->budget_amount= price2num(GETPOST('budget_amount', 'alpha')); + if (isset($_POST['budget_amount'])) $object->budget_amount = price2num(GETPOST('budget_amount', 'alpha')); if (isset($_POST['opp_status'])) $object->opp_status = $opp_status; if (isset($_POST['opp_percent'])) $object->opp_percent = $opp_percent; - $object->usage_opportunity = (GETPOST('usage_opportunity', 'alpha')=='on'?1:0); - $object->usage_task = (GETPOST('usage_task', 'alpha')=='on'?1:0); - $object->usage_bill_time = (GETPOST('usage_bill_time', 'alpha')=='on'?1:0); - $object->usage_organize_event = (GETPOST('usage_organize_event', 'alpha')=='on'?1:0); + $object->usage_opportunity = (GETPOST('usage_opportunity', 'alpha') == 'on' ? 1 : 0); + $object->usage_task = (GETPOST('usage_task', 'alpha') == 'on' ? 1 : 0); + $object->usage_bill_time = (GETPOST('usage_bill_time', 'alpha') == 'on' ? 1 : 0); + $object->usage_organize_event = (GETPOST('usage_organize_event', 'alpha') == 'on' ? 1 : 0); // Fill array 'array_options' with data from add form $ret = $extrafields->setOptionalsFromPost(null, $object); @@ -284,18 +284,18 @@ if (empty($reshook)) setEventMessages($langs->trans("ErrorOppStatusRequiredIfAmount"), null, 'errors'); } - if (! $error) + if (!$error) { - $result=$object->update($user); + $result = $object->update($user); if ($result < 0) { $error++; if ($result == -4) setEventMessages($langs->trans("ErrorRefAlreadyExists"), null, 'errors'); else setEventMessages($object->error, $object->errors, 'errors'); - }else { + } else { // Category association $categories = GETPOST('categories', 'array'); - $result=$object->setCategories($categories); + $result = $object->setCategories($categories); if ($result < 0) { $error++; @@ -304,11 +304,11 @@ if (empty($reshook)) } } - if (! $error) + if (!$error) { - if (GETPOST("reportdate") && ($object->date_start!=$old_start_date)) + if (GETPOST("reportdate") && ($object->date_start != $old_start_date)) { - $result=$object->shiftTaskDate($old_start_date); + $result = $object->shiftTaskDate($old_start_date); if ($result < 0) { $error++; @@ -332,7 +332,7 @@ if (empty($reshook)) if ($error) { $db->rollback(); - $action='edit'; + $action = 'edit'; } else { @@ -355,11 +355,11 @@ if (empty($reshook)) $outputlangs = new Translate("", $conf); $outputlangs->setDefaultLang(GETPOST('lang_id', 'aZ09')); } - $result= $object->generateDocument($object->modelpdf, $outputlangs); + $result = $object->generateDocument($object->modelpdf, $outputlangs); if ($result <= 0) { setEventMessages($object->error, $object->errors, 'errors'); - $action=''; + $action = ''; } } @@ -368,11 +368,11 @@ if (empty($reshook)) { if ($object->id > 0) { - require_once DOL_DOCUMENT_ROOT . '/core/lib/files.lib.php'; + require_once DOL_DOCUMENT_ROOT.'/core/lib/files.lib.php'; $langs->load("other"); $upload_dir = $conf->projet->dir_output; - $file = $upload_dir . '/' . GETPOST('file'); + $file = $upload_dir.'/'.GETPOST('file'); $ret = dol_delete_file($file, 0, 0, 0, $object); if ($ret) setEventMessages($langs->trans("FileWasRemoved", GETPOST('file')), null, 'mesgs'); @@ -413,7 +413,7 @@ if (empty($reshook)) if ($action == 'confirm_delete' && GETPOST("confirm") == "yes" && $user->rights->projet->supprimer) { $object->fetch($id); - $result=$object->delete($user); + $result = $object->delete($user); if ($result > 0) { setEventMessages($langs->trans("RecordDeleted"), null, 'mesgs'); @@ -429,15 +429,15 @@ if (empty($reshook)) if ($action == 'confirm_clone' && $user->rights->projet->creer && $confirm == 'yes') { - $clone_contacts=GETPOST('clone_contacts')?1:0; - $clone_tasks=GETPOST('clone_tasks')?1:0; + $clone_contacts = GETPOST('clone_contacts') ? 1 : 0; + $clone_tasks = GETPOST('clone_tasks') ? 1 : 0; $clone_project_files = GETPOST('clone_project_files') ? 1 : 0; $clone_task_files = GETPOST('clone_task_files') ? 1 : 0; - $clone_notes=GETPOST('clone_notes')?1:0; - $move_date=GETPOST('move_date')?1:0; - $clone_thirdparty=GETPOST('socid', 'int')?GETPOST('socid', 'int'):0; + $clone_notes = GETPOST('clone_notes') ? 1 : 0; + $move_date = GETPOST('move_date') ? 1 : 0; + $clone_thirdparty = GETPOST('socid', 'int') ?GETPOST('socid', 'int') : 0; - $result=$object->createFromClone($user, $object->id, $clone_contacts, $clone_tasks, $clone_project_files, $clone_task_files, $clone_notes, $move_date, 0, $clone_thirdparty); + $result = $object->createFromClone($user, $object->id, $clone_contacts, $clone_tasks, $clone_project_files, $clone_task_files, $clone_notes, $move_date, 0, $clone_thirdparty); if ($result <= 0) { setEventMessages($object->error, $object->errors, 'errors'); @@ -445,21 +445,21 @@ if (empty($reshook)) else { // Load new object - $newobject=new Project($db); + $newobject = new Project($db); $newobject->fetch($result); $newobject->fetch_optionals(); - $newobject->fetch_thirdparty(); // Load new object - $object=$newobject; - $action='edit'; - $comefromclone=true; + $newobject->fetch_thirdparty(); // Load new object + $object = $newobject; + $action = 'edit'; + $comefromclone = true; } } // Actions to send emails - $trigger_name='PROJECT_SENTBYMAIL'; - $paramname='id'; - $autocopy='MAIN_MAIL_AUTOCOPY_PROJECT_TO'; // used to know the automatic BCC to add - $trackid='proj'.$object->id; + $trigger_name = 'PROJECT_SENTBYMAIL'; + $paramname = 'id'; + $autocopy = 'MAIN_MAIL_AUTOCOPY_PROJECT_TO'; // used to know the automatic BCC to add + $trackid = 'proj'.$object->id; include DOL_DOCUMENT_ROOT.'/core/actions_sendmails.inc.php'; } @@ -473,21 +473,21 @@ $formfile = new FormFile($db); $formproject = new FormProjets($db); $userstatic = new User($db); -$title=$langs->trans("Project").' - '.$object->ref.($object->thirdparty->name?' - '.$object->thirdparty->name:'').($object->title?' - '.$object->title:''); -if (! empty($conf->global->MAIN_HTML_TITLE) && preg_match('/projectnameonly/', $conf->global->MAIN_HTML_TITLE)) $title=$object->ref.($object->thirdparty->name?' - '.$object->thirdparty->name:'').($object->title?' - '.$object->title:''); -$help_url="EN:Module_Projects|FR:Module_Projets|ES:Módulo_Proyectos"; +$title = $langs->trans("Project").' - '.$object->ref.($object->thirdparty->name ? ' - '.$object->thirdparty->name : '').($object->title ? ' - '.$object->title : ''); +if (!empty($conf->global->MAIN_HTML_TITLE) && preg_match('/projectnameonly/', $conf->global->MAIN_HTML_TITLE)) $title = $object->ref.($object->thirdparty->name ? ' - '.$object->thirdparty->name : '').($object->title ? ' - '.$object->title : ''); +$help_url = "EN:Module_Projects|FR:Module_Projets|ES:Módulo_Proyectos"; llxHeader("", $title, $help_url); -$titleboth=$langs->trans("LeadsOrProjects"); -$titlenew = $langs->trans("NewLeadOrProject"); // Leads and opportunities by default +$titleboth = $langs->trans("LeadsOrProjects"); +$titlenew = $langs->trans("NewLeadOrProject"); // Leads and opportunities by default if ($conf->global->PROJECT_USE_OPPORTUNITIES == 0) { - $titleboth=$langs->trans("Projects"); + $titleboth = $langs->trans("Projects"); $titlenew = $langs->trans("NewProject"); } if ($conf->global->PROJECT_USE_OPPORTUNITIES == 2) { // 2 = leads only - $titleboth=$langs->trans("Leads"); + $titleboth = $langs->trans("Leads"); $titlenew = $langs->trans("NewLead"); } @@ -497,7 +497,7 @@ if ($action == 'create' && $user->rights->projet->creer) * Create */ - $thirdparty=new Societe($db); + $thirdparty = new Societe($db); if ($socid > 0) $thirdparty->fetch($socid); print load_fiche_titre($titlenew, '', 'project'); @@ -511,18 +511,18 @@ if ($action == 'create' && $user->rights->projet->creer) print '
    ".$langs->trans("Parameters")."'.$langs->trans("Value").'
    '; - $defaultref=''; - $modele = empty($conf->global->PROJECT_ADDON)?'mod_project_simple':$conf->global->PROJECT_ADDON; + $defaultref = ''; + $modele = empty($conf->global->PROJECT_ADDON) ? 'mod_project_simple' : $conf->global->PROJECT_ADDON; // Search template files - $file=''; $classname=''; $filefound=0; - $dirmodels=array_merge(array('/'), (array) $conf->modules_parts['models']); - foreach($dirmodels as $reldir) + $file = ''; $classname = ''; $filefound = 0; + $dirmodels = array_merge(array('/'), (array) $conf->modules_parts['models']); + foreach ($dirmodels as $reldir) { - $file=dol_buildpath($reldir."core/modules/project/".$modele.'.php', 0); + $file = dol_buildpath($reldir."core/modules/project/".$modele.'.php', 0); if (file_exists($file)) { - $filefound=1; + $filefound = 1; $classname = $modele; break; } @@ -530,16 +530,16 @@ if ($action == 'create' && $user->rights->projet->creer) if ($filefound) { - $result=dol_include_once($reldir."core/modules/project/".$modele.'.php'); + $result = dol_include_once($reldir."core/modules/project/".$modele.'.php'); $modProject = new $classname; $defaultref = $modProject->getNextValue($thirdparty, $object); } - if (is_numeric($defaultref) && $defaultref <= 0) $defaultref=''; + if (is_numeric($defaultref) && $defaultref <= 0) $defaultref = ''; // Ref - $suggestedref=($_POST["ref"]?$_POST["ref"]:$defaultref); + $suggestedref = ($_POST["ref"] ? $_POST["ref"] : $defaultref); print ''; @@ -552,23 +552,23 @@ if ($action == 'create' && $user->rights->projet->creer) print $langs->trans("Usage"); print ''; print ''; } @@ -612,46 +612,46 @@ if ($action == 'create' && $user->rights->projet->creer) // Visibility print ''; // Date start print ''; // Date end print ''; - if (! empty($conf->global->PROJECT_USE_OPPORTUNITIES)) + if (!empty($conf->global->PROJECT_USE_OPPORTUNITIES)) { // Opportunity status print ''; print ''; // Opportunity probability print ''; - print ''; print ''; // Opportunity amount print ''; - print ''; + print ''; print ''; } // Budget print ''; - print ''; + print ''; print ''; // Description @@ -664,14 +664,14 @@ if ($action == 'create' && $user->rights->projet->creer) // Categories print '"; } // Other options - $parameters=array(); - $reshook=$hookmanager->executeHooks('formObjectOptions', $parameters, $object, $action); // Note that $action and $object may have been modified by hook + $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)) { @@ -684,7 +684,7 @@ if ($action == 'create' && $user->rights->projet->creer) print '
    '; print ''; - if (! empty($backtopage)) + if (!empty($backtopage)) { print '     '; print ''; @@ -692,7 +692,7 @@ if ($action == 'create' && $user->rights->projet->creer) else { print '     '; - print ''; + print ''; } print '
    '; @@ -721,7 +721,7 @@ elseif ($object->id > 0) * Show or edit */ - $res=$object->fetch_optionals(); + $res = $object->fetch_optionals(); // To verify role of users $userAccess = $object->restrictedProjectArea($user, 'read'); @@ -748,26 +748,26 @@ elseif ($object->id > 0) // Confirmation delete if ($action == 'delete') { - $text=$langs->trans("ConfirmDeleteAProject"); - $task=new Task($db); - $taskarray=$task->getTasksArray(0, 0, $object->id, 0, 0); - $nboftask=count($taskarray); - if ($nboftask) $text.='
    '.img_warning().' '.$langs->trans("ThisWillAlsoRemoveTasks", $nboftask); + $text = $langs->trans("ConfirmDeleteAProject"); + $task = new Task($db); + $taskarray = $task->getTasksArray(0, 0, $object->id, 0, 0); + $nboftask = count($taskarray); + if ($nboftask) $text .= '
    '.img_warning().' '.$langs->trans("ThisWillAlsoRemoveTasks", $nboftask); print $form->formconfirm($_SERVER["PHP_SELF"]."?id=".$object->id, $langs->trans("DeleteAProject"), $text, "confirm_delete", '', '', 1); } // Clone confirmation if ($action == 'clone') { - $formquestion=array( + $formquestion = array( 'text' => $langs->trans("ConfirmClone"), - array('type' => 'other','name' => 'socid','label' => $langs->trans("SelectThirdParty"),'value' => $form->select_company(GETPOST('socid', 'int')>0?GETPOST('socid', 'int'):$object->socid, 'socid', '', "None", 0, 0, null, 0, 'minwidth200')), - array('type' => 'checkbox', 'name' => 'clone_contacts', 'label' => $langs->trans("CloneContacts"), 'value' => true), - array('type' => 'checkbox', 'name' => 'clone_tasks', 'label' => $langs->trans("CloneTasks"), 'value' => true), - array('type' => 'checkbox', 'name' => 'move_date', 'label' => $langs->trans("CloneMoveDate"), 'value' => true), - array('type' => 'checkbox', 'name' => 'clone_notes', 'label' => $langs->trans("CloneNotes"), 'value' => true), - array('type' => 'checkbox', 'name' => 'clone_project_files','label' => $langs->trans("CloneProjectFiles"), 'value' => false), - array('type' => 'checkbox', 'name' => 'clone_task_files', 'label' => $langs->trans("CloneTaskFiles"), 'value' => false) + array('type' => 'other', 'name' => 'socid', 'label' => $langs->trans("SelectThirdParty"), 'value' => $form->select_company(GETPOST('socid', 'int') > 0 ?GETPOST('socid', 'int') : $object->socid, 'socid', '', "None", 0, 0, null, 0, 'minwidth200')), + array('type' => 'checkbox', 'name' => 'clone_contacts', 'label' => $langs->trans("CloneContacts"), 'value' => true), + array('type' => 'checkbox', 'name' => 'clone_tasks', 'label' => $langs->trans("CloneTasks"), 'value' => true), + array('type' => 'checkbox', 'name' => 'move_date', 'label' => $langs->trans("CloneMoveDate"), 'value' => true), + array('type' => 'checkbox', 'name' => 'clone_notes', 'label' => $langs->trans("CloneNotes"), 'value' => true), + array('type' => 'checkbox', 'name' => 'clone_project_files', 'label' => $langs->trans("CloneProjectFiles"), 'value' => false), + array('type' => 'checkbox', 'name' => 'clone_task_files', 'label' => $langs->trans("CloneTaskFiles"), 'value' => false) ); print $form->formconfirm($_SERVER["PHP_SELF"]."?id=".$object->id, $langs->trans("CloneProject"), $langs->trans("ConfirmCloneProject"), "confirm_clone", $formquestion, '', 1, 300, 590); @@ -780,16 +780,16 @@ elseif ($object->id > 0) print ''; print ''; - $head=project_prepare_head($object); + $head = project_prepare_head($object); if ($action == 'edit' && $userWrite > 0) { - dol_fiche_head($head, 'project', $langs->trans("Project"), 0, ($object->public?'projectpub':'project')); + dol_fiche_head($head, 'project', $langs->trans("Project"), 0, ($object->public ? 'projectpub' : 'project')); - print '
    '.$langs->trans("Ref").''; print ' '.$form->textwithpicto('', $langs->trans("YouCanCompleteRef", $suggestedref)); print '
    '; - if (! empty($conf->global->PROJECT_USE_OPPORTUNITIES)) + if (!empty($conf->global->PROJECT_USE_OPPORTUNITIES)) { - print ' '; + print ' '; $htmltext = $langs->trans("ProjectFollowOpportunity"); print $form->textwithpicto($langs->trans("ProjectFollowOpportunity"), $htmltext); print '
    '; } if (empty($conf->global->PROJECT_HIDE_TASKS)) { - print ' '; + print ' '; $htmltext = $langs->trans("ProjectFollowTasks"); print $form->textwithpicto($langs->trans("ProjectFollowTasks"), $htmltext); print '
    '; } - if (! empty($conf->global->PROJECT_BILL_TIME_SPENT)) + if (!empty($conf->global->PROJECT_BILL_TIME_SPENT)) { - print ' '; + print ' '; $htmltext = $langs->trans("ProjectBillTimeDescription"); print $form->textwithpicto($langs->trans("BillTime"), $htmltext); print '
    '; @@ -584,20 +584,20 @@ if ($action == 'create' && $user->rights->projet->creer) if ($conf->societe->enabled) { print '
    '; - print (empty($conf->global->PROJECT_THIRDPARTY_REQUIRED)?'':''); + print (empty($conf->global->PROJECT_THIRDPARTY_REQUIRED) ? '' : ''); print $langs->trans("ThirdParty"); - print (empty($conf->global->PROJECT_THIRDPARTY_REQUIRED)?'':''); + print (empty($conf->global->PROJECT_THIRDPARTY_REQUIRED) ? '' : ''); print ''; - $filteronlist=''; - if (! empty($conf->global->PROJECT_FILTER_FOR_THIRDPARTY_LIST)) $filteronlist=$conf->global->PROJECT_FILTER_FOR_THIRDPARTY_LIST; - $text=$form->select_company(GETPOST('socid', 'int'), 'socid', $filteronlist, 'SelectThirdParty', 1, 0, array(), 0, 'minwidth300'); + $filteronlist = ''; + if (!empty($conf->global->PROJECT_FILTER_FOR_THIRDPARTY_LIST)) $filteronlist = $conf->global->PROJECT_FILTER_FOR_THIRDPARTY_LIST; + $text = $form->select_company(GETPOST('socid', 'int'), 'socid', $filteronlist, 'SelectThirdParty', 1, 0, array(), 0, 'minwidth300'); if (empty($conf->global->PROJECT_CAN_ALWAYS_LINK_TO_ALL_SUPPLIERS) && empty($conf->dol_use_jmobile)) { - $texthelp=$langs->trans("IfNeedToUseOtherObjectKeepEmpty"); + $texthelp = $langs->trans("IfNeedToUseOtherObjectKeepEmpty"); print $form->textwithtooltip($text.' '.img_help(), $texthelp, 1); } else print $text; - if (! GETPOSTISSET('backtopage')) print ' '.$langs->trans("AddThirdParty").''; + if (!GETPOSTISSET('backtopage')) print ' '.$langs->trans("AddThirdParty").''; print '
    '.$langs->trans("Visibility").''; - $array=array(); + $array = array(); if (empty($conf->global->PROJECT_DISABLE_PRIVATE_PROJECT)) $array[0] = $langs->trans("PrivateProject"); if (empty($conf->global->PROJECT_DISABLE_PUBLIC_PROJECT)) $array[1] = $langs->trans("SharedProject"); - print $form->selectarray('public', $array, GETPOST('public')?GETPOST('public'):$object->public); + print $form->selectarray('public', $array, GETPOST('public') ?GETPOST('public') : $object->public); print '
    '.$langs->trans("DateStart").''; - print $form->selectDate(($date_start?$date_start:''), 'projectstart', 0, 0, 0, '', 1, 0); + print $form->selectDate(($date_start ? $date_start : ''), 'projectstart', 0, 0, 0, '', 1, 0); print '
    '.$langs->trans("DateEnd").''; - print $form->selectDate(($date_end?$date_end:-1), 'projectend', 0, 0, 0, '', 1, 0); + print $form->selectDate(($date_end ? $date_end : -1), 'projectend', 0, 0, 0, '', 1, 0); print '
    '.$langs->trans("OpportunityStatus").''; - print $formproject->selectOpportunityStatus('opp_status', GETPOST('opp_status')?GETPOST('opp_status'):$object->opp_status); + print $formproject->selectOpportunityStatus('opp_status', GETPOST('opp_status') ?GETPOST('opp_status') : $object->opp_status); print '
    '.$langs->trans("OpportunityProbability").' %'; - print ''; + print ' %'; + print ''; print '
    '.$langs->trans("OpportunityAmount").'
    '.$langs->trans("Budget").'
    '.$langs->trans("Categories").''; $cate_arbo = $form->select_all_categories(Categorie::TYPE_PROJECT, '', 'parent', 64, 0, 1); - $arrayselected=GETPOST('categories', 'array'); + $arrayselected = GETPOST('categories', 'array'); print $form->multiselectarray('categories', $cate_arbo, $arrayselected, '', 0, '', 0, '100%'); print "
    '; + print '
    '; // Ref - $suggestedref=$object->ref; + $suggestedref = $object->ref; print ''; print ''; @@ -815,23 +815,23 @@ elseif ($object->id > 0) print $langs->trans("Usage"); print ''; print ''; - if (! empty($conf->global->PROJECT_USE_OPPORTUNITIES)) + if (!empty($conf->global->PROJECT_USE_OPPORTUNITIES)) { // Opportunity status print ''; @@ -881,33 +881,33 @@ elseif ($object->id > 0) // Opportunity probability print ''; - print ''; print ''; // Opportunity amount print ''; - print ''; + print ''; print ''; } // Date start print ''; // Date end print ''; // Budget print ''; - print ''; + print ''; print ''; // Description @@ -923,7 +923,7 @@ elseif ($object->id > 0) $cate_arbo = $form->select_all_categories(Categorie::TYPE_PROJECT, '', 'parent', 64, 0, 1); $c = new Categorie($db); $cats = $c->containing($object->id, Categorie::TYPE_PROJECT); - foreach($cats as $cat) { + foreach ($cats as $cat) { $arrayselected[] = $cat->id; } print $form->multiselectarray('categories', $cate_arbo, $arrayselected, '', 0, '', 0, '100%'); @@ -931,8 +931,8 @@ elseif ($object->id > 0) } // Other options - $parameters=array(); - $reshook=$hookmanager->executeHooks('formObjectOptions', $parameters, $object, $action); // Note that $action and $object may have been modified by hook + $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)) { @@ -943,28 +943,28 @@ elseif ($object->id > 0) } else { - dol_fiche_head($head, 'project', $langs->trans("Project"), -1, ($object->public?'projectpub':'project')); + dol_fiche_head($head, 'project', $langs->trans("Project"), -1, ($object->public ? 'projectpub' : 'project')); // Project card $linkback = ''.$langs->trans("BackToList").''; - $morehtmlref='
    '; + $morehtmlref = '
    '; // Title - $morehtmlref.=$object->title; + $morehtmlref .= $object->title; // Thirdparty - $morehtmlref.='
    '.$langs->trans('ThirdParty') . ' : '; + $morehtmlref .= '
    '.$langs->trans('ThirdParty').' : '; if ($object->thirdparty->id > 0) { $morehtmlref .= $object->thirdparty->getNomUrl(1, 'project'); } - $morehtmlref.='
    '; + $morehtmlref .= '
    '; // Define a complementary filter for search of next/prev ref. - if (! $user->rights->projet->all->lire) + if (!$user->rights->projet->all->lire) { $objectsListId = $object->getProjectsAuthorizedForUser($user, 0, 0); - $object->next_prev_filter=" rowid in (".(count($objectsListId)?join(',', array_keys($objectsListId)):'0').")"; + $object->next_prev_filter = " rowid in (".(count($objectsListId) ?join(',', array_keys($objectsListId)) : '0').")"; } dol_banner_tab($object, 'ref', $linkback, 1, 'ref', 'ref', $morehtmlref); @@ -981,23 +981,23 @@ elseif ($object->id > 0) print $langs->trans("Usage"); print ''; print ''; - if (! empty($conf->global->PROJECT_USE_OPPORTUNITIES) && ! empty($object->usage_opportunity)) + if (!empty($conf->global->PROJECT_USE_OPPORTUNITIES) && !empty($object->usage_opportunity)) { // Opportunity status print ''; @@ -1050,7 +1050,7 @@ elseif ($object->id > 0) // Other attributes $cols = 2; - include DOL_DOCUMENT_ROOT . '/core/tpl/extrafields_view.tpl.php'; + include DOL_DOCUMENT_ROOT.'/core/tpl/extrafields_view.tpl.php'; print '
    '.$langs->trans("Ref").''; print ' '.$form->textwithpicto('', $langs->trans("YouCanCompleteRef", $suggestedref)); @@ -803,9 +803,9 @@ elseif ($object->id > 0) // Status print '
    '.$langs->trans("Status").''; print ''; print '
    '; - if (! empty($conf->global->PROJECT_USE_OPPORTUNITIES)) + if (!empty($conf->global->PROJECT_USE_OPPORTUNITIES)) { - print 'usage_opportunity ? ' checked="checked"' : '')).'"> '; + print 'usage_opportunity ? ' checked="checked"' : '')).'"> '; $htmltext = $langs->trans("ProjectFollowOpportunity"); print $form->textwithpicto($langs->trans("ProjectFollowOpportunity"), $htmltext); print '
    '; } if (empty($conf->global->PROJECT_HIDE_TASKS)) { - print 'usage_task ? ' checked="checked"' : '')).'"> '; + print 'usage_task ? ' checked="checked"' : '')).'"> '; $htmltext = $langs->trans("ProjectFollowTasks"); print $form->textwithpicto($langs->trans("ProjectFollowTasks"), $htmltext); print '
    '; } - if (! empty($conf->global->PROJECT_BILL_TIME_SPENT)) + if (!empty($conf->global->PROJECT_BILL_TIME_SPENT)) { - print 'usage_bill_time ? ' checked="checked"' : '')).'"> '; + print 'usage_bill_time ? ' checked="checked"' : '')).'"> '; $htmltext = $langs->trans("ProjectBillTimeDescription"); print $form->textwithpicto($langs->trans("BillTime"), $htmltext); print '
    '; @@ -842,16 +842,16 @@ elseif ($object->id > 0) if ($conf->societe->enabled) { print '
    '; - print (empty($conf->global->PROJECT_THIRDPARTY_REQUIRED)?'':''); + print (empty($conf->global->PROJECT_THIRDPARTY_REQUIRED) ? '' : ''); print $langs->trans("ThirdParty"); - print (empty($conf->global->PROJECT_THIRDPARTY_REQUIRED)?'':''); + print (empty($conf->global->PROJECT_THIRDPARTY_REQUIRED) ? '' : ''); print ''; - $filteronlist=''; - if (! empty($conf->global->PROJECT_FILTER_FOR_THIRDPARTY_LIST)) $filteronlist=$conf->global->PROJECT_FILTER_FOR_THIRDPARTY_LIST; - $text=$form->select_company($object->thirdparty->id, 'socid', $filteronlist, 'None', 1, 0, array(), 0, 'minwidth300'); + $filteronlist = ''; + if (!empty($conf->global->PROJECT_FILTER_FOR_THIRDPARTY_LIST)) $filteronlist = $conf->global->PROJECT_FILTER_FOR_THIRDPARTY_LIST; + $text = $form->select_company($object->thirdparty->id, 'socid', $filteronlist, 'None', 1, 0, array(), 0, 'minwidth300'); if (empty($conf->global->PROJECT_CAN_ALWAYS_LINK_TO_ALL_SUPPLIERS) && empty($conf->dol_use_jmobile)) { - $texthelp=$langs->trans("IfNeedToUseOtherObjectKeepEmpty"); + $texthelp = $langs->trans("IfNeedToUseOtherObjectKeepEmpty"); print $form->textwithtooltip($text.' '.img_help(), $texthelp, 1, 0, '', '', 2); } else print $text; @@ -860,13 +860,13 @@ elseif ($object->id > 0) // Visibility print '
    '.$langs->trans("Visibility").''; - $array=array(); + $array = array(); if (empty($conf->global->PROJECT_DISABLE_PRIVATE_PROJECT)) $array[0] = $langs->trans("PrivateProject"); if (empty($conf->global->PROJECT_DISABLE_PUBLIC_PROJECT)) $array[1] = $langs->trans("SharedProject"); print $form->selectarray('public', $array, $object->public); print '
    '.$langs->trans("OpportunityStatus").'
    '.$langs->trans("OpportunityProbability").' %'; + print ' %'; print ''; print '
    '.$langs->trans("OpportunityAmount").'
    '.$langs->trans("DateStart").''; - print $form->selectDate($object->date_start?$object->date_start:-1, 'projectstart', 0, 0, 0, '', 1, 0); + print $form->selectDate($object->date_start ? $object->date_start : -1, 'projectstart', 0, 0, 0, '', 1, 0); print '     '. $langs->trans("ProjectReportDate"); + if ($comefromclone) {print ' checked '; } + print '/> '.$langs->trans("ProjectReportDate"); print '
    '.$langs->trans("DateEnd").''; - print $form->selectDate($object->date_end?$object->date_end:-1, 'projectend', 0, 0, 0, '', 1, 0); + print $form->selectDate($object->date_end ? $object->date_end : -1, 'projectend', 0, 0, 0, '', 1, 0); print '
    '.$langs->trans("Budget").'
    '; - if (! empty($conf->global->PROJECT_USE_OPPORTUNITIES)) + if (!empty($conf->global->PROJECT_USE_OPPORTUNITIES)) { - print 'usage_opportunity ? ' checked="checked"' : '')).'"> '; + print 'usage_opportunity ? ' checked="checked"' : '')).'"> '; $htmltext = $langs->trans("ProjectFollowOpportunity"); print $form->textwithpicto($langs->trans("ProjectFollowOpportunity"), $htmltext); print '
    '; } if (empty($conf->global->PROJECT_HIDE_TASKS)) { - print 'usage_task ? ' checked="checked"' : '')).'"> '; + print 'usage_task ? ' checked="checked"' : '')).'"> '; $htmltext = $langs->trans("ProjectFollowTasks"); print $form->textwithpicto($langs->trans("ProjectFollowTasks"), $htmltext); print '
    '; } - if (! empty($conf->global->PROJECT_BILL_TIME_SPENT)) + if (!empty($conf->global->PROJECT_BILL_TIME_SPENT)) { - print 'usage_bill_time ? ' checked="checked"' : '')).'"> '; + print 'usage_bill_time ? ' checked="checked"' : '')).'"> '; $htmltext = $langs->trans("ProjectBillTimeDescription"); print $form->textwithpicto($langs->trans("BillTime"), $htmltext); print '
    '; @@ -1010,7 +1010,7 @@ elseif ($object->id > 0) else print $langs->trans('PrivateProject'); print '
    '.$langs->trans("OpportunityStatus").''; @@ -1036,10 +1036,10 @@ elseif ($object->id > 0) // Date start - end print '
    '.$langs->trans("DateStart").' - '.$langs->trans("DateEnd").''; $start = dol_print_date($object->date_start, 'day'); - print ($start?$start:'?'); + print ($start ? $start : '?'); $end = dol_print_date($object->date_end, 'day'); print ' - '; - print ($end?$end:'?'); + print ($end ? $end : '?'); if ($object->hasDelay()) print img_warning("Late"); print '
    '; @@ -1067,7 +1067,7 @@ elseif ($object->id > 0) print '
    '.$langs->trans("Categories").''; print $form->showCategories($object->id, 'project', 1); print "
    '.$langs->trans("Subscription").''; - if (! empty($conf->global->MEMBER_NEWFORM_EDITAMOUNT)) + if (!empty($conf->global->MEMBER_NEWFORM_EDITAMOUNT)) { print ''; } @@ -730,7 +730,7 @@ dol_fiche_end(); // Save print '
    '; print ''; -if (! empty($backtopage)) +if (!empty($backtopage)) { print '     '; } diff --git a/htdocs/public/members/public_card.php b/htdocs/public/members/public_card.php index e10186458fa..32a83e5c432 100644 --- a/htdocs/public/members/public_card.php +++ b/htdocs/public/members/public_card.php @@ -25,14 +25,14 @@ * \brief File to show a public card of a member */ -if (! defined('NOLOGIN')) define("NOLOGIN", 1); // This means this output page does not require to be logged. -if (! defined('NOCSRFCHECK')) define("NOCSRFCHECK", 1); // We accept to go on this page from external web site. -if (! defined('NOIPCHECK')) define('NOIPCHECK', '1'); // Do not check IP defined into conf $dolibarr_main_restrict_ip +if (!defined('NOLOGIN')) define("NOLOGIN", 1); // This means this output page does not require to be logged. +if (!defined('NOCSRFCHECK')) define("NOCSRFCHECK", 1); // We accept to go on this page from external web site. +if (!defined('NOIPCHECK')) define('NOIPCHECK', '1'); // Do not check IP defined into conf $dolibarr_main_restrict_ip // For MultiCompany module. // Do not use GETPOST here, function is not defined and define must be done before including main.inc.php // TODO This should be useless. Because entity must be retreive from object ref and not from url. -$entity=(! empty($_GET['entity']) ? (int) $_GET['entity'] : (! empty($_POST['entity']) ? (int) $_POST['entity'] : 1)); +$entity = (!empty($_GET['entity']) ? (int) $_GET['entity'] : (!empty($_POST['entity']) ? (int) $_POST['entity'] : 1)); if (is_numeric($entity)) define("DOLENTITY", $entity); require '../../main.inc.php'; @@ -46,7 +46,7 @@ if (empty($conf->adherent->enabled)) accessforbidden('', 0, 0, 1); $langs->loadLangs(array("main", "members", "companies", "other")); -$id=GETPOST('id', 'int'); +$id = GETPOST('id', 'int'); $object = new Adherent($db); $extrafields = new ExtraFields($db); @@ -64,9 +64,9 @@ $extrafields = new ExtraFields($db); * View */ -$morehead=''; -if (! empty($conf->global->MEMBER_PUBLIC_CSS)) $morehead=''; -else $morehead=''; +$morehead = ''; +if (!empty($conf->global->MEMBER_PUBLIC_CSS)) $morehead = ''; +else $morehead = ''; llxHeaderVierge($langs->trans("MemberCard"), $morehead); @@ -75,9 +75,9 @@ $extrafields->fetch_name_optionals_label($object->table_element); if ($id > 0) { - $res=$object->fetch($id); + $res = $object->fetch($id); if ($res < 0) { dol_print_error($db, $object->error); exit; } - $res=$object->fetch_optionals(); + $res = $object->fetch_optionals(); print load_fiche_titre($langs->trans("MemberCard"), '', ''); @@ -101,7 +101,7 @@ if ($id > 0) print '
    '.$langs->trans("EMail").''.$object->email.' 
    '.$langs->trans("Birthday").''.dol_print_date($object->birth, 'day').'
    URL Photo'; diff --git a/htdocs/public/members/public_list.php b/htdocs/public/members/public_list.php index 5dce7eed5c6..560d7dbd0a9 100644 --- a/htdocs/public/members/public_list.php +++ b/htdocs/public/members/public_list.php @@ -24,14 +24,14 @@ * \brief File sample to list members */ -if (! defined('NOLOGIN')) define("NOLOGIN", 1); // This means this output page does not require to be logged. -if (! defined('NOCSRFCHECK')) define("NOCSRFCHECK", 1); // We accept to go on this page from external web site. -if (! defined('NOIPCHECK')) define('NOIPCHECK', '1'); // Do not check IP defined into conf $dolibarr_main_restrict_ip +if (!defined('NOLOGIN')) define("NOLOGIN", 1); // This means this output page does not require to be logged. +if (!defined('NOCSRFCHECK')) define("NOCSRFCHECK", 1); // We accept to go on this page from external web site. +if (!defined('NOIPCHECK')) define('NOIPCHECK', '1'); // Do not check IP defined into conf $dolibarr_main_restrict_ip // For MultiCompany module. // Do not use GETPOST here, function is not defined and define must be done before including main.inc.php // TODO This should be useless. Because entity must be retreive from object ref and not from url. -$entity=(! empty($_GET['entity']) ? (int) $_GET['entity'] : (! empty($_POST['entity']) ? (int) $_POST['entity'] : 1)); +$entity = (!empty($_GET['entity']) ? (int) $_GET['entity'] : (!empty($_POST['entity']) ? (int) $_POST['entity'] : 1)); if (is_numeric($entity)) define("DOLENTITY", $entity); require '../../main.inc.php'; @@ -79,18 +79,18 @@ function llxFooterVierge() $sortfield = GETPOST("sortfield", 'alpha'); $sortorder = GETPOST("sortorder", 'alpha'); -$limit = GETPOST('limit', 'int')?GETPOST('limit', 'int'):$conf->liste_limit; +$limit = GETPOST('limit', 'int') ?GETPOST('limit', 'int') : $conf->liste_limit; $page = GETPOST("page", 'int'); if (empty($page) || $page == -1) { $page = 0; } // If $page is not defined, or '' or -1 $offset = $limit * $page; $pageprev = $page - 1; $pagenext = $page + 1; -$filter=GETPOST('filter'); -$statut=GETPOST('statut'); +$filter = GETPOST('filter'); +$statut = GETPOST('statut'); -if (! $sortorder) { $sortorder="ASC"; } -if (! $sortfield) { $sortfield="lastname"; } +if (!$sortorder) { $sortorder = "ASC"; } +if (!$sortfield) { $sortfield = "lastname"; } /* @@ -99,19 +99,19 @@ if (! $sortfield) { $sortfield="lastname"; } $form = new Form($db); -$morehead=''; -if (! empty($conf->global->MEMBER_PUBLIC_CSS)) $morehead=''; -else $morehead=''; +$morehead = ''; +if (!empty($conf->global->MEMBER_PUBLIC_CSS)) $morehead = ''; +else $morehead = ''; llxHeaderVierge($langs->trans("ListOfValidatedPublicMembers"), $morehead); $sql = "SELECT rowid, firstname, lastname, societe, zip, town, email, birth, photo"; -$sql.= " FROM ".MAIN_DB_PREFIX."adherent"; -$sql.= " WHERE entity = ".$entity; -$sql.= " AND statut = 1"; -$sql.= " AND public = 1"; -$sql.= $db->order($sortfield, $sortorder); -$sql.= $db->plimit($conf->liste_limit+1, $offset); +$sql .= " FROM ".MAIN_DB_PREFIX."adherent"; +$sql .= " WHERE entity = ".$entity; +$sql .= " AND statut = 1"; +$sql .= " AND public = 1"; +$sql .= $db->order($sortfield, $sortorder); +$sql .= $db->plimit($conf->liste_limit + 1, $offset); //$sql = "SELECT d.rowid, d.firstname, d.lastname, d.societe, zip, town, d.email, t.libelle as type, d.morphy, d.statut, t.subscription"; //$sql .= " FROM ".MAIN_DB_PREFIX."adherent as d, ".MAIN_DB_PREFIX."adherent_type as t"; //$sql .= " WHERE d.fk_adherent_type = t.rowid AND d.statut = $statut"; @@ -123,9 +123,9 @@ if ($result) $num = $db->num_rows($result); $i = 0; - $param="&statut=$statut&sortorder=$sortorder&sortfield=$sortfield"; + $param = "&statut=$statut&sortorder=$sortorder&sortfield=$sortfield"; print_barre_liste($langs->trans("ListOfValidatedPublicMembers"), $page, $_SERVER["PHP_SELF"], $param, $sortfield, $sortorder, '', $num, 0, ''); - print ''; + print '
    '; print ''; print ''; diff --git a/htdocs/public/onlinesign/newonlinesign.php b/htdocs/public/onlinesign/newonlinesign.php index 6a0748f8f84..7ffc0908c4e 100644 --- a/htdocs/public/onlinesign/newonlinesign.php +++ b/htdocs/public/onlinesign/newonlinesign.php @@ -26,13 +26,13 @@ * \brief File to offer a way to make an online signature for a particular Dolibarr entity */ -define("NOLOGIN", 1); // This means this output page does not require to be logged. -define("NOCSRFCHECK", 1); // We accept to go on this page from external web site. +define("NOLOGIN", 1); // This means this output page does not require to be logged. +define("NOCSRFCHECK", 1); // We accept to go on this page from external web site. // For MultiCompany module. // Do not use GETPOST here, function is not defined and define must be done before including main.inc.php // TODO This should be useless. Because entity must be retreive from object ref and not from url. -$entity=(! empty($_GET['entity']) ? (int) $_GET['entity'] : (! empty($_POST['entity']) ? (int) $_POST['entity'] : 1)); +$entity = (!empty($_GET['entity']) ? (int) $_GET['entity'] : (!empty($_POST['entity']) ? (int) $_POST['entity'] : 1)); if (is_numeric($entity)) define("DOLENTITY", $entity); require '../../main.inc.php'; @@ -46,7 +46,7 @@ require_once DOL_DOCUMENT_ROOT.'/product/class/product.class.php'; $langs->loadLangs(array("main", "other", "dict", "bills", "companies", "errors", "paybox")); -$action=GETPOST('action', 'alpha'); +$action = GETPOST('action', 'alpha'); // Input are: // type ('invoice','order','contractline'), @@ -55,15 +55,15 @@ $action=GETPOST('action', 'alpha'); // tag (a free text, required if type is empty) // currency (iso code) -$suffix=GETPOST("suffix", 'alpha'); -$source=GETPOST("source", 'alpha'); -$ref=$REF=GETPOST("ref", 'alpha'); +$suffix = GETPOST("suffix", 'alpha'); +$source = GETPOST("source", 'alpha'); +$ref = $REF = GETPOST("ref", 'alpha'); -if (empty($source)) $source='proposal'; +if (empty($source)) $source = 'proposal'; -if (! $action) +if (!$action) { - if ($source && ! $ref) + if ($source && !$ref) { print $langs->trans('ErrorBadParameters')." - ref missing"; exit; @@ -71,8 +71,8 @@ if (! $action) } -$paymentmethod=''; -$validpaymentmethod=array(); +$paymentmethod = ''; +$validpaymentmethod = array(); @@ -80,34 +80,34 @@ $validpaymentmethod=array(); // Define $urlwithroot //$urlwithouturlroot=preg_replace('/'.preg_quote(DOL_URL_ROOT,'/').'$/i','',trim($dolibarr_main_url_root)); //$urlwithroot=$urlwithouturlroot.DOL_URL_ROOT; // This is to use external domain name found into config file -$urlwithroot=DOL_MAIN_URL_ROOT; // This is to use same domain name than current. For Paypal payment, we can use internal URL like localhost. +$urlwithroot = DOL_MAIN_URL_ROOT; // This is to use same domain name than current. For Paypal payment, we can use internal URL like localhost. // Complete urls for post treatment -$SECUREKEY=GETPOST("securekey"); // Secure key +$SECUREKEY = GETPOST("securekey"); // Secure key -if (! empty($source)) +if (!empty($source)) { - $urlok.='source='.urlencode($source).'&'; - $urlko.='source='.urlencode($source).'&'; + $urlok .= 'source='.urlencode($source).'&'; + $urlko .= 'source='.urlencode($source).'&'; } -if (! empty($REF)) +if (!empty($REF)) { - $urlok.='ref='.urlencode($REF).'&'; - $urlko.='ref='.urlencode($REF).'&'; + $urlok .= 'ref='.urlencode($REF).'&'; + $urlko .= 'ref='.urlencode($REF).'&'; } -if (! empty($SECUREKEY)) +if (!empty($SECUREKEY)) { - $urlok.='securekey='.urlencode($SECUREKEY).'&'; - $urlko.='securekey='.urlencode($SECUREKEY).'&'; + $urlok .= 'securekey='.urlencode($SECUREKEY).'&'; + $urlko .= 'securekey='.urlencode($SECUREKEY).'&'; } -if (! empty($entity)) +if (!empty($entity)) { - $urlok.='entity='.urlencode($entity).'&'; - $urlko.='entity='.urlencode($entity).'&'; + $urlok .= 'entity='.urlencode($entity).'&'; + $urlko .= 'entity='.urlencode($entity).'&'; } -$urlok=preg_replace('/&$/', '', $urlok); // Remove last & -$urlko=preg_replace('/&$/', '', $urlko); // Remove last & +$urlok = preg_replace('/&$/', '', $urlok); // Remove last & +$urlko = preg_replace('/&$/', '', $urlko); // Remove last & $creditor = $mysoc->name; @@ -127,16 +127,16 @@ if ($action == 'dosign') * View */ -$head=''; -if (! empty($conf->global->MAIN_SIGN_CSS_URL)) $head=''."\n"; +$head = ''; +if (!empty($conf->global->MAIN_SIGN_CSS_URL)) $head = ''."\n"; -$conf->dol_hide_topmenu=1; -$conf->dol_hide_leftmenu=1; +$conf->dol_hide_topmenu = 1; +$conf->dol_hide_leftmenu = 1; llxHeader($head, $langs->trans("OnlineSignature"), '', '', 0, 0, '', '', '', 'onlinepaymentbody'); // Check link validity -if (! empty($source) && in_array($ref, array('member_ref', 'contractline_ref', 'invoice_ref', 'order_ref', ''))) +if (!empty($source) && in_array($ref, array('member_ref', 'contractline_ref', 'invoice_ref', 'order_ref', ''))) { $langs->load("errors"); dol_print_error_email('BADREFINONLINESIGNFORM', $langs->trans("ErrorBadLinkSourceSetButBadValueForRef", $source, $ref)); @@ -161,24 +161,24 @@ print ''."\n"; print '
    '.dolGetFirstLastname($langs->trans("Firstname"), $langs->trans("Lastname")).'
    '."\n"; // Show logo (search order: logo defined by ONLINE_SIGN_LOGO_suffix, then ONLINE_SIGN_LOGO_, then small company logo, large company logo, theme logo, common logo) -$width=0; +$width = 0; // Define logo and logosmall -$logosmall=$mysoc->logo_small; -$logo=$mysoc->logo; -$paramlogo='ONLINE_SIGN_LOGO_'.$suffix; -if (! empty($conf->global->$paramlogo)) $logosmall=$conf->global->$paramlogo; -elseif (! empty($conf->global->ONLINE_SIGN_LOGO)) $logosmall=$conf->global->ONLINE_SIGN_LOGO; +$logosmall = $mysoc->logo_small; +$logo = $mysoc->logo; +$paramlogo = 'ONLINE_SIGN_LOGO_'.$suffix; +if (!empty($conf->global->$paramlogo)) $logosmall = $conf->global->$paramlogo; +elseif (!empty($conf->global->ONLINE_SIGN_LOGO)) $logosmall = $conf->global->ONLINE_SIGN_LOGO; //print ''."\n"; // Define urllogo -$urllogo=''; -if (! empty($logosmall) && is_readable($conf->mycompany->dir_output.'/logos/thumbs/'.$logosmall)) +$urllogo = ''; +if (!empty($logosmall) && is_readable($conf->mycompany->dir_output.'/logos/thumbs/'.$logosmall)) { - $urllogo=DOL_URL_ROOT.'/viewimage.php?modulepart=mycompany&entity='.$conf->entity.'&file='.urlencode('logos/thumbs/'.$logosmall); + $urllogo = DOL_URL_ROOT.'/viewimage.php?modulepart=mycompany&entity='.$conf->entity.'&file='.urlencode('logos/thumbs/'.$logosmall); } -elseif (! empty($logo) && is_readable($conf->mycompany->dir_output.'/logos/'.$logo)) +elseif (!empty($logo) && is_readable($conf->mycompany->dir_output.'/logos/'.$logo)) { - $urllogo=DOL_URL_ROOT.'/viewimage.php?modulepart=mycompany&entity='.$conf->entity.'&file='.urlencode('logos/'.$logo); - $width=96; + $urllogo = DOL_URL_ROOT.'/viewimage.php?modulepart=mycompany&entity='.$conf->entity.'&file='.urlencode('logos/'.$logo); + $width = 96; } // Output html code for logo if ($urllogo) @@ -191,18 +191,18 @@ if ($urllogo) } // Output introduction text -$text=''; -if (! empty($conf->global->ONLINE_SIGN_NEWFORM_TEXT)) +$text = ''; +if (!empty($conf->global->ONLINE_SIGN_NEWFORM_TEXT)) { $langs->load("members"); - if (preg_match('/^\((.*)\)$/', $conf->global->ONLINE_SIGN_NEWFORM_TEXT, $reg)) $text.=$langs->trans($reg[1])."
    \n"; - else $text.=$conf->global->ONLINE_SIGN_NEWFORM_TEXT."
    \n"; - $text=''."\n"; + if (preg_match('/^\((.*)\)$/', $conf->global->ONLINE_SIGN_NEWFORM_TEXT, $reg)) $text .= $langs->trans($reg[1])."
    \n"; + else $text .= $conf->global->ONLINE_SIGN_NEWFORM_TEXT."
    \n"; + $text = ''."\n"; } if (empty($text)) { - $text.=''."\n"; - $text.=''."\n"; + $text .= ''."\n"; + $text .= ''."\n"; } print $text; @@ -211,47 +211,47 @@ print '

    '.$text.'

    '.$text.'

    '.$langs->trans("WelcomeOnOnlineSignaturePage", $mysoc->name).'
    '.$langs->trans("ThisScreenAllowsYouToSignDocFrom", $creditor).'


    '.$langs->trans("WelcomeOnOnlineSignaturePage", $mysoc->name).'
    '.$langs->trans("ThisScreenAllowsYouToSignDocFrom", $creditor).'

    '; print ''; print ''."\n"; -$found=false; -$error=0; -$var=false; +$found = false; +$error = 0; +$var = false; // Payment on customer order if ($source == 'proposal') { - $found=true; + $found = true; $langs->load("proposal"); require_once DOL_DOCUMENT_ROOT.'/comm/propal/class/propal.class.php'; - $proposal=new Propal($db); - $result=$proposal->fetch('', $ref); + $proposal = new Propal($db); + $result = $proposal->fetch('', $ref); if ($result <= 0) { - $mesg=$proposal->error; + $mesg = $proposal->error; $error++; } else { - $result=$proposal->fetch_thirdparty($proposal->socid); + $result = $proposal->fetch_thirdparty($proposal->socid); } // Creditor - print ''."\n"; // Debitor - print ''."\n"; @@ -259,7 +259,7 @@ if ($source == 'proposal') -if (! $found && ! $mesg) $mesg=$langs->trans("ErrorBadParameters"); +if (!$found && !$mesg) $mesg = $langs->trans("ErrorBadParameters"); if ($mesg) print ''."\n"; @@ -268,7 +268,7 @@ print "\n"; if ($action != 'dosign') { - if ($found && ! $error) // We are in a management option and no error + if ($found && !$error) // We are in a management option and no error { } else diff --git a/htdocs/public/payment/newpayment.php b/htdocs/public/payment/newpayment.php index 4a3d08f6602..fe2822452a6 100644 --- a/htdocs/public/payment/newpayment.php +++ b/htdocs/public/payment/newpayment.php @@ -34,12 +34,12 @@ * \brief File to offer a way to make a payment for a particular Dolibarr object */ -define("NOLOGIN", 1); // This means this output page does not require to be logged. -define("NOCSRFCHECK", 1); // We accept to go on this page from external web site. +define("NOLOGIN", 1); // This means this output page does not require to be logged. +define("NOCSRFCHECK", 1); // We accept to go on this page from external web site. // For MultiCompany module. // Do not use GETPOST here, function is not defined and get of entity must be done before including main.inc.php -$entity=(! empty($_GET['entity']) ? (int) $_GET['entity'] : (! empty($_POST['entity']) ? (int) $_POST['entity'] : (! empty($_GET['e']) ? (int) $_GET['e'] : (! empty($_POST['e']) ? (int) $_POST['e'] : 1)))); +$entity = (!empty($_GET['entity']) ? (int) $_GET['entity'] : (!empty($_POST['entity']) ? (int) $_POST['entity'] : (!empty($_GET['e']) ? (int) $_GET['e'] : (!empty($_POST['e']) ? (int) $_POST['e'] : 1)))); if (is_numeric($entity)) define("DOLENTITY", $entity); require '../../main.inc.php'; @@ -52,9 +52,9 @@ require_once DOL_DOCUMENT_ROOT.'/societe/class/societeaccount.class.php'; // Security check // No check on module enabled. Done later according to $validpaymentmethod -$langs->loadLangs(array("main","other","dict","bills","companies","errors","paybox","paypal","stripe")); // File with generic data +$langs->loadLangs(array("main", "other", "dict", "bills", "companies", "errors", "paybox", "paypal", "stripe")); // File with generic data -$action=GETPOST('action', 'aZ09'); +$action = GETPOST('action', 'aZ09'); // Input are: // type ('invoice','order','contractline'), @@ -63,10 +63,10 @@ $action=GETPOST('action', 'aZ09'); // tag (a free text, required if type is empty) // currency (iso code) -$suffix=GETPOST("suffix", 'aZ09'); -$amount=price2num(GETPOST("amount", 'alpha')); -if (! GETPOST("currency", 'alpha')) $currency=$conf->currency; -else $currency=GETPOST("currency", 'alpha'); +$suffix = GETPOST("suffix", 'aZ09'); +$amount = price2num(GETPOST("amount", 'alpha')); +if (! GETPOST("currency", 'alpha')) $currency = $conf->currency; +else $currency = GETPOST("currency", 'alpha'); $source = GETPOST("s", 'alpha')?GETPOST("s", 'alpha'):GETPOST("source", 'alpha'); $download = GETPOST('d', 'int')?GETPOST('d', 'int'):GETPOST('download', 'int'); @@ -90,15 +90,15 @@ if (! $action) } -$paymentmethod=GETPOST('paymentmethod', 'alphanohtml')?GETPOST('paymentmethod', 'alphanohtml'):''; // Empty in most cases. Defined when a payment mode is forced -$validpaymentmethod=array(); +$paymentmethod = GETPOST('paymentmethod', 'alphanohtml') ?GETPOST('paymentmethod', 'alphanohtml') : ''; // Empty in most cases. Defined when a payment mode is forced +$validpaymentmethod = array(); // Detect $paymentmethod -foreach($_POST as $key => $val) +foreach ($_POST as $key => $val) { if (preg_match('/^dopayment_(.*)$/', $key, $reg)) { - $paymentmethod=$reg[1]; + $paymentmethod = $reg[1]; break; } } @@ -159,7 +159,7 @@ $urlko=preg_replace('/&$/', '', $urlko); // Remove last & -// Find valid payment methods +// Make special controls if ((empty($paymentmethod) || $paymentmethod == 'paypal') && ! empty($conf->paypal->enabled)) { @@ -186,45 +186,27 @@ if ((empty($paymentmethod) || $paymentmethod == 'paypal') && ! empty($conf->payp dol_print_error('', "Paypal setup param PAYPAL_API_SIGNATURE not defined"); return -1; } - - $validpaymentmethod['paypal']='valid'; } - if ((empty($paymentmethod) || $paymentmethod == 'paybox') && ! empty($conf->paybox->enabled)) { - $langs->load("paybox"); - - // TODO Chek setup is complete - - $validpaymentmethod['paybox']='valid'; + // No specific test for the moment } - if ((empty($paymentmethod) || $paymentmethod == 'stripe') && ! empty($conf->stripe->enabled)) { - $langs->load("stripe"); - - require_once DOL_DOCUMENT_ROOT.'/stripe/config.php'; - /* already included into /stripe/config.php - require_once DOL_DOCUMENT_ROOT.'/core/lib/company.lib.php'; - require_once DOL_DOCUMENT_ROOT.'/core/lib/payments.lib.php'; - require_once DOL_DOCUMENT_ROOT.'/stripe/lib/stripe.lib.php'; - require_once DOL_DOCUMENT_ROOT.'/includes/stripe/init.php'; - */ - - $validpaymentmethod['stripe']='valid'; + require_once DOL_DOCUMENT_ROOT.'/stripe/config.php'; // This include also /stripe/lib/stripe.lib.php, /includes/stripe/init.php, ... } -// TODO Replace previous set of $validpaymentmethod with this line: -//$validpaymentmethod = getValidOnlinePaymentMethods($paymentmethod); +// Initialize $validpaymentmethod +$validpaymentmethod = getValidOnlinePaymentMethods($paymentmethod); // Check security token -$valid=true; -if (! empty($conf->global->PAYMENT_SECURITY_TOKEN)) +$valid = true; +if (!empty($conf->global->PAYMENT_SECURITY_TOKEN)) { - if (! empty($conf->global->PAYMENT_SECURITY_TOKEN_UNIQUE)) + if (!empty($conf->global->PAYMENT_SECURITY_TOKEN_UNIQUE)) { - if ($source && $REF) $token = dol_hash($conf->global->PAYMENT_SECURITY_TOKEN . $source . $REF, 2); // Use the source in the hash to avoid duplicates if the references are identical + if ($source && $REF) $token = dol_hash($conf->global->PAYMENT_SECURITY_TOKEN.$source.$REF, 2); // Use the source in the hash to avoid duplicates if the references are identical else $token = dol_hash($conf->global->PAYMENT_SECURITY_TOKEN, 2); } else @@ -233,11 +215,11 @@ if (! empty($conf->global->PAYMENT_SECURITY_TOKEN)) } if ($SECUREKEY != $token) { - if (empty($conf->global->PAYMENT_SECURITY_ACCEPT_ANY_TOKEN)) $valid=false; // PAYMENT_SECURITY_ACCEPT_ANY_TOKEN is for backward compatibility + if (empty($conf->global->PAYMENT_SECURITY_ACCEPT_ANY_TOKEN)) $valid = false; // PAYMENT_SECURITY_ACCEPT_ANY_TOKEN is for backward compatibility else dol_syslog("Warning: PAYMENT_SECURITY_ACCEPT_ANY_TOKEN is on", LOG_WARNING); } - if (! $valid) + if (!$valid) { print '
    Bad value for key.
    '; //print 'SECUREKEY='.$SECUREKEY.' token='.$token.' valid='.$valid; @@ -245,7 +227,7 @@ if (! empty($conf->global->PAYMENT_SECURITY_TOKEN)) } } -if (! empty($paymentmethod) && empty($validpaymentmethod[$paymentmethod])) +if (!empty($paymentmethod) && empty($validpaymentmethod[$paymentmethod])) { print 'Payment module for payment method '.$paymentmethod.' is not active'; exit; @@ -257,11 +239,11 @@ if (empty($validpaymentmethod)) } // Common variables -$creditor=$mysoc->name; -$paramcreditor='ONLINE_PAYMENT_CREDITOR'; -$paramcreditorlong='ONLINE_PAYMENT_CREDITOR_'.$suffix; -if (! empty($conf->global->$paramcreditorlong)) $creditor=$conf->global->$paramcreditorlong; -elseif (! empty($conf->global->$paramcreditor)) $creditor=$conf->global->$paramcreditor; +$creditor = $mysoc->name; +$paramcreditor = 'ONLINE_PAYMENT_CREDITOR'; +$paramcreditorlong = 'ONLINE_PAYMENT_CREDITOR_'.$suffix; +if (!empty($conf->global->$paramcreditorlong)) $creditor = $conf->global->$paramcreditorlong; +elseif (!empty($conf->global->$paramcreditor)) $creditor = $conf->global->$paramcreditor; @@ -274,40 +256,40 @@ if ($action == 'dopayment') { if ($paymentmethod == 'paypal') { - $PAYPAL_API_PRICE=price2num(GETPOST("newamount", 'alpha'), 'MT'); - $PAYPAL_PAYMENT_TYPE='Sale'; + $PAYPAL_API_PRICE = price2num(GETPOST("newamount", 'alpha'), 'MT'); + $PAYPAL_PAYMENT_TYPE = 'Sale'; // Vars that are used as global var later in print_paypal_redirect() - $origfulltag=GETPOST("fulltag", 'alpha'); - $shipToName=GETPOST("shipToName", 'alpha'); - $shipToStreet=GETPOST("shipToStreet", 'alpha'); - $shipToCity=GETPOST("shipToCity", 'alpha'); - $shipToState=GETPOST("shipToState", 'alpha'); - $shipToCountryCode=GETPOST("shipToCountryCode", 'alpha'); - $shipToZip=GETPOST("shipToZip", 'alpha'); - $shipToStreet2=GETPOST("shipToStreet2", 'alpha'); - $phoneNum=GETPOST("phoneNum", 'alpha'); - $email=GETPOST("email", 'alpha'); - $desc=GETPOST("desc", 'alpha'); - $thirdparty_id=GETPOST('thirdparty_id', 'int'); + $origfulltag = GETPOST("fulltag", 'alpha'); + $shipToName = GETPOST("shipToName", 'alpha'); + $shipToStreet = GETPOST("shipToStreet", 'alpha'); + $shipToCity = GETPOST("shipToCity", 'alpha'); + $shipToState = GETPOST("shipToState", 'alpha'); + $shipToCountryCode = GETPOST("shipToCountryCode", 'alpha'); + $shipToZip = GETPOST("shipToZip", 'alpha'); + $shipToStreet2 = GETPOST("shipToStreet2", 'alpha'); + $phoneNum = GETPOST("phoneNum", 'alpha'); + $email = GETPOST("email", 'alpha'); + $desc = GETPOST("desc", 'alpha'); + $thirdparty_id = GETPOST('thirdparty_id', 'int'); // Special case for Paypal-Indonesia - if ($shipToCountryCode == 'ID' && ! preg_match('/\-/', $shipToState)) + if ($shipToCountryCode == 'ID' && !preg_match('/\-/', $shipToState)) { $shipToState = 'ID-'.$shipToState; } - $mesg=''; - if (empty($PAYPAL_API_PRICE) || ! is_numeric($PAYPAL_API_PRICE)) + $mesg = ''; + if (empty($PAYPAL_API_PRICE) || !is_numeric($PAYPAL_API_PRICE)) { - $mesg=$langs->trans("ErrorFieldRequired", $langs->transnoentitiesnoconv("Amount")); + $mesg = $langs->trans("ErrorFieldRequired", $langs->transnoentitiesnoconv("Amount")); $action = ''; } //elseif (empty($EMAIL)) $mesg=$langs->trans("ErrorFieldRequired",$langs->transnoentitiesnoconv("YourEMail")); //elseif (! isValidEMail($EMAIL)) $mesg=$langs->trans("ErrorBadEMail",$EMAIL); - elseif (! $origfulltag) + elseif (!$origfulltag) { - $mesg=$langs->trans("ErrorFieldRequired", $langs->transnoentitiesnoconv("PaymentCode")); + $mesg = $langs->trans("ErrorFieldRequired", $langs->transnoentitiesnoconv("PaymentCode")); $action = ''; } @@ -317,13 +299,13 @@ if ($action == 'dopayment') dol_syslog("newpayment.php call paypal api and do redirect", LOG_DEBUG); // Other - $PAYPAL_API_DEVISE="USD"; - if (! empty($currency)) $PAYPAL_API_DEVISE=$currency; + $PAYPAL_API_DEVISE = "USD"; + if (!empty($currency)) $PAYPAL_API_DEVISE = $currency; // Show var initialized by include fo paypal lib at begin of this file dol_syslog("Submit Paypal form", LOG_DEBUG); dol_syslog("PAYPAL_API_USER: $PAYPAL_API_USER", LOG_DEBUG); - dol_syslog("PAYPAL_API_PASSWORD: ".preg_replace('/./', '*', $PAYPAL_API_PASSWORD), LOG_DEBUG); // No password into log files + dol_syslog("PAYPAL_API_PASSWORD: ".preg_replace('/./', '*', $PAYPAL_API_PASSWORD), LOG_DEBUG); // No password into log files dol_syslog("PAYPAL_API_SIGNATURE: $PAYPAL_API_SIGNATURE", LOG_DEBUG); dol_syslog("PAYPAL_API_SANDBOX: $PAYPAL_API_SANDBOX", LOG_DEBUG); dol_syslog("PAYPAL_API_OK: $PAYPAL_API_OK", LOG_DEBUG); @@ -342,7 +324,7 @@ if ($action == 'dopayment') dol_syslog("email: $email", LOG_DEBUG); dol_syslog("desc: $desc", LOG_DEBUG); - dol_syslog("SCRIPT_URI: ".(empty($_SERVER["SCRIPT_URI"])?'':$_SERVER["SCRIPT_URI"]), LOG_DEBUG); // If defined script uri must match domain of PAYPAL_API_OK and PAYPAL_API_KO + dol_syslog("SCRIPT_URI: ".(empty($_SERVER["SCRIPT_URI"]) ? '' : $_SERVER["SCRIPT_URI"]), LOG_DEBUG); // If defined script uri must match domain of PAYPAL_API_OK and PAYPAL_API_KO // A redirect is added if API call successfull $mesg = print_paypal_redirect($PAYPAL_API_PRICE, $PAYPAL_API_DEVISE, $PAYPAL_PAYMENT_TYPE, $PAYPAL_API_OK, $PAYPAL_API_KO, $FULLTAG); @@ -354,23 +336,23 @@ if ($action == 'dopayment') if ($paymentmethod == 'paybox') { - $PRICE=price2num(GETPOST("newamount"), 'MT'); - $email=$conf->global->ONLINE_PAYMENT_SENDEMAIL; - $thirdparty_id=GETPOST('thirdparty_id', 'int'); + $PRICE = price2num(GETPOST("newamount"), 'MT'); + $email = $conf->global->ONLINE_PAYMENT_SENDEMAIL; + $thirdparty_id = GETPOST('thirdparty_id', 'int'); - $origfulltag=GETPOST("fulltag", 'alpha'); + $origfulltag = GETPOST("fulltag", 'alpha'); // Securekey into back url useless for back url and we need an url lower than 150. $urlok = preg_replace('/securekey=[^&]+/', '', $urlok); $urlko = preg_replace('/securekey=[^&]+/', '', $urlko); - $mesg=''; - if (empty($PRICE) || ! is_numeric($PRICE)) $mesg=$langs->trans("ErrorFieldRequired", $langs->transnoentitiesnoconv("Amount")); - elseif (empty($email)) $mesg=$langs->trans("ErrorFieldRequired", $langs->transnoentitiesnoconv("YourEMail")); - elseif (! isValidEMail($email)) $mesg=$langs->trans("ErrorBadEMail", $email); - elseif (! $origfulltag) $mesg=$langs->trans("ErrorFieldRequired", $langs->transnoentitiesnoconv("PaymentCode")); - elseif (dol_strlen($urlok) > 150) $mesg='Error urlok too long '.$urlok.'( Paybox requires 150, found '.strlen($urlok).')'; - elseif (dol_strlen($urlko) > 150) $mesg='Error urlko too long '.$urlko.'( Paybox requires 150, found '.strlen($urlok).')'; + $mesg = ''; + if (empty($PRICE) || !is_numeric($PRICE)) $mesg = $langs->trans("ErrorFieldRequired", $langs->transnoentitiesnoconv("Amount")); + elseif (empty($email)) $mesg = $langs->trans("ErrorFieldRequired", $langs->transnoentitiesnoconv("YourEMail")); + elseif (!isValidEMail($email)) $mesg = $langs->trans("ErrorBadEMail", $email); + elseif (!$origfulltag) $mesg = $langs->trans("ErrorFieldRequired", $langs->transnoentitiesnoconv("PaymentCode")); + elseif (dol_strlen($urlok) > 150) $mesg = 'Error urlok too long '.$urlok.'( Paybox requires 150, found '.strlen($urlok).')'; + elseif (dol_strlen($urlko) > 150) $mesg = 'Error urlko too long '.$urlko.'( Paybox requires 150, found '.strlen($urlok).')'; if (empty($mesg)) { @@ -399,25 +381,25 @@ if ($action == 'dopayment') // Called when choosing Stripe mode. // When using the Charge API architecture, this code is called after clicking the 'dopayment' with the Charge API architecture. // When using the PaymentIntent API architecture, the Stripe customer is already created when creating PaymentItent when showing payment page and the payment is already ok. -if ($action == 'charge' && ! empty($conf->stripe->enabled)) +if ($action == 'charge' && !empty($conf->stripe->enabled)) { $amountstripe = $amount; // Correct the amount according to unit of currency // See https://support.stripe.com/questions/which-zero-decimal-currencies-does-stripe-support - $arrayzerounitcurrency=array('BIF', 'CLP', 'DJF', 'GNF', 'JPY', 'KMF', 'KRW', 'MGA', 'PYG', 'RWF', 'VND', 'VUV', 'XAF', 'XOF', 'XPF'); - if (! in_array($currency, $arrayzerounitcurrency)) $amountstripe=$amountstripe * 100; + $arrayzerounitcurrency = array('BIF', 'CLP', 'DJF', 'GNF', 'JPY', 'KMF', 'KRW', 'MGA', 'PYG', 'RWF', 'VND', 'VUV', 'XAF', 'XOF', 'XPF'); + if (!in_array($currency, $arrayzerounitcurrency)) $amountstripe = $amountstripe * 100; dol_syslog("POST keys : ".join(',', array_keys($_POST)), LOG_DEBUG, 0, '_stripe'); dol_syslog("POST values: ".join(',', $_POST), LOG_DEBUG, 0, '_stripe'); $stripeToken = GETPOST("stripeToken", 'alpha'); $email = GETPOST("email", 'alpha'); - $thirdparty_id=GETPOST('thirdparty_id', 'int'); // Note that for payment following online registration for members, this is empty because thirdparty is created once payment is confirmed by paymentok.php - $dol_type=(GETPOST('s', 'alpha') ? GETPOST('s', 'alpha') : GETPOST('source', 'alpha')); - $dol_id=GETPOST('dol_id', 'int'); + $thirdparty_id = GETPOST('thirdparty_id', 'int'); // Note that for payment following online registration for members, this is empty because thirdparty is created once payment is confirmed by paymentok.php + $dol_type = (GETPOST('s', 'alpha') ? GETPOST('s', 'alpha') : GETPOST('source', 'alpha')); + $dol_id = GETPOST('dol_id', 'int'); $vatnumber = GETPOST('vatnumber', 'alpha'); - $savesource=GETPOSTISSET('savesource')?GETPOST('savesource', 'int'):1; + $savesource = GETPOSTISSET('savesource') ?GETPOST('savesource', 'int') : 1; dol_syslog("POST stripeToken = ".$stripeToken, LOG_DEBUG, 0, '_stripe'); dol_syslog("POST email = ".$email, LOG_DEBUG, 0, '_stripe'); @@ -434,12 +416,12 @@ if ($action == 'charge' && ! empty($conf->stripe->enabled)) $metadata = array( 'dol_version' => DOL_VERSION, 'dol_entity' => $conf->entity, - 'dol_company' => $mysoc->name, // Usefull when using multicompany + 'dol_company' => $mysoc->name, // Usefull when using multicompany 'dol_tax_num' => $vatnumber, 'ipaddress'=> getUserRemoteIP() ); - if (! empty($thirdparty_id)) $metadata["dol_thirdparty_id"] = $thirdparty_id; + if (!empty($thirdparty_id)) $metadata["dol_thirdparty_id"] = $thirdparty_id; if ($thirdparty_id > 0) { @@ -447,7 +429,7 @@ if ($action == 'charge' && ! empty($conf->stripe->enabled)) $service = 'StripeTest'; $servicestatus = 0; - if (! empty($conf->global->STRIPE_LIVE) && ! GETPOST('forcesandbox', 'int')) + if (!empty($conf->global->STRIPE_LIVE) && !GETPOST('forcesandbox', 'int')) { $service = 'StripeLive'; $servicestatus = 1; @@ -466,11 +448,11 @@ if ($action == 'charge' && ! empty($conf->stripe->enabled)) $error++; dol_syslog('Failed to get/create stripe customer for thirdparty id = '.$thirdparty_id.' and servicestatus = '.$servicestatus.': '.$stripe->error, LOG_ERR, 0, '_stripe'); setEventMessages('Failed to get/create stripe customer for thirdparty id = '.$thirdparty_id.' and servicestatus = '.$servicestatus.': '.$stripe->error, null, 'errors'); - $action=''; + $action = ''; } // Create Stripe card from Token - if (! $error) + if (!$error) { if ($savesource) { $card = $customer->sources->create(array("source" => $stripeToken, "metadata" => $metadata)); @@ -483,24 +465,24 @@ if ($action == 'charge' && ! empty($conf->stripe->enabled)) $error++; dol_syslog('Failed to create card record', LOG_WARNING, 0, '_stripe'); setEventMessages('Failed to create card record', null, 'errors'); - $action=''; + $action = ''; } else { - if (! empty($FULLTAG)) $metadata["FULLTAG"] = $FULLTAG; - if (! empty($dol_id)) $metadata["dol_id"] = $dol_id; - if (! empty($dol_type)) $metadata["dol_type"] = $dol_type; + if (!empty($FULLTAG)) $metadata["FULLTAG"] = $FULLTAG; + if (!empty($dol_id)) $metadata["dol_id"] = $dol_id; + if (!empty($dol_type)) $metadata["dol_type"] = $dol_type; dol_syslog("Create charge on card ".$card->id, LOG_DEBUG, 0, '_stripe'); $charge = \Stripe\Charge::create(array( 'amount' => price2num($amountstripe, 'MU'), 'currency' => $currency, - 'capture' => true, // Charge immediatly + 'capture' => true, // Charge immediatly 'description' => 'Stripe payment: '.$FULLTAG.' ref='.$ref, 'metadata' => $metadata, 'customer' => $customer->id, 'source' => $card, - 'statement_descriptor' => dol_trunc($FULLTAG, 10, 'right', 'UTF-8', 1), // 22 chars that appears on bank receipt (company + description) + 'statement_descriptor' => dol_trunc($FULLTAG, 10, 'right', 'UTF-8', 1), // 22 chars that appears on bank receipt (company + description) ), array("idempotency_key" => "$FULLTAG", "stripe_account" => "$stripeacc")); // Return $charge = array('id'=>'ch_XXXX', 'status'=>'succeeded|pending|failed', 'failure_code'=>, 'failure_message'=>...) if (empty($charge)) @@ -508,7 +490,7 @@ if ($action == 'charge' && ! empty($conf->stripe->enabled)) $error++; dol_syslog('Failed to charge card', LOG_WARNING, 0, '_stripe'); setEventMessages('Failed to charge card', null, 'errors'); - $action=''; + $action = ''; } } } @@ -530,7 +512,7 @@ if ($action == 'charge' && ! empty($conf->stripe->enabled)) $customer = \Stripe\Customer::create(array( 'email' => $email, - 'description' => ($email?'Anonymous customer for '.$email:'Anonymous customer'), + 'description' => ($email ? 'Anonymous customer for '.$email : 'Anonymous customer'), 'metadata' => $metadata, 'source' => $stripeToken // source can be a token OR array('object'=>'card', 'exp_month'=>xx, 'exp_year'=>xxxx, 'number'=>xxxxxxx, 'cvc'=>xxx, 'name'=>'Cardholder's full name', zip ?) )); @@ -551,9 +533,9 @@ if ($action == 'charge' && ! empty($conf->stripe->enabled)) } }*/ - if (! empty($FULLTAG)) $metadata["FULLTAG"] = $FULLTAG; - if (! empty($dol_id)) $metadata["dol_id"] = $dol_id; - if (! empty($dol_type)) $metadata["dol_type"] = $dol_type; + if (!empty($FULLTAG)) $metadata["FULLTAG"] = $FULLTAG; + if (!empty($dol_id)) $metadata["dol_id"] = $dol_id; + if (!empty($dol_type)) $metadata["dol_type"] = $dol_type; // The customer was just created with a source, so we can make a charge // with no card defined, the source just used for customer creation will be used. @@ -562,10 +544,10 @@ if ($action == 'charge' && ! empty($conf->stripe->enabled)) 'customer' => $customer->id, 'amount' => price2num($amountstripe, 'MU'), 'currency' => $currency, - 'capture' => true, // Charge immediatly + 'capture' => true, // Charge immediatly 'description' => 'Stripe payment: '.$FULLTAG.' ref='.$ref, 'metadata' => $metadata, - 'statement_descriptor' => dol_trunc($FULLTAG, 10, 'right', 'UTF-8', 1), // 22 chars that appears on bank receipt (company + description) + 'statement_descriptor' => dol_trunc($FULLTAG, 10, 'right', 'UTF-8', 1), // 22 chars that appears on bank receipt (company + description) ), array("idempotency_key" => "$FULLTAG", "stripe_account" => "$stripeacc")); // Return $charge = array('id'=>'ch_XXXX', 'status'=>'succeeded|pending|failed', 'failure_code'=>, 'failure_message'=>...) if (empty($charge)) @@ -573,79 +555,79 @@ if ($action == 'charge' && ! empty($conf->stripe->enabled)) $error++; dol_syslog('Failed to charge card', LOG_WARNING, 0, '_stripe'); setEventMessages('Failed to charge card', null, 'errors'); - $action=''; + $action = ''; } } - } catch(\Stripe\Error\Card $e) { + } catch (\Stripe\Error\Card $e) { // Since it's a decline, \Stripe\Error\Card will be caught $body = $e->getJsonBody(); $err = $body['error']; - print('Status is:' . $e->getHttpStatus() . "\n"); - print('Type is:' . $err['type'] . "\n"); - print('Code is:' . $err['code'] . "\n"); + print('Status is:'.$e->getHttpStatus()."\n"); + print('Type is:'.$err['type']."\n"); + print('Code is:'.$err['code']."\n"); // param is '' in this case - print('Param is:' . $err['param'] . "\n"); - print('Message is:' . $err['message'] . "\n"); + print('Param is:'.$err['param']."\n"); + print('Message is:'.$err['message']."\n"); $error++; - $errormessage="ErrorCard ".$e->getMessage()." err=".var_export($err, true); + $errormessage = "ErrorCard ".$e->getMessage()." err=".var_export($err, true); dol_syslog($errormessage, LOG_WARNING, 0, '_stripe'); setEventMessages($e->getMessage(), null, 'errors'); - $action=''; + $action = ''; } catch (\Stripe\Error\RateLimit $e) { // Too many requests made to the API too quickly $error++; - $errormessage="ErrorRateLimit ".$e->getMessage(); + $errormessage = "ErrorRateLimit ".$e->getMessage(); dol_syslog($errormessage, LOG_WARNING, 0, '_stripe'); setEventMessages($e->getMessage(), null, 'errors'); - $action=''; + $action = ''; } catch (\Stripe\Error\InvalidRequest $e) { // Invalid parameters were supplied to Stripe's API $error++; - $errormessage="ErrorInvalidRequest ".$e->getMessage(); + $errormessage = "ErrorInvalidRequest ".$e->getMessage(); dol_syslog($errormessage, LOG_WARNING, 0, '_stripe'); setEventMessages($e->getMessage(), null, 'errors'); - $action=''; + $action = ''; } catch (\Stripe\Error\Authentication $e) { // Authentication with Stripe's API failed // (maybe you changed API keys recently) $error++; - $errormessage="ErrorAuthentication ".$e->getMessage(); + $errormessage = "ErrorAuthentication ".$e->getMessage(); dol_syslog($errormessage, LOG_WARNING, 0, '_stripe'); setEventMessages($e->getMessage(), null, 'errors'); - $action=''; + $action = ''; } catch (\Stripe\Error\ApiConnection $e) { // Network communication with Stripe failed $error++; - $errormessage="ErrorApiConnection ".$e->getMessage(); + $errormessage = "ErrorApiConnection ".$e->getMessage(); dol_syslog($errormessage, LOG_WARNING, 0, '_stripe'); setEventMessages($e->getMessage(), null, 'errors'); - $action=''; + $action = ''; } catch (\Stripe\Error\Base $e) { // Display a very generic error to the user, and maybe send // yourself an email $error++; - $errormessage="ErrorBase ".$e->getMessage(); + $errormessage = "ErrorBase ".$e->getMessage(); dol_syslog($errormessage, LOG_WARNING, 0, '_stripe'); setEventMessages($e->getMessage(), null, 'errors'); - $action=''; + $action = ''; } catch (Exception $e) { // Something else happened, completely unrelated to Stripe $error++; - $errormessage="ErrorException ".$e->getMessage(); + $errormessage = "ErrorException ".$e->getMessage(); dol_syslog($errormessage, LOG_WARNING, 0, '_stripe'); setEventMessages($e->getMessage(), null, 'errors'); - $action=''; + $action = ''; } } // When using the PaymentIntent API architecture - if (! empty($conf->global->STRIPE_USE_INTENT_WITH_AUTOMATIC_CONFIRMATION)) + if (!empty($conf->global->STRIPE_USE_INTENT_WITH_AUTOMATIC_CONFIRMATION)) { $service = 'StripeTest'; $servicestatus = 0; - if (! empty($conf->global->STRIPE_LIVE) && ! GETPOST('forcesandbox', 'int')) + if (!empty($conf->global->STRIPE_LIVE) && !GETPOST('forcesandbox', 'int')) { $service = 'StripeLive'; $servicestatus = 1; @@ -669,22 +651,22 @@ if ($action == 'charge' && ! empty($conf->stripe->enabled)) $paymentintent = \Stripe\PaymentIntent::retrieve($paymentintent_id, array("stripe_account" => $stripeacc)); } } - catch(Exception $e) + catch (Exception $e) { $error++; - $errormessage="CantRetreivePaymentIntent ".$e->getMessage(); + $errormessage = "CantRetreivePaymentIntent ".$e->getMessage(); dol_syslog($errormessage, LOG_WARNING, 0, '_stripe'); setEventMessages($e->getMessage(), null, 'errors'); - $action=''; + $action = ''; } if ($paymentintent->status != 'succeeded') { $error++; - $errormessage="StatusOfRetreivedIntent is not succeeded: ".$e->getMessage(); + $errormessage = "StatusOfRetreivedIntent is not succeeded: ".$e->getMessage(); dol_syslog($errormessage, LOG_WARNING, 0, '_stripe'); setEventMessages($e->getMessage(), null, 'errors'); - $action=''; + $action = ''; } else { @@ -701,8 +683,8 @@ if ($action == 'charge' && ! empty($conf->stripe->enabled)) $_SESSION["FinalPaymentAmt"] = $amount; $_SESSION["currencyCodeType"] = $currency; $_SESSION["paymentType"] = ''; - $_SESSION['ipaddress'] = ($remoteip?$remoteip:'unknown'); // Payer ip - $_SESSION['payerID'] = is_object($customer)?$customer->id:''; + $_SESSION['ipaddress'] = ($remoteip ? $remoteip : 'unknown'); // Payer ip + $_SESSION['payerID'] = is_object($customer) ? $customer->id : ''; $_SESSION['TRANSACTIONID'] = (is_object($charge) ? $charge->id : (is_object($paymentintent) ? $paymentintent->id : '')); $_SESSION['errormessage'] = $errormessage; @@ -729,11 +711,11 @@ if ($action == 'charge' && ! empty($conf->stripe->enabled)) * View */ -$head=''; -if (! empty($conf->global->ONLINE_PAYMENT_CSS_URL)) $head=''."\n"; +$head = ''; +if (!empty($conf->global->ONLINE_PAYMENT_CSS_URL)) $head = ''."\n"; -$conf->dol_hide_topmenu=1; -$conf->dol_hide_leftmenu=1; +$conf->dol_hide_topmenu = 1; +$conf->dol_hide_leftmenu = 1; llxHeader($head, $langs->trans("PaymentForm"), '', '', 0, 0, '', '', '', 'onlinepaymentbody'); @@ -750,11 +732,11 @@ if ($source && in_array($ref, array('member_ref', 'contractline_ref', 'invoice_r // Show sandbox warning -if ((empty($paymentmethod) || $paymentmethod == 'paypal') && ! empty($conf->paypal->enabled) && (! empty($conf->global->PAYPAL_API_SANDBOX) || GETPOST('forcesandbox', 'int'))) // We can force sand box with param 'forcesandbox' +if ((empty($paymentmethod) || $paymentmethod == 'paypal') && !empty($conf->paypal->enabled) && (!empty($conf->global->PAYPAL_API_SANDBOX) || GETPOST('forcesandbox', 'int'))) // We can force sand box with param 'forcesandbox' { dol_htmloutput_mesg($langs->trans('YouAreCurrentlyInSandboxMode', 'Paypal'), '', 'warning'); } -if ((empty($paymentmethod) || $paymentmethod == 'stripe') && ! empty($conf->stripe->enabled) && (empty($conf->global->STRIPE_LIVE) || GETPOST('forcesandbox', 'int'))) +if ((empty($paymentmethod) || $paymentmethod == 'stripe') && !empty($conf->stripe->enabled) && (empty($conf->global->STRIPE_LIVE) || GETPOST('forcesandbox', 'int'))) { dol_htmloutput_mesg($langs->trans('YouAreCurrentlyInSandboxMode', 'Stripe'), '', 'warning'); } @@ -774,16 +756,16 @@ print "\n"; print ''."\n"; print ''."\n"; // Additionnal information for each payment system -if (! empty($conf->paypal->enabled)) +if (!empty($conf->paypal->enabled)) { print ''."\n"; print ''."\n"; } -if (! empty($conf->paybox->enabled)) +if (!empty($conf->paybox->enabled)) { print ''."\n"; } -if (! empty($conf->stripe->enabled)) +if (!empty($conf->stripe->enabled)) { print ''."\n"; } @@ -794,28 +776,28 @@ print "\n"; print '
    '.$langs->trans("ThisIsInformationOnDocumentToSign").' :
    '.$langs->trans("Creditor"); - print ''.$creditor.''; + print '
    '.$langs->trans("Creditor"); + print ''.$creditor.''; print ''; print '
    '.$langs->trans("ThirdParty"); - print ''.$proposal->thirdparty->name.''; + print '
    '.$langs->trans("ThirdParty"); + print ''.$proposal->thirdparty->name.''; // Object - $text=''.$langs->trans("SignatureProposalRef", $proposal->ref).''; - print '
    '.$langs->trans("Designation"); - print ''.$text; + $text = ''.$langs->trans("SignatureProposalRef", $proposal->ref).''; + print '
    '.$langs->trans("Designation"); + print ''.$text; print ''; print ''; print '

    '.$mesg.'
    '."\n"; // Show logo (search order: logo defined by PAYMENT_LOGO_suffix, then PAYMENT_LOGO, then small company logo, large company logo, theme logo, common logo) -$width=0; +$width = 0; // Define logo and logosmall -$logosmall=$mysoc->logo_small; -$logo=$mysoc->logo; -$paramlogo='ONLINE_PAYMENT_LOGO_'.$suffix; -if (! empty($conf->global->$paramlogo)) $logosmall=$conf->global->$paramlogo; -elseif (! empty($conf->global->ONLINE_PAYMENT_LOGO)) $logosmall=$conf->global->ONLINE_PAYMENT_LOGO; +$logosmall = $mysoc->logo_small; +$logo = $mysoc->logo; +$paramlogo = 'ONLINE_PAYMENT_LOGO_'.$suffix; +if (!empty($conf->global->$paramlogo)) $logosmall = $conf->global->$paramlogo; +elseif (!empty($conf->global->ONLINE_PAYMENT_LOGO)) $logosmall = $conf->global->ONLINE_PAYMENT_LOGO; //print ''."\n"; // Define urllogo -$urllogo=''; -$urllogofull=''; -if (! empty($logosmall) && is_readable($conf->mycompany->dir_output.'/logos/thumbs/'.$logosmall)) +$urllogo = ''; +$urllogofull = ''; +if (!empty($logosmall) && is_readable($conf->mycompany->dir_output.'/logos/thumbs/'.$logosmall)) { - $urllogo=DOL_URL_ROOT.'/viewimage.php?modulepart=mycompany&entity='.$conf->entity.'&file='.urlencode('logos/thumbs/'.$logosmall); - $urllogofull=$dolibarr_main_url_root.'/viewimage.php?modulepart=mycompany&entity='.$conf->entity.'&file='.urlencode('logos/thumbs/'.$logosmall); - $width=150; + $urllogo = DOL_URL_ROOT.'/viewimage.php?modulepart=mycompany&entity='.$conf->entity.'&file='.urlencode('logos/thumbs/'.$logosmall); + $urllogofull = $dolibarr_main_url_root.'/viewimage.php?modulepart=mycompany&entity='.$conf->entity.'&file='.urlencode('logos/thumbs/'.$logosmall); + $width = 150; } -elseif (! empty($logo) && is_readable($conf->mycompany->dir_output.'/logos/'.$logo)) +elseif (!empty($logo) && is_readable($conf->mycompany->dir_output.'/logos/'.$logo)) { - $urllogo=DOL_URL_ROOT.'/viewimage.php?modulepart=mycompany&entity='.$conf->entity.'&file='.urlencode('logos/'.$logo); - $urllogofull=$dolibarr_main_url_root.'/viewimage.php?modulepart=mycompany&entity='.$conf->entity.'&file='.urlencode('logos/'.$logo); - $width=150; + $urllogo = DOL_URL_ROOT.'/viewimage.php?modulepart=mycompany&entity='.$conf->entity.'&file='.urlencode('logos/'.$logo); + $urllogofull = $dolibarr_main_url_root.'/viewimage.php?modulepart=mycompany&entity='.$conf->entity.'&file='.urlencode('logos/'.$logo); + $width = 150; } // Output html code for logo @@ -829,18 +811,18 @@ if ($urllogo) } // Output introduction text -$text=''; -if (! empty($conf->global->PAYMENT_NEWFORM_TEXT)) +$text = ''; +if (!empty($conf->global->PAYMENT_NEWFORM_TEXT)) { $langs->load("members"); - if (preg_match('/^\((.*)\)$/', $conf->global->PAYMENT_NEWFORM_TEXT, $reg)) $text.=$langs->trans($reg[1])."
    \n"; - else $text.=$conf->global->PAYMENT_NEWFORM_TEXT."
    \n"; - $text=''."\n"; + if (preg_match('/^\((.*)\)$/', $conf->global->PAYMENT_NEWFORM_TEXT, $reg)) $text .= $langs->trans($reg[1])."
    \n"; + else $text .= $conf->global->PAYMENT_NEWFORM_TEXT."
    \n"; + $text = ''."\n"; } if (empty($text)) { - $text.=''."\n"; - $text.=''."\n"; + $text .= ''."\n"; + $text .= ''."\n"; } print $text; @@ -849,31 +831,31 @@ print ''; } - elseif($mysoc->localtax1_assuj=="1") + elseif ($mysoc->localtax1_assuj == "1") { print ''; } - elseif($mysoc->localtax2_assuj=="1") + elseif ($mysoc->localtax2_assuj == "1") { print ''; } // Type - Size print ''; @@ -1485,10 +1485,10 @@ else print ''; - if (! empty($conf->global->MAIN_MULTILANGS)) + if (!empty($conf->global->MAIN_MULTILANGS)) { print ''; print ''; } @@ -1499,18 +1499,18 @@ else print ''; print ''; print ''; } // Categories - if (! empty($conf->categorie->enabled) && ! empty($user->rights->categorie->lire)) + if (!empty($conf->categorie->enabled) && !empty($user->rights->categorie->lire)) { $langs->load('categories'); // Customer //if ($object->prospect || $object->client || (! $object->fournisseur && ! empty($conf->global->THIRDPARTY_CAN_HAVE_CATEGORY_EVEN_IF_NOT_CUSTOMER_PROSPECT_SUPPLIER))) { - print '"; @@ -1518,7 +1518,7 @@ else // Supplier //if ($object->fournisseur) { - print '"; @@ -1526,7 +1526,7 @@ else } // Multicurrency - if (! empty($conf->multicurrency->enabled)) + if (!empty($conf->multicurrency->enabled)) { print ''; print ''; @@ -1536,12 +1536,12 @@ else } // Other attributes - $parameters=array('colspan' => ' colspan="3"', 'colspanvalue' => '3'); - $reshook=$hookmanager->executeHooks('formObjectOptions', $parameters, $object, $action); // Note that $action and $object may have been modified by hook + $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)) { - print $object->showOptionals($extrafields, 'edit'); + print $object->showOptionals($extrafields, 'edit', $parameters); } // Assign a sale representative @@ -1550,7 +1550,7 @@ else print ''; @@ -1568,7 +1568,7 @@ else print '
    '; print ''; - if (! empty($backtopage)) + if (!empty($backtopage)) { print '     '; print ''; @@ -1576,7 +1576,7 @@ else else { print '     '; - print ''; + print ''; } print '
    '."\n"; @@ -1588,21 +1588,21 @@ else if ($socid) { - $res=$object->fetch_optionals(); + $res = $object->fetch_optionals(); //if ($res < 0) { dol_print_error($db); exit; } $head = societe_prepare_head($object); // Load object modCodeTiers - $module=(! empty($conf->global->SOCIETE_CODECLIENT_ADDON)?$conf->global->SOCIETE_CODECLIENT_ADDON:'mod_codeclient_leopard'); + $module = (!empty($conf->global->SOCIETE_CODECLIENT_ADDON) ? $conf->global->SOCIETE_CODECLIENT_ADDON : 'mod_codeclient_leopard'); if (substr($module, 0, 15) == 'mod_codeclient_' && substr($module, -3) == 'php') { - $module = substr($module, 0, dol_strlen($module)-4); + $module = substr($module, 0, dol_strlen($module) - 4); } - $dirsociete=array_merge(array('/core/modules/societe/'), $conf->modules_parts['societe']); + $dirsociete = array_merge(array('/core/modules/societe/'), $conf->modules_parts['societe']); foreach ($dirsociete as $dirroot) { - $res=dol_include_once($dirroot.$module.'.php'); + $res = dol_include_once($dirroot.$module.'.php'); if ($res) break; } $modCodeClient = new $module($db); @@ -1611,15 +1611,15 @@ else { $prefixCustomerIsUsed = $modCodeClient->verif_prefixIsUsed(); } - $module=$conf->global->SOCIETE_CODECLIENT_ADDON; + $module = $conf->global->SOCIETE_CODECLIENT_ADDON; if (substr($module, 0, 15) == 'mod_codeclient_' && substr($module, -3) == 'php') { - $module = substr($module, 0, dol_strlen($module)-4); + $module = substr($module, 0, dol_strlen($module) - 4); } - $dirsociete=array_merge(array('/core/modules/societe/'), $conf->modules_parts['societe']); + $dirsociete = array_merge(array('/core/modules/societe/'), $conf->modules_parts['societe']); foreach ($dirsociete as $dirroot) { - $res=dol_include_once($dirroot.$module.'.php'); + $res = dol_include_once($dirroot.$module.'.php'); if ($res) break; } $modCodeFournisseur = new $module($db); @@ -1634,25 +1634,25 @@ else if (GETPOSTISSET('name')) { // We overwrite with values if posted - $object->name = GETPOST('name', 'alpha'); + $object->name = GETPOST('name', 'alpha'); $object->prefix_comm = GETPOST('prefix_comm', 'alpha'); - $object->client = GETPOST('client', 'int'); + $object->client = GETPOST('client', 'int'); $object->code_client = GETPOST('customer_code', 'alpha'); $object->fournisseur = GETPOST('fournisseur', 'int'); - $object->code_fournisseur = GETPOST('supplier_code', 'alpha'); - $object->address = GETPOST('address', 'alpha'); - $object->zip = GETPOST('zipcode', 'alpha'); - $object->town = GETPOST('town', 'alpha'); - $object->country_id = GETPOST('country_id')?GETPOST('country_id', 'int'):$mysoc->country_id; - $object->state_id = GETPOST('state_id', 'int'); + $object->code_fournisseur = GETPOST('supplier_code', 'alpha'); + $object->address = GETPOST('address', 'alpha'); + $object->zip = GETPOST('zipcode', 'alpha'); + $object->town = GETPOST('town', 'alpha'); + $object->country_id = GETPOST('country_id') ?GETPOST('country_id', 'int') : $mysoc->country_id; + $object->state_id = GETPOST('state_id', 'int'); //$object->skype = GETPOST('skype', 'alpha'); //$object->twitter = GETPOST('twitter', 'alpha'); //$object->facebook = GETPOST('facebook', 'alpha'); //$object->linkedin = GETPOST('linkedin', 'alpha'); $object->socialnetworks = array(); - if (! empty($conf->socialnetworks->enabled)) { + if (!empty($conf->socialnetworks->enabled)) { foreach ($socialnetworks as $key => $value) { - if (GETPOSTISSET($key) && GETPOST($key, 'alphanohtml')!='') { + if (GETPOSTISSET($key) && GETPOST($key, 'alphanohtml') != '') { $object->socialnetworks[$key] = GETPOST($key, 'alphanohtml'); } } @@ -1668,15 +1668,15 @@ else $object->idprof4 = GETPOST('idprof4', 'alpha'); $object->idprof5 = GETPOST('idprof5', 'alpha'); $object->idprof6 = GETPOST('idprof6', 'alpha'); - $object->typent_id = GETPOST('typent_id', 'int'); - $object->effectif_id = GETPOST('effectif_id', 'int'); + $object->typent_id = GETPOST('typent_id', 'int'); + $object->effectif_id = GETPOST('effectif_id', 'int'); $object->barcode = GETPOST('barcode', 'alpha'); - $object->forme_juridique_code = GETPOST('forme_juridique_code', 'int'); - $object->default_lang = GETPOST('default_lang', 'alpha'); + $object->forme_juridique_code = GETPOST('forme_juridique_code', 'int'); + $object->default_lang = GETPOST('default_lang', 'alpha'); $object->tva_assuj = GETPOST('assujtva_value', 'int'); $object->tva_intra = GETPOST('tva_intra', 'alpha'); - $object->status = GETPOST('status', 'int'); + $object->status = GETPOST('status', 'int'); // Webservices url/key $object->webservices_url = GETPOST('webservices_url', 'custom', 0, FILTER_SANITIZE_URL); @@ -1685,32 +1685,32 @@ else //Incoterms if (!empty($conf->incoterm->enabled)) { - $object->fk_incoterms = GETPOST('incoterm_id', 'int'); - $object->location_incoterms = GETPOST('lcoation_incoterms', 'alpha'); + $object->fk_incoterms = GETPOST('incoterm_id', 'int'); + $object->location_incoterms = GETPOST('lcoation_incoterms', 'alpha'); } //Local Taxes $object->localtax1_assuj = GETPOST('localtax1assuj_value'); $object->localtax2_assuj = GETPOST('localtax2assuj_value'); - $object->localtax1_value =GETPOST('lt1'); - $object->localtax2_value =GETPOST('lt2'); + $object->localtax1_value = GETPOST('lt1'); + $object->localtax2_value = GETPOST('lt2'); // We set country_id, and country_code label of the chosen country if ($object->country_id > 0) { - $tmparray=getCountry($object->country_id, 'all'); - $object->country_code = $tmparray['code']; - $object->country = $tmparray['label']; + $tmparray = getCountry($object->country_id, 'all'); + $object->country_code = $tmparray['code']; + $object->country = $tmparray['label']; } } - if($object->localtax1_assuj==0){ - $sub=0; - }else{$sub=1;} - if($object->localtax2_assuj==0){ - $sub2=0; - }else{$sub2=1;} + if ($object->localtax1_assuj == 0) { + $sub = 0; + } else {$sub = 1; } + if ($object->localtax2_assuj == 0) { + $sub2 = 0; + } else {$sub2 = 1; } if ($conf->use_javascript_ajax) { @@ -1755,7 +1755,7 @@ else }); function init_customer_categ() { console.log("is customer or prospect = "+jQuery("#customerprospect").val()); - if (jQuery("#customerprospect").val() == 0 && (jQuery("#fournisseur").val() == 0 || '.(empty($conf->global->THIRDPARTY_CAN_HAVE_CATEGORY_EVEN_IF_NOT_CUSTOMER_PROSPECT_SUPPLIER)?'1':'0').')) + if (jQuery("#customerprospect").val() == 0 && (jQuery("#fournisseur").val() == 0 || '.(empty($conf->global->THIRDPARTY_CAN_HAVE_CATEGORY_EVEN_IF_NOT_CUSTOMER_PROSPECT_SUPPLIER) ? '1' : '0').')) { jQuery(".visibleifcustomer").hide(); } @@ -1801,10 +1801,10 @@ else dol_fiche_head($head, 'card', $langs->trans("ThirdParty"), 0, 'company'); print '
    '; - print '

    '.$text.'

    '.$text.'

    '.$langs->trans("WelcomeOnPaymentPage").'
    '.$langs->trans("ThisScreenAllowsYouToPay", $creditor).'


    '.$langs->trans("WelcomeOnPaymentPage").'
    '.$langs->trans("ThisScreenAllowsYouToPay", $creditor).'

    '; print ''; print ''."\n"; -$found=false; -$error=0; -$var=false; +$found = false; +$error = 0; +$var = false; $object = null; // Free payment -if (! $source) +if (!$source) { - $found=true; - $tag=GETPOST("tag", 'alpha'); - $fulltag="TAG=".$tag; + $found = true; + $tag = GETPOST("tag", 'alpha'); + $fulltag = "TAG=".$tag; // Creditor - print ''."\n"; // Amount - print ''."\n"; // Tag - print ''."\n"; @@ -903,51 +885,51 @@ if (! $source) // Payment on customer order if ($source == 'order') { - $found=true; + $found = true; $langs->load("orders"); require_once DOL_DOCUMENT_ROOT.'/commande/class/commande.class.php'; - $order=new Commande($db); - $result=$order->fetch('', $ref); + $order = new Commande($db); + $result = $order->fetch('', $ref); if ($result <= 0) { - $mesg=$order->error; + $mesg = $order->error; $error++; } else { - $result=$order->fetch_thirdparty($order->socid); + $result = $order->fetch_thirdparty($order->socid); } $object = $order; if ($action != 'dopayment') // Do not change amount if we just click on first dopayment { - $amount=$order->total_ttc; - if (GETPOST("amount", 'int')) $amount=GETPOST("amount", 'int'); - $amount=price2num($amount); + $amount = $order->total_ttc; + if (GETPOST("amount", 'int')) $amount = GETPOST("amount", 'int'); + $amount = price2num($amount); } - $fulltag='ORD='.$order->id.'.CUS='.$order->thirdparty->id; - if (! empty($TAG)) { $tag=$TAG; $fulltag.='.TAG='.$TAG; } - $fulltag=dol_string_unaccent($fulltag); + $fulltag = 'ORD='.$order->id.'.CUS='.$order->thirdparty->id; + if (!empty($TAG)) { $tag = $TAG; $fulltag .= '.TAG='.$TAG; } + $fulltag = dol_string_unaccent($fulltag); // Creditor - print ''."\n"; // Debitor - print ''."\n"; // Object - $text=''.$langs->trans("PaymentOrderRef", $order->ref).''; - if (GETPOST('desc', 'alpha')) $text=''.$langs->trans(GETPOST('desc', 'alpha')).''; - print ''."\n"; // Amount - print ''."\n"; // Tag - print ''."\n"; // Shipping address - $shipToName=$order->thirdparty->name; - $shipToStreet=$order->thirdparty->address; - $shipToCity=$order->thirdparty->town; - $shipToState=$order->thirdparty->state_code; - $shipToCountryCode=$order->thirdparty->country_code; - $shipToZip=$order->thirdparty->zip; - $shipToStreet2=''; - $phoneNum=$order->thirdparty->phone; + $shipToName = $order->thirdparty->name; + $shipToStreet = $order->thirdparty->address; + $shipToCity = $order->thirdparty->town; + $shipToState = $order->thirdparty->state_code; + $shipToCountryCode = $order->thirdparty->country_code; + $shipToZip = $order->thirdparty->zip; + $shipToStreet2 = ''; + $phoneNum = $order->thirdparty->phone; if ($shipToName && $shipToStreet && $shipToCity && $shipToCountryCode && $shipToZip) { print ''."\n"; @@ -1013,8 +995,8 @@ if ($source == 'order') if (is_object($order->thirdparty)) print ''."\n"; print ''."\n"; print ''."\n"; - $labeldesc=$langs->trans("Order").' '.$order->ref; - if (GETPOST('desc', 'alpha')) $labeldesc=GETPOST('desc', 'alpha'); + $labeldesc = $langs->trans("Order").' '.$order->ref; + if (GETPOST('desc', 'alpha')) $labeldesc = GETPOST('desc', 'alpha'); print ''."\n"; } @@ -1022,52 +1004,52 @@ if ($source == 'order') // Payment on customer invoice if ($source == 'invoice') { - $found=true; + $found = true; $langs->load("bills"); require_once DOL_DOCUMENT_ROOT.'/compta/facture/class/facture.class.php'; - $invoice=new Facture($db); - $result=$invoice->fetch('', $ref); + $invoice = new Facture($db); + $result = $invoice->fetch('', $ref); if ($result <= 0) { - $mesg=$invoice->error; + $mesg = $invoice->error; $error++; } else { - $result=$invoice->fetch_thirdparty($invoice->socid); + $result = $invoice->fetch_thirdparty($invoice->socid); } $object = $invoice; if ($action != 'dopayment') // Do not change amount if we just click on first dopayment { - $amount=price2num($invoice->total_ttc - ($invoice->getSommePaiement() + $invoice->getSumCreditNotesUsed() + $invoice->getSumDepositsUsed())); - if (GETPOST("amount", 'int')) $amount=GETPOST("amount", 'int'); - $amount=price2num($amount); + $amount = price2num($invoice->total_ttc - ($invoice->getSommePaiement() + $invoice->getSumCreditNotesUsed() + $invoice->getSumDepositsUsed())); + if (GETPOST("amount", 'int')) $amount = GETPOST("amount", 'int'); + $amount = price2num($amount); } - $fulltag='INV='.$invoice->id.'.CUS='.$invoice->thirdparty->id; + $fulltag = 'INV='.$invoice->id.'.CUS='.$invoice->thirdparty->id; //$fulltag.='.NAM='.strtr($invoice->thirdparty->name,"-"," "); - if (! empty($TAG)) { $tag=$TAG; $fulltag.='.TAG='.$TAG; } - $fulltag=dol_string_unaccent($fulltag); + if (!empty($TAG)) { $tag = $TAG; $fulltag .= '.TAG='.$TAG; } + $fulltag = dol_string_unaccent($fulltag); // Creditor - print ''."\n"; // Debitor - print ''."\n"; // Object - $text=''.$langs->trans("PaymentInvoiceRef", $invoice->ref).''; - if (GETPOST('desc', 'alpha')) $text=''.$langs->trans(GETPOST('desc', 'alpha')).''; - print ''."\n"; // Amount - print ''."\n"; // Tag - print ''."\n"; // Shipping address - $shipToName=$invoice->thirdparty->name; - $shipToStreet=$invoice->thirdparty->address; - $shipToCity=$invoice->thirdparty->town; - $shipToState=$invoice->thirdparty->state_code; - $shipToCountryCode=$invoice->thirdparty->country_code; - $shipToZip=$invoice->thirdparty->zip; - $shipToStreet2=''; - $phoneNum=$invoice->thirdparty->phone; + $shipToName = $invoice->thirdparty->name; + $shipToStreet = $invoice->thirdparty->address; + $shipToCity = $invoice->thirdparty->town; + $shipToState = $invoice->thirdparty->state_code; + $shipToCountryCode = $invoice->thirdparty->country_code; + $shipToZip = $invoice->thirdparty->zip; + $shipToStreet2 = ''; + $phoneNum = $invoice->thirdparty->phone; if ($shipToName && $shipToStreet && $shipToCity && $shipToCountryCode && $shipToZip) { print ''."\n"; @@ -1140,46 +1122,46 @@ if ($source == 'invoice') if (is_object($invoice->thirdparty)) print ''."\n"; print ''."\n"; print ''."\n"; - $labeldesc=$langs->trans("Invoice").' '.$invoice->ref; - if (GETPOST('desc', 'alpha')) $labeldesc=GETPOST('desc', 'alpha'); + $labeldesc = $langs->trans("Invoice").' '.$invoice->ref; + if (GETPOST('desc', 'alpha')) $labeldesc = GETPOST('desc', 'alpha'); print ''."\n"; } // Payment on contract line if ($source == 'contractline') { - $found=true; + $found = true; $langs->load("contracts"); require_once DOL_DOCUMENT_ROOT.'/contrat/class/contrat.class.php'; - $contract=new Contrat($db); - $contractline=new ContratLigne($db); + $contract = new Contrat($db); + $contractline = new ContratLigne($db); - $result=$contractline->fetch('', $ref); + $result = $contractline->fetch('', $ref); if ($result <= 0) { - $mesg=$contractline->error; + $mesg = $contractline->error; $error++; } else { if ($contractline->fk_contrat > 0) { - $result=$contract->fetch($contractline->fk_contrat); + $result = $contract->fetch($contractline->fk_contrat); if ($result > 0) { - $result=$contract->fetch_thirdparty($contract->socid); + $result = $contract->fetch_thirdparty($contract->socid); } else { - $mesg=$contract->error; + $mesg = $contract->error; $error++; } } else { - $mesg='ErrorRecordNotFound'; + $mesg = 'ErrorRecordNotFound'; $error++; } } @@ -1187,15 +1169,15 @@ if ($source == 'contractline') if ($action != 'dopayment') // Do not change amount if we just click on first dopayment { - $amount=$contractline->total_ttc; + $amount = $contractline->total_ttc; - if ($contractline->fk_product && ! empty($conf->global->PAYMENT_USE_NEW_PRICE_FOR_CONTRACTLINES)) + if ($contractline->fk_product && !empty($conf->global->PAYMENT_USE_NEW_PRICE_FOR_CONTRACTLINES)) { - $product=new Product($db); - $result=$product->fetch($contractline->fk_product); + $product = new Product($db); + $result = $product->fetch($contractline->fk_product); // We define price for product (TODO Put this in a method in product class) - if (! empty($conf->global->PRODUIT_MULTIPRICES)) + if (!empty($conf->global->PRODUIT_MULTIPRICES)) { $pu_ht = $product->multiprices[$contract->thirdparty->price_level]; $pu_ttc = $product->multiprices_ttc[$contract->thirdparty->price_level]; @@ -1208,7 +1190,7 @@ if ($source == 'contractline') $price_base_type = $product->price_base_type; } - $amount=$pu_ttc; + $amount = $pu_ttc; if (empty($amount)) { dol_print_error('', 'ErrorNoPriceDefinedForThisProduct'); @@ -1216,48 +1198,48 @@ if ($source == 'contractline') } } - if (GETPOST("amount", 'int')) $amount=GETPOST("amount", 'int'); - $amount=price2num($amount); + if (GETPOST("amount", 'int')) $amount = GETPOST("amount", 'int'); + $amount = price2num($amount); } - $fulltag='COL='.$contractline->id.'.CON='.$contract->id.'.CUS='.$contract->thirdparty->id.'.DAT='.dol_print_date(dol_now(), '%Y%m%d%H%M'); + $fulltag = 'COL='.$contractline->id.'.CON='.$contract->id.'.CUS='.$contract->thirdparty->id.'.DAT='.dol_print_date(dol_now(), '%Y%m%d%H%M'); //$fulltag.='.NAM='.strtr($contract->thirdparty->name,"-"," "); - if (! empty($TAG)) { $tag=$TAG; $fulltag.='.TAG='.$TAG; } - $fulltag=dol_string_unaccent($fulltag); + if (!empty($TAG)) { $tag = $TAG; $fulltag .= '.TAG='.$TAG; } + $fulltag = dol_string_unaccent($fulltag); - $qty=1; - if (GETPOST('qty')) $qty=GETPOST('qty'); + $qty = 1; + if (GETPOST('qty')) $qty = GETPOST('qty'); // Creditor - print ''."\n"; // Debitor - print ''."\n"; // Object - $text=''.$langs->trans("PaymentRenewContractId", $contract->ref, $contractline->ref).''; + $text = ''.$langs->trans("PaymentRenewContractId", $contract->ref, $contractline->ref).''; if ($contractline->fk_product) { $contractline->fetch_product(); - $text.='
    '.$contractline->product->ref.($contractline->product->label?' - '.$contractline->product->label:''); + $text .= '
    '.$contractline->product->ref.($contractline->product->label ? ' - '.$contractline->product->label : ''); } - if ($contractline->description) $text.='
    '.dol_htmlentitiesbr($contractline->description); + if ($contractline->description) $text .= '
    '.dol_htmlentitiesbr($contractline->description); //if ($contractline->date_fin_validite) { // $text.='
    '.$langs->trans("DateEndPlanned").': '; // $text.=dol_print_date($contractline->date_fin_validite); //} if ($contractline->date_fin_validite) { - $text.='
    '.$langs->trans("ExpiredSince").': '.dol_print_date($contractline->date_fin_validite); + $text .= '
    '.$langs->trans("ExpiredSince").': '.dol_print_date($contractline->date_fin_validite); } - if (GETPOST('desc', 'alpha')) $text=''.$langs->trans(GETPOST('desc', 'alpha')).''; - print ''."\n"; // Quantity - $label=$langs->trans("Quantity"); - $qty=1; - $duration=''; + $label = $langs->trans("Quantity"); + $qty = 1; + $duration = ''; if ($contractline->fk_product) { if ($contractline->product->isService() && $contractline->product->duration_value > 0) { - $label=$langs->trans("Duration"); + $label = $langs->trans("Duration"); // TODO Put this in a global method if ($contractline->product->duration_value > 1) { - $dur=array("h"=>$langs->trans("Hours"),"d"=>$langs->trans("DurationDays"),"w"=>$langs->trans("DurationWeeks"),"m"=>$langs->trans("DurationMonths"),"y"=>$langs->trans("DurationYears")); + $dur = array("h"=>$langs->trans("Hours"), "d"=>$langs->trans("DurationDays"), "w"=>$langs->trans("DurationWeeks"), "m"=>$langs->trans("DurationMonths"), "y"=>$langs->trans("DurationYears")); } else { - $dur=array("h"=>$langs->trans("Hour"),"d"=>$langs->trans("DurationDay"),"w"=>$langs->trans("DurationWeek"),"m"=>$langs->trans("DurationMonth"),"y"=>$langs->trans("DurationYear")); + $dur = array("h"=>$langs->trans("Hour"), "d"=>$langs->trans("DurationDay"), "w"=>$langs->trans("DurationWeek"), "m"=>$langs->trans("DurationMonth"), "y"=>$langs->trans("DurationYear")); } - $duration=$contractline->product->duration_value.' '.$dur[$contractline->product->duration_unit]; + $duration = $contractline->product->duration_value.' '.$dur[$contractline->product->duration_unit]; } } - print ''; - print ''; + print ''."\n"; // Amount - print ''."\n"; // Tag - print ''."\n"; // Shipping address - $shipToName=$contract->thirdparty->name; - $shipToStreet=$contract->thirdparty->address; - $shipToCity=$contract->thirdparty->town; - $shipToState=$contract->thirdparty->state_code; - $shipToCountryCode=$contract->thirdparty->country_code; - $shipToZip=$contract->thirdparty->zip; - $shipToStreet2=''; - $phoneNum=$contract->thirdparty->phone; + $shipToName = $contract->thirdparty->name; + $shipToStreet = $contract->thirdparty->address; + $shipToCity = $contract->thirdparty->town; + $shipToState = $contract->thirdparty->state_code; + $shipToCountryCode = $contract->thirdparty->country_code; + $shipToZip = $contract->thirdparty->zip; + $shipToStreet2 = ''; + $phoneNum = $contract->thirdparty->phone; if ($shipToName && $shipToStreet && $shipToCity && $shipToCountryCode && $shipToZip) { print ''."\n"; @@ -1350,71 +1332,71 @@ if ($source == 'contractline') if (is_object($contract->thirdparty)) print ''."\n"; print ''."\n"; print ''."\n"; - $labeldesc=$langs->trans("Contract").' '.$contract->ref; - if (GETPOST('desc', 'alpha')) $labeldesc=GETPOST('desc', 'alpha'); + $labeldesc = $langs->trans("Contract").' '.$contract->ref; + if (GETPOST('desc', 'alpha')) $labeldesc = GETPOST('desc', 'alpha'); print ''."\n"; } // Payment on member subscription if ($source == 'membersubscription') { - $found=true; + $found = true; $langs->load("members"); require_once DOL_DOCUMENT_ROOT.'/adherents/class/adherent.class.php'; require_once DOL_DOCUMENT_ROOT.'/adherents/class/subscription.class.php'; - $member=new Adherent($db); - $result=$member->fetch('', $ref); + $member = new Adherent($db); + $result = $member->fetch('', $ref); if ($result <= 0) { - $mesg=$member->error; + $mesg = $member->error; $error++; } else { $member->fetch_thirdparty(); - $subscription=new Subscription($db); + $subscription = new Subscription($db); } $object = $member; if ($action != 'dopayment') // Do not change amount if we just click on first dopayment { - $amount=$subscription->total_ttc; - if (GETPOST("amount", 'int')) $amount=GETPOST("amount", 'int'); - $amount=price2num($amount); + $amount = $subscription->total_ttc; + if (GETPOST("amount", 'int')) $amount = GETPOST("amount", 'int'); + $amount = price2num($amount); } - $fulltag='MEM='.$member->id.'.DAT='.dol_print_date(dol_now(), '%Y%m%d%H%M'); - if (! empty($TAG)) { $tag=$TAG; $fulltag.='.TAG='.$TAG; } - $fulltag=dol_string_unaccent($fulltag); + $fulltag = 'MEM='.$member->id.'.DAT='.dol_print_date(dol_now(), '%Y%m%d%H%M'); + if (!empty($TAG)) { $tag = $TAG; $fulltag .= '.TAG='.$TAG; } + $fulltag = dol_string_unaccent($fulltag); // Creditor - print ''."\n"; // Debitor - print ''."\n"; // Object - $text=''.$langs->trans("PaymentSubscription").''; - if (GETPOST('desc', 'alpha')) $text=''.$langs->trans(GETPOST('desc', 'alpha')).''; - print ''."\n"; if ($object->datefin > 0) { - print ''."\n"; } @@ -1422,57 +1404,57 @@ if ($source == 'membersubscription') { // Last subscription date - print ''."\n"; // Last subscription amount - print ''."\n"; - if (empty($amount) && ! GETPOST('newamount', 'alpha')) $_GET['newamount']=$member->last_subscription_amount; + if (empty($amount) && !GETPOST('newamount', 'alpha')) $_GET['newamount'] = $member->last_subscription_amount; } // Amount - print ''."\n"; // Tag - print ''."\n"; // Shipping address - $shipToName=$member->getFullName($langs); - $shipToStreet=$member->address; - $shipToCity=$member->town; - $shipToState=$member->state_code; - $shipToCountryCode=$member->country_code; - $shipToZip=$member->zip; - $shipToStreet2=''; - $phoneNum=$member->phone; + $shipToName = $member->getFullName($langs); + $shipToStreet = $member->address; + $shipToCity = $member->town; + $shipToState = $member->state_code; + $shipToCountryCode = $member->country_code; + $shipToZip = $member->zip; + $shipToStreet2 = ''; + $phoneNum = $member->phone; if ($shipToName && $shipToStreet && $shipToCity && $shipToCountryCode && $shipToZip) { print ''; @@ -1517,23 +1499,23 @@ if ($source == 'membersubscription') if (is_object($member->thirdparty)) print ''."\n"; print ''."\n"; $labeldesc = $langs->trans("PaymentSubscription"); - if (GETPOST('desc', 'alpha')) $labeldesc=GETPOST('desc', 'alpha'); + if (GETPOST('desc', 'alpha')) $labeldesc = GETPOST('desc', 'alpha'); print ''."\n"; } // Payment on donation if ($source == 'donation') { - $found=true; + $found = true; $langs->load("don"); require_once DOL_DOCUMENT_ROOT.'/don/class/don.class.php'; - $don=new Don($db); - $result=$don->fetch($ref); + $don = new Don($db); + $result = $don->fetch($ref); if ($result <= 0) { - $mesg=$don->error; + $mesg = $don->error; $error++; } else @@ -1544,76 +1526,76 @@ if ($source == 'donation') if ($action != 'dopayment') // Do not change amount if we just click on first dopayment { - $amount=$subscription->total_ttc; - if (GETPOST("amount", 'int')) $amount=GETPOST("amount", 'int'); - $amount=price2num($amount); + $amount = $subscription->total_ttc; + if (GETPOST("amount", 'int')) $amount = GETPOST("amount", 'int'); + $amount = price2num($amount); } - $fulltag='DON='.$don->ref.'.DAT='.dol_print_date(dol_now(), '%Y%m%d%H%M'); - if (! empty($TAG)) { $tag=$TAG; $fulltag.='.TAG='.$TAG; } - $fulltag=dol_string_unaccent($fulltag); + $fulltag = 'DON='.$don->ref.'.DAT='.dol_print_date(dol_now(), '%Y%m%d%H%M'); + if (!empty($TAG)) { $tag = $TAG; $fulltag .= '.TAG='.$TAG; } + $fulltag = dol_string_unaccent($fulltag); // Creditor - print ''."\n"; // Debitor - print ''."\n"; // Object - $text=''.$langs->trans("PaymentDonation").''; - if (GETPOST('desc', 'alpha')) $text=''.$langs->trans(GETPOST('desc', 'alpha')).''; - print ''."\n"; // Amount - print ''."\n"; // Tag - print ''."\n"; // Shipping address - $shipToName=$don->getFullName($langs); - $shipToStreet=$don->address; - $shipToCity=$don->town; - $shipToState=$don->state_code; - $shipToCountryCode=$don->country_code; - $shipToZip=$don->zip; - $shipToStreet2=''; - $phoneNum=$don->phone; + $shipToName = $don->getFullName($langs); + $shipToStreet = $don->address; + $shipToCity = $don->town; + $shipToState = $don->state_code; + $shipToCountryCode = $don->country_code; + $shipToZip = $don->zip; + $shipToStreet2 = ''; + $phoneNum = $don->phone; if ($shipToName && $shipToStreet && $shipToCity && $shipToCountryCode && $shipToZip) { print ''; @@ -1658,12 +1640,12 @@ if ($source == 'donation') if (is_object($don->thirdparty)) print ''."\n"; print ''."\n"; $labeldesc = $langs->trans("PaymentSubscription"); - if (GETPOST('desc', 'alpha')) $labeldesc=GETPOST('desc', 'alpha'); + if (GETPOST('desc', 'alpha')) $labeldesc = GETPOST('desc', 'alpha'); print ''."\n"; } -if (! $found && ! $mesg) $mesg=$langs->trans("ErrorBadParameters"); +if (!$found && !$mesg) $mesg = $langs->trans("ErrorBadParameters"); if ($mesg) print ''."\n"; @@ -1674,7 +1656,7 @@ print "\n"; // Show all payment mode buttons (Stripe, Paypal, ...) if ($action != 'dopayment') { - if ($found && ! $error) // We are in a management option and no error + if ($found && !$error) // We are in a management option and no error { if ($source == 'order' && $object->billed) { @@ -1700,7 +1682,7 @@ if ($action != 'dopayment') // Buttons for all payments registration methods - if ((empty($paymentmethod) || $paymentmethod == 'paybox') && ! empty($conf->paybox->enabled)) + if ((empty($paymentmethod) || $paymentmethod == 'paybox') && !empty($conf->paybox->enabled)) { // If STRIPE_PICTO_FOR_PAYMENT is 'cb' we show a picto of a crdit card instead of paybox print '
    '; @@ -1721,7 +1703,7 @@ if ($action != 'dopayment') '; } - if ((empty($paymentmethod) || $paymentmethod == 'stripe') && ! empty($conf->stripe->enabled)) + if ((empty($paymentmethod) || $paymentmethod == 'stripe') && !empty($conf->stripe->enabled)) { // If STRIPE_PICTO_FOR_PAYMENT is 'cb' we show a picto of a crdit card instead of stripe print '
    '; @@ -1744,9 +1726,9 @@ if ($action != 'dopayment') '; } - if ((empty($paymentmethod) || $paymentmethod == 'paypal') && ! empty($conf->paypal->enabled)) + if ((empty($paymentmethod) || $paymentmethod == 'paypal') && !empty($conf->paypal->enabled)) { - if (empty($conf->global->PAYPAL_API_INTEGRAL_OR_PAYPALONLY)) $conf->global->PAYPAL_API_INTEGRAL_OR_PAYPALONLY='integral'; + if (empty($conf->global->PAYPAL_API_INTEGRAL_OR_PAYPALONLY)) $conf->global->PAYPAL_API_INTEGRAL_OR_PAYPALONLY = 'integral'; print '
    '; if ($conf->global->PAYPAL_API_INTEGRAL_OR_PAYPALONLY == 'integral') @@ -1853,7 +1835,7 @@ if (preg_match('/^dopayment/', $action)) // If we choosed/click on the payment print ''; print ''; - if (! empty($conf->global->STRIPE_USE_INTENT_WITH_AUTOMATIC_CONFIRMATION) || ! empty($conf->global->STRIPE_USE_NEW_CHECKOUT)) // Use a SCA ready method + if (!empty($conf->global->STRIPE_USE_INTENT_WITH_AUTOMATIC_CONFIRMATION) || !empty($conf->global->STRIPE_USE_NEW_CHECKOUT)) // Use a SCA ready method { require_once DOL_DOCUMENT_ROOT.'/stripe/class/stripe.class.php'; @@ -1870,10 +1852,10 @@ if (preg_match('/^dopayment/', $action)) // If we choosed/click on the payment $stripecu = null; if (is_object($object) && is_object($object->thirdparty)) $stripecu = $stripe->customerStripe($object->thirdparty, $stripeacc, $servicestatus, 1); - if (! empty($conf->global->STRIPE_USE_INTENT_WITH_AUTOMATIC_CONFIRMATION)) + if (!empty($conf->global->STRIPE_USE_INTENT_WITH_AUTOMATIC_CONFIRMATION)) { - $noidempotency_key = (GETPOSTISSET('noidempotency') ? GETPOST('noidempotency', 'int') : 0); // By default noidempotency is unset, so we must use a different tag/ref for each payment. If set, we can pay several times the same tag/ref. - $paymentintent=$stripe->getPaymentIntent($amount, $currency, $tag, 'Stripe payment: '.$fulltag.(is_object($object)?' ref='.$object->ref:''), $object, $stripecu, $stripeacc, $servicestatus, 0, 'automatic', false, null, 0, $noidempotency_key); + $noidempotency_key = (GETPOSTISSET('noidempotency') ? GETPOST('noidempotency', 'int') : 0); // By default noidempotency is unset, so we must use a different tag/ref for each payment. If set, we can pay several times the same tag/ref. + $paymentintent = $stripe->getPaymentIntent($amount, $currency, $tag, 'Stripe payment: '.$fulltag.(is_object($object) ? ' ref='.$object->ref : ''), $object, $stripecu, $stripeacc, $servicestatus, 0, 'automatic', false, null, 0, $noidempotency_key); // The paymentintnent has status 'requires_payment_method' (even if paymentintent was already payed) //var_dump($paymentintent); if ($stripe->error) setEventMessages($stripe->error, null, 'errors'); @@ -1886,7 +1868,7 @@ if (preg_match('/^dopayment/', $action)) // If we choosed/click on the payment
    '.$langs->trans("ThisIsInformationOnPayment").' :
    '.$langs->trans("Creditor"); - print ''.$creditor.''; + print '
    '.$langs->trans("Creditor"); + print ''.$creditor.''; print ''; print '
    '.$langs->trans("Amount"); + print '
    '.$langs->trans("Amount"); if (empty($amount)) print ' ('.$langs->trans("ToComplete").')'; - print ''; - if (empty($amount) || ! is_numeric($amount)) + print ''; + if (empty($amount) || !is_numeric($amount)) { print ''; print ''; @@ -889,8 +871,8 @@ if (! $source) print '
    '.$langs->trans("PaymentCode"); - print ''.$fulltag.''; + print '
    '.$langs->trans("PaymentCode"); + print ''.$fulltag.''; print ''; print ''; print '
    '.$langs->trans("Creditor"); - print ''.$creditor.''; + print '
    '.$langs->trans("Creditor"); + print ''.$creditor.''; print ''; print '
    '.$langs->trans("ThirdParty"); - print ''.$order->thirdparty->name.''; + print '
    '.$langs->trans("ThirdParty"); + print ''.$order->thirdparty->name.''; print '
    '.$langs->trans("Designation"); - print ''.$text; + $text = ''.$langs->trans("PaymentOrderRef", $order->ref).''; + if (GETPOST('desc', 'alpha')) $text = ''.$langs->trans(GETPOST('desc', 'alpha')).''; + print '
    '.$langs->trans("Designation"); + print ''.$text; print ''; print ''; print ''; @@ -961,10 +943,10 @@ if ($source == 'order') print '
    '.$langs->trans("Amount"); + print '
    '.$langs->trans("Amount"); if (empty($amount)) print ' ('.$langs->trans("ToComplete").')'; - print ''; - if (empty($amount) || ! is_numeric($amount)) + print ''; + if (empty($amount) || !is_numeric($amount)) { print ''; print ''; @@ -980,21 +962,21 @@ if ($source == 'order') print '
    '.$langs->trans("PaymentCode"); - print ''.$fulltag.''; + print '
    '.$langs->trans("PaymentCode"); + print ''.$fulltag.''; print ''; print ''; print '
    '.$langs->trans("Creditor"); - print ''.$creditor.''; + print '
    '.$langs->trans("Creditor"); + print ''.$creditor.''; print ''; print '
    '.$langs->trans("ThirdParty"); - print ''.$invoice->thirdparty->name.''; + print '
    '.$langs->trans("ThirdParty"); + print ''.$invoice->thirdparty->name.''; print '
    '.$langs->trans("Designation"); - print ''.$text; + $text = ''.$langs->trans("PaymentInvoiceRef", $invoice->ref).''; + if (GETPOST('desc', 'alpha')) $text = ''.$langs->trans(GETPOST('desc', 'alpha')).''; + print '
    '.$langs->trans("Designation"); + print ''.$text; print ''; print ''; print ''; @@ -1081,12 +1063,12 @@ if ($source == 'invoice') print '
    '.$langs->trans("PaymentAmount"); + print '
    '.$langs->trans("PaymentAmount"); if (empty($amount) && empty($object->paye)) print ' ('.$langs->trans("ToComplete").')'; - print ''; + print ''; if (empty($object->paye)) { - if (empty($amount) || ! is_numeric($amount)) + if (empty($amount) || !is_numeric($amount)) { print ''; print ''; @@ -1107,21 +1089,21 @@ if ($source == 'invoice') print '
    '.$langs->trans("PaymentCode"); - print ''.$fulltag.''; + print '
    '.$langs->trans("PaymentCode"); + print ''.$fulltag.''; print ''; print ''; print '
    '.$langs->trans("Creditor"); - print ''.$creditor.''; + print '
    '.$langs->trans("Creditor"); + print ''.$creditor.''; print ''; print '
    '.$langs->trans("ThirdParty"); - print ''.$contract->thirdparty->name.''; + print '
    '.$langs->trans("ThirdParty"); + print ''.$contract->thirdparty->name.''; print '
    '.$langs->trans("Designation"); - print ''.$text; + if (GETPOST('desc', 'alpha')) $text = ''.$langs->trans(GETPOST('desc', 'alpha')).''; + print '
    '.$langs->trans("Designation"); + print ''.$text; print ''; print ''; print ''; @@ -1271,37 +1253,37 @@ if ($source == 'contractline') print '
    '.$label.''.($duration?$duration:$qty).''; + print '
    '.$label.''.($duration ? $duration : $qty).''; print ''; print '
    '.$langs->trans("Amount"); + print '
    '.$langs->trans("Amount"); if (empty($amount)) print ' ('.$langs->trans("ToComplete").')'; - print ''; - if (empty($amount) || ! is_numeric($amount)) + print ''; + if (empty($amount) || !is_numeric($amount)) { print ''; print ''; @@ -1317,21 +1299,21 @@ if ($source == 'contractline') print '
    '.$langs->trans("PaymentCode"); - print ''.$fulltag.''; + print '
    '.$langs->trans("PaymentCode"); + print ''.$fulltag.''; print ''; print ''; print '
    '.$langs->trans("Creditor"); - print ''.$creditor.''; + print '
    '.$langs->trans("Creditor"); + print ''.$creditor.''; print ''; print '
    '.$langs->trans("Member"); - print ''; - if ($member->morphy == 'mor' && ! empty($member->societe)) print $member->societe; + print '
    '.$langs->trans("Member"); + print ''; + if ($member->morphy == 'mor' && !empty($member->societe)) print $member->societe; else print $member->getFullName($langs); print ''; print '
    '.$langs->trans("Designation"); - print ''.$text; + $text = ''.$langs->trans("PaymentSubscription").''; + if (GETPOST('desc', 'alpha')) $text = ''.$langs->trans(GETPOST('desc', 'alpha')).''; + print '
    '.$langs->trans("Designation"); + print ''.$text; print ''; print ''; print '
    '.$langs->trans("DateEndSubscription"); - print ''.dol_print_date($member->datefin, 'day'); + print '
    '.$langs->trans("DateEndSubscription"); + print ''.dol_print_date($member->datefin, 'day'); print '
    '.$langs->trans("LastSubscriptionDate"); - print ''.dol_print_date($member->last_subscription_date, 'day'); + print '
    '.$langs->trans("LastSubscriptionDate"); + print ''.dol_print_date($member->last_subscription_date, 'day'); print '
    '.$langs->trans("LastSubscriptionAmount"); - print ''.price($member->last_subscription_amount); + print '
    '.$langs->trans("LastSubscriptionAmount"); + print ''.price($member->last_subscription_amount); print '
    '.$langs->trans("Amount"); + print '
    '.$langs->trans("Amount"); if (empty($amount)) { if (empty($conf->global->MEMBER_NEWFORM_AMOUNT)) print ' ('.$langs->trans("ToComplete"); - if (! empty($conf->global->MEMBER_EXT_URL_SUBSCRIPTION_INFO)) print ' - '.$langs->trans("SeeHere").''; + if (!empty($conf->global->MEMBER_EXT_URL_SUBSCRIPTION_INFO)) print ' - '.$langs->trans("SeeHere").''; if (empty($conf->global->MEMBER_NEWFORM_AMOUNT)) print ')'; } - print ''; - $valtoshow=''; - if (empty($amount) || ! is_numeric($amount)) + print ''; + $valtoshow = ''; + if (empty($amount) || !is_numeric($amount)) { - $valtoshow=price2num(GETPOST("newamount", 'alpha'), 'MT'); + $valtoshow = price2num(GETPOST("newamount", 'alpha'), 'MT'); // force default subscription amount to value defined into constant... if (empty($valtoshow)) { - if (! empty($conf->global->MEMBER_NEWFORM_EDITAMOUNT)) { - if (! empty($conf->global->MEMBER_NEWFORM_AMOUNT)) { + if (!empty($conf->global->MEMBER_NEWFORM_EDITAMOUNT)) { + if (!empty($conf->global->MEMBER_NEWFORM_AMOUNT)) { $valtoshow = $conf->global->MEMBER_NEWFORM_AMOUNT; } } else { - if (! empty($conf->global->MEMBER_NEWFORM_AMOUNT)) { + if (!empty($conf->global->MEMBER_NEWFORM_AMOUNT)) { $amount = $conf->global->MEMBER_NEWFORM_AMOUNT; } } } } - if (empty($amount) || ! is_numeric($amount)) + if (empty($amount) || !is_numeric($amount)) { //$valtoshow=price2num(GETPOST("newamount",'alpha'),'MT'); - if (! empty($conf->global->MEMBER_MIN_AMOUNT) && $valtoshow) $valtoshow=max($conf->global->MEMBER_MIN_AMOUNT, $valtoshow); + if (!empty($conf->global->MEMBER_MIN_AMOUNT) && $valtoshow) $valtoshow = max($conf->global->MEMBER_MIN_AMOUNT, $valtoshow); print ''; print ''; } else { - $valtoshow=$amount; - if (! empty($conf->global->MEMBER_MIN_AMOUNT) && $valtoshow) $valtoshow=max($conf->global->MEMBER_MIN_AMOUNT, $valtoshow); + $valtoshow = $amount; + if (!empty($conf->global->MEMBER_MIN_AMOUNT) && $valtoshow) $valtoshow = max($conf->global->MEMBER_MIN_AMOUNT, $valtoshow); print ''.price($valtoshow).''; print ''; print ''; @@ -1483,21 +1465,21 @@ if ($source == 'membersubscription') print '
    '.$langs->trans("PaymentCode"); - print ''.$fulltag.''; + print '
    '.$langs->trans("PaymentCode"); + print ''.$fulltag.''; print ''; print ''; print '
    '.$langs->trans("Creditor"); - print ''.$creditor.''; + print '
    '.$langs->trans("Creditor"); + print ''.$creditor.''; print ''; print '
    '.$langs->trans("ThirdParty"); - print ''; - if ($don->morphy == 'mor' && ! empty($don->societe)) print $don->societe; + print '
    '.$langs->trans("ThirdParty"); + print ''; + if ($don->morphy == 'mor' && !empty($don->societe)) print $don->societe; else print $don->getFullName($langs); print ''; print '
    '.$langs->trans("Designation"); - print ''.$text; + $text = ''.$langs->trans("PaymentDonation").''; + if (GETPOST('desc', 'alpha')) $text = ''.$langs->trans(GETPOST('desc', 'alpha')).''; + print '
    '.$langs->trans("Designation"); + print ''.$text; print ''; print ''; print '
    '.$langs->trans("Amount"); + print '
    '.$langs->trans("Amount"); if (empty($amount)) { if (empty($conf->global->MEMBER_NEWFORM_AMOUNT)) print ' ('.$langs->trans("ToComplete"); - if (! empty($conf->global->MEMBER_EXT_URL_SUBSCRIPTION_INFO)) print ' - '.$langs->trans("SeeHere").''; + if (!empty($conf->global->MEMBER_EXT_URL_SUBSCRIPTION_INFO)) print ' - '.$langs->trans("SeeHere").''; if (empty($conf->global->MEMBER_NEWFORM_AMOUNT)) print ')'; } - print ''; - $valtoshow=''; - if (empty($amount) || ! is_numeric($amount)) + print ''; + $valtoshow = ''; + if (empty($amount) || !is_numeric($amount)) { - $valtoshow=price2num(GETPOST("newamount", 'alpha'), 'MT'); + $valtoshow = price2num(GETPOST("newamount", 'alpha'), 'MT'); // force default subscription amount to value defined into constant... if (empty($valtoshow)) { - if (! empty($conf->global->MEMBER_NEWFORM_EDITAMOUNT)) { - if (! empty($conf->global->MEMBER_NEWFORM_AMOUNT)) { + if (!empty($conf->global->MEMBER_NEWFORM_EDITAMOUNT)) { + if (!empty($conf->global->MEMBER_NEWFORM_AMOUNT)) { $valtoshow = $conf->global->MEMBER_NEWFORM_AMOUNT; } } else { - if (! empty($conf->global->MEMBER_NEWFORM_AMOUNT)) { + if (!empty($conf->global->MEMBER_NEWFORM_AMOUNT)) { $amount = $conf->global->MEMBER_NEWFORM_AMOUNT; } } } } - if (empty($amount) || ! is_numeric($amount)) + if (empty($amount) || !is_numeric($amount)) { //$valtoshow=price2num(GETPOST("newamount",'alpha'),'MT'); - if (! empty($conf->global->MEMBER_MIN_AMOUNT) && $valtoshow) $valtoshow=max($conf->global->MEMBER_MIN_AMOUNT, $valtoshow); + if (!empty($conf->global->MEMBER_MIN_AMOUNT) && $valtoshow) $valtoshow = max($conf->global->MEMBER_MIN_AMOUNT, $valtoshow); print ''; print ''; } else { - $valtoshow=$amount; - if (! empty($conf->global->MEMBER_MIN_AMOUNT) && $valtoshow) $valtoshow=max($conf->global->MEMBER_MIN_AMOUNT, $valtoshow); + $valtoshow = $amount; + if (!empty($conf->global->MEMBER_MIN_AMOUNT) && $valtoshow) $valtoshow = max($conf->global->MEMBER_MIN_AMOUNT, $valtoshow); print ''.price($valtoshow).''; print ''; print ''; @@ -1624,21 +1606,21 @@ if ($source == 'donation') print '
    '.$langs->trans("PaymentCode"); - print ''.$fulltag.''; + print '
    '.$langs->trans("PaymentCode"); + print ''.$fulltag.''; print ''; print ''; print '

    '.$mesg.'
    '; - if (! empty($conf->global->STRIPE_USE_INTENT_WITH_AUTOMATIC_CONFIRMATION)) + if (!empty($conf->global->STRIPE_USE_INTENT_WITH_AUTOMATIC_CONFIRMATION)) { print '
    '; } @@ -1894,7 +1876,7 @@ if (preg_match('/^dopayment/', $action)) // If we choosed/click on the payment print '
    '; print ''; - if (! empty($conf->global->STRIPE_USE_INTENT_WITH_AUTOMATIC_CONFIRMATION)) + if (!empty($conf->global->STRIPE_USE_INTENT_WITH_AUTOMATIC_CONFIRMATION)) { print '
    '; } @@ -1915,7 +1897,7 @@ if (preg_match('/^dopayment/', $action)) // If we choosed/click on the payment print '
    '; //} - if (! empty($conf->global->STRIPE_USE_INTENT_WITH_AUTOMATIC_CONFIRMATION)) + if (!empty($conf->global->STRIPE_USE_INTENT_WITH_AUTOMATIC_CONFIRMATION)) { if (empty($paymentintent)) { @@ -1946,16 +1928,16 @@ if (preg_match('/^dopayment/', $action)) // If we choosed/click on the payment // Code to ask the credit card. This use the default "API version". No way to force API version when using JS code. print ''; print "\n"; - $s.=''.$langs->trans("VATIntraCheck").''; + $s .= ''.$langs->trans("VATIntraCheck").''; $s = $form->textwithpicto($s, $langs->trans("VATIntraCheckDesc", $langs->transnoentitiesnoconv("VATIntraCheck")), 1); } else { - $s.='country_id).'" target="_blank">'.img_picto($langs->trans("VATIntraCheckableOnEUSite"), 'help').''; + $s .= 'country_id).'" target="_blank">'.img_picto($langs->trans("VATIntraCheckableOnEUSite"), 'help').''; } } print $s; @@ -1435,30 +1435,30 @@ else // Local Taxes //TODO: Place into a function to control showing by country or study better option - if($mysoc->localtax1_assuj=="1" && $mysoc->localtax2_assuj=="1") + if ($mysoc->localtax1_assuj == "1" && $mysoc->localtax2_assuj == "1") { print '
    '.$langs->transcountry("LocalTax1IsUsed", $mysoc->country_code).''; - print $form->selectyesno('localtax1assuj_value', (isset($conf->global->THIRDPARTY_DEFAULT_USELOCALTAX1)?$conf->global->THIRDPARTY_DEFAULT_USELOCALTAX1:0), 1); + print $form->selectyesno('localtax1assuj_value', (isset($conf->global->THIRDPARTY_DEFAULT_USELOCALTAX1) ? $conf->global->THIRDPARTY_DEFAULT_USELOCALTAX1 : 0), 1); print ''.$langs->transcountry("LocalTax2IsUsed", $mysoc->country_code).''; - print $form->selectyesno('localtax2assuj_value', (isset($conf->global->THIRDPARTY_DEFAULT_USELOCALTAX2)?$conf->global->THIRDPARTY_DEFAULT_USELOCALTAX2:0), 1); + print $form->selectyesno('localtax2assuj_value', (isset($conf->global->THIRDPARTY_DEFAULT_USELOCALTAX2) ? $conf->global->THIRDPARTY_DEFAULT_USELOCALTAX2 : 0), 1); print '
    '.$langs->transcountry("LocalTax1IsUsed", $mysoc->country_code).''; - print $form->selectyesno('localtax1assuj_value', (isset($conf->global->THIRDPARTY_DEFAULT_USELOCALTAX1)?$conf->global->THIRDPARTY_DEFAULT_USELOCALTAX1:0), 1); + print $form->selectyesno('localtax1assuj_value', (isset($conf->global->THIRDPARTY_DEFAULT_USELOCALTAX1) ? $conf->global->THIRDPARTY_DEFAULT_USELOCALTAX1 : 0), 1); print '
    '.$langs->transcountry("LocalTax2IsUsed", $mysoc->country_code).''; - print $form->selectyesno('localtax2assuj_value', (isset($conf->global->THIRDPARTY_DEFAULT_USELOCALTAX2)?$conf->global->THIRDPARTY_DEFAULT_USELOCALTAX2:0), 1); + print $form->selectyesno('localtax2assuj_value', (isset($conf->global->THIRDPARTY_DEFAULT_USELOCALTAX2) ? $conf->global->THIRDPARTY_DEFAULT_USELOCALTAX2 : 0), 1); print '
    '.$form->editfieldkey('ThirdPartyType', 'typent_id', '', $object, 0).''."\n"; - $sortparam=(empty($conf->global->SOCIETE_SORT_ON_TYPEENT)?'ASC':$conf->global->SOCIETE_SORT_ON_TYPEENT); // NONE means we keep sort of original array, so we sort on position. ASC, means next function will sort on label. + $sortparam = (empty($conf->global->SOCIETE_SORT_ON_TYPEENT) ? 'ASC' : $conf->global->SOCIETE_SORT_ON_TYPEENT); // NONE means we keep sort of original array, so we sort on position. ASC, means next function will sort on label. print $form->selectarray("typent_id", $formcompany->typent_array(0), $object->typent_id, 0, 0, 0, '', 0, 0, 0, $sortparam); if ($user->admin) print ' '.info_admin($langs->trans("YouCanChangeValuesForThisListFromDictionarySetup"), 1); print ' '; print ''.$langs->trans("Currency".$conf->currency).'
    '.$form->editfieldkey('DefaultLang', 'default_lang', '', $object, 0).''."\n"; - print $formadmin->select_language(GETPOST('default_lang', 'alpha')?GETPOST('default_lang', 'alpha'):($object->default_lang?$object->default_lang:''), 'default_lang', 0, 0, 1, 0, 0, 'maxwidth200onsmartphone'); + print $formadmin->select_language(GETPOST('default_lang', 'alpha') ?GETPOST('default_lang', 'alpha') : ($object->default_lang ? $object->default_lang : ''), 'default_lang', 0, 0, 1, 0, 0, 'maxwidth200onsmartphone'); print '
    '.$form->editfieldkey('IncotermLabel', 'incoterm_id', '', $object, 0).''; - print $form->select_incoterms((!empty($object->fk_incoterms) ? $object->fk_incoterms : ''), (!empty($object->location_incoterms)?$object->location_incoterms:'')); + print $form->select_incoterms((!empty($object->fk_incoterms) ? $object->fk_incoterms : ''), (!empty($object->location_incoterms) ? $object->location_incoterms : '')); print '
    ' . $form->editfieldkey('CustomersProspectsCategoriesShort', 'custcats', '', $object, 0) . ''; + print '
    '.$form->editfieldkey('CustomersProspectsCategoriesShort', 'custcats', '', $object, 0).''; $cate_arbo = $form->select_all_categories(Categorie::TYPE_CUSTOMER, null, 'parent', null, null, 1); print $form->multiselectarray('custcats', $cate_arbo, GETPOST('custcats', 'array'), null, null, null, null, "90%"); print "
    ' . $form->editfieldkey('SuppliersCategoriesShort', 'suppcats', '', $object, 0) . ''; + print '
    '.$form->editfieldkey('SuppliersCategoriesShort', 'suppcats', '', $object, 0).''; $cate_arbo = $form->select_all_categories(Categorie::TYPE_SUPPLIER, null, 'parent', null, null, 1); print $form->multiselectarray('suppcats', $cate_arbo, GETPOST('suppcats', 'array'), null, null, null, null, "90%"); print "
    '.$form->editfieldkey('Currency', 'multicurrency_code', '', $object, 0).''; $userlist = $form->select_dolusers('', '', 0, null, 0, '', '', 0, 0, 0, '', 0, '', '', 0, 1); // Note: If user has no right to "see all thirdparties", we force selection of sale representative to him, so after creation he can see the record. - $selected = (count(GETPOST('commercial', 'array')) > 0 ? GETPOST('commercial', 'array') : (GETPOST('commercial', 'int') > 0 ? array(GETPOST('commercial', 'int')) : (empty($user->rights->societe->client->voir)?array($user->id):array()))); + $selected = (count(GETPOST('commercial', 'array')) > 0 ? GETPOST('commercial', 'array') : (GETPOST('commercial', 'int') > 0 ? array(GETPOST('commercial', 'int')) : (empty($user->rights->societe->client->voir) ? array($user->id) : array()))); print $form->multiselectarray('commercial', $userlist, $selected, null, null, null, null, "90%"); print '
    '; + print '
    '; // Ref/ID - if (! empty($conf->global->MAIN_SHOW_TECHNICAL_ID)) + if (!empty($conf->global->MAIN_SHOW_TECHNICAL_ID)) { print ''; // Prefix - if (! empty($conf->global->SOCIETE_USEPREFIX)) // Old not used prefix field + if (!empty($conf->global->SOCIETE_USEPREFIX)) // Old not used prefix field { print ''; // Supplier - if ((! empty($conf->fournisseur->enabled) && ! empty($user->rights->fournisseur->lire)) - || (! empty($conf->supplier_proposal->enabled) && ! empty($user->rights->supplier_proposal->lire))) + if ((!empty($conf->fournisseur->enabled) && !empty($user->rights->fournisseur->lire)) + || (!empty($conf->supplier_proposal->enabled) && !empty($user->rights->supplier_proposal->lire))) { print ''; print ''; print ''; print ''; // Address @@ -1936,14 +1936,14 @@ else // Country print ''; // State if (empty($conf->global->SOCIETE_DISABLE_STATE)) { - if(!empty($conf->global->MAIN_SHOW_REGION_IN_STATE_SELECT) && ($conf->global->MAIN_SHOW_REGION_IN_STATE_SELECT == 1 || $conf->global->MAIN_SHOW_REGION_IN_STATE_SELECT == 2)) + if (!empty($conf->global->MAIN_SHOW_REGION_IN_STATE_SELECT) && ($conf->global->MAIN_SHOW_REGION_IN_STATE_SELECT == 1 || $conf->global->MAIN_SHOW_REGION_IN_STATE_SELECT == 2)) { print ''; - print ''; + print ''; print ''; - print ''; + print ''; // EMail / Web - print ''; - print ''; + print ''; + print ''; print ''; - print ''; + print ''; - if (! empty($conf->socialnetworks->enabled)) { + if (!empty($conf->socialnetworks->enabled)) { foreach ($socialnetworks as $key => $value) { if ($value['active']) { print ''; @@ -2011,18 +2011,18 @@ else // } // Prof ids - $i=1; $j=0; + $i = 1; $j = 0; while ($i <= 6) { - $idprof=$langs->transcountry('ProfId'.$i, $object->country_code); - if ($idprof!='-') + $idprof = $langs->transcountry('ProfId'.$i, $object->country_code); + if ($idprof != '-') { - $key='idprof'.$i; + $key = 'idprof'.$i; if (($j % 2) == 0) print ''; - $idprof_mandatory ='SOCIETE_IDPROF'.($i).'_MANDATORY'; - print ''; if (($j % 2) == 1) print ''; @@ -2039,11 +2039,11 @@ else // Local Taxes //TODO: Place into a function to control showing by country or study better option - if($mysoc->localtax1_assuj=="1" && $mysoc->localtax2_assuj=="1") + if ($mysoc->localtax1_assuj == "1" && $mysoc->localtax2_assuj == "1") { print ''; } - elseif($mysoc->localtax1_assuj=="1" && $mysoc->localtax2_assuj!="1") + elseif ($mysoc->localtax1_assuj == "1" && $mysoc->localtax2_assuj != "1") { print ''; } - elseif($mysoc->localtax2_assuj=="1" && $mysoc->localtax1_assuj!="1") + elseif ($mysoc->localtax2_assuj == "1" && $mysoc->localtax1_assuj != "1") { print ''; print ''; print ''; // Default language - if (! empty($conf->global->MAIN_MULTILANGS)) + if (!empty($conf->global->MAIN_MULTILANGS)) { print ''; print ''; print ''; } // Categories - if (! empty($conf->categorie->enabled) && ! empty($user->rights->categorie->lire)) + if (!empty($conf->categorie->enabled) && !empty($user->rights->categorie->lire)) { // Customer - print ''; + print ''; print '"; // Supplier - print ''; + print ''; print ''; print ''; @@ -2200,12 +2200,12 @@ else } // Other attributes - $parameters=array('colspan' => ' colspan="3"', 'colspanvalue' => '3'); - $reshook=$hookmanager->executeHooks('formObjectOptions', $parameters, $object, $action); // Note that $action and $object may have been modified by hook + $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)) { - print $object->showOptionals($extrafields, 'edit'); + print $object->showOptionals($extrafields, 'edit', $parameters); } // Webservices url/key @@ -2221,7 +2221,7 @@ else print ''; print ''; // Supplier - if (! empty($conf->fournisseur->enabled) || ! empty($conf->supplier_proposal->enabled)) + if (!empty($conf->fournisseur->enabled) || !empty($conf->supplier_proposal->enabled)) { print ''; print ''; @@ -2337,7 +2337,7 @@ else } // Supplier code - if (! empty($conf->fournisseur->enabled) && $object->fournisseur && ! empty($user->rights->fournisseur->lire)) + if (!empty($conf->fournisseur->enabled) && $object->fournisseur && !empty($user->rights->fournisseur->lire)) { print ''; print ''; print ''; - if($object->localtax1_assuj=="1" && (! isOnlyOneLocalTax(1))) + if ($object->localtax1_assuj == "1" && (!isOnlyOneLocalTax(1))) { print ''; print ''; print ''; print ''; - if($action == 'editRE') + if ($action == 'editRE') { print ''; } - if($object->localtax2_assuj=="1" && (! isOnlyOneLocalTax(2))) + if ($object->localtax2_assuj == "1" && (!isOnlyOneLocalTax(2))) { print ''; print ''; print ''; print ''; - if($action == 'editIRPF'){ + if ($action == 'editIRPF') { print ''; - }else{ + } else { print ''; } print ''; } } - elseif($mysoc->localtax1_assuj=="1" && $mysoc->localtax2_assuj!="1") + elseif ($mysoc->localtax1_assuj == "1" && $mysoc->localtax2_assuj != "1") { print ''; - if($object->localtax1_assuj=="1" && (! isOnlyOneLocalTax(1))) + if ($object->localtax1_assuj == "1" && (!isOnlyOneLocalTax(1))) { print ''; print ''; print ''; print ''; - if($action == 'editRE'){ + if ($action == 'editRE') { print ''; - }else{ + } else { print ''; } print ''; } } - elseif($mysoc->localtax2_assuj=="1" && $mysoc->localtax1_assuj!="1") + elseif ($mysoc->localtax2_assuj == "1" && $mysoc->localtax1_assuj != "1") { print ''; - if($object->localtax2_assuj=="1" && (! isOnlyOneLocalTax(2))) + if ($object->localtax2_assuj == "1" && (!isOnlyOneLocalTax(2))) { print ''; print ''; print ''; print ''; - if($action == 'editIRPF'){ + if ($action == 'editIRPF') { print ''; - }else{ + } else { print ''; } print ''; @@ -2492,18 +2492,18 @@ else print ''; print ''; @@ -2544,11 +2544,11 @@ else print '
    '.$langs->trans("ID").''; print $object->ref; @@ -1820,7 +1820,7 @@ else print '
    '.$form->editfieldkey('Prefix', 'prefix', '', $object, 0).''; // It does not change the prefix mode using the auto numbering prefix @@ -1846,9 +1846,9 @@ else print '
    '; if ((!$object->code_client || $object->code_client == -1) && $modCodeClient->code_auto) { - $tmpcode=$object->code_client; - if (empty($tmpcode) && ! empty($object->oldcopy->code_client)) $tmpcode=$object->oldcopy->code_client; // When there is an error to update a thirdparty, the number for supplier and customer code is kept to old value. - if (empty($tmpcode) && ! empty($modCodeClient->code_auto)) $tmpcode=$modCodeClient->getNextValue($object, 0); + $tmpcode = $object->code_client; + if (empty($tmpcode) && !empty($object->oldcopy->code_client)) $tmpcode = $object->oldcopy->code_client; // When there is an error to update a thirdparty, the number for supplier and customer code is kept to old value. + if (empty($tmpcode) && !empty($modCodeClient->code_auto)) $tmpcode = $modCodeClient->getNextValue($object, 0); print ''; } elseif ($object->codeclient_modifiable()) @@ -1861,34 +1861,34 @@ else print ''; } print ''; - $s=$modCodeClient->getToolTip($langs, $object, 0); + $s = $modCodeClient->getToolTip($langs, $object, 0); print $form->textwithpicto('', $s, 1); print '
    '; print '
    '.$form->editfieldkey('Supplier', 'fournisseur', '', $object, 0, 'string', '', 1).''; print $form->selectyesno("fournisseur", $object->fournisseur, 1); print ''; - if (! empty($conf->fournisseur->enabled) && ! empty($user->rights->fournisseur->lire)) + if (!empty($conf->fournisseur->enabled) && !empty($user->rights->fournisseur->lire)) { print $form->editfieldkey('SupplierCode', 'supplier_code', '', $object, 0); } print ''; - if (! empty($conf->fournisseur->enabled) && ! empty($user->rights->fournisseur->lire)) + if (!empty($conf->fournisseur->enabled) && !empty($user->rights->fournisseur->lire)) { print '
    '; if ((!$object->code_fournisseur || $object->code_fournisseur == -1) && $modCodeFournisseur->code_auto) { - $tmpcode=$object->code_fournisseur; - if (empty($tmpcode) && ! empty($object->oldcopy->code_fournisseur)) $tmpcode=$object->oldcopy->code_fournisseur; // When there is an error to update a thirdparty, the number for supplier and customer code is kept to old value. - if (empty($tmpcode) && ! empty($modCodeFournisseur->code_auto)) $tmpcode=$modCodeFournisseur->getNextValue($object, 1); + $tmpcode = $object->code_fournisseur; + if (empty($tmpcode) && !empty($object->oldcopy->code_fournisseur)) $tmpcode = $object->oldcopy->code_fournisseur; // When there is an error to update a thirdparty, the number for supplier and customer code is kept to old value. + if (empty($tmpcode) && !empty($modCodeFournisseur->code_auto)) $tmpcode = $modCodeFournisseur->getNextValue($object, 1); print ''; } elseif ($object->codefournisseur_modifiable()) @@ -1901,7 +1901,7 @@ else print ''; } print ''; - $s=$modCodeFournisseur->getToolTip($langs, $object, 1); + $s = $modCodeFournisseur->getToolTip($langs, $object, 1); print $form->textwithpicto('', $s, 1); print '
    '; } @@ -1909,7 +1909,7 @@ else } // Barcode - if (! empty($conf->barcode->enabled)) + if (!empty($conf->barcode->enabled)) { print '
    '.$form->editfieldkey('Gencod', 'barcode', '', $object, 0).''; @@ -1918,7 +1918,7 @@ else // Status print '
    '.$form->editfieldkey('Status', 'status', '', $object, 0).''; - print $form->selectarray('status', array('0'=>$langs->trans('ActivityCeased'),'1'=>$langs->trans('InActivity')), $object->status); + print $form->selectarray('status', array('0'=>$langs->trans('ActivityCeased'), '1'=>$langs->trans('InActivity')), $object->status); print '
    '.$form->editfieldkey('Country', 'selectcounty_id', '', $object, 0).''; - print $form->select_country((GETPOST('country_id')!=''?GETPOST('country_id'):$object->country_id), 'country_id'); + print $form->select_country((GETPOST('country_id') != '' ?GETPOST('country_id') : $object->country_id), 'country_id'); if ($user->admin) print info_admin($langs->trans("YouCanChangeValuesForThisListFromDictionarySetup"), 1); print '
    '.$form->editfieldkey('Region-State', 'state_id', '', $object, 0).''; } @@ -1958,17 +1958,17 @@ else // Phone / Fax print '
    '.img_picto('', 'object_phoning').' '.$form->editfieldkey('Phone', 'phone', GETPOST('phone', 'alpha'), $object, 0).''.img_picto('', 'object_phoning_fax').' '.$form->editfieldkey('Fax', 'fax', GETPOST('fax', 'alpha'), $object, 0).'
    '.img_picto('', 'object_email').' '.$form->editfieldkey('EMail', 'email', GETPOST('email', 'alpha'), $object, 0, 'string', '', (! empty($conf->global->SOCIETE_EMAIL_MANDATORY))).'
    '.img_picto('', 'object_email').' '.$form->editfieldkey('EMail', 'email', GETPOST('email', 'alpha'), $object, 0, 'string', '', (!empty($conf->global->SOCIETE_EMAIL_MANDATORY))).'
    '.img_picto('', 'globe').' '.$form->editfieldkey('Web', 'url', GETPOST('url', 'alpha'), $object, 0).'
    '.$form->editfieldkey($idprof, $key, '', $object, 0, 'string', '', ! (empty($conf->global->$idprof_mandatory) || ! $object->isACompany())).''; + $idprof_mandatory = 'SOCIETE_IDPROF'.($i).'_MANDATORY'; + print ''.$form->editfieldkey($idprof, $key, '', $object, 0, 'string', '', !(empty($conf->global->$idprof_mandatory) || !$object->isACompany())).''; print $formcompany->get_input_id_prof($i, $key, $object->$key, $object->country_code); print '
    '.$form->editfieldkey($langs->transcountry("LocalTax1IsUsed", $mysoc->country_code), 'localtax1assuj_value', '', $object, 0).''; print $form->selectyesno('localtax1assuj_value', $object->localtax1_assuj, 1); - if(! isOnlyOneLocalTax(1)) + if (!isOnlyOneLocalTax(1)) { print ' '.$langs->transcountry("Type", $mysoc->country_code).': '; $formcompany->select_localtax(1, $object->localtax1_value, "lt1"); @@ -2053,7 +2053,7 @@ else print ''.$form->editfieldkey($langs->transcountry("LocalTax2IsUsed", $mysoc->country_code), 'localtax2assuj_value', '', $object, 0).''; print $form->selectyesno('localtax2assuj_value', $object->localtax2_assuj, 1); - if (! isOnlyOneLocalTax(2)) + if (!isOnlyOneLocalTax(2)) { print ' '.$langs->transcountry("Type", $mysoc->country_code).': '; $formcompany->select_localtax(2, $object->localtax2_value, "lt2"); @@ -2061,11 +2061,11 @@ else } print '
    '.$form->editfieldkey($langs->transcountry("LocalTax1IsUsed", $mysoc->country_code), 'localtax1assuj_value', '', $object, 0).''; print $form->selectyesno('localtax1assuj_value', $object->localtax1_assuj, 1); - if(! isOnlyOneLocalTax(1)) + if (!isOnlyOneLocalTax(1)) { print ' '.$langs->transcountry("Type", $mysoc->country_code).': '; $formcompany->select_localtax(1, $object->localtax1_value, "lt1"); @@ -2073,11 +2073,11 @@ else } print '
    '.$form->editfieldkey($langs->transcountry("LocalTax2IsUsed", $mysoc->country_code), 'localtax2assuj_value', '', $object, 0).''; print $form->selectyesno('localtax2assuj_value', $object->localtax2_assuj, 1); - if(! isOnlyOneLocalTax(2)) + if (!isOnlyOneLocalTax(2)) { print ' '.$langs->transcountry("Type", $mysoc->country_code).': '; $formcompany->select_localtax(2, $object->localtax2_value, "lt2"); @@ -2089,16 +2089,16 @@ else // VAT Code print '
    '.$form->editfieldkey('VATIntra', 'intra_vat', '', $object, 0).''; - $s =''; + $s = ''; if (empty($conf->global->MAIN_DISABLEVATCHECK) && isInEEC($object)) { - $s.='   '; + $s .= '   '; if ($conf->use_javascript_ajax) { $widthpopup = 600; - if (! empty($conf->dol_use_jmobile)) $widthpopup = 350; + if (!empty($conf->dol_use_jmobile)) $widthpopup = 350; $heightpopup = 400; print "\n"; print ''; print "\n"; - $s.=''.$langs->trans("VATIntraCheck").''; + $s .= ''.$langs->trans("VATIntraCheck").''; $s = $form->textwithpicto($s, $langs->trans("VATIntraCheckDesc", $langs->transnoentitiesnoconv("VATIntraCheck")), 1); } else { - $s.='country_id).'" class="hideonsmartphone" target="_blank">'.img_picto($langs->trans("VATIntraCheckableOnEUSite"), 'help').''; + $s .= 'country_id).'" class="hideonsmartphone" target="_blank">'.img_picto($langs->trans("VATIntraCheckableOnEUSite"), 'help').''; } } print $s; @@ -2121,7 +2121,7 @@ else // Type - Size print '
    '.$form->editfieldkey('ThirdPartyType', 'typent_id', '', $object, 0).''; - print $form->selectarray("typent_id", $formcompany->typent_array(0), $object->typent_id, 0, 0, 0, '', 0, 0, 0, (empty($conf->global->SOCIETE_SORT_ON_TYPEENT)?'ASC':$conf->global->SOCIETE_SORT_ON_TYPEENT)); + print $form->selectarray("typent_id", $formcompany->typent_array(0), $object->typent_id, 0, 0, 0, '', 0, 0, 0, (empty($conf->global->SOCIETE_SORT_ON_TYPEENT) ? 'ASC' : $conf->global->SOCIETE_SORT_ON_TYPEENT)); if ($user->admin) print info_admin($langs->trans("YouCanChangeValuesForThisListFromDictionarySetup"), 1); print ''.$form->editfieldkey('Staff', 'effectif_id', '', $object, 0).''; @@ -2141,7 +2141,7 @@ else print '"> '.$langs->trans("Currency".$conf->currency).'
    '.$form->editfieldkey('DefaultLang', 'default_lang', '', $object, 0).''."\n"; print $formadmin->select_language($object->default_lang, 'default_lang', 0, 0, 1); @@ -2155,20 +2155,20 @@ else print '
    '.$form->editfieldkey('IncotermLabel', 'incoterm_id', '', $object, 0).''; - print $form->select_incoterms((!empty($object->fk_incoterms) ? $object->fk_incoterms : ''), (!empty($object->location_incoterms)?$object->location_incoterms:'')); + print $form->select_incoterms((!empty($object->fk_incoterms) ? $object->fk_incoterms : ''), (!empty($object->location_incoterms) ? $object->location_incoterms : '')); print '
    ' . $form->editfieldkey('CustomersCategoriesShort', 'custcats', '', $object, 0) . '
    '.$form->editfieldkey('CustomersCategoriesShort', 'custcats', '', $object, 0).''; $cate_arbo = $form->select_all_categories(Categorie::TYPE_CUSTOMER, null, null, null, null, 1); $c = new Categorie($db); $cats = $c->containing($object->id, Categorie::TYPE_CUSTOMER); - $arrayselected=array(); + $arrayselected = array(); foreach ($cats as $cat) { $arrayselected[] = $cat->id; } @@ -2176,12 +2176,12 @@ else print "
    ' . $form->editfieldkey('SuppliersCategoriesShort', 'suppcats', '', $object, 0) . '
    '.$form->editfieldkey('SuppliersCategoriesShort', 'suppcats', '', $object, 0).''; $cate_arbo = $form->select_all_categories(Categorie::TYPE_SUPPLIER, null, null, null, null, 1); $c = new Categorie($db); $cats = $c->containing($object->id, Categorie::TYPE_SUPPLIER); - $arrayselected=array(); + $arrayselected = array(); foreach ($cats as $cat) { $arrayselected[] = $cat->id; } @@ -2190,7 +2190,7 @@ else } // Multicurrency - if (! empty($conf->multicurrency->enabled)) + if (!empty($conf->multicurrency->enabled)) { print '
    '.$form->editfieldkey('Currency', 'multicurrency_code', '', $object, 0).''.$form->editfieldkey('Logo', 'photoinput', '', $object, 0).''; if ($object->logo) print $form->showphoto('societe', $object); - $caneditfield=1; + $caneditfield = 1; if ($caneditfield) { if ($object->logo) print "
    \n"; @@ -2264,7 +2264,7 @@ else * View */ - if (!empty($object->id)) $res=$object->fetch_optionals(); + if (!empty($object->id)) $res = $object->fetch_optionals(); //if ($res < 0) { dol_print_error($db); exit; } @@ -2292,11 +2292,11 @@ else print $form->formconfirm($_SERVER["PHP_SELF"]."?socid=".$object->id, $langs->trans("MergeThirdparties"), $langs->trans("ConfirmMergeThirdparties"), "confirm_merge", $formquestion, 'no', 1, 250); } - dol_htmloutput_mesg(is_numeric($error)?'':$error, $errors, 'error'); + dol_htmloutput_mesg(is_numeric($error) ? '' : $error, $errors, 'error'); $linkback = ''.$langs->trans("BackToList").''; - dol_banner_tab($object, 'socid', $linkback, ($user->socid?0:1), 'rowid', 'nom'); + dol_banner_tab($object, 'socid', $linkback, ($user->socid ? 0 : 1), 'rowid', 'nom'); print '
    '; @@ -2311,7 +2311,7 @@ else print '
    '.$langs->trans('Supplier').''; print yn($object->fournisseur); @@ -2319,7 +2319,7 @@ else } // Prefix - if (! empty($conf->global->SOCIETE_USEPREFIX)) // Old not used prefix field + if (!empty($conf->global->SOCIETE_USEPREFIX)) // Old not used prefix field { print '
    '.$langs->trans('Prefix').''.$object->prefix_comm.'
    '; print $langs->trans('SupplierCode').''; @@ -2348,7 +2348,7 @@ else } // Barcode - if (! empty($conf->barcode->enabled)) + if (!empty($conf->barcode->enabled)) { print '
    '; print $langs->trans('Gencod').''.$object->barcode; @@ -2357,16 +2357,16 @@ else } // Prof ids - $i=1; $j=0; + $i = 1; $j = 0; while ($i <= 6) { - $idprof=$langs->transcountry('ProfId'.$i, $object->country_code); - if ($idprof!='-') + $idprof = $langs->transcountry('ProfId'.$i, $object->country_code); + if ($idprof != '-') { //if (($j % 2) == 0) print '
    '.$idprof.''; - $key='idprof'.$i; + $key = 'idprof'.$i; print $object->$key; if ($object->$key) { @@ -2399,9 +2399,9 @@ else } // Local Taxes - if ($object->fournisseur || $mysoc->country_code=='ES') + if ($object->fournisseur || $mysoc->country_code == 'ES') { - if($mysoc->localtax1_assuj=="1" && $mysoc->localtax2_assuj=="1") + if ($mysoc->localtax1_assuj == "1" && $mysoc->localtax2_assuj == "1") { print '
    '.$langs->transcountry("LocalTax1IsUsed", $mysoc->country_code).''; print yn($object->localtax1_assuj); @@ -2409,13 +2409,13 @@ else print yn($object->localtax2_assuj); print '
    '.$langs->transcountry("Localtax1", $mysoc->country_code).' id.'">'.img_edit($langs->transnoentitiesnoconv('Edit'), 1).''; $formcompany->select_localtax(1, $object->localtax1_value, "lt1"); @@ -2427,59 +2427,59 @@ else } print '
    '.$langs->transcountry("Localtax2", $mysoc->country_code).'id.'">'.img_edit($langs->transnoentitiesnoconv('Edit'), 1).''; $formcompany->select_localtax(2, $object->localtax2_value, "lt2"); print ''.$object->localtax2_value.'
    '.$langs->transcountry("LocalTax1IsUsed", $mysoc->country_code).''; print yn($object->localtax1_assuj); print '
    '.$langs->transcountry("Localtax1", $mysoc->country_code).'id.'">'.img_edit($langs->transnoentitiesnoconv('Edit'), 1).''; $formcompany->select_localtax(1, $object->localtax1_value, "lt1"); print ''.$object->localtax1_value.'
    '.$langs->transcountry("LocalTax2IsUsed", $mysoc->country_code).''; print yn($object->localtax2_assuj); print '
    '.$langs->transcountry("Localtax2", $mysoc->country_code).' id.'">'.img_edit($langs->transnoentitiesnoconv('Edit'), 1).''; $formcompany->select_localtax(2, $object->localtax2_value, "lt2"); print ''.$object->localtax2_value.'
    '.$langs->trans('VATIntra').''; if ($object->tva_intra) { - $s=''; - $s.=$object->tva_intra; - $s.=''; + $s = ''; + $s .= $object->tva_intra; + $s .= ''; if (empty($conf->global->MAIN_DISABLEVATCHECK) && isInEEC($object)) { - $s.='   '; + $s .= '   '; if ($conf->use_javascript_ajax) { $widthpopup = 600; - if (! empty($conf->dol_use_jmobile)) $widthpopup = 350; + if (!empty($conf->dol_use_jmobile)) $widthpopup = 350; $heightpopup = 400; print "\n"; print ''; print "\n"; - $s.=''.$langs->trans("VATIntraCheck").''; + $s .= ''.$langs->trans("VATIntraCheck").''; $s = $form->textwithpicto($s, $langs->trans("VATIntraCheckDesc", $langs->transnoentitiesnoconv("VATIntraCheck")), 1); } else { - $s.='country_id).'" class="hideonsmartphone" target="_blank">'.img_picto($langs->trans("VATIntraCheckableOnEUSite"), 'help').''; + $s .= 'country_id).'" class="hideonsmartphone" target="_blank">'.img_picto($langs->trans("VATIntraCheckableOnEUSite"), 'help').''; } } print $s; @@ -2531,7 +2531,7 @@ else // Type + Staff $arr = $formcompany->typent_array(1); - $object->typent= $arr[$object->typent_code]; + $object->typent = $arr[$object->typent_code]; print '
    '.$langs->trans("ThirdPartyType").''.$object->typent.'
    '.$langs->trans("Staff").''.$object->effectif.'
    '; // Tags / categories - if (! empty($conf->categorie->enabled) && ! empty($user->rights->categorie->lire)) + if (!empty($conf->categorie->enabled) && !empty($user->rights->categorie->lire)) { // Customer - if ($object->prospect || $object->client || (! $object->fournisseur && ! empty($conf->global->THIRDPARTY_CAN_HAVE_CATEGORY_EVEN_IF_NOT_CUSTOMER_PROSPECT_SUPPLIER))) { - print ''; + if ($object->prospect || $object->client || (!$object->fournisseur && !empty($conf->global->THIRDPARTY_CAN_HAVE_CATEGORY_EVEN_IF_NOT_CUSTOMER_PROSPECT_SUPPLIER))) { + print ''; print '"; @@ -2556,7 +2556,7 @@ else // Supplier if ($object->fournisseur) { - print ''; + print ''; print '"; @@ -2573,14 +2573,14 @@ else print ''; // Default language - if (! empty($conf->global->MAIN_MULTILANGS)) + if (!empty($conf->global->MAIN_MULTILANGS)) { require_once DOL_DOCUMENT_ROOT.'/core/lib/functions2.lib.php'; print ''; } @@ -2603,13 +2603,13 @@ else } else { - print $form->select_incoterms((!empty($object->fk_incoterms) ? $object->fk_incoterms : ''), (!empty($object->location_incoterms)?$object->location_incoterms:''), $_SERVER['PHP_SELF'].'?socid='.$object->id); + print $form->select_incoterms((!empty($object->fk_incoterms) ? $object->fk_incoterms : ''), (!empty($object->location_incoterms) ? $object->location_incoterms : ''), $_SERVER['PHP_SELF'].'?socid='.$object->id); } print ''; } // Multicurrency - if (! empty($conf->multicurrency->enabled)) + if (!empty($conf->multicurrency->enabled)) { print ''; print ''; @@ -2619,8 +2619,8 @@ else } // Other attributes - $parameters=array('socid'=>$socid, 'colspan' => ' colspan="3"', 'colspanvalue' => '3'); - include DOL_DOCUMENT_ROOT . '/core/tpl/extrafields_view.tpl.php'; + $parameters = array('socid'=>$socid, 'colspan' => ' colspan="3"', 'colspanvalue' => '3'); + include DOL_DOCUMENT_ROOT.'/core/tpl/extrafields_view.tpl.php'; // Parent company if (empty($conf->global->SOCIETE_DISABLE_PARENTCOMPANY)) @@ -2648,16 +2648,16 @@ else include DOL_DOCUMENT_ROOT.'/societe/tpl/linesalesrepresentative.tpl.php'; // Module Adherent - if (! empty($conf->adherent->enabled)) + if (!empty($conf->adherent->enabled)) { $langs->load("members"); print ''; print '
    ' . $langs->trans("CustomersCategoriesShort") . '
    '.$langs->trans("CustomersCategoriesShort").''; print $form->showCategories($object->id, 'customer', 1); print "
    ' . $langs->trans("SuppliersCategoriesShort") . '
    '.$langs->trans("SuppliersCategoriesShort").''; print $form->showCategories($object->id, 'supplier', 1); print "
    '.$langs->trans("DefaultLang").''; //$s=picto_from_langcode($object->default_lang); //print ($s?$s.' ':''); $langs->load("languages"); - $labellang = ($object->default_lang?$langs->trans('Language_'.$object->default_lang):''); + $labellang = ($object->default_lang ? $langs->trans('Language_'.$object->default_lang) : ''); print $labellang; print '
    '.$form->editfieldkey('Currency', 'multicurrency_code', '', $object, 0).'
    '.$langs->trans("LinkedToDolibarrMember").''; - $adh=new Adherent($db); - $result=$adh->fetch('', '', $object->id); + $adh = new Adherent($db); + $result = $adh->fetch('', '', $object->id); if ($result > 0) { - $adh->ref=$adh->getFullName($langs); + $adh->ref = $adh->getFullName($langs); print $adh->getNomUrl(1); } else @@ -2690,8 +2690,8 @@ else { print '
    '."\n"; - $parameters=array(); - $reshook=$hookmanager->executeHooks('addMoreActionsButtons', $parameters, $object, $action); // Note that $action and $object may have been modified by hook + $parameters = array(); + $reshook = $hookmanager->executeHooks('addMoreActionsButtons', $parameters, $object, $action); // Note that $action and $object may have been modified by hook if (empty($reshook)) { $at_least_one_email_contact = false; @@ -2705,7 +2705,7 @@ else } } - if (! empty($object->email) || $at_least_one_email_contact) + if (!empty($object->email) || $at_least_one_email_contact) { $langs->load("mails"); print ''.$langs->trans('SendMail').''; @@ -2721,11 +2721,11 @@ else print ''.$langs->trans("Modify").''."\n"; } - if (! empty($conf->adherent->enabled)) + if (!empty($conf->adherent->enabled)) { $adh = new Adherent($db); - $result=$adh->fetch('', '', $object->id); - if ($result == 0 && ($object->client == 1 || $object->client == 3) && ! empty($conf->global->MEMBER_CAN_CONVERT_CUSTOMERS_TO_MEMBERS)) + $result = $adh->fetch('', '', $object->id); + if ($result == 0 && ($object->client == 1 || $object->client == 3) && !empty($conf->global->MEMBER_CAN_CONVERT_CUSTOMERS_TO_MEMBERS)) { print ''.$langs->trans("NewMember").''; } @@ -2768,10 +2768,10 @@ else /* * Documents generes */ - $filedir=$conf->societe->multidir_output[$object->entity].'/'.$object->id; - $urlsource=$_SERVER["PHP_SELF"]."?socid=".$object->id; - $genallowed=$user->rights->societe->lire; - $delallowed=$user->rights->societe->creer; + $filedir = $conf->societe->multidir_output[$object->entity].'/'.$object->id; + $urlsource = $_SERVER["PHP_SELF"]."?socid=".$object->id; + $genallowed = $user->rights->societe->lire; + $delallowed = $user->rights->societe->creer; print $formfile->showdocuments('company', $object->id, $filedir, $urlsource, $genallowed, $delallowed, $object->modelpdf, 0, 0, 0, 28, 0, 'entity='.$object->entity, 0, '', $object->default_lang); } @@ -2779,7 +2779,7 @@ else // Subsidiaries list if (empty($conf->global->SOCIETE_DISABLE_SUBSIDIARIES)) { - $result=show_subsidiaries($conf, $langs, $db, $object); + $result = show_subsidiaries($conf, $langs, $db, $object); } print '
    '; @@ -2789,31 +2789,31 @@ else $morehtmlright = dolGetButtonTitle($langs->trans('SeeAll'), '', 'fa fa-list-alt', DOL_URL_ROOT.'/societe/agenda.php?socid='.$object->id); // List of actions on element - include_once DOL_DOCUMENT_ROOT . '/core/class/html.formactions.class.php'; + include_once DOL_DOCUMENT_ROOT.'/core/class/html.formactions.class.php'; $formactions = new FormActions($db); - $somethingshown = $formactions->showactions($object, '', $socid, 1, '', $MAXEVENT, '', $morehtmlright); // Show all action for thirdparty + $somethingshown = $formactions->showactions($object, '', $socid, 1, '', $MAXEVENT, '', $morehtmlright); // Show all action for thirdparty print '
    '; - if (! empty($conf->global->MAIN_DUPLICATE_CONTACTS_TAB_ON_MAIN_CARD)) + if (!empty($conf->global->MAIN_DUPLICATE_CONTACTS_TAB_ON_MAIN_CARD)) { // Contacts list if (empty($conf->global->SOCIETE_DISABLE_CONTACTS)) { - $result=show_contacts($conf, $langs, $db, $object, $_SERVER["PHP_SELF"].'?socid='.$object->id); + $result = show_contacts($conf, $langs, $db, $object, $_SERVER["PHP_SELF"].'?socid='.$object->id); } // Addresses list - if (! empty($conf->global->SOCIETE_ADDRESSES_MANAGEMENT)) + if (!empty($conf->global->SOCIETE_ADDRESSES_MANAGEMENT)) { - $result=show_addresses($conf, $langs, $db, $object, $_SERVER["PHP_SELF"].'?socid='.$object->id); + $result = show_addresses($conf, $langs, $db, $object, $_SERVER["PHP_SELF"].'?socid='.$object->id); } } } // Presend form - $modelmail='thirdparty'; - $defaulttopic='Information'; + $modelmail = 'thirdparty'; + $defaulttopic = 'Information'; $diroutput = $conf->societe->dir_output; $trackid = 'thi'.$object->id; diff --git a/htdocs/societe/class/api_thirdparties.class.php b/htdocs/societe/class/api_thirdparties.class.php index 42fae860666..c855346dbec 100644 --- a/htdocs/societe/class/api_thirdparties.class.php +++ b/htdocs/societe/class/api_thirdparties.class.php @@ -57,7 +57,7 @@ class Thirdparties extends DolibarrApi $this->company = new Societe($this->db); - if (! empty($conf->global->SOCIETE_EMAIL_MANDATORY)) { + if (!empty($conf->global->SOCIETE_EMAIL_MANDATORY)) { static::$FIELDS[] = 'email'; } } @@ -112,7 +112,7 @@ class Thirdparties extends DolibarrApi */ public function index($sortfield = "t.rowid", $sortorder = 'ASC', $limit = 100, $page = 0, $mode = 0, $sqlfilters = '') { - global $db, $conf; + global $db; $obj_ret = array(); @@ -121,24 +121,24 @@ class Thirdparties 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) - $sql.= " FROM ".MAIN_DB_PREFIX."societe as t"; + $sql .= " FROM ".MAIN_DB_PREFIX."societe 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 - $sql.= ", ".MAIN_DB_PREFIX."c_stcomm as st"; - $sql.= " WHERE t.fk_stcomm = st.id"; - if ($mode == 1) $sql.= " AND t.client IN (1, 3)"; - if ($mode == 2) $sql.= " AND t.client IN (2, 3)"; - if ($mode == 3) $sql.= " AND t.client IN (0)"; - if ($mode == 4) $sql.= " AND t.fournisseur IN (1)"; - $sql.= ' AND t.entity IN ('.getEntity('societe').')'; - if ((!DolibarrApiAccess::$user->rights->societe->client->voir && !$socids) || $search_sale > 0) $sql.= " AND t.rowid = sc.fk_soc"; + 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 .= ", ".MAIN_DB_PREFIX."c_stcomm as st"; + $sql .= " WHERE t.fk_stcomm = st.id"; + if ($mode == 1) $sql .= " AND t.client IN (1, 3)"; + if ($mode == 2) $sql .= " AND t.client IN (2, 3)"; + if ($mode == 3) $sql .= " AND t.client IN (0)"; + if ($mode == 4) $sql .= " AND t.fournisseur IN (1)"; + $sql .= ' AND t.entity IN ('.getEntity('societe').')'; + if ((!DolibarrApiAccess::$user->rights->societe->client->voir && !$socids) || $search_sale > 0) $sql .= " AND t.rowid = sc.fk_soc"; //if ($email != NULL) $sql.= " AND s.email = \"".$email."\""; - if ($socid) $sql.= " AND t.rowid IN (".$socids.")"; - if ($search_sale > 0) $sql.= " AND t.rowid = sc.fk_soc"; // Join for the needed table to filter by sale + if ($socids) $sql .= " AND t.rowid 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) { @@ -147,15 +147,15 @@ class Thirdparties extends DolibarrApi // Add sql filters if ($sqlfilters) { - if (! DolibarrApi::_checkFilters($sqlfilters)) + if (!DolibarrApi::_checkFilters($sqlfilters)) { throw new RestException(503, 'Error when validating parameter sqlfilters '.$sqlfilters); } - $regexstring='\(([^:\'\(\)]+:[^:\'\(\)]+:[^:\(\)]+)\)'; - $sql.=" AND (".preg_replace_callback('/'.$regexstring.'/', 'DolibarrApi::_forge_criteria_callback', $sqlfilters).")"; + $regexstring = '\(([^:\'\(\)]+:[^:\'\(\)]+:[^:\(\)]+)\)'; + $sql .= " AND (".preg_replace_callback('/'.$regexstring.'/', 'DolibarrApi::_forge_criteria_callback', $sqlfilters).")"; } - $sql.= $db->order($sortfield, $sortorder); + $sql .= $db->order($sortfield, $sortorder); if ($limit) { if ($page < 0) @@ -164,7 +164,7 @@ class Thirdparties extends DolibarrApi } $offset = $limit * $page; - $sql.= $db->plimit($limit + 1, $offset); + $sql .= $db->plimit($limit + 1, $offset); } $result = $db->query($sql); @@ -172,11 +172,12 @@ class Thirdparties extends DolibarrApi { $num = $db->num_rows($result); $min = min($num, ($limit <= 0 ? $num : $limit)); + $i = 0; while ($i < $min) { $obj = $db->fetch_object($result); $soc_static = new Societe($db); - if($soc_static->fetch($obj->rowid)) { + if ($soc_static->fetch($obj->rowid)) { $obj_ret[] = $this->_cleanObjectDatas($soc_static); } $i++; @@ -185,7 +186,7 @@ class Thirdparties extends DolibarrApi else { throw new RestException(503, 'Error when retrieve thirdparties : '.$db->lasterror()); } - if( ! count($obj_ret)) { + if (!count($obj_ret)) { throw new RestException(404, 'Thirdparties not found'); } return $obj_ret; @@ -199,13 +200,13 @@ class Thirdparties extends DolibarrApi */ public function post($request_data = null) { - if(! DolibarrApiAccess::$user->rights->societe->creer) { + if (!DolibarrApiAccess::$user->rights->societe->creer) { throw new RestException(401); } // Check mandatory fields $result = $this->_validate($request_data); - foreach($request_data as $field => $value) { + foreach ($request_data as $field => $value) { $this->company->$field = $value; } if ($this->company->create(DolibarrApiAccess::$user) < 0) @@ -223,25 +224,25 @@ class Thirdparties extends DolibarrApi */ public function put($id, $request_data = null) { - if(! DolibarrApiAccess::$user->rights->societe->creer) { + if (!DolibarrApiAccess::$user->rights->societe->creer) { throw new RestException(401); } $result = $this->company->fetch($id); - if( ! $result ) { + if (!$result) { throw new RestException(404, 'Thirdparty not found'); } - if( ! DolibarrApi::_checkAccessToResource('societe', $this->company->id)) { + if (!DolibarrApi::_checkAccessToResource('societe', $this->company->id)) { throw new RestException(401, 'Access not allowed for login '.DolibarrApiAccess::$user->login); } - foreach($request_data as $field => $value) { + foreach ($request_data as $field => $value) { if ($field == 'id') continue; $this->company->$field = $value; } - if($this->company->update($id, DolibarrApiAccess::$user, 1, '', '', 'update')) + if ($this->company->update($id, DolibarrApiAccess::$user, 1, '', '', 'update')) return $this->get($id); return false; @@ -272,27 +273,27 @@ class Thirdparties extends DolibarrApi throw new RestException(400, 'Try to merge a thirdparty into itself'); } - if(! DolibarrApiAccess::$user->rights->societe->creer) { + if (!DolibarrApiAccess::$user->rights->societe->creer) { throw new RestException(401); } - $result = $this->company->fetch($id); // include the fetch of extra fields - if( ! $result ) { + $result = $this->company->fetch($id); // include the fetch of extra fields + if (!$result) { throw new RestException(404, 'Thirdparty not found'); } - if( ! DolibarrApi::_checkAccessToResource('societe', $this->company->id)) { + if (!DolibarrApi::_checkAccessToResource('societe', $this->company->id)) { throw new RestException(401, 'Access not allowed for login '.DolibarrApiAccess::$user->login); } $this->companytoremove = new Societe($db); - $result = $this->companytoremove->fetch($idtodelete); // include the fetch of extra fields - if( ! $result ) { + $result = $this->companytoremove->fetch($idtodelete); // include the fetch of extra fields + if (!$result) { throw new RestException(404, 'Thirdparty not found'); } - if( ! DolibarrApi::_checkAccessToResource('societe', $this->companytoremove->id)) { + if (!DolibarrApi::_checkAccessToResource('societe', $this->companytoremove->id)) { throw new RestException(401, 'Access not allowed for login '.DolibarrApiAccess::$user->login); } @@ -309,7 +310,7 @@ class Thirdparties extends DolibarrApi // Recopy some data $object->client = $object->client | $soc_origin->client; $object->fournisseur = $object->fournisseur | $soc_origin->fournisseur; - $listofproperties=array( + $listofproperties = array( 'address', 'zip', 'town', 'state_id', 'country_id', 'phone', 'phone_pro', 'fax', 'email', 'skype', 'url', 'barcode', 'idprof1', 'idprof2', 'idprof3', 'idprof4', 'idprof5', 'idprof6', 'tva_intra', 'effectif_id', 'forme_juridique', 'remise_percent', 'remise_supplier_percent', 'mode_reglement_supplier_id', 'cond_reglement_supplier_id', 'name_bis', @@ -323,7 +324,7 @@ class Thirdparties extends DolibarrApi } // Concat some data - $listofproperties=array( + $listofproperties = array( 'note_public', 'note_private' ); foreach ($listofproperties as $property) @@ -367,7 +368,7 @@ class Thirdparties extends DolibarrApi } // Move links - if (! $error) + if (!$error) { $objects = array( 'Adherent' => '/adherents/class/adherent.class.php', @@ -422,12 +423,12 @@ class Thirdparties extends DolibarrApi } - if (! $error) + if (!$error) { - $object->context=array('merge'=>1, 'mergefromid'=>$soc_origin->id); + $object->context = array('merge'=>1, 'mergefromid'=>$soc_origin->id); // Call trigger - $result=$object->call_trigger('COMPANY_MODIFY', $user); + $result = $object->call_trigger('COMPANY_MODIFY', $user); if ($result < 0) { //setEventMessages($object->error, $object->errors, 'errors'); @@ -436,7 +437,7 @@ class Thirdparties extends DolibarrApi // End call triggers } - if (! $error) + if (!$error) { //We finally remove the old thirdparty if ($soc_origin->delete($soc_origin->id, $user) < 1) @@ -469,14 +470,14 @@ class Thirdparties extends DolibarrApi */ public function delete($id) { - if(! DolibarrApiAccess::$user->rights->societe->supprimer) { + if (!DolibarrApiAccess::$user->rights->societe->supprimer) { throw new RestException(401); } $result = $this->company->fetch($id); - if( ! $result ) { + if (!$result) { throw new RestException(404, 'Thirdparty not found'); } - if( ! DolibarrApi::_checkAccessToResource('societe', $this->company->id)) { + if (!DolibarrApi::_checkAccessToResource('societe', $this->company->id)) { throw new RestException(401, 'Access not allowed for login '.DolibarrApiAccess::$user->login); } $this->company->oldcopy = clone $this->company; @@ -498,12 +499,12 @@ class Thirdparties extends DolibarrApi */ public function getCategories($id, $sortfield = "s.rowid", $sortorder = 'ASC', $limit = 0, $page = 0) { - if (! DolibarrApiAccess::$user->rights->categorie->lire) { + if (!DolibarrApiAccess::$user->rights->categorie->lire) { throw new RestException(401); } $result = $this->company->fetch($id); - if( ! $result ) + if (!$result) { throw new RestException(404, 'Thirdparty not found'); } @@ -537,24 +538,24 @@ class Thirdparties extends DolibarrApi */ public function addCategory($id, $category_id) { - if(! DolibarrApiAccess::$user->rights->societe->creer) { + if (!DolibarrApiAccess::$user->rights->societe->creer) { throw new RestException(401); } $result = $this->company->fetch($id); - if( ! $result ) { + if (!$result) { throw new RestException(404, 'Thirdparty not found'); } $category = new Categorie($this->db); $result = $category->fetch($category_id); - if( ! $result ) { + if (!$result) { throw new RestException(404, 'category not found'); } - if( ! DolibarrApi::_checkAccessToResource('societe', $this->company->id)) { + if (!DolibarrApi::_checkAccessToResource('societe', $this->company->id)) { throw new RestException(401, 'Access not allowed for login '.DolibarrApiAccess::$user->login); } - if( ! DolibarrApi::_checkAccessToResource('category', $category->id)) { + if (!DolibarrApi::_checkAccessToResource('category', $category->id)) { throw new RestException(401, 'Access not allowed for login '.DolibarrApiAccess::$user->login); } @@ -575,24 +576,24 @@ class Thirdparties extends DolibarrApi */ public function deleteCategory($id, $category_id) { - if(! DolibarrApiAccess::$user->rights->societe->creer) { + if (!DolibarrApiAccess::$user->rights->societe->creer) { throw new RestException(401); } $result = $this->company->fetch($id); - if( ! $result ) { + if (!$result) { throw new RestException(404, 'Thirdparty not found'); } $category = new Categorie($this->db); $result = $category->fetch($category_id); - if( ! $result ) { + if (!$result) { throw new RestException(404, 'category not found'); } - if( ! DolibarrApi::_checkAccessToResource('societe', $this->company->id)) { + if (!DolibarrApi::_checkAccessToResource('societe', $this->company->id)) { throw new RestException(401, 'Access not allowed for login '.DolibarrApiAccess::$user->login); } - if( ! DolibarrApi::_checkAccessToResource('category', $category->id)) { + if (!DolibarrApi::_checkAccessToResource('category', $category->id)) { throw new RestException(401, 'Access not allowed for login '.DolibarrApiAccess::$user->login); } @@ -616,12 +617,12 @@ class Thirdparties extends DolibarrApi */ public function getSupplierCategories($id, $sortfield = "s.rowid", $sortorder = 'ASC', $limit = 0, $page = 0) { - if (! DolibarrApiAccess::$user->rights->categorie->lire) { + if (!DolibarrApiAccess::$user->rights->categorie->lire) { throw new RestException(401); } $result = $this->company->fetch($id); - if( ! $result ) + if (!$result) { throw new RestException(404, 'Thirdparty not found'); } @@ -655,24 +656,24 @@ class Thirdparties extends DolibarrApi */ public function addSupplierCategory($id, $category_id) { - if(! DolibarrApiAccess::$user->rights->societe->creer) { + if (!DolibarrApiAccess::$user->rights->societe->creer) { throw new RestException(401); } $result = $this->company->fetch($id); - if( ! $result ) { + if (!$result) { throw new RestException(404, 'Thirdparty not found'); } $category = new Categorie($this->db); $result = $category->fetch($category_id); - if( ! $result ) { + if (!$result) { throw new RestException(404, 'category not found'); } - if( ! DolibarrApi::_checkAccessToResource('societe', $this->company->id)) { + if (!DolibarrApi::_checkAccessToResource('societe', $this->company->id)) { throw new RestException(401, 'Access not allowed for login '.DolibarrApiAccess::$user->login); } - if( ! DolibarrApi::_checkAccessToResource('category', $category->id)) { + if (!DolibarrApi::_checkAccessToResource('category', $category->id)) { throw new RestException(401, 'Access not allowed for login '.DolibarrApiAccess::$user->login); } @@ -693,24 +694,24 @@ class Thirdparties extends DolibarrApi */ public function deleteSupplierCategory($id, $category_id) { - if(! DolibarrApiAccess::$user->rights->societe->creer) { + if (!DolibarrApiAccess::$user->rights->societe->creer) { throw new RestException(401); } $result = $this->company->fetch($id); - if( ! $result ) { + if (!$result) { throw new RestException(404, 'Thirdparty not found'); } $category = new Categorie($this->db); $result = $category->fetch($category_id); - if( ! $result ) { + if (!$result) { throw new RestException(404, 'category not found'); } - if( ! DolibarrApi::_checkAccessToResource('societe', $this->company->id)) { + if (!DolibarrApi::_checkAccessToResource('societe', $this->company->id)) { throw new RestException(401, 'Access not allowed for login '.DolibarrApiAccess::$user->login); } - if( ! DolibarrApi::_checkAccessToResource('category', $category->id)) { + if (!DolibarrApi::_checkAccessToResource('category', $category->id)) { throw new RestException(401, 'Access not allowed for login '.DolibarrApiAccess::$user->login); } @@ -738,20 +739,20 @@ class Thirdparties extends DolibarrApi { $obj_ret = array(); - if(! DolibarrApiAccess::$user->rights->societe->lire) { + if (!DolibarrApiAccess::$user->rights->societe->lire) { throw new RestException(401); } - if(empty($id)) { + if (empty($id)) { throw new RestException(400, 'Thirdparty ID is mandatory'); } - if( ! DolibarrApi::_checkAccessToResource('societe', $id)) { + if (!DolibarrApi::_checkAccessToResource('societe', $id)) { throw new RestException(401, 'Access not allowed for login '.DolibarrApiAccess::$user->login); } $result = $this->company->fetch($id); - if( ! $result ) { + if (!$result) { throw new RestException(404, 'Thirdparty not found'); } @@ -782,20 +783,20 @@ class Thirdparties extends DolibarrApi { $obj_ret = array(); - if(! DolibarrApiAccess::$user->rights->societe->lire) { + if (!DolibarrApiAccess::$user->rights->societe->lire) { throw new RestException(401); } - if(empty($id)) { + if (empty($id)) { throw new RestException(400, 'Thirdparty ID is mandatory'); } - if( ! DolibarrApi::_checkAccessToResource('societe', $id)) { + if (!DolibarrApi::_checkAccessToResource('societe', $id)) { throw new RestException(401, 'Access not allowed for login '.DolibarrApiAccess::$user->login); } $result = $this->company->fetch($id); - if( ! $result ) { + if (!$result) { throw new RestException(404, 'Thirdparty not found'); } @@ -825,20 +826,20 @@ class Thirdparties extends DolibarrApi { $obj_ret = array(); - if(! DolibarrApiAccess::$user->rights->societe->lire) { + if (!DolibarrApiAccess::$user->rights->societe->lire) { throw new RestException(401); } - if(empty($id)) { + if (empty($id)) { throw new RestException(400, 'Thirdparty ID is mandatory'); } - if( ! DolibarrApi::_checkAccessToResource('societe', $id)) { + if (!DolibarrApi::_checkAccessToResource('societe', $id)) { throw new RestException(401, 'Access not allowed for login '.DolibarrApiAccess::$user->login); } $result = $this->company->fetch($id); - if( ! $result ) { + if (!$result) { throw new RestException(404, 'Thirdparty not found'); } @@ -868,20 +869,20 @@ class Thirdparties extends DolibarrApi { $obj_ret = array(); - if(! DolibarrApiAccess::$user->rights->societe->lire) { + if (!DolibarrApiAccess::$user->rights->societe->lire) { throw new RestException(401); } - if(empty($id)) { + if (empty($id)) { throw new RestException(400, 'Thirdparty ID is mandatory'); } - if( ! DolibarrApi::_checkAccessToResource('societe', $id)) { + if (!DolibarrApi::_checkAccessToResource('societe', $id)) { throw new RestException(401, 'Access not allowed for login '.DolibarrApiAccess::$user->login); } $result = $this->company->fetch($id); - if( ! $result ) { + if (!$result) { throw new RestException(404, 'Thirdparty not found'); } @@ -911,20 +912,20 @@ class Thirdparties extends DolibarrApi { $obj_ret = array(); - if(! DolibarrApiAccess::$user->rights->societe->lire) { + if (!DolibarrApiAccess::$user->rights->societe->lire) { throw new RestException(401); } - if(empty($id)) { + if (empty($id)) { throw new RestException(400, 'Thirdparty ID is mandatory'); } - if( ! DolibarrApi::_checkAccessToResource('societe', $id)) { + if (!DolibarrApi::_checkAccessToResource('societe', $id)) { throw new RestException(401, 'Access not allowed for login '.DolibarrApiAccess::$user->login); } $result = $this->company->fetch($id); - if( ! $result ) { + if (!$result) { throw new RestException(404, 'Thirdparty not found'); } @@ -935,14 +936,14 @@ class Thirdparties extends DolibarrApi if ($filter == "available") $sql .= " AND re.fk_facture IS NULL AND re.fk_facture_line IS NULL"; if ($filter == "used") $sql .= " AND (re.fk_facture IS NOT NULL OR re.fk_facture_line IS NOT NULL)"; - $sql.= $this->db->order($sortfield, $sortorder); + $sql .= $this->db->order($sortfield, $sortorder); $result = $this->db->query($sql); - if( ! $result ) { + if (!$result) { throw new RestException(503, $this->db->lasterror()); } else { $num = $this->db->num_rows($result); - while ( $obj = $this->db->fetch_object($result) ) { + while ($obj = $this->db->fetch_object($result)) { $obj_ret[] = $obj; } } @@ -967,14 +968,14 @@ class Thirdparties extends DolibarrApi */ public function getInvoicesQualifiedForReplacement($id) { - if(! DolibarrApiAccess::$user->rights->facture->lire) { + if (!DolibarrApiAccess::$user->rights->facture->lire) { throw new RestException(401); } - if(empty($id)) { + if (empty($id)) { throw new RestException(400, 'Thirdparty ID is mandatory'); } - if( ! DolibarrApi::_checkAccessToResource('societe', $id)) { + if (!DolibarrApi::_checkAccessToResource('societe', $id)) { throw new RestException(401, 'Access not allowed for login '.DolibarrApiAccess::$user->login); } @@ -985,7 +986,7 @@ class Thirdparties extends DolibarrApi $invoice = new Facture($this->db); $result = $invoice->list_replacable_invoices($id); - if( $result < 0) { + if ($result < 0) { throw new RestException(405, $this->thirdparty->error); } @@ -1009,14 +1010,14 @@ class Thirdparties extends DolibarrApi */ public function getInvoicesQualifiedForCreditNote($id) { - if(! DolibarrApiAccess::$user->rights->facture->lire) { + if (!DolibarrApiAccess::$user->rights->facture->lire) { throw new RestException(401); } - if(empty($id)) { + if (empty($id)) { throw new RestException(400, 'Thirdparty ID is mandatory'); } - if( ! DolibarrApi::_checkAccessToResource('societe', $id)) { + if (!DolibarrApi::_checkAccessToResource('societe', $id)) { throw new RestException(401, 'Access not allowed for login '.DolibarrApiAccess::$user->login); } @@ -1027,7 +1028,7 @@ class Thirdparties extends DolibarrApi $invoice = new Facture($this->db); $result = $invoice->list_qualified_avoir_invoices($id); - if( $result < 0) { + if ($result < 0) { throw new RestException(405, $this->thirdparty->error); } @@ -1047,14 +1048,14 @@ class Thirdparties extends DolibarrApi { global $db, $conf; - if(! DolibarrApiAccess::$user->rights->facture->lire) { + if (!DolibarrApiAccess::$user->rights->facture->lire) { throw new RestException(401); } - if(empty($id)) { + if (empty($id)) { throw new RestException(400, 'Thirdparty ID is mandatory'); } - if( ! DolibarrApi::_checkAccessToResource('societe', $id)) { + if (!DolibarrApi::_checkAccessToResource('societe', $id)) { throw new RestException(401, 'Access not allowed for login '.DolibarrApiAccess::$user->login); } @@ -1063,18 +1064,18 @@ class Thirdparties extends DolibarrApi */ $sql = "SELECT rowid, fk_soc, bank, number, code_banque, code_guichet, cle_rib, bic, iban_prefix as iban, domiciliation, proprio,"; - $sql.= " owner_address, default_rib, label, datec, tms as datem, rum, frstrecur"; - $sql.= " FROM ".MAIN_DB_PREFIX."societe_rib"; - if ($id) $sql.= " WHERE fk_soc = ".$id." "; + $sql .= " owner_address, default_rib, label, datec, tms as datem, rum, frstrecur"; + $sql .= " FROM ".MAIN_DB_PREFIX."societe_rib"; + if ($id) $sql .= " WHERE fk_soc = ".$id." "; $result = $db->query($sql); - if($result->num_rows == 0 ){ + if ($result->num_rows == 0) { throw new RestException(404, 'Account not found'); } - $i=0; + $i = 0; $accounts = array(); @@ -1085,13 +1086,13 @@ class Thirdparties extends DolibarrApi { $obj = $db->fetch_object($result); $account = new CompanyBankAccount($db); - if($account->fetch($obj->rowid)) { + if ($account->fetch($obj->rowid)) { $accounts[] = $account; } $i++; } } - else{ + else { throw new RestException(404, 'Account not found'); } @@ -1124,7 +1125,7 @@ class Thirdparties extends DolibarrApi */ public function createCompanyBankAccount($id, $request_data = null) { - if(! DolibarrApiAccess::$user->rights->societe->creer) { + if (!DolibarrApiAccess::$user->rights->societe->creer) { throw new RestException(401); } @@ -1132,7 +1133,7 @@ class Thirdparties extends DolibarrApi $account->socid = $id; - foreach($request_data as $field => $value) { + foreach ($request_data as $field => $value) { $account->$field = $value; } @@ -1159,7 +1160,7 @@ class Thirdparties extends DolibarrApi */ public function updateCompanyBankAccount($id, $bankaccount_id, $request_data = null) { - if(! DolibarrApiAccess::$user->rights->societe->creer) { + if (!DolibarrApiAccess::$user->rights->societe->creer) { throw new RestException(401); } @@ -1167,12 +1168,12 @@ class Thirdparties extends DolibarrApi $account->fetch($bankaccount_id, $id, -1, ''); - if($account->socid != $id){ + if ($account->socid != $id) { throw new RestException(401); } - foreach($request_data as $field => $value) { + foreach ($request_data as $field => $value) { $account->$field = $value; } @@ -1194,7 +1195,7 @@ class Thirdparties extends DolibarrApi */ public function deleteCompanyBankAccount($id, $bankaccount_id) { - if(! DolibarrApiAccess::$user->rights->societe->creer) { + if (!DolibarrApiAccess::$user->rights->societe->creer) { throw new RestException(401); } @@ -1202,7 +1203,7 @@ class Thirdparties extends DolibarrApi $account->fetch($bankaccount_id); - if(!$account->socid == $id) + if (!$account->socid == $id) throw new RestException(401); return $account->delete(DolibarrApiAccess::$user); @@ -1222,12 +1223,12 @@ class Thirdparties extends DolibarrApi { global $conf; - $this->langs->loadLangs(array("main","dict","commercial","products","companies","banks","bills","withdrawals")); + $this->langs->loadLangs(array("main", "dict", "commercial", "products", "companies", "banks", "bills", "withdrawals")); $this->company->fetch($id); $action = 'builddoc'; - if(! DolibarrApiAccess::$user->rights->societe->creer) + if (!DolibarrApiAccess::$user->rights->societe->creer) throw new RestException(401); $this->company->setDocModel(DolibarrApiAccess::$user, $model); @@ -1235,32 +1236,32 @@ class Thirdparties extends DolibarrApi $this->company->fk_bank = $this->company->fk_account; $outputlangs = $this->langs; - $newlang=''; + $newlang = ''; - if ($this->conf->global->MAIN_MULTILANGS && empty($newlang) && GETPOST('lang_id', 'aZ09')) $newlang=GETPOST('lang_id', 'aZ09'); - if ($this->conf->global->MAIN_MULTILANGS && empty($newlang) && isset($this->company->thirdparty->default_lang)) $newlang=$this->company->thirdparty->default_lang; // for proposal, order, invoice, ... - if ($this->conf->global->MAIN_MULTILANGS && empty($newlang) && isset($this->company->default_lang)) $newlang=$this->company->default_lang; // for thirdparty - if (! empty($newlang)) { + if ($this->conf->global->MAIN_MULTILANGS && empty($newlang) && GETPOST('lang_id', 'aZ09')) $newlang = GETPOST('lang_id', 'aZ09'); + if ($this->conf->global->MAIN_MULTILANGS && empty($newlang) && isset($this->company->thirdparty->default_lang)) $newlang = $this->company->thirdparty->default_lang; // for proposal, order, invoice, ... + if ($this->conf->global->MAIN_MULTILANGS && empty($newlang) && isset($this->company->default_lang)) $newlang = $this->company->default_lang; // for thirdparty + if (!empty($newlang)) { $outputlangs = new Translate("", $conf); $outputlangs->setDefaultLang($newlang); } // To be sure vars is defined $hidedetails = $hidedesc = $hideref = 0; - $moreparams=null; - if (empty($hidedetails)) $hidedetails=0; - if (empty($hidedesc)) $hidedesc=0; - if (empty($hideref)) $hideref=0; - if (empty($moreparams)) $moreparams=null; + $moreparams = null; + if (empty($hidedetails)) $hidedetails = 0; + if (empty($hidedesc)) $hidedesc = 0; + if (empty($hideref)) $hideref = 0; + if (empty($moreparams)) $moreparams = null; $sql = "SELECT rowid"; - $sql.= " FROM ".MAIN_DB_PREFIX."societe_rib"; - if ($id) $sql.= " WHERE fk_soc = ".$id." "; - if ($companybankid) $sql.= " AND id = ".$companybankid.""; + $sql .= " FROM ".MAIN_DB_PREFIX."societe_rib"; + if ($id) $sql .= " WHERE fk_soc = ".$id." "; + if ($companybankid) $sql .= " AND id = ".$companybankid.""; - $i=0; - $accounts=array(); + $i = 0; + $accounts = array(); $result = $this->db->query($sql); if ($result) @@ -1321,11 +1322,11 @@ class Thirdparties extends DolibarrApi { global $db, $conf; - if(!DolibarrApiAccess::$user->rights->societe->lire) { + if (!DolibarrApiAccess::$user->rights->societe->lire) { throw new RestException(401); } - if(!DolibarrApi::_checkAccessToResource('societe', $id)) { + if (!DolibarrApi::_checkAccessToResource('societe', $id)) { throw new RestException(401, 'Access not allowed for login '.DolibarrApiAccess::$user->login); } @@ -1333,16 +1334,16 @@ class Thirdparties extends DolibarrApi * We select all the records that match the socid */ $sql = "SELECT rowid, fk_soc, key_account, site, date_creation, tms FROM ".MAIN_DB_PREFIX."societe_account"; - $sql.= " WHERE fk_soc = $id"; - if($site) $sql .= " AND site ='$site'"; + $sql .= " WHERE fk_soc = $id"; + if ($site) $sql .= " AND site ='$site'"; $result = $db->query($sql); - if($result->num_rows == 0){ + if ($result->num_rows == 0) { throw new RestException(404, 'This thirdparty does not have any gateway attached or does not exist.'); } - $i=0; + $i = 0; $accounts = array(); @@ -1352,7 +1353,7 @@ class Thirdparties extends DolibarrApi $obj = $db->fetch_object($result); $account = new SocieteAccount($db); - if($account->fetch($obj->rowid)) { + if ($account->fetch($obj->rowid)) { $accounts[] = $account; } $i++; @@ -1365,7 +1366,7 @@ class Thirdparties extends DolibarrApi foreach ($accounts as $account) { $object = array(); foreach ($account as $key => $value) { - if(in_array($key, $fields)) { + if (in_array($key, $fields)) { $object[$key] = $value; } } @@ -1398,25 +1399,25 @@ class Thirdparties extends DolibarrApi { global $db; - if(! DolibarrApiAccess::$user->rights->societe->creer) { + if (!DolibarrApiAccess::$user->rights->societe->creer) { throw new RestException(401); } - if(!isset($request_data['site'])) { + if (!isset($request_data['site'])) { throw new RestException(422, 'Unprocessable Entity: You must pass the site attribute in your request data !'); } - $sql = "SELECT rowid FROM ".MAIN_DB_PREFIX."societe_account WHERE fk_soc = ".$id." AND site = '". $request_data['site']."' "; + $sql = "SELECT rowid FROM ".MAIN_DB_PREFIX."societe_account WHERE fk_soc = ".$id." AND site = '".$request_data['site']."' "; $result = $db->query($sql); - if($result->num_rows == 0 ){ + if ($result->num_rows == 0) { $account = new SocieteAccount($this->db); - if(!isset($request_data['login'])) { + if (!isset($request_data['login'])) { $account->login = ""; } $account->fk_soc = $id; - foreach($request_data as $field => $value) { + foreach ($request_data as $field => $value) { $account->$field = $value; } @@ -1457,7 +1458,7 @@ class Thirdparties extends DolibarrApi { global $db; - if(! DolibarrApiAccess::$user->rights->societe->creer) { + if (!DolibarrApiAccess::$user->rights->societe->creer) { throw new RestException(401); } @@ -1465,16 +1466,16 @@ class Thirdparties extends DolibarrApi $result = $db->query($sql); // We do not found an existing SocieteAccount entity for this fk_soc and site ; we then create a new one. - if($result->num_rows == 0 ){ - if(!isset($request_data['key_account'])) { + if ($result->num_rows == 0) { + if (!isset($request_data['key_account'])) { throw new RestException(422, 'Unprocessable Entity: You must pass the key_account attribute in your request data !'); } $account = new SocieteAccount($this->db); - if(!isset($request_data['login'])) { + if (!isset($request_data['login'])) { $account->login = ""; } - foreach($request_data as $field => $value) { + foreach ($request_data as $field => $value) { $account->$field = $value; } @@ -1487,11 +1488,11 @@ class Thirdparties extends DolibarrApi // We found an existing SocieteAccount entity, we are replacing it } else { if (isset($request_data['site']) && $request_data['site'] !== $site) { - $sql = "SELECT rowid FROM ".MAIN_DB_PREFIX."societe_account WHERE fk_soc = ".$id." AND site = '". $request_data['site']."' "; + $sql = "SELECT rowid FROM ".MAIN_DB_PREFIX."societe_account WHERE fk_soc = ".$id." AND site = '".$request_data['site']."' "; $result = $db->query($sql); if ($result->num_rows !== 0) { - throw new RestException(409, "You are trying to update this thirdparty SocieteAccount (gateway record) from $site to ".$request_data['site'] . " but another SocieteAccount entity already exists with this site key."); + throw new RestException(409, "You are trying to update this thirdparty SocieteAccount (gateway record) from $site to ".$request_data['site']." but another SocieteAccount entity already exists with this site key."); } } @@ -1501,13 +1502,13 @@ class Thirdparties extends DolibarrApi $account->id = $obj->rowid; $account->fk_soc = $id; $account->site = $site; - if(!isset($request_data['login'])) { + if (!isset($request_data['login'])) { $account->login = ""; } $account->fk_user_creat = $obj->fk_user_creat; $account->date_creation = $obj->date_creation; - foreach($request_data as $field => $value) { + foreach ($request_data as $field => $value) { $account->$field = $value; } @@ -1539,30 +1540,30 @@ class Thirdparties extends DolibarrApi { global $db; - if(! DolibarrApiAccess::$user->rights->societe->creer) { + if (!DolibarrApiAccess::$user->rights->societe->creer) { throw new RestException(401); } $sql = "SELECT rowid FROM ".MAIN_DB_PREFIX."societe_account WHERE fk_soc = $id AND site = '$site' "; $result = $db->query($sql); - if($result->num_rows == 0 ){ + if ($result->num_rows == 0) { throw new RestException(404, "This thirdparty does not have $site gateway attached or does not exist."); } else { // If the user tries to edit the site member, we check first if - if(isset($request_data['site']) && $request_data['site'] !== $site) { - $sql = "SELECT rowid FROM ".MAIN_DB_PREFIX."societe_account WHERE fk_soc = ".$id." AND site = '". $request_data['site']."' "; + if (isset($request_data['site']) && $request_data['site'] !== $site) { + $sql = "SELECT rowid FROM ".MAIN_DB_PREFIX."societe_account WHERE fk_soc = ".$id." AND site = '".$request_data['site']."' "; $result = $db->query($sql); - if($result->num_rows !== 0) - throw new RestException(409, "You are trying to update this thirdparty SocieteAccount (gateway record) site member from $site to ".$request_data['site'] . " but another SocieteAccount entity already exists for this thirdparty with this site key."); + if ($result->num_rows !== 0) + throw new RestException(409, "You are trying to update this thirdparty SocieteAccount (gateway record) site member from $site to ".$request_data['site']." but another SocieteAccount entity already exists for this thirdparty with this site key."); } $obj = $db->fetch_object($result); $account = new SocieteAccount($this->db); $account->fetch($obj->rowid); - foreach($request_data as $field => $value) { + foreach ($request_data as $field => $value) { $account->$field = $value; } @@ -1593,21 +1594,21 @@ class Thirdparties extends DolibarrApi global /** @var Database $db */ $db; - if(! DolibarrApiAccess::$user->rights->societe->creer) { + if (!DolibarrApiAccess::$user->rights->societe->creer) { throw new RestException(401); } $sql = "SELECT rowid FROM ".MAIN_DB_PREFIX."societe_account WHERE fk_soc = $id AND site = '$site' "; $result = $db->query($sql); - if($result->num_rows == 0 ){ + if ($result->num_rows == 0) { throw new RestException(404); } else { $obj = $db->fetch_object($result); $account = new SocieteAccount($this->db); $account->fetch($obj->rowid); - if($account->delete(DolibarrApiAccess::$user) < 0) { + if ($account->delete(DolibarrApiAccess::$user) < 0) { throw new RestException(500, "Error while deleting $site gateway attached to this third party"); } } @@ -1630,7 +1631,7 @@ class Thirdparties extends DolibarrApi global /** @var Database $db */ $db; - if(! DolibarrApiAccess::$user->rights->societe->creer) { + if (!DolibarrApiAccess::$user->rights->societe->creer) { throw new RestException(401); } @@ -1639,14 +1640,14 @@ class Thirdparties extends DolibarrApi */ $sql = "SELECT rowid, fk_soc, key_account, site, date_creation, tms"; - $sql.= " FROM ".MAIN_DB_PREFIX."societe_account WHERE fk_soc = $id "; + $sql .= " FROM ".MAIN_DB_PREFIX."societe_account WHERE fk_soc = $id "; $result = $db->query($sql); - if($result->num_rows == 0 ){ + if ($result->num_rows == 0) { throw new RestException(404, 'This third party does not have any gateway attached or does not exist.'); } else { - $i=0; + $i = 0; $num = $db->num_rows($result); while ($i < $num) @@ -1655,7 +1656,7 @@ class Thirdparties extends DolibarrApi $account = new SocieteAccount($db); $account->fetch($obj->rowid); - if($account->delete(DolibarrApiAccess::$user) < 0) { + if ($account->delete(DolibarrApiAccess::$user) < 0) { throw new RestException(500, 'Error while deleting gateways attached to this third party'); } $i++; @@ -1675,9 +1676,9 @@ class Thirdparties extends DolibarrApi // phpcs:enable $object = parent::_cleanObjectDatas($object); - unset($object->nom); // ->name already defined and nom deprecated - unset($object->name_bis); // ->name_alias already defined - unset($object->note); // ->note_private and note_public already defined + unset($object->nom); // ->name already defined and nom deprecated + unset($object->name_bis); // ->name_alias already defined + unset($object->note); // ->note_private and note_public already defined unset($object->departement); unset($object->departement_code); unset($object->pays); @@ -1693,7 +1694,7 @@ class Thirdparties extends DolibarrApi unset($object->lines); unset($object->thirdparty); - unset($object->fk_delivery_address); // deprecated feature + unset($object->fk_delivery_address); // deprecated feature return $object; } @@ -1722,7 +1723,7 @@ class Thirdparties extends DolibarrApi * * Return an array with thirdparty informations * - * @param int $rowid Id of third party to load + * @param int $rowid Id of third party to load * @param string $ref Reference of third party, name (Warning, this can return several records) * @param string $ref_ext External reference of third party (Warning, this information is a free field not provided by Dolibarr) * @param string $ref_int Internal reference of third party (not used by dolibarr) @@ -1740,20 +1741,21 @@ class Thirdparties extends DolibarrApi */ private function _fetch($rowid, $ref = '', $ref_ext = '', $ref_int = '', $idprof1 = '', $idprof2 = '', $idprof3 = '', $idprof4 = '', $idprof5 = '', $idprof6 = '', $email = '', $ref_alias = '') { - if(! DolibarrApiAccess::$user->rights->societe->lire) { + global $conf; + if (!DolibarrApiAccess::$user->rights->societe->lire) { throw new RestException(401); } $result = $this->company->fetch($rowid, $ref, $ref_ext, $ref_int, $idprof1, $idprof2, $idprof3, $idprof4, $idprof5, $idprof6, $email, $ref_alias); - if( ! $result ) { + if (!$result) { throw new RestException(404, 'Thirdparty not found'); } - if( ! DolibarrApi::_checkAccessToResource('societe', $this->company->id)) { + if (!DolibarrApi::_checkAccessToResource('societe', $this->company->id)) { throw new RestException(401, 'Access not allowed for login '.DolibarrApiAccess::$user->login); } - if (! empty($conf->global->FACTURE_DEPOSITS_ARE_JUST_PAYMENTS)) { + if (!empty($conf->global->FACTURE_DEPOSITS_ARE_JUST_PAYMENTS)) { $filterabsolutediscount = "fk_facture_source IS NULL"; // If we want deposit to be substracted to payments only and not to total of final invoice $filtercreditnote = "fk_facture_source IS NOT NULL"; // If we want deposit to be substracted to payments only and not to total of final invoice } else { diff --git a/htdocs/societe/class/companybankaccount.class.php b/htdocs/societe/class/companybankaccount.class.php index d403499a79e..5cfe6fa3709 100644 --- a/htdocs/societe/class/companybankaccount.class.php +++ b/htdocs/societe/class/companybankaccount.class.php @@ -25,7 +25,7 @@ * \brief File of class to manage bank accounts description of third parties */ -require_once DOL_DOCUMENT_ROOT .'/compta/bank/class/account.class.php'; +require_once DOL_DOCUMENT_ROOT.'/compta/bank/class/account.class.php'; /** @@ -81,34 +81,34 @@ class CompanyBankAccount extends Account public function create(User $user = null, $notrigger = 0) { $now = dol_now(); - $error = 0; + $error = 0; // Correct default_rib to be sure to have always one default $sql = "SELECT rowid FROM ".MAIN_DB_PREFIX."societe_rib where fk_soc = ".$this->socid." AND default_rib = 1 AND type = 'ban'"; $result = $this->db->query($sql); if ($result) { - $numrows=$this->db->num_rows($result); + $numrows = $this->db->num_rows($result); if ($this->default_rib && $numrows > 0) $this->default_rib = 0; if (empty($this->default_rib) && $numrows == 0) $this->default_rib = 1; } $sql = "INSERT INTO ".MAIN_DB_PREFIX."societe_rib (fk_soc, type, datec)"; - $sql.= " VALUES (".$this->socid.", 'ban', '".$this->db->idate($now)."')"; - $resql=$this->db->query($sql); + $sql .= " VALUES (".$this->socid.", 'ban', '".$this->db->idate($now)."')"; + $resql = $this->db->query($sql); if ($resql) { if ($this->db->affected_rows($resql)) { $this->id = $this->db->last_insert_id(MAIN_DB_PREFIX."societe_rib"); - if (! $notrigger) + if (!$notrigger) { // Call trigger - $result=$this->call_trigger('COMPANY_RIB_CREATE', $user); + $result = $this->call_trigger('COMPANY_RIB_CREATE', $user); if ($result < 0) $error++; // End call triggers - if (! $error) + if (!$error) { return 1; } @@ -215,14 +215,14 @@ class CompanyBankAccount extends Account if (empty($id) && empty($socid)) return -1; $sql = "SELECT rowid, type, fk_soc, bank, number, code_banque, code_guichet, cle_rib, bic, iban_prefix as iban, domiciliation, proprio,"; - $sql.= " owner_address, default_rib, label, datec, tms as datem, rum, frstrecur, date_rum"; - $sql.= " FROM ".MAIN_DB_PREFIX."societe_rib"; - if ($id) $sql.= " WHERE rowid = ".$id; + $sql .= " owner_address, default_rib, label, datec, tms as datem, rum, frstrecur, date_rum"; + $sql .= " FROM ".MAIN_DB_PREFIX."societe_rib"; + if ($id) $sql .= " WHERE rowid = ".$id; if ($socid) { - $sql.= " WHERE fk_soc = ".$socid; - if ($default > -1) $sql.=" AND default_rib = ".$this->db->escape($default); - if ($type) $sql.= " AND type ='".$this->db->escape($type)."'"; + $sql .= " WHERE fk_soc = ".$socid; + if ($default > -1) $sql .= " AND default_rib = ".$this->db->escape($default); + if ($type) $sql .= " AND type ='".$this->db->escape($type)."'"; } $resql = $this->db->query($sql); @@ -232,10 +232,10 @@ class CompanyBankAccount extends Account { $obj = $this->db->fetch_object($resql); - $this->ref = $obj->fk_soc.'-'.$obj->label; // Generate an artificial ref + $this->ref = $obj->fk_soc.'-'.$obj->label; // Generate an artificial ref - $this->id = $obj->rowid; - $this->type = $obj->type; + $this->id = $obj->rowid; + $this->type = $obj->type; $this->socid = $obj->fk_soc; $this->bank = $obj->bank; $this->code_banque = $obj->code_banque; @@ -243,7 +243,7 @@ class CompanyBankAccount extends Account $this->number = $obj->number; $this->cle_rib = $obj->cle_rib; $this->bic = $obj->bic; - $this->iban = $obj->iban; + $this->iban = $obj->iban; $this->domiciliation = $obj->domiciliation; $this->proprio = $obj->proprio; $this->owner_address = $obj->owner_address; @@ -279,31 +279,31 @@ class CompanyBankAccount extends Account $error = 0; - dol_syslog(get_class($this) . "::delete ".$this->id, LOG_DEBUG); + dol_syslog(get_class($this)."::delete ".$this->id, LOG_DEBUG); $this->db->begin(); - if (! $error && ! $notrigger) + if (!$error && !$notrigger) { // Call trigger - $result=$this->call_trigger('COMPANY_RIB_DELETE', $user); + $result = $this->call_trigger('COMPANY_RIB_DELETE', $user); if ($result < 0) $error++; // End call triggers } - if (! $error) + if (!$error) { - $sql = "DELETE FROM " . MAIN_DB_PREFIX . "societe_rib"; - $sql .= " WHERE rowid = " . $this->id; + $sql = "DELETE FROM ".MAIN_DB_PREFIX."societe_rib"; + $sql .= " WHERE rowid = ".$this->id; - if (! $this->db->query($sql)) + if (!$this->db->query($sql)) { $error++; - $this->errors[]=$this->db->lasterror(); + $this->errors[] = $this->db->lasterror(); } } - if (! $error) + if (!$error) { $this->db->commit(); return 1; @@ -311,7 +311,7 @@ class CompanyBankAccount extends Account else { $this->db->rollback(); - return -1*$error; + return -1 * $error; } } @@ -325,7 +325,7 @@ class CompanyBankAccount extends Account { $rib = ''; - if ($this->code_banque || $this->code_guichet || $this->number || $this->cle_rib || $this->iban || $this->bic ) { + if ($this->code_banque || $this->code_guichet || $this->number || $this->cle_rib || $this->iban || $this->bic) { if ($this->label && $displayriblabel) { $rib = $this->label." : "; } @@ -345,7 +345,7 @@ class CompanyBankAccount extends Account public function setAsDefault($rib = 0) { $sql1 = "SELECT rowid as id, fk_soc FROM ".MAIN_DB_PREFIX."societe_rib"; - $sql1.= " WHERE rowid = ".($rib?$rib:$this->id); + $sql1 .= " WHERE rowid = ".($rib ? $rib : $this->id); dol_syslog(get_class($this).'::setAsDefault', LOG_DEBUG); $result1 = $this->db->query($sql1); @@ -362,12 +362,12 @@ class CompanyBankAccount extends Account $this->db->begin(); $sql2 = "UPDATE ".MAIN_DB_PREFIX."societe_rib SET default_rib = 0"; - $sql2.= " WHERE type = 'ban' AND fk_soc = ".$obj->fk_soc; + $sql2 .= " WHERE type = 'ban' AND fk_soc = ".$obj->fk_soc; dol_syslog(get_class($this).'::setAsDefault', LOG_DEBUG); $result2 = $this->db->query($sql2); $sql3 = "UPDATE ".MAIN_DB_PREFIX."societe_rib SET default_rib = 1"; - $sql3.= " WHERE rowid = ".$obj->id; + $sql3 .= " WHERE rowid = ".$obj->id; dol_syslog(get_class($this).'::setAsDefault', LOG_DEBUG); $result3 = $this->db->query($sql3); diff --git a/htdocs/societe/class/societe.class.php b/htdocs/societe/class/societe.class.php index 21213272a26..788fc45ee7e 100644 --- a/htdocs/societe/class/societe.class.php +++ b/htdocs/societe/class/societe.class.php @@ -47,7 +47,7 @@ class Societe extends CommonObject /** * @var string ID to identify managed object */ - public $element='societe'; + public $element = 'societe'; /** * @var string Name of table without prefix where object is stored @@ -57,18 +57,18 @@ class Societe extends CommonObject /** * @var int Field with ID of parent key if this field has a parent */ - public $fk_element='fk_soc'; + public $fk_element = 'fk_soc'; - public $fieldsforcombobox='nom,name_alias'; + public $fieldsforcombobox = 'nom,name_alias'; /** * @var array List of child tables. To test if we can delete object. */ - protected $childtables=array("supplier_proposal"=>'SupplierProposal',"propal"=>'Proposal',"commande"=>'Order',"facture"=>'Invoice',"facture_rec"=>'RecurringInvoiceTemplate',"contrat"=>'Contract',"fichinter"=>'Fichinter',"facture_fourn"=>'SupplierInvoice',"commande_fournisseur"=>'SupplierOrder',"projet"=>'Project',"expedition"=>'Shipment',"prelevement_lignes"=>'DirectDebitRecord'); + protected $childtables = array("supplier_proposal"=>'SupplierProposal', "propal"=>'Proposal', "commande"=>'Order', "facture"=>'Invoice', "facture_rec"=>'RecurringInvoiceTemplate', "contrat"=>'Contract', "fichinter"=>'Fichinter', "facture_fourn"=>'SupplierInvoice', "commande_fournisseur"=>'SupplierOrder', "projet"=>'Project', "expedition"=>'Shipment', "prelevement_lignes"=>'DirectDebitRecord'); /** * @var array List of child tables. To know object to delete on cascade. */ - protected $childtablesoncascade=array("societe_prices", "societe_log", "societe_address", "product_fournisseur_price", "product_customer_price_log", "product_customer_price", "socpeople", "adherent", "societe_account", "societe_rib", "societe_remise", "societe_remise_except", "societe_commerciaux", "categorie", "notify", "notify_def", "actioncomm"); + protected $childtablesoncascade = array("societe_prices", "societe_log", "societe_address", "product_fournisseur_price", "product_customer_price_log", "product_customer_price", "socpeople", "adherent", "societe_account", "societe_rib", "societe_remise", "societe_remise_except", "societe_commerciaux", "categorie", "notify", "notify_def", "actioncomm"); /** * @var string String with name of icon for myobject. Must be the part after the 'object_' into object_myobject.png @@ -92,20 +92,20 @@ class Societe extends CommonObject /** * @var array Array with all fields and their property. Do not use it as a static var. It may be modified by constructor. */ - public $fields=array( - 'rowid' =>array('type'=>'integer', 'label'=>'TechnicalID', 'enabled'=>1, 'visible'=>-2, 'notnull'=>1, 'index'=>1, 'position'=>1, 'comment'=>'Id'), - 'nom' =>array('type'=>'varchar(128)', 'label'=>'Name', 'enabled'=>1, 'visible'=>1, 'notnull'=>1, 'showoncombobox'=>1, 'index'=>1, 'position'=>10, 'searchall'=>1, 'comment'=>'Reference of object'), - 'name_alias' =>array('type'=>'varchar(128)', 'label'=>'Name', 'enabled'=>1, 'visible'=>1, 'notnull'=>1, 'showoncombobox'=>1, 'index'=>1, 'position'=>10, 'searchall'=>1, 'comment'=>'Reference of object'), - 'entity' =>array('type'=>'integer', 'label'=>'Entity', 'enabled'=>1, 'visible'=>0, 'default'=>1, 'notnull'=>1, 'index'=>1, 'position'=>20), - 'note_public' =>array('type'=>'text', 'label'=>'NotePublic', 'enabled'=>1, 'visible'=>0, 'position'=>60), - 'note_private' =>array('type'=>'text', 'label'=>'NotePrivate', 'enabled'=>1, 'visible'=>0, 'position'=>61), - 'datec' =>array('type'=>'datetime', 'label'=>'DateCreation', 'enabled'=>1, 'visible'=>-2, 'notnull'=>1, 'position'=>500), - 'tms' =>array('type'=>'timestamp', 'label'=>'DateModification', 'enabled'=>1, 'visible'=>-2, 'notnull'=>1, 'position'=>501), + public $fields = array( + 'rowid' =>array('type'=>'integer', 'label'=>'TechnicalID', 'enabled'=>1, 'visible'=>-2, 'notnull'=>1, 'index'=>1, 'position'=>1, 'comment'=>'Id'), + 'nom' =>array('type'=>'varchar(128)', 'label'=>'Name', 'enabled'=>1, 'visible'=>1, 'notnull'=>1, 'showoncombobox'=>1, 'index'=>1, 'position'=>10, 'searchall'=>1, 'comment'=>'Reference of object'), + 'name_alias' =>array('type'=>'varchar(128)', 'label'=>'Name', 'enabled'=>1, 'visible'=>1, 'notnull'=>1, 'showoncombobox'=>1, 'index'=>1, 'position'=>10, 'searchall'=>1, 'comment'=>'Reference of object'), + 'entity' =>array('type'=>'integer', 'label'=>'Entity', 'enabled'=>1, 'visible'=>0, 'default'=>1, 'notnull'=>1, 'index'=>1, 'position'=>20), + 'note_public' =>array('type'=>'text', 'label'=>'NotePublic', 'enabled'=>1, 'visible'=>0, 'position'=>60), + 'note_private' =>array('type'=>'text', 'label'=>'NotePrivate', 'enabled'=>1, 'visible'=>0, 'position'=>61), + 'datec' =>array('type'=>'datetime', 'label'=>'DateCreation', 'enabled'=>1, 'visible'=>-2, 'notnull'=>1, 'position'=>500), + 'tms' =>array('type'=>'timestamp', 'label'=>'DateModification', 'enabled'=>1, 'visible'=>-2, 'notnull'=>1, 'position'=>501), //'date_valid' =>array('type'=>'datetime', 'label'=>'DateCreation', 'enabled'=>1, 'visible'=>-2, 'position'=>502), - 'fk_user_creat' =>array('type'=>'integer', 'label'=>'UserAuthor', 'enabled'=>1, 'visible'=>-2, 'notnull'=>1, 'position'=>510), - 'fk_user_modif' =>array('type'=>'integer', 'label'=>'UserModif', 'enabled'=>1, 'visible'=>-2, 'notnull'=>-1, 'position'=>511), + 'fk_user_creat' =>array('type'=>'integer', 'label'=>'UserAuthor', 'enabled'=>1, 'visible'=>-2, 'notnull'=>1, 'position'=>510), + 'fk_user_modif' =>array('type'=>'integer', 'label'=>'UserModif', 'enabled'=>1, 'visible'=>-2, 'notnull'=>-1, 'position'=>511), //'fk_user_valid' =>array('type'=>'integer', 'label'=>'UserValidation', 'enabled'=>1, 'visible'=>-1, 'position'=>512), - 'import_key' =>array('type'=>'varchar(14)', 'label'=>'ImportId', 'enabled'=>1, 'visible'=>-2, 'notnull'=>-1, 'index'=>1, 'position'=>1000), + 'import_key' =>array('type'=>'varchar(14)', 'label'=>'ImportId', 'enabled'=>1, 'visible'=>-2, 'notnull'=>-1, 'index'=>1, 'position'=>1000), ); @@ -147,7 +147,7 @@ class Societe extends CommonObject * Thirdparty status : 0=activity ceased, 1= in activity * @var int */ - public $status=1; + public $status = 1; /** * Id of department @@ -285,7 +285,7 @@ class Societe extends CommonObject public $prefix_comm; - public $tva_assuj=1; + public $tva_assuj = 1; /** * Intracommunitary VAT ID * @var string @@ -300,12 +300,12 @@ class Societe extends CommonObject public $managers; public $capital; - public $typent_id=0; + public $typent_id = 0; public $typent_code; public $effectif; - public $effectif_id=0; + public $effectif_id = 0; public $forme_juridique_code; - public $forme_juridique=0; + public $forme_juridique = 0; public $remise_percent; public $remise_supplier_percent; @@ -350,12 +350,12 @@ class Societe extends CommonObject * 0=no customer, 1=customer, 2=prospect, 3=customer and prospect * @var int */ - public $client=0; + public $client = 0; /** * 0=no prospect, 1=prospect * @var int */ - public $prospect=0; + public $prospect = 0; /** * 0=no supplier, 1=supplier * @var int @@ -501,7 +501,7 @@ class Societe extends CommonObject public $fk_incoterms; public $location_incoterms; - public $label_incoterms; //Used into tooltip + public $label_incoterms; //Used into tooltip // Multicurrency /** @@ -527,9 +527,9 @@ class Societe extends CommonObject $this->client = 0; $this->prospect = 0; $this->fournisseur = 0; - $this->typent_id = 0; - $this->effectif_id = 0; - $this->forme_juridique_code = 0; + $this->typent_id = 0; + $this->effectif_id = 0; + $this->forme_juridique_code = 0; $this->tva_assuj = 1; $this->status = 1; } @@ -544,17 +544,17 @@ class Societe extends CommonObject */ public function create(User $user) { - global $langs,$conf,$mysoc; + global $langs, $conf, $mysoc; - $error=0; + $error = 0; // Clean parameters - if (empty($this->status)) $this->status=0; - $this->name=$this->name?trim($this->name):trim($this->nom); - if (! empty($conf->global->MAIN_FIRST_TO_UPPER)) $this->name=ucwords($this->name); - $this->nom=$this->name; // For backward compatibility - if (empty($this->client)) $this->client=0; - if (empty($this->fournisseur)) $this->fournisseur=0; + if (empty($this->status)) $this->status = 0; + $this->name = $this->name ?trim($this->name) : trim($this->nom); + if (!empty($conf->global->MAIN_FIRST_TO_UPPER)) $this->name = ucwords($this->name); + $this->nom = $this->name; // For backward compatibility + if (empty($this->client)) $this->client = 0; + if (empty($this->fournisseur)) $this->fournisseur = 0; $this->import_key = trim($this->import_key); if (!empty($this->multicurrency_code)) $this->fk_multicurrency = MultiCurrency::getIdFromCode($this->db, $this->multicurrency_code); @@ -566,7 +566,7 @@ class Societe extends CommonObject dol_syslog(get_class($this)."::create ".$this->name); - $now=dol_now(); + $now = dol_now(); $this->db->begin(); @@ -580,24 +580,24 @@ class Societe extends CommonObject if ($result >= 0) { - $this->entity = ((isset($this->entity) && is_numeric($this->entity))?$this->entity:$conf->entity); + $this->entity = ((isset($this->entity) && is_numeric($this->entity)) ? $this->entity : $conf->entity); $sql = "INSERT INTO ".MAIN_DB_PREFIX."societe (nom, name_alias, entity, datec, fk_user_creat, canvas, status, ref_int, ref_ext, fk_stcomm, fk_incoterms, location_incoterms ,import_key, fk_multicurrency, multicurrency_code)"; - $sql.= " VALUES ('".$this->db->escape($this->name)."', '".$this->db->escape($this->name_alias)."', ".$this->db->escape($this->entity).", '".$this->db->idate($now)."'"; - $sql.= ", ".(! empty($user->id) ? "'".$user->id."'":"null"); - $sql.= ", ".(! empty($this->canvas) ? "'".$this->db->escape($this->canvas)."'":"null"); - $sql.= ", ".$this->status; - $sql.= ", ".(! empty($this->ref_int) ? "'".$this->db->escape($this->ref_int)."'":"null"); - $sql.= ", ".(! empty($this->ref_ext) ? "'".$this->db->escape($this->ref_ext)."'":"null"); - $sql.= ", 0"; - $sql.= ", ".(int) $this->fk_incoterms; - $sql.= ", '".$this->db->escape($this->location_incoterms)."'"; - $sql.= ", ".(! empty($this->import_key) ? "'".$this->db->escape($this->import_key)."'":"null"); - $sql.= ", ".(int) $this->fk_multicurrency; - $sql.= ", '".$this->db->escape($this->multicurrency_code)."')"; + $sql .= " VALUES ('".$this->db->escape($this->name)."', '".$this->db->escape($this->name_alias)."', ".$this->db->escape($this->entity).", '".$this->db->idate($now)."'"; + $sql .= ", ".(!empty($user->id) ? "'".$user->id."'" : "null"); + $sql .= ", ".(!empty($this->canvas) ? "'".$this->db->escape($this->canvas)."'" : "null"); + $sql .= ", ".$this->status; + $sql .= ", ".(!empty($this->ref_int) ? "'".$this->db->escape($this->ref_int)."'" : "null"); + $sql .= ", ".(!empty($this->ref_ext) ? "'".$this->db->escape($this->ref_ext)."'" : "null"); + $sql .= ", 0"; + $sql .= ", ".(int) $this->fk_incoterms; + $sql .= ", '".$this->db->escape($this->location_incoterms)."'"; + $sql .= ", ".(!empty($this->import_key) ? "'".$this->db->escape($this->import_key)."'" : "null"); + $sql .= ", ".(int) $this->fk_multicurrency; + $sql .= ", '".$this->db->escape($this->multicurrency_code)."')"; dol_syslog(get_class($this)."::create", LOG_DEBUG); - $result=$this->db->query($sql); + $result = $this->db->query($sql); if ($result) { $this->id = $this->db->last_insert_id(MAIN_DB_PREFIX."societe"); @@ -618,13 +618,13 @@ class Societe extends CommonObject if ($ret >= 0) { // Call trigger - $result=$this->call_trigger('COMPANY_CREATE', $user); + $result = $this->call_trigger('COMPANY_CREATE', $user); if ($result < 0) $error++; // End call triggers } else $error++; - if (! $error) + if (!$error) { dol_syslog(get_class($this)."::Create success id=".$this->id); $this->db->commit(); @@ -641,13 +641,13 @@ class Societe extends CommonObject { if ($this->db->lasterrno() == 'DB_ERROR_RECORD_ALREADY_EXISTS') { - $this->error=$langs->trans("ErrorCompanyNameAlreadyExists", $this->name); // duplicate on a field (code or profid or ...) - $result=-1; + $this->error = $langs->trans("ErrorCompanyNameAlreadyExists", $this->name); // duplicate on a field (code or profid or ...) + $result = -1; } else { - $this->error=$this->db->lasterror(); - $result=-2; + $this->error = $this->db->lasterror(); + $result = -2; } $this->db->rollback(); return $result; @@ -673,12 +673,12 @@ class Societe extends CommonObject { // phpcs:enable require_once DOL_DOCUMENT_ROOT.'/contact/class/contact.class.php'; - $contact=new Contact($this->db); + $contact = new Contact($this->db); $contact->name = $this->name_bis; $contact->firstname = $this->firstname; $contact->civility_id = $this->civility_id; - $contact->socid = $this->id; // fk_soc + $contact->socid = $this->id; // fk_soc $contact->statut = 1; $contact->priv = 0; $contact->country_id = $this->country_id; @@ -694,7 +694,7 @@ class Societe extends CommonObject { $this->error = $contact->error; $this->errors = $contact->errors; - dol_syslog(get_class($this)."::create_individual ERROR:" . $this->error, LOG_ERR); + dol_syslog(get_class($this)."::create_individual ERROR:".$this->error, LOG_ERR); } return $result; @@ -711,13 +711,13 @@ class Societe extends CommonObject global $conf, $langs, $mysoc; $error = 0; - $this->errors=array(); + $this->errors = array(); $result = 0; - $this->name = trim($this->name); - $this->nom=$this->name; // For backward compatibility + $this->name = trim($this->name); + $this->nom = $this->name; // For backward compatibility - if (! $this->name) + if (!$this->name) { $this->errors[] = 'ErrorBadThirdPartyName'; $result = -2; @@ -774,32 +774,22 @@ class Societe extends CommonObject } // Check for duplicate or mandatory fields defined into setup - $array_to_check=array('IDPROF1','IDPROF2','IDPROF3','IDPROF4','IDPROF5','IDPROF6','EMAIL'); - foreach($array_to_check as $key) + $array_to_check = array('IDPROF1', 'IDPROF2', 'IDPROF3', 'IDPROF4', 'IDPROF5', 'IDPROF6', 'EMAIL'); + foreach ($array_to_check as $key) { - $keymin=strtolower($key); - $i=(int) preg_replace('/[^0-9]/', '', $key); - $vallabel=$this->$keymin; + $keymin = strtolower($key); + $i = (int) preg_replace('/[^0-9]/', '', $key); + $vallabel = $this->$keymin; if ($i > 0) { if ($this->isACompany()) { - // Check for unicity - if ($vallabel && $this->id_prof_verifiable($i)) - { - if ($this->id_prof_exists($keymin, $vallabel, ($this->id > 0 ? $this->id : 0))) - { - $langs->load("errors"); - $error++; $this->errors[] = $langs->transcountry('ProfId'.$i, $this->country_code)." ".$langs->trans("ErrorProdIdAlreadyExist", $vallabel).' ('.$langs->trans("ForbiddenBySetupRules").')'; - } - } - - // Check for mandatory prof id (but only if country is other than ours) + // Check for mandatory prof id (but only if country is same than ours) if ($mysoc->country_id > 0 && $this->country_id == $mysoc->country_id) { - $idprof_mandatory ='SOCIETE_'.$key.'_MANDATORY'; - if (! $vallabel && ! empty($conf->global->$idprof_mandatory)) + $idprof_mandatory = 'SOCIETE_'.$key.'_MANDATORY'; + if (!$vallabel && !empty($conf->global->$idprof_mandatory)) { $langs->load("errors"); $error++; @@ -807,6 +797,17 @@ class Societe extends CommonObject } } } + + // Check for unicity + if (!$error && $vallabel && $this->id_prof_verifiable($i)) + { + if ($this->id_prof_exists($keymin, $vallabel, ($this->id > 0 ? $this->id : 0))) + { + $langs->load("errors"); + $error++; + $this->errors[] = $langs->transcountry('ProfId'.$i, $this->country_code)." ".$langs->trans("ErrorProdIdAlreadyExist", $vallabel).' ('.$langs->trans("ForbiddenBySetupRules").')'; + } + } } else { @@ -814,8 +815,16 @@ class Societe extends CommonObject //var_dump($conf->global->SOCIETE_EMAIL_MANDATORY); if ($key == 'EMAIL') { + // Check for mandatory + if (!empty($conf->global->SOCIETE_EMAIL_MANDATORY) && !isValidEMail($this->email)) + { + $langs->load("errors"); + $error++; + $this->errors[] = $langs->trans("ErrorBadEMail", $this->email).' ('.$langs->trans("ForbiddenBySetupRules").')'; + } + // Check for unicity - if ($vallabel && ! empty($conf->global->SOCIETE_EMAIL_UNIQUE)) + if (!$error && $vallabel && !empty($conf->global->SOCIETE_EMAIL_UNIQUE)) { if ($this->id_prof_exists($keymin, $vallabel, ($this->id > 0 ? $this->id : 0))) { @@ -823,14 +832,6 @@ class Societe extends CommonObject $error++; $this->errors[] = $langs->trans('Email')." ".$langs->trans("ErrorProdIdAlreadyExist", $vallabel).' ('.$langs->trans("ForbiddenBySetupRules").')'; } } - - // Check for mandatory - if (! empty($conf->global->SOCIETE_EMAIL_MANDATORY) && ! isValidEMail($this->email)) - { - $langs->load("errors"); - $error++; - $this->errors[] = $langs->trans("ErrorBadEMail", $this->email).' ('.$langs->trans("ForbiddenBySetupRules").')'; - } } } } @@ -854,47 +855,47 @@ class Societe extends CommonObject */ public function update($id, $user = '', $call_trigger = 1, $allowmodcodeclient = 0, $allowmodcodefournisseur = 0, $action = 'update', $nosyncmember = 1) { - global $langs,$conf,$hookmanager; + global $langs, $conf, $hookmanager; require_once DOL_DOCUMENT_ROOT.'/core/lib/functions2.lib.php'; if (empty($id)) $id = $this->id; - $error=0; + $error = 0; dol_syslog(get_class($this)."::Update id=".$id." call_trigger=".$call_trigger." allowmodcodeclient=".$allowmodcodeclient." allowmodcodefournisseur=".$allowmodcodefournisseur); - $now=dol_now(); + $now = dol_now(); // Clean parameters - $this->id = $id; - $this->entity = ((isset($this->entity) && is_numeric($this->entity))?$this->entity:$conf->entity); - $this->name = $this->name?trim($this->name):trim($this->nom); - $this->nom = $this->name; // For backward compatibility - $this->name_alias = trim($this->name_alias); + $this->id = $id; + $this->entity = ((isset($this->entity) && is_numeric($this->entity)) ? $this->entity : $conf->entity); + $this->name = $this->name ?trim($this->name) : trim($this->nom); + $this->nom = $this->name; // For backward compatibility + $this->name_alias = trim($this->name_alias); $this->ref_ext = trim($this->ref_ext); - $this->address = $this->address?trim($this->address):trim($this->address); - $this->zip = $this->zip?trim($this->zip):trim($this->zip); - $this->town = $this->town?trim($this->town):trim($this->town); - $this->state_id = trim($this->state_id); - $this->country_id = ($this->country_id > 0)?$this->country_id:0; + $this->address = $this->address ?trim($this->address) : trim($this->address); + $this->zip = $this->zip ?trim($this->zip) : trim($this->zip); + $this->town = $this->town ?trim($this->town) : trim($this->town); + $this->state_id = trim($this->state_id); + $this->country_id = ($this->country_id > 0) ? $this->country_id : 0; $this->phone = trim($this->phone); $this->phone = preg_replace("/\s/", "", $this->phone); $this->phone = preg_replace("/\./", "", $this->phone); $this->fax = trim($this->fax); $this->fax = preg_replace("/\s/", "", $this->fax); $this->fax = preg_replace("/\./", "", $this->fax); - $this->email = trim($this->email); - $this->url = $this->url?clean_url($this->url, 0):''; + $this->email = trim($this->email); + $this->url = $this->url ?clean_url($this->url, 0) : ''; $this->note_private = trim($this->note_private); $this->note_public = trim($this->note_public); $this->idprof1 = trim($this->idprof1); $this->idprof2 = trim($this->idprof2); $this->idprof3 = trim($this->idprof3); $this->idprof4 = trim($this->idprof4); - $this->idprof5 = (! empty($this->idprof5)?trim($this->idprof5):''); - $this->idprof6 = (! empty($this->idprof6)?trim($this->idprof6):''); - $this->prefix_comm = trim($this->prefix_comm); + $this->idprof5 = (!empty($this->idprof5) ?trim($this->idprof5) : ''); + $this->idprof6 = (!empty($this->idprof6) ?trim($this->idprof6) : ''); + $this->prefix_comm = trim($this->prefix_comm); $this->outstanding_limit = price2num($this->outstanding_limit); $this->order_min_amount = price2num($this->order_min_amount); $this->supplier_order_min_amount = price2num($this->supplier_order_min_amount); @@ -911,64 +912,64 @@ class Societe extends CommonObject } // Local taxes - $this->localtax1_assuj=trim($this->localtax1_assuj); - $this->localtax2_assuj=trim($this->localtax2_assuj); + $this->localtax1_assuj = trim($this->localtax1_assuj); + $this->localtax2_assuj = trim($this->localtax2_assuj); - $this->localtax1_value=trim($this->localtax1_value); - $this->localtax2_value=trim($this->localtax2_value); + $this->localtax1_value = trim($this->localtax1_value); + $this->localtax2_value = trim($this->localtax2_value); - if ($this->capital != '') $this->capital=price2num(trim($this->capital)); - if (! is_numeric($this->capital)) $this->capital = ''; // '' = undef + if ($this->capital != '') $this->capital = price2num(trim($this->capital)); + if (!is_numeric($this->capital)) $this->capital = ''; // '' = undef - $this->effectif_id=trim($this->effectif_id); - $this->forme_juridique_code=trim($this->forme_juridique_code); + $this->effectif_id = trim($this->effectif_id); + $this->forme_juridique_code = trim($this->forme_juridique_code); //Gencod - $this->barcode=trim($this->barcode); + $this->barcode = trim($this->barcode); // For automatic creation if ($this->code_client == -1 || $this->code_client === 'auto') $this->get_codeclient($this, 0); if ($this->code_fournisseur == -1 || $this->code_fournisseur === 'auto') $this->get_codefournisseur($this, 1); - $this->code_compta=trim($this->code_compta); - $this->code_compta_fournisseur=trim($this->code_compta_fournisseur); + $this->code_compta = trim($this->code_compta); + $this->code_compta_fournisseur = trim($this->code_compta_fournisseur); // Check parameters. More tests are done later in the ->verify() - if (! is_numeric($this->client) && ! is_numeric($this->fournisseur)) + if (!is_numeric($this->client) && !is_numeric($this->fournisseur)) { $langs->load("errors"); $this->error = $langs->trans("BadValueForParameterClientOrSupplier"); return -1; } - $customer=false; - if (! empty($allowmodcodeclient) && ! empty($this->client)) + $customer = false; + if (!empty($allowmodcodeclient) && !empty($this->client)) { // Attention get_codecompta peut modifier le code suivant le module utilise if (empty($this->code_compta)) { - $ret=$this->get_codecompta('customer'); + $ret = $this->get_codecompta('customer'); if ($ret < 0) return -1; } - $customer=true; + $customer = true; } - $supplier=false; - if (! empty($allowmodcodefournisseur) && ! empty($this->fournisseur)) + $supplier = false; + if (!empty($allowmodcodefournisseur) && !empty($this->fournisseur)) { // Attention get_codecompta peut modifier le code suivant le module utilise if ($this->code_compta_fournisseur == "") { - $ret=$this->get_codecompta('supplier'); + $ret = $this->get_codecompta('supplier'); if ($ret < 0) return -1; } - $supplier=true; + $supplier = true; } //Web services - $this->webservices_url = $this->webservices_url?clean_url($this->webservices_url, 0):''; + $this->webservices_url = $this->webservices_url ?clean_url($this->webservices_url, 0) : ''; $this->webservices_key = trim($this->webservices_key); //Incoterms @@ -992,11 +993,11 @@ class Societe extends CommonObject { if (in_array('ErrorBadCustomerCodeSyntax', $this->errors) && is_object($this->oldcopy) && $this->oldcopy->code_client == $this->code_client) { - if (($key = array_search('ErrorBadCustomerCodeSyntax', $this->errors)) !== false) unset($this->errors[$key]); // Remove error message + if (($key = array_search('ErrorBadCustomerCodeSyntax', $this->errors)) !== false) unset($this->errors[$key]); // Remove error message } if (in_array('ErrorBadSupplierCodeSyntax', $this->errors) && is_object($this->oldcopy) && $this->oldcopy->code_fournisseur == $this->code_fournisseur) { - if (($key = array_search('ErrorBadSupplierCodeSyntax', $this->errors)) !== false) unset($this->errors[$key]); // Remove error message + if (($key = array_search('ErrorBadSupplierCodeSyntax', $this->errors)) !== false) unset($this->errors[$key]); // Remove error message } if (empty($this->errors)) // If there is no more error, we can make like if there is no error at all { @@ -1010,117 +1011,117 @@ class Societe extends CommonObject dol_syslog(get_class($this)."::update verify ok or not done"); $sql = "UPDATE ".MAIN_DB_PREFIX."societe SET "; - $sql .= "entity = " . $this->db->escape($this->entity); - $sql .= ",nom = '" . $this->db->escape($this->name) ."'"; // Required - $sql .= ",name_alias = '" . $this->db->escape($this->name_alias) ."'"; - $sql .= ",ref_ext = " .(! empty($this->ref_ext)?"'".$this->db->escape($this->ref_ext) ."'":"null"); - $sql .= ",address = '" . $this->db->escape($this->address) ."'"; + $sql .= "entity = ".$this->db->escape($this->entity); + $sql .= ",nom = '".$this->db->escape($this->name)."'"; // Required + $sql .= ",name_alias = '".$this->db->escape($this->name_alias)."'"; + $sql .= ",ref_ext = ".(!empty($this->ref_ext) ? "'".$this->db->escape($this->ref_ext)."'" : "null"); + $sql .= ",address = '".$this->db->escape($this->address)."'"; - $sql .= ",zip = ".(! empty($this->zip)?"'".$this->db->escape($this->zip)."'":"null"); - $sql .= ",town = ".(! empty($this->town)?"'".$this->db->escape($this->town)."'":"null"); + $sql .= ",zip = ".(!empty($this->zip) ? "'".$this->db->escape($this->zip)."'" : "null"); + $sql .= ",town = ".(!empty($this->town) ? "'".$this->db->escape($this->town)."'" : "null"); - $sql .= ",fk_departement = '" . (! empty($this->state_id)?$this->state_id:'0') ."'"; - $sql .= ",fk_pays = '" . (! empty($this->country_id)?$this->country_id:'0') ."'"; + $sql .= ",fk_departement = '".(!empty($this->state_id) ? $this->state_id : '0')."'"; + $sql .= ",fk_pays = '".(!empty($this->country_id) ? $this->country_id : '0')."'"; - $sql .= ",phone = ".(! empty($this->phone)?"'".$this->db->escape($this->phone)."'":"null"); - $sql .= ",fax = ".(! empty($this->fax)?"'".$this->db->escape($this->fax)."'":"null"); - $sql .= ",email = ".(! empty($this->email)?"'".$this->db->escape($this->email)."'":"null"); + $sql .= ",phone = ".(!empty($this->phone) ? "'".$this->db->escape($this->phone)."'" : "null"); + $sql .= ",fax = ".(!empty($this->fax) ? "'".$this->db->escape($this->fax)."'" : "null"); + $sql .= ",email = ".(!empty($this->email) ? "'".$this->db->escape($this->email)."'" : "null"); $sql .= ", socialnetworks = '".$this->db->escape(json_encode($this->socialnetworks))."'"; - $sql .= ",url = ".(! empty($this->url)?"'".$this->db->escape($this->url)."'":"null"); + $sql .= ",url = ".(!empty($this->url) ? "'".$this->db->escape($this->url)."'" : "null"); - $sql .= ",parent = " . ($this->parent > 0 ? $this->parent : "null"); + $sql .= ",parent = ".($this->parent > 0 ? $this->parent : "null"); - $sql .= ",note_private = ".(! empty($this->note_private)?"'".$this->db->escape($this->note_private)."'":"null"); - $sql .= ",note_public = ".(! empty($this->note_public)?"'".$this->db->escape($this->note_public)."'":"null"); + $sql .= ",note_private = ".(!empty($this->note_private) ? "'".$this->db->escape($this->note_private)."'" : "null"); + $sql .= ",note_public = ".(!empty($this->note_public) ? "'".$this->db->escape($this->note_public)."'" : "null"); - $sql .= ",siren = '". $this->db->escape($this->idprof1) ."'"; - $sql .= ",siret = '". $this->db->escape($this->idprof2) ."'"; - $sql .= ",ape = '". $this->db->escape($this->idprof3) ."'"; - $sql .= ",idprof4 = '". $this->db->escape($this->idprof4) ."'"; - $sql .= ",idprof5 = '". $this->db->escape($this->idprof5) ."'"; - $sql .= ",idprof6 = '". $this->db->escape($this->idprof6) ."'"; + $sql .= ",siren = '".$this->db->escape($this->idprof1)."'"; + $sql .= ",siret = '".$this->db->escape($this->idprof2)."'"; + $sql .= ",ape = '".$this->db->escape($this->idprof3)."'"; + $sql .= ",idprof4 = '".$this->db->escape($this->idprof4)."'"; + $sql .= ",idprof5 = '".$this->db->escape($this->idprof5)."'"; + $sql .= ",idprof6 = '".$this->db->escape($this->idprof6)."'"; - $sql .= ",tva_assuj = ".($this->tva_assuj!=''?"'".$this->db->escape($this->tva_assuj)."'":"null"); - $sql .= ",tva_intra = '" . $this->db->escape($this->tva_intra) ."'"; - $sql .= ",status = " .$this->status; + $sql .= ",tva_assuj = ".($this->tva_assuj != '' ? "'".$this->db->escape($this->tva_assuj)."'" : "null"); + $sql .= ",tva_intra = '".$this->db->escape($this->tva_intra)."'"; + $sql .= ",status = ".$this->status; // Local taxes - $sql .= ",localtax1_assuj = ".($this->localtax1_assuj!=''?"'".$this->db->escape($this->localtax1_assuj)."'":"null"); - $sql .= ",localtax2_assuj = ".($this->localtax2_assuj!=''?"'".$this->db->escape($this->localtax2_assuj)."'":"null"); - if($this->localtax1_assuj==1) + $sql .= ",localtax1_assuj = ".($this->localtax1_assuj != '' ? "'".$this->db->escape($this->localtax1_assuj)."'" : "null"); + $sql .= ",localtax2_assuj = ".($this->localtax2_assuj != '' ? "'".$this->db->escape($this->localtax2_assuj)."'" : "null"); + if ($this->localtax1_assuj == 1) { - if($this->localtax1_value!='') + if ($this->localtax1_value != '') { - $sql .=",localtax1_value =".$this->localtax1_value; + $sql .= ",localtax1_value =".$this->localtax1_value; } - else $sql .=",localtax1_value =0.000"; + else $sql .= ",localtax1_value =0.000"; } - else $sql .=",localtax1_value =0.000"; + else $sql .= ",localtax1_value =0.000"; - if($this->localtax2_assuj==1) + if ($this->localtax2_assuj == 1) { - if($this->localtax2_value!='') + if ($this->localtax2_value != '') { - $sql .=",localtax2_value =".$this->localtax2_value; + $sql .= ",localtax2_value =".$this->localtax2_value; } - else $sql .=",localtax2_value =0.000"; + else $sql .= ",localtax2_value =0.000"; } - else $sql .=",localtax2_value =0.000"; + else $sql .= ",localtax2_value =0.000"; $sql .= ",capital = ".($this->capital == '' ? "null" : $this->capital); - $sql .= ",prefix_comm = ".(! empty($this->prefix_comm)?"'".$this->db->escape($this->prefix_comm)."'":"null"); + $sql .= ",prefix_comm = ".(!empty($this->prefix_comm) ? "'".$this->db->escape($this->prefix_comm)."'" : "null"); - $sql .= ",fk_effectif = ".(! empty($this->effectif_id)?"'".$this->db->escape($this->effectif_id)."'":"null"); + $sql .= ",fk_effectif = ".(!empty($this->effectif_id) ? "'".$this->db->escape($this->effectif_id)."'" : "null"); if (isset($this->stcomm_id)) { - $sql .= ",fk_stcomm=".(!empty($this->stcomm_id) ? $this->stcomm_id : "0"); + $sql .= ",fk_stcomm=".(!empty($this->stcomm_id) ? $this->stcomm_id : "0"); } - $sql .= ",fk_typent = ".(! empty($this->typent_id)?"'".$this->db->escape($this->typent_id)."'":"0"); + $sql .= ",fk_typent = ".(!empty($this->typent_id) ? "'".$this->db->escape($this->typent_id)."'" : "0"); - $sql .= ",fk_forme_juridique = ".(! empty($this->forme_juridique_code)?"'".$this->db->escape($this->forme_juridique_code)."'":"null"); + $sql .= ",fk_forme_juridique = ".(!empty($this->forme_juridique_code) ? "'".$this->db->escape($this->forme_juridique_code)."'" : "null"); - $sql .= ",mode_reglement = ".(! empty($this->mode_reglement_id)?"'".$this->db->escape($this->mode_reglement_id)."'":"null"); - $sql .= ",cond_reglement = ".(! empty($this->cond_reglement_id)?"'".$this->db->escape($this->cond_reglement_id)."'":"null"); - $sql .= ",mode_reglement_supplier = ".(! empty($this->mode_reglement_supplier_id)?"'".$this->db->escape($this->mode_reglement_supplier_id)."'":"null"); - $sql .= ",cond_reglement_supplier = ".(! empty($this->cond_reglement_supplier_id)?"'".$this->db->escape($this->cond_reglement_supplier_id)."'":"null"); - $sql .= ",fk_shipping_method = ".(! empty($this->shipping_method_id)?"'".$this->db->escape($this->shipping_method_id)."'":"null"); + $sql .= ",mode_reglement = ".(!empty($this->mode_reglement_id) ? "'".$this->db->escape($this->mode_reglement_id)."'" : "null"); + $sql .= ",cond_reglement = ".(!empty($this->cond_reglement_id) ? "'".$this->db->escape($this->cond_reglement_id)."'" : "null"); + $sql .= ",mode_reglement_supplier = ".(!empty($this->mode_reglement_supplier_id) ? "'".$this->db->escape($this->mode_reglement_supplier_id)."'" : "null"); + $sql .= ",cond_reglement_supplier = ".(!empty($this->cond_reglement_supplier_id) ? "'".$this->db->escape($this->cond_reglement_supplier_id)."'" : "null"); + $sql .= ",fk_shipping_method = ".(!empty($this->shipping_method_id) ? "'".$this->db->escape($this->shipping_method_id)."'" : "null"); - $sql .= ",client = " . (! empty($this->client)?$this->client:0); - $sql .= ",fournisseur = " . (! empty($this->fournisseur)?$this->fournisseur:0); - $sql .= ",barcode = ".(! empty($this->barcode)?"'".$this->db->escape($this->barcode)."'":"null"); - $sql .= ",default_lang = ".(! empty($this->default_lang)?"'".$this->db->escape($this->default_lang)."'":"null"); - $sql .= ",logo = ".(! empty($this->logo)?"'".$this->db->escape($this->logo)."'":"null"); - $sql .= ",logo_squarred = ".(! empty($this->logo_squarred)?"'".$this->db->escape($this->logo_squarred)."'":"null"); - $sql .= ",outstanding_limit= ".($this->outstanding_limit!=''?$this->outstanding_limit:'null'); - $sql .= ",order_min_amount= ".($this->order_min_amount!=''?$this->order_min_amount:'null'); - $sql .= ",supplier_order_min_amount= ".($this->supplier_order_min_amount!=''?$this->supplier_order_min_amount:'null'); + $sql .= ",client = ".(!empty($this->client) ? $this->client : 0); + $sql .= ",fournisseur = ".(!empty($this->fournisseur) ? $this->fournisseur : 0); + $sql .= ",barcode = ".(!empty($this->barcode) ? "'".$this->db->escape($this->barcode)."'" : "null"); + $sql .= ",default_lang = ".(!empty($this->default_lang) ? "'".$this->db->escape($this->default_lang)."'" : "null"); + $sql .= ",logo = ".(!empty($this->logo) ? "'".$this->db->escape($this->logo)."'" : "null"); + $sql .= ",logo_squarred = ".(!empty($this->logo_squarred) ? "'".$this->db->escape($this->logo_squarred)."'" : "null"); + $sql .= ",outstanding_limit= ".($this->outstanding_limit != '' ? $this->outstanding_limit : 'null'); + $sql .= ",order_min_amount= ".($this->order_min_amount != '' ? $this->order_min_amount : 'null'); + $sql .= ",supplier_order_min_amount= ".($this->supplier_order_min_amount != '' ? $this->supplier_order_min_amount : 'null'); $sql .= ",fk_prospectlevel='".$this->db->escape($this->fk_prospectlevel)."'"; - $sql .= ",webservices_url = ".(! empty($this->webservices_url)?"'".$this->db->escape($this->webservices_url)."'":"null"); - $sql .= ",webservices_key = ".(! empty($this->webservices_key)?"'".$this->db->escape($this->webservices_key)."'":"null"); + $sql .= ",webservices_url = ".(!empty($this->webservices_url) ? "'".$this->db->escape($this->webservices_url)."'" : "null"); + $sql .= ",webservices_key = ".(!empty($this->webservices_key) ? "'".$this->db->escape($this->webservices_key)."'" : "null"); //Incoterms - $sql.= ", fk_incoterms = ".$this->fk_incoterms; - $sql.= ", location_incoterms = ".(! empty($this->location_incoterms)?"'".$this->db->escape($this->location_incoterms)."'":"null"); + $sql .= ", fk_incoterms = ".$this->fk_incoterms; + $sql .= ", location_incoterms = ".(!empty($this->location_incoterms) ? "'".$this->db->escape($this->location_incoterms)."'" : "null"); if ($customer) { - $sql .= ", code_client = ".(! empty($this->code_client)?"'".$this->db->escape($this->code_client)."'":"null"); - $sql .= ", code_compta = ".(! empty($this->code_compta)?"'".$this->db->escape($this->code_compta)."'":"null"); + $sql .= ", code_client = ".(!empty($this->code_client) ? "'".$this->db->escape($this->code_client)."'" : "null"); + $sql .= ", code_compta = ".(!empty($this->code_compta) ? "'".$this->db->escape($this->code_compta)."'" : "null"); } if ($supplier) { - $sql .= ", code_fournisseur = ".(! empty($this->code_fournisseur)?"'".$this->db->escape($this->code_fournisseur)."'":"null"); - $sql .= ", code_compta_fournisseur = ".(($this->code_compta_fournisseur != "")?"'".$this->db->escape($this->code_compta_fournisseur)."'":"null"); + $sql .= ", code_fournisseur = ".(!empty($this->code_fournisseur) ? "'".$this->db->escape($this->code_fournisseur)."'" : "null"); + $sql .= ", code_compta_fournisseur = ".(($this->code_compta_fournisseur != "") ? "'".$this->db->escape($this->code_compta_fournisseur)."'" : "null"); } - $sql .= ", fk_user_modif = ".($user->id > 0 ? $user->id:"null"); + $sql .= ", fk_user_modif = ".($user->id > 0 ? $user->id : "null"); $sql .= ", fk_multicurrency = ".(int) $this->fk_multicurrency; $sql .= ", multicurrency_code = '".$this->db->escape($this->multicurrency_code)."'"; - $sql .= " WHERE rowid = " . (int) $id; + $sql .= " WHERE rowid = ".(int) $id; - $resql=$this->db->query($sql); + $resql = $this->db->query($sql); if ($resql) { if (is_object($this->oldcopy)) // If we have information on old values @@ -1138,7 +1139,7 @@ class Societe extends CommonObject } else { - unset($this->country_code); // We clean this, in the doubt, because it may have been changed after an update of country_id + unset($this->country_code); // We clean this, in the doubt, because it may have been changed after an update of country_id unset($this->country); unset($this->state_code); unset($this->state); @@ -1146,33 +1147,33 @@ class Societe extends CommonObject $nbrowsaffected = $this->db->affected_rows($resql); - if (! $error && $nbrowsaffected) + if (!$error && $nbrowsaffected) { // Update information on linked member if it is an update - if (! $nosyncmember && ! empty($conf->adherent->enabled)) + if (!$nosyncmember && !empty($conf->adherent->enabled)) { require_once DOL_DOCUMENT_ROOT.'/adherents/class/adherent.class.php'; dol_syslog(get_class($this)."::update update linked member"); - $lmember=new Adherent($this->db); - $result=$lmember->fetch(0, 0, $this->id); + $lmember = new Adherent($this->db); + $result = $lmember->fetch(0, 0, $this->id); if ($result > 0) { - $lmember->company=$this->name; + $lmember->company = $this->name; //$lmember->firstname=$this->firstname?$this->firstname:$lmember->firstname; // We keep firstname and lastname of member unchanged //$lmember->lastname=$this->lastname?$this->lastname:$lmember->lastname; // We keep firstname and lastname of member unchanged - $lmember->address=$this->address; - $lmember->zip=$this->zip; - $lmember->town=$this->town; - $lmember->email=$this->email; - $lmember->socialnetworks=$this->socialnetworks; - $lmember->phone=$this->phone; - $lmember->state_id=$this->state_id; - $lmember->country_id=$this->country_id; + $lmember->address = $this->address; + $lmember->zip = $this->zip; + $lmember->town = $this->town; + $lmember->email = $this->email; + $lmember->socialnetworks = $this->socialnetworks; + $lmember->phone = $this->phone; + $lmember->state_id = $this->state_id; + $lmember->country_id = $this->country_id; - $result=$lmember->update($user, 0, 1, 1, 1); // Use nosync to 1 to avoid cyclic updates + $result = $lmember->update($user, 0, 1, 1, 1); // Use nosync to 1 to avoid cyclic updates if ($result < 0) { $this->error = $lmember->error; @@ -1183,33 +1184,33 @@ class Societe extends CommonObject } elseif ($result < 0) { - $this->error=$lmember->error; + $this->error = $lmember->error; $error++; } } } - $action='update'; + $action = 'update'; // Actions on extra fields - if (! $error && empty($conf->global->MAIN_EXTRAFIELDS_DISABLED)) // For avoid conflicts if trigger used + if (!$error && empty($conf->global->MAIN_EXTRAFIELDS_DISABLED)) // For avoid conflicts if trigger used { - $result=$this->insertExtraFields(); + $result = $this->insertExtraFields(); if ($result < 0) { $error++; } } - if (! $error && $call_trigger) + if (!$error && $call_trigger) { // Call trigger - $result=$this->call_trigger('COMPANY_MODIFY', $user); + $result = $this->call_trigger('COMPANY_MODIFY', $user); if ($result < 0) $error++; // End call triggers } - if (! $error) + if (!$error) { dol_syslog(get_class($this)."::Update success"); $this->db->commit(); @@ -1322,13 +1323,13 @@ class Societe extends CommonObject if ($idprof6) $sql .= " AND s.idprof6 = '".$this->db->escape($idprof6)."'"; if ($email) $sql .= " AND s.email = '".$this->db->escape($email)."'"; - $resql=$this->db->query($sql); + $resql = $this->db->query($sql); if ($resql) { - $num=$this->db->num_rows($resql); + $num = $this->db->num_rows($resql); if ($num > 1) { - $this->error='Fetch found several records. Rename one of thirdparties to avoid duplicate.'; + $this->error = 'Fetch found several records. Rename one of thirdparties to avoid duplicate.'; dol_syslog($this->error, LOG_ERR); $result = -2; } @@ -1338,11 +1339,11 @@ class Societe extends CommonObject $this->id = $obj->rowid; $this->entity = $obj->entity; - $this->canvas = $obj->canvas; + $this->canvas = $obj->canvas; $this->ref = $obj->rowid; - $this->name = $obj->name; - $this->nom = $obj->name; // deprecated + $this->name = $obj->name; + $this->nom = $obj->name; // deprecated $this->name_alias = $obj->name_alias; $this->ref_ext = $obj->ref_ext; $this->ref_int = $obj->ref_int; @@ -1352,22 +1353,22 @@ class Societe extends CommonObject $this->user_creation = $obj->fk_user_creat; $this->user_modification = $obj->fk_user_modif; - $this->address = $obj->address; + $this->address = $obj->address; $this->zip = $obj->zip; $this->town = $obj->town; $this->country_id = $obj->country_id; - $this->country_code = $obj->country_id?$obj->country_code:''; - $this->country = $obj->country_id?($langs->transnoentities('Country'.$obj->country_code)!='Country'.$obj->country_code?$langs->transnoentities('Country'.$obj->country_code):$obj->country):''; + $this->country_code = $obj->country_id ? $obj->country_code : ''; + $this->country = $obj->country_id ? ($langs->transnoentities('Country'.$obj->country_code) != 'Country'.$obj->country_code ? $langs->transnoentities('Country'.$obj->country_code) : $obj->country) : ''; $this->state_id = $obj->state_id; $this->state_code = $obj->state_code; - $this->state = ($obj->state!='-'?$obj->state:''); + $this->state = ($obj->state != '-' ? $obj->state : ''); - $transcode=$langs->trans('StatusProspect'.$obj->fk_stcomm); - $label = ($transcode!='StatusProspect'.$obj->fk_stcomm ? $transcode : $obj->stcomm); - $this->stcomm_id = $obj->fk_stcomm; // id status prospect - $this->status_prospect_label = $label; // label status prospect + $transcode = $langs->trans('StatusProspect'.$obj->fk_stcomm); + $label = ($transcode != 'StatusProspect'.$obj->fk_stcomm ? $transcode : $obj->stcomm); + $this->stcomm_id = $obj->fk_stcomm; // id status prospect + $this->status_prospect_label = $label; // label status prospect $this->email = $obj->email; $this->socialnetworks = (array) json_decode($obj->socialnetworks, true); @@ -1376,7 +1377,7 @@ class Societe extends CommonObject $this->phone = $obj->phone; $this->fax = $obj->fax; - $this->parent = $obj->parent; + $this->parent = $obj->parent; $this->idprof1 = $obj->idprof1; $this->idprof2 = $obj->idprof2; @@ -1385,7 +1386,7 @@ class Societe extends CommonObject $this->idprof5 = $obj->idprof5; $this->idprof6 = $obj->idprof6; - $this->capital = $obj->capital; + $this->capital = $obj->capital; $this->code_client = $obj->code_client; $this->code_fournisseur = $obj->code_fournisseur; @@ -1410,23 +1411,23 @@ class Societe extends CommonObject $this->typent_code = $obj->typent_code; $this->effectif_id = $obj->effectif_id; - $this->effectif = $obj->effectif_id?$obj->effectif:''; + $this->effectif = $obj->effectif_id ? $obj->effectif : ''; - $this->forme_juridique_code= $obj->forme_juridique_code; - $this->forme_juridique = $obj->forme_juridique_code?$obj->forme_juridique:''; + $this->forme_juridique_code = $obj->forme_juridique_code; + $this->forme_juridique = $obj->forme_juridique_code ? $obj->forme_juridique : ''; $this->fk_prospectlevel = $obj->fk_prospectlevel; $this->prefix_comm = $obj->prefix_comm; - $this->remise_percent = price2num($obj->remise_client); // 0.000000 must be 0 - $this->remise_supplier_percent = $obj->remise_supplier; + $this->remise_percent = price2num($obj->remise_client); // 0.000000 must be 0 + $this->remise_supplier_percent = $obj->remise_supplier; $this->mode_reglement_id = $obj->mode_reglement; $this->cond_reglement_id = $obj->cond_reglement; $this->mode_reglement_supplier_id = $obj->mode_reglement_supplier; $this->cond_reglement_supplier_id = $obj->cond_reglement_supplier; - $this->shipping_method_id = ($obj->fk_shipping_method>0)?$obj->fk_shipping_method:null; - $this->fk_account = $obj->fk_account; + $this->shipping_method_id = ($obj->fk_shipping_method > 0) ? $obj->fk_shipping_method : null; + $this->fk_account = $obj->fk_account; $this->client = $obj->client; $this->fournisseur = $obj->fournisseur; @@ -1444,7 +1445,7 @@ class Societe extends CommonObject $this->outstanding_limit = $obj->outstanding_limit; $this->order_min_amount = $obj->order_min_amount; - $this->supplier_order_min_amount = $obj->supplier_order_min_amount; + $this->supplier_order_min_amount = $obj->supplier_order_min_amount; // multiprix $this->price_level = $obj->price_level; @@ -1474,12 +1475,12 @@ class Societe extends CommonObject } else { - $this->error=$this->db->lasterror(); + $this->error = $this->db->lasterror(); $result = -3; } // Use first price level if level not defined for third party - if ((! empty($conf->global->PRODUIT_MULTIPRICES) || ! empty($conf->global->PRODUIT_CUSTOMER_PRICES_BY_QTY_MULTIPRICES)) && empty($this->price_level)) $this->price_level=1; + if ((!empty($conf->global->PRODUIT_MULTIPRICES) || !empty($conf->global->PRODUIT_CUSTOMER_PRICES_BY_QTY_MULTIPRICES)) && empty($this->price_level)) $this->price_level = 1; return $result; } @@ -1496,11 +1497,11 @@ class Societe extends CommonObject { global $langs, $conf, $user; - if (empty($fuser)) $fuser=$user; + if (empty($fuser)) $fuser = $user; require_once DOL_DOCUMENT_ROOT.'/core/lib/files.lib.php'; - $entity=isset($this->entity)?$this->entity:$conf->entity; + $entity = isset($this->entity) ? $this->entity : $conf->entity; dol_syslog(get_class($this)."::delete", LOG_DEBUG); $error = 0; @@ -1512,15 +1513,15 @@ class Societe extends CommonObject $this->db->begin(); // User is mandatory for trigger call - if (! $error && $call_trigger) + if (!$error && $call_trigger) { // Call trigger - $result=$this->call_trigger('COMPANY_DELETE', $fuser); + $result = $this->call_trigger('COMPANY_DELETE', $fuser); if ($result < 0) $error++; // End call triggers } - if (! $error) + if (!$error) { require_once DOL_DOCUMENT_ROOT.'/categories/class/categorie.class.php'; $static_cat = new Categorie($this->db); @@ -1548,11 +1549,11 @@ class Societe extends CommonObject foreach ($this->childtablesoncascade as $tabletodelete) { - if (! $error) + if (!$error) { $sql = "DELETE FROM ".MAIN_DB_PREFIX.$tabletodelete; - $sql.= " WHERE fk_soc = " . $id; - if (! $this->db->query($sql)) + $sql .= " WHERE fk_soc = ".$id; + if (!$this->db->query($sql)) { $error++; $this->errors[] = $this->db->lasterror(); @@ -1561,9 +1562,9 @@ class Societe extends CommonObject } // Removed extrafields - if ((! $error) && (empty($conf->global->MAIN_EXTRAFIELDS_DISABLED))) // For avoid conflicts if trigger used + if ((!$error) && (empty($conf->global->MAIN_EXTRAFIELDS_DISABLED))) // For avoid conflicts if trigger used { - $result=$this->deleteExtraFields(); + $result = $this->deleteExtraFields(); if ($result < 0) { $error++; @@ -1572,12 +1573,12 @@ class Societe extends CommonObject } // Remove links to subsidiaries companies - if (! $error) + if (!$error) { $sql = "UPDATE ".MAIN_DB_PREFIX."societe"; - $sql.= " SET parent = NULL"; - $sql.= " WHERE parent = " . $id; - if (! $this->db->query($sql)) + $sql .= " SET parent = NULL"; + $sql .= " WHERE parent = ".$id; + if (!$this->db->query($sql)) { $error++; $this->errors[] = $this->db->lasterror(); @@ -1585,25 +1586,25 @@ class Societe extends CommonObject } // Remove third party - if (! $error) + if (!$error) { $sql = "DELETE FROM ".MAIN_DB_PREFIX."societe"; - $sql.= " WHERE rowid = " . $id; - if (! $this->db->query($sql)) + $sql .= " WHERE rowid = ".$id; + if (!$this->db->query($sql)) { $error++; $this->errors[] = $this->db->lasterror(); } } - if (! $error) + if (!$error) { $this->db->commit(); // Delete directory - if (! empty($conf->societe->multidir_output[$entity])) + if (!empty($conf->societe->multidir_output[$entity])) { - $docdir = $conf->societe->multidir_output[$entity] . "/" . $id; + $docdir = $conf->societe->multidir_output[$entity]."/".$id; if (dol_is_dir($docdir)) { dol_delete_dir_recursive($docdir); @@ -1634,13 +1635,13 @@ class Societe extends CommonObject // phpcs:enable if ($this->id) { - $newclient=1; - if ($this->client == 2 || $this->client == 3) $newclient=3; //If prospect, we keep prospect tag + $newclient = 1; + if ($this->client == 2 || $this->client == 3) $newclient = 3; //If prospect, we keep prospect tag $sql = "UPDATE ".MAIN_DB_PREFIX."societe"; - $sql.= " SET client = ".$newclient; - $sql.= " WHERE rowid = " . $this->id; + $sql .= " SET client = ".$newclient; + $sql .= " WHERE rowid = ".$this->id; - $resql=$this->db->query($sql); + $resql = $this->db->query($sql); if ($resql) { $this->client = $newclient; @@ -1666,10 +1667,10 @@ class Societe extends CommonObject global $conf, $langs; // Parameter cleaning - $note=trim($note); - if (! $note) + $note = trim($note); + if (!$note) { - $this->error=$langs->trans("ErrorFieldRequired", $langs->transnoentitiesnoconv("NoteReason")); + $this->error = $langs->trans("ErrorFieldRequired", $langs->transnoentitiesnoconv("NoteReason")); return -2; } @@ -1679,33 +1680,33 @@ class Societe extends CommonObject { $this->db->begin(); - $now=dol_now(); + $now = dol_now(); // Position current discount $sql = "UPDATE ".MAIN_DB_PREFIX."societe "; - $sql.= " SET remise_client = '".$this->db->escape($remise)."'"; - $sql.= " WHERE rowid = " . $this->id; - $resql=$this->db->query($sql); - if (! $resql) + $sql .= " SET remise_client = '".$this->db->escape($remise)."'"; + $sql .= " WHERE rowid = ".$this->id; + $resql = $this->db->query($sql); + if (!$resql) { $this->db->rollback(); - $this->error=$this->db->error(); + $this->error = $this->db->error(); return -1; } // Writes trace in discount history $sql = "INSERT INTO ".MAIN_DB_PREFIX."societe_remise"; - $sql.= " (entity, datec, fk_soc, remise_client, note, fk_user_author)"; - $sql.= " VALUES (".$conf->entity.", '".$this->db->idate($now)."', ".$this->id.", '".$this->db->escape($remise)."',"; - $sql.= " '".$this->db->escape($note)."',"; - $sql.= " ".$user->id; - $sql.= ")"; + $sql .= " (entity, datec, fk_soc, remise_client, note, fk_user_author)"; + $sql .= " VALUES (".$conf->entity.", '".$this->db->idate($now)."', ".$this->id.", '".$this->db->escape($remise)."',"; + $sql .= " '".$this->db->escape($note)."',"; + $sql .= " ".$user->id; + $sql .= ")"; - $resql=$this->db->query($sql); - if (! $resql) + $resql = $this->db->query($sql); + if (!$resql) { $this->db->rollback(); - $this->error=$this->db->lasterror(); + $this->error = $this->db->lasterror(); return -1; } @@ -1729,10 +1730,10 @@ class Societe extends CommonObject global $conf, $langs; // Parameter cleaning - $note=trim($note); - if (! $note) + $note = trim($note); + if (!$note) { - $this->error=$langs->trans("ErrorFieldRequired", $langs->transnoentitiesnoconv("NoteReason")); + $this->error = $langs->trans("ErrorFieldRequired", $langs->transnoentitiesnoconv("NoteReason")); return -2; } @@ -1742,33 +1743,33 @@ class Societe extends CommonObject { $this->db->begin(); - $now=dol_now(); + $now = dol_now(); // Position current discount $sql = "UPDATE ".MAIN_DB_PREFIX."societe "; - $sql.= " SET remise_supplier = '".$this->db->escape($remise)."'"; - $sql.= " WHERE rowid = " . $this->id; - $resql=$this->db->query($sql); - if (! $resql) + $sql .= " SET remise_supplier = '".$this->db->escape($remise)."'"; + $sql .= " WHERE rowid = ".$this->id; + $resql = $this->db->query($sql); + if (!$resql) { $this->db->rollback(); - $this->error=$this->db->error(); + $this->error = $this->db->error(); return -1; } // Writes trace in discount history $sql = "INSERT INTO ".MAIN_DB_PREFIX."societe_remise_supplier"; - $sql.= " (entity, datec, fk_soc, remise_supplier, note, fk_user_author)"; - $sql.= " VALUES (".$conf->entity.", '".$this->db->idate($now)."', ".$this->id.", '".$this->db->escape($remise)."',"; - $sql.= " '".$this->db->escape($note)."',"; - $sql.= " ".$user->id; - $sql.= ")"; + $sql .= " (entity, datec, fk_soc, remise_supplier, note, fk_user_author)"; + $sql .= " VALUES (".$conf->entity.", '".$this->db->idate($now)."', ".$this->id.", '".$this->db->escape($remise)."',"; + $sql .= " '".$this->db->escape($note)."',"; + $sql .= " ".$user->id; + $sql .= ")"; - $resql=$this->db->query($sql); - if (! $resql) + $resql = $this->db->query($sql); + if (!$resql) { $this->db->rollback(); - $this->error=$this->db->lasterror(); + $this->error = $this->db->lasterror(); return -1; } @@ -1798,14 +1799,14 @@ class Societe extends CommonObject $desc = trim($desc); // Check parameters - if (! $remise > 0) + if (!$remise > 0) { - $this->error=$langs->trans("ErrorWrongValueForParameter", "1"); + $this->error = $langs->trans("ErrorWrongValueForParameter", "1"); return -1; } - if (! $desc) + if (!$desc) { - $this->error=$langs->trans("ErrorWrongValueForParameter", "3"); + $this->error = $langs->trans("ErrorWrongValueForParameter", "3"); return -2; } @@ -1814,25 +1815,25 @@ class Societe extends CommonObject require_once DOL_DOCUMENT_ROOT.'/core/class/discount.class.php'; $discount = new DiscountAbsolute($this->db); - $discount->fk_soc=$this->id; + $discount->fk_soc = $this->id; - $discount->discount_type=$discount_type; + $discount->discount_type = $discount_type; - $discount->amount_ht=$discount->multicurrency_amount_ht=price2num($remise, 'MT'); - $discount->amount_tva=$discount->multicurrency_amount_tva=price2num($remise*$tva_tx/100, 'MT'); - $discount->amount_ttc=$discount->multicurrency_amount_ttc=price2num($discount->amount_ht+$discount->amount_tva, 'MT'); + $discount->amount_ht = $discount->multicurrency_amount_ht = price2num($remise, 'MT'); + $discount->amount_tva = $discount->multicurrency_amount_tva = price2num($remise * $tva_tx / 100, 'MT'); + $discount->amount_ttc = $discount->multicurrency_amount_ttc = price2num($discount->amount_ht + $discount->amount_tva, 'MT'); - $discount->tva_tx=price2num($tva_tx, 'MT'); - $discount->description=$desc; + $discount->tva_tx = price2num($tva_tx, 'MT'); + $discount->description = $desc; - $result=$discount->create($user); + $result = $discount->create($user); if ($result > 0) { return $result; } else { - $this->error=$discount->error; + $this->error = $discount->error; return -3; } } @@ -1852,15 +1853,15 @@ class Societe extends CommonObject { require_once DOL_DOCUMENT_ROOT.'/core/class/discount.class.php'; - $discountstatic=new DiscountAbsolute($this->db); - $result=$discountstatic->getAvailableDiscounts($this, $user, $filter, $maxvalue, $discount_type); + $discountstatic = new DiscountAbsolute($this->db); + $result = $discountstatic->getAvailableDiscounts($this, $user, $filter, $maxvalue, $discount_type); if ($result >= 0) { return $result; } else { - $this->error=$discountstatic->error; + $this->error = $discountstatic->error; return -1; } } @@ -1876,47 +1877,47 @@ class Societe extends CommonObject { global $conf; - $reparray=array(); + $reparray = array(); $sql = "SELECT DISTINCT u.rowid, u.login, u.lastname, u.firstname, u.office_phone, u.job, u.email, u.statut, u.entity, u.photo"; - $sql.= " FROM ".MAIN_DB_PREFIX."societe_commerciaux as sc, ".MAIN_DB_PREFIX."user as u"; - if (! empty($conf->multicompany->enabled) && ! empty($conf->global->MULTICOMPANY_TRANSVERSE_MODE)) + $sql .= " FROM ".MAIN_DB_PREFIX."societe_commerciaux as sc, ".MAIN_DB_PREFIX."user as u"; + if (!empty($conf->multicompany->enabled) && !empty($conf->global->MULTICOMPANY_TRANSVERSE_MODE)) { - $sql.= ", ".MAIN_DB_PREFIX."usergroup_user as ug"; - $sql.= " WHERE ((ug.fk_user = sc.fk_user"; - $sql.= " AND ug.entity = ".$conf->entity.")"; - $sql.= " OR u.admin = 1)"; + $sql .= ", ".MAIN_DB_PREFIX."usergroup_user as ug"; + $sql .= " WHERE ((ug.fk_user = sc.fk_user"; + $sql .= " AND ug.entity = ".$conf->entity.")"; + $sql .= " OR u.admin = 1)"; } else - $sql.= " WHERE entity in (0, ".$conf->entity.")"; + $sql .= " WHERE entity in (0, ".$conf->entity.")"; - $sql.= " AND u.rowid = sc.fk_user AND sc.fk_soc = ".$this->id; + $sql .= " AND u.rowid = sc.fk_user AND sc.fk_soc = ".$this->id; $resql = $this->db->query($sql); if ($resql) { $num = $this->db->num_rows($resql); - $i=0; + $i = 0; while ($i < $num) { $obj = $this->db->fetch_object($resql); if (empty($mode)) { - $reparray[$i]['id']=$obj->rowid; - $reparray[$i]['lastname']=$obj->lastname; - $reparray[$i]['firstname']=$obj->firstname; - $reparray[$i]['email']=$obj->email; - $reparray[$i]['phone']=$obj->office_phone; - $reparray[$i]['job']=$obj->job; - $reparray[$i]['statut']=$obj->statut; - $reparray[$i]['entity']=$obj->entity; - $reparray[$i]['login']=$obj->login; - $reparray[$i]['photo']=$obj->photo; + $reparray[$i]['id'] = $obj->rowid; + $reparray[$i]['lastname'] = $obj->lastname; + $reparray[$i]['firstname'] = $obj->firstname; + $reparray[$i]['email'] = $obj->email; + $reparray[$i]['phone'] = $obj->office_phone; + $reparray[$i]['job'] = $obj->job; + $reparray[$i]['statut'] = $obj->statut; + $reparray[$i]['entity'] = $obj->entity; + $reparray[$i]['login'] = $obj->login; + $reparray[$i]['photo'] = $obj->photo; } else { - $reparray[]=$obj->rowid; + $reparray[] = $obj->rowid; } $i++; } @@ -1941,13 +1942,13 @@ class Societe extends CommonObject // phpcs:enable if ($this->id) { - $now=dol_now(); + $now = dol_now(); $sql = "UPDATE ".MAIN_DB_PREFIX."societe"; $sql .= " SET price_level = '".$this->db->escape($price_level)."'"; - $sql .= " WHERE rowid = " . $this->id; + $sql .= " WHERE rowid = ".$this->id; - if (! $this->db->query($sql)) + if (!$this->db->query($sql)) { dol_print_error($this->db); return -1; @@ -1957,7 +1958,7 @@ class Societe extends CommonObject $sql .= " (datec, fk_soc, price_level, fk_user_author)"; $sql .= " VALUES ('".$this->db->idate($now)."', ".$this->id.", '".$this->db->escape($price_level)."', ".$user->id.")"; - if (! $this->db->query($sql)) + if (!$this->db->query($sql)) { dol_print_error($this->db); return -1; @@ -1978,51 +1979,51 @@ class Societe extends CommonObject public function add_commercial(User $user, $commid) { // phpcs:enable - $error=0; + $error = 0; if ($this->id > 0 && $commid > 0) { $this->db->begin(); - if (! $error) + if (!$error) { $sql = "DELETE FROM ".MAIN_DB_PREFIX."societe_commerciaux"; - $sql.= " WHERE fk_soc = ".$this->id." AND fk_user =".$commid; + $sql .= " WHERE fk_soc = ".$this->id." AND fk_user =".$commid; $resql = $this->db->query($sql); - if (! $resql) + if (!$resql) { dol_syslog(get_class($this)."::add_commercial Error ".$this->db->lasterror()); $error++; } } - if (! $error) + if (!$error) { $sql = "INSERT INTO ".MAIN_DB_PREFIX."societe_commerciaux"; - $sql.= " (fk_soc, fk_user)"; - $sql.= " VALUES (".$this->id.", ".$commid.")"; + $sql .= " (fk_soc, fk_user)"; + $sql .= " VALUES (".$this->id.", ".$commid.")"; $resql = $this->db->query($sql); - if (! $resql) + if (!$resql) { dol_syslog(get_class($this)."::add_commercial Error ".$this->db->lasterror()); $error++; } } - if (! $error) + if (!$error) { - $this->context=array('commercial_modified'=>$commid); + $this->context = array('commercial_modified'=>$commid); - $result=$this->call_trigger('COMPANY_LINK_SALE_REPRESENTATIVE', $user); + $result = $this->call_trigger('COMPANY_LINK_SALE_REPRESENTATIVE', $user); if ($result < 0) { $error++; } } - if (! $error) + if (!$error) { $this->db->commit(); return 1; @@ -2048,10 +2049,10 @@ class Societe extends CommonObject public function del_commercial(User $user, $commid) { // phpcs:enable - $error=0; - $this->context=array('commercial_modified'=>$commid); + $error = 0; + $this->context = array('commercial_modified'=>$commid); - $result=$this->call_trigger('COMPANY_UNLINK_SALE_REPRESENTATIVE', $user); + $result = $this->call_trigger('COMPANY_UNLINK_SALE_REPRESENTATIVE', $user); if ($result < 0) $error++; if ($this->id > 0 && $commid > 0) @@ -2059,7 +2060,7 @@ class Societe extends CommonObject $sql = "DELETE FROM ".MAIN_DB_PREFIX."societe_commerciaux "; $sql .= " WHERE fk_soc = ".$this->id." AND fk_user =".$commid; - if (! $this->db->query($sql) ) + if (!$this->db->query($sql)) { dol_syslog(get_class($this)."::del_commercial Erreur"); } @@ -2081,160 +2082,160 @@ class Societe extends CommonObject { global $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 - $name=$this->name?$this->name:$this->nom; + $name = $this->name ? $this->name : $this->nom; - if (!empty($conf->global->SOCIETE_ON_SEARCH_AND_LIST_GO_ON_CUSTOMER_OR_SUPPLIER_CARD)){ + if (!empty($conf->global->SOCIETE_ON_SEARCH_AND_LIST_GO_ON_CUSTOMER_OR_SUPPLIER_CARD)) { if (empty($option) && $this->client > 0) $option = 'customer'; if (empty($option) && $this->fournisseur > 0) $option = 'supplier'; } - if (! empty($conf->global->SOCIETE_ADD_REF_IN_LIST) && (!empty($withpicto))) + if (!empty($conf->global->SOCIETE_ADD_REF_IN_LIST) && (!empty($withpicto))) { $code = ''; - if (($this->client) && (! empty($this->code_client)) + if (($this->client) && (!empty($this->code_client)) && ($conf->global->SOCIETE_ADD_REF_IN_LIST == 1 || $conf->global->SOCIETE_ADD_REF_IN_LIST == 2 ) ) { - $code = $this->code_client . ' - '; + $code = $this->code_client.' - '; } - if (($this->fournisseur) && (! empty($this->code_fournisseur)) - && ($conf->global->SOCIETE_ADD_REF_IN_LIST == 1 || $conf->global->SOCIETE_ADD_REF_IN_LIST == 3 + if (($this->fournisseur) && (!empty($this->code_fournisseur)) + && ($conf->global->SOCIETE_ADD_REF_IN_LIST == 1 || $conf->global->SOCIETE_ADD_REF_IN_LIST == 3 ) ) { - $code .= $this->code_fournisseur . ' - '; + $code .= $this->code_fournisseur.' - '; } if ($conf->global->SOCIETE_ADD_REF_IN_LIST == 1) { - $name =$code.' '.$name; + $name = $code.' '.$name; } else { - $name =$code; + $name = $code; } } if (!empty($this->name_alias)) $name .= ' ('.$this->name_alias.')'; - $result=''; $label=''; - $linkstart=''; $linkend=''; + $result = ''; $label = ''; + $linkstart = ''; $linkend = ''; - if (! empty($this->logo) && class_exists('Form')) + if (!empty($this->logo) && class_exists('Form')) { - $label.= '
    '; - $label.= Form::showphoto('societe', $this, 0, 40, 0, 'photowithmargin', '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.= '
    '; + $label .= '
    '; + $label .= Form::showphoto('societe', $this, 0, 40, 0, 'photowithmargin', '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 .= '
    '; } - elseif (! empty($this->logo_squarred) && class_exists('Form')) + elseif (!empty($this->logo_squarred) && class_exists('Form')) { /*$label.= '
    '; $label.= Form::showphoto('societe', $this, 0, 40, 0, 'photowithmargin', '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.= '
    ';*/ } - $label.= '
    '; + $label .= '
    '; if ($option == 'customer' || $option == 'compta' || $option == 'category' || $option == 'category_supplier') { - $label.= '' . $langs->trans("ShowCustomer") . ''; + $label .= ''.$langs->trans("ShowCustomer").''; $linkstart = ''; + $label .= ''.$langs->trans("ShowProspect").''; $linkstart = ''; + $label .= ''.$langs->trans("ShowSupplier").''; $linkstart = ''; + $label .= ''.$langs->trans("ShowAgenda").''; $linkstart = ''; + $label .= ''.$langs->trans("ShowProject").''; $linkstart = ''; + $label .= ''.$langs->trans("ShowMargin").''; $linkstart = ''; + $label .= ''.$langs->trans("ShowContacts").''; $linkstart = ''; + $label .= ''.$langs->trans("ShowBan").''; $linkstart = ''; + $label .= ''.$langs->trans("ShowCompany").''; $linkstart = 'global->MAIN_OPTIMIZEFORTEXTBROWSER)) + if (!empty($conf->global->MAIN_OPTIMIZEFORTEXTBROWSER)) { - $label=$langs->trans("ShowCompany"); - $linkclose.=' alt="'.dol_escape_htmltag($label, 1).'"'; + $label = $langs->trans("ShowCompany"); + $linkclose .= ' alt="'.dol_escape_htmltag($label, 1).'"'; } - $linkclose.= ' title="'.dol_escape_htmltag($label, 1).'"'; - $linkclose.=' class="classfortooltip refurl"'; + $linkclose .= ' title="'.dol_escape_htmltag($label, 1).'"'; + $linkclose .= ' class="classfortooltip refurl"'; /* $hookmanager->initHooks(array('thirdpartydao')); @@ -2243,25 +2244,25 @@ class Societe extends CommonObject if ($reshook > 0) $linkclose = $hookmanager->resPrint; */ } - $linkstart.=$linkclose.'>'; - $linkend=''; + $linkstart .= $linkclose.'>'; + $linkend = ''; global $user; - if (! $user->rights->societe->client->voir && $user->socid > 0 && $this->id != $user->socid) + if (!$user->rights->societe->client->voir && $user->socid > 0 && $this->id != $user->socid) { - $linkstart=''; - $linkend=''; + $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 valignmiddle"'), 0, 0, $notooltip?0:1); - if ($withpicto != 2) $result.=($maxlen?dol_trunc($name, $maxlen):$name); - $result.=$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 valignmiddle"'), 0, 0, $notooltip ? 0 : 1); + if ($withpicto != 2) $result .= ($maxlen ?dol_trunc($name, $maxlen) : $name); + $result .= $linkend; global $action; $hookmanager->initHooks(array('thirdpartydao')); - $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 + $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; @@ -2322,8 +2323,8 @@ class Societe extends CommonObject $contact_emails = $this->contact_property_array('email', 1); if ($this->email && $addthirdparty) { - if (empty($this->name)) $this->name=$this->nom; - $contact_emails['thirdparty']=$langs->transnoentitiesnoconv("ThirdParty").': '.dol_trunc($this->name, 16)." <".$this->email.">"; + if (empty($this->name)) $this->name = $this->nom; + $contact_emails['thirdparty'] = $langs->transnoentitiesnoconv("ThirdParty").': '.dol_trunc($this->name, 16)." <".$this->email.">"; } //var_dump($contact_emails) return $contact_emails; @@ -2342,11 +2343,11 @@ class Societe extends CommonObject $contact_phone = $this->contact_property_array('mobile'); - if (! empty($this->phone)) // If a phone of thirdparty is defined, we add it ot mobile of contacts + if (!empty($this->phone)) // If a phone of thirdparty is defined, we add it ot mobile of contacts { - if (empty($this->name)) $this->name=$this->nom; + if (empty($this->name)) $this->name = $this->nom; // TODO: Tester si tel non deja present dans tableau contact - $contact_phone['thirdparty']=$langs->transnoentitiesnoconv("ThirdParty").': '.dol_trunc($this->name, 16)." <".$this->phone.">"; + $contact_phone['thirdparty'] = $langs->transnoentitiesnoconv("ThirdParty").': '.dol_trunc($this->name, 16)." <".$this->phone.">"; } return $contact_phone; } @@ -2368,46 +2369,46 @@ class Societe extends CommonObject $sql = "SELECT rowid, email, statut, phone_mobile, lastname, poste, firstname"; - $sql.= " FROM ".MAIN_DB_PREFIX."socpeople"; - $sql.= " WHERE fk_soc = ".$this->id; - $sql.= " ORDER BY lastname, firstname"; + $sql .= " FROM ".MAIN_DB_PREFIX."socpeople"; + $sql .= " WHERE fk_soc = ".$this->id; + $sql .= " ORDER BY lastname, firstname"; - $resql=$this->db->query($sql); + $resql = $this->db->query($sql); if ($resql) { $nump = $this->db->num_rows($resql); if ($nump) { - $sepa="("; $sepb=")"; + $sepa = "("; $sepb = ")"; if ($mode == 'email') { //$sepa="<"; $sepb=">"; - $sepa="<"; $sepb=">"; + $sepa = "<"; $sepb = ">"; } $i = 0; while ($i < $nump) { $obj = $this->db->fetch_object($resql); - if ($mode == 'email') $property=$obj->email; - elseif ($mode == 'mobile') $property=$obj->phone_mobile; - else $property=$obj->$mode; + if ($mode == 'email') $property = $obj->email; + elseif ($mode == 'mobile') $property = $obj->phone_mobile; + else $property = $obj->$mode; // Show all contact. If hidedisabled is 1, showonly contacts with status = 1 if ($obj->statut == 1 || empty($hidedisabled)) { if (empty($property)) { - if ($mode == 'email') $property=$langs->transnoentitiesnoconv("NoEMail"); - elseif ($mode == 'mobile') $property=$langs->transnoentitiesnoconv("NoMobilePhone"); + if ($mode == 'email') $property = $langs->transnoentitiesnoconv("NoEMail"); + elseif ($mode == 'mobile') $property = $langs->transnoentitiesnoconv("NoMobilePhone"); } if (!empty($obj->poste)) { - $contact_property[$obj->rowid] = trim(dolGetFirstLastname($obj->firstname, $obj->lastname)).($obj->poste?" - ".$obj->poste:"").(($mode != 'poste' && $property)?" ".$sepa.$property.$sepb:''); + $contact_property[$obj->rowid] = trim(dolGetFirstLastname($obj->firstname, $obj->lastname)).($obj->poste ? " - ".$obj->poste : "").(($mode != 'poste' && $property) ? " ".$sepa.$property.$sepb : ''); } else { - $contact_property[$obj->rowid] = trim(dolGetFirstLastname($obj->firstname, $obj->lastname)).(($mode != 'poste' && $property)?" ".$sepa.$property.$sepb:''); + $contact_property[$obj->rowid] = trim(dolGetFirstLastname($obj->firstname, $obj->lastname)).(($mode != 'poste' && $property) ? " ".$sepa.$property.$sepb : ''); } } $i++; @@ -2434,7 +2435,7 @@ class Societe extends CommonObject $contacts = array(); $sql = "SELECT rowid, lastname, firstname FROM ".MAIN_DB_PREFIX."socpeople WHERE fk_soc = ".$this->id; - $resql=$this->db->query($sql); + $resql = $this->db->query($sql); if ($resql) { $nump = $this->db->num_rows($resql); @@ -2465,11 +2466,11 @@ class Societe extends CommonObject public function contact_array_objects() { // phpcs:enable - require_once DOL_DOCUMENT_ROOT . '/contact/class/contact.class.php'; + require_once DOL_DOCUMENT_ROOT.'/contact/class/contact.class.php'; $contacts = array(); $sql = "SELECT rowid FROM ".MAIN_DB_PREFIX."socpeople WHERE fk_soc = ".$this->id; - $resql=$this->db->query($sql); + $resql = $this->db->query($sql); if ($resql) { $nump = $this->db->num_rows($resql); @@ -2504,15 +2505,15 @@ class Societe extends CommonObject public function contact_get_property($rowid, $mode) { // phpcs:enable - $contact_property=''; + $contact_property = ''; if (empty($rowid)) return ''; $sql = "SELECT rowid, email, phone_mobile, lastname, firstname"; - $sql.= " FROM ".MAIN_DB_PREFIX."socpeople"; - $sql.= " WHERE rowid = '".$rowid."'"; + $sql .= " FROM ".MAIN_DB_PREFIX."socpeople"; + $sql .= " WHERE rowid = '".$rowid."'"; - $resql=$this->db->query($sql); + $resql = $this->db->query($sql); if ($resql) { $nump = $this->db->num_rows($resql); @@ -2543,7 +2544,7 @@ class Societe extends CommonObject public function display_rib($mode = 'label') { // phpcs:enable - require_once DOL_DOCUMENT_ROOT . '/societe/class/companybankaccount.class.php'; + require_once DOL_DOCUMENT_ROOT.'/societe/class/companybankaccount.class.php'; $bac = new CompanyBankAccount($this->db); $bac->fetch(0, $this->id); @@ -2556,7 +2557,7 @@ class Societe extends CommonObject { if (empty($bac->rum)) { - require_once DOL_DOCUMENT_ROOT . '/compta/prelevement/class/bonprelevement.class.php'; + require_once DOL_DOCUMENT_ROOT.'/compta/prelevement/class/bonprelevement.class.php'; $prelevement = new BonPrelevement($this->db); $bac->fetch_thirdparty(); $bac->rum = $prelevement->buildRumNumber($bac->thirdparty->code_client, $bac->datec, $bac->id); @@ -2580,7 +2581,7 @@ class Societe extends CommonObject public function get_all_rib() { // phpcs:enable - require_once DOL_DOCUMENT_ROOT . '/societe/class/companybankaccount.class.php'; + require_once DOL_DOCUMENT_ROOT.'/societe/class/companybankaccount.class.php'; $sql = "SELECT rowid FROM ".MAIN_DB_PREFIX."societe_rib WHERE type='ban' AND fk_soc = ".$this->id; $result = $this->db->query($sql); if (!$result) { @@ -2614,14 +2615,14 @@ class Societe extends CommonObject { // phpcs:enable global $conf; - if (! empty($conf->global->SOCIETE_CODECLIENT_ADDON)) + if (!empty($conf->global->SOCIETE_CODECLIENT_ADDON)) { - $module=$conf->global->SOCIETE_CODECLIENT_ADDON; + $module = $conf->global->SOCIETE_CODECLIENT_ADDON; - $dirsociete=array_merge(array('/core/modules/societe/'), $conf->modules_parts['societe']); + $dirsociete = array_merge(array('/core/modules/societe/'), $conf->modules_parts['societe']); foreach ($dirsociete as $dirroot) { - $res=dol_include_once($dirroot.$module.'.php'); + $res = dol_include_once($dirroot.$module.'.php'); if ($res) break; } $mod = new $module(); @@ -2646,14 +2647,14 @@ class Societe extends CommonObject { // phpcs:enable global $conf; - if (! empty($conf->global->SOCIETE_CODECLIENT_ADDON)) + if (!empty($conf->global->SOCIETE_CODECLIENT_ADDON)) { - $module=$conf->global->SOCIETE_CODECLIENT_ADDON; + $module = $conf->global->SOCIETE_CODECLIENT_ADDON; - $dirsociete=array_merge(array('/core/modules/societe/'), $conf->modules_parts['societe']); + $dirsociete = array_merge(array('/core/modules/societe/'), $conf->modules_parts['societe']); foreach ($dirsociete as $dirroot) { - $res=dol_include_once($dirroot.$module.'.php'); + $res = dol_include_once($dirroot.$module.'.php'); if ($res) break; } $mod = new $module(); @@ -2675,23 +2676,23 @@ class Societe extends CommonObject { // phpcs:enable global $conf; - if (! empty($conf->global->SOCIETE_CODECLIENT_ADDON)) + if (!empty($conf->global->SOCIETE_CODECLIENT_ADDON)) { - $module=$conf->global->SOCIETE_CODECLIENT_ADDON; + $module = $conf->global->SOCIETE_CODECLIENT_ADDON; - $dirsociete=array_merge(array('/core/modules/societe/'), $conf->modules_parts['societe']); + $dirsociete = array_merge(array('/core/modules/societe/'), $conf->modules_parts['societe']); foreach ($dirsociete as $dirroot) { - $res=dol_include_once($dirroot.$module.'.php'); + $res = dol_include_once($dirroot.$module.'.php'); if ($res) break; } $mod = new $module(); dol_syslog(get_class($this)."::codeclient_modifiable code_client=".$this->code_client." module=".$module); - if ($mod->code_modifiable_null && ! $this->code_client) return 1; + if ($mod->code_modifiable_null && !$this->code_client) return 1; if ($mod->code_modifiable_invalide && $this->check_codeclient() < 0) return 1; - if ($mod->code_modifiable) return 1; // A mettre en dernier + if ($mod->code_modifiable) return 1; // A mettre en dernier return 0; } else @@ -2711,23 +2712,23 @@ class Societe extends CommonObject { // phpcs:enable global $conf; - if (! empty($conf->global->SOCIETE_CODECLIENT_ADDON)) + if (!empty($conf->global->SOCIETE_CODECLIENT_ADDON)) { - $module=$conf->global->SOCIETE_CODECLIENT_ADDON; + $module = $conf->global->SOCIETE_CODECLIENT_ADDON; - $dirsociete=array_merge(array('/core/modules/societe/'), $conf->modules_parts['societe']); + $dirsociete = array_merge(array('/core/modules/societe/'), $conf->modules_parts['societe']); foreach ($dirsociete as $dirroot) { - $res=dol_include_once($dirroot.$module.'.php'); + $res = dol_include_once($dirroot.$module.'.php'); if ($res) break; } $mod = new $module(); dol_syslog(get_class($this)."::codefournisseur_modifiable code_founisseur=".$this->code_fournisseur." module=".$module); - if ($mod->code_modifiable_null && ! $this->code_fournisseur) return 1; + if ($mod->code_modifiable_null && !$this->code_fournisseur) return 1; if ($mod->code_modifiable_invalide && $this->check_codefournisseur() < 0) return 1; - if ($mod->code_modifiable) return 1; // A mettre en dernier + if ($mod->code_modifiable) return 1; // A mettre en dernier return 0; } else @@ -2751,14 +2752,14 @@ class Societe extends CommonObject { // phpcs:enable global $conf; - if (! empty($conf->global->SOCIETE_CODECLIENT_ADDON)) + if (!empty($conf->global->SOCIETE_CODECLIENT_ADDON)) { - $module=$conf->global->SOCIETE_CODECLIENT_ADDON; + $module = $conf->global->SOCIETE_CODECLIENT_ADDON; - $dirsociete=array_merge(array('/core/modules/societe/'), $conf->modules_parts['societe']); + $dirsociete = array_merge(array('/core/modules/societe/'), $conf->modules_parts['societe']); foreach ($dirsociete as $dirroot) { - $res=dol_include_once($dirroot.$module.'.php'); + $res = dol_include_once($dirroot.$module.'.php'); if ($res) break; } @@ -2788,14 +2789,14 @@ class Societe extends CommonObject { // phpcs:enable global $conf; - if (! empty($conf->global->SOCIETE_CODECLIENT_ADDON)) + if (!empty($conf->global->SOCIETE_CODECLIENT_ADDON)) { - $module=$conf->global->SOCIETE_CODECLIENT_ADDON; + $module = $conf->global->SOCIETE_CODECLIENT_ADDON; - $dirsociete=array_merge(array('/core/modules/societe/'), $conf->modules_parts['societe']); + $dirsociete = array_merge(array('/core/modules/societe/'), $conf->modules_parts['societe']); foreach ($dirsociete as $dirroot) { - $res=dol_include_once($dirroot.$module.'.php'); + $res = dol_include_once($dirroot.$module.'.php'); if ($res) break; } @@ -2825,13 +2826,13 @@ class Societe extends CommonObject // phpcs:enable global $conf; - if (! empty($conf->global->SOCIETE_CODECOMPTA_ADDON)) + if (!empty($conf->global->SOCIETE_CODECOMPTA_ADDON)) { - $res=false; - $dirsociete=array_merge(array('/core/modules/societe/'), $conf->modules_parts['societe']); + $res = false; + $dirsociete = array_merge(array('/core/modules/societe/'), $conf->modules_parts['societe']); foreach ($dirsociete as $dirroot) { - $res=dol_include_once($dirroot.$conf->global->SOCIETE_CODECOMPTA_ADDON.'.php'); + $res = dol_include_once($dirroot.$conf->global->SOCIETE_CODECOMPTA_ADDON.'.php'); if ($res) break; } @@ -2876,10 +2877,10 @@ class Societe extends CommonObject if ($this->id) { $sql = "UPDATE ".MAIN_DB_PREFIX."societe"; - $sql.= " SET parent = ".($id > 0 ? $id : "null"); - $sql.= " WHERE rowid = " . $this->id; + $sql .= " SET parent = ".($id > 0 ? $id : "null"); + $sql .= " WHERE rowid = ".$this->id; dol_syslog(get_class($this).'::set_parent', LOG_DEBUG); - $resql=$this->db->query($sql); + $resql = $this->db->query($sql); if ($resql) { $this->parent = $id; @@ -2905,28 +2906,28 @@ class Societe extends CommonObject // phpcs:enable global $conf; - switch($idprof) + switch ($idprof) { case 1: - $ret=(!$conf->global->SOCIETE_IDPROF1_UNIQUE?false:true); + $ret = (!$conf->global->SOCIETE_IDPROF1_UNIQUE ?false:true); break; case 2: - $ret=(!$conf->global->SOCIETE_IDPROF2_UNIQUE?false:true); + $ret = (!$conf->global->SOCIETE_IDPROF2_UNIQUE ?false:true); break; case 3: - $ret=(!$conf->global->SOCIETE_IDPROF3_UNIQUE?false:true); + $ret = (!$conf->global->SOCIETE_IDPROF3_UNIQUE ?false:true); break; case 4: - $ret=(!$conf->global->SOCIETE_IDPROF4_UNIQUE?false:true); + $ret = (!$conf->global->SOCIETE_IDPROF4_UNIQUE ?false:true); break; case 5: - $ret=(!$conf->global->SOCIETE_IDPROF5_UNIQUE?false:true); + $ret = (!$conf->global->SOCIETE_IDPROF5_UNIQUE ?false:true); break; case 6: - $ret=(!$conf->global->SOCIETE_IDPROF6_UNIQUE?false:true); + $ret = (!$conf->global->SOCIETE_IDPROF6_UNIQUE ?false:true); break; default: - $ret=false; + $ret = false; } return $ret; @@ -2946,35 +2947,35 @@ class Societe extends CommonObject // phpcs:enable $field = $idprof; - switch($idprof) // For backward compatibility + switch ($idprof) // For backward compatibility { case '1': case 'idprof1': - $field="siren"; + $field = "siren"; break; case '2': case 'idprof2': - $field="siret"; + $field = "siret"; break; case '3': case 'idprof3': - $field="ape"; + $field = "ape"; break; case '4': case 'idprof4': - $field="idprof4"; + $field = "idprof4"; break; case '5': - $field="idprof5"; + $field = "idprof5"; break; case '6': - $field="idprof6"; + $field = "idprof6"; break; } //Verify duplicate entries - $sql = "SELECT COUNT(*) as idprof FROM ".MAIN_DB_PREFIX."societe WHERE ".$field." = '".$value."' AND entity IN (".getEntity('societe').")"; - if($socid) $sql .= " AND rowid <> ".$socid; + $sql = "SELECT COUNT(*) as idprof FROM ".MAIN_DB_PREFIX."societe WHERE ".$field." = '".$value."' AND entity IN (".getEntity('societe').")"; + if ($socid) $sql .= " AND rowid <> ".$socid; $resql = $this->db->query($sql); if ($resql) { @@ -3006,15 +3007,15 @@ class Societe extends CommonObject // phpcs:enable global $conf; - $ok=1; + $ok = 1; - if (! empty($conf->global->MAIN_DISABLEPROFIDRULES)) return 1; + if (!empty($conf->global->MAIN_DISABLEPROFIDRULES)) return 1; // Check SIREN if country FR if ($idprof == 1 && $soc->country_code == 'FR') { - $chaine=trim($this->idprof1); - $chaine=preg_replace('/(\s)/', '', $chaine); + $chaine = trim($this->idprof1); + $chaine = preg_replace('/(\s)/', '', $chaine); if (!is_numeric($chaine)) return -1; if (dol_strlen($chaine) != 9) return -1; @@ -3024,7 +3025,7 @@ class Societe extends CommonObject // on double sa valeur et si cette dernière est supérieure à 9, on lui retranche 9 // on ajoute cette valeur à la somme totale - for ($index = 0; $index < 9; $index ++) + for ($index = 0; $index < 9; $index++) { $number = (int) $chaine[$index]; if (($index % 2) != 0) { if (($number *= 2) > 9) $number -= 9; } @@ -3038,8 +3039,8 @@ class Societe extends CommonObject // Verifie SIRET si pays FR if ($idprof == 2 && $soc->country_code == 'FR') { - $chaine=trim($this->idprof2); - $chaine=preg_replace('/(\s)/', '', $chaine); + $chaine = trim($this->idprof2); + $chaine = preg_replace('/(\s)/', '', $chaine); if (!is_numeric($chaine)) return -1; if (dol_strlen($chaine) != 14) return -1; @@ -3049,7 +3050,7 @@ class Societe extends CommonObject // on double sa valeur et si cette dernière est supérieure à 9, on lui retranche 9 // on ajoute cette valeur à la somme totale - for ($index = 0; $index < 14; $index ++) + for ($index = 0; $index < 14; $index++) { $number = (int) $chaine[$index]; if (($index % 2) == 0) { if (($number *= 2) > 9) $number -= 9; } @@ -3064,8 +3065,8 @@ class Societe extends CommonObject //Returns: 1 if NIF ok, 2 if CIF ok, 3 if NIE ok, -1 if NIF bad, -2 if CIF bad, -3 if NIE bad, 0 if unexpected bad if ($idprof == 1 && $soc->country_code == 'ES') { - $string=trim($this->idprof1); - $string=preg_replace('/(\s)/', '', $string); + $string = trim($this->idprof1); + $string = preg_replace('/(\s)/', '', $string); $string = strtoupper($string); //Check format @@ -3073,7 +3074,7 @@ class Societe extends CommonObject return 0; $num = array(); - for ($i = 0; $i < 9; $i ++) + for ($i = 0; $i < 9; $i++) { $num[$i] = substr($string, $i, 1); } @@ -3114,7 +3115,7 @@ class Societe extends CommonObject //Check NIE XYZ if (preg_match('/^[XYZ]{1}/', $string)) - if ($num[8] == substr('TRWAGMYFPDXBNJZSQVHLCKE', substr(str_replace(array('X','Y','Z'), array('0','1','2'), $string), 0, 8) % 23, 1)) + if ($num[8] == substr('TRWAGMYFPDXBNJZSQVHLCKE', substr(str_replace(array('X', 'Y', 'Z'), array('0', '1', '2'), $string), 0, 8) % 23, 1)) return 3; else return -3; @@ -3127,10 +3128,10 @@ class Societe extends CommonObject //Returns: 1 if NIF ok, -1 if NIF bad, 0 if unexpected bad if ($idprof == 1 && $soc->country_code == 'PT') { - $string=trim($this->idprof1); - $string=preg_replace('/(\s)/', '', $string); + $string = trim($this->idprof1); + $string = preg_replace('/(\s)/', '', $string); - for ($i = 0; $i < 9; $i ++) { + for ($i = 0; $i < 9; $i++) { $num[$i] = substr($string, $i, 1); } @@ -3158,35 +3159,35 @@ class Societe extends CommonObject public function id_prof_url($idprof, $thirdparty) { // phpcs:enable - global $conf,$langs,$hookmanager; + global $conf, $langs, $hookmanager; - $url=''; + $url = ''; $action = ''; $hookmanager->initHooks(array('idprofurl')); - $parameters=array('idprof'=>$idprof, 'company'=>$thirdparty); - $reshook=$hookmanager->executeHooks('getIdProfUrl', $parameters, $this, $action); // Note that $action and $object may have been modified by some hooks + $parameters = array('idprof'=>$idprof, 'company'=>$thirdparty); + $reshook = $hookmanager->executeHooks('getIdProfUrl', $parameters, $this, $action); // Note that $action and $object may have been modified by some hooks if (empty($reshook)) { - if (! empty($conf->global->MAIN_DISABLEPROFIDRULES)) { + if (!empty($conf->global->MAIN_DISABLEPROFIDRULES)) { return ''; } // TODO Move links to validate professional ID into a dictionary table "country" + "link" $strippedIdProf1 = str_replace(' ', '', $thirdparty->idprof1); if ($idprof == 1 && $thirdparty->country_code == 'FR') { - $url='http://www.societe.com/cgi-bin/search?champs='.$strippedIdProf1; // See also http://avis-situation-sirene.insee.fr/ + $url = 'http://www.societe.com/cgi-bin/search?champs='.$strippedIdProf1; // See also http://avis-situation-sirene.insee.fr/ } if ($idprof == 1 && ($thirdparty->country_code == 'GB' || $thirdparty->country_code == 'UK')) { - $url='https://beta.companieshouse.gov.uk/company/'.$strippedIdProf1; + $url = 'https://beta.companieshouse.gov.uk/company/'.$strippedIdProf1; } if ($idprof == 1 && $thirdparty->country_code == 'ES') { - $url='http://www.e-informa.es/servlet/app/portal/ENTP/screen/SProducto/prod/ETIQUETA_EMPRESA/nif/'.$strippedIdProf1; + $url = 'http://www.e-informa.es/servlet/app/portal/ENTP/screen/SProducto/prod/ETIQUETA_EMPRESA/nif/'.$strippedIdProf1; } if ($idprof == 1 && $thirdparty->country_code == 'IN') { - $url='http://www.tinxsys.com/TinxsysInternetWeb/dealerControllerServlet?tinNumber='.$strippedIdProf1.';&searchBy=TIN&backPage=searchByTin_Inter.jsp'; + $url = 'http://www.tinxsys.com/TinxsysInternetWeb/dealerControllerServlet?tinNumber='.$strippedIdProf1.';&searchBy=TIN&backPage=searchByTin_Inter.jsp'; } if ($idprof == 1 && $thirdparty->country_code == 'PT') { - $url='http://www.nif.pt/'.$strippedIdProf1; + $url = 'http://www.nif.pt/'.$strippedIdProf1; } if ($url) { @@ -3209,7 +3210,7 @@ class Societe extends CommonObject public function has_projects() { // phpcs:enable - $sql = 'SELECT COUNT(*) as numproj FROM '.MAIN_DB_PREFIX.'projet WHERE fk_soc = ' . $this->id; + $sql = 'SELECT COUNT(*) as numproj FROM '.MAIN_DB_PREFIX.'projet WHERE fk_soc = '.$this->id; $resql = $this->db->query($sql); if ($resql) { @@ -3235,11 +3236,11 @@ class Societe extends CommonObject public function info($id) { $sql = "SELECT s.rowid, s.nom as name, s.datec as date_creation, tms as date_modification,"; - $sql.= " fk_user_creat, fk_user_modif"; - $sql.= " FROM ".MAIN_DB_PREFIX."societe as s"; - $sql.= " WHERE s.rowid = ".$id; + $sql .= " fk_user_creat, fk_user_modif"; + $sql .= " FROM ".MAIN_DB_PREFIX."societe as s"; + $sql .= " WHERE s.rowid = ".$id; - $result=$this->db->query($sql); + $result = $this->db->query($sql); if ($result) { if ($this->db->num_rows($result)) @@ -3251,7 +3252,7 @@ class Societe extends CommonObject if ($obj->fk_user_creat) { $cuser = new User($this->db); $cuser->fetch($obj->fk_user_creat); - $this->user_creation = $cuser; + $this->user_creation = $cuser; } if ($obj->fk_user_modif) { @@ -3260,7 +3261,7 @@ class Societe extends CommonObject $this->user_modification = $muser; } - $this->ref = $obj->name; + $this->ref = $obj->name; $this->date_creation = $this->db->jdate($obj->date_creation); $this->date_modification = $this->db->jdate($obj->date_modification); } @@ -3283,13 +3284,18 @@ class Societe extends CommonObject global $conf; // Define if third party is treated as company (or not) when nature is unknown - $isacompany=empty($conf->global->MAIN_UNKNOWN_CUSTOMERS_ARE_COMPANIES)?0:1; // 0 by default - if (! empty($this->tva_intra)) $isacompany=1; - elseif (! empty($this->typent_code) && $this->typent_code != 'TE_UNKNOWN') + $isacompany = empty($conf->global->MAIN_UNKNOWN_CUSTOMERS_ARE_COMPANIES) ? 0 : 1; // 0 by default + if (!empty($this->tva_intra)) { + $isacompany = 1; + } + elseif (!empty($this->idprof1) || !empty($this->idprof2) || !empty($this->idprof3) || !empty($this->idprof4) || !empty($this->idprof5) || !empty($this->idprof6)) { + $isacompany = 1; + } + elseif (!empty($this->typent_code) && $this->typent_code != 'TE_UNKNOWN') { // TODO Add a field is_a_company into dictionary - if (preg_match('/^TE_PRIVATE/', $this->typent_code)) $isacompany=0; - else $isacompany=1; + if (preg_match('/^TE_PRIVATE/', $this->typent_code)) $isacompany = 0; + else $isacompany = 1; } return $isacompany; @@ -3317,13 +3323,13 @@ class Societe extends CommonObject // phpcs:enable $this->SupplierCategories = array(); $sql = "SELECT rowid, label"; - $sql.= " FROM ".MAIN_DB_PREFIX."categorie"; - $sql.= " WHERE type = ".Categorie::TYPE_SUPPLIER; + $sql .= " FROM ".MAIN_DB_PREFIX."categorie"; + $sql .= " WHERE type = ".Categorie::TYPE_SUPPLIER; - $resql=$this->db->query($sql); + $resql = $this->db->query($sql); if ($resql) { - while ($obj = $this->db->fetch_object($resql) ) + while ($obj = $this->db->fetch_object($resql)) { $this->SupplierCategories[$obj->rowid] = $obj->label; } @@ -3348,9 +3354,9 @@ class Societe extends CommonObject if ($categorie_id > 0 && $this->id > 0) { $sql = "INSERT INTO ".MAIN_DB_PREFIX."categorie_fournisseur (fk_categorie, fk_soc) "; - $sql.= " VALUES (".$categorie_id.", ".$this->id.")"; + $sql .= " VALUES (".$categorie_id.", ".$this->id.")"; - if ($resql=$this->db->query($sql)) return 0; + if ($resql = $this->db->query($sql)) return 0; } else { @@ -3373,43 +3379,43 @@ class Societe extends CommonObject public function create_from_member(Adherent $member, $socname = '', $socalias = '', $customercode = '') { // phpcs:enable - global $user,$langs; + global $user, $langs; dol_syslog(get_class($this)."::create_from_member", LOG_DEBUG); - $name = $socname?$socname:$member->societe; - if (empty($name)) $name=$member->getFullName($langs); + $name = $socname ? $socname : $member->societe; + if (empty($name)) $name = $member->getFullName($langs); - $alias = $socalias?$socalias:''; + $alias = $socalias ? $socalias : ''; // Positionne parametres - $this->nom=$name; // TODO deprecated - $this->name=$name; - $this->name_alias=$alias; - $this->address=$member->address; - $this->zip=$member->zip; - $this->town=$member->town; - $this->country_code=$member->country_code; - $this->country_id=$member->country_id; - $this->phone=$member->phone; // Prof phone - $this->email=$member->email; + $this->nom = $name; // TODO deprecated + $this->name = $name; + $this->name_alias = $alias; + $this->address = $member->address; + $this->zip = $member->zip; + $this->town = $member->town; + $this->country_code = $member->country_code; + $this->country_id = $member->country_id; + $this->phone = $member->phone; // Prof phone + $this->email = $member->email; $this->socialnetworks = $member->socialnetworks; - $this->client = 1; // A member is a customer by default - $this->code_client = ($customercode?$customercode:-1); + $this->client = 1; // A member is a customer by default + $this->code_client = ($customercode ? $customercode : -1); $this->code_fournisseur = -1; $this->db->begin(); // Cree et positionne $this->id - $result=$this->create($user); + $result = $this->create($user); if ($result >= 0) { $sql = "UPDATE ".MAIN_DB_PREFIX."adherent"; - $sql.= " SET fk_soc=".$this->id; - $sql.= " WHERE rowid=".$member->id; + $sql .= " SET fk_soc=".$this->id; + $sql .= " WHERE rowid=".$member->id; - $resql=$this->db->query($sql); + $resql = $this->db->query($sql); if ($resql) { $this->db->commit(); @@ -3417,7 +3423,7 @@ class Societe extends CommonObject } else { - $this->error=$this->db->error(); + $this->error = $this->db->error(); $this->db->rollback(); return -1; @@ -3443,96 +3449,96 @@ class Societe extends CommonObject { global $langs; - $this->id=0; - $this->name=empty($conf->global->MAIN_INFO_SOCIETE_NOM)?'':$conf->global->MAIN_INFO_SOCIETE_NOM; - $this->address=empty($conf->global->MAIN_INFO_SOCIETE_ADDRESS)?'':$conf->global->MAIN_INFO_SOCIETE_ADDRESS; - $this->zip=empty($conf->global->MAIN_INFO_SOCIETE_ZIP)?'':$conf->global->MAIN_INFO_SOCIETE_ZIP; - $this->town=empty($conf->global->MAIN_INFO_SOCIETE_TOWN)?'':$conf->global->MAIN_INFO_SOCIETE_TOWN; - $this->region_code=empty($conf->global->MAIN_INFO_SOCIETE_REGION)?'':$conf->global->MAIN_INFO_SOCIETE_REGION; - $this->object=empty($conf->global->MAIN_INFO_SOCIETE_OBJECT)?'':$conf->global->MAIN_INFO_SOCIETE_OBJECT; + $this->id = 0; + $this->name = empty($conf->global->MAIN_INFO_SOCIETE_NOM) ? '' : $conf->global->MAIN_INFO_SOCIETE_NOM; + $this->address = empty($conf->global->MAIN_INFO_SOCIETE_ADDRESS) ? '' : $conf->global->MAIN_INFO_SOCIETE_ADDRESS; + $this->zip = empty($conf->global->MAIN_INFO_SOCIETE_ZIP) ? '' : $conf->global->MAIN_INFO_SOCIETE_ZIP; + $this->town = empty($conf->global->MAIN_INFO_SOCIETE_TOWN) ? '' : $conf->global->MAIN_INFO_SOCIETE_TOWN; + $this->region_code = empty($conf->global->MAIN_INFO_SOCIETE_REGION) ? '' : $conf->global->MAIN_INFO_SOCIETE_REGION; + $this->object = empty($conf->global->MAIN_INFO_SOCIETE_OBJECT) ? '' : $conf->global->MAIN_INFO_SOCIETE_OBJECT; - $this->note_private=empty($conf->global->MAIN_INFO_SOCIETE_NOTE)?'':$conf->global->MAIN_INFO_SOCIETE_NOTE; + $this->note_private = empty($conf->global->MAIN_INFO_SOCIETE_NOTE) ? '' : $conf->global->MAIN_INFO_SOCIETE_NOTE; - $this->nom=$this->name; // deprecated + $this->nom = $this->name; // deprecated // We define country_id, country_code and country - $country_id=$country_code=$country_label=''; - if (! empty($conf->global->MAIN_INFO_SOCIETE_COUNTRY)) + $country_id = $country_code = $country_label = ''; + if (!empty($conf->global->MAIN_INFO_SOCIETE_COUNTRY)) { - $tmp=explode(':', $conf->global->MAIN_INFO_SOCIETE_COUNTRY); - $country_id=$tmp[0]; - if (! empty($tmp[1])) // If $conf->global->MAIN_INFO_SOCIETE_COUNTRY is "id:code:label" + $tmp = explode(':', $conf->global->MAIN_INFO_SOCIETE_COUNTRY); + $country_id = $tmp[0]; + if (!empty($tmp[1])) // If $conf->global->MAIN_INFO_SOCIETE_COUNTRY is "id:code:label" { - $country_code=$tmp[1]; - $country_label=$tmp[2]; + $country_code = $tmp[1]; + $country_label = $tmp[2]; } else // For backward compatibility { dol_syslog("Your country setup use an old syntax. Reedit it using setup area.", LOG_WARNING); include_once DOL_DOCUMENT_ROOT.'/core/lib/company.lib.php'; - $country_code=getCountry($country_id, 2, $this->db); // This need a SQL request, but it's the old feature that should not be used anymore - $country_label=getCountry($country_id, 0, $this->db); // This need a SQL request, but it's the old feature that should not be used anymore + $country_code = getCountry($country_id, 2, $this->db); // This need a SQL request, but it's the old feature that should not be used anymore + $country_label = getCountry($country_id, 0, $this->db); // This need a SQL request, but it's the old feature that should not be used anymore } } - $this->country_id=$country_id; - $this->country_code=$country_code; - $this->country=$country_label; - if (is_object($langs)) $this->country=($langs->trans('Country'.$country_code)!='Country'.$country_code)?$langs->trans('Country'.$country_code):$country_label; + $this->country_id = $country_id; + $this->country_code = $country_code; + $this->country = $country_label; + if (is_object($langs)) $this->country = ($langs->trans('Country'.$country_code) != 'Country'.$country_code) ? $langs->trans('Country'.$country_code) : $country_label; //TODO This could be replicated for region but function `getRegion` didn't exist, so I didn't added it. // We define state_id, state_code and state - $state_id=0;$state_code=$state_label=''; - if (! empty($conf->global->MAIN_INFO_SOCIETE_STATE)) + $state_id = 0; $state_code = $state_label = ''; + if (!empty($conf->global->MAIN_INFO_SOCIETE_STATE)) { - $tmp=explode(':', $conf->global->MAIN_INFO_SOCIETE_STATE); - $state_id=$tmp[0]; - if (! empty($tmp[1])) // If $conf->global->MAIN_INFO_SOCIETE_STATE is "id:code:label" + $tmp = explode(':', $conf->global->MAIN_INFO_SOCIETE_STATE); + $state_id = $tmp[0]; + if (!empty($tmp[1])) // If $conf->global->MAIN_INFO_SOCIETE_STATE is "id:code:label" { - $state_code=$tmp[1]; - $state_label=$tmp[2]; + $state_code = $tmp[1]; + $state_label = $tmp[2]; } else // For backward compatibility { dol_syslog("Your state setup use an old syntax. Reedit it using setup area.", LOG_ERR); include_once DOL_DOCUMENT_ROOT.'/core/lib/company.lib.php'; - $state_code=getState($state_id, 2, $this->db); // This need a SQL request, but it's the old feature that should not be used anymore - $state_label=getState($state_id, 0, $this->db); // This need a SQL request, but it's the old feature that should not be used anymore + $state_code = getState($state_id, 2, $this->db); // This need a SQL request, but it's the old feature that should not be used anymore + $state_label = getState($state_id, 0, $this->db); // This need a SQL request, but it's the old feature that should not be used anymore } } - $this->state_id=$state_id; - $this->state_code=$state_code; - $this->state=$state_label; - if (is_object($langs)) $this->state=($langs->trans('State'.$state_code)!='State'.$state_code)?$langs->trans('State'.$state_code):$state_label; + $this->state_id = $state_id; + $this->state_code = $state_code; + $this->state = $state_label; + if (is_object($langs)) $this->state = ($langs->trans('State'.$state_code) != 'State'.$state_code) ? $langs->trans('State'.$state_code) : $state_label; - $this->phone=empty($conf->global->MAIN_INFO_SOCIETE_TEL)?'':$conf->global->MAIN_INFO_SOCIETE_TEL; - $this->fax=empty($conf->global->MAIN_INFO_SOCIETE_FAX)?'':$conf->global->MAIN_INFO_SOCIETE_FAX; - $this->url=empty($conf->global->MAIN_INFO_SOCIETE_WEB)?'':$conf->global->MAIN_INFO_SOCIETE_WEB; + $this->phone = empty($conf->global->MAIN_INFO_SOCIETE_TEL) ? '' : $conf->global->MAIN_INFO_SOCIETE_TEL; + $this->fax = empty($conf->global->MAIN_INFO_SOCIETE_FAX) ? '' : $conf->global->MAIN_INFO_SOCIETE_FAX; + $this->url = empty($conf->global->MAIN_INFO_SOCIETE_WEB) ? '' : $conf->global->MAIN_INFO_SOCIETE_WEB; // Id prof generiques - $this->idprof1=empty($conf->global->MAIN_INFO_SIREN)?'':$conf->global->MAIN_INFO_SIREN; - $this->idprof2=empty($conf->global->MAIN_INFO_SIRET)?'':$conf->global->MAIN_INFO_SIRET; - $this->idprof3=empty($conf->global->MAIN_INFO_APE)?'':$conf->global->MAIN_INFO_APE; - $this->idprof4=empty($conf->global->MAIN_INFO_RCS)?'':$conf->global->MAIN_INFO_RCS; - $this->idprof5=empty($conf->global->MAIN_INFO_PROFID5)?'':$conf->global->MAIN_INFO_PROFID5; - $this->idprof6=empty($conf->global->MAIN_INFO_PROFID6)?'':$conf->global->MAIN_INFO_PROFID6; - $this->tva_intra=empty($conf->global->MAIN_INFO_TVAINTRA)?'':$conf->global->MAIN_INFO_TVAINTRA; // VAT number, not necessarly INTRA. - $this->managers=empty($conf->global->MAIN_INFO_SOCIETE_MANAGERS)?'':$conf->global->MAIN_INFO_SOCIETE_MANAGERS; - $this->capital=empty($conf->global->MAIN_INFO_CAPITAL)?'':$conf->global->MAIN_INFO_CAPITAL; - $this->forme_juridique_code=empty($conf->global->MAIN_INFO_SOCIETE_FORME_JURIDIQUE)?'':$conf->global->MAIN_INFO_SOCIETE_FORME_JURIDIQUE; - $this->email=empty($conf->global->MAIN_INFO_SOCIETE_MAIL)?'':$conf->global->MAIN_INFO_SOCIETE_MAIL; - $this->default_lang = (empty($conf->global->MAIN_LANG_DEFAULT)?'auto':$conf->global->MAIN_LANG_DEFAULT); - $this->logo=empty($conf->global->MAIN_INFO_SOCIETE_LOGO)?'':$conf->global->MAIN_INFO_SOCIETE_LOGO; - $this->logo_small=empty($conf->global->MAIN_INFO_SOCIETE_LOGO_SMALL)?'':$conf->global->MAIN_INFO_SOCIETE_LOGO_SMALL; - $this->logo_mini=empty($conf->global->MAIN_INFO_SOCIETE_LOGO_MINI)?'':$conf->global->MAIN_INFO_SOCIETE_LOGO_MINI; - $this->logo_squarred=empty($conf->global->MAIN_INFO_SOCIETE_LOGO_SQUARRED)?'':$conf->global->MAIN_INFO_SOCIETE_LOGO_SQUARRED; - $this->logo_squarred_small=empty($conf->global->MAIN_INFO_SOCIETE_LOGO_SQUARRED_SMALL)?'':$conf->global->MAIN_INFO_SOCIETE_LOGO_SQUARRED_SMALL; - $this->logo_squarred_mini=empty($conf->global->MAIN_INFO_SOCIETE_LOGO_SQUARRED_MINI)?'':$conf->global->MAIN_INFO_SOCIETE_LOGO_SQUARRED_MINI; + $this->idprof1 = empty($conf->global->MAIN_INFO_SIREN) ? '' : $conf->global->MAIN_INFO_SIREN; + $this->idprof2 = empty($conf->global->MAIN_INFO_SIRET) ? '' : $conf->global->MAIN_INFO_SIRET; + $this->idprof3 = empty($conf->global->MAIN_INFO_APE) ? '' : $conf->global->MAIN_INFO_APE; + $this->idprof4 = empty($conf->global->MAIN_INFO_RCS) ? '' : $conf->global->MAIN_INFO_RCS; + $this->idprof5 = empty($conf->global->MAIN_INFO_PROFID5) ? '' : $conf->global->MAIN_INFO_PROFID5; + $this->idprof6 = empty($conf->global->MAIN_INFO_PROFID6) ? '' : $conf->global->MAIN_INFO_PROFID6; + $this->tva_intra = empty($conf->global->MAIN_INFO_TVAINTRA) ? '' : $conf->global->MAIN_INFO_TVAINTRA; // VAT number, not necessarly INTRA. + $this->managers = empty($conf->global->MAIN_INFO_SOCIETE_MANAGERS) ? '' : $conf->global->MAIN_INFO_SOCIETE_MANAGERS; + $this->capital = empty($conf->global->MAIN_INFO_CAPITAL) ? '' : $conf->global->MAIN_INFO_CAPITAL; + $this->forme_juridique_code = empty($conf->global->MAIN_INFO_SOCIETE_FORME_JURIDIQUE) ? '' : $conf->global->MAIN_INFO_SOCIETE_FORME_JURIDIQUE; + $this->email = empty($conf->global->MAIN_INFO_SOCIETE_MAIL) ? '' : $conf->global->MAIN_INFO_SOCIETE_MAIL; + $this->default_lang = (empty($conf->global->MAIN_LANG_DEFAULT) ? 'auto' : $conf->global->MAIN_LANG_DEFAULT); + $this->logo = empty($conf->global->MAIN_INFO_SOCIETE_LOGO) ? '' : $conf->global->MAIN_INFO_SOCIETE_LOGO; + $this->logo_small = empty($conf->global->MAIN_INFO_SOCIETE_LOGO_SMALL) ? '' : $conf->global->MAIN_INFO_SOCIETE_LOGO_SMALL; + $this->logo_mini = empty($conf->global->MAIN_INFO_SOCIETE_LOGO_MINI) ? '' : $conf->global->MAIN_INFO_SOCIETE_LOGO_MINI; + $this->logo_squarred = empty($conf->global->MAIN_INFO_SOCIETE_LOGO_SQUARRED) ? '' : $conf->global->MAIN_INFO_SOCIETE_LOGO_SQUARRED; + $this->logo_squarred_small = empty($conf->global->MAIN_INFO_SOCIETE_LOGO_SQUARRED_SMALL) ? '' : $conf->global->MAIN_INFO_SOCIETE_LOGO_SQUARRED_SMALL; + $this->logo_squarred_mini = empty($conf->global->MAIN_INFO_SOCIETE_LOGO_SQUARRED_MINI) ? '' : $conf->global->MAIN_INFO_SOCIETE_LOGO_SQUARRED_MINI; // Define if company use vat or not - $this->tva_assuj=$conf->global->FACTURE_TVAOPTION; + $this->tva_assuj = $conf->global->FACTURE_TVAOPTION; // Define if company use local taxes - $this->localtax1_assuj=((isset($conf->global->FACTURE_LOCAL_TAX1_OPTION) && ($conf->global->FACTURE_LOCAL_TAX1_OPTION=='1' || $conf->global->FACTURE_LOCAL_TAX1_OPTION=='localtax1on'))?1:0); - $this->localtax2_assuj=((isset($conf->global->FACTURE_LOCAL_TAX2_OPTION) && ($conf->global->FACTURE_LOCAL_TAX2_OPTION=='1' || $conf->global->FACTURE_LOCAL_TAX2_OPTION=='localtax2on'))?1:0); + $this->localtax1_assuj = ((isset($conf->global->FACTURE_LOCAL_TAX1_OPTION) && ($conf->global->FACTURE_LOCAL_TAX1_OPTION == '1' || $conf->global->FACTURE_LOCAL_TAX1_OPTION == 'localtax1on')) ? 1 : 0); + $this->localtax2_assuj = ((isset($conf->global->FACTURE_LOCAL_TAX2_OPTION) && ($conf->global->FACTURE_LOCAL_TAX2_OPTION == '1' || $conf->global->FACTURE_LOCAL_TAX2_OPTION == 'localtax2on')) ? 1 : 0); } /** @@ -3544,51 +3550,51 @@ class Societe extends CommonObject */ public function initAsSpecimen() { - $now=dol_now(); + $now = dol_now(); // Initialize parameters - $this->id=0; + $this->id = 0; $this->name = 'THIRDPARTY SPECIMEN '.dol_print_date($now, 'dayhourlog'); - $this->nom = $this->name; // For backward compatibility + $this->nom = $this->name; // For backward compatibility $this->ref_ext = 'Ref ext'; - $this->specimen=1; - $this->address='21 jump street'; - $this->zip='99999'; - $this->town='MyTown'; - $this->state_id=1; - $this->state_code='AA'; - $this->state='MyState'; - $this->country_id=1; - $this->country_code='FR'; - $this->email='specimen@specimen.com'; + $this->specimen = 1; + $this->address = '21 jump street'; + $this->zip = '99999'; + $this->town = 'MyTown'; + $this->state_id = 1; + $this->state_code = 'AA'; + $this->state = 'MyState'; + $this->country_id = 1; + $this->country_code = 'FR'; + $this->email = 'specimen@specimen.com'; $this->socialnetworks = array( 'skype' => 'tom.hanson', 'twitter' => 'tomhanson', 'facebook' => 'tomhanson', 'linkedin' => 'tomhanson', ); - $this->url='http://www.specimen.com'; + $this->url = 'http://www.specimen.com'; - $this->phone='0909090901'; - $this->fax='0909090909'; + $this->phone = '0909090901'; + $this->fax = '0909090909'; - $this->code_client='CC-'.dol_print_date($now, 'dayhourlog'); - $this->code_fournisseur='SC-'.dol_print_date($now, 'dayhourlog'); - $this->capital=10000; - $this->client=1; - $this->prospect=1; - $this->fournisseur=1; - $this->tva_assuj=1; - $this->tva_intra='EU1234567'; - $this->note_public='This is a comment (public)'; - $this->note_private='This is a comment (private)'; + $this->code_client = 'CC-'.dol_print_date($now, 'dayhourlog'); + $this->code_fournisseur = 'SC-'.dol_print_date($now, 'dayhourlog'); + $this->capital = 10000; + $this->client = 1; + $this->prospect = 1; + $this->fournisseur = 1; + $this->tva_assuj = 1; + $this->tva_intra = 'EU1234567'; + $this->note_public = 'This is a comment (public)'; + $this->note_private = 'This is a comment (private)'; - $this->idprof1='idprof1'; - $this->idprof2='idprof2'; - $this->idprof3='idprof3'; - $this->idprof4='idprof4'; - $this->idprof5='idprof5'; - $this->idprof6='idprof6'; + $this->idprof1 = 'idprof1'; + $this->idprof2 = 'idprof2'; + $this->idprof3 = 'idprof3'; + $this->idprof4 = 'idprof4'; + $this->idprof5 = 'idprof5'; + $this->idprof6 = 'idprof6'; return 1; } @@ -3609,7 +3615,7 @@ class Societe extends CommonObject elseif ($localTaxNum == 2) $sql .= " AND t.localtax2_type <> '0'"; dol_syslog("useLocalTax", LOG_DEBUG); - $resql=$this->db->query($sql); + $resql = $this->db->query($sql); if ($resql) { return ($this->db->num_rows($resql) > 0); @@ -3630,7 +3636,7 @@ class Societe extends CommonObject $sql .= " AND t.active = 1 AND t.recuperableonly = 1"; dol_syslog("useNPR", LOG_DEBUG); - $resql=$this->db->query($sql); + $resql = $this->db->query($sql); if ($resql) { return ($this->db->num_rows($resql) > 0); @@ -3651,15 +3657,15 @@ class Societe extends CommonObject $sql .= " AND r.active = 1"; dol_syslog("useRevenueStamp", LOG_DEBUG); - $resql=$this->db->query($sql); + $resql = $this->db->query($sql); if ($resql) { - $obj=$this->db->fetch_object($resql); - return (($obj->nb > 0)?true:false); + $obj = $this->db->fetch_object($resql); + return (($obj->nb > 0) ?true:false); } else { - $this->error=$this->db->lasterror(); + $this->error = $this->db->lasterror(); return false; } } @@ -3686,11 +3692,11 @@ class Societe extends CommonObject // phpcs:enable global $langs; - $lib=$langs->trans("ProspectLevel".$fk_prospectlevel); + $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)) { - $lib=$langs->getLabelFromKey($this->db, $fk_prospectlevel, 'c_prospectlevel', 'code', 'label'); + $lib = $langs->getLabelFromKey($this->db, $fk_prospectlevel, 'c_prospectlevel', 'code', 'label'); } return $lib; } @@ -3740,10 +3746,10 @@ class Societe extends CommonObject if ($mode == 2) { if ($status == '-1' || $status == 'ST_NO') return img_action($langs->trans("StatusProspect-1"), -1).' '.$langs->trans("StatusProspect-1"); - elseif ($status == '0' || $status == 'ST_NEVER') return img_action($langs->trans("StatusProspect0"), 0).' '.$langs->trans("StatusProspect0"); - elseif ($status == '1' || $status == 'ST_TODO') return img_action($langs->trans("StatusProspect1"), 1).' '.$langs->trans("StatusProspect1"); - elseif ($status == '2' || $status == 'ST_PEND') return img_action($langs->trans("StatusProspect2"), 2).' '.$langs->trans("StatusProspect2"); - elseif ($status == '3' || $status == 'ST_DONE') return img_action($langs->trans("StatusProspect3"), 3).' '.$langs->trans("StatusProspect3"); + elseif ($status == '0' || $status == 'ST_NEVER') return img_action($langs->trans("StatusProspect0"), 0).' '.$langs->trans("StatusProspect0"); + elseif ($status == '1' || $status == 'ST_TODO') return img_action($langs->trans("StatusProspect1"), 1).' '.$langs->trans("StatusProspect1"); + elseif ($status == '2' || $status == 'ST_PEND') return img_action($langs->trans("StatusProspect2"), 2).' '.$langs->trans("StatusProspect2"); + elseif ($status == '3' || $status == 'ST_DONE') return img_action($langs->trans("StatusProspect3"), 3).' '.$langs->trans("StatusProspect3"); else { return img_action(($langs->trans("StatusProspect".$status) != "StatusProspect".$status) ? $langs->trans("StatusProspect".$status) : $label, 0).' '.(($langs->trans("StatusProspect".$status) != "StatusProspect".$status) ? $langs->trans("StatusProspect".$status) : $label); @@ -3752,10 +3758,10 @@ class Societe extends CommonObject if ($mode == 3) { if ($status == '-1' || $status == 'ST_NO') return img_action($langs->trans("StatusProspect-1"), -1); - elseif ($status == '0' || $status == 'ST_NEVER') return img_action($langs->trans("StatusProspect0"), 0); - elseif ($status == '1' || $status == 'ST_TODO') return img_action($langs->trans("StatusProspect1"), 1); - elseif ($status == '2' || $status == 'ST_PEND') return img_action($langs->trans("StatusProspect2"), 2); - elseif ($status == '3' || $status == 'ST_DONE') return img_action($langs->trans("StatusProspect3"), 3); + elseif ($status == '0' || $status == 'ST_NEVER') return img_action($langs->trans("StatusProspect0"), 0); + elseif ($status == '1' || $status == 'ST_TODO') return img_action($langs->trans("StatusProspect1"), 1); + elseif ($status == '2' || $status == 'ST_PEND') return img_action($langs->trans("StatusProspect2"), 2); + elseif ($status == '3' || $status == 'ST_DONE') return img_action($langs->trans("StatusProspect3"), 3); else { return img_action(($langs->trans("StatusProspect".$status) != "StatusProspect".$status) ? $langs->trans("StatusProspect".$status) : $label, 0); @@ -3764,10 +3770,10 @@ class Societe extends CommonObject if ($mode == 4) { if ($status == '-1' || $status == 'ST_NO') return img_action($langs->trans("StatusProspect-1"), -1).' '.$langs->trans("StatusProspect-1"); - elseif ($status == '0' || $status == 'ST_NEVER') return img_action($langs->trans("StatusProspect0"), 0).' '.$langs->trans("StatusProspect0"); - elseif ($status == '1' || $status == 'ST_TODO') return img_action($langs->trans("StatusProspect1"), 1).' '.$langs->trans("StatusProspect1"); - elseif ($status == '2' || $status == 'ST_PEND') return img_action($langs->trans("StatusProspect2"), 2).' '.$langs->trans("StatusProspect2"); - elseif ($status == '3' || $status == 'ST_DONE') return img_action($langs->trans("StatusProspect3"), 3).' '.$langs->trans("StatusProspect3"); + elseif ($status == '0' || $status == 'ST_NEVER') return img_action($langs->trans("StatusProspect0"), 0).' '.$langs->trans("StatusProspect0"); + elseif ($status == '1' || $status == 'ST_TODO') return img_action($langs->trans("StatusProspect1"), 1).' '.$langs->trans("StatusProspect1"); + elseif ($status == '2' || $status == 'ST_PEND') return img_action($langs->trans("StatusProspect2"), 2).' '.$langs->trans("StatusProspect2"); + elseif ($status == '3' || $status == 'ST_DONE') return img_action($langs->trans("StatusProspect3"), 3).' '.$langs->trans("StatusProspect3"); else { return img_action(($langs->trans("StatusProspect".$status) != "StatusProspect".$status) ? $langs->trans("StatusProspect".$status) : $label, 0).' '.(($langs->trans("StatusProspect".$status) != "StatusProspect".$status) ? $langs->trans("StatusProspect".$status) : $label); @@ -3799,11 +3805,11 @@ class Societe extends CommonObject */ public function getOutstandingProposals($mode = 'customer') { - $table='propal'; + $table = 'propal'; if ($mode == 'supplier') $table = 'supplier_proposal'; $sql = "SELECT rowid, total_ht, total as total_ttc, fk_statut FROM ".MAIN_DB_PREFIX.$table." as f"; - $sql .= " WHERE fk_soc = ". $this->id; + $sql .= " WHERE fk_soc = ".$this->id; if ($mode == 'supplier') { $sql .= " AND entity IN (".getEntity('supplier_proposal').")"; } else { @@ -3811,21 +3817,21 @@ class Societe extends CommonObject } dol_syslog("getOutstandingProposals", LOG_DEBUG); - $resql=$this->db->query($sql); + $resql = $this->db->query($sql); if ($resql) { $outstandingOpened = 0; $outstandingTotal = 0; $outstandingTotalIncTax = 0; - while($obj=$this->db->fetch_object($resql)) { - $outstandingTotal+= $obj->total_ht; - $outstandingTotalIncTax+= $obj->total_ttc; + while ($obj = $this->db->fetch_object($resql)) { + $outstandingTotal += $obj->total_ht; + $outstandingTotalIncTax += $obj->total_ttc; if ($obj->fk_statut != 0) // Not a draft { - $outstandingOpened+=$obj->total_ttc; + $outstandingOpened += $obj->total_ttc; } } - return array('opened'=>$outstandingOpened, 'total_ht'=>$outstandingTotal, 'total_ttc'=>$outstandingTotalIncTax); // 'opened' is 'incl taxes' + return array('opened'=>$outstandingOpened, 'total_ht'=>$outstandingTotal, 'total_ttc'=>$outstandingTotalIncTax); // 'opened' is 'incl taxes' } else return array(); @@ -3839,11 +3845,11 @@ class Societe extends CommonObject */ public function getOutstandingOrders($mode = 'customer') { - $table='commande'; + $table = 'commande'; if ($mode == 'supplier') $table = 'commande_fournisseur'; $sql = "SELECT rowid, total_ht, total_ttc, fk_statut FROM ".MAIN_DB_PREFIX.$table." as f"; - $sql .= " WHERE fk_soc = ". $this->id; + $sql .= " WHERE fk_soc = ".$this->id; if ($mode == 'supplier') { $sql .= " AND entity IN (".getEntity('supplier_order').")"; } else { @@ -3851,21 +3857,21 @@ class Societe extends CommonObject } dol_syslog("getOutstandingOrders", LOG_DEBUG); - $resql=$this->db->query($sql); + $resql = $this->db->query($sql); if ($resql) { $outstandingOpened = 0; $outstandingTotal = 0; $outstandingTotalIncTax = 0; - while($obj=$this->db->fetch_object($resql)) { - $outstandingTotal+= $obj->total_ht; - $outstandingTotalIncTax+= $obj->total_ttc; + while ($obj = $this->db->fetch_object($resql)) { + $outstandingTotal += $obj->total_ht; + $outstandingTotalIncTax += $obj->total_ttc; if ($obj->fk_statut != 0) // Not a draft { - $outstandingOpened+=$obj->total_ttc; + $outstandingOpened += $obj->total_ttc; } } - return array('opened'=>$outstandingOpened, 'total_ht'=>$outstandingTotal, 'total_ttc'=>$outstandingTotalIncTax); // 'opened' is 'incl taxes' + return array('opened'=>$outstandingOpened, 'total_ht'=>$outstandingTotal, 'total_ttc'=>$outstandingTotalIncTax); // 'opened' is 'incl taxes' } else return array(); @@ -3879,7 +3885,7 @@ class Societe extends CommonObject */ public function getOutstandingBills($mode = 'customer') { - $table='facture'; + $table = 'facture'; if ($mode == 'supplier') $table = 'facture_fourn'; /* Accurate value of remain to pay is to sum remaintopay for each invoice @@ -3889,9 +3895,9 @@ class Societe extends CommonObject $alreadypayed=price2num($paiement + $creditnotes + $deposits,'MT'); $remaintopay=price2num($invoice->total_ttc - $paiement - $creditnotes - $deposits,'MT'); */ - if ($mode == 'supplier') $sql = "SELECT rowid, total_ht as total_ht, total_ttc, paye, type, fk_statut, close_code FROM ".MAIN_DB_PREFIX.$table." as f"; - else $sql = "SELECT rowid, total as total_ht, total_ttc, paye, fk_statut, close_code FROM ".MAIN_DB_PREFIX.$table." as f"; - $sql .= " WHERE fk_soc = ". $this->id; + if ($mode == 'supplier') $sql = "SELECT rowid, total_ht as total_ht, total_ttc, paye, type, fk_statut, close_code FROM ".MAIN_DB_PREFIX.$table." as f"; + else $sql = "SELECT rowid, total as total_ht, total_ttc, paye, fk_statut, close_code FROM ".MAIN_DB_PREFIX.$table." as f"; + $sql .= " WHERE fk_soc = ".$this->id; if ($mode == 'supplier') { $sql .= " AND entity IN (".getEntity('facture_fourn').")"; } else { @@ -3899,7 +3905,7 @@ class Societe extends CommonObject } dol_syslog("getOutstandingBills", LOG_DEBUG); - $resql=$this->db->query($sql); + $resql = $this->db->query($sql); if ($resql) { $outstandingOpened = 0; @@ -3908,22 +3914,22 @@ class Societe extends CommonObject if ($mode == 'supplier') { require_once DOL_DOCUMENT_ROOT.'/fourn/class/fournisseur.facture.class.php'; - $tmpobject=new FactureFournisseur($this->db); + $tmpobject = new FactureFournisseur($this->db); } else { require_once DOL_DOCUMENT_ROOT.'/compta/facture/class/facture.class.php'; - $tmpobject=new Facture($this->db); + $tmpobject = new Facture($this->db); } - while($obj=$this->db->fetch_object($resql)) { - $tmpobject->id=$obj->rowid; + while ($obj = $this->db->fetch_object($resql)) { + $tmpobject->id = $obj->rowid; if ($obj->fk_statut != $tmpobject::STATUS_DRAFT // Not a draft - && ! ($obj->fk_statut == $tmpobject::STATUS_ABANDONED && $obj->close_code == 'replaced') // Not a replaced invoice + && !($obj->fk_statut == $tmpobject::STATUS_ABANDONED && $obj->close_code == 'replaced') // Not a replaced invoice ) { - $outstandingTotal+= $obj->total_ht; - $outstandingTotalIncTax+= $obj->total_ttc; + $outstandingTotal += $obj->total_ht; + $outstandingTotalIncTax += $obj->total_ttc; } if ($obj->paye == 0 && $obj->fk_statut != $tmpobject::STATUS_DRAFT // Not a draft @@ -3935,17 +3941,17 @@ class Societe extends CommonObject $creditnotes = $tmpobject->getSumCreditNotesUsed(); $deposits = $tmpobject->getSumDepositsUsed(); - $outstandingOpened+=$obj->total_ttc - $paiement - $creditnotes - $deposits; + $outstandingOpened += $obj->total_ttc - $paiement - $creditnotes - $deposits; } //if credit note is converted but not used // TODO Do this also for customer ? - if($mode == 'supplier' && $obj->type == FactureFournisseur::TYPE_CREDIT_NOTE && $tmpobject->isCreditNoteUsed()) + if ($mode == 'supplier' && $obj->type == FactureFournisseur::TYPE_CREDIT_NOTE && $tmpobject->isCreditNoteUsed()) { - $outstandingOpened-=$tmpobject->getSumFromThisCreditNotesNotUsed(); + $outstandingOpened -= $tmpobject->getSumFromThisCreditNotesNotUsed(); } } - return array('opened'=>$outstandingOpened, 'total_ht'=>$outstandingTotal, 'total_ttc'=>$outstandingTotalIncTax); // 'opened' is 'incl taxes' + return array('opened'=>$outstandingOpened, 'total_ht'=>$outstandingTotal, 'total_ttc'=>$outstandingTotalIncTax); // 'opened' is 'incl taxes' } else { @@ -3976,10 +3982,10 @@ class Societe extends CommonObject global $langs; $langs->load('companies'); - if ($status==0) return $langs->trans("NorProspectNorCustomer"); - elseif ($status==1) return $langs->trans("Customer"); - elseif ($status==2) return $langs->trans("Prospect"); - elseif ($status==3) return $langs->trans("ProspectCustomer"); + if ($status == 0) return $langs->trans("NorProspectNorCustomer"); + elseif ($status == 1) return $langs->trans("Customer"); + elseif ($status == 2) return $langs->trans("Prospect"); + elseif ($status == 3) return $langs->trans("ProspectCustomer"); } @@ -3996,24 +4002,24 @@ class Societe extends CommonObject */ public function generateDocument($modele, $outputlangs, $hidedetails = 0, $hidedesc = 0, $hideref = 0, $moreparams = null) { - global $conf,$user,$langs; + global $conf, $user, $langs; - if (! empty($moreparams) && ! empty($moreparams['use_companybankid'])) + if (!empty($moreparams) && !empty($moreparams['use_companybankid'])) { $modelpath = "core/modules/bank/doc/"; include_once DOL_DOCUMENT_ROOT.'/societe/class/companybankaccount.class.php'; $companybankaccount = new CompanyBankAccount($this->db); $result = $companybankaccount->fetch($moreparams['use_companybankid']); - if (! $result) dol_print_error($this->db, $companybankaccount->error, $companybankaccount->errors); - $result=$companybankaccount->commonGenerateDocument($modelpath, $modele, $outputlangs, $hidedetails, $hidedesc, $hideref, $moreparams); + if (!$result) dol_print_error($this->db, $companybankaccount->error, $companybankaccount->errors); + $result = $companybankaccount->commonGenerateDocument($modelpath, $modele, $outputlangs, $hidedetails, $hidedesc, $hideref, $moreparams); } else { // Positionne le modele sur le nom du modele a utiliser - if (! dol_strlen($modele)) + if (!dol_strlen($modele)) { - if (! empty($conf->global->COMPANY_ADDON_PDF)) + if (!empty($conf->global->COMPANY_ADDON_PDF)) { $modele = $conf->global->COMPANY_ADDON_PDF; } @@ -4026,7 +4032,7 @@ class Societe extends CommonObject $modelpath = "core/modules/societe/doc/"; - $result=$this->commonGenerateDocument($modelpath, $modele, $outputlangs, $hidedetails, $hidedesc, $hideref, $moreparams); + $result = $this->commonGenerateDocument($modelpath, $modele, $outputlangs, $hidedetails, $hidedesc, $hideref, $moreparams); } return $result; @@ -4046,11 +4052,11 @@ class Societe extends CommonObject */ public function setCategories($categories, $type_categ) { - require_once DOL_DOCUMENT_ROOT . '/categories/class/categorie.class.php'; + require_once DOL_DOCUMENT_ROOT.'/categories/class/categorie.class.php'; // Decode type - if (! in_array($type_categ, array(Categorie::TYPE_CUSTOMER, Categorie::TYPE_SUPPLIER))) { - dol_syslog(__METHOD__ . ': Type ' . $type_categ . 'is an unknown company category type. Done nothing.', LOG_ERR); + if (!in_array($type_categ, array(Categorie::TYPE_CUSTOMER, Categorie::TYPE_SUPPLIER))) { + dol_syslog(__METHOD__.': Type '.$type_categ.'is an unknown company category type. Done nothing.', LOG_ERR); return -1; } @@ -4170,10 +4176,9 @@ class Societe extends CommonObject $sql .= ' FROM '.MAIN_DB_PREFIX.'societe_commerciaux '; $sql .= ' WHERE fk_soc = '.(int) $origin_id.') '; - $query = $db->query($sql); - - while ($result = $db->fetch_object($query)) { - $db->query('DELETE FROM '.MAIN_DB_PREFIX.'societe_commerciaux WHERE rowid = '.$result->rowid); + $resql = $db->query($sql); + while ($obj = $db->fetch_object($resql)) { + $db->query('DELETE FROM '.MAIN_DB_PREFIX.'societe_commerciaux WHERE rowid = '.$obj->rowid); } /** diff --git a/htdocs/societe/class/societeaccount.class.php b/htdocs/societe/class/societeaccount.class.php index f93dfd0ea68..abfe4cad716 100644 --- a/htdocs/societe/class/societeaccount.class.php +++ b/htdocs/societe/class/societeaccount.class.php @@ -121,7 +121,13 @@ class SocieteAccount extends CommonObject public $fk_soc; public $site; + + /** + * @var integer|string date_last_login + */ public $date_last_login; + + public $date_previous_login; public $note_private; diff --git a/htdocs/societe/consumption.php b/htdocs/societe/consumption.php index 0039504e950..b55c6a3242e 100644 --- a/htdocs/societe/consumption.php +++ b/htdocs/societe/consumption.php @@ -364,7 +364,7 @@ if ($sql_select) print_barre_liste($langs->trans('ProductsIntoElements').' '.$typeElementString.' '.$button, $page, $_SERVER["PHP_SELF"], $param, $sortfield, $sortorder, '', $num, $totalnboflines, '', 0, '', '', $limit); print '
    '; - print ''."\n"; + print '
    '."\n"; // Filters print ''; @@ -612,7 +612,7 @@ elseif (empty($type_element) || $type_element == -1) { print_barre_liste($langs->trans('ProductsIntoElements').' '.$typeElementString.' '.$button, $page, $_SERVER["PHP_SELF"], $param, $sortfield, $sortorder, '', $num, '', ''); - print '
    '."\n"; + print '
    '."\n"; // Titles with sort buttons print ''; print_liste_field_titre('Ref', $_SERVER['PHP_SELF'], 'doc_number', '', $param, '', $sortfield, $sortorder, 'left '); @@ -629,7 +629,7 @@ elseif (empty($type_element) || $type_element == -1) else { print_barre_liste($langs->trans('ProductsIntoElements').' '.$typeElementString.' '.$button, $page, $_SERVER["PHP_SELF"], $param, $sortfield, $sortorder, '', $num, '', ''); - print '
    '."\n"; + print '
    '."\n"; print ''; diff --git a/htdocs/societe/contact.php b/htdocs/societe/contact.php index 352c9c53c35..d761d8a1f71 100644 --- a/htdocs/societe/contact.php +++ b/htdocs/societe/contact.php @@ -66,9 +66,9 @@ $extrafields = new ExtraFields($db); $extrafields->fetch_name_optionals_label($object->table_element); // Initialize technical object to manage hooks of page. Note that conf->hooks_modules contains array of hook context -$hookmanager->initHooks(array('thirdpartycontact','globalcard')); +$hookmanager->initHooks(array('thirdpartycontact', 'globalcard')); -if ($action == 'view' && $object->fetch($socid)<=0) +if ($action == 'view' && $object->fetch($socid) <= 0) { $langs->load("errors"); print($langs->trans('ErrorRecordNotFound')); @@ -77,9 +77,9 @@ if ($action == 'view' && $object->fetch($socid)<=0) // Get object canvas (By default, this is not defined, so standard usage of dolibarr) $object->getCanvas($socid); -$canvas = $object->canvas?$object->canvas:GETPOST("canvas"); -$objcanvas=null; -if (! empty($canvas)) +$canvas = $object->canvas ? $object->canvas : GETPOST("canvas"); +$objcanvas = null; +if (!empty($canvas)) { require_once DOL_DOCUMENT_ROOT.'/core/class/canvas.class.php'; $objcanvas = new Canvas($db, $action); @@ -96,16 +96,16 @@ $result = restrictedArea($user, 'societe', $socid, '&societe', '', 'fk_soc', 'ro * Actions */ -$parameters=array('id'=>$socid, 'objcanvas'=>$objcanvas); -$reshook=$hookmanager->executeHooks('doActions', $parameters, $object, $action); // Note that $action and $object may have been modified by some hooks +$parameters = array('id'=>$socid, '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 (empty($reshook)) { if ($cancel) { - $action=''; - if (! empty($backtopage)) + $action = ''; + if (!empty($backtopage)) { header("Location: ".$backtopage); exit; @@ -128,19 +128,19 @@ $formcompany = new FormCompany($db); if ($socid > 0 && empty($object->id)) { - $result=$object->fetch($socid); + $result = $object->fetch($socid); if ($result <= 0) dol_print_error('', $object->error); } -$title=$langs->trans("ThirdParty"); -if (! empty($conf->global->MAIN_HTML_TITLE) && preg_match('/thirdpartynameonly/', $conf->global->MAIN_HTML_TITLE) && $object->name) $title=$object->name." - ".$langs->trans('Card'); -$help_url='EN:Module_Third_Parties|FR:Module_Tiers|ES:Empresas'; +$title = $langs->trans("ThirdParty"); +if (!empty($conf->global->MAIN_HTML_TITLE) && preg_match('/thirdpartynameonly/', $conf->global->MAIN_HTML_TITLE) && $object->name) $title = $object->name." - ".$langs->trans('Card'); +$help_url = 'EN:Module_Third_Parties|FR:Module_Tiers|ES:Empresas'; llxHeader('', $title, $help_url); -$countrynotdefined=$langs->trans("ErrorSetACountryFirst").' ('.$langs->trans("SeeAbove").')'; +$countrynotdefined = $langs->trans("ErrorSetACountryFirst").' ('.$langs->trans("SeeAbove").')'; -if (!empty($object->id)) $res=$object->fetch_optionals($object->id, null); +if (!empty($object->id)) $res = $object->fetch_optionals($object->id, null); //if ($res < 0) { dol_print_error($db); exit; } @@ -161,7 +161,7 @@ if ($action != 'presend') // Contacts list if (empty($conf->global->SOCIETE_DISABLE_CONTACTS)) { - $result=show_contacts($conf, $langs, $db, $object, $_SERVER["PHP_SELF"].'?socid='.$object->id); + $result = show_contacts($conf, $langs, $db, $object, $_SERVER["PHP_SELF"].'?socid='.$object->id); } } diff --git a/htdocs/societe/document.php b/htdocs/societe/document.php index 8e0c36aa451..f907bd210f6 100644 --- a/htdocs/societe/document.php +++ b/htdocs/societe/document.php @@ -34,9 +34,9 @@ require_once DOL_DOCUMENT_ROOT.'/core/class/html.formfile.class.php'; $langs->loadLangs(array("companies", "other")); -$action=GETPOST('action', 'aZ09'); -$confirm=GETPOST('confirm'); -$id=(GETPOST('socid', 'int') ? GETPOST('socid', 'int') : GETPOST('id', 'int')); +$action = GETPOST('action', 'aZ09'); +$confirm = GETPOST('confirm'); +$id = (GETPOST('socid', 'int') ? GETPOST('socid', 'int') : GETPOST('id', 'int')); $ref = GETPOST('ref', 'alpha'); // Security check @@ -80,7 +80,7 @@ $hookmanager->initHooks(array('thirdpartydocument','globalcard')); * Actions */ -include_once DOL_DOCUMENT_ROOT . '/core/actions_linkedfiles.inc.php'; +include_once DOL_DOCUMENT_ROOT.'/core/actions_linkedfiles.inc.php'; /* @@ -89,9 +89,9 @@ include_once DOL_DOCUMENT_ROOT . '/core/actions_linkedfiles.inc.php'; $form = new Form($db); -$title=$langs->trans("ThirdParty").' - '.$langs->trans("Files"); -if (! empty($conf->global->MAIN_HTML_TITLE) && preg_match('/thirdpartynameonly/', $conf->global->MAIN_HTML_TITLE) && $object->name) $title=$object->name.' - '.$langs->trans("Files"); -$help_url='EN:Module_Third_Parties|FR:Module_Tiers|ES:Empresas'; +$title = $langs->trans("ThirdParty").' - '.$langs->trans("Files"); +if (!empty($conf->global->MAIN_HTML_TITLE) && preg_match('/thirdpartynameonly/', $conf->global->MAIN_HTML_TITLE) && $object->name) $title = $object->name.' - '.$langs->trans("Files"); +$help_url = 'EN:Module_Third_Parties|FR:Module_Tiers|ES:Empresas'; llxHeader('', $title, $help_url); if ($object->id) @@ -125,7 +125,7 @@ if ($object->id) print '
    '.$langs->trans("FeatureNotYetAvailable").'
    '; // Prefix - if (! empty($conf->global->SOCIETE_USEPREFIX)) // Old not used prefix field + if (!empty($conf->global->SOCIETE_USEPREFIX)) // Old not used prefix field { print ''; } @@ -163,8 +163,8 @@ if ($object->id) $modulepart = 'societe'; $permission = $user->rights->societe->creer; $permtoedit = $user->rights->societe->creer; - $param = '&id=' . $object->id; - include_once DOL_DOCUMENT_ROOT . '/core/tpl/document_actions_post_headers.tpl.php'; + $param = '&id='.$object->id; + include_once DOL_DOCUMENT_ROOT.'/core/tpl/document_actions_post_headers.tpl.php'; } else { diff --git a/htdocs/societe/index.php b/htdocs/societe/index.php index 5aadc5d3606..a56762ce447 100644 --- a/htdocs/societe/index.php +++ b/htdocs/societe/index.php @@ -99,7 +99,7 @@ if ($result) else dol_print_error($db); print '
    '; -print '
    '.$langs->trans('Prefix').''.$object->prefix_comm.'
    '."\n"; +print '
    '."\n"; print ''; if (!empty($conf->use_javascript_ajax) && ((round($third['prospect']) ? 1 : 0) + (round($third['customer']) ? 1 : 0) + (round($third['supplier']) ? 1 : 0) + (round($third['other']) ? 1 : 0) >= 2)) { @@ -157,7 +157,7 @@ if (!empty($conf->categorie->enabled) && !empty($conf->global->CATEGORY_GRAPHSTA print '
    '; print '
    '; - print '
    '.$langs->trans("Statistics").'
    '; + print '
    '; print ''; print '
    '.$langs->trans("Categories").'
    '; $sql = "SELECT c.label, count(*) as nb"; @@ -263,7 +263,7 @@ if ($result) print "\n\n"; print '
    '; - print ''; + print '
    '; print ''; print ''; diff --git a/htdocs/societe/list.php b/htdocs/societe/list.php index 260c165064e..504ccb37a25 100644 --- a/htdocs/societe/list.php +++ b/htdocs/societe/list.php @@ -1,6 +1,6 @@ - * Copyright (C) 2004-2016 Laurent Destailleur + * Copyright (C) 2004-2019 Laurent Destailleur * Copyright (C) 2005-2019 Regis Houssin * Copyright (C) 2012 Marcos García * Copyright (C) 2013-2015 Raphaël Doursenaud @@ -41,12 +41,12 @@ require_once DOL_DOCUMENT_ROOT.'/societe/class/client.class.php'; $langs->loadLangs(array("companies", "commercial", "customers", "suppliers", "bills", "compta", "categories", "cashdesk")); -$action=GETPOST('action', 'alpha'); -$massaction=GETPOST('massaction', 'alpha'); -$show_files=GETPOST('show_files', 'int'); -$confirm=GETPOST('confirm', 'alpha'); +$action = GETPOST('action', 'alpha'); +$massaction = GETPOST('massaction', 'alpha'); +$show_files = GETPOST('show_files', 'int'); +$confirm = GETPOST('confirm', 'alpha'); $toselect = GETPOST('toselect', 'array'); -$contextpage=GETPOST('contextpage', 'aZ')?GETPOST('contextpage', 'aZ'):'thirdpartylist'; +$contextpage = GETPOST('contextpage', 'aZ') ?GETPOST('contextpage', 'aZ') : 'thirdpartylist'; if ($contextpage == 'poslist') { @@ -55,71 +55,71 @@ if ($contextpage == 'poslist') // Security check $socid = GETPOST('socid', 'int'); -if ($user->socid) $socid=$user->socid; +if ($user->socid) $socid = $user->socid; $result = restrictedArea($user, 'societe', $socid, ''); -$search_all=trim(GETPOST('search_all', 'alphanohtml')?GETPOST('search_all', 'alphanohtml'):GETPOST('sall', 'alphanohtml')); -$search_cti=preg_replace('/^0+/', '', preg_replace('/[^0-9]/', '', GETPOST('search_cti', 'alphanohtml'))); // Phone number without any special chars +$search_all = trim(GETPOST('search_all', 'alphanohtml') ?GETPOST('search_all', 'alphanohtml') : GETPOST('sall', 'alphanohtml')); +$search_cti = preg_replace('/^0+/', '', preg_replace('/[^0-9]/', '', GETPOST('search_cti', 'alphanohtml'))); // Phone number without any special chars -$search_id=trim(GETPOST("search_id", "int")); -$search_nom=trim(GETPOST("search_nom", 'none')); -$search_alias=trim(GETPOST("search_alias", 'none')); -$search_nom_only=trim(GETPOST("search_nom_only", 'none')); -$search_barcode=trim(GETPOST("search_barcode", 'alpha')); -$search_customer_code=trim(GETPOST('search_customer_code', 'alpha')); -$search_supplier_code=trim(GETPOST('search_supplier_code', 'alpha')); -$search_account_customer_code=trim(GETPOST('search_account_customer_code', 'alpha')); -$search_account_supplier_code=trim(GETPOST('search_account_supplier_code', 'alpha')); -$search_town=trim(GETPOST("search_town", 'alpha')); -$search_zip=trim(GETPOST("search_zip", 'alpha')); -$search_state=trim(GETPOST("search_state", 'alpha')); -$search_region=trim(GETPOST("search_region", 'alpha')); -$search_email=trim(GETPOST('search_email', 'alpha')); -$search_phone=trim(GETPOST('search_phone', 'alpha')); -$search_fax=trim(GETPOST('search_fax', 'alpha')); -$search_url=trim(GETPOST('search_url', 'alpha')); -$search_idprof1=trim(GETPOST('search_idprof1', 'alpha')); -$search_idprof2=trim(GETPOST('search_idprof2', 'alpha')); -$search_idprof3=trim(GETPOST('search_idprof3', 'alpha')); -$search_idprof4=trim(GETPOST('search_idprof4', 'alpha')); -$search_idprof5=trim(GETPOST('search_idprof5', 'alpha')); -$search_idprof6=trim(GETPOST('search_idprof6', 'alpha')); -$search_vat=trim(GETPOST('search_vat', 'alpha')); -$search_sale=trim(GETPOST("search_sale", 'int')); -$search_categ_cus=trim(GETPOST("search_categ_cus", 'int')); -$search_categ_sup=trim(GETPOST("search_categ_sup", 'int')); -$search_country=GETPOST("search_country", 'intcomma'); -$search_type_thirdparty=GETPOST("search_type_thirdparty", 'int'); -$search_staff=GETPOST("search_staff", 'int'); -$search_status=GETPOST("search_status", 'int'); -$search_type=GETPOST('search_type', 'alpha'); -$search_level = GETPOST("search_level", "array"); -$search_stcomm=GETPOST('search_stcomm', 'int'); +$search_id = trim(GETPOST("search_id", "int")); +$search_nom = trim(GETPOST("search_nom", 'none')); +$search_alias = trim(GETPOST("search_alias", 'none')); +$search_nom_only = trim(GETPOST("search_nom_only", 'none')); +$search_barcode = trim(GETPOST("search_barcode", 'alpha')); +$search_customer_code = trim(GETPOST('search_customer_code', 'alpha')); +$search_supplier_code = trim(GETPOST('search_supplier_code', 'alpha')); +$search_account_customer_code = trim(GETPOST('search_account_customer_code', 'alpha')); +$search_account_supplier_code = trim(GETPOST('search_account_supplier_code', 'alpha')); +$search_town = trim(GETPOST("search_town", 'alpha')); +$search_zip = trim(GETPOST("search_zip", 'alpha')); +$search_state = trim(GETPOST("search_state", 'alpha')); +$search_region = trim(GETPOST("search_region", 'alpha')); +$search_email = trim(GETPOST('search_email', 'alpha')); +$search_phone = trim(GETPOST('search_phone', 'alpha')); +$search_fax = trim(GETPOST('search_fax', 'alpha')); +$search_url = trim(GETPOST('search_url', 'alpha')); +$search_idprof1 = trim(GETPOST('search_idprof1', 'alpha')); +$search_idprof2 = trim(GETPOST('search_idprof2', 'alpha')); +$search_idprof3 = trim(GETPOST('search_idprof3', 'alpha')); +$search_idprof4 = trim(GETPOST('search_idprof4', 'alpha')); +$search_idprof5 = trim(GETPOST('search_idprof5', 'alpha')); +$search_idprof6 = trim(GETPOST('search_idprof6', 'alpha')); +$search_vat = trim(GETPOST('search_vat', 'alpha')); +$search_sale = trim(GETPOST("search_sale", 'int')); +$search_categ_cus = trim(GETPOST("search_categ_cus", 'int')); +$search_categ_sup = trim(GETPOST("search_categ_sup", 'int')); +$search_country = GETPOST("search_country", 'intcomma'); +$search_type_thirdparty = GETPOST("search_type_thirdparty", 'int'); +$search_staff = GETPOST("search_staff", 'int'); +$search_status = GETPOST("search_status", 'int'); +$search_type = GETPOST('search_type', 'alpha'); +$search_level = GETPOST("search_level", "array"); +$search_stcomm = GETPOST('search_stcomm', 'int'); $search_import_key = GETPOST("search_import_key", "alpha"); -$search_btn=GETPOST('button_search', 'alpha'); -$search_remove_btn=GETPOST('button_removefilter', 'alpha'); +$search_btn = GETPOST('button_search', 'alpha'); +$search_remove_btn = GETPOST('button_removefilter', 'alpha'); $search_parent_name = GETPOST('search_parent_name', 'alpha'); -$type=GETPOST('type', 'alpha'); -$optioncss=GETPOST('optioncss', 'alpha'); -$mode=GETPOST("mode", 'alpha'); +$type = GETPOST('type', 'alpha'); +$optioncss = GETPOST('optioncss', 'alpha'); +$mode = GETPOST("mode", 'alpha'); -$diroutputmassaction=$conf->societe->dir_output . '/temp/massgeneration/'.$user->id; +$diroutputmassaction = $conf->societe->dir_output.'/temp/massgeneration/'.$user->id; -$limit = GETPOST('limit', 'int')?GETPOST('limit', 'int'):$conf->liste_limit; -$sortfield=GETPOST("sortfield", 'alpha'); -$sortorder=GETPOST("sortorder", 'alpha'); -$page=GETPOST("page", 'int'); -if (! $sortorder) $sortorder="ASC"; -if (! $sortfield) $sortfield="s.nom"; +$limit = GETPOST('limit', 'int') ?GETPOST('limit', 'int') : $conf->liste_limit; +$sortfield = GETPOST("sortfield", 'alpha'); +$sortorder = GETPOST("sortorder", 'alpha'); +$page = GETPOST("page", 'int'); +if (!$sortorder) $sortorder = "ASC"; +if (!$sortfield) $sortfield = "s.nom"; if (empty($page) || $page == -1 || !empty($search_btn) || !empty($search_remove_btn) || (empty($toselect) && $massaction === '0')) { $page = 0; } $offset = $limit * $page; $pageprev = $page - 1; $pagenext = $page + 1; -if ($type == 'c') { if (empty($contextpage) || $contextpage == 'thirdpartylist') $contextpage='customerlist'; if ($search_type=='') $search_type='1,3'; } -if ($type == 'p') { if (empty($contextpage) || $contextpage == 'thirdpartylist') $contextpage='prospectlist'; if ($search_type=='') $search_type='2,3'; } -if ($type == 'f') { if (empty($contextpage) || $contextpage == 'thirdpartylist') $contextpage='supplierlist'; if ($search_type=='') $search_type='4'; } +if ($type == 'c') { if (empty($contextpage) || $contextpage == 'thirdpartylist') $contextpage = 'customerlist'; if ($search_type == '') $search_type = '1,3'; } +if ($type == 'p') { if (empty($contextpage) || $contextpage == 'thirdpartylist') $contextpage = 'prospectlist'; if ($search_type == '') $search_type = '2,3'; } +if ($type == 'f') { if (empty($contextpage) || $contextpage == 'thirdpartylist') $contextpage = 'supplierlist'; if ($search_type == '') $search_type = '4'; } // Initialize technical object to manage hooks of page. Note that conf->hooks_modules contains array of hook context $object = new Societe($db); @@ -129,7 +129,7 @@ $extrafields = new ExtraFields($db); // fetch optionals attributes and labels $extrafields->fetch_name_optionals_label($object->table_element); -$search_array_options=$extrafields->getOptionalsFromPost($object->table_element, '', 'search_'); +$search_array_options = $extrafields->getOptionalsFromPost($object->table_element, '', 'search_'); // List of fields to search into when doing a "search in all" $fieldstosearchall = array( @@ -148,40 +148,40 @@ $fieldstosearchall = array( 's.phone'=>"Phone", 's.fax'=>"Fax", ); -if (($tmp = $langs->transnoentities("ProfId4".$mysoc->country_code)) && $tmp != "ProfId4".$mysoc->country_code && $tmp != '-') $fieldstosearchall['s.idprof4']='ProfId4'; -if (($tmp = $langs->transnoentities("ProfId5".$mysoc->country_code)) && $tmp != "ProfId5".$mysoc->country_code && $tmp != '-') $fieldstosearchall['s.idprof5']='ProfId5'; -if (($tmp = $langs->transnoentities("ProfId6".$mysoc->country_code)) && $tmp != "ProfId6".$mysoc->country_code && $tmp != '-') $fieldstosearchall['s.idprof6']='ProfId6'; -if (!empty($conf->barcode->enabled)) $fieldstosearchall['s.barcode']='Gencod'; +if (($tmp = $langs->transnoentities("ProfId4".$mysoc->country_code)) && $tmp != "ProfId4".$mysoc->country_code && $tmp != '-') $fieldstosearchall['s.idprof4'] = 'ProfId4'; +if (($tmp = $langs->transnoentities("ProfId5".$mysoc->country_code)) && $tmp != "ProfId5".$mysoc->country_code && $tmp != '-') $fieldstosearchall['s.idprof5'] = 'ProfId5'; +if (($tmp = $langs->transnoentities("ProfId6".$mysoc->country_code)) && $tmp != "ProfId6".$mysoc->country_code && $tmp != '-') $fieldstosearchall['s.idprof6'] = 'ProfId6'; +if (!empty($conf->barcode->enabled)) $fieldstosearchall['s.barcode'] = 'Gencod'; // Personalized search criterias. Example: $conf->global->THIRDPARTY_QUICKSEARCH_ON_FIELDS = 's.nom=ThirdPartyName;s.name_alias=AliasNameShort;s.code_client=CustomerCode' -if (! empty($conf->global->THIRDPARTY_QUICKSEARCH_ON_FIELDS)) $fieldstosearchall=dolExplodeIntoArray($conf->global->THIRDPARTY_QUICKSEARCH_ON_FIELDS); +if (!empty($conf->global->THIRDPARTY_QUICKSEARCH_ON_FIELDS)) $fieldstosearchall = dolExplodeIntoArray($conf->global->THIRDPARTY_QUICKSEARCH_ON_FIELDS); // Define list of fields to show into list -$checkedcustomercode=(in_array($contextpage, array('thirdpartylist', 'customerlist', 'prospectlist', 'poslist')) ? 1 : 0); -$checkedsuppliercode=(in_array($contextpage, array('supplierlist')) ? 1 : 0); -$checkedcustomeraccountcode=(in_array($contextpage, array('customerlist')) ? 1 : 0); -$checkedsupplieraccountcode=(in_array($contextpage, array('supplierlist')) ? 1 : 0); -$checkedtypetiers=1; -$checkedprofid1=0; -$checkedprofid2=0; -$checkedprofid3=0; -$checkedprofid4=0; -$checkedprofid5=0; -$checkedprofid6=0; +$checkedcustomercode = (in_array($contextpage, array('thirdpartylist', 'customerlist', 'prospectlist', 'poslist')) ? 1 : 0); +$checkedsuppliercode = (in_array($contextpage, array('supplierlist')) ? 1 : 0); +$checkedcustomeraccountcode = (in_array($contextpage, array('customerlist')) ? 1 : 0); +$checkedsupplieraccountcode = (in_array($contextpage, array('supplierlist')) ? 1 : 0); +$checkedtypetiers = 1; +$checkedprofid1 = 0; +$checkedprofid2 = 0; +$checkedprofid3 = 0; +$checkedprofid4 = 0; +$checkedprofid5 = 0; +$checkedprofid6 = 0; //$checkedprofid4=((($tmp = $langs->transnoentities("ProfId4".$mysoc->country_code)) && $tmp != "ProfId4".$mysoc->country_code && $tmp != '-') ? 1 : 0); //$checkedprofid5=((($tmp = $langs->transnoentities("ProfId5".$mysoc->country_code)) && $tmp != "ProfId5".$mysoc->country_code && $tmp != '-') ? 1 : 0); //$checkedprofid6=((($tmp = $langs->transnoentities("ProfId6".$mysoc->country_code)) && $tmp != "ProfId6".$mysoc->country_code && $tmp != '-') ? 1 : 0); -$checkprospectlevel=(in_array($contextpage, array('prospectlist')) ? 1 : 0); -$checkstcomm=(in_array($contextpage, array('prospectlist')) ? 1 : 0); -$arrayfields=array( - 's.rowid'=>array('label'=>"TechnicalID", 'checked'=>($conf->global->MAIN_SHOW_TECHNICAL_ID?1:0), 'enabled'=>($conf->global->MAIN_SHOW_TECHNICAL_ID?1:0)), +$checkprospectlevel = (in_array($contextpage, array('prospectlist')) ? 1 : 0); +$checkstcomm = (in_array($contextpage, array('prospectlist')) ? 1 : 0); +$arrayfields = array( + 's.rowid'=>array('label'=>"TechnicalID", 'checked'=>($conf->global->MAIN_SHOW_TECHNICAL_ID ? 1 : 0), 'enabled'=>($conf->global->MAIN_SHOW_TECHNICAL_ID ? 1 : 0)), 's.nom'=>array('label'=>"ThirdPartyName", 'checked'=>1), 's.name_alias'=>array('label'=>"AliasNameShort", 'checked'=>1), - 's.barcode'=>array('label'=>"Gencod", 'checked'=>1, 'enabled'=>(! empty($conf->barcode->enabled))), + 's.barcode'=>array('label'=>"Gencod", 'checked'=>1, 'enabled'=>(!empty($conf->barcode->enabled))), 's.code_client'=>array('label'=>"CustomerCodeShort", 'checked'=>$checkedcustomercode), - 's.code_fournisseur'=>array('label'=>"SupplierCodeShort", 'checked'=>$checkedsuppliercode, 'enabled'=>(! empty($conf->fournisseur->enabled))), + 's.code_fournisseur'=>array('label'=>"SupplierCodeShort", 'checked'=>$checkedsuppliercode, 'enabled'=>(!empty($conf->fournisseur->enabled))), 's.code_compta'=>array('label'=>"CustomerAccountancyCodeShort", 'checked'=>$checkedcustomeraccountcode), - 's.code_compta_fournisseur'=>array('label'=>"SupplierAccountancyCodeShort", 'checked'=>$checkedsupplieraccountcode, 'enabled'=>(! empty($conf->fournisseur->enabled))), + 's.code_compta_fournisseur'=>array('label'=>"SupplierAccountancyCodeShort", 'checked'=>$checkedsupplieraccountcode, 'enabled'=>(!empty($conf->fournisseur->enabled))), 's.town'=>array('label'=>"Town", 'checked'=>1), 's.zip'=>array('label'=>"Zip", 'checked'=>1), 'state.nom'=>array('label'=>"State", 'checked'=>0), @@ -212,10 +212,10 @@ $arrayfields=array( // 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) + 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], 'checked'=>(($extrafields->attributes[$object->table_element]['list'][$key]<0)?0:1), 'position'=>$extrafields->attributes[$object->table_element]['pos'][$key], 'enabled'=>(abs($extrafields->attributes[$object->table_element]['list'][$key])!=3 && $extrafields->attributes[$object->table_element]['perms'][$key])); + if (!empty($extrafields->attributes[$object->table_element]['list'][$key])) + $arrayfields["ef.".$key] = array('label'=>$extrafields->attributes[$object->table_element]['label'][$key], 'checked'=>(($extrafields->attributes[$object->table_element]['list'][$key] < 0) ? 0 : 1), 'position'=>$extrafields->attributes[$object->table_element]['pos'][$key], 'enabled'=>(abs($extrafields->attributes[$object->table_element]['list'][$key]) != 3 && $extrafields->attributes[$object->table_element]['perms'][$key])); } } $object->fields = dol_sort_array($object->fields, 'position'); @@ -226,19 +226,36 @@ $arrayfields = dol_sort_array($arrayfields, 'position'); * Actions */ -if ($action=="change") // Change customer for TakePOS +if ($action == "change") // Change customer for TakePOS { $idcustomer = GETPOST('idcustomer', 'int'); - $place = (GETPOST('place', 'int') > 0 ? GETPOST('place', 'int') : 0); // $place is id of table for Ba or Restaurant + $place = (GETPOST('place', 'int') > 0 ? GETPOST('place', 'int') : 0); // $place is id of table for Ba or Restaurant - // @TODO Check if draft invoice already exists, if not create it or return a warning to ask to enter at least one line to have it created automatically - $sql="UPDATE ".MAIN_DB_PREFIX."facture set fk_soc=".$idcustomer." where ref='(PROV-POS".$_SESSION["takeposterminal"]."-".$place.")'"; + // Check if draft invoice already exists, if not create it + $sql = "SELECT rowid FROM ".MAIN_DB_PREFIX."facture where ref='(PROV-POS".$_SESSION["takeposterminal"]."-".$place.")' AND entity IN (".getEntity('invoice').")"; + $result = $db->query($sql); + $num_lines = $db->num_rows($result); + if ($num_lines==0) + { + require_once DOL_DOCUMENT_ROOT . '/compta/facture/class/facture.class.php'; + $invoice = new Facture($db); + $constforthirdpartyid = 'CASHDESK_ID_THIRDPARTY'.$_SESSION["takeposterminal"]; + $invoice->socid = $conf->global->$constforthirdpartyid; + $invoice->date = dol_now(); + $invoice->module_source = 'takepos'; + $invoice->pos_source = $_SESSION["takeposterminal"]; + $placeid =$invoice->create($user); + $sql="UPDATE ".MAIN_DB_PREFIX."facture set ref='(PROV-POS".$_SESSION["takeposterminal"]."-".$place.")' where rowid=".$placeid; + $db->query($sql); + } + + $sql = "UPDATE ".MAIN_DB_PREFIX."facture set fk_soc=".$idcustomer." where ref='(PROV-POS".$_SESSION["takeposterminal"]."-".$place.")'"; $resql = $db->query($sql); ?> '; -} + if ($conf->global->TAKEPOS_AUTO_PRINT_TICKETS) $sectionwithinvoicelink .= ''; +} /* * View @@ -465,9 +469,9 @@ $form = new Form($db); '."\n"; + print ''."\n"; } @@ -579,7 +589,7 @@ print ''; } -if ($_SESSION["basiclayout"]!=1) +if ($_SESSION["basiclayout"] != 1) { - print ''; - print ''; - print ''; + print ''; + print ''; + print ''; } print "\n"; -if ($_SESSION["basiclayout"]==1) +if ($_SESSION["basiclayout"] == 1) { - if ($mobilepage=="cats") + if ($mobilepage == "cats") { require_once DOL_DOCUMENT_ROOT.'/categories/class/categorie.class.php'; $categorie = new Categorie($db); $categories = $categorie->get_full_arbo('product'); $htmlforlines = ''; - foreach ($categories as $row){ - $htmlforlines.= ''; - $htmlforlines.= ''; - $htmlforlines.= ''."\n"; + foreach ($categories as $row) { + $htmlforlines .= ''; + $htmlforlines .= ''; + $htmlforlines .= ''."\n"; } - $htmlforlines.= '
    '.$transRecordedType.' '; print ''; if ($conf->global->TAKEPOS_BAR_RESTAURANT) { - $sql="SELECT floor, label FROM ".MAIN_DB_PREFIX."takepos_floor_tables where rowid=".((int) $place); + $sql = "SELECT floor, label FROM ".MAIN_DB_PREFIX."takepos_floor_tables where rowid=".((int) $place); $resql = $db->query($sql); $obj = $db->fetch_object($resql); if ($obj) @@ -588,83 +598,83 @@ if ($conf->global->TAKEPOS_BAR_RESTAURANT) $floor = $obj->floor; } // In phone version only show when is invoice page - if ($mobilepage=="invoice" || $mobilepage=="") { - print $langs->trans('Place') . " " . $label . " - "; - print $langs->trans('Floor') . " " . $floor . " - "; + if ($mobilepage == "invoice" || $mobilepage == "") { + print $langs->trans('Place')." ".$label." - "; + print $langs->trans('Floor')." ".$floor." - "; } } // In phone version only show when is invoice page -if ($mobilepage=="invoice" || $mobilepage=="") { +if ($mobilepage == "invoice" || $mobilepage == "") { print $langs->trans('TotalTTC'); - print ' : ' . price($invoice->total_ttc, 1, '', 1, -1, -1, $conf->currency) . ''; - print '
    ' . $sectionwithinvoicelink; + print ' : '.price($invoice->total_ttc, 1, '', 1, -1, -1, $conf->currency).''; + print '
    '.$sectionwithinvoicelink; print '
    ' . $langs->trans('ReductionShort') . '' . $langs->trans('Qty') . '' . $langs->trans('TotalTTCShort') . ''.$langs->trans('ReductionShort').''.$langs->trans('Qty').''.$langs->trans('TotalTTCShort').'
    '; - $htmlforlines.= $row['label']; - $htmlforlines.= '
    '; + $htmlforlines .= $row['label']; + $htmlforlines .= '
    '; - $htmlforlines.= '
    '; + $htmlforlines .= '
    '; + $htmlforlines .= '
    '; print $htmlforlines; } - if ($mobilepage=="products") + if ($mobilepage == "products") { require_once DOL_DOCUMENT_ROOT.'/categories/class/categorie.class.php'; $object = new Categorie($db); $catid = GETPOST('catid', 'int'); - $result=$object->fetch($catid); + $result = $object->fetch($catid); $prods = $object->getObjectsInCateg("product"); $htmlforlines = ''; foreach ($prods as $row) { - $htmlforlines.= '
    '; - $htmlforlines.= $row->label; - $htmlforlines.= '
    '; + $htmlforlines .= $row->label; + $htmlforlines .= '
    '; + $htmlforlines .= '
    '; print $htmlforlines; } - if ($mobilepage=="places") + if ($mobilepage == "places") { - $sql="SELECT rowid, entity, label, leftpos, toppos, floor FROM ".MAIN_DB_PREFIX."takepos_floor_tables"; + $sql = "SELECT rowid, entity, label, leftpos, toppos, floor FROM ".MAIN_DB_PREFIX."takepos_floor_tables"; $resql = $db->query($sql); $rows = array(); $htmlforlines = ''; - while($row = $db->fetch_array($resql)){ + while ($row = $db->fetch_array($resql)) { $rows[] = $row; - $htmlforlines.= '
    '; - $htmlforlines.= $row['label']; - $htmlforlines.= '
    '; + $htmlforlines .= $row['label']; + $htmlforlines .= '
    '; + $htmlforlines .= '
    '; print $htmlforlines; } } @@ -672,50 +682,50 @@ if ($_SESSION["basiclayout"]==1) if ($placeid > 0) { //In Phone basic layout hide some content depends situation - if ($_SESSION["basiclayout"]==1 && $mobilepage!="invoice" && $action!="order") return; + if ($_SESSION["basiclayout"] == 1 && $mobilepage != "invoice" && $action != "order") return; if (is_array($invoice->lines) && count($invoice->lines)) { $tmplines = array_reverse($invoice->lines); - foreach($tmplines as $line) + foreach ($tmplines as $line) { $htmlforlines = ''; - $htmlforlines.= '
    '; + $htmlforlines .= '" id="'.$line->id.'">'; + $htmlforlines .= ''; //if ($line->product_label) $htmlforlines.= ''.$line->product_label.''; if (isset($line->product_type)) { - if (empty($line->product_type)) $htmlforlines.=img_object('', 'product').' '; - else $htmlforlines.=img_object('', 'service').' '; + if (empty($line->product_type)) $htmlforlines .= img_object('', 'product').' '; + else $htmlforlines .= img_object('', 'service').' '; } - if ($line->product_label) $htmlforlines.= $line->product_label; - if ($line->product_label && $line->desc) $htmlforlines.= '
    '; + if ($line->product_label) $htmlforlines .= $line->product_label; + if ($line->product_label && $line->desc) $htmlforlines .= '
    '; if ($line->product_label != $line->desc) { $firstline = dolGetFirstLineOfText($line->desc); if ($firstline != $line->desc) { - $htmlforlines.= $form->textwithpicto(dolGetFirstLineOfText($line->desc), $line->desc); + $htmlforlines .= $form->textwithpicto(dolGetFirstLineOfText($line->desc), $line->desc); } else { - $htmlforlines.= $line->desc; + $htmlforlines .= $line->desc; } } - if (!empty($line->array_options['options_order_notes'])) $htmlforlines.= "
    (".$line->array_options['options_order_notes'].")"; - if ($_SESSION["basiclayout"]!=1) + if (!empty($line->array_options['options_order_notes'])) $htmlforlines .= "
    (".$line->array_options['options_order_notes'].")"; + if ($_SESSION["basiclayout"] != 1) { - $htmlforlines.= '
    ' . vatrate($line->remise_percent, true) . '' . $line->qty . '' . price($line->total_ttc) . ''.vatrate($line->remise_percent, true).''.$line->qty.''.price($line->total_ttc).'
    '; if ($invoice->socid != $conf->global->{'CASHDESK_ID_THIRDPARTY'.$_SESSION["takeposterminal"]}) { - $constforcompanyid='CASHDESK_ID_THIRDPARTY'.$_SESSION["takeposterminal"]; + $constforcompanyid = 'CASHDESK_ID_THIRDPARTY'.$_SESSION["takeposterminal"]; $soc = new Societe($db); if ($invoice->socid > 0) $soc->fetch($invoice->socid); else $soc->fetch($conf->global->$constforcompanyid); @@ -742,7 +752,7 @@ if ($invoice->socid != $conf->global->{'CASHDESK_ID_THIRDPARTY'.$_SESSION["takep print $langs->trans("Customer").': '.$soc->name; $constantforkey = 'CASHDESK_NO_DECREASE_STOCK'.$_SESSION["takeposterminal"]; - if (! empty($conf->stock->enabled) && $conf->global->$constantforkey != "1") + if (!empty($conf->stock->enabled) && $conf->global->$constantforkey != "1") { $constantforkey = 'CASHDESK_ID_WAREHOUSE'.$_SESSION["takeposterminal"]; $warehouse = new Entrepot($db); @@ -751,16 +761,16 @@ if ($invoice->socid != $conf->global->{'CASHDESK_ID_THIRDPARTY'.$_SESSION["takep } // Module Adherent - if (! empty($conf->adherent->enabled)) + if (!empty($conf->adherent->enabled)) { require_once DOL_DOCUMENT_ROOT.'/adherents/class/adherent.class.php'; $langs->load("members"); print '
    '.$langs->trans("Member").': '; - $adh=new Adherent($db); - $result=$adh->fetch('', '', $invoice->socid); + $adh = new Adherent($db); + $result = $adh->fetch('', '', $invoice->socid); if ($result > 0) { - $adh->ref=$adh->getFullName($langs); + $adh->ref = $adh->getFullName($langs); print $adh->getFullName($langs); print '
    '.$langs->trans("Type").': '.$adh->type; if ($adh->datefin) @@ -787,7 +797,7 @@ if ($invoice->socid != $conf->global->{'CASHDESK_ID_THIRDPARTY'.$_SESSION["takep if ($action == "search") { print '
    - '; } diff --git a/htdocs/takepos/pay.php b/htdocs/takepos/pay.php index aea8d14ebba..42ebe2fa85a 100644 --- a/htdocs/takepos/pay.php +++ b/htdocs/takepos/pay.php @@ -72,9 +72,9 @@ top_htmlhead($head, $title, $disablejs, $disablehead, $arrayofjs, $arrayofcss); $langs->loadLangs(array("main", "bills", "cashdesk")); $sql = "SELECT code, libelle as label FROM ".MAIN_DB_PREFIX."c_paiement"; -$sql.= " WHERE entity IN (".getEntity('c_paiement').")"; -$sql.= " AND active = 1"; -$sql.= " ORDER BY libelle"; +$sql .= " WHERE entity IN (".getEntity('c_paiement').")"; +$sql .= " AND active = 1"; +$sql .= " ORDER BY libelle"; $resql = $db->query($sql); $paiements = array(); if ($resql) { @@ -102,7 +102,7 @@ if ($invoice->id > 0) } $alreadypayed = (is_object($invoice) ? ($invoice->total_ttc - $remaintopay) : 0); -if ($conf->global->TAKEPOS_NUMPAD==0) print "var received='';"; +if ($conf->global->TAKEPOS_NUMPAD == 0) print "var received='';"; else print "var received=0;"; ?> @@ -118,10 +118,10 @@ else print "var received=0;"; $('.change1').val(parseFloat(received)); alreadypaydplusreceived=price2numjs(alreadypayed + parseFloat(received)); //console.log("already+received = "+alreadypaydplusreceived); - //console.log("total_ttc = "+total_ttc;?>); - if (alreadypaydplusreceived > total_ttc;?>) + //console.log("total_ttc = "+total_ttc; ?>); + if (alreadypaydplusreceived > total_ttc; ?>) { - var change=parseFloat(alreadypayed + parseFloat(received) - total_ttc;?>); + var change=parseFloat(alreadypayed + parseFloat(received) - total_ttc; ?>); $('.change2').html(pricejs(change, 'MT')); $('.change2').val(change); $('.change1').removeClass('colorred'); @@ -133,7 +133,7 @@ else print "var received=0;"; { $('.change2').html(pricejs(0, 'MT')); $('.change2').val(0); - if (alreadypaydplusreceived == total_ttc;?>) + if (alreadypaydplusreceived == total_ttc; ?>) { $('.change1').removeClass('colorred'); $('.change1').addClass('colorgreen'); @@ -213,11 +213,11 @@ $action_buttons = array( "class" => "poscolordelete" ), ); -$numpad=$conf->global->TAKEPOS_NUMPAD; +$numpad = $conf->global->TAKEPOS_NUMPAD; ?> - - - + + + 0) { $paycode = $paiements[0]->code; if ($paycode == 'LIQ') $paycode = 'cash'; @@ -226,11 +226,11 @@ $numpad=$conf->global->TAKEPOS_NUMPAD; ?> - + - - - + + + 1) { $paycode = $paiements[1]->code; if ($paycode == 'LIQ') $paycode = 'cash'; diff --git a/htdocs/takepos/phone.php b/htdocs/takepos/phone.php index 2bd21626f34..5d0346a495c 100644 --- a/htdocs/takepos/phone.php +++ b/htdocs/takepos/phone.php @@ -25,37 +25,37 @@ //if (! defined('NOREQUIREDB')) define('NOREQUIREDB','1'); // Not disabled cause need to load personalized language //if (! defined('NOREQUIRESOC')) define('NOREQUIRESOC','1'); //if (! defined('NOREQUIRETRAN')) define('NOREQUIRETRAN','1'); -if (! defined('NOCSRFCHECK')) define('NOCSRFCHECK', '1'); -if (! defined('NOTOKENRENEWAL')) define('NOTOKENRENEWAL', '1'); -if (! defined('NOREQUIREMENU')) define('NOREQUIREMENU', '1'); -if (! defined('NOREQUIREHTML')) define('NOREQUIREHTML', '1'); -if (! defined('NOREQUIREAJAX')) define('NOREQUIREAJAX', '1'); +if (!defined('NOCSRFCHECK')) define('NOCSRFCHECK', '1'); +if (!defined('NOTOKENRENEWAL')) define('NOTOKENRENEWAL', '1'); +if (!defined('NOREQUIREMENU')) define('NOREQUIREMENU', '1'); +if (!defined('NOREQUIREHTML')) define('NOREQUIREHTML', '1'); +if (!defined('NOREQUIREAJAX')) define('NOREQUIREAJAX', '1'); -require '../main.inc.php'; // Load $user and permissions +require '../main.inc.php'; // Load $user and permissions 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/facture.class.php'; require_once DOL_DOCUMENT_ROOT.'/core/class/hookmanager.class.php'; -$place = (GETPOST('place', 'int') > 0 ? GETPOST('place', 'int') : 0); // $place is id of table for Ba or Restaurant +$place = (GETPOST('place', 'int') > 0 ? GETPOST('place', 'int') : 0); // $place is id of table for Ba or Restaurant $action = GETPOST('action', 'alpha'); $setterminal = GETPOST('setterminal', 'int'); -if ($setterminal>0) +if ($setterminal > 0) { - $_SESSION["takeposterminal"]=$setterminal; + $_SESSION["takeposterminal"] = $setterminal; } -$langs->loadLangs(array("bills","orders","commercial","cashdesk","receiptprinter")); +$langs->loadLangs(array("bills", "orders", "commercial", "cashdesk", "receiptprinter")); /* * View */ // Title -$title='TakePOS - Dolibarr '.DOL_VERSION; -if (! empty($conf->global->MAIN_APPLICATION_TITLE)) $title='TakePOS - '.$conf->global->MAIN_APPLICATION_TITLE; -$head=' +$title = 'TakePOS - Dolibarr '.DOL_VERSION; +if (!empty($conf->global->MAIN_APPLICATION_TITLE)) $title = 'TakePOS - '.$conf->global->MAIN_APPLICATION_TITLE; +$head = ' '; @@ -66,14 +66,14 @@ top_htmlhead($head, $title, $disablejs, $disablehead, $arrayofjs, $arrayofcss); + +
    +
    +
    +
    +
    +
    +
    + + + +
    + + + diff --git a/htdocs/takepos/takepos.php b/htdocs/takepos/takepos.php index 8966c575f9f..f12b287dc8c 100644 --- a/htdocs/takepos/takepos.php +++ b/htdocs/takepos/takepos.php @@ -26,49 +26,49 @@ //if (! defined('NOREQUIREDB')) define('NOREQUIREDB','1'); // Not disabled cause need to load personalized language //if (! defined('NOREQUIRESOC')) define('NOREQUIRESOC','1'); //if (! defined('NOREQUIRETRAN')) define('NOREQUIRETRAN','1'); -if (! defined('NOCSRFCHECK')) define('NOCSRFCHECK', '1'); -if (! defined('NOTOKENRENEWAL')) define('NOTOKENRENEWAL', '1'); -if (! defined('NOREQUIREMENU')) define('NOREQUIREMENU', '1'); -if (! defined('NOREQUIREHTML')) define('NOREQUIREHTML', '1'); -if (! defined('NOREQUIREAJAX')) define('NOREQUIREAJAX', '1'); +if (!defined('NOCSRFCHECK')) define('NOCSRFCHECK', '1'); +if (!defined('NOTOKENRENEWAL')) define('NOTOKENRENEWAL', '1'); +if (!defined('NOREQUIREMENU')) define('NOREQUIREMENU', '1'); +if (!defined('NOREQUIREHTML')) define('NOREQUIREHTML', '1'); +if (!defined('NOREQUIREAJAX')) define('NOREQUIREAJAX', '1'); -require '../main.inc.php'; // Load $user and permissions +require '../main.inc.php'; // Load $user and permissions 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/facture.class.php'; require_once DOL_DOCUMENT_ROOT.'/core/class/hookmanager.class.php'; -$place = (GETPOST('place', 'int') > 0 ? GETPOST('place', 'int') : 0); // $place is id of table for Ba or Restaurant +$place = (GETPOST('place', 'int') > 0 ? GETPOST('place', 'int') : 0); // $place is id of table for Ba or Restaurant $action = GETPOST('action', 'alpha'); $setterminal = GETPOST('setterminal', 'int'); -if ($setterminal>0) +if ($setterminal > 0) { - $_SESSION["takeposterminal"]=$setterminal; + $_SESSION["takeposterminal"] = $setterminal; } -$_SESSION["urlfrom"]='/takepos/takepos.php'; +$_SESSION["urlfrom"] = '/takepos/takepos.php'; -$langs->loadLangs(array("bills","orders","commercial","cashdesk","receiptprinter")); +$langs->loadLangs(array("bills", "orders", "commercial", "cashdesk", "receiptprinter")); $categorie = new Categorie($db); -$maxcategbydefaultforthisdevice=16; -$maxproductbydefaultforthisdevice=32; +$maxcategbydefaultforthisdevice = 16; +$maxproductbydefaultforthisdevice = 32; if ($conf->browser->layout == 'phone') { - $maxcategbydefaultforthisdevice=8; - $maxproductbydefaultforthisdevice=16; + $maxcategbydefaultforthisdevice = 8; + $maxproductbydefaultforthisdevice = 16; //REDIRECT TO BASIC LAYOUT IF TERMINAL SELECTED AND BASIC MOBILE LAYOUT ENABLED - if ($_SESSION["takeposterminal"]!="" && $conf->global->TAKEPOS_PHONE_BASIC_LAYOUT==1) + if ($_SESSION["takeposterminal"] != "" && $conf->global->TAKEPOS_PHONE_BASIC_LAYOUT == 1) { - $_SESSION["basiclayout"]=1; + $_SESSION["basiclayout"] = 1; header("Location: phone.php?mobilepage=invoice"); exit; } } -$MAXCATEG = (empty($conf->global->TAKEPOS_NB_MAXCATEG)?$maxcategbydefaultforthisdevice:$conf->global->TAKEPOS_NB_MAXCATEG); -$MAXPRODUCT = (empty($conf->global->TAKEPOS_NB_MAXPRODUCT)?$maxproductbydefaultforthisdevice:$conf->global->TAKEPOS_NB_MAXPRODUCT); +$MAXCATEG = (empty($conf->global->TAKEPOS_NB_MAXCATEG) ? $maxcategbydefaultforthisdevice : $conf->global->TAKEPOS_NB_MAXCATEG); +$MAXPRODUCT = (empty($conf->global->TAKEPOS_NB_MAXPRODUCT) ? $maxproductbydefaultforthisdevice : $conf->global->TAKEPOS_NB_MAXPRODUCT); /* @@ -76,9 +76,9 @@ $MAXPRODUCT = (empty($conf->global->TAKEPOS_NB_MAXPRODUCT)?$maxproductbydefaultf */ // Title -$title='TakePOS - Dolibarr '.DOL_VERSION; -if (! empty($conf->global->MAIN_APPLICATION_TITLE)) $title='TakePOS - '.$conf->global->MAIN_APPLICATION_TITLE; -$head=' +$title = 'TakePOS - Dolibarr '.DOL_VERSION; +if (!empty($conf->global->MAIN_APPLICATION_TITLE)) $title = 'TakePOS - '.$conf->global->MAIN_APPLICATION_TITLE; +$head = ' '; @@ -90,15 +90,15 @@ top_htmlhead($head, $title, $disablejs, $disablehead, $arrayofjs, $arrayofcss); '; $stringtoshow .= '
    '; // hideobject is to start hidden -$stringtoshow .= '
    '; -$stringtoshow .= ''; +$stringtoshow .= ''; +$stringtoshow .= ''; $stringtoshow .= ''; -$stringtoshow .= $langs->trans("Year") . ' '; -$stringtoshow .= ''; +$stringtoshow .= $langs->trans("Year").' '; +$stringtoshow .= ''; $stringtoshow .= '
    '; $stringtoshow .= '
    '; print '
    '; -print ''; -print ''; +print '
    ' . $langs->trans("Statistics") . ' ' . img_picto('', 'filter.png', 'id="idsubimgDOLUSERCOOKIE_ticket_by_status" class="linkobject"') . '
    '; +print ''; print ''; @@ -274,26 +274,26 @@ $max = 10; $sql = "SELECT t.rowid, t.ref, t.track_id, t.datec, t.subject, t.type_code, t.category_code, t.severity_code, t.fk_statut, t.progress,"; $sql .= " type.label as type_label, category.label as category_label, severity.label as severity_label"; -$sql .= " FROM " . MAIN_DB_PREFIX . "ticket as t"; -$sql .= " LEFT JOIN " . MAIN_DB_PREFIX . "c_ticket_type as type ON type.code=t.type_code"; -$sql .= " LEFT JOIN " . MAIN_DB_PREFIX . "c_ticket_category as category ON category.code=t.category_code"; -$sql .= " LEFT JOIN " . MAIN_DB_PREFIX . "c_ticket_severity as severity ON severity.code=t.severity_code"; +$sql .= " FROM ".MAIN_DB_PREFIX."ticket as t"; +$sql .= " LEFT JOIN ".MAIN_DB_PREFIX."c_ticket_type as type ON type.code=t.type_code"; +$sql .= " LEFT JOIN ".MAIN_DB_PREFIX."c_ticket_category as category ON category.code=t.category_code"; +$sql .= " LEFT JOIN ".MAIN_DB_PREFIX."c_ticket_severity as severity ON severity.code=t.severity_code"; if (!$user->rights->societe->client->voir && !$socid) { - $sql .= ", " . MAIN_DB_PREFIX . "societe_commerciaux as sc"; + $sql .= ", ".MAIN_DB_PREFIX."societe_commerciaux as sc"; } -$sql .= ' WHERE t.entity IN (' . getEntity('ticket') . ')'; +$sql .= ' WHERE t.entity IN ('.getEntity('ticket').')'; $sql .= " AND t.fk_statut=0"; if (!$user->rights->societe->client->voir && !$socid) { - $sql .= " AND t.fk_soc = sc.fk_soc AND sc.fk_user = " . $user->id; + $sql .= " AND t.fk_soc = sc.fk_soc AND sc.fk_user = ".$user->id; } if ($user->socid > 0) { - $sql .= " AND t.fk_soc='" . $user->socid . "'"; + $sql .= " AND t.fk_soc='".$user->socid."'"; } else { // Restricted to assigned user only if ($conf->global->TICKET_LIMIT_VIEW_ASSIGNED_ONLY && !$user->rights->ticket->manage) { - $sql .= " AND t.fk_user_assign=" . $user->id; + $sql .= " AND t.fk_user_assign=".$user->id; } } $sql .= $db->order("t.datec", "DESC"); @@ -309,8 +309,8 @@ if ($result) { $transRecordedType = $langs->trans("LatestNewTickets", $max); print '
    '; - print '
    '.$langs->trans("Statistics").' '.img_picto('', 'filter.png', 'id="idsubimgDOLUSERCOOKIE_ticket_by_status" class="linkobject"').'
    '; print $stringtoshow; // don't display graph if no series -if (! empty($dataseries) && count($dataseries) > 1) { - $totalnb=0; +if (!empty($dataseries) && count($dataseries) > 1) { + $totalnb = 0; foreach ($dataseries as $key => $value) { $totalnb += $value['data']; } @@ -252,7 +252,7 @@ if (! empty($dataseries) && count($dataseries) > 1) { //$px1->SetTitle($langs->trans("TicketStatByStatus")); $px1->draw($filenamenb, $fileurlnb); - print $px1->show($totalnb?0:1); + print $px1->show($totalnb ? 0 : 1); } } print '
    '; - print ''; + print '
    ' . $transRecordedType . '
    '; + print ''; print ''; print ''; if ($num > 0) { @@ -338,7 +338,7 @@ if ($result) { // Subject print '\n"; // Type @@ -366,7 +366,7 @@ if ($result) { $db->free(); } else { - print ''; + print ''; } print "
    '.$transRecordedType.''.$langs->trans("FullList").'
    '; - print '' . dol_trunc($objp->subject, 30) . ''; + print ''.dol_trunc($objp->subject, 30).''; print "
    ' . $langs->trans('NoUnreadTicketsFound') . '
    '.$langs->trans('NoUnreadTicketsFound').'
    "; diff --git a/htdocs/ticket/list.php b/htdocs/ticket/list.php index 1360dc6efcd..670ed740b5f 100644 --- a/htdocs/ticket/list.php +++ b/htdocs/ticket/list.php @@ -26,42 +26,42 @@ */ require '../main.inc.php'; -require_once DOL_DOCUMENT_ROOT . '/ticket/class/actions_ticket.class.php'; -require_once DOL_DOCUMENT_ROOT . '/core/class/html.formticket.class.php'; -require_once DOL_DOCUMENT_ROOT . '/core/lib/functions2.lib.php'; -require_once DOL_DOCUMENT_ROOT . '/core/lib/company.lib.php'; -require_once DOL_DOCUMENT_ROOT . '/user/class/user.class.php'; -include_once DOL_DOCUMENT_ROOT . '/projet/class/project.class.php'; -include_once DOL_DOCUMENT_ROOT . '/core/class/html.formprojet.class.php'; -include_once DOL_DOCUMENT_ROOT . '/core/lib/project.lib.php'; +require_once DOL_DOCUMENT_ROOT.'/ticket/class/actions_ticket.class.php'; +require_once DOL_DOCUMENT_ROOT.'/core/class/html.formticket.class.php'; +require_once DOL_DOCUMENT_ROOT.'/core/lib/functions2.lib.php'; +require_once DOL_DOCUMENT_ROOT.'/core/lib/company.lib.php'; +require_once DOL_DOCUMENT_ROOT.'/user/class/user.class.php'; +include_once DOL_DOCUMENT_ROOT.'/projet/class/project.class.php'; +include_once DOL_DOCUMENT_ROOT.'/core/class/html.formprojet.class.php'; +include_once DOL_DOCUMENT_ROOT.'/core/lib/project.lib.php'; // Load translation files required by the page $langs->loadLangs(array("ticket", "companies", "other", "projects")); // Get parameters -$action = GETPOST('action', 'aZ09')?GETPOST('action', 'aZ09'):'view'; // The action 'add', 'create', 'edit', 'update', 'view', ... -$massaction = GETPOST('massaction', 'alpha'); // The bulk action (combo box choice into lists) -$show_files = GETPOST('show_files', 'int'); // Show files area generated by bulk actions ? -$confirm = GETPOST('confirm', 'alpha'); // Result of a confirmation -$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'):'ticketlist'; // 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') +$action = GETPOST('action', 'aZ09') ?GETPOST('action', 'aZ09') : 'view'; // The action 'add', 'create', 'edit', 'update', 'view', ... +$massaction = GETPOST('massaction', 'alpha'); // The bulk action (combo box choice into lists) +$show_files = GETPOST('show_files', 'int'); // Show files area generated by bulk actions ? +$confirm = GETPOST('confirm', 'alpha'); // Result of a confirmation +$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') : 'ticketlist'; // 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') -$id = GETPOST('id', 'int'); +$id = GETPOST('id', 'int'); $msg_id = GETPOST('msg_id', 'int'); $socid = GETPOST('socid', 'int'); $projectid = GETPOST('projectid', 'int'); -$project_ref= GETPOST('project_ref', 'alpha'); +$project_ref = GETPOST('project_ref', 'alpha'); $search_societe = GETPOST('search_societe', 'alpha'); -$search_fk_project=GETPOST('search_fk_project', 'int')?GETPOST('search_fk_project', 'int'):GETPOST('projectid', 'int'); +$search_fk_project = GETPOST('search_fk_project', 'int') ?GETPOST('search_fk_project', 'int') : GETPOST('projectid', 'int'); $search_fk_status = GETPOST('search_fk_statut', 'array'); -$mode = GETPOST('mode', 'alpha'); +$mode = GETPOST('mode', 'alpha'); // Load variable for pagination -$limit = GETPOST('limit', 'int')?GETPOST('limit', 'int'):$conf->liste_limit; +$limit = GETPOST('limit', 'int') ?GETPOST('limit', 'int') : $conf->liste_limit; $sortfield = GETPOST('sortfield', 'alpha'); $sortorder = GETPOST('sortorder', 'alpha'); $page = GETPOST('page', 'int'); @@ -71,51 +71,51 @@ $pageprev = $page - 1; $pagenext = $page + 1; // Initialize technical objects -$object=new Ticket($db); +$object = new Ticket($db); $extrafields = new ExtraFields($db); -$diroutputmassaction=$conf->ticket->dir_output . '/temp/massgeneration/'.$user->id; +$diroutputmassaction = $conf->ticket->dir_output.'/temp/massgeneration/'.$user->id; if ($socid > 0) $hookmanager->initHooks(array('thirdpartyticket')); elseif ($project > 0) $hookmanager->initHooks(array('projectticket')); else $hookmanager->initHooks(array('ticketlist')); // Fetch optionals attributes and labels $extrafields->fetch_name_optionals_label($object->table_element); -$search_array_options=$extrafields->getOptionalsFromPost($object->table_element, '', 'search_'); +$search_array_options = $extrafields->getOptionalsFromPost($object->table_element, '', 'search_'); // Default sort order (if not yet defined by previous GETPOST) -if (! $sortfield) $sortfield="t.datec"; -if (! $sortorder) $sortorder="DESC"; +if (!$sortfield) $sortfield = "t.datec"; +if (!$sortorder) $sortorder = "DESC"; -if (GETPOST('search_fk_status', 'alpha') == 'non_closed') $_GET['search_fk_statut'][]='openall'; // For backward compatibility +if (GETPOST('search_fk_status', 'alpha') == 'non_closed') $_GET['search_fk_statut'][] = 'openall'; // For backward compatibility // Initialize array of search criterias -$search_all=trim(GETPOSTISSET("search_all")?GETPOSTISSET("search_all", 'alpha'):GETPOST('sall')); -$search=array(); -foreach($object->fields as $key => $val) +$search_all = trim(GETPOSTISSET("search_all") ?GETPOSTISSET("search_all", 'alpha') : GETPOST('sall')); +$search = array(); +foreach ($object->fields as $key => $val) { - if (GETPOST('search_'.$key, 'alpha')) $search[$key]=GETPOST('search_'.$key, 'alpha'); + 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) +foreach ($object->fields as $key => $val) { - if ($val['searchall']) $fieldstosearchall['t.'.$key]=$val['label']; + if ($val['searchall']) $fieldstosearchall['t.'.$key] = $val['label']; } // Definition of fields for list -$arrayfields=array(); -foreach($object->fields as $key => $val) +$arrayfields = array(); +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'], 'position'=>$val['position']); + if (!empty($val['visible'])) $arrayfields['t.'.$key] = array('label'=>$val['label'], 'checked'=>(($val['visible'] < 0) ? 0 : 1), 'enabled'=>$val['enabled'], '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) + 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], 'checked'=>(($extrafields->attributes[$object->table_element]['list'][$key]<0)?0:1), 'position'=>$extrafields->attributes[$object->table_element]['pos'][$key], 'enabled'=>(abs($extrafields->attributes[$object->table_element]['list'][$key])!=3 && $extrafields->attributes[$object->table_element]['perms'][$key])); + if (!empty($extrafields->attributes[$object->table_element]['list'][$key])) + $arrayfields["ef.".$key] = array('label'=>$extrafields->attributes[$object->table_element]['label'][$key], 'checked'=>(($extrafields->attributes[$object->table_element]['list'][$key] < 0) ? 0 : 1), 'position'=>$extrafields->attributes[$object->table_element]['pos'][$key], 'enabled'=>(abs($extrafields->attributes[$object->table_element]['list'][$key]) != 3 && $extrafields->attributes[$object->table_element]['perms'][$key])); } } $object->fields = dol_sort_array($object->fields, 'position'); @@ -145,11 +145,11 @@ if ($project_ref) * 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 +$parameters = array(); +$reshook = $hookmanager->executeHooks('doActions', $parameters, $object, $action); // Note that $action and $object may have been modified by some hooks if ($reshook < 0) setEventMessages($hookmanager->error, $hookmanager->errors, 'errors'); if (empty($reshook)) @@ -158,24 +158,24 @@ if (empty($reshook)) 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 { - foreach($object->fields as $key => $val) + foreach ($object->fields as $key => $val) { - $search[$key]=''; + $search[$key] = ''; } - $toselect=''; - $search_array_options=array(); + $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')) { - $massaction=''; // Protection to avoid mass action if we force a new search during a mass action confirmation + $massaction = ''; // Protection to avoid mass action if we force a new search during a mass action confirmation } // Mass actions - $objectclass='Ticket'; - $objectlabel='Ticket'; + $objectclass = 'Ticket'; + $objectlabel = 'Ticket'; $permissiontoread = $user->rights->ticket->read; $permissiontodelete = $user->rights->ticket->delete; $uploaddir = $conf->ticket->dir_output; @@ -188,10 +188,10 @@ if (empty($reshook)) * View */ -$form=new Form($db); +$form = new Form($db); $formTicket = new FormTicket($db); -$now=dol_now(); +$now = dol_now(); $user_assign = new User($db); $user_create = new User($db); @@ -204,63 +204,63 @@ $title = $langs->trans('TicketList'); // Build and execute select // -------------------------------------------------------------------- $sql = 'SELECT '; -foreach($object->fields as $key => $val) +foreach ($object->fields as $key => $val) { - $sql.='t.'.$key.', '; + $sql .= 't.'.$key.', '; } // Add fields from extrafields -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.', ' : ''); +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.', ' : ''); // Add fields from hooks -$parameters=array(); -$reshook=$hookmanager->executeHooks('printFieldListSelect', $parameters, $object); // Note that $action and $object may have been modified by hook -$sql.=$hookmanager->resPrint; -$sql=preg_replace('/, $/', '', $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)"; -$sql.= " LEFT JOIN ".MAIN_DB_PREFIX."societe as s ON (t.fk_soc = s.rowid)"; -$sql.= " WHERE t.entity IN (".getEntity($object->element).")"; +$parameters = array(); +$reshook = $hookmanager->executeHooks('printFieldListSelect', $parameters, $object); // Note that $action and $object may have been modified by hook +$sql .= $hookmanager->resPrint; +$sql = preg_replace('/, $/', '', $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)"; +$sql .= " LEFT JOIN ".MAIN_DB_PREFIX."societe as s ON (t.fk_soc = s.rowid)"; +$sql .= " WHERE t.entity IN (".getEntity($object->element).")"; if ($socid > 0) { - $sql.= " AND t.fk_soc = ".$socid; + $sql .= " AND t.fk_soc = ".$socid; } -foreach($search as $key => $val) +foreach ($search as $key => $val) { if ($key == 'fk_statut') { - $tmpstatus=''; - if ($search['fk_statut'] == 'openall' || in_array('openall', $search['fk_statut'])) $tmpstatus.=($tmpstatus?',':'')."'".Ticket::STATUS_NOT_READ."', '".Ticket::STATUS_READ."', '".Ticket::STATUS_ASSIGNED."', '".Ticket::STATUS_IN_PROGRESS."', '".Ticket::STATUS_NEED_MORE_INFO."', '".Ticket::STATUS_WAITING."'"; - if ($search['fk_statut'] == 'closeall' || in_array('closeall', $search['fk_statut'])) $tmpstatus.=($tmpstatus?',':'')."'".Ticket::STATUS_CLOSED."', '".Ticket::STATUS_CANCELED."'"; - if ($tmpstatus) $sql.=" AND fk_statut IN (".$tmpstatus.")"; - elseif (is_array($search[$key]) && count($search[$key])) $sql.=natural_search($key, join(',', $search[$key]), 2); + $tmpstatus = ''; + if ($search['fk_statut'] == 'openall' || in_array('openall', $search['fk_statut'])) $tmpstatus .= ($tmpstatus ? ',' : '')."'".Ticket::STATUS_NOT_READ."', '".Ticket::STATUS_READ."', '".Ticket::STATUS_ASSIGNED."', '".Ticket::STATUS_IN_PROGRESS."', '".Ticket::STATUS_NEED_MORE_INFO."', '".Ticket::STATUS_WAITING."'"; + if ($search['fk_statut'] == 'closeall' || in_array('closeall', $search['fk_statut'])) $tmpstatus .= ($tmpstatus ? ',' : '')."'".Ticket::STATUS_CLOSED."', '".Ticket::STATUS_CANCELED."'"; + if ($tmpstatus) $sql .= " AND fk_statut IN (".$tmpstatus.")"; + elseif (is_array($search[$key]) && count($search[$key])) $sql .= natural_search($key, join(',', $search[$key]), 2); continue; } if ($key == 'fk_user_assign') { - if ($search[$key] > 0) $sql.=natural_search($key, $search[$key], 2); + if ($search[$key] > 0) $sql .= natural_search($key, $search[$key], 2); continue; } - $mode_search=(($object->isInt($object->fields[$key]) || $object->isFloat($object->fields[$key]))?1:0); - if ($search[$key] != '') $sql.=natural_search($key, $search[$key], $mode_search); + $mode_search = (($object->isInt($object->fields[$key]) || $object->isFloat($object->fields[$key])) ? 1 : 0); + if ($search[$key] != '') $sql .= natural_search($key, $search[$key], $mode_search); } -if ($search_all) $sql.= natural_search(array_keys($fieldstosearchall), $search_all); +if ($search_all) $sql .= natural_search(array_keys($fieldstosearchall), $search_all); if ($search_societe) $sql .= natural_search('s.nom', $search_societe); -if ($search_fk_project) $sql.= natural_search('fk_project', $search_fk_project, 2); -if (! $user->socid && ($mode == "mine" || (!$user->admin && $conf->global->TICKET_LIMIT_VIEW_ASSIGNED_ONLY))) { - $sql.= " AND (t.fk_user_assign = ".$user->id; - if (empty($conf->global->TICKET_LIMIT_VIEW_ASSIGNED_ONLY)) $sql.=" OR t.fk_user_create = ".$user->id; - $sql.=")"; +if ($search_fk_project) $sql .= natural_search('fk_project', $search_fk_project, 2); +if (!$user->socid && ($mode == "mine" || (!$user->admin && $conf->global->TICKET_LIMIT_VIEW_ASSIGNED_ONLY))) { + $sql .= " AND (t.fk_user_assign = ".$user->id; + if (empty($conf->global->TICKET_LIMIT_VIEW_ASSIGNED_ONLY)) $sql .= " OR t.fk_user_create = ".$user->id; + $sql .= ")"; } // Add where from extra fields include DOL_DOCUMENT_ROOT.'/core/tpl/extrafields_list_search_sql.tpl.php'; // Add where from hooks -$parameters=array(); -$reshook=$hookmanager->executeHooks('printFieldListWhere', $parameters, $object); // Note that $action and $object may have been modified by hook -$sql.=$hookmanager->resPrint; +$parameters = array(); +$reshook = $hookmanager->executeHooks('printFieldListWhere', $parameters, $object); // Note that $action and $object may have been modified by hook +$sql .= $hookmanager->resPrint; -$sql.=$db->order($sortfield, $sortorder); +$sql .= $db->order($sortfield, $sortorder); // Count total nb of records $nbtotalofrecords = ''; @@ -281,10 +281,10 @@ if (is_numeric($nbtotalofrecords) && $limit > $nbtotalofrecords) } else { - $sql.= $db->plimit($limit+1, $offset); + $sql .= $db->plimit($limit + 1, $offset); - $resql=$db->query($sql); - if (! $resql) + $resql = $db->query($sql); + if (!$resql) { dol_print_error($db); exit; @@ -294,7 +294,7 @@ else } // Direct jump if only one record found -if ($num == 1 && ! empty($conf->global->MAIN_SEARCH_DIRECT_OPEN_IF_ONLY_ONE) && $search_all) +if ($num == 1 && !empty($conf->global->MAIN_SEARCH_DIRECT_OPEN_IF_ONLY_ONE) && $search_all) { $obj = $db->fetch_object($resql); $id = $obj->rowid; @@ -309,12 +309,12 @@ if ($num == 1 && ! empty($conf->global->MAIN_SEARCH_DIRECT_OPEN_IF_ONLY_ONE) && llxHeader('', $title, $help_url); -if ($socid && ! $projectid && ! $project_ref && $user->rights->societe->lire) { +if ($socid && !$projectid && !$project_ref && $user->rights->societe->lire) { $socstat = new Societe($db); $res = $socstat->fetch($socid); if ($res > 0) { $tmpobject = $object; - $object = $socstat; // $object must be of type Societe when calling societe_prepare_head + $object = $socstat; // $object must be of type Societe when calling societe_prepare_head $head = societe_prepare_head($socstat); $object = $tmpobject; @@ -330,10 +330,10 @@ if ($socid && ! $projectid && ! $project_ref && $user->rights->societe->lire) { // Customer code if ($socstat->client && !empty($socstat->code_client)) { print '
    '; - print $langs->trans('CustomerCode') . ''; + print $langs->trans('CustomerCode').''; print $socstat->code_client; if ($socstat->check_codeclient() != 0) { - print ' (' . $langs->trans("WrongCustomerCode") . ')'; + print ' ('.$langs->trans("WrongCustomerCode").')'; } print '
    '; - print $langs->trans('SupplierCode') . ''; + print $langs->trans('SupplierCode').''; print $socstat->code_fournisseur; if ($socstat->check_codefournisseur() != 0) { - print ' (' . $langs->trans("WrongSupplierCode") . ')'; + print ' ('.$langs->trans("WrongSupplierCode").')'; } print '
    '; // Visibility - print '
    ' . $langs->trans("Visibility") . ''; + print '
    '.$langs->trans("Visibility").''; if ($projectstat->public) { print $langs->trans('SharedProject'); } else { @@ -424,30 +424,30 @@ if ($projectid > 0 || $project_ref) { } } -$arrayofselected=is_array($toselect)?$toselect:array(); +$arrayofselected = is_array($toselect) ? $toselect : array(); -$param=''; -if (! empty($contextpage) && $contextpage != $_SERVER["PHP_SELF"]) $param.='&contextpage='.urlencode($contextpage); -if ($limit > 0 && $limit != $conf->liste_limit) $param.='&limit='.urlencode($limit); -foreach($search as $key => $val) +$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 (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'; -if ($socid) $param.='&socid='.urlencode($socid); -if ($projectid) $param.='&projectid='.urlencode($projectid); +if ($socid) $param .= '&socid='.urlencode($socid); +if ($projectid) $param .= '&projectid='.urlencode($projectid); // List of mass actions available -$arrayofmassactions = array( +$arrayofmassactions = array( //'presend'=>$langs->trans("SendByMail"), //'builddoc'=>$langs->trans("PDFMerge"), ); -if ($user->rights->ticket->delete) $arrayofmassactions['predelete']=''.$langs->trans("Delete"); -if (GETPOST('nomassaction', 'int') || in_array($massaction, array('presend','predelete'))) $arrayofmassactions=array(); -$massactionbutton=$form->selectMassAction('', $arrayofmassactions); +if ($user->rights->ticket->delete) $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 ''; @@ -458,12 +458,12 @@ print ''; print ''; print ''; print ''; -print ''; -if ($socid) print ''; -if ($projectid) print ''; +print ''; +if ($socid) print ''; +if ($projectid) print ''; -$newcardbutton=''; -$newcardbutton.= dolGetButtonTitle($langs->trans('NewTicket'), '', 'fa fa-plus-circle', DOL_URL_ROOT.'/ticket/card.php?action=create' . ($socid ? '&socid=' . $socid : '') . ($projectid ? '&origin=projet_project&originid=' . $projectid : ''), '', !empty($user->rights->ticket->write)); +$newcardbutton = ''; +$newcardbutton .= dolGetButtonTitle($langs->trans('NewTicket'), '', 'fa fa-plus-circle', DOL_URL_ROOT.'/ticket/card.php?action=create'.($socid ? '&socid='.$socid : '').($projectid ? '&origin=projet_project&originid='.$projectid : ''), '', !empty($user->rights->ticket->write)); $picto = 'ticket'; if ($socid > 0) $picto = ''; @@ -471,19 +471,19 @@ if ($socid > 0) $picto = ''; print_barre_liste($title, $page, $_SERVER["PHP_SELF"], $param, $sortfield, $sortorder, $massactionbutton, $num, $nbtotalofrecords, $picto, 0, $newcardbutton, '', $limit); if ($mode == 'mine') { - print '
    ' . $langs->trans('TicketAssignedToMeInfos') . '

    '; + print '
    '.$langs->trans('TicketAssignedToMeInfos').'

    '; } // Add code for pre mass action (confirmation or email presend form) -$topicmail="SendTicketRef"; -$modelmail="ticket"; -$objecttmp=new Ticket($db); -$trackid='tick'.$object->id; +$topicmail = "SendTicketRef"; +$modelmail = "ticket"; +$objecttmp = new Ticket($db); +$trackid = 'tick'.$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); - print '
    '.$langs->trans("FilterOnInto", $search_all) . join(', ', $fieldstosearchall).'
    '; + foreach ($fieldstosearchall as $key => $val) $fieldstosearchall[$key] = $langs->trans($val); + print '
    '.$langs->trans("FilterOnInto", $search_all).join(', ', $fieldstosearchall).'
    '; } $moreforfilter = ''; @@ -491,62 +491,62 @@ $moreforfilter = ''; $moreforfilter.= $langs->trans('MyFilter') . ': '; $moreforfilter.= '';*/ -$parameters=array(); -$reshook=$hookmanager->executeHooks('printFieldPreListTitle', $parameters, $object); // Note that $action and $object may have been modified by hook +$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($moreforfilter)) +if (!empty($moreforfilter)) { print '
    '; print $moreforfilter; print '
    '; } -$varpage=empty($contextpage)?$_SERVER["PHP_SELF"]:$contextpage; -$selectedfields=$form->multiSelectArrayWithCheckbox('selectedfields', $arrayfields, $varpage); // This also change content of $arrayfields -$selectedfields.=(count($arrayofmassactions) ? $form->showCheckAddButtons('checkforselect', 1) : ''); +$varpage = empty($contextpage) ? $_SERVER["PHP_SELF"] : $contextpage; +$selectedfields = $form->multiSelectArrayWithCheckbox('selectedfields', $arrayfields, $varpage); // This also change content of $arrayfields +$selectedfields .= (count($arrayofmassactions) ? $form->showCheckAddButtons('checkforselect', 1) : ''); -print '
    '; // You can use div-table-responsive-no-min if you dont need reserved height for your table -print ''."\n"; +print '
    '; // You can use div-table-responsive-no-min if you dont need reserved height for your table +print '
    '."\n"; // Fields title search // -------------------------------------------------------------------- print ''; -foreach($object->fields as $key => $val) +foreach ($object->fields as $key => $val) { - $cssforfield=(empty($val['css'])?'':$val['css']); - if ($key == 'fk_statut') $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'])) { + $cssforfield = (empty($val['css']) ? '' : $val['css']); + if ($key == 'fk_statut') $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 == 'type_code') { - print ''; } elseif ($key == 'category_code') { - print ''; } elseif ($key == 'severity_code') { - print ''; } elseif ($key == 'fk_user_assign') { - print ''; } elseif ($key == 'fk_statut') { $arrayofstatus = array(); - $arrayofstatus['openall']='-- '.$langs->trans('OpenAll').' --'; + $arrayofstatus['openall'] = '-- '.$langs->trans('OpenAll').' --'; foreach ($object->statuts_short as $key2 => $val2) { $arrayofstatus[$key2] = $val2; - if ($key2 == '6') $arrayofstatus['closeall']='-- '.$langs->trans('ClosedAll').' --'; + if ($key2 == '6') $arrayofstatus['closeall'] = '-- '.$langs->trans('ClosedAll').' --'; } - print ''; + print ''; } else { - print ''; + print ''; } } } @@ -566,12 +566,12 @@ foreach($object->fields as $key => $val) include DOL_DOCUMENT_ROOT.'/core/tpl/extrafields_list_search_input.tpl.php'; // Fields from hook -$parameters=array('arrayfields'=>$arrayfields); -$reshook=$hookmanager->executeHooks('printFieldListOption', $parameters, $object); // Note that $action and $object may have been modified by hook +$parameters = array('arrayfields'=>$arrayfields); +$reshook = $hookmanager->executeHooks('printFieldListOption', $parameters, $object); // Note that $action and $object may have been modified by hook print $hookmanager->resPrint; // Action column print ''; print ''."\n"; @@ -580,51 +580,51 @@ 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 == 'fk_statut') $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'])) + $cssforfield = (empty($val['css']) ? '' : $val['css']); + if ($key == 'fk_statut') $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, '', $sortfield, $sortorder, ($cssforfield?$cssforfield.' ':''))."\n"; + print getTitleFieldOfList($arrayfields['t.'.$key]['label'], 0, $_SERVER['PHP_SELF'], 't.'.$key, '', $param, '', $sortfield, $sortorder, ($cssforfield ? $cssforfield.' ' : ''))."\n"; } } // 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, $object); // Note that $action and $object may have been modified by hook +$parameters = array('arrayfields'=>$arrayfields, 'param'=>$param, 'sortfield'=>$sortfield, 'sortorder'=>$sortorder); +$reshook = $hookmanager->executeHooks('printFieldListTitle', $parameters, $object); // Note that $action and $object may have been modified by hook print $hookmanager->resPrint; print getTitleFieldOfList($selectedfields, 0, $_SERVER["PHP_SELF"], '', '', '', '', $sortfield, $sortorder, 'maxwidthsearch center ')."\n"; print ''."\n"; // Detect if we need a fetch on each output line -$needToFetchEachLine=0; +$needToFetchEachLine = 0; if (is_array($extrafields->attributes[$object->table_element]['computed']) && count($extrafields->attributes[$object->table_element]['computed']) > 0) { foreach ($extrafields->attributes[$object->table_element]['computed'] as $key => $val) { - if (preg_match('/\$object/', $val)) $needToFetchEachLine++; // There is at least one compute field that use $object + if (preg_match('/\$object/', $val)) $needToFetchEachLine++; // There is at least one compute field that use $object } } // Loop on record // -------------------------------------------------------------------- -$i=0; -$totalarray=array(); +$i = 0; +$totalarray = array(); while ($i < min($num, $limit)) { $obj = $db->fetch_object($resql); - if (empty($obj)) break; // Should not happen + if (empty($obj)) break; // Should not happen // Store properties in $object $object->id = $obj->rowid; - foreach($object->fields as $key => $val) + foreach ($object->fields as $key => $val) { if (property_exists($obj, $key)) $object->$key = $obj->$key; } @@ -632,14 +632,14 @@ while ($i < min($num, $limit)) // Show here line of result print ''; - foreach($object->fields as $key => $val) + foreach ($object->fields as $key => $val) { - $cssforfield=''; - if (in_array($val['type'], array('date','datetime','timestamp'))) $cssforfield.=($cssforfield?' ':'').'center'; - if (in_array($val['type'], array('timestamp'))) $cssforfield.=($cssforfield?' ':'').'nowrap'; - if ($key == 'ref') $cssforfield.=($cssforfield?' ':'').'nowraponall'; - if ($key == 'fk_statut') $cssforfield.=($cssforfield?' ':'').'center'; - if (! empty($arrayfields['t.'.$key]['checked'])) + $cssforfield = ''; + if (in_array($val['type'], array('date', 'datetime', 'timestamp'))) $cssforfield .= ($cssforfield ? ' ' : '').'center'; + if (in_array($val['type'], array('timestamp'))) $cssforfield .= ($cssforfield ? ' ' : '').'nowrap'; + if ($key == 'ref') $cssforfield .= ($cssforfield ? ' ' : '').'nowraponall'; + if ($key == 'fk_statut') $cssforfield .= ($cssforfield ? ' ' : '').'center'; + if (!empty($arrayfields['t.'.$key]['checked'])) { print ''; if ($massactionbutton || $massaction) // If we are in select mode (massactionbutton defined) or if we have already selected and sent an action ($massaction) defined { - $selected=0; - if (in_array($obj->rowid, $arrayofselected)) $selected=1; - print ''; + $selected = 0; + if (in_array($obj->rowid, $arrayofselected)) $selected = 1; + print ''; } print ''; - if (! $i) $totalarray['nbfield']++; + if (!$i) $totalarray['nbfield']++; print ''; @@ -693,16 +693,16 @@ include DOL_DOCUMENT_ROOT.'/core/tpl/list_print_total.tpl.php'; // If no record found if ($num == 0) { - $colspan=1; - foreach($arrayfields as $key => $val) { if (! empty($val['checked'])) $colspan++; } + $colspan = 1; + foreach ($arrayfields as $key => $val) { if (!empty($val['checked'])) $colspan++; } print ''; } $db->free($resql); -$parameters=array('arrayfields'=>$arrayfields, 'sql'=>$sql); -$reshook=$hookmanager->executeHooks('printFieldListFooter', $parameters, $object); // Note that $action and $object may have been modified by hook +$parameters = array('arrayfields'=>$arrayfields, 'sql'=>$sql); +$reshook = $hookmanager->executeHooks('printFieldListFooter', $parameters, $object); // Note that $action and $object may have been modified by hook print $hookmanager->resPrint; print '
    '; - $formTicket->selectTypesTickets(dol_escape_htmltag($search[$key]), 'search_'.$key.'', '', 2, 1, 1, 0, ($val['css']?$val['css']:'maxwidth150')); + print ''; + $formTicket->selectTypesTickets(dol_escape_htmltag($search[$key]), 'search_'.$key.'', '', 2, 1, 1, 0, ($val['css'] ? $val['css'] : 'maxwidth150')); print ''; - $formTicket->selectGroupTickets(dol_escape_htmltag($search[$key]), 'search_'.$key.'', '', 2, 1, 1, 0, ($val['css']?$val['css']:'maxwidth150')); + print ''; + $formTicket->selectGroupTickets(dol_escape_htmltag($search[$key]), 'search_'.$key.'', '', 2, 1, 1, 0, ($val['css'] ? $val['css'] : 'maxwidth150')); print ''; - $formTicket->selectSeveritiesTickets(dol_escape_htmltag($search[$key]), 'search_'.$key.'', '', 2, 1, 1, 0, ($val['css']?$val['css']:'maxwidth150')); + print ''; + $formTicket->selectSeveritiesTickets(dol_escape_htmltag($search[$key]), 'search_'.$key.'', '', 2, 1, 1, 0, ($val['css'] ? $val['css'] : 'maxwidth150')); print ''; - print $form->select_dolusers($search[$key], 'search_'.$key, 1, null, 0, '', '', '0', 0, 0, '', 0, '', ($val['css']?$val['css']:'maxwidth150')); + print ''; + print $form->select_dolusers($search[$key], 'search_'.$key, 1, null, 0, '', '', '0', 0, 0, '', 0, '', ($val['css'] ? $val['css'] : 'maxwidth150')); print ''; + print ''; //var_dump($arrayofstatus);var_dump($search['fk_statut']);var_dump(array_values($search[$key])); $selectedarray = null; if ($search[$key]) $selectedarray = array_values($search[$key]); @@ -555,10 +555,10 @@ foreach($object->fields as $key => $val) } elseif ($key == "fk_soc") { - print ''; -$searchpicto=$form->showFilterButtons(); +$searchpicto = $form->showFilterButtons(); print $searchpicto; print '
    '.$langs->trans("NoRecordFound").'
    '."\n"; @@ -714,19 +714,19 @@ print ''."\n"; if (in_array('builddoc', $arrayofmassactions) && ($nbtotalofrecords === '' || $nbtotalofrecords)) { - $hidegeneratedfilelistifempty=1; - if ($massaction == 'builddoc' || $action == 'remove_file' || $show_files) $hidegeneratedfilelistifempty=0; + $hidegeneratedfilelistifempty = 1; + 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); // Show list of available documents - $urlsource=$_SERVER['PHP_SELF'].'?sortfield='.$sortfield.'&sortorder='.$sortorder; - $urlsource.=str_replace('&', '&', $param); + $urlsource = $_SERVER['PHP_SELF'].'?sortfield='.$sortfield.'&sortorder='.$sortorder; + $urlsource .= str_replace('&', '&', $param); - $filedir=$diroutputmassaction; - $genallowed=$user->rights->ticket->read; - $delallowed=$user->rights->ticket->write; + $filedir = $diroutputmassaction; + $genallowed = $user->rights->ticket->read; + $delallowed = $user->rights->ticket->write; print $formfile->showdocuments('massfilesarea_ticket', '', $filedir, $urlsource, 0, $delallowed, '', 1, 1, 0, 48, 1, $param, $title, '', '', '', null, $hidegeneratedfilelistifempty); } diff --git a/htdocs/ticket/messaging.php b/htdocs/ticket/messaging.php index 11bd501bd17..da7bf1aaadc 100644 --- a/htdocs/ticket/messaging.php +++ b/htdocs/ticket/messaging.php @@ -22,13 +22,13 @@ */ require '../main.inc.php'; -require_once DOL_DOCUMENT_ROOT . '/ticket/class/actions_ticket.class.php'; -require_once DOL_DOCUMENT_ROOT . '/core/class/html.formticket.class.php'; -require_once DOL_DOCUMENT_ROOT . '/core/lib/ticket.lib.php'; -require_once DOL_DOCUMENT_ROOT . "/core/lib/company.lib.php"; -require_once DOL_DOCUMENT_ROOT . '/core/lib/date.lib.php'; -require_once DOL_DOCUMENT_ROOT . '/core/class/extrafields.class.php'; -require_once DOL_DOCUMENT_ROOT . '/contact/class/contact.class.php'; +require_once DOL_DOCUMENT_ROOT.'/ticket/class/actions_ticket.class.php'; +require_once DOL_DOCUMENT_ROOT.'/core/class/html.formticket.class.php'; +require_once DOL_DOCUMENT_ROOT.'/core/lib/ticket.lib.php'; +require_once DOL_DOCUMENT_ROOT."/core/lib/company.lib.php"; +require_once DOL_DOCUMENT_ROOT.'/core/lib/date.lib.php'; +require_once DOL_DOCUMENT_ROOT.'/core/class/extrafields.class.php'; +require_once DOL_DOCUMENT_ROOT.'/contact/class/contact.class.php'; // Load translation files required by the page $langs->loadLangs(array('companies', 'other', 'ticket')); @@ -40,28 +40,28 @@ $track_id = GETPOST('track_id', 'alpha', 3); $socid = GETPOST('socid', 'int'); $action = GETPOST('action', 'aZ09'); -$limit = GETPOST('limit', 'int')?GETPOST('limit', 'int'):$conf->liste_limit; +$limit = GETPOST('limit', 'int') ?GETPOST('limit', 'int') : $conf->liste_limit; $sortfield = GETPOST("sortfield", "alpha"); $sortorder = GETPOST("sortorder"); $page = GETPOST("page"); $page = is_numeric($page) ? $page : 0; $page = $page == -1 ? 0 : $page; -if (! $sortfield) $sortfield="a.datep,a.id"; -if (! $sortorder) $sortorder="desc"; -$offset = $limit * $page ; +if (!$sortfield) $sortfield = "a.datep,a.id"; +if (!$sortorder) $sortorder = "desc"; +$offset = $limit * $page; $pageprev = $page - 1; $pagenext = $page + 1; if (GETPOST('actioncode', 'array')) { - $actioncode=GETPOST('actioncode', 'array', 3); - if (! count($actioncode)) $actioncode='0'; + $actioncode = GETPOST('actioncode', 'array', 3); + 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)); + $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'); +$search_agenda_label = GETPOST('search_agenda_label'); $object = new Ticket($db); $object->fetch($id, $ref, $track_id); @@ -99,11 +99,11 @@ if (!$user->socid && ($conf->global->TICKET_LIMIT_VIEW_ASSIGNED_ONLY && $object- * Actions */ -$parameters=array('id'=>$socid); -$reshook=$hookmanager->executeHooks('doActions', $parameters, $object, $action); // Note that $action and $object may have been modified by some hooks +$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(empty($reshook)) +if (empty($reshook)) { // Set view style $_SESSION['ticket-view-type'] = "messaging"; @@ -112,8 +112,8 @@ if(empty($reshook)) // 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 { - $actioncode=''; - $search_agenda_label=''; + $actioncode = ''; + $search_agenda_label = ''; } @@ -126,8 +126,8 @@ $form = new Form($db); $userstat = new User($db); $formticket = new FormTicket($db); -$title=$langs->trans("Ticket").' - '.$object->ref.' '.$object->name; -if (! empty($conf->global->MAIN_HTML_TITLE) && preg_match('/ticketnameonly/', $conf->global->MAIN_HTML_TITLE) && $object->name) $title=$object->ref.' '.$object->name.' - '.$langs->trans("Info"); +$title = $langs->trans("Ticket").' - '.$object->ref.' '.$object->name; +if (!empty($conf->global->MAIN_HTML_TITLE) && preg_match('/ticketnameonly/', $conf->global->MAIN_HTML_TITLE) && $object->name) $title = $object->ref.' '.$object->name.' - '.$langs->trans("Info"); $help_url = 'FR:DocumentationModuleTicket'; llxHeader('', $title, $help_url); @@ -143,19 +143,19 @@ if ($socid > 0) { } if (!$user->socid && $conf->global->TICKET_LIMIT_VIEW_ASSIGNED_ONLY) { - $object->next_prev_filter = "te.fk_user_assign = '" . $user->id . "'"; + $object->next_prev_filter = "te.fk_user_assign = '".$user->id."'"; } elseif ($user->socid > 0) { - $object->next_prev_filter = "te.fk_soc = '" . $user->socid . "'"; + $object->next_prev_filter = "te.fk_soc = '".$user->socid."'"; } $head = ticket_prepare_head($object); dol_fiche_head($head, 'tabTicketLogs', $langs->trans("Ticket"), 0, 'ticket'); -$morehtmlref ='
    '; -$morehtmlref.= $object->subject; +$morehtmlref = '
    '; +$morehtmlref .= $object->subject; // Author if ($object->fk_user_create > 0) { - $morehtmlref .= '
    ' . $langs->trans("CreatedBy") . ' : '; + $morehtmlref .= '
    '.$langs->trans("CreatedBy").' : '; $langs->load("users"); $fuser = new User($db); @@ -228,31 +228,31 @@ print '
    '; 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; + $param = '&id='.$object->id; + if (!empty($contextpage) && $contextpage != $_SERVER["PHP_SELF"]) $param .= '&contextpage='.$contextpage; + if ($limit > 0 && $limit != $conf->liste_limit) $param .= '&limit='.$limit; $morehtmlright = ''; - $messagingUrl = DOL_URL_ROOT.'/ticket/agenda.php?track_id=' . $object->track_id; + $messagingUrl = DOL_URL_ROOT.'/ticket/agenda.php?track_id='.$object->track_id; $morehtmlright .= dolGetButtonTitle($langs->trans('MessageListViewType'), '', 'fa fa-list-alt imgforviewmode', $messagingUrl, '', 1); // Show link to add a message (if read and not closed) $btnstatus = $object->fk_statut < Ticket::STATUS_CLOSED && $action != "presend" && $action != "presend_addmessage"; - $url = 'card.php?track_id=' . $object->track_id . '&action=presend_addmessage&mode=init'; + $url = 'card.php?track_id='.$object->track_id.'&action=presend_addmessage&mode=init'; $morehtmlright .= dolGetButtonTitle($langs->trans('TicketAddMessage'), '', 'fa fa-comment-dots', $url, 'add-new-ticket-title-button', $btnstatus); // Show link to add event (if read and not closed) $btnstatus = $object->fk_statut < Ticket::STATUS_CLOSED && $action != "presend" && $action != "presend_addmessage"; - $url = dol_buildpath('/comm/action/card.php', 1).'?action=create&datep='.date('YmdHi').'&origin=ticket&originid='.$object->id.'&projectid='.$object->fk_project.'&backtopage='.urlencode($_SERVER["PHP_SELF"].'?track_id=' . $object->track_id); + $url = dol_buildpath('/comm/action/card.php', 1).'?action=create&datep='.date('YmdHi').'&origin=ticket&originid='.$object->id.'&projectid='.$object->fk_project.'&backtopage='.urlencode($_SERVER["PHP_SELF"].'?track_id='.$object->track_id); $morehtmlright .= dolGetButtonTitle($langs->trans('AddAction'), '', 'fa fa-plus-circle', $url, 'add-new-ticket-even-button', $btnstatus); print_barre_liste($langs->trans("ActionsOnTicket"), 0, $_SERVER["PHP_SELF"], '', $sortfield, $sortorder, '', 0, -1, '', 0, $morehtmlright, '', 0, 1, 1); // List of all actions - $filters=array(); - $filters['search_agenda_label']=$search_agenda_label; + $filters = array(); + $filters['search_agenda_label'] = $search_agenda_label; show_ticket_messaging($conf, $langs, $db, $object, null, 0, $actioncode, '', $filters, $sortfield, $sortorder); } diff --git a/htdocs/ticket/stats/index.php b/htdocs/ticket/stats/index.php index a6baeef7c06..588b645710a 100644 --- a/htdocs/ticket/stats/index.php +++ b/htdocs/ticket/stats/index.php @@ -230,7 +230,7 @@ print '
    '; print ''; -print ''; +print '
    '; print ''; // Company print ''; - print ''; print '
    '.$langs->trans("Filter").'
    '.$langs->trans("ThirdParty").''; diff --git a/htdocs/user/bank.php b/htdocs/user/bank.php index b24b6db9381..9df1afb01de 100644 --- a/htdocs/user/bank.php +++ b/htdocs/user/bank.php @@ -32,9 +32,9 @@ require_once DOL_DOCUMENT_ROOT.'/core/lib/usergroups.lib.php'; require_once DOL_DOCUMENT_ROOT.'/core/lib/bank.lib.php'; require_once DOL_DOCUMENT_ROOT.'/core/lib/date.lib.php'; require_once DOL_DOCUMENT_ROOT.'/user/class/userbankaccount.class.php'; -if (! empty($conf->holiday->enabled)) require_once DOL_DOCUMENT_ROOT.'/holiday/class/holiday.class.php'; -if (! empty($conf->expensereport->enabled)) require_once DOL_DOCUMENT_ROOT.'/expensereport/class/expensereport.class.php'; -if (! empty($conf->salaries->enabled)) require_once DOL_DOCUMENT_ROOT.'/salaries/class/paymentsalary.class.php'; +if (!empty($conf->holiday->enabled)) require_once DOL_DOCUMENT_ROOT.'/holiday/class/holiday.class.php'; +if (!empty($conf->expensereport->enabled)) require_once DOL_DOCUMENT_ROOT.'/expensereport/class/expensereport.class.php'; +if (!empty($conf->salaries->enabled)) require_once DOL_DOCUMENT_ROOT.'/salaries/class/paymentsalary.class.php'; // Load translation files required by page $langs->loadLangs(array('companies', 'commercial', 'banks', 'bills', 'trips', 'holiday', 'salaries')); @@ -45,23 +45,23 @@ $action = GETPOST("action", 'alpha'); $cancel = GETPOST('cancel', 'alpha'); // Security check -$socid=0; +$socid = 0; if ($user->socid > 0) $socid = $user->socid; -$feature2 = (($socid && $user->rights->user->self->creer)?'':'user'); +$feature2 = (($socid && $user->rights->user->self->creer) ? '' : 'user'); // Ok if user->rights->salaries->read or user->rights->hrm->read //$result = restrictedArea($user, 'salaries|hrm', $id, 'user&user', $feature2); -$ok=false; -if ($user->id == $id) $ok=true; // A user can always read its own card -if (! empty($user->rights->salaries->read)) $ok=true; -if (! empty($user->rights->hrm->read)) $ok=true; -if (! empty($user->rights->expensereport->lire) && ($user->id == $object->id || $user->rights->expensereport->readall)) $ok=true; -if (! $ok) +$ok = false; +if ($user->id == $id) $ok = true; // A user can always read its own card +if (!empty($user->rights->salaries->read)) $ok = true; +if (!empty($user->rights->hrm->read)) $ok = true; +if (!empty($user->rights->expensereport->lire) && ($user->id == $object->id || $user->rights->expensereport->readall)) $ok = true; +if (!$ok) { accessforbidden(); } $object = new User($db); -if ($id > 0 || ! empty($ref)) +if ($id > 0 || !empty($ref)) { $result = $object->fetch($id, $ref, '', 1); $object->getrights(); @@ -72,7 +72,7 @@ if ($id > 0 || ! empty($ref)) * Actions */ -if ($action == 'add' && ! $cancel) +if ($action == 'add' && !$cancel) { // Modification $account = new UserBankAccount($db); @@ -94,10 +94,10 @@ if ($action == 'add' && ! $cancel) $result = $account->create($user); - if (! $result) + if (!$result) { setEventMessages($account->error, $account->errors, 'errors'); - $action='edit'; // Force chargement page edition + $action = 'edit'; // Force chargement page edition } else { @@ -106,14 +106,14 @@ if ($action == 'add' && ! $cancel) } } -if ($action == 'update' && ! $cancel) +if ($action == 'update' && !$cancel) { // Modification $account = new UserBankAccount($db); $account->fetch($bankid); - $account->userid = $object->id; + $account->userid = $object->id; $account->bank = GETPOST('bank', 'alpha'); $account->label = GETPOST('label', 'alpha'); @@ -130,10 +130,10 @@ if ($action == 'update' && ! $cancel) $result = $account->update($user); - if (! $result) + if (!$result) { setEventMessages($account->error, $account->errors, 'errors'); - $action='edit'; // Force chargement page edition + $action = 'edit'; // Force chargement page edition } else { @@ -154,7 +154,7 @@ llxHeader(null, $langs->trans("BankAccounts")); $head = user_prepare_head($object); $account = new UserBankAccount($db); -if (! $bankid) +if (!$bankid) { $account->fetch(0, '', $id); } @@ -162,7 +162,7 @@ else { $account->fetch($bankid); } -if (empty($account->userid)) $account->userid=$object->id; +if (empty($account->userid)) $account->userid = $object->id; if ($id && $bankid && $action == 'edit' && $user->rights->user->user->creer) @@ -239,9 +239,9 @@ if ($action != 'edit' && $action != 'create') // If not bank account yet, $acco } print '
    '.$langs->trans("IBAN").''.$account->iban . ' '; - if (! empty($account->iban)) { - if (! checkIbanForAccount($account)) { + print ''.$account->iban.' '; + if (!empty($account->iban)) { + if (!checkIbanForAccount($account)) { print img_picto($langs->trans("IbanNotValid"), 'warning'); } else { print img_picto($langs->trans("IbanValid"), 'info'); @@ -251,8 +251,8 @@ if ($action != 'edit' && $action != 'create') // If not bank account yet, $acco print '
    '.$langs->trans("BIC").''.$account->bic.' '; - if (! empty($account->bic)) { - if (! checkSwiftForAccount($account)) { + if (!empty($account->bic)) { + if (!checkSwiftForAccount($account)) { print img_picto($langs->trans("SwiftNotValid"), 'warning'); } else { print img_picto($langs->trans("SwiftValid"), 'info'); @@ -275,7 +275,7 @@ if ($action != 'edit' && $action != 'create') // If not bank account yet, $acco print '
    '; // Check BBAN - if ($account->label && ! checkBanForAccount($account)) + if ($account->label && !checkBanForAccount($account)) { print '
    '.$langs->trans("RIBControlError").'
    '; } @@ -283,32 +283,32 @@ if ($action != 'edit' && $action != 'create') // If not bank account yet, $acco print '
    '; // Nbre max d'elements des petites listes - $MAXLIST=$conf->global->MAIN_SIZE_SHORTLIST_LIMIT; + $MAXLIST = $conf->global->MAIN_SIZE_SHORTLIST_LIMIT; /* * Last salaries */ - if (! empty($conf->salaries->enabled) && + if (!empty($conf->salaries->enabled) && ($user->rights->salaries->read && $object->id == $user->id) ) { $salary = new PaymentSalary($db); $sql = "SELECT ps.rowid, ps.datesp, ps.dateep, ps.amount"; - $sql.= " FROM ".MAIN_DB_PREFIX."payment_salary as ps"; - $sql.= " WHERE ps.fk_user = ".$object->id; - $sql.= " AND ps.entity = ".$conf->entity; - $sql.= " ORDER BY ps.datesp DESC"; + $sql .= " FROM ".MAIN_DB_PREFIX."payment_salary as ps"; + $sql .= " WHERE ps.fk_user = ".$object->id; + $sql .= " AND ps.entity = ".$conf->entity; + $sql .= " ORDER BY ps.datesp DESC"; - $resql=$db->query($sql); + $resql = $db->query($sql); if ($resql) { $num = $db->num_rows($resql); - print ''; + print '
    '; print ''; - print '
    '; + print ''; print ''; @@ -342,19 +342,19 @@ if ($action != 'edit' && $action != 'create') // If not bank account yet, $acco /* * Last holidays */ - if (! empty($conf->holiday->enabled) && + if (!empty($conf->holiday->enabled) && ($user->rights->holiday->read_all || ($user->rights->holiday->read && $object->id == $user->id)) ) { $holiday = new Holiday($db); $sql = "SELECT h.rowid, h.statut, h.fk_type, h.date_debut, h.date_fin, h.halfday"; - $sql.= " FROM ".MAIN_DB_PREFIX."holiday as h"; - $sql.= " WHERE h.fk_user = ".$object->id; - $sql.= " AND h.entity = ".$conf->entity; - $sql.= " ORDER BY h.date_debut DESC"; + $sql .= " FROM ".MAIN_DB_PREFIX."holiday as h"; + $sql .= " WHERE h.fk_user = ".$object->id; + $sql .= " AND h.entity = ".$conf->entity; + $sql .= " ORDER BY h.date_debut DESC"; - $resql=$db->query($sql); + $resql = $db->query($sql); if ($resql) { $num = $db->num_rows($resql); @@ -362,7 +362,7 @@ if ($action != 'edit' && $action != 'create') // If not bank account yet, $acco print '
    '.$langs->trans("LastSalaries", ($num<=$MAXLIST?"":$MAXLIST)).''.$langs->trans("AllSalaries").''.$num.''; print '
    '.$langs->trans("LastSalaries", ($num <= $MAXLIST ? "" : $MAXLIST)).''.$langs->trans("AllSalaries").''.$num.'
    '; print ''; - print '
    '; + print ''; print ''; @@ -376,7 +376,7 @@ if ($action != 'edit' && $action != 'create') // If not bank account yet, $acco $holiday->id = $objp->rowid; $holiday->ref = $objp->rowid; $holiday->fk_type = $objp->fk_type; - $nbopenedday=num_open_day($db->jdate($objp->date_debut), $db->jdate($objp->date_fin), 0, 1, $objp->halfday); + $nbopenedday = num_open_day($db->jdate($objp->date_debut), $db->jdate($objp->date_fin), 0, 1, $objp->halfday); print $holiday->getNomUrl(1); print '\n"; @@ -398,19 +398,19 @@ if ($action != 'edit' && $action != 'create') // If not bank account yet, $acco /* * Last expense report */ - if (! empty($conf->expensereport->enabled) && + if (!empty($conf->expensereport->enabled) && ($user->rights->expensereport->readall || ($user->rights->expensereport->lire && $object->id == $user->id)) ) { $exp = new ExpenseReport($db); $sql = "SELECT e.rowid, e.ref, e.fk_statut, e.date_debut, e.total_ttc"; - $sql.= " FROM ".MAIN_DB_PREFIX."expensereport as e"; - $sql.= " WHERE e.fk_user_author = ".$object->id; - $sql.= " AND e.entity = ".$conf->entity; - $sql.= " ORDER BY e.date_debut DESC"; + $sql .= " FROM ".MAIN_DB_PREFIX."expensereport as e"; + $sql .= " WHERE e.fk_user_author = ".$object->id; + $sql .= " AND e.entity = ".$conf->entity; + $sql .= " ORDER BY e.date_debut DESC"; - $resql=$db->query($sql); + $resql = $db->query($sql); if ($resql) { $num = $db->num_rows($resql); @@ -418,7 +418,7 @@ if ($action != 'edit' && $action != 'create') // If not bank account yet, $acco print '
    '.$langs->trans("LastHolidays", ($num<=$MAXLIST?"":$MAXLIST)).''.$langs->trans("AllHolidays").''.$num.''; print '
    '.$langs->trans("LastHolidays", ($num <= $MAXLIST ? "" : $MAXLIST)).''.$langs->trans("AllHolidays").''.$num.'
    '.dol_print_date($db->jdate($objp->date_debut), 'day')."
    '; print ''; - print ''; print ''; print ''; // Firstname print ''; print ''; // Login print ''; print ''; - $generated_password=''; + $generated_password = ''; if (empty($ldap_sid)) // ldap_sid is for activedirectory { require_once DOL_DOCUMENT_ROOT.'/core/lib/security2.lib.php'; - $generated_password=getRandomPassword(false); + $generated_password = getRandomPassword(false); } - $password=$generated_password; + $password=(GETPOSTISSET('password')?GETPOST('password'):$generated_password); // Password print ''; print ''; - if (! empty($conf->api->enabled)) + if (!empty($conf->api->enabled)) { // API key $generated_api_key = ''; require_once DOL_DOCUMENT_ROOT.'/core/lib/security2.lib.php'; - $generated_password=getRandomPassword(false); + $generated_password = getRandomPassword(false); print ''; print ''; } @@ -905,20 +905,20 @@ if ($action == 'create' || $action == 'adduserldap') { require_once DOL_DOCUMENT_ROOT.'/core/lib/security2.lib.php'; // PARTIAL WORKAROUND - $generated_fake_api_key=getRandomPassword(false); + $generated_fake_api_key = getRandomPassword(false); print ''; } // Administrator - if (! empty($user->admin)) + if (!empty($user->admin)) { print ''; print '\n"; @@ -962,15 +962,15 @@ if ($action == 'create' || $action == 'adduserldap') // Gender print ''; print ''; // Employee - $defaultemployee=1; + $defaultemployee = 1; print ''; print ''; // Hierarchy @@ -981,7 +981,7 @@ if ($action == 'create' || $action == 'adduserldap') print "\n"; // Expense report validator - if(!empty($conf->expensereport->enabled)) + if (!empty($conf->expensereport->enabled)) { print ''; // Town print ''; // Country print ''; @@ -1043,65 +1043,65 @@ if ($action == 'create' || $action == 'adduserldap') // Tel print ''; print ''; // Tel portable print ''; print ''; // Fax print ''; print ''; // EMail - print 'global->USER_MAIL_REQUIRED)?' class="fieldrequired"':'').'>'.img_picto('', 'object_email').' '.$langs->trans("EMail").''; + print 'global->USER_MAIL_REQUIRED) ? ' class="fieldrequired"' : '').'>'.img_picto('', 'object_email').' '.$langs->trans("EMail").''; print ''; - if (! empty($conf->socialnetworks->enabled)) { + if (!empty($conf->socialnetworks->enabled)) { foreach ($socialnetworks as $key => $value) { if ($value['active']) { print ''; print ''; } else { // if social network is not active but value exist we do not want to loose it - if (! empty($ldap_social[$key])) { + if (!empty($ldap_social[$key])) { print ''; } else { print ''; @@ -1191,35 +1191,35 @@ if ($action == 'create' || $action == 'adduserldap') { print ''; print ''; } // User color - if (! empty($conf->agenda->enabled)) + if (!empty($conf->agenda->enabled)) { print ''; print ''; } // Categories - if (! empty($conf->categorie->enabled) && ! empty($user->rights->categorie->lire)) + if (!empty($conf->categorie->enabled) && !empty($user->rights->categorie->lire)) { - print '"; } // Multicompany - if (! empty($conf->multicompany->enabled) && is_object($mc)) + if (!empty($conf->multicompany->enabled) && is_object($mc)) { // This is now done with hook formObjectOptions. Keep this code for backward compatibility with old multicompany module - if (! method_exists($mc, 'formObjectOptions')) + if (!method_exists($mc, 'formObjectOptions')) { - if (empty($conf->global->MULTICOMPANY_TRANSVERSE_MODE) && $conf->entity == 1 && $user->admin && ! $user->entity) // condition must be same for create and edit mode + if (empty($conf->global->MULTICOMPANY_TRANSVERSE_MODE) && $conf->entity == 1 && $user->admin && !$user->entity) // condition must be same for create and edit mode { print "".''; print "\n"; @@ -1254,7 +1254,7 @@ if ($action == 'create' || $action == 'adduserldap') print ''; print ''; @@ -1265,7 +1265,7 @@ if ($action == 'create' || $action == 'adduserldap') // TODO Move this into tab RH (HierarchicalResponsible must be on both tab) // Default warehouse - if (! empty($conf->stock->enabled) && ! empty($conf->global->USER_DEFAULT_WAREHOUSE)) // TODO What is goal of this. How it is used ? + if (!empty($conf->stock->enabled) && !empty($conf->global->USER_DEFAULT_WAREHOUSE)) // TODO What is goal of this. How it is used ? { print ''; print ''; - if ((! empty($conf->salaries->enabled) && ! empty($user->rights->salaries->read)) - || (! empty($conf->hrm->enabled) && ! empty($user->rights->hrm->employee->read))) + if ((!empty($conf->salaries->enabled) && !empty($user->rights->salaries->read)) + || (!empty($conf->hrm->enabled) && !empty($user->rights->hrm->employee->read))) { $langs->load("salaries"); // THM print ''; print ''; print "\n"; // TJM print ''; print ''; print "\n"; // Salary print ''; print ''; print "\n"; } @@ -1314,7 +1314,7 @@ if ($action == 'create' || $action == 'adduserldap') // Weeklyhours print ''; print ''; print "\n"; @@ -1363,7 +1363,7 @@ else { $object->fetch($id, '', '', 1); if ($res < 0) { dol_print_error($db, $object->error); exit; } - $res=$object->fetch_optionals(); + $res = $object->fetch_optionals(); // Check if user has rights if (empty($conf->global->MULTICOMPANY_TRANSVERSE_MODE)) @@ -1374,15 +1374,15 @@ else // Connexion ldap // pour recuperer passDoNotExpire et userChangePassNextLogon - if (! empty($conf->ldap->enabled) && ! empty($object->ldap_sid)) + if (!empty($conf->ldap->enabled) && !empty($object->ldap_sid)) { $ldap = new Ldap(); - $result=$ldap->connect_bind(); + $result = $ldap->connect_bind(); if ($result > 0) { $userSearchFilter = '('.$conf->global->LDAP_FILTER_CONNECTION.'('.$ldap->getUserIdentifier().'='.$object->login.'))'; $entries = $ldap->fetch($object->login, $userSearchFilter); - if (! $entries) + if (!$entries) { setEventMessages($ldap->error, $ldap->errors, 'errors'); } @@ -1492,7 +1492,7 @@ else // Login print ''; - if (! empty($object->ldap_sid) && $object->statut==0) + if (!empty($object->ldap_sid) && $object->statut == 0) { print ''; } @@ -1506,68 +1506,68 @@ else print ''; print '"; print ''."\n"; // API key - if (! empty($conf->api->enabled) && $user->admin) { + if (!empty($conf->api->enabled) && $user->admin) { print ''; print ''; } // Administrator print ''."\n"; @@ -1618,7 +1618,7 @@ else print ''; print ''; print '\n"; // Default warehouse - if (! empty($conf->stock->enabled) && ! empty($conf->global->USER_DEFAULT_WAREHOUSE)) // TODO What is goal of this. How it is used ? + if (!empty($conf->stock->enabled) && !empty($conf->global->USER_DEFAULT_WAREHOUSE)) // TODO What is goal of this. How it is used ? { - require_once DOL_DOCUMENT_ROOT .'/product/stock/class/entrepot.class.php'; - $warehousestatic=new Entrepot($db); + require_once DOL_DOCUMENT_ROOT.'/product/stock/class/entrepot.class.php'; + $warehousestatic = new Entrepot($db); $warehousestatic->fetch($object->fk_warehouse); print ''; print ''; print "\n"; // TJM print ''; print ''; print "\n"; // Salary print ''; print ''; print "\n"; } @@ -1750,7 +1750,7 @@ else print '
    '; + print ''; print ''; @@ -472,7 +472,7 @@ if ($action != 'edit' && $action != 'create') // If not bank account yet, $acco } // Edit -if ($id && ($action == 'edit' || $action == 'create' ) && $user->rights->user->user->creer) +if ($id && ($action == 'edit' || $action == 'create') && $user->rights->user->user->creer) { $title = $langs->trans("User"); dol_fiche_head($head, 'bank', $title, 0, 'user'); diff --git a/htdocs/user/card.php b/htdocs/user/card.php index f689cdc71d4..1430ccc8483 100644 --- a/htdocs/user/card.php +++ b/htdocs/user/card.php @@ -45,50 +45,50 @@ require_once DOL_DOCUMENT_ROOT.'/core/lib/usergroups.lib.php'; require_once DOL_DOCUMENT_ROOT.'/core/class/extrafields.class.php'; require_once DOL_DOCUMENT_ROOT.'/core/class/html.formcompany.class.php'; require_once DOL_DOCUMENT_ROOT.'/core/class/html.formother.class.php'; -if (! empty($conf->ldap->enabled)) require_once DOL_DOCUMENT_ROOT.'/core/class/ldap.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->stock->enabled)) require_once DOL_DOCUMENT_ROOT.'/product/class/html.formproduct.class.php'; +if (!empty($conf->ldap->enabled)) require_once DOL_DOCUMENT_ROOT.'/core/class/ldap.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->stock->enabled)) require_once DOL_DOCUMENT_ROOT.'/product/class/html.formproduct.class.php'; -$id = GETPOST('id', 'int'); +$id = GETPOST('id', 'int'); $action = GETPOST('action', 'aZ09'); -$mode = GETPOST('mode', 'alpha'); +$mode = GETPOST('mode', 'alpha'); $confirm = GETPOST('confirm', 'alpha'); -$group = GETPOST("group", "int", 3); +$group = GETPOST("group", "int", 3); $cancel = GETPOST('cancel', 'alpha'); -$contextpage= GETPOST('contextpage', 'aZ')?GETPOST('contextpage', 'aZ'):'useracard'; // To manage different context of search +$contextpage = GETPOST('contextpage', 'aZ') ?GETPOST('contextpage', 'aZ') : 'useracard'; // To manage different context of search // Define value to know what current user can do on users -$canadduser=(! empty($user->admin) || $user->rights->user->user->creer); -$canreaduser=(! empty($user->admin) || $user->rights->user->user->lire); -$canedituser=(! empty($user->admin) || $user->rights->user->user->creer); -$candisableuser=(! empty($user->admin) || $user->rights->user->user->supprimer); -$canreadgroup=$canreaduser; -$caneditgroup=$canedituser; -if (! empty($conf->global->MAIN_USE_ADVANCED_PERMS)) +$canadduser = (!empty($user->admin) || $user->rights->user->user->creer); +$canreaduser = (!empty($user->admin) || $user->rights->user->user->lire); +$canedituser = (!empty($user->admin) || $user->rights->user->user->creer); +$candisableuser = (!empty($user->admin) || $user->rights->user->user->supprimer); +$canreadgroup = $canreaduser; +$caneditgroup = $canedituser; +if (!empty($conf->global->MAIN_USE_ADVANCED_PERMS)) { - $canreadgroup=(! empty($user->admin) || $user->rights->user->group_advance->read); - $caneditgroup=(! empty($user->admin) || $user->rights->user->group_advance->write); + $canreadgroup = (!empty($user->admin) || $user->rights->user->group_advance->read); + $caneditgroup = (!empty($user->admin) || $user->rights->user->group_advance->write); } // Define value to know what current user can do on properties of edited user if ($id) { // $user est le user qui edite, $id est l'id de l'utilisateur edite - $caneditfield=((($user->id == $id) && $user->rights->user->self->creer) + $caneditfield = ((($user->id == $id) && $user->rights->user->self->creer) || (($user->id != $id) && $user->rights->user->user->creer)); - $caneditpassword=((($user->id == $id) && $user->rights->user->self->password) + $caneditpassword = ((($user->id == $id) && $user->rights->user->self->password) || (($user->id != $id) && $user->rights->user->user->password)); } // Security check -$socid=0; +$socid = 0; if ($user->socid > 0) $socid = $user->socid; -$feature2='user'; +$feature2 = 'user'; $result = restrictedArea($user, 'user', $id, 'user&user', $feature2); -if ($user->id <> $id && ! $canreaduser) accessforbidden(); +if ($user->id <> $id && !$canreaduser) accessforbidden(); // Load translation files required by page $langs->loadLangs(array('users', 'companies', 'ldap', 'admin', 'hrm', 'stocks')); @@ -109,8 +109,8 @@ $hookmanager->initHooks(array('usercard', 'globalcard')); /** * Actions */ -$parameters=array('id' => $id, 'socid' => $socid, 'group' => $group, 'caneditgroup' => $caneditgroup); -$reshook=$hookmanager->executeHooks('doActions', $parameters, $object, $action); // Note that $action and $object may have been modified by some hooks +$parameters = array('id' => $id, 'socid' => $socid, 'group' => $group, 'caneditgroup' => $caneditgroup); +$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)) { @@ -131,7 +131,7 @@ if (empty($reshook)) { if (!empty($conf->file->main_limit_users)) { $nb = $object->getNbOfUsers("active"); if ($nb >= $conf->file->main_limit_users) { - $error ++; + $error++; setEventMessages($langs->trans("YourQuotaOfUsersIsReached"), null, 'errors'); } } @@ -148,7 +148,7 @@ if (empty($reshook)) { { if ($id <> $user->id) { - if (! GETPOSTISSET('token')) + if (!GETPOSTISSET('token')) { print 'Error, token required for this critical operation'; exit; @@ -175,22 +175,22 @@ if (empty($reshook)) { $error = 0; if (!$_POST["lastname"]) { - $error ++; + $error++; setEventMessages($langs->trans("NameNotDefined"), null, 'errors'); - $action = "create"; // Go back to create page + $action = "create"; // Go back to create page } if (!$_POST["login"]) { - $error ++; + $error++; setEventMessages($langs->trans("LoginNotDefined"), null, 'errors'); - $action = "create"; // Go back to create page + $action = "create"; // Go back to create page } if (!empty($conf->file->main_limit_users)) { // If option to limit users is set $nb = $object->getNbOfUsers("active"); if ($nb >= $conf->file->main_limit_users) { - $error ++; + $error++; setEventMessages($langs->trans("YourQuotaOfUsersIsReached"), null, 'errors'); - $action = "create"; // Go back to create page + $action = "create"; // Go back to create page } } @@ -217,7 +217,7 @@ if (empty($reshook)) { //$object->facebook = GETPOST("facebook", 'alphanohtml'); //$object->linkedin = GETPOST("linkedin", 'alphanohtml'); $object->socialnetworks = array(); - if (! empty($conf->socialnetworks->enabled)) { + if (!empty($conf->socialnetworks->enabled)) { foreach ($socialnetworks as $key => $value) { $object->socialnetworks[$key] = GETPOST($key, 'alphanohtml'); } @@ -252,16 +252,16 @@ if (empty($reshook)) { // Fill array 'array_options' with data from add form $ret = $extrafields->setOptionalsFromPost(null, $object); if ($ret < 0) { - $error ++; + $error++; } // Set entity property $entity = GETPOST('entity', 'int'); - if (! empty($conf->multicompany->enabled)) { + if (!empty($conf->multicompany->enabled)) { if (GETPOST('superadmin', 'int')) { $object->entity = 0; } else { - if (! empty($conf->global->MULTICOMPANY_TRANSVERSE_MODE)) { + if (!empty($conf->global->MULTICOMPANY_TRANSVERSE_MODE)) { $object->entity = 1; // all users are forced into master entity } else { $object->entity = ($entity == '' ? 1 : $entity); @@ -281,7 +281,7 @@ if (empty($reshook)) { if (GETPOST('password')) { $object->setPassword($user, GETPOST('password')); } - if (! empty($conf->categorie->enabled)) { + if (!empty($conf->categorie->enabled)) { // Categories association $usercats = GETPOST('usercats', 'array'); $object->setCategories($usercats); @@ -296,7 +296,7 @@ if (empty($reshook)) { $langs->load("errors"); $db->rollback(); setEventMessages($object->error, $object->errors, 'errors'); - $action = "create"; // Go back to create page + $action = "create"; // Go back to create page } } } @@ -308,7 +308,7 @@ if (empty($reshook)) { { $editgroup = new UserGroup($db); $editgroup->fetch($group); - $editgroup->oldcopy=clone $editgroup; + $editgroup->oldcopy = clone $editgroup; $object->fetch($id); if ($action == 'addgroup') { @@ -329,7 +329,7 @@ if (empty($reshook)) { } } - if ($action == 'update' && ! $cancel) + if ($action == 'update' && !$cancel) { require_once DOL_DOCUMENT_ROOT.'/core/lib/files.lib.php'; @@ -337,15 +337,15 @@ if (empty($reshook)) { { $error = 0; - if (! GETPOST("lastname", 'alpha')) { + if (!GETPOST("lastname", 'alpha')) { setEventMessages($langs->trans("NameNotDefined"), null, 'errors'); - $action = "edit"; // Go back to create page - $error ++; + $action = "edit"; // Go back to create page + $error++; } - if (! GETPOST("login", 'alpha')) { + if (!GETPOST("login", 'alpha')) { setEventMessages($langs->trans("LoginNotDefined"), null, 'errors'); - $action = "edit"; // Go back to create page - $error ++; + $action = "edit"; // Go back to create page + $error++; } if (!$error) @@ -364,7 +364,7 @@ if (empty($reshook)) { $object->birth = $birth; $object->pass = GETPOST("password", 'none'); $object->api_key = (GETPOST("api_key", 'alphanohtml')) ? GETPOST("api_key", 'alphanohtml') : $object->api_key; - if (! empty($user->admin)) $object->admin = GETPOST("admin", "int"); // admin flag can only be set/unset by an admin user. A test is also done later when forging sql request + if (!empty($user->admin)) $object->admin = GETPOST("admin", "int"); // admin flag can only be set/unset by an admin user. A test is also done later when forging sql request $object->address = GETPOST('address', 'alphanohtml'); $object->zip = GETPOST('zipcode', 'alphanohtml'); $object->town = GETPOST('town', 'alphanohtml'); @@ -378,7 +378,7 @@ if (empty($reshook)) { //$object->facebook = GETPOST("facebook", 'alphanohtml'); //$object->linkedin = GETPOST("linkedin", 'alphanohtml'); $object->socialnetworks = array(); - if (! empty($conf->socialnetworks->enabled)) { + if (!empty($conf->socialnetworks->enabled)) { foreach ($socialnetworks as $key => $value) { $object->socialnetworks[$key] = GETPOST($key, 'alphanohtml'); } @@ -405,35 +405,35 @@ if (empty($reshook)) { $dateemploymentend = dol_mktime(0, 0, 0, GETPOST('dateemploymentendmonth', 'int'), GETPOST('dateemploymentendday', 'int'), GETPOST('dateemploymentendyear', 'int')); $object->dateemploymentend = $dateemploymentend; - if (! empty($conf->stock->enabled)) + if (!empty($conf->stock->enabled)) { $object->fk_warehouse = GETPOST('fk_warehouse', 'int'); } - if (! empty($conf->multicompany->enabled)) + if (!empty($conf->multicompany->enabled)) { - if (! empty($_POST["superadmin"])) + if (!empty($_POST["superadmin"])) { $object->entity = 0; } - elseif (! empty($conf->global->MULTICOMPANY_TRANSVERSE_MODE)) + elseif (!empty($conf->global->MULTICOMPANY_TRANSVERSE_MODE)) { $object->entity = 1; // all users in master entity } else { - $object->entity = (! GETPOST('entity', 'int') ? 0 : GETPOST('entity', 'int')); + $object->entity = (!GETPOST('entity', 'int') ? 0 : GETPOST('entity', 'int')); } } else { - $object->entity = (! GETPOST('entity', 'int') ? 0 : GETPOST('entity', 'int')); + $object->entity = (!GETPOST('entity', 'int') ? 0 : GETPOST('entity', 'int')); } // Fill array 'array_options' with data from add form $ret = $extrafields->setOptionalsFromPost(null, $object); if ($ret < 0) { - $error ++; + $error++; } if (GETPOST('deletephoto')) { @@ -441,7 +441,7 @@ if (empty($reshook)) { } if (!empty($_FILES['photo']['name'])) { - $isimage=image_format_supported($_FILES['photo']['name']); + $isimage = image_format_supported($_FILES['photo']['name']); if ($isimage > 0) { $object->photo = dol_sanitizeFileName($_FILES['photo']['name']); @@ -491,7 +491,7 @@ if (empty($reshook)) { dol_syslog("usercard::update", LOG_DEBUG); $resql = $db->query($sql); if (!$resql) { - $error ++; + $error++; setEventMessages($db->lasterror(), null, 'errors'); } } @@ -520,14 +520,14 @@ if (empty($reshook)) { $object->addThumbs($newfile); } } else { - $error ++; + $error++; $langs->load("errors"); setEventMessages($langs->trans("ErrorFailedToCreateDir", $dir), $mesgs, 'errors'); } } } - if (! $error && ! count($object->errors)) + if (!$error && !count($object->errors)) { // Then we add the associated categories $categories = GETPOST('usercats', 'array'); @@ -657,15 +657,15 @@ if (empty($reshook)) { } // Actions to send emails - $trigger_name='USER_SENTBYMAIL'; - $paramname='id'; // Name of param key to open the card - $mode='emailfromuser'; - $trackid='use'.$id; + $trigger_name = 'USER_SENTBYMAIL'; + $paramname = 'id'; // Name of param key to open the card + $mode = 'emailfromuser'; + $trackid = 'use'.$id; include DOL_DOCUMENT_ROOT.'/core/actions_sendmails.inc.php'; // Actions to build doc $upload_dir = $conf->user->dir_output; - $permissiontoadd=$user->rights->user->user->creer; + $permissiontoadd = $user->rights->user->user->creer; include DOL_DOCUMENT_ROOT.'/core/actions_builddoc.inc.php'; } @@ -675,10 +675,10 @@ if (empty($reshook)) { */ $form = new Form($db); -$formother=new FormOther($db); +$formother = new FormOther($db); $formcompany = new FormCompany($db); $formfile = new FormFile($db); -if (! empty($conf->stock->enabled)) $formproduct = new FormProduct($db); +if (!empty($conf->stock->enabled)) $formproduct = new FormProduct($db); llxHeader('', $langs->trans("UserCard")); @@ -696,7 +696,7 @@ if ($action == 'create' || $action == 'adduserldap') print "
    "; - if (! empty($conf->ldap->enabled) && (isset($conf->global->LDAP_SYNCHRO_ACTIVE) && $conf->global->LDAP_SYNCHRO_ACTIVE == 'ldap2dolibarr')) + if (!empty($conf->ldap->enabled) && (isset($conf->global->LDAP_SYNCHRO_ACTIVE) && $conf->global->LDAP_SYNCHRO_ACTIVE == 'ldap2dolibarr')) { /* * Affiche formulaire d'ajout d'un compte depuis LDAP @@ -707,7 +707,7 @@ if ($action == 'create' || $action == 'adduserldap') $result = $ldap->connect_bind(); if ($result >= 0) { - $required_fields=array( + $required_fields = array( $conf->global->LDAP_KEY_USERS, $conf->global->LDAP_FIELD_FULLNAME, $conf->global->LDAP_FIELD_NAME, @@ -727,23 +727,23 @@ if ($action == 'create' || $action == 'adduserldap') ); // Remove from required_fields all entries not configured in LDAP (empty) and duplicated - $required_fields=array_unique(array_values(array_filter($required_fields, "dol_validElement"))); + $required_fields = array_unique(array_values(array_filter($required_fields, "dol_validElement"))); // Get from LDAP database an array of results $ldapusers = $ldap->getRecords('*', $conf->global->LDAP_USER_DN, $conf->global->LDAP_KEY_USERS, $required_fields, 1); if (is_array($ldapusers)) { - $liste=array(); + $liste = array(); foreach ($ldapusers as $key => $ldapuser) { // Define the label string for this user - $label=''; + $label = ''; foreach ($required_fields as $value) { if ($value) { - $label.=$value."=".$ldapuser[$value]." "; + $label .= $value."=".$ldapuser[$value]." "; } } $liste[$key] = $label; @@ -776,7 +776,7 @@ if ($action == 'create' || $action == 'adduserldap') print ajax_combobox('users'); } print '
    '.$langs->trans("LastExpenseReports", ($num<=$MAXLIST?"":$MAXLIST)).''.$langs->trans("AllExpenseReports").''.$num.''; print '
    '.$langs->trans("LastExpenseReports", ($num <= $MAXLIST ? "" : $MAXLIST)).''.$langs->trans("AllExpenseReports").''.$num.'
    '; - print ''; + print ''; print '
    '; print ''; @@ -788,7 +788,7 @@ if ($action == 'create' || $action == 'adduserldap') print '
    '; print ''; print ''; - if (! empty($ldap_sid)) print ''; + if (!empty($ldap_sid)) print ''; print ''; dol_fiche_head('', '', '', 0, ''); @@ -801,103 +801,103 @@ if ($action == 'create' || $action == 'adduserldap') print '
    '.$langs->trans("Lastname").''; - if (! empty($ldap_lastname)) + if (!empty($ldap_lastname)) { - print ''; + print ''; print $ldap_lastname; } else { - print ''; + print ''; } print '
    '.$langs->trans("Firstname").''; - if (! empty($ldap_firstname)) + if (!empty($ldap_firstname)) { - print ''; + print ''; print $ldap_firstname; } else { - print ''; + print ''; } print '
    '.$langs->trans("Login").''; - if (! empty($ldap_login)) + if (!empty($ldap_login)) { - print ''; + print ''; print $ldap_login; } - elseif (! empty($ldap_loginsmb)) + elseif (!empty($ldap_loginsmb)) { - print ''; + print ''; print $ldap_loginsmb; } else { - print ''; + print ''; } print '
    '.$langs->trans("Password").''; - $valuetoshow=''; + $valuetoshow = ''; if (preg_match('/ldap/', $dolibarr_main_authentication)) { - $valuetoshow.=($valuetoshow?', ':'').$langs->trans("PasswordOfUserInLDAP"); + $valuetoshow .= ($valuetoshow ? ', ' : '').$langs->trans("PasswordOfUserInLDAP"); } if (preg_match('/http/', $dolibarr_main_authentication)) { - $valuetoshow.=($valuetoshow?', ':'').$langs->trans("HTTPBasicPassword"); + $valuetoshow .= ($valuetoshow ? ', ' : '').$langs->trans("HTTPBasicPassword"); } if (preg_match('/dolibarr/', $dolibarr_main_authentication)) { - if (! empty($ldap_pass)) // For very old system comaptibilty. Now clear password can't be viewed from LDAP read + if (!empty($ldap_pass)) // For very old system comaptibilty. Now clear password can't be viewed from LDAP read { - $valuetoshow.= ($valuetoshow?', ':'').''; // Dolibarr password is preffiled with LDAP known password - $valuetoshow.= preg_replace('/./i', '*', $ldap_pass); + $valuetoshow .= ($valuetoshow ? ', ' : '').''; // Dolibarr password is preffiled with LDAP known password + $valuetoshow .= preg_replace('/./i', '*', $ldap_pass); } else { // We do not use a field password but a field text to show new password to use. - $valuetoshow.= ($valuetoshow?', ':'').''; + $valuetoshow .= ($valuetoshow ? ', ' : '').''; } } // Other form for user password - $parameters=array('valuetoshow' => $valuetoshow, 'password' => $password); - $reshook=$hookmanager->executeHooks('printUserPasswordField', $parameters, $object, $action); // Note that $action and $object may have been modified by hook - if ($reshook > 0) $valuetoshow=$hookmanager->resPrint; // to replace - else $valuetoshow.=$hookmanager->resPrint; // to add + $parameters = array('valuetoshow' => $valuetoshow, 'password' => $password); + $reshook = $hookmanager->executeHooks('printUserPasswordField', $parameters, $object, $action); // Note that $action and $object may have been modified by hook + if ($reshook > 0) $valuetoshow = $hookmanager->resPrint; // to replace + else $valuetoshow .= $hookmanager->resPrint; // to add print $valuetoshow; print '
    '.$langs->trans("ApiKey").''; print ''; - if (! empty($conf->use_javascript_ajax)) + if (!empty($conf->use_javascript_ajax)) print ' '.img_picto($langs->trans('Generate'), 'refresh', 'id="generate_api_key" class="linkobject"'); print '
    '.$langs->trans("Administrator").''; print $form->selectyesno('admin', GETPOST('admin'), 1); - if (! empty($conf->multicompany->enabled) && ! $user->entity) + if (!empty($conf->multicompany->enabled) && !$user->entity) { - if (! empty($conf->use_javascript_ajax)) + if (!empty($conf->use_javascript_ajax)) { print ''; } - $checked=(GETPOST('superadmin', 'int')?' checked':''); - $disabled=(GETPOST('superadmin', 'int')?'':' disabled'); + $checked = (GETPOST('superadmin', 'int') ? ' checked' : ''); + $disabled = (GETPOST('superadmin', 'int') ? '' : ' disabled'); print ' '.$langs->trans("SuperAdministrator"); } print "
    '.$langs->trans("Gender").''; - $arraygender=array('man'=>$langs->trans("Genderman"),'woman'=>$langs->trans("Genderwoman")); + $arraygender = array('man'=>$langs->trans("Genderman"), 'woman'=>$langs->trans("Genderwoman")); print $form->selectarray('gender', $arraygender, GETPOST('gender'), 1); print '
    '.$langs->trans('Employee').''; - print $form->selectyesno("employee", (GETPOST('employee')!=''?GETPOST('employee'):$defaultemployee), 1); + print $form->selectyesno("employee", (GETPOST('employee') != '' ?GETPOST('employee') : $defaultemployee), 1); print '
    '; $text = $langs->trans("ForceUserExpenseValidator"); @@ -994,7 +994,7 @@ if ($action == 'create' || $action == 'adduserldap') } // Holiday request validator - if(!empty($conf->holiday->enabled)) + if (!empty($conf->holiday->enabled)) { print '
    '; $text = $langs->trans("ForceUserHolidayValidator"); @@ -1018,17 +1018,17 @@ if ($action == 'create' || $action == 'adduserldap') // Zip print '
    '.$form->editfieldkey('Zip', 'zipcode', '', $object, 0).''; - print $formcompany->select_ziptown($object->zip, 'zipcode', array('town','selectcountry_id','state_id'), 6); + print $formcompany->select_ziptown($object->zip, 'zipcode', array('town', 'selectcountry_id', 'state_id'), 6); print '
    '.$form->editfieldkey('Town', 'town', '', $object, 0).''; - print $formcompany->select_ziptown($object->town, 'town', array('zipcode','selectcountry_id','state_id')); + print $formcompany->select_ziptown($object->town, 'town', array('zipcode', 'selectcountry_id', 'state_id')); print '
    '.$form->editfieldkey('Country', 'selectcountry_id', '', $object, 0).''; - print $form->select_country((GETPOST('country_id')!=''?GETPOST('country_id'):$object->country_id)); + print $form->select_country((GETPOST('country_id') != '' ?GETPOST('country_id') : $object->country_id)); if ($user->admin) print info_admin($langs->trans("YouCanChangeValuesForThisListFromDictionarySetup"), 1); print '
    '.img_picto('', 'object_phoning').' '.$langs->trans("PhonePro").''; - if (! empty($ldap_phone)) + if (!empty($ldap_phone)) { - print ''; + print ''; print $ldap_phone; } else { - print ''; + print ''; } print '
    '.img_picto('', 'object_phoning_mobile').' '.$langs->trans("PhoneMobile").''; - if (! empty($ldap_mobile)) + if (!empty($ldap_mobile)) { - print ''; + print ''; print $ldap_mobile; } else { - print ''; + print ''; } print '
    '.img_picto('', 'object_phoning_fax').' '.$langs->trans("Fax").''; - if (! empty($ldap_fax)) + if (!empty($ldap_fax)) { - print ''; + print ''; print $ldap_fax; } else { - print ''; + print ''; } print '
    '; - if (! empty($ldap_mail)) + if (!empty($ldap_mail)) { - print ''; + print ''; print $ldap_mail; } else { - print ''; + print ''; } print '
    '.$langs->trans($value['label']).''; - if (! empty($ldap_social[$key])) { + if (!empty($ldap_social[$key])) { print ''; print $ldap_social[$key]; } else { @@ -1110,7 +1110,7 @@ if ($action == 'create' || $action == 'adduserldap') print '
    '.$langs->trans("AccountancyCode").''; - print ''; + print ''; print '
    '.$langs->trans("ColorUser").''; - print $formother->selectColor(GETPOST('color')?GETPOST('color'):$object->color, 'color', null, 1, '', 'hideifnotset'); + print $formother->selectColor(GETPOSTISSET('color')?GETPOST('color', 'alphanohtml'):$object->color, 'color', null, 1, '', 'hideifnotset'); print '
    ' . $form->editfieldkey('Categories', 'usercats', '', $object, 0) . ''; + print '
    '.$form->editfieldkey('Categories', 'usercats', '', $object, 0).''; $cate_arbo = $form->select_all_categories('user', null, 'parent', null, null, 1); print $form->multiselectarray('usercats', $cate_arbo, GETPOST('usercats', 'array'), null, null, null, null, '90%'); print "
    '.$langs->trans("Entity").'".$mc->select_entities($conf->entity); @@ -1233,8 +1233,8 @@ if ($action == 'create' || $action == 'adduserldap') } // Other attributes - $parameters=array('objectsrc' => $objectsrc, 'colspan' => ' colspan="3"'); - $reshook=$hookmanager->executeHooks('formObjectOptions', $parameters, $object, $action); // Note that $action and $object may have been modified by hook + $parameters = array('objectsrc' => $objectsrc, 'colspan' => ' colspan="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)) { @@ -1246,7 +1246,7 @@ if ($action == 'create' || $action == 'adduserldap') print $langs->trans("Note"); print ''; require_once DOL_DOCUMENT_ROOT.'/core/class/doleditor.class.php'; - $doleditor=new DolEditor('note', '', '', 120, 'dolibarr_notes', '', false, true, $conf->global->FCKEDITOR_ENABLE_SOCIETE, ROWS_3, '90%'); + $doleditor = new DolEditor('note', GETPOSTISSET('note')?GETPOST('note', 'none'):'', '', 120, 'dolibarr_notes', '', false, true, $conf->global->FCKEDITOR_ENABLE_SOCIETE, ROWS_3, '90%'); $doleditor->Create(); print "
    '.$langs->trans("Signature").''; require_once DOL_DOCUMENT_ROOT.'/core/class/doleditor.class.php'; - $doleditor=new DolEditor('signature', GETPOST('signature'), '', 138, 'dolibarr_notes', 'In', true, true, empty($conf->global->FCKEDITOR_ENABLE_USERSIGN)?0:1, ROWS_4, '90%'); + $doleditor = new DolEditor('signature', GETPOST('signature'), '', 138, 'dolibarr_notes', 'In', true, true, empty($conf->global->FCKEDITOR_ENABLE_USERSIGN) ? 0 : 1, ROWS_4, '90%'); print $doleditor->Create(1); print '
    '.$langs->trans("DefaultWarehouse").''; print $formproduct->selectWarehouses($object->fk_warehouse, 'fk_warehouse', 'warehouseopen', 1); @@ -1275,38 +1275,38 @@ if ($action == 'create' || $action == 'adduserldap') // Position/Job print '
    '.$langs->trans("PostOrFunction").''; - print ''; + print ''; print '
    '; - $text=$langs->trans("THM"); + $text = $langs->trans("THM"); print $form->textwithpicto($text, $langs->trans("THMDescription"), 1, 'help', 'classthm'); print ''; - print ''; + print ''; print '
    '; - $text=$langs->trans("TJM"); + $text = $langs->trans("TJM"); print $form->textwithpicto($text, $langs->trans("TJMDescription"), 1, 'help', 'classtjm'); print ''; - print ''; + print ''; print '
    '.$langs->trans("Salary").''; - print ''; + print ''; print '
    '.$langs->trans("WeeklyHours").''; - print ''; + print ''; print '
    '.$langs->trans("Login").''.$langs->trans("LoginAccountDisableInDolibarr").'
    '.$langs->trans("Password").''; - $valuetoshow=''; + $valuetoshow = ''; if (preg_match('/ldap/', $dolibarr_main_authentication)) { - if (! empty($object->ldap_sid)) + if (!empty($object->ldap_sid)) { if ($passDoNotExpire) { - $valuetoshow.=($valuetoshow?(' '.$langs->trans("or").' '):'').$langs->trans("LdapUacf_".$statutUACF); + $valuetoshow .= ($valuetoshow ? (' '.$langs->trans("or").' ') : '').$langs->trans("LdapUacf_".$statutUACF); } - elseif($userChangePassNextLogon) + elseif ($userChangePassNextLogon) { - $valuetoshow.=($valuetoshow?(' '.$langs->trans("or").' '):'').''.$langs->trans("UserMustChangePassNextLogon", $ldap->domainFQDN).''; + $valuetoshow .= ($valuetoshow ? (' '.$langs->trans("or").' ') : '').''.$langs->trans("UserMustChangePassNextLogon", $ldap->domainFQDN).''; } - elseif($userDisabled) + elseif ($userDisabled) { - $valuetoshow.=($valuetoshow?(' '.$langs->trans("or").' '):'').''.$langs->trans("LdapUacf_".$statutUACF, $ldap->domainFQDN).''; + $valuetoshow .= ($valuetoshow ? (' '.$langs->trans("or").' ') : '').''.$langs->trans("LdapUacf_".$statutUACF, $ldap->domainFQDN).''; } else { - $valuetoshow.=($valuetoshow?(' '.$langs->trans("or").' '):'').$langs->trans("PasswordOfUserInLDAP"); + $valuetoshow .= ($valuetoshow ? (' '.$langs->trans("or").' ') : '').$langs->trans("PasswordOfUserInLDAP"); } } else { - $valuetoshow.=($valuetoshow?(' '.$langs->trans("or").' '):'').$langs->trans("PasswordOfUserInLDAP"); + $valuetoshow .= ($valuetoshow ? (' '.$langs->trans("or").' ') : '').$langs->trans("PasswordOfUserInLDAP"); } } if (preg_match('/http/', $dolibarr_main_authentication)) { - $valuetoshow.=($valuetoshow?(' '.$langs->trans("or").' '):'').$langs->trans("HTTPBasicPassword"); + $valuetoshow .= ($valuetoshow ? (' '.$langs->trans("or").' ') : '').$langs->trans("HTTPBasicPassword"); } if (preg_match('/dolibarr/', $dolibarr_main_authentication)) { - if ($object->pass) $valuetoshow.= ($valuetoshow?(' '.$langs->trans("or").' '):'').preg_replace('/./i', '*', $object->pass); + if ($object->pass) $valuetoshow .= ($valuetoshow ? (' '.$langs->trans("or").' ') : '').preg_replace('/./i', '*', $object->pass); else { - if ($user->admin) $valuetoshow.= ($valuetoshow?(' '.$langs->trans("or").' '):'').$langs->trans("Crypted").': '.$object->pass_indatabase_crypted; - else $valuetoshow.= ($valuetoshow?(' '.$langs->trans("or").' '):'').$langs->trans("Hidden"); + if ($user->admin) $valuetoshow .= ($valuetoshow ? (' '.$langs->trans("or").' ') : '').$langs->trans("Crypted").': '.$object->pass_indatabase_crypted; + else $valuetoshow .= ($valuetoshow ? (' '.$langs->trans("or").' ') : '').$langs->trans("Hidden"); } } // Other form for user password - $parameters=array('valuetoshow' => $valuetoshow); - $reshook=$hookmanager->executeHooks('printUserPasswordField', $parameters, $object, $action); // Note that $action and $object may have been modified by hook - if ($reshook > 0) $valuetoshow=$hookmanager->resPrint; // to replace - else $valuetoshow.=$hookmanager->resPrint; // to add + $parameters = array('valuetoshow' => $valuetoshow); + $reshook = $hookmanager->executeHooks('printUserPasswordField', $parameters, $object, $action); // Note that $action and $object may have been modified by hook + if ($reshook > 0) $valuetoshow = $hookmanager->resPrint; // to replace + else $valuetoshow .= $hookmanager->resPrint; // to add print $valuetoshow; print "
    '.$langs->trans("ApiKey").''; - if (! empty($object->api_key)) print preg_replace('/./', '*', $object->api_key); + if (!empty($object->api_key)) print preg_replace('/./', '*', $object->api_key); print '
    '.$langs->trans("Administrator").''; - if (! empty($conf->multicompany->enabled) && $object->admin && ! $object->entity) + if (!empty($conf->multicompany->enabled) && $object->admin && !$object->entity) { print $form->textwithpicto(yn($object->admin), $langs->trans("SuperAdministratorDesc"), 1, "superadmin"); } @@ -1583,11 +1583,11 @@ else // Type print '
    '; - $text=$langs->trans("Type"); + $text = $langs->trans("Type"); print $form->textwithpicto($text, $langs->trans("InternalExternalDesc")); print ''; - $type=$langs->trans("Internal"); - if ($object->societe_id > 0) $type=$langs->trans("External"); + $type = $langs->trans("Internal"); + if ($object->societe_id > 0) $type = $langs->trans("External"); print $type; if ($object->ldap_sid) print ' ('.$langs->trans("DomainUser").')'; print '
    '; if (empty($object->fk_user)) print $langs->trans("None"); else { - $huser=new User($db); + $huser = new User($db); $huser->fetch($object->fk_user); print $huser->getNomUrl(1); } @@ -1631,8 +1631,8 @@ else print $form->textwithpicto($text, $langs->trans("ValidatorIsSupervisorByDefault"), 1, 'help'); print ''; - if (! empty($object->fk_user_expense_validator)) { - $evuser=new User($db); + if (!empty($object->fk_user_expense_validator)) { + $evuser = new User($db); $evuser->fetch($object->fk_user_expense_validator); print $evuser->getNomUrl(1); } @@ -1645,8 +1645,8 @@ else print $form->textwithpicto($text, $langs->trans("ValidatorIsSupervisorByDefault"), 1, 'help'); print ''; - if (! empty($object->fk_user_holiday_validator)) { - $hvuser=new User($db); + if (!empty($object->fk_user_holiday_validator)) { + $hvuser = new User($db); $hvuser->fetch($object->fk_user_holiday_validator); print $hvuser->getNomUrl(1); } @@ -1654,10 +1654,10 @@ else print "
    '.$langs->trans("DefaultWarehouse").''; print $warehousestatic->getNomUrl(); @@ -1671,8 +1671,8 @@ else //$childids = $user->getAllChildIds(1); - if ((! empty($conf->salaries->enabled) && ! empty($user->rights->salaries->read)) - || (! empty($conf->hrm->enabled) && ! empty($user->rights->hrm->employee->read))) + if ((!empty($conf->salaries->enabled) && !empty($user->rights->salaries->read)) + || (!empty($conf->hrm->enabled) && !empty($user->rights->hrm->employee->read))) { // Even a superior can't see this info of its subordinates wihtout $user->rights->salaries->read and $user->rights->hrm->employee->read (setting/viewing is reserverd to HR people). // However, he can see the valuation of timesheet of its subordinates even without these permissions. @@ -1680,28 +1680,28 @@ else // THM print '
    '; - $text=$langs->trans("THM"); + $text = $langs->trans("THM"); print $form->textwithpicto($text, $langs->trans("THMDescription"), 1, 'help', 'classthm'); print ''; - print ($object->thm!=''?price($object->thm, '', $langs, 1, -1, -1, $conf->currency):''); + print ($object->thm != '' ?price($object->thm, '', $langs, 1, -1, -1, $conf->currency) : ''); print '
    '; - $text=$langs->trans("TJM"); + $text = $langs->trans("TJM"); print $form->textwithpicto($text, $langs->trans("TJMDescription"), 1, 'help', 'classtjm'); print ''; - print ($object->tjm!=''?price($object->tjm, '', $langs, 1, -1, -1, $conf->currency):''); + print ($object->tjm != '' ?price($object->tjm, '', $langs, 1, -1, -1, $conf->currency) : ''); print '
    '.$langs->trans("Salary").''; - print ($object->salary!=''?price($object->salary, '', $langs, 1, -1, -1, $conf->currency):''); + print ($object->salary != '' ?price($object->salary, '', $langs, 1, -1, -1, $conf->currency) : ''); print '
    '; // Color user - if (! empty($conf->agenda->enabled)) + if (!empty($conf->agenda->enabled)) { print ''; print ''; + print ''; print ''; } - if (isset($conf->file->main_authentication) && preg_match('/openid/', $conf->file->main_authentication) && ! empty($conf->global->MAIN_OPENIDURL_PERUSER)) + if (isset($conf->file->main_authentication) && preg_match('/openid/', $conf->file->main_authentication) && !empty($conf->global->MAIN_OPENIDURL_PERUSER)) { print ''; print ''; @@ -1784,14 +1784,14 @@ else print "\n"; // Multicompany - if (! empty($conf->multicompany->enabled) && is_object($mc)) + if (!empty($conf->multicompany->enabled) && is_object($mc)) { // This is now done with hook formObjectOptions. Keep this code for backward compatibility with old multicompany module - if (! method_exists($mc, 'formObjectOptions')) + if (!method_exists($mc, 'formObjectOptions')) { - if (! empty($conf->multicompany->enabled) && empty($conf->global->MULTICOMPANY_TRANSVERSE_MODE) && $conf->entity == 1 && $user->admin && ! $user->entity) + if (!empty($conf->multicompany->enabled) && empty($conf->global->MULTICOMPANY_TRANSVERSE_MODE) && $conf->entity == 1 && $user->admin && !$user->entity) { - print ''; print ''; print '
    '.$langs->trans("ColorUser").''; @@ -1760,15 +1760,15 @@ else } // Categories - if (! empty($conf->categorie->enabled) && ! empty($user->rights->categorie->lire)) + if (!empty($conf->categorie->enabled) && !empty($user->rights->categorie->lire)) { - print '
    ' . $langs->trans("Categories") . '
    '.$langs->trans("Categories").''; print $form->showCategories($object->id, 'user', 1); print '
    '.$langs->trans("OpenIDURL").''.$object->openid.'
    ' . $langs->trans("Entity") . ''; + print '
    '.$langs->trans("Entity").''; if (empty($object->entity)) { print $langs->trans("AllEntities"); } else { @@ -1804,10 +1804,10 @@ else } // Other attributes - include DOL_DOCUMENT_ROOT . '/core/tpl/extrafields_view.tpl.php'; + include DOL_DOCUMENT_ROOT.'/core/tpl/extrafields_view.tpl.php'; // Company / Contact - if (! empty($conf->societe->enabled)) + if (!empty($conf->societe->enabled)) { print '
    '.$langs->trans("LinkToCompanyContact").''; @@ -1821,7 +1821,7 @@ else { print $langs->trans("ThisUserIsNot"); } - if (! empty($object->contactid)) + if (!empty($object->contactid)) { $contact = new Contact($db); $contact->fetch($object->contactid); @@ -1834,16 +1834,16 @@ else } // Module Adherent - if (! empty($conf->adherent->enabled)) + if (!empty($conf->adherent->enabled)) { $langs->load("members"); print '
    '.$langs->trans("LinkedToDolibarrMember").''; if ($object->fk_member) { - $adh=new Adherent($db); + $adh = new Adherent($db); $adh->fetch($object->fk_member); - $adh->ref=$adh->getFullname($langs); // Force to show login instead of id + $adh->ref = $adh->getFullname($langs); // Force to show login instead of id print $adh->getNomUrl(1); } else @@ -1875,11 +1875,11 @@ else print '
    '; - $parameters=array(); - $reshook=$hookmanager->executeHooks('addMoreActionsButtons', $parameters, $object, $action); // Note that $action and $object may have been modified by hook + $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($object->email)) + if (!empty($object->email)) { $langs->load("mails"); print ''; @@ -1890,9 +1890,9 @@ else print ''; } - if ($caneditfield && (empty($conf->multicompany->enabled) || ! $user->entity || ($object->entity == $conf->entity) || ($conf->global->MULTICOMPANY_TRANSVERSE_MODE && $conf->entity == 1))) + if ($caneditfield && (empty($conf->multicompany->enabled) || !$user->entity || ($object->entity == $conf->entity) || ($conf->global->MULTICOMPANY_TRANSVERSE_MODE && $conf->entity == 1))) { - if (! empty($conf->global->MAIN_ONLY_LOGIN_ALLOWED)) + if (!empty($conf->global->MAIN_ONLY_LOGIN_ALLOWED)) { print ''; } @@ -1901,8 +1901,8 @@ else print ''; } } - elseif ($caneditpassword && ! $object->ldap_sid && - (empty($conf->multicompany->enabled) || ! $user->entity || ($object->entity == $conf->entity) || ($conf->global->MULTICOMPANY_TRANSVERSE_MODE && $conf->entity == 1))) + elseif ($caneditpassword && !$object->ldap_sid && + (empty($conf->multicompany->enabled) || !$user->entity || ($object->entity == $conf->entity) || ($conf->global->MULTICOMPANY_TRANSVERSE_MODE && $conf->entity == 1))) { print ''; } @@ -1915,7 +1915,7 @@ else print ''; } elseif (($user->id != $id && $caneditpassword) && $object->login && !$object->ldap_sid && - ((empty($conf->multicompany->enabled) && $object->entity == $user->entity) || ! $user->entity || ($object->entity == $conf->entity) || ($conf->global->MULTICOMPANY_TRANSVERSE_MODE && $conf->entity == 1))) + ((empty($conf->multicompany->enabled) && $object->entity == $user->entity) || !$user->entity || ($object->entity == $conf->entity) || ($conf->global->MULTICOMPANY_TRANSVERSE_MODE && $conf->entity == 1))) { print ''; } @@ -1925,7 +1925,7 @@ else print ''; } elseif (($user->id != $id && $caneditpassword) && $object->login && !$object->ldap_sid && - ((empty($conf->multicompany->enabled) && $object->entity == $user->entity) || ! $user->entity || ($object->entity == $conf->entity) || ($conf->global->MULTICOMPANY_TRANSVERSE_MODE && $conf->entity == 1))) + ((empty($conf->multicompany->enabled) && $object->entity == $user->entity) || !$user->entity || ($object->entity == $conf->entity) || ($conf->global->MULTICOMPANY_TRANSVERSE_MODE && $conf->entity == 1))) { if ($object->email) print ''; else print ''; @@ -1934,13 +1934,13 @@ else // Enable user if ($user->id <> $id && $candisableuser && $object->statut == 0 && - ((empty($conf->multicompany->enabled) && $object->entity == $user->entity) || ! $user->entity || ($object->entity == $conf->entity) || ($conf->global->MULTICOMPANY_TRANSVERSE_MODE && $conf->entity == 1))) + ((empty($conf->multicompany->enabled) && $object->entity == $user->entity) || !$user->entity || ($object->entity == $conf->entity) || ($conf->global->MULTICOMPANY_TRANSVERSE_MODE && $conf->entity == 1))) { print ''; } // Disable user if ($user->id <> $id && $candisableuser && $object->statut == 1 && - ((empty($conf->multicompany->enabled) && $object->entity == $user->entity) || ! $user->entity || ($object->entity == $conf->entity) || ($conf->global->MULTICOMPANY_TRANSVERSE_MODE && $conf->entity == 1))) + ((empty($conf->multicompany->enabled) && $object->entity == $user->entity) || !$user->entity || ($object->entity == $conf->entity) || ($conf->global->MULTICOMPANY_TRANSVERSE_MODE && $conf->entity == 1))) { print ''; } @@ -1953,9 +1953,9 @@ else } // Delete if ($user->id <> $id && $candisableuser && - ((empty($conf->multicompany->enabled) && $object->entity == $user->entity) || ! $user->entity || ($object->entity == $conf->entity) || ($conf->global->MULTICOMPANY_TRANSVERSE_MODE && $conf->entity == 1))) + ((empty($conf->multicompany->enabled) && $object->entity == $user->entity) || !$user->entity || ($object->entity == $conf->entity) || ($conf->global->MULTICOMPANY_TRANSVERSE_MODE && $conf->entity == 1))) { - if ($user->admin || ! $object->admin) // If user edited is admin, delete is possible on for an admin + if ($user->admin || !$object->admin) // If user edited is admin, delete is possible on for an admin { print ''; } @@ -1974,8 +1974,8 @@ else if (GETPOST('modelselected')) $action = 'presend'; // Presend form - $modelmail='user'; - $defaulttopic='Information'; + $modelmail = 'user'; + $defaulttopic = 'Information'; $diroutput = $conf->user->dir_output; $trackid = 'use'.$object->id; @@ -1994,33 +1994,32 @@ else // On selectionne les groupes auquel fait parti le user $exclude = array(); - $usergroup=new UserGroup($db); + $usergroup = new UserGroup($db); $groupslist = $usergroup->listGroupsForUser($object->id); - if (! empty($groupslist)) + if (!empty($groupslist)) { - foreach($groupslist as $groupforuser) + foreach ($groupslist as $groupforuser) { - $exclude[]=$groupforuser->id; + $exclude[] = $groupforuser->id; } } - if ($caneditgroup) - { - print ''."\n"; - print ''; - print ''; - } - - print ''."\n"; - // Other form for add user to group - $parameters=array('caneditgroup' => $caneditgroup, 'groupslist' => $groupslist, 'exclude' => $exclude); - $reshook=$hookmanager->executeHooks('formAddUserToGroup', $parameters, $object, $action); // Note that $action and $object may have been modified by hook + $parameters = array('caneditgroup' => $caneditgroup, 'groupslist' => $groupslist, 'exclude' => $exclude); + $reshook = $hookmanager->executeHooks('formAddUserToGroup', $parameters, $object, $action); // Note that $action and $object may have been modified by hook print $hookmanager->resPrint; if (empty($reshook)) { + if ($caneditgroup) + { + print ''."\n"; + print ''; + print ''; + } + + print '
    '."\n"; print ''."\n"; print ''; print ''; } - } - print "
    '.$langs->trans("Groups").''; if ($caneditgroup) @@ -2035,9 +2034,9 @@ else /* * Groups assigned to user */ - if (! empty($groupslist)) + if (!empty($groupslist)) { - foreach($groupslist as $group) + foreach ($groupslist as $group) { print '
    '; @@ -2068,15 +2067,15 @@ else { print '
    '.$langs->trans("None").'
    "; + print "
    "; - if ($caneditgroup) - { - print ''; + if ($caneditgroup) + { + print ''; + } + print "
    "; } - print "
    "; } } } @@ -2096,7 +2095,7 @@ else print ''; // Ref/ID - if (! empty($conf->global->MAIN_SHOW_TECHNICAL_ID)) + if (!empty($conf->global->MAIN_SHOW_TECHNICAL_ID)) { print ''; print '".''; print ''; print '\n"; // API key - if(! empty($conf->api->enabled) && $user->admin) + if (!empty($conf->api->enabled) && $user->admin) { print ''; print ''; } @@ -2215,13 +2214,13 @@ else && ($user->id != $object->id) // Don't downgrade ourself && ( (empty($conf->multicompany->enabled) && $nbAdmin >= 1) - || (! empty($conf->multicompany->enabled) && (($object->entity > 0 || ($user->entity == 0 && $object->entity == 0)) || $nbSuperAdmin > 1)) // Don't downgrade a superadmin if alone + || (!empty($conf->multicompany->enabled) && (($object->entity > 0 || ($user->entity == 0 && $object->entity == 0)) || $nbSuperAdmin > 1)) // Don't downgrade a superadmin if alone ) ) { print $form->selectyesno('admin', $object->admin, 1); - if (! empty($conf->multicompany->enabled) && ! $user->entity) + if (!empty($conf->multicompany->enabled) && !$user->entity) { if ($conf->use_javascript_ajax) { @@ -2262,7 +2261,7 @@ else '; } - $checked=(($object->admin && ! $object->entity) ? ' checked' : ''); + $checked = (($object->admin && !$object->entity) ? ' checked' : ''); print ' '.$langs->trans("SuperAdministrator"); } } @@ -2271,7 +2270,7 @@ else $yn = yn($object->admin); print ''; print ''; - if (! empty($conf->multicompany->enabled) && empty($object->entity)) print $form->textwithpicto($yn, $langs->trans("DontDowngradeSuperAdmin"), 1, 'warning'); + if (!empty($conf->multicompany->enabled) && empty($object->entity)) print $form->textwithpicto($yn, $langs->trans("DontDowngradeSuperAdmin"), 1, 'warning'); else print $yn; } print ''; @@ -2280,17 +2279,17 @@ else // Type print ''; print ''; print ''; // Employee @@ -2309,7 +2308,7 @@ else if ($caneditfield) { print $form->selectyesno("employee", $object->employee, 1); } else { - if ($object->employee){ + if ($object->employee) { print $langs->trans("Yes"); } else { print $langs->trans("No"); @@ -2327,7 +2326,7 @@ else else { print ''; - $huser=new User($db); + $huser = new User($db); $huser->fetch($object->fk_user); print $huser->getNomUrl(1); } @@ -2347,7 +2346,7 @@ else else { print ''; - $evuser=new User($db); + $evuser = new User($db); $evuser->fetch($object->fk_user_expense_validator); print $evuser->getNomUrl(1); } @@ -2367,7 +2366,7 @@ else else { print ''; - $hvuser=new User($db); + $hvuser = new User($db); $hvuser->fetch($object->fk_user_holiday_validator); print $hvuser->getNomUrl(1); } @@ -2396,7 +2395,7 @@ else // Country print ''; @@ -2411,7 +2410,7 @@ else // Tel pro print "".''; print '".''; print ''; // EMail - print "".'global->USER_MAIL_REQUIRED)?' class="fieldrequired"':'').'>'.img_picto('', 'object_email').' '.$langs->trans("EMail").''; + print "".'global->USER_MAIL_REQUIRED) ? ' class="fieldrequired"' : '').'>'.img_picto('', 'object_email').' '.$langs->trans("EMail").''; print ''; - if (! empty($conf->socialnetworks->enabled)) { + if (!empty($conf->socialnetworks->enabled)) { foreach ($socialnetworks as $key => $value) { if ($value['active']) { print ''; print '".''; print ''; print ''; @@ -2614,7 +2613,7 @@ else // Categories if (!empty($conf->categorie->enabled) && !empty($user->rights->categorie->lire)) { - print ''; + print ''; print '"; @@ -2638,7 +2637,7 @@ else print ''; // Company / Contact - if (! empty($conf->societe->enabled)) + if (!empty($conf->societe->enabled)) { print ''; print ''; print '".''; - print "\n"; } else @@ -2705,15 +2704,15 @@ else } // Other attributes - $parameters=array('colspan' => ' colspan="2"'); - $reshook=$hookmanager->executeHooks('formObjectOptions', $parameters, $object, $action); // Note that $action and $object may have been modified by hook + $parameters = array('colspan' => ' colspan="2"'); + $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 ($caneditfield) { print $object->showOptionals($extrafields, 'edit'); - }else{ + } else { print $object->showOptionals($extrafields, 'view'); } } @@ -2724,7 +2723,7 @@ else if ($caneditfield) { require_once DOL_DOCUMENT_ROOT.'/core/class/doleditor.class.php'; - $doleditor=new DolEditor('signature', $object->signature, '', 138, 'dolibarr_notes', 'In', false, true, empty($conf->global->FCKEDITOR_ENABLE_USERSIGN)?0:1, ROWS_4, '90%'); + $doleditor = new DolEditor('signature', $object->signature, '', 138, 'dolibarr_notes', 'In', false, true, empty($conf->global->FCKEDITOR_ENABLE_USERSIGN) ? 0 : 1, ROWS_4, '90%'); print $doleditor->Create(1); } else @@ -2740,7 +2739,7 @@ else // TODO Move this into tab RH (HierarchicalResponsible must be on both tab) // Default warehouse - if (! empty($conf->stock->enabled) && ! empty($conf->global->USER_DEFAULT_WAREHOUSE)) // TODO What is goal of this. How it is used ? + if (!empty($conf->stock->enabled) && !empty($conf->global->USER_DEFAULT_WAREHOUSE)) // TODO What is goal of this. How it is used ? { print ''; - if ((! empty($conf->salaries->enabled) && ! empty($user->rights->salaries->read)) - || (! empty($conf->hrm->enabled) && ! empty($user->rights->hrm->employee->read))) + if ((!empty($conf->salaries->enabled) && !empty($user->rights->salaries->read)) + || (!empty($conf->hrm->enabled) && !empty($user->rights->hrm->employee->read))) { $langs->load("salaries"); // THM print ''; print ''; print "\n"; // TJM print ''; print ''; print "\n"; @@ -2799,7 +2798,7 @@ else // Salary print ''; print ''; print "\n"; } @@ -2807,10 +2806,10 @@ else // Weeklyhours print ''; print ''; @@ -2819,10 +2818,10 @@ else // Date employment print ''; print ''; @@ -2831,10 +2830,10 @@ else // Date employmentEnd print ''; print ''; @@ -2844,10 +2843,10 @@ else // Date birth print ''; print ''; @@ -2873,8 +2872,8 @@ else * Documents generes */ $filename = dol_sanitizeFileName($object->ref); - $filedir = $conf->user->dir_output . "/" . dol_sanitizeFileName($object->ref); - $urlsource = $_SERVER["PHP_SELF"] . "?id=" . $object->id; + $filedir = $conf->user->dir_output."/".dol_sanitizeFileName($object->ref); + $urlsource = $_SERVER["PHP_SELF"]."?id=".$object->id; $genallowed = $user->rights->user->user->lire; $delallowed = $user->rights->user->user->creer; @@ -2888,7 +2887,7 @@ else print '
    '; // List of actions on element - include_once DOL_DOCUMENT_ROOT . '/core/class/html.formactions.class.php'; + include_once DOL_DOCUMENT_ROOT.'/core/class/html.formactions.class.php'; $formactions = new FormActions($db); $somethingshown = $formactions->showactions($object, 'user', $socid, 1); @@ -2896,11 +2895,11 @@ else print '
    '; } - if (! empty($conf->ldap->enabled) && ! empty($object->ldap_sid)) $ldap->close(); + if (!empty($conf->ldap->enabled) && !empty($object->ldap_sid)) $ldap->close(); } } -if (! empty($conf->api->enabled) && ! empty($conf->use_javascript_ajax)) +if (!empty($conf->api->enabled) && !empty($conf->use_javascript_ajax)) { print "\n".''."\n"; -$htmlheadercontentdefault.=''."\n"; -$htmlheadercontentdefault.=''."\n"; -$htmlheadercontentdefault.=''."\n"; -$htmlheadercontentdefault.=''."\n"; -$htmlheadercontentdefault.=''."\n"; +$htmlheadercontentdefault .= ''."\n"; +$htmlheadercontentdefault .= ''."\n"; +$htmlheadercontentdefault .= ''."\n"; +$htmlheadercontentdefault .= ''."\n"; +$htmlheadercontentdefault .= ''."\n"; +$htmlheadercontentdefault .= ''."\n"; +$htmlheadercontentdefault .= ''."\n"; +$htmlheadercontentdefault .= ''."\n"; $manifestjsoncontentdefault = ''; -$manifestjsoncontentdefault.= '{ +$manifestjsoncontentdefault .= '{ "name": "MyWebsite", "short_name": "MyWebsite", "start_url": "/", @@ -270,9 +272,24 @@ if (GETPOST('refreshsite') || GETPOST('refreshsite_x') || GETPOST('refreshsite.x } 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. { - $pageid=0; if ($action == 'addsite') $action = 'preview'; if ($action == 'updatesource') $action = 'preview'; + + $pageid = $object->fk_default_home; + 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); + $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; + } + $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'; @@ -288,17 +305,17 @@ if ($cancel) } $savbacktopage = $backtopage; -$backtopage = $_SERVER["PHP_SELF"].'?file_manager=1&website='.$websitekey.'&pageid='.$pageid.(GETPOST('section_dir', 'alpha')?'§ion_dir='.urlencode(GETPOST('section_dir', 'alpha')):''); // used after a confirm_deletefile into actions_linkedfiles.inc.php +$backtopage = $_SERVER["PHP_SELF"].'?file_manager=1&website='.$websitekey.'&pageid='.$pageid.(GETPOST('section_dir', 'alpha') ? '§ion_dir='.urlencode(GETPOST('section_dir', 'alpha')) : ''); // used after a confirm_deletefile into actions_linkedfiles.inc.php include DOL_DOCUMENT_ROOT.'/core/actions_linkedfiles.inc.php'; $backtopage = $savbacktopage; -if ($action == 'renamefile') $action='file_manager'; // After actions_linkedfiles, if action were renamefile, we set it to 'file_manager' +if ($action == 'renamefile') $action = 'file_manager'; // After actions_linkedfiles, if action were renamefile, we set it to 'file_manager' 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' + 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; } @@ -311,7 +328,7 @@ if ($action == 'unseteditinline') if ($action == 'setshowsubcontainers') { dolibarr_set_const($db, 'WEBSITE_SUBCONTAINERSINLINE', 1); - dolibarr_set_const($db, 'WEBSITE_EDITINLINE', 0); // Force disable of edit inline + 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; } @@ -357,28 +374,28 @@ 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) { - $tmpobject=new Website($db); + $tmpobject = new Website($db); $tmpobject->ref = GETPOST('WEBSITE_REF', 'alpha'); $tmpobject->description = GETPOST('WEBSITE_DESCRIPTION', 'alpha'); $tmpobject->virtualhost = GETPOST('virtualhost', 'alpha'); @@ -391,11 +408,11 @@ if ($action == 'addsite') } } - if (! $error) + if (!$error) { $db->commit(); setEventMessages($langs->trans("SiteAdded", $object->ref), null, 'mesgs'); - $action=''; + $action = ''; header("Location: ".$_SERVER["PHP_SELF"].'?website='.$tmpobject->ref); exit; @@ -403,10 +420,10 @@ if ($action == 'addsite') else { $db->rollback(); - $action='createsite'; + $action = 'createsite'; } - if (! $error) + if (!$error) { $action = 'preview'; $id = $object->id; @@ -423,9 +440,9 @@ if ($action == 'addcontainer') $objectpage->fk_website = $object->id; if (GETPOSTISSET('fetchexternalurl')) { - $urltograb=GETPOST('externalurl', 'alpha'); - $grabimages=GETPOST('grabimages', 'alpha'); - $grabimagesinto=GETPOST('grabimagesinto', 'alpha'); + $urltograb = GETPOST('externalurl', 'alpha'); + $grabimages = GETPOST('grabimages', 'alpha'); + $grabimagesinto = GETPOST('grabimagesinto', 'alpha'); //var_dump($grabimages);exit; } @@ -440,7 +457,7 @@ if ($action == 'addcontainer') 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"); @@ -448,16 +465,16 @@ if ($action == 'addcontainer') $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.='/'; + $urltograb .= '/'; } $pageurl = dol_sanitizeFileName(preg_replace('/[\/\.]/', '-', preg_replace('/\/+$/', '', $urltograbwithoutdomainandparam))); @@ -476,31 +493,31 @@ if ($action == 'addcontainer') { setEventMessages($langs->trans("AliasPageAlreadyExists", $pageurl), null, 'errors'); $error++; - $action='createcontainer'; + $action = 'createcontainer'; } } - if (! $error) + if (!$error) { $tmp = getURLContent($urltograb); if ($tmp['curl_error_no']) { $error++; setEventMessages('Error getting '.$urltograb.': '.$tmp['curl_error_msg'], null, 'errors'); - $action='createcontainer'; + $action = 'createcontainer'; } elseif ($tmp['http_code'] != '200') { $error++; setEventMessages('Error getting '.$urltograb.': '.$tmp['http_code'], null, 'errors'); - $action='createcontainer'; + $action = 'createcontainer'; } else { // Remove comments $tmp['content'] = removeHtmlComment($tmp['content']); - $regs=array(); + $regs = array(); preg_match('/(.*)<\/head>/ims', $tmp['content'], $regs); $head = $regs[1]; @@ -510,21 +527,21 @@ if ($action == 'addcontainer') if (empty($objectpage->pageurl)) { $tmpdomain = getDomainFromURL($urltograb); - $objectpage->pageurl=$tmpdomain.'-home'; + $objectpage->pageurl = $tmpdomain.'-home'; } $objectpage->aliasalt = ''; if (preg_match('/^(\d+)\-/', basename($urltograb), $regs)) $objectpage->aliasalt = $regs[1]; - $regtmp=array(); + $regtmp = array(); if (preg_match('/(.*)<\/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 (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)) { @@ -536,7 +553,7 @@ if ($action == 'addcontainer') } if (preg_match('/<html\s+lang="([^"]+)"/ims', $tmp['content'], $regtmp)) { - $tmplang=explode('-', $regtmp[1]); + $tmplang = explode('-', $regtmp[1]); $objectpage->lang = $tmplang[0].($tmplang[1] ? '_'.strtoupper($tmplang[1]) : ''); } @@ -546,7 +563,7 @@ if ($action == 'addcontainer') $objectpage->content = preg_replace('/^.*<body(\s[^>]*)*>/ims', '', $objectpage->content); $objectpage->content = preg_replace('/<\/body(\s[^>]*)*>.*$/ims', '', $objectpage->content); - $absoluteurlinaction=$urltograbdirwithoutslash; + $absoluteurlinaction = $urltograbdirwithoutslash; // TODO Replace 'action="$urltograbdirwithoutslash' into action="/" // TODO Replace 'action="$urltograbdirwithoutslash..."' into action="..." // TODO Replace 'a href="$urltograbdirwithoutslash' into a href="/" @@ -581,11 +598,11 @@ if ($action == 'addcontainer') $linkwithoutdomain = $regs[2][$key]; if (preg_match('/^\//', $regs[2][$key])) { - $urltograbbis = $urltograbdirrootwithoutslash.$regs[2][$key]; // We use dirroot + $urltograbbis = $urltograbdirrootwithoutslash.$regs[2][$key]; // We use dirroot } else { - $urltograbbis = $urltograbdirwithoutslash.'/'.$regs[2][$key]; // We use dir of grabbed file + $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]; @@ -650,11 +667,11 @@ if ($action == 'addcontainer') $linkwithoutdomain = $regs[2][$key]; if (preg_match('/^\//', $regs[2][$key])) { - $urltograbbis = $urltograbdirrootwithoutslash.$regs[2][$key]; // We use dirroot + $urltograbbis = $urltograbdirrootwithoutslash.$regs[2][$key]; // We use dirroot } else { - $urltograbbis = $urltograbdirwithoutslash.'/'.$regs[2][$key]; // We use dir of grabbed file + $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]; @@ -679,14 +696,14 @@ if ($action == 'addcontainer') $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'; + $action = 'createcontainer'; } 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'; + $action = 'createcontainer'; } else { @@ -709,7 +726,7 @@ if ($action == 'addcontainer') // @chmod($file, octdec($conf->global->MAIN_UMASK)); // $filename = 'image/'.$object->ref.'/'.$objectpage->pageurl.(preg_match('/^\//', $linkwithoutdomain)?'':'/').$linkwithoutdomain; - $pagecsscontent.='/* Content of file '.$urltograbbis.' */'."\n"; + $pagecsscontent .= '/* Content of file '.$urltograbbis.' */'."\n"; getAllImages($object, $objectpage, $urltograbbis, $tmpgeturl['content'], $action, 1, $grabimages, $grabimagesinto); @@ -721,19 +738,19 @@ if ($action == 'addcontainer') $contentforlessc = $lesscobj->compile($contentforlessc); //var_dump($contentforlessc); exit; - $pagecsscontent.=$contentforlessc."\n"; + $pagecsscontent .= $contentforlessc."\n"; //$pagecsscontent.=$tmpgeturl['content']."\n"; } catch (exception $e) { //echo "failed to compile lessc"; dol_syslog("Failed to compile the CSS from URL ".$urltograbbis." with lessc: ".$e->getMessage(), LOG_WARNING); - $pagecsscontent.=$tmpgeturl['content']."\n"; + $pagecsscontent .= $tmpgeturl['content']."\n"; } $objectpage->htmlheader = preg_replace('/'.preg_quote($regs[0][$key], '/').'\n*/ims', '', $objectpage->htmlheader); } } - $pagecsscontent.='</style>'; + $pagecsscontent .= '</style>'; //var_dump($pagecsscontent); //print dol_escape_htmltag($tmp);exit; @@ -769,11 +786,11 @@ if ($action == 'addcontainer') $objectpage->lang = GETPOST('WEBSITE_LANG', 'aZ09'); $objectpage->htmlheader = GETPOST('htmlheader', 'none'); - $substitutionarray=array(); - $substitutionarray['__WEBSITE_CREATE_BY__']=$user->getFullName($langs); + $substitutionarray = array(); + $substitutionarray['__WEBSITE_CREATE_BY__'] = $user->getFullName($langs); $sample = GETPOST('sample', 'alpha'); - if (empty($sample)) $sample='empty'; + if (empty($sample)) $sample = 'empty'; $pathtosample = DOL_DOCUMENT_ROOT.'/website/samples/page-sample-'.$sample.'.html'; @@ -781,57 +798,57 @@ if ($action == 'addcontainer') $objectpage->content = make_substitutions(@file_get_contents($pathtosample), $substitutionarray); } - if (! $error) + if (!$error) { if (empty($objectpage->pageurl)) { $langs->load("errors"); setEventMessages($langs->trans("ErrorFieldRequired", $langs->transnoentitiesnoconv("WEBSITE_PAGENAME")), null, 'errors'); $error++; - $action='createcontainer'; + $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'; + $action = 'createcontainer'; } if (empty($objectpage->title)) { $langs->load("errors"); setEventMessages($langs->trans("ErrorFieldRequired", $langs->transnoentitiesnoconv("WEBSITE_TITLE")), null, 'errors'); $error++; - $action='createcontainer'; + $action = 'createcontainer'; } } - if (! $error) + if (!$error) { $res = $objectpage->create($user); if ($res <= 0) { $error++; setEventMessages($objectpage->error, $objectpage->errors, 'errors'); - $action='createcontainer'; + $action = 'createcontainer'; } } - if (! $error) + if (!$error) { - if (! empty($objectpage->content)) + if (!empty($objectpage->content)) { - $filealias=$pathofwebsite.'/'.$objectpage->pageurl.'.php'; - $filetpl=$pathofwebsite.'/page'.$objectpage->id.'.tpl.php'; + $filealias = $pathofwebsite.'/'.$objectpage->pageurl.'.php'; + $filetpl = $pathofwebsite.'/page'.$objectpage->id.'.tpl.php'; // Save page alias - $result=dolSavePageAlias($filealias, $object, $objectpage); - if (! $result) + $result = dolSavePageAlias($filealias, $object, $objectpage); + if (!$result) { setEventMessages('Failed to write file '.$filealias, null, 'errors'); } // Save page of content - $result=dolSavePageContent($filetpl, $object, $objectpage); + $result = dolSavePageContent($filetpl, $object, $objectpage); if ($result) { setEventMessages($langs->trans("Saved"), null, 'mesgs'); @@ -843,75 +860,75 @@ if ($action == 'addcontainer') } } } - if (! $error) + if (!$error) { $db->commit(); setEventMessages($langs->trans("PageAdded", $objectpage->pageurl), null, 'mesgs'); - $action=''; + $action = ''; } else { $db->rollback(); } - if (! $error) + if (!$error) { $pageid = $objectpage->id; // To generate the CSS, robot and htmlheader file. // Check symlink to medias and restore it if ko - $pathtomedias=DOL_DATA_ROOT.'/medias'; - $pathtomediasinwebsite=$pathofwebsite.'/medias'; - if (! is_link(dol_osencode($pathtomediasinwebsite))) + $pathtomedias = DOL_DATA_ROOT.'/medias'; + $pathtomediasinwebsite = $pathofwebsite.'/medias'; + 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 + dol_mkdir(dirname($pathtomediasinwebsite)); // To be sure dir for website exists $result = symlink($pathtomedias, $pathtomediasinwebsite); } - if (! dol_is_file($filehtmlheader)) + if (!dol_is_file($filehtmlheader)) { - $htmlheadercontent ="<html>\n"; - $htmlheadercontent.=$htmlheadercontentdefault; - $htmlheadercontent.="</html>"; - $result=dolSaveHtmlHeader($filehtmlheader, $htmlheadercontent); + $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); + $result = dolSaveCssFile($filecss, $csscontent); } - if (! dol_is_file($filejs)) + if (!dol_is_file($filejs)) { $jscontent = "/* JS content (all pages) */\n"; - $result=dolSaveJsFile($filejs, $jscontent); + $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); + $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); + $result = dolSaveHtaccessFile($filehtaccess, $htaccesscontent); } - if (! dol_is_file($filemanifestjson)) + if (!dol_is_file($filemanifestjson)) { $manifestjsoncontent = ""; - $result=dolSaveManifestJson($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); + $result = dolSaveReadme($filereadme, $readmecontent); } $action = 'preview'; @@ -937,23 +954,23 @@ if ($action == 'confirm_deletesite' && $confirm == 'yes') setEventMessages($object->error, $object->errors, 'errors'); } } - if (! $error) + if (!$error) { if (GETPOST('delete_also_js', 'alpha') == 'on') { - $pathofwebsitejs=DOL_DATA_ROOT.'/medias/js/'.$object->ref; + $pathofwebsitejs = DOL_DATA_ROOT.'/medias/js/'.$object->ref; dol_delete_dir_recursive($pathofwebsitejs); } if (GETPOST('delete_also_medias', 'alpha') == 'on') { - $pathofwebsitemedias=DOL_DATA_ROOT.'/medias/image/'.$object->ref; + $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'); @@ -990,7 +1007,7 @@ if ($action == 'delete') } } - if (! $error) + if (!$error) { $db->commit(); setEventMessages($langs->trans("PageDeleted", $objectpage->pageurl, $websitekey), null, 'mesgs'); @@ -1009,9 +1026,9 @@ if ($action == 'delete') 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'; + $action = 'editcss'; } else { @@ -1020,14 +1037,14 @@ if ($action == 'updatecss') if (GETPOSTISSET('virtualhost')) { - 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'); - $action='editcss'; + $action = 'editcss'; } - if (! $error) + if (!$error) { $object->virtualhost = GETPOST('virtualhost', 'alpha'); @@ -1036,15 +1053,15 @@ if ($action == 'updatecss') { $error++; setEventMessages($object->error, $object->errors, 'errors'); - $action='editcss'; + $action = 'editcss'; } } } - if (! $error) + if (!$error) { // Save master.inc.php file - $filemaster=$pathofwebsite.'/master.inc.php'; + $filemaster = $pathofwebsite.'/master.inc.php'; dol_syslog("Save master file ".$filemaster); @@ -1052,7 +1069,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'); @@ -1060,7 +1077,7 @@ if ($action == 'updatecss') // Html header file - $htmlheadercontent =''; + $htmlheadercontent = ''; /* We disable php code since htmlheader is never executed as an include but only read by fgets_content. $htmlheadercontent.= "<?php // BEGIN PHP\n"; @@ -1072,7 +1089,7 @@ if ($action == 'updatecss') // $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 .= 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"; @@ -1081,7 +1098,7 @@ if ($action == 'updatecss') $htmlheadercontent = trim($htmlheadercontent)."\n"; $result = dolSaveHtmlHeader($filehtmlheader, $htmlheadercontent); - if (! $result) + if (!$result) { $error++; setEventMessages('Failed to write file '.$filehtmlheader, null, 'errors'); @@ -1089,30 +1106,30 @@ if ($action == 'updatecss') // Css file - $csscontent =''; + $csscontent = ''; - $csscontent.= "<?php // BEGIN PHP\n"; - $csscontent.= '$websitekey=basename(__DIR__);'."\n"; - $csscontent.= "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. - $csscontent.= "require_once DOL_DOCUMENT_ROOT.'/core/lib/website.lib.php';\n"; - $csscontent.= "require_once DOL_DOCUMENT_ROOT.'/core/website.inc.php';\n"; - $csscontent.= "ob_start();\n"; - $csscontent.= "if (! headers_sent()) { /* because file is included inline when in edit mode and we don't want warning */ \n"; - $csscontent.= "header('Cache-Control: max-age=3600, public, must-revalidate');\n"; - $csscontent.= "header('Content-type: text/css');\n"; - $csscontent.= "}\n"; - $csscontent.= "// END PHP ?>\n"; + $csscontent .= "<?php // BEGIN PHP\n"; + $csscontent .= '$websitekey=basename(__DIR__);'."\n"; + $csscontent .= "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. + $csscontent .= "require_once DOL_DOCUMENT_ROOT.'/core/lib/website.lib.php';\n"; + $csscontent .= "require_once DOL_DOCUMENT_ROOT.'/core/website.inc.php';\n"; + $csscontent .= "ob_start();\n"; + $csscontent .= "if (! headers_sent()) { /* because file is included inline when in edit mode and we don't want warning */ \n"; + $csscontent .= "header('Cache-Control: max-age=3600, public, must-revalidate');\n"; + $csscontent .= "header('Content-type: text/css');\n"; + $csscontent .= "}\n"; + $csscontent .= "// END PHP ?>\n"; - $csscontent.= trim(GETPOST('WEBSITE_CSS_INLINE', 'none'))."\n"; + $csscontent .= trim(GETPOST('WEBSITE_CSS_INLINE', 'none'))."\n"; - $csscontent.= '<?php // BEGIN PHP'."\n"; - $csscontent.= '$tmp = ob_get_contents(); ob_end_clean(); dolWebsiteOutput($tmp, "css");'."\n"; - $csscontent.= "// END PHP ?>"."\n"; + $csscontent .= '<?php // BEGIN PHP'."\n"; + $csscontent .= '$tmp = ob_get_contents(); ob_end_clean(); dolWebsiteOutput($tmp, "css");'."\n"; + $csscontent .= "// END PHP ?>"."\n"; dol_syslog("Save css content into ".$filecss); $result = dolSaveCssFile($filecss, $csscontent); - if (! $result) + if (!$result) { $error++; setEventMessages('Failed to write file '.$filecss, null, 'errors'); @@ -1120,26 +1137,26 @@ if ($action == 'updatecss') // Js file - $jscontent =''; + $jscontent = ''; - $jscontent.= "<?php // BEGIN PHP\n"; - $jscontent.= '$websitekey=basename(__DIR__);'."\n"; - $jscontent.= "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. - $jscontent.= "require_once DOL_DOCUMENT_ROOT.'/core/lib/website.lib.php';\n"; - $jscontent.= "require_once DOL_DOCUMENT_ROOT.'/core/website.inc.php';\n"; - $jscontent.= "ob_start();\n"; - $jscontent.= "header('Cache-Control: max-age=3600, public, must-revalidate');\n"; - $jscontent.= "header('Content-type: application/javascript');\n"; - $jscontent.= "// END PHP ?>\n"; + $jscontent .= "<?php // BEGIN PHP\n"; + $jscontent .= '$websitekey=basename(__DIR__);'."\n"; + $jscontent .= "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. + $jscontent .= "require_once DOL_DOCUMENT_ROOT.'/core/lib/website.lib.php';\n"; + $jscontent .= "require_once DOL_DOCUMENT_ROOT.'/core/website.inc.php';\n"; + $jscontent .= "ob_start();\n"; + $jscontent .= "header('Cache-Control: max-age=3600, public, must-revalidate');\n"; + $jscontent .= "header('Content-type: application/javascript');\n"; + $jscontent .= "// END PHP ?>\n"; - $jscontent.= trim(GETPOST('WEBSITE_JS_INLINE', 'none'))."\n"; + $jscontent .= trim(GETPOST('WEBSITE_JS_INLINE', 'none'))."\n"; - $jscontent.= '<?php // BEGIN PHP'."\n"; - $jscontent.= '$tmp = ob_get_contents(); ob_end_clean(); dolWebsiteOutput($tmp, "js");'."\n"; - $jscontent.= "// END PHP ?>"."\n"; + $jscontent .= '<?php // BEGIN PHP'."\n"; + $jscontent .= '$tmp = ob_get_contents(); ob_end_clean(); dolWebsiteOutput($tmp, "js");'."\n"; + $jscontent .= "// END PHP ?>"."\n"; $result = dolSaveJsFile($filejs, $jscontent); - if (! $result) + if (!$result) { $error++; setEventMessages('Failed to write file '.$filejs, null, 'errors'); @@ -1147,7 +1164,7 @@ if ($action == 'updatecss') // Robot file - $robotcontent =''; + $robotcontent = ''; /*$robotcontent.= "<?php // BEGIN PHP\n"; $robotcontent.= '$websitekey=basename(__DIR__);'."\n"; @@ -1159,14 +1176,14 @@ if ($action == 'updatecss') $robotcontent.= "header('Content-type: text/css');\n"; $robotcontent.= "// END PHP ?>\n";*/ - $robotcontent.= trim(GETPOST('WEBSITE_ROBOT', 'none'))."\n"; + $robotcontent .= trim(GETPOST('WEBSITE_ROBOT', 'none'))."\n"; /*$robotcontent.= "\n".'<?php // BEGIN 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'); @@ -1174,11 +1191,11 @@ if ($action == 'updatecss') // Htaccess file - $htaccesscontent =''; - $htaccesscontent.= trim(GETPOST('WEBSITE_HTACCESS', 'none'))."\n"; + $htaccesscontent = ''; + $htaccesscontent .= trim(GETPOST('WEBSITE_HTACCESS', 'none'))."\n"; $result = dolSaveHtaccessFile($filehtaccess, $htaccesscontent); - if (! $result) + if (!$result) { $error++; setEventMessages('Failed to write file '.$filehtaccess, null, 'errors'); @@ -1186,26 +1203,26 @@ if ($action == 'updatecss') // manifest.json file - $manifestjsoncontent =''; + $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) + if (!$result) { $error++; setEventMessages('Failed to write file '.$filemanifestjson, null, 'errors'); @@ -1213,7 +1230,7 @@ if ($action == 'updatecss') // README.md file - $readmecontent =''; + $readmecontent = ''; /*$readmecontent.= "<?php // BEGIN PHP\n"; $readmecontent.= '$websitekey=basename(__DIR__);'."\n"; @@ -1225,14 +1242,14 @@ if ($action == 'updatecss') $readmecontent.= "header('Content-type: application/manifest+json');\n"; $readmecontent.= "// END PHP ?>\n";*/ - $readmecontent.= trim(GETPOST('WEBSITE_README', 'none'))."\n"; + $readmecontent .= trim(GETPOST('WEBSITE_README', 'none'))."\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) + if (!$result) { $error++; setEventMessages('Failed to write file '.$filereadme, null, 'errors'); @@ -1240,14 +1257,14 @@ if ($action == 'updatecss') // 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'; + $action = 'preview'; if ($backtopage) { header("Location: ".$backtopage); @@ -1271,13 +1288,13 @@ if ($action == 'setashome') $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(); @@ -1288,7 +1305,7 @@ if ($action == 'setashome') if ($result) setEventMessages($langs->trans("Saved"), null, 'mesgs'); else setEventMessages('Failed to write file '.$fileindex, null, 'errors'); - $action='preview'; + $action = 'preview'; } else { @@ -1307,12 +1324,12 @@ 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'); - $action='editmeta'; + $action = 'editmeta'; } $res = $objectpage->fetch($pageid, $object->id); @@ -1323,9 +1340,9 @@ if ($action == 'updatemeta') } // Check alias not exists - if (! $error && GETPOST('WEBSITE_PAGENAME', 'alpha')) + if (!$error && GETPOST('WEBSITE_PAGENAME', 'alpha')) { - $websitepagetemp=new WebsitePage($db); + $websitepagetemp = new WebsitePage($db); $result = $websitepagetemp->fetch(-1 * $objectpage->id, $object->id, GETPOST('WEBSITE_PAGENAME', 'alpha')); if ($result < 0) { @@ -1342,11 +1359,11 @@ if ($action == 'updatemeta') $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) + $arrayofaliastotest = explode(',', GETPOST('WEBSITE_ALIASALT', 'alpha')); + $websitepagetemp = new WebsitePage($db); + foreach ($arrayofaliastotest as $aliastotest) { $result = $websitepagetemp->fetch(-1 * $objectpage->id, $object->id, $aliastotest); if ($result < 0) @@ -1368,7 +1385,7 @@ if ($action == 'updatemeta') } } - if (! $error) + if (!$error) { $objectpage->old_object = clone $objectpage; @@ -1381,13 +1398,13 @@ if ($action == 'updatemeta') $objectpage->keywords = GETPOST('WEBSITE_KEYWORDS', 'alpha'); $objectpage->lang = GETPOST('WEBSITE_LANG', 'aZ09'); $objectpage->htmlheader = trim(GETPOST('htmlheader', 'none')); - $objectpage->fk_page = GETPOST('pageidfortranslation', 'int'); + $objectpage->fk_page = (GETPOST('pageidfortranslation', 'int') > 0 ? GETPOST('pageidfortranslation', 'int') : 0); - $newdatecreation=dol_mktime(GETPOST('datecreationhour', 'int'), GETPOST('datecreationmin', 'int'), GETPOST('datecreationsec', 'int'), GETPOST('datecreationmonth', 'int'), GETPOST('datecreationday', 'int'), GETPOST('datecreationyear', 'int')); + $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; $res = $objectpage->update($user); - if (! ($res > 0)) + if (!($res > 0)) { $langs->load("errors"); if ($db->lasterrno == 'DB_ERROR_RECORD_ALREADY_EXISTS') @@ -1407,7 +1424,7 @@ if ($action == 'updatemeta') } } - if (! $error) + if (!$error) { $db->commit(); } @@ -1416,32 +1433,32 @@ if ($action == 'updatemeta') $db->rollback(); } - if (! $error) + if (!$error) { - $filemaster=$pathofwebsite.'/master.inc.php'; - $fileoldalias=$pathofwebsite.'/'.$objectpage->old_object->pageurl.'.php'; - $filealias=$pathofwebsite.'/'.$objectpage->pageurl.'.php'; + $filemaster = $pathofwebsite.'/master.inc.php'; + $fileoldalias = $pathofwebsite.'/'.$objectpage->old_object->pageurl.'.php'; + $filealias = $pathofwebsite.'/'.$objectpage->pageurl.'.php'; dol_mkdir($pathofwebsite); // 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); } // 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); + $tmpaltaliases = explode(',', $objectpage->old_object->aliasalt); if (is_array($tmpaltaliases)) { - foreach($tmpaltaliases as $tmpaliasalt) + foreach ($tmpaltaliases as $tmpaliasalt) { dol_syslog("We delete old alt alias pages name=".trim($tmpaliasalt)); dol_delete_file($pathofwebsite.'/'.trim($tmpaliasalt).'.php'); @@ -1450,20 +1467,20 @@ if ($action == 'updatemeta') } // Save page alias - $result=dolSavePageAlias($filealias, $object, $objectpage); - if (! $result) setEventMessages('Failed to write file '.$filealias, null, 'errors'); + $result = dolSavePageAlias($filealias, $object, $objectpage); + 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); + $tmpaltaliases = explode(',', $objectpage->aliasalt); if (is_array($tmpaltaliases)) { - foreach($tmpaltaliases as $tmpaliasalt) + foreach ($tmpaltaliases as $tmpaliasalt) { if (trim($tmpaliasalt)) { - $result=dolSavePageAlias($pathofwebsite.'/'.trim($tmpaliasalt).'.php', $object, $objectpage); - if (! $result) setEventMessages('Failed to write file '.$pathofwebsite.'/'.trim($tmpaliasalt).'.php', null, 'errors'); + $result = dolSavePageAlias($pathofwebsite.'/'.trim($tmpaliasalt).'.php', $object, $objectpage); + if (!$result) setEventMessages('Failed to write file '.$pathofwebsite.'/'.trim($tmpaliasalt).'.php', null, 'errors'); } } } @@ -1471,7 +1488,7 @@ if ($action == 'updatemeta') // Save page of content - $result=dolSavePageContent($filetpl, $object, $objectpage); + $result = dolSavePageContent($filetpl, $object, $objectpage); if ($result) { setEventMessages($langs->trans("Saved"), null, 'mesgs'); @@ -1485,7 +1502,7 @@ if ($action == 'updatemeta') //exit; } - $action='preview'; + $action = 'preview'; } } @@ -1501,12 +1518,12 @@ if (($action == 'updatesource' || $action == 'updatecontent' || $action == 'conf $db->begin(); $objectnew = new Website($db); - $result = $objectnew->createFromClone($user, GETPOST('id', 'int'), GETPOST('siteref', 'aZ09'), (GETPOST('newlang', 'aZ09')?GETPOST('newlang', 'aZ09'):'')); + $result = $objectnew->createFromClone($user, GETPOST('id', 'int'), GETPOST('siteref', 'aZ09'), (GETPOST('newlang', 'aZ09') ?GETPOST('newlang', 'aZ09') : '')); if ($result < 0) { $error++; setEventMessages($objectnew->error, $objectnew->errors, 'errors'); - $action='preview'; + $action = 'preview'; $db->rollback(); } @@ -1523,25 +1540,25 @@ if (($action == 'updatesource' || $action == 'updatecontent' || $action == 'conf if ($action == 'confirm_createpagefromclone') { - $istranslation=(GETPOST('is_a_translation', 'aZ09')=='on'?1:0); + $istranslation = (GETPOST('is_a_translation', 'aZ09') == 'on' ? 1 : 0); if ($istranslation) { if (GETPOST('newlang', 'aZ09') == $objectpage->lang) { $error++; setEventMessages($langs->trans("LanguageMustNotBeSameThanClonedPage"), null, 'errors'); - $action='preview'; + $action = 'preview'; } } - if (! $error) + if (!$error) { $db->begin(); $newwebsiteid = GETPOST('newwebsite', 'int'); $pathofwebsitenew = $pathofwebsite; - $tmpwebsite=new Website($db); + $tmpwebsite = new Website($db); if ($newwebsiteid > 0 && $newwebsiteid != $object->id) { $tmpwebsite->fetch($newwebsiteid); @@ -1553,20 +1570,20 @@ if (($action == 'updatesource' || $action == 'updatecontent' || $action == 'conf } $objectpage = new WebsitePage($db); - $resultpage = $objectpage->createFromClone($user, $pageid, GETPOST('pageurl', 'aZ09'), (GETPOST('newlang', 'aZ09')?GETPOST('newlang', 'aZ09'):''), $istranslation, $newwebsiteid); + $resultpage = $objectpage->createFromClone($user, $pageid, GETPOST('pageurl', 'aZ09'), (GETPOST('newlang', 'aZ09') ?GETPOST('newlang', 'aZ09') : ''), $istranslation, $newwebsiteid); if ($resultpage < 0) { $error++; setEventMessages($objectpage->error, $objectpage->errors, 'errors'); - $action='createpagefromclone'; + $action = 'createpagefromclone'; $db->rollback(); } else { - $fileindex=$pathofwebsitenew.'/index.php'; - $filetpl=$pathofwebsitenew.'/page'.$resultpage->id.'.tpl.php'; - $filewrapper=$pathofwebsitenew.'/wrapper.php'; + $fileindex = $pathofwebsitenew.'/index.php'; + $filetpl = $pathofwebsitenew.'/page'.$resultpage->id.'.tpl.php'; + $filewrapper = $pathofwebsitenew.'/wrapper.php'; //var_dump($pathofwebsitenew); //var_dump($filetpl); @@ -1587,15 +1604,15 @@ 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))) + $pathtomedias = DOL_DATA_ROOT.'/medias'; + $pathtomediasinwebsite = $pathofwebsite.'/medias'; + 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 + dol_mkdir(dirname($pathtomediasinwebsite)); // To be sure dir for website exists $result = symlink($pathtomedias, $pathtomediasinwebsite); } @@ -1613,19 +1630,19 @@ if (($action == 'updatesource' || $action == 'updatecontent' || $action == 'conf } else { - $res=0; + $res = 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 (!$error && $res > 0) { if ($action == 'updatesource' || $action == 'updatecontent') { @@ -1638,12 +1655,12 @@ if (($action == 'updatesource' || $action == 'updatecontent' || $action == 'conf // Security analysis $phpfullcodestring = dolKeepOnlyPhpCode($objectpage->content); //print dol_escape_htmltag($phpfullcodestring);exit; - $forbiddenphpcommands=array("exec", "passthru", "system", "shell_exec", "proc_open"); + $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 { - $forbiddenphpcommands=array_merge($forbiddenphpcommands, array("fopen", "file_put_contents", "fputs", "fputscsv", "fwrite", "fpassthru", "unlink", "mkdir", "rmdir", "symlink", "touch", "umask")); + $forbiddenphpcommands = array_merge($forbiddenphpcommands, array("fopen", "file_put_contents", "fputs", "fputscsv", "fwrite", "fpassthru", "unlink", "mkdir", "rmdir", "symlink", "touch", "umask")); } - foreach($forbiddenphpcommands as $forbiddenphpcommand) + foreach ($forbiddenphpcommands as $forbiddenphpcommand) { if (preg_match('/'.$forbiddenphpcommand.'\s*\(/ms', $phpfullcodestring)) { @@ -1679,13 +1696,13 @@ if (($action == 'updatesource' || $action == 'updatecontent' || $action == 'conf if ($action == 'updatecontent') $action = 'editcontent'; } - if (! $error) + if (!$error) { $db->commit(); - $filemaster=$pathofwebsite.'/master.inc.php'; + $filemaster = $pathofwebsite.'/master.inc.php'; //$fileoldalias=$pathofwebsite.'/'.$objectpage->old_object->pageurl.'.php'; - $filealias=$pathofwebsite.'/'.$objectpage->pageurl.'.php'; + $filealias = $pathofwebsite.'/'.$objectpage->pageurl.'.php'; dol_mkdir($pathofwebsite); @@ -1693,22 +1710,22 @@ if (($action == 'updatesource' || $action == 'updatecontent' || $action == 'conf // 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 generate the alias.php page - if (! empty($fileoldalias)) + if (!empty($fileoldalias)) { dol_syslog("We regenerate alias page new name=".$filealias.", old name=".$fileoldalias); dol_delete_file($fileoldalias); } // Save page alias - $result=dolSavePageAlias($filealias, $object, $objectpage); - if (! $result) setEventMessages('Failed to write file '.$filealias, null, 'errors'); + $result = dolSavePageAlias($filealias, $object, $objectpage); + if (!$result) setEventMessages('Failed to write file '.$filealias, null, 'errors'); // Save page content - $result=dolSavePageContent($filetpl, $object, $objectpage); + $result = dolSavePageContent($filetpl, $object, $objectpage); if ($result) { setEventMessages($langs->trans("Saved"), null, 'mesgs'); @@ -1735,7 +1752,7 @@ if (($action == 'updatesource' || $action == 'updatecontent' || $action == 'conf } else { - if (! $error) + if (!$error) { if (empty($websitekey) || $websitekey == '-1') { @@ -1761,7 +1778,7 @@ if ($action == 'exportsite') header("Content-Type: application/zip"); header("Content-Disposition: attachment; filename=".$file_name); - header("Content-Length: " . filesize($fileofzip)); + header("Content-Length: ".filesize($fileofzip)); readfile($fileofzip); exit; @@ -1776,24 +1793,24 @@ if ($action == 'exportsite') // Import site if ($action == 'importsiteconfirm') { - if (empty($_FILES) && ! GETPOSTISSET('templateuserfile')) + if (empty($_FILES) && !GETPOSTISSET('templateuserfile')) { setEventMessages($langs->trans("ErrorFieldRequired", $langs->transnoentitiesnoconv("File")), null, 'errors'); $action = 'importsite'; } else { - if (! empty($_FILES) || GETPOSTISSET('templateuserfile')) + 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))) + $pathtomedias = DOL_DATA_ROOT.'/medias'; + $pathtomediasinwebsite = $pathofwebsite.'/medias'; + 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 + 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'; @@ -1805,17 +1822,17 @@ if ($action == 'importsiteconfirm') { $fileofzip = DOL_DATA_ROOT.'/doctemplates/websites/'.GETPOST('templateuserfile', 'alpha'); } - elseif (! empty($_FILES)) + elseif (!empty($_FILES)) { - if (is_array($_FILES['userfile']['tmp_name'])) $userfiles=$_FILES['userfile']['tmp_name']; - else $userfiles=array($_FILES['userfile']['tmp_name']); + if (is_array($_FILES['userfile']['tmp_name'])) $userfiles = $_FILES['userfile']['tmp_name']; + else $userfiles = array($_FILES['userfile']['tmp_name']); - foreach($userfiles as $key => $userfile) + foreach ($userfiles as $key => $userfile) { if (empty($_FILES['userfile']['tmp_name'][$key])) { $error++; - if ($_FILES['userfile']['error'][$key] == 1 || $_FILES['userfile']['error'][$key] == 2){ + if ($_FILES['userfile']['error'][$key] == 1 || $_FILES['userfile']['error'][$key] == 2) { setEventMessages($langs->trans('ErrorFileSizeTooLarge'), null, 'errors'); $action = 'importsite'; } @@ -1826,7 +1843,7 @@ if ($action == 'importsiteconfirm') } } - if (! $error) + if (!$error) { $upload_dir = $conf->website->dir_temp; $result = dol_add_file_process($upload_dir, 1, -1, 'userfile', ''); @@ -1834,16 +1851,16 @@ if ($action == 'importsiteconfirm') // Get name of file (take last one if several name provided) $fileofzip = $upload_dir.'/unknown'; - foreach($_FILES as $key => $ifile) + foreach ($_FILES as $key => $ifile) { - foreach($ifile['name'] as $key2 => $ifile2) + foreach ($ifile['name'] as $key2 => $ifile2) { - $fileofzip = $upload_dir . '/' .$ifile2; + $fileofzip = $upload_dir.'/'.$ifile2; } } } - if (! $error) + if (!$error) { $result = $object->importWebSite($fileofzip); if ($result < 0) @@ -1876,7 +1893,7 @@ $formadmin = new FormAdmin($db); $formwebsite = new FormWebsite($db); $formother = new FormOther($db); -$help_url=''; +$help_url = ''; $arrayofjs = array( '/includes/ace/src/ace.js', @@ -1887,16 +1904,16 @@ $arrayofjs = array( ); $arrayofcss = array(); -$moreheadcss=''; -$moreheadjs=''; +$moreheadcss = ''; +$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"; +$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"; -$moreheadjs.='<script type="text/javascript">'."\n"; -$moreheadjs.='var indicatorBlockUI = \''.DOL_URL_ROOT."/theme/".$conf->theme."/img/working.gif".'\';'."\n"; -$moreheadjs.='</script>'."\n"; +$moreheadjs .= '<script type="text/javascript">'."\n"; +$moreheadjs .= 'var indicatorBlockUI = \''.DOL_URL_ROOT."/theme/".$conf->theme."/img/working.gif".'\';'."\n"; +$moreheadjs .= '</script>'."\n"; llxHeader($moreheadcss.$moreheadjs, $langs->trans("WebsiteSetup"), $help_url, '', 0, 0, $arrayofjs, $arrayofcss, '', '', '<!-- Begin div class="fiche" -->'."\n".'<div class="fichebutwithotherclass">'); @@ -1961,12 +1978,15 @@ if ($action == 'replacesiteconfirm') print '<div>'; // Add a margin under toolbar ? -$style=''; -if ($action != 'preview' && $action != 'editcontent' && $action != 'editsource') $style=' margin-bottom: 5px;'; +$style = ''; +if ($action != 'preview' && $action != 'editcontent' && $action != 'editsource') $style = ' margin-bottom: 5px;'; -if (! GETPOST('hide_websitemenu')) +if (!GETPOST('hide_websitemenu')) { + $disabled=''; + if (empty($user->rights->website->write)) $disabled=' disabled="disabled"'; + //var_dump($objectpage);exit; print '<div class="centpercent websitebar">'; @@ -1978,29 +1998,30 @@ if (! GETPOST('hide_websitemenu')) print '</span>'; print '<span class="websiteselection hideonsmartphoneimp">'; - print ' <input type="submit"'.$disabled.' class="button" value="'.dol_escape_htmltag($langs->trans("Add")).'" name="createsite">'; + print '<a href="'.$_SERVER["PHP_SEFL"].'?action=createsite&website='.$website->ref.'" class="button bordertransp"'.$disabled.' title="'.dol_escape_htmltag($langs->trans("AddWebsite")).'"><span class="fa fa-plus-circle valignmiddle btnTitle-icon"><span></a>'; + //print ' <input type="submit"'.$disabled.' class="button" value="'.dol_escape_htmltag($langs->trans("Add")).'" name="createsite">'; print '</span>'; // List of website print '<span class="websiteselection">'; - $out=''; - $out.='<select name="website" class="minwidth100 maxwidth300" id="website">'; - if (empty($object->records)) $out.='<option value="-1"> </option>'; + $out = ''; + $out .= '<select name="website" class="minwidth100 maxwidth300" id="website">'; + if (empty($object->records)) $out .= '<option value="-1"> </option>'; // Loop on each sites - $i=0; - foreach($object->records as $key => $valwebsite) + $i = 0; + foreach ($object->records as $key => $valwebsite) { - if (empty($websitekey)) $websitekey=$valwebsite->ref; + if (empty($websitekey)) $websitekey = $valwebsite->ref; - $out.='<option value="'.$valwebsite->ref.'"'; - if ($websitekey == $valwebsite->ref) $out.=' selected'; // To preselect a value - $out.='>'; - $out.=$valwebsite->ref; - $out.='</option>'; + $out .= '<option value="'.$valwebsite->ref.'"'; + if ($websitekey == $valwebsite->ref) $out .= ' selected'; // To preselect a value + $out .= '>'; + $out .= $valwebsite->ref; + $out .= '</option>'; $i++; } - $out.='</select>'; - $out.=ajax_combobox('website'); + $out .= '</select>'; + $out .= ajax_combobox('website'); print $out; //print '<input type="submit" class="button" name="refreshsite" value="'.$langs->trans("Load").'">'; print '<input type="image" class="valignmiddle" src="'.img_picto('', 'refresh', '', 0, 1).'" name="refreshsite" value="'.$langs->trans("Load").'">'; @@ -2024,9 +2045,6 @@ if (! GETPOST('hide_websitemenu')) if ($websitekey && $websitekey != '-1' && ($action == 'preview' || $action == 'createfromclone' || $action == 'createpagefromclone' || $action == 'deletesite')) { - $disabled=''; - if (empty($user->rights->website->write)) $disabled=' disabled="disabled"'; - print '   '; print '<input type="submit" class="button bordertransp"'.$disabled.' value="'.dol_escape_htmltag($langs->trans("EditCss")).'" name="editcss">'; @@ -2044,7 +2062,7 @@ if (! GETPOST('hide_websitemenu')) print '<input type="submit" class="button bordertransp"'.$disabled.' value="'.dol_escape_htmltag($langs->trans("ExportSite")).'" name="exportsite">'; print '<input type="submit" class="button bordertransp"'.$disabled.' value="'.dol_escape_htmltag($langs->trans("CloneSite")).'" name="createfromclone">'; - print '<input type="submit" class="buttonDelete bordertransp" name="deletesite" value="'.$langs->trans("Delete").'"'.($atleastonepage?' disabled="disabled"':'').'>'; + print '<input type="submit" class="buttonDelete bordertransp" name="deletesite" value="'.$langs->trans("Delete").'"'.($atleastonepage ? ' disabled="disabled"' : '').'>'; print '   '; @@ -2080,48 +2098,48 @@ if (! GETPOST('hide_websitemenu')) if ($action == 'preview' || $action == 'createfromclone' || $action == 'createpagefromclone' || $action == 'deletesite') { - $urlext=$virtualurl; - $urlint=$urlwithroot.'/public/website/index.php?website='.$websitekey; + $urlext = $virtualurl; + $urlint = $urlwithroot.'/public/website/index.php?website='.$websitekey; print '<span class="websiteinputurl valignmiddle" id="websiteinputurl">'; - $linktotestonwebserver = '<a href="'.($virtualurl?$virtualurl:'#').'" class="valignmiddle">'; - $linktotestonwebserver.= $langs->trans("TestDeployOnWeb", $virtualurl).' '.img_picto('', 'globe'); - $linktotestonwebserver.= '</a>'; + $linktotestonwebserver = '<a href="'.($virtualurl ? $virtualurl : '#').'" class="valignmiddle">'; + $linktotestonwebserver .= $langs->trans("TestDeployOnWeb", $virtualurl).' '.img_picto('', 'globe'); + $linktotestonwebserver .= '</a>'; $htmltext = ''; if (empty($object->fk_default_home)) { - $htmltext.= '<br><span class="error">'.$langs->trans("YouMustDefineTheHomePage").'</span><br><br>'; + $htmltext .= '<br><span class="error">'.$langs->trans("YouMustDefineTheHomePage").'</span><br><br>'; } elseif (empty($virtualurl)) { - $htmltext.= '<br><span class="error">'.$langs->trans("VirtualHostUrlNotDefined").'</span><br><br>'; + $htmltext .= '<br><span class="error">'.$langs->trans("VirtualHostUrlNotDefined").'</span><br><br>'; } else { - $htmltext.= '<br><center>'.$langs->trans("GoTo").' <a href="'.$virtualurl.'" target="_website">'.$virtualurl.'</a></center><br>'; + $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); + $htmltext .= '<br>'.$langs->trans($conf->global->WEBSITE_REPLACE_INFO_ABOUT_USAGE_WITH_WEBSERVER); } else { - $htmltext.=$langs->trans("SetHereVirtualHost", $dataroot); - $htmltext.='<br>'; - $htmltext.='<br>'.$langs->trans("CheckVirtualHostPerms", $langs->transnoentitiesnoconv("ReadPerm"), DOL_DOCUMENT_ROOT); - $htmltext.='<br>'.$langs->trans("CheckVirtualHostPerms", $langs->transnoentitiesnoconv("WritePerm"), DOL_DATA_ROOT.'/website<br>'.DOL_DATA_ROOT.'/medias'); - $htmltext.='<br>'; - $htmltext.='<br>'; - $htmltext.=$langs->trans("YouCanAlsoTestWithPHPS", $dataroot); - $htmltext.='<br>'; - $htmltext.='<br>'; - $htmltext.=$langs->trans("YouCanAlsoDeployToAnotherWHP"); + $htmltext .= $langs->trans("SetHereVirtualHost", $dataroot); + $htmltext .= '<br>'; + $htmltext .= '<br>'.$langs->trans("CheckVirtualHostPerms", $langs->transnoentitiesnoconv("ReadPerm"), DOL_DOCUMENT_ROOT); + $htmltext .= '<br>'.$langs->trans("CheckVirtualHostPerms", $langs->transnoentitiesnoconv("WritePerm"), DOL_DATA_ROOT.'/website<br>'.DOL_DATA_ROOT.'/medias'); + $htmltext .= '<br>'; + $htmltext .= '<br>'; + $htmltext .= $langs->trans("YouCanAlsoTestWithPHPS", $dataroot); + $htmltext .= '<br>'; + $htmltext .= '<br>'; + $htmltext .= $langs->trans("YouCanAlsoDeployToAnotherWHP"); } print $form->textwithpicto($linktotestonwebserver, $htmltext, 1, 'none', 'valignmiddle', 0, 3, 'helpvirtualhost'); print '</span>'; } - if (in_array($action, array('editcss','editmenu','file_manager','replacesite','replacesiteconfirm'))) + if (in_array($action, array('editcss', 'editmenu', 'file_manager', 'replacesite', 'replacesiteconfirm'))) { if ($action == 'editcss' && $action != 'file_manager' && $action != 'replacesite' && $action != 'replacesiteconfirm') 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" value="'.dol_escape_htmltag($langs->trans("Save")).'" name="update">'; @@ -2134,26 +2152,27 @@ if (! GETPOST('hide_websitemenu')) // Toolbar for pages - if ($websitekey && $websitekey != '-1' && ! in_array($action, array('editcss','editmenu','importsite'))) + if ($websitekey && $websitekey != '-1' && !in_array($action, array('editcss', 'editmenu', 'importsite'))) { - print '</div>'; // Close current websitebar to open a new one + print '</div>'; // Close current websitebar to open a new one print '<!-- Bar for websitepage -->'; - print '<div class="centpercent websitebar"'.($style?' style="'.$style.'"':'').'">'; + print '<div class="centpercent websitebar"'.($style ? ' style="'.$style.'"' : '').'">'; print '<span class="websiteselection hideonsmartphoneimp minwidth100 tdoverflowmax100">'; print $langs->trans("PageContainer").': '; print '</span>'; print '<span class="websiteselection hideonsmartphoneimp">'; - print '<input type="submit"'.$disabled.' class="button" value="'.dol_escape_htmltag($langs->trans("Add")).'" name="createcontainer">'; + //print '<input type="submit"'.$disabled.' class="button" value="'.dol_escape_htmltag($langs->trans("Add")).'" name="createcontainer">'; + print '<a href="'.$_SERVER["PHP_SEFL"].'?action=createcontainer&website='.$website->ref.'" class="button bordertransp"'.$disabled.' title="'.dol_escape_htmltag($langs->trans("AddPage")).'"><span class="fa fa-plus-circle valignmiddle btnTitle-icon"><span></a>'; print '</span>'; //print '<span class="websiteselection">'; if ($action != 'addcontainer') { - print $formwebsite->selectContainer($website, 'pageid', $pageid, 0, $action); + print '<span class="websiteselection">'.$formwebsite->selectContainer($website, 'pageid', $pageid, 0, $action).'</span>'; } else { @@ -2161,12 +2180,12 @@ if (! GETPOST('hide_websitemenu')) } //print '<input type="submit" class="button" name="refreshpage" value="'.$langs->trans("Load").'"'.($atleastonepage?'':' disabled="disabled"').'>'; - print '<input type="image" class="valignmiddle" src="'.img_picto('', 'refresh', '', 0, 1).'" name="refreshpage" value="'.$langs->trans("Load").'"'.(($atleastonepage && $action != 'editsource')?'':' disabled="disabled"').'>'; + print '<input type="image" class="valignmiddle" src="'.img_picto('', 'refresh', '', 0, 1).'" name="refreshpage" value="'.$langs->trans("Load").'"'.(($atleastonepage && $action != 'editsource') ? '' : ' disabled="disabled"').'>'; // Print nav arrows - $pagepreviousid=0; - $pagenextid=0; + $pagepreviousid = 0; + $pagenextid = 0; if ($pageid) { $sql = 'SELECT MAX(rowid) as pagepreviousid FROM '.MAIN_DB_PREFIX.'website_page WHERE rowid < '.$pageid.' AND fk_website = '.$object->id; @@ -2206,8 +2225,8 @@ if (! GETPOST('hide_websitemenu')) if ($action == 'preview' || $action == 'createfromclone' || $action == 'createpagefromclone' || $action == 'deletesite') { - $disabled=''; - if (empty($user->rights->website->write)) $disabled=' disabled="disabled"'; + $disabled = ''; + if (empty($user->rights->website->write)) $disabled = ' disabled="disabled"'; // Confirmation delete site if ($action == 'deletesite') { @@ -2219,7 +2238,7 @@ if (! GETPOST('hide_websitemenu')) //array('type' => 'other','name' => 'newwebsite','label' => $langs->trans("WebSite"), 'value' => $formwebsite->selectWebsite($object->id, 'newwebsite', 0)) ); - $formconfirm = $form->formconfirm($_SERVER["PHP_SELF"] . '?id='.$object->id, $langs->trans('DeleteWebsite'), '', 'confirm_deletesite', $formquestion, 0, 1, 200); + $formconfirm = $form->formconfirm($_SERVER["PHP_SELF"].'?id='.$object->id, $langs->trans('DeleteWebsite'), '', 'confirm_deletesite', $formquestion, 0, 1, 200); print $formconfirm; } @@ -2228,13 +2247,13 @@ if (! GETPOST('hide_websitemenu')) if ($action == 'createfromclone') { // Create an array for form $formquestion = array( - array('type' => 'text', 'name' => 'siteref', 'label'=> $langs->trans("WebSite") ,'value'=> 'copy_of_'.$object->ref), + array('type' => 'text', 'name' => 'siteref', 'label'=> $langs->trans("WebSite"), 'value'=> 'copy_of_'.$object->ref), //array('type' => 'checkbox', 'name' => 'is_a_translation', 'label' => $langs->trans("SiteIsANewTranslation"), 'value' => 0), //array('type' => 'other','name' => 'newlang','label' => $langs->trans("Language"), 'value' => $formadmin->select_language(GETPOST('newlang', 'aZ09')?GETPOST('newlang', 'aZ09'):$langs->defaultlang, 'newlang', 0, null, '', 0, 0, 'minwidth200')), //array('type' => 'other','name' => 'newwebsite','label' => $langs->trans("WebSite"), 'value' => $formwebsite->selectWebsite($object->id, 'newwebsite', 0)) ); - $formconfirm = $form->formconfirm($_SERVER["PHP_SELF"] . '?id='.$object->id, $langs->trans('CloneSite'), '', 'confirm_createfromclone', $formquestion, 0, 1, 200); + $formconfirm = $form->formconfirm($_SERVER["PHP_SELF"].'?id='.$object->id, $langs->trans('CloneSite'), '', 'confirm_createfromclone', $formquestion, 0, 1, 200); print $formconfirm; } @@ -2248,12 +2267,12 @@ if (! GETPOST('hide_websitemenu')) $formquestion = array( array('type' => 'hidden', 'name' => 'sourcepageurl', 'value'=> $objectpage->pageurl), array('type' => 'checkbox', 'tdclass'=>'maxwidth200', 'name' => 'is_a_translation', 'label' => $langs->trans("PageIsANewTranslation"), 'value' => 0), - array('type' => 'other','name' => 'newlang', 'label' => $langs->trans("Language"), 'value' => $formadmin->select_language($preselectedlanguage, 'newlang', 0, null, 1, 0, 0, 'minwidth200', 0, 1)), - array('type' => 'other','name' => 'newwebsite', 'label' => $langs->trans("WebSite"), 'value' => $formwebsite->selectWebsite($object->id, 'newwebsite', 0)), + array('type' => 'other', 'name' => 'newlang', 'label' => $langs->trans("Language"), 'value' => $formadmin->select_language($preselectedlanguage, 'newlang', 0, null, 1, 0, 0, 'minwidth200', 0, 1)), + array('type' => 'other', 'name' => 'newwebsite', 'label' => $langs->trans("WebSite"), 'value' => $formwebsite->selectWebsite($object->id, 'newwebsite', 0)), array('type' => 'text', 'tdclass'=>'maxwidth200 fieldrequired', 'name' => 'pageurl', 'label'=> $langs->trans("WEBSITE_PAGENAME"), 'value'=> 'copy_of_'.$objectpage->pageurl), ); - $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; } @@ -2272,7 +2291,7 @@ if (! GETPOST('hide_websitemenu')) print '<!-- Code to enabled edit inline ckeditor -->'."\n"; print '<script type="text/javascript"> $(document).ready(function() { - var isEditingEnabled = '.($conf->global->WEBSITE_EDITINLINE?'true':'false').'; + var isEditingEnabled = '.($conf->global->WEBSITE_EDITINLINE ? 'true' : 'false').'; if (isEditingEnabled) { switchEditorOnline(true); @@ -2355,21 +2374,22 @@ if (! GETPOST('hide_websitemenu')) print '</div>'; print '</div>'; - // @TODO Move this action into a combo list + // Set page as homepage 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 '<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 { //$disabled=''; - //print '<a href="'.$_SERVER["PHP_SEFL"].'?action=setashome&website='.$website->ref.'" class="button bordertransp"'.$disabled.' title="'.dol_escape_htmltag($langs->trans("SetAsHomePage")).'"><span class="fa fa-home"><span></a>'; - print '<input type="submit" class="button bordertransp"'.$disabled.' value="'.dol_escape_htmltag($langs->trans("SetAsHomePage")).'" name="setashome">'; + //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&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>'; } print '<input type="submit" class="button bordertransp"'.$disabled.' value="'.dol_escape_htmltag($langs->trans("ClonePage")).'" name="createpagefromclone">'; - print '<input type="submit" class="buttonDelete bordertransp" name="delete" value="'.$langs->trans("Delete").'"'.($atleastonepage?'':' disabled="disabled"').'>'; + print '<input type="submit" class="buttonDelete bordertransp" name="delete" value="'.$langs->trans("Delete").'"'.($atleastonepage ? '' : ' disabled="disabled"').'>'; } } @@ -2379,48 +2399,48 @@ if (! GETPOST('hide_websitemenu')) if (($pageid > 0 && $atleastonepage) && ($action == 'preview' || $action == 'createfromclone' || $action == 'createpagefromclone' || $action == 'deletesite')) { - $realpage=$urlwithroot.'/public/website/index.php?website='.$websitekey.'&pageref='.$websitepage->pageurl; + $realpage = $urlwithroot.'/public/website/index.php?website='.$websitekey.'&pageref='.$websitepage->pageurl; $pagealias = $websitepage->pageurl; $htmltext = $langs->trans("PreviewSiteServedByDolibarr", $langs->transnoentitiesnoconv("Page"), $langs->transnoentitiesnoconv("Page"), $realpage, $dataroot); - $htmltext.='<br>'.$langs->trans("CheckVirtualHostPerms", $langs->transnoentitiesnoconv("ReadPerm"), DOL_DOCUMENT_ROOT); - $htmltext.='<br>'.$langs->trans("CheckVirtualHostPerms", $langs->transnoentitiesnoconv("WritePerm"), DOL_DATA_ROOT.'/website<br>'.DOL_DATA_ROOT.'/medias'); + $htmltext .= '<br>'.$langs->trans("CheckVirtualHostPerms", $langs->transnoentitiesnoconv("ReadPerm"), DOL_DOCUMENT_ROOT); + $htmltext .= '<br>'.$langs->trans("CheckVirtualHostPerms", $langs->transnoentitiesnoconv("WritePerm"), DOL_DATA_ROOT.'/website<br>'.DOL_DATA_ROOT.'/medias'); print '<a class="websitebuttonsitepreview" id="previewpage" href="'.$realpage.'&nocache='.dol_now().'" class="button" target="tab'.$websitekey.'" alt="'.dol_escape_htmltag($htmltext).'">'; print $form->textwithpicto('', $htmltext, 1, 'preview'); - print '</a>'; // View page in new Tab + print '</a>'; // View page in new Tab print '<div class="websiteinputurl" id="websiteinputpage">'; print '<input type="text" id="previewpageurl" class="minwidth200imp" name="previewsite" value="'.$pagealias.'" disabled="disabled">'; - $htmltext=$langs->trans("PageNameAliasHelp", $langs->transnoentitiesnoconv("EditPageMeta")); + $htmltext = $langs->trans("PageNameAliasHelp", $langs->transnoentitiesnoconv("EditPageMeta")); print $form->textwithpicto('', $htmltext, 1, 'help', '', 0, 2, 'helppagealias'); print '</div>'; - $urlext=$virtualurl.'/'.$pagealias.'.php'; - $urlint=$urlwithroot.'/public/website/index.php?website='.$websitekey; + $urlext = $virtualurl.'/'.$pagealias.'.php'; + $urlint = $urlwithroot.'/public/website/index.php?website='.$websitekey; - $htmltext = $langs->trans("PreviewSiteServedByWebServer", $langs->transnoentitiesnoconv("Page"), $langs->transnoentitiesnoconv("Page"), $dataroot, $virtualurl?$urlext:'<span class="error">'.$langs->trans("VirtualHostUrlNotDefined").'</span>'); + $htmltext = $langs->trans("PreviewSiteServedByWebServer", $langs->transnoentitiesnoconv("Page"), $langs->transnoentitiesnoconv("Page"), $dataroot, $virtualurl ? $urlext : '<span class="error">'.$langs->trans("VirtualHostUrlNotDefined").'</span>'); - print '<a class="websitebuttonsitepreview'.($virtualurl?'':' websitebuttonsitepreviewdisabled cursornotallowed').'" id="previewpageext" href="'.$urlext.'" target="tab'.$websitekey.'ext" alt="'.dol_escape_htmltag($htmltext).'">'; + print '<a class="websitebuttonsitepreview'.($virtualurl ? '' : ' websitebuttonsitepreviewdisabled cursornotallowed').'" id="previewpageext" href="'.$urlext.'" target="tab'.$websitekey.'ext" alt="'.dol_escape_htmltag($htmltext).'">'; print $form->textwithpicto('', $htmltext, 1, 'preview_ext'); print '</a>'; //print '<input type="submit" class="button" name="previewpage" target="tab'.$websitekey.'"value="'.$langs->trans("ViewPageInNewTab").'">'; // 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 (!in_array($action, array('editcss', 'editmenu', 'file_manager', 'replacesite', 'replacesiteconfirm', 'createsite', 'createcontainer', 'createfromclone', 'createpagefromclone', 'deletesite'))) { if (preg_match('/^create/', $action)) print '<input type="submit" id="savefile" class="button buttonforacesave" value="'.dol_escape_htmltag($langs->trans("Save")).'" name="update">'; if (preg_match('/^edit/', $action)) print '<input type="submit" id="savefile" class="button buttonforacesave" value="'.dol_escape_htmltag($langs->trans("Save")).'" name="update">'; if ($action != 'preview') print '<input type="submit" class="button" value="'.dol_escape_htmltag($langs->trans("Cancel")).'" name="preview">'; } - print '</span>'; // end websitetools + print '</span>'; // end websitetools print '<span class="websitehelp">'; if (GETPOST('editsource', 'alpha') || GETPOST('editcontent', 'alpha')) { - $htmltext=$langs->transnoentitiesnoconv("YouCanEditHtmlSource").'<br>'; + $htmltext = $langs->transnoentitiesnoconv("YouCanEditHtmlSource").'<br>'; if ($conf->browser->layout == 'phone') { print $form->textwithpicto('', $htmltext, 1, 'help', 'inline-block', 1, 2, 'tooltipsubstitution'); @@ -2431,14 +2451,14 @@ if (! GETPOST('hide_websitemenu')) print $form->textwithpicto($langs->trans("SyntaxHelp").' '.img_help(2, $langs->trans("SyntaxHelp")), $htmltext, 1, 'none', 'inline-block', 1, 2, 'tooltipsubstitution'); } } - print '</span>'; // end websitehelp + print '</span>'; // end websitehelp 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() { @@ -2486,7 +2506,7 @@ if (! GETPOST('hide_websitemenu')) } } - print '</div>'; // end current websitebar + print '</div>'; // end current websitebar } @@ -2504,7 +2524,7 @@ if ($action == 'editcss') 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 @@ -2514,9 +2534,9 @@ if ($action == 'editcss') { $csscontent = GETPOST('WEBSITE_CSS_INLINE', 'none'); } - if (! trim($csscontent)) $csscontent='/* CSS content (all pages) */'."\n"."body.bodywebsite { margin: 0; font-family: 'Open Sans', sans-serif; }\n.bodywebsite h1 { margin-top: 0; margin-bottom: 0; padding: 10px;}"; + if (!trim($csscontent)) $csscontent = '/* CSS content (all pages) */'."\n"."body.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 @@ -2526,9 +2546,9 @@ if ($action == 'editcss') { $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 @@ -2538,20 +2558,20 @@ if ($action == 'editcss') { $htmlheadercontent = GETPOST('WEBSITE_HTML_HEADER', 'none'); } - if (! trim($htmlheadercontent)) + if (!trim($htmlheadercontent)) { - $htmlheadercontent ="<html>\n"; - $htmlheadercontent.=$htmlheadercontentdefault; - $htmlheadercontent.="</html>"; + $htmlheadercontent = "<html>\n"; + $htmlheadercontent .= $htmlheadercontentdefault; + $htmlheadercontent .= "</html>"; } else { $htmlheadercontent = preg_replace('/^\s*<html>/ims', '', $htmlheadercontent); $htmlheadercontent = preg_replace('/<\/html>\s*$/ims', '', $htmlheadercontent); - $htmlheadercontent='<html>'."\n".trim($htmlheadercontent)."\n".'</html>'; + $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 @@ -2561,15 +2581,15 @@ if ($action == 'editcss') { $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"; + $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 @@ -2579,14 +2599,14 @@ if ($action == 'editcss') { $htaccesscontent = GETPOST('WEBSITE_HTACCESS', 'nohtml'); } - if (! trim($htaccesscontent)) + if (!trim($htaccesscontent)) { - $htaccesscontent.="# Order allow,deny\n"; - $htaccesscontent.="# Deny from all\n"; + $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 @@ -2596,12 +2616,12 @@ if ($action == 'editcss') { $manifestjsoncontent = GETPOST('WEBSITE_MANIFEST_JSON', 'none'); } - 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 @@ -2611,7 +2631,7 @@ if ($action == 'editcss') { $readmecontent = GETPOST('WEBSITE_README', 'none'); } - if (! trim($readmecontent)) + if (!trim($readmecontent)) { //$readmecontent.=""; } @@ -2619,7 +2639,7 @@ if ($action == 'editcss') dol_fiche_head(); print '<!-- Edit CSS -->'."\n"; - print '<table class="border" width="100%">'; + print '<table class="border centpercent">'; // Website print '<tr><td class="titlefieldcreate">'; @@ -2632,9 +2652,9 @@ if ($action == 'editcss') print '<tr><td class="tdtop">'; $htmltext = $langs->trans("SetHereVirtualHost", DOL_DATA_ROOT.'/website/<i>'.$websitekey.'</i>'); - $htmltext.='<br>'; - $htmltext.='<br>'.$langs->trans("CheckVirtualHostPerms", $langs->transnoentitiesnoconv("ReadPerm"), DOL_DOCUMENT_ROOT); - $htmltext.='<br>'.$langs->trans("CheckVirtualHostPerms", $langs->transnoentitiesnoconv("WritePerm"), DOL_DATA_ROOT.'/website<br>'.DOL_DATA_ROOT.'/medias'); + $htmltext .= '<br>'; + $htmltext .= '<br>'.$langs->trans("CheckVirtualHostPerms", $langs->transnoentitiesnoconv("ReadPerm"), DOL_DOCUMENT_ROOT); + $htmltext .= '<br>'.$langs->trans("CheckVirtualHostPerms", $langs->transnoentitiesnoconv("WritePerm"), DOL_DATA_ROOT.'/website<br>'.DOL_DATA_ROOT.'/medias'); print $form->textwithpicto($langs->trans('Virtualhost'), $htmltext, 1, 'help', '', 0, 2, 'virtualhosttooltip'); print '</td><td>'; @@ -2644,11 +2664,11 @@ if ($action == 'editcss') // CSS file print '<tr><td class="tdtop">'; - $htmlhelp=$langs->trans("CSSContentTooltipHelp"); + $htmlhelp = $langs->trans("CSSContentTooltipHelp"); print $form->textwithpicto($langs->trans('WEBSITE_CSS_INLINE'), $htmlhelp, 1, 'help', '', 0, 2, 'csstooltip'); print '</td><td>'; - $doleditor=new DolEditor('WEBSITE_CSS_INLINE', $csscontent, '', '220', 'ace', 'In', true, false, 'ace', 0, '100%', ''); + $doleditor = new DolEditor('WEBSITE_CSS_INLINE', $csscontent, '', '220', 'ace', 'In', true, false, 'ace', 0, '100%', ''); print $doleditor->Create(1, '', true, 'CSS', 'css'); print '</td></tr>'; @@ -2658,7 +2678,7 @@ if ($action == 'editcss') print $langs->trans('WEBSITE_JS_INLINE'); print '</td><td>'; - $doleditor=new DolEditor('WEBSITE_JS_INLINE', $jscontent, '', '220', 'ace', 'In', true, false, 'ace', 0, '100%', ''); + $doleditor = new DolEditor('WEBSITE_JS_INLINE', $jscontent, '', '220', 'ace', 'In', true, false, 'ace', 0, '100%', ''); print $doleditor->Create(1, '', true, 'JS', 'javascript'); print '</td></tr>'; @@ -2666,14 +2686,14 @@ if ($action == 'editcss') // Common HTML header print '<tr><td class="tdtop">'; print $langs->trans('WEBSITE_HTML_HEADER'); - $htmlhelp=$langs->trans("Example").' :<br>'; - $htmlhelp.=dol_htmlentitiesbr($htmlheadercontentdefault); + $htmlhelp = $langs->trans("Example").' :<br>'; + $htmlhelp .= dol_htmlentitiesbr($htmlheadercontentdefault); $textwithhelp = $form->textwithpicto('', $htmlhelp, 1, 'help', '', 0, 2, 'htmlheadertooltip'); - $htmlhelp2=$langs->trans("LinkAndScriptsHereAreNotLoadedInEditor").'<br>'; + $htmlhelp2 = $langs->trans("LinkAndScriptsHereAreNotLoadedInEditor").'<br>'; print $form->textwithpicto($textwithhelp, $htmlhelp2, 1, 'warning', '', 0, 2, 'htmlheadertooltip2'); print '</td><td>'; - $doleditor=new DolEditor('WEBSITE_HTML_HEADER', $htmlheadercontent, '', '220', 'ace', 'In', true, false, 'ace', 0, '100%', ''); + $doleditor = new DolEditor('WEBSITE_HTML_HEADER', $htmlheadercontent, '', '220', 'ace', 'In', true, false, 'ace', 0, '100%', ''); print $doleditor->Create(1, '', true, 'HTML Header', 'html'); print '</td></tr>'; @@ -2683,7 +2703,7 @@ if ($action == 'editcss') print $langs->trans('WEBSITE_ROBOT'); print '</td><td>'; - $doleditor=new DolEditor('WEBSITE_ROBOT', $robotcontent, '', '220', 'ace', 'In', true, false, 'ace', 0, '100%', ''); + $doleditor = new DolEditor('WEBSITE_ROBOT', $robotcontent, '', '220', 'ace', 'In', true, false, 'ace', 0, '100%', ''); print $doleditor->Create(1, '', true, 'Robot file', 'text'); print '</td></tr>'; @@ -2693,30 +2713,30 @@ if ($action == 'editcss') print $langs->trans('WEBSITE_HTACCESS'); print '</td><td>'; - $doleditor=new DolEditor('WEBSITE_HTACCESS', $htaccesscontent, '', '220', 'ace', 'In', true, false, 'ace', 0, '100%', ''); + $doleditor = new DolEditor('WEBSITE_HTACCESS', $htaccesscontent, '', '220', 'ace', 'In', true, false, 'ace', 0, '100%', ''); print $doleditor->Create(1, '', true, $langs->trans("File").' .htaccess', 'text'); print '</td></tr>'; // Manifest.json print '<tr><td class="tdtop">'; - $htmlhelp=$langs->trans("Example").' :<br>'; - $htmlhelp.=dol_htmlentitiesbr($manifestjsoncontentdefault); + $htmlhelp = $langs->trans("Example").' :<br>'; + $htmlhelp .= dol_htmlentitiesbr($manifestjsoncontentdefault); print $form->textwithpicto($langs->trans('WEBSITE_MANIFEST_JSON'), $htmlhelp, 1, 'help', '', 0, 2, 'manifestjsontooltip'); print '</td><td>'; - $doleditor=new DolEditor('WEBSITE_MANIFEST_JSON', $manifestjsoncontent, '', '220', 'ace', 'In', true, false, 'ace', 0, '100%', ''); + $doleditor = new DolEditor('WEBSITE_MANIFEST_JSON', $manifestjsoncontent, '', '220', 'ace', 'In', true, false, 'ace', 0, '100%', ''); print $doleditor->Create(1, '', true, $langs->trans("File").' manifest.json', 'text'); print '</td></tr>'; // README.md print '<tr><td class="tdtop">'; - $htmlhelp=$langs->trans("EnterHereLicenseInformation"); + $htmlhelp = $langs->trans("EnterHereLicenseInformation"); print $form->textwithpicto($langs->trans('WEBSITE_README'), $htmlhelp, 1, 'help', '', 0, 2, 'readmetooltip'); print '</td><td>'; - $doleditor=new DolEditor('WEBSITE_README', $readmecontent, '', '220', 'ace', 'In', true, false, 'ace', 0, '100%', ''); + $doleditor = new DolEditor('WEBSITE_README', $readmecontent, '', '220', 'ace', 'In', true, false, 'ace', 0, '100%', ''); print $doleditor->Create(1, '', true, $langs->trans("File").' README.md', 'text'); print '</td></tr>'; @@ -2752,10 +2772,10 @@ if ($action == 'createsite') print '<!-- Add site -->'."\n"; //print '<div class="fichecenter">'; - print '<table class="border" width="100%">'; + print '<table class="border centpercent">'; - if (GETPOST('WEBSITE_REF')) $siteref=GETPOST('WEBSITE_REF', 'alpha'); - if (GETPOST('WEBSITE_DESCRIPTION')) $sitedesc=GETPOST('WEBSITE_DESCRIPTION', 'alpha'); + if (GETPOST('WEBSITE_REF')) $siteref = GETPOST('WEBSITE_REF', 'alpha'); + if (GETPOST('WEBSITE_DESCRIPTION')) $sitedesc = GETPOST('WEBSITE_DESCRIPTION', 'alpha'); print '<tr><td class="titlefieldcreate fieldrequired">'; print $langs->trans('Ref'); @@ -2772,9 +2792,9 @@ if ($action == 'createsite') print '<tr><td>'; $htmltext = $langs->trans("SetHereVirtualHost", DOL_DATA_ROOT.'/website/<i>websiteref</i>'); - $htmltext.='<br>'; - $htmltext.='<br>'.$langs->trans("CheckVirtualHostPerms", $langs->transnoentitiesnoconv("ReadPerm"), DOL_DOCUMENT_ROOT); - $htmltext.='<br>'.$langs->trans("CheckVirtualHostPerms", $langs->transnoentitiesnoconv("WritePerm"), DOL_DATA_ROOT.'/website<br>'.DOL_DATA_ROOT.'/medias'); + $htmltext .= '<br>'; + $htmltext .= '<br>'.$langs->trans("CheckVirtualHostPerms", $langs->transnoentitiesnoconv("ReadPerm"), DOL_DOCUMENT_ROOT); + $htmltext .= '<br>'.$langs->trans("CheckVirtualHostPerms", $langs->transnoentitiesnoconv("WritePerm"), DOL_DATA_ROOT.'/website<br>'.DOL_DATA_ROOT.'/medias'); print $form->textwithpicto($langs->trans('Virtualhost'), $htmltext, 1, 'help', '', 0, 2, 'virtualhosttooltip'); print '</td><td>'; @@ -2862,15 +2882,15 @@ if ($action == 'editmeta' || $action == 'createcontainer') if (GETPOST('radiocreatefrom') == 'checkboxcreatemanually') $hiddenmanuallyafterload = ''; if ($action == 'editmeta' || empty($conf->use_javascript_ajax)) { // No autohide/show in such case - $hiddenfromfetchingafterload=''; - $hiddenmanuallyafterload=''; + $hiddenfromfetchingafterload = ''; + $hiddenmanuallyafterload = ''; } 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="opacitymedium">'.$langs->trans("CreateByFetchingExternalPage").'</span></label><br>'; print '<hr class="tablecheckboxcreatefromfetching'.$hiddenfromfetchingafterload.'">'; print '<table class="tableforfield centpercent tablecheckboxcreatefromfetching'.$hiddenfromfetchingafterload.'">'; @@ -2882,8 +2902,8 @@ if ($action == 'editmeta' || $action == 'createcontainer') print '<br><input class="flat paddingtop" type="checkbox" name="grabimages" value="1" checked="checked"> '.$langs->trans("GrabImagesInto"); print ' '; print $langs->trans("ImagesShouldBeSavedInto").' '; - $arraygrabimagesinto=array('root'=>$langs->trans("WebsiteRootOfImages"), 'subpage'=>$langs->trans("SubdirOfPage")); - print $form->selectarray('grabimagesinto', $arraygrabimagesinto, GETPOSTISSET('grabimagesinto')?GETPOST('grabimagesinto'):'root'); + $arraygrabimagesinto = array('root'=>$langs->trans("WebsiteRootOfImages"), 'subpage'=>$langs->trans("SubdirOfPage")); + print $form->selectarray('grabimagesinto', $arraygrabimagesinto, GETPOSTISSET('grabimagesinto') ?GETPOST('grabimagesinto') : 'root'); print '<br>'; print '<input class="button" style="margin-top: 5px" type="submit" name="fetchexternalurl" value="'.dol_escape_htmltag($langs->trans("FetchAndCreate")).'">'; print '</td></tr>'; @@ -2891,7 +2911,7 @@ if ($action == 'editmeta' || $action == 'createcontainer') 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="opacitymedium">'.$langs->trans("OrEnterPageInfoManually").'</span></label><br>'; print '<hr class="tablecheckboxcreatemanually'.$hiddenmanuallyafterload.'">'; } @@ -2913,35 +2933,35 @@ if ($action == 'editmeta' || $action == 'createcontainer') //if ($objectpage->grabbed_from) print ' - <span class="opacitymedium">'.$langs->trans('InitiallyGrabbedFrom').' '.$objectpage->grabbed_from.'</span>'; print '</td></tr>'; - $type_container=$objectpage->type_container; - $pageurl=$objectpage->pageurl; - $pagealiasalt=$objectpage->aliasalt; - $pagetitle=$objectpage->title; - $pagedescription=$objectpage->description; - $pageimage=$objectpage->image; - $pagekeywords=$objectpage->keywords; - $pagelang=$objectpage->lang; - $pagehtmlheader=$objectpage->htmlheader; - $pagedatecreation=$objectpage->date_creation; - $pagedatemodification=$objectpage->date_modification; - $pageauthorid=$objectpage->fk_user_creat; - $pageusermodifid=$objectpage->fk_user_modif; + $type_container = $objectpage->type_container; + $pageurl = $objectpage->pageurl; + $pagealiasalt = $objectpage->aliasalt; + $pagetitle = $objectpage->title; + $pagedescription = $objectpage->description; + $pageimage = $objectpage->image; + $pagekeywords = $objectpage->keywords; + $pagelang = $objectpage->lang; + $pagehtmlheader = $objectpage->htmlheader; + $pagedatecreation = $objectpage->date_creation; + $pagedatemodification = $objectpage->date_modification; + $pageauthorid = $objectpage->fk_user_creat; + $pageusermodifid = $objectpage->fk_user_modif; } else { $type_container = 'page'; - $pagedatecreation=dol_now(); - $pageauthorid=$user->id; - $pageusermodifid=0; + $pagedatecreation = dol_now(); + $pageauthorid = $user->id; + $pageusermodifid = 0; } - if (GETPOST('WEBSITE_TITLE', 'alpha')) $pagetitle=GETPOST('WEBSITE_TITLE', 'alpha'); - if (GETPOST('WEBSITE_PAGENAME', 'alpha')) $pageurl=GETPOST('WEBSITE_PAGENAME', 'alpha'); - if (GETPOST('WEBSITE_ALIASALT', 'alpha')) $pagealiasalt=GETPOST('WEBSITE_ALIASALT', 'alpha'); - if (GETPOST('WEBSITE_DESCRIPTION', 'alpha')) $pagedescription=GETPOST('WEBSITE_DESCRIPTION', 'alpha'); - if (GETPOST('WEBSITE_IMAGE', 'alpha')) $pageimage=GETPOST('WEBSITE_IMAGE', 'alpha'); - if (GETPOST('WEBSITE_KEYWORDS', 'alpha')) $pagekeywords=GETPOST('WEBSITE_KEYWORDS', 'alpha'); - if (GETPOST('WEBSITE_LANG', 'aZ09')) $pagelang=GETPOST('WEBSITE_LANG', 'aZ09'); - if (GETPOST('htmlheader', 'none')) $pagehtmlheader=GETPOST('htmlheader', 'none'); + if (GETPOST('WEBSITE_TITLE', 'alpha')) $pagetitle = GETPOST('WEBSITE_TITLE', 'alpha'); + if (GETPOST('WEBSITE_PAGENAME', 'alpha')) $pageurl = GETPOST('WEBSITE_PAGENAME', 'alpha'); + if (GETPOST('WEBSITE_ALIASALT', 'alpha')) $pagealiasalt = GETPOST('WEBSITE_ALIASALT', 'alpha'); + if (GETPOST('WEBSITE_DESCRIPTION', 'alpha')) $pagedescription = GETPOST('WEBSITE_DESCRIPTION', 'alpha'); + if (GETPOST('WEBSITE_IMAGE', 'alpha')) $pageimage = GETPOST('WEBSITE_IMAGE', 'alpha'); + if (GETPOST('WEBSITE_KEYWORDS', 'alpha')) $pagekeywords = GETPOST('WEBSITE_KEYWORDS', 'alpha'); + if (GETPOST('WEBSITE_LANG', 'aZ09')) $pagelang = GETPOST('WEBSITE_LANG', 'aZ09'); + if (GETPOST('htmlheader', 'none')) $pagehtmlheader = GETPOST('htmlheader', 'none'); // Title print '<tr><td class="fieldrequired">'; @@ -2961,7 +2981,7 @@ if ($action == 'editmeta' || $action == 'createcontainer') print '<tr><td class="titlefield fieldrequired">'; print $langs->trans('WEBSITE_TYPE_CONTAINER'); print '</td><td>'; - print $formwebsite->selectTypeOfContainer('WEBSITE_TYPE_CONTAINER', (GETPOST('WEBSITE_TYPE_CONTAINER', 'alpha')?GETPOST('WEBSITE_TYPE_CONTAINER', 'alpha'):$type_container)); + print $formwebsite->selectTypeOfContainer('WEBSITE_TYPE_CONTAINER', (GETPOST('WEBSITE_TYPE_CONTAINER', 'alpha') ?GETPOST('WEBSITE_TYPE_CONTAINER', 'alpha') : $type_container)); print '</td></tr>'; if ($action == 'createcontainer') @@ -2969,7 +2989,7 @@ if ($action == 'editmeta' || $action == 'createcontainer') print '<tr><td class="titlefield fieldrequired">'; print $langs->trans('WEBSITE_PAGE_EXAMPLE'); print '</td><td>'; - print $formwebsite->selectSampleOfContainer('sample', (GETPOSTISSET('sample')?GETPOST('sample', 'alpha'):'empty')); + print $formwebsite->selectSampleOfContainer('sample', (GETPOSTISSET('sample') ?GETPOST('sample', 'alpha') : 'empty')); print '</td></tr>'; } @@ -2980,7 +3000,7 @@ if ($action == 'editmeta' || $action == 'createcontainer') print '</td></tr>'; print '<tr><td>'; - $htmlhelp=$langs->trans("WEBSITE_IMAGEDesc"); + $htmlhelp = $langs->trans("WEBSITE_IMAGEDesc"); print $form->textwithpicto($langs->trans('WEBSITE_IMAGE'), $htmlhelp, 1, 'help', '', 0, 2, 'imagetooltip'); print '</td><td>'; print '<input type="text" class="flat quatrevingtpercent" name="WEBSITE_IMAGE" value="'.dol_escape_htmltag($pageimage).'">'; @@ -2995,43 +3015,49 @@ if ($action == 'editmeta' || $action == 'createcontainer') print '<tr><td>'; print $langs->trans('Language'); print '</td><td>'; - print $formadmin->select_language($pagelang?$pagelang:$langs->defaultlang, 'WEBSITE_LANG', 0, null, '1'); + print $formadmin->select_language($pagelang ? $pagelang : $langs->defaultlang, 'WEBSITE_LANG', 0, null, '1'); print '</td></tr>'; // Translation of - $translationof=0; - $translatedby=0; + $translationof = 0; + $translatedby = 0; print '<!-- Translation of --><tr><td>'; print $langs->trans('TranslationLinks'); print '</td><td>'; if ($action != 'createcontainer') { // Has translation pages - $sql='SELECT rowid, lang from '.MAIN_DB_PREFIX.'website_page where fk_page = '.$objectpage->id; + $sql = 'SELECT rowid, lang from '.MAIN_DB_PREFIX.'website_page where fk_page = '.$objectpage->id; $resql = $db->query($sql); if ($resql) { $num_rows = $db->num_rows($resql); if ($num_rows > 0) { - print '<span class="opacitymedium">'.$langs->trans('ThisPageHasTranslationPages').':</span><br>'; - $i=0; + print '<span class="opacitymedium">'.$langs->trans('ThisPageHasTranslationPages').':</span>'; + $i = 0; + $tmppage = new WebsitePage($db); + $tmpstring = ''; while ($obj = $db->fetch_object($resql)) { - $tmppage=new WebsitePage($db); - $tmppage->fetch($obj->rowid); - if ($i > 0) print ' - '; - print $tmppage->getNomUrl(1).' ('.$tmppage->lang.')<br>'; - $translatedby++; - $i++; + $result = $tmppage->fetch($obj->rowid); + if ($result > 0) { + if ($i > 0) $tmpstring .= '<br>'; + $tmpstring .= $tmppage->getNomUrl(1).' ('.$tmppage->lang.')'; + $translatedby++; + $i++; + } } + if ($i > 1) print '<br>'; + else print ' '; + print $tmpstring; } } else dol_print_error($db); } if (empty($translatedby) && ($action == 'editmeta' || $action == 'createcontainer' || $objectpage->fk_page > 0)) { - $sourcepage=new WebsitePage($db); + $sourcepage = new WebsitePage($db); $result = $sourcepage->fetch($objectpage->fk_page); if ($result == 0) { @@ -3039,21 +3065,24 @@ if ($action == 'editmeta' || $action == 'createcontainer') } elseif ($result > 0) { - $translationof = $sourcepage->id; + $translationof = $objectpage->fk_page; print '<span class="opacitymedium">'.$langs->trans('ThisPageIsTranslationOf').'</span> '; - print $formwebsite->selectContainer($website, 'pageidfortranslation', $sourcepage->id, 1, $action); + print $formwebsite->selectContainer($website, 'pageidfortranslation', ($translationof ? $translationof : -1), 1, $action, 'minwidth300', array($objectpage->id)); + if ($translationof > 0) { + print $sourcepage->getNomUrl(2).' ('.$sourcepage->lang.')'; + } } } print '</td></tr>'; print '<tr><td class="titlefieldcreate">'; - $htmlhelp=$langs->trans("WEBSITE_ALIASALTDesc"); + $htmlhelp = $langs->trans("WEBSITE_ALIASALTDesc"); print $form->textwithpicto($langs->trans('WEBSITE_ALIASALT'), $htmlhelp, 1, 'help', '', 0, 2, 'aliastooltip'); print '</td><td>'; print '<input type="text" class="flat minwidth300" name="WEBSITE_ALIASALT" value="'.dol_escape_htmltag($pagealiasalt).'">'; print '</td></tr>'; - $fuser=new User($db); + $fuser = new User($db); print '<tr><td>'; print $langs->trans('Author'); @@ -3092,12 +3121,12 @@ if ($action == 'editmeta' || $action == 'createcontainer') } print '<tr><td class="tdhtmlheader tdtop">'; - $htmlhelp =$langs->trans("EditTheWebSiteForACommonHeader").'<br><br>'; - $htmlhelp.=$langs->trans("Example").' :<br>'; - $htmlhelp.=dol_htmlentitiesbr($htmlheadercontentdefault); + $htmlhelp = $langs->trans("EditTheWebSiteForACommonHeader").'<br><br>'; + $htmlhelp .= $langs->trans("Example").' :<br>'; + $htmlhelp .= dol_htmlentitiesbr($htmlheadercontentdefault); print $form->textwithpicto($langs->trans('HtmlHeaderPage'), $htmlhelp, 1, 'help', '', 0, 2, 'htmlheadertooltip'); print '</td><td>'; - $doleditor=new DolEditor('htmlheader', $pagehtmlheader, '', '120', 'ace', 'In', true, false, 'ace', ROWS_3, '100%', ''); + $doleditor = new DolEditor('htmlheader', $pagehtmlheader, '', '120', 'ace', 'In', true, false, 'ace', ROWS_3, '100%', ''); print $doleditor->Create(1, '', true, 'HTML Header', 'html'); print '</td></tr>'; @@ -3165,7 +3194,7 @@ if ($action == 'editfile' || $action == 'file_manager') //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>'; @@ -3187,15 +3216,15 @@ if ($action == 'editsource') //$contentforedit.='</style>'."\n"; $contentforedit .= $objectpage->content; //var_dump($_SESSION["dol_screenheight"]); - $maxheightwin=480; + $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 ($_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'; - $doleditor=new DolEditor('PAGE_CONTENT', $contentforedit, '', $maxheightwin, 'Full', '', true, true, 'ace', ROWS_5, '40%'); + $doleditor = new DolEditor('PAGE_CONTENT', $contentforedit, '', $maxheightwin, 'Full', '', true, true, 'ace', ROWS_5, '40%'); $doleditor->Create(0, '', false, 'HTML Source', 'php'); } @@ -3242,9 +3271,9 @@ if ($action == 'replacesite' || $action == 'replacesiteconfirm') print $langs->trans("SearchReplaceInto"); print '</div>'; print '<div class="tagtd">'; - print '<input type="checkbox" name="optioncontent" value="content"'.((! GETPOSTISSET('buttonreplacesitesearch') || GETPOST('optioncontent', 'aZ09'))?' checked':'').'> '.$langs->trans("Content"); - print '<input type="checkbox" class="marginleftonly" name="optionmeta" value="meta"'.(GETPOST('optionmeta', 'aZ09')?' checked':'').'> '.$langs->trans("Title").' | '.$langs->trans("Description").' | '.$langs->trans("Keywords"); - print '<input type="checkbox" class="marginleftonly" name="optionsitefiles" value="sitefiles"'.(GETPOST('optionsitefiles', 'aZ09')?' checked':'').'> '.$langs->trans("GlobalCSSorJS"); + print '<input type="checkbox" class="marginleftonly" name="optioncontent" value="content"'.((!GETPOSTISSET('buttonreplacesitesearch') || GETPOST('optioncontent', 'aZ09')) ? ' checked' : '').'> '.$langs->trans("Content").'<br>'; + print '<input type="checkbox" class="marginleftonly" name="optionmeta" value="meta"'.(GETPOST('optionmeta', 'aZ09') ? ' checked' : '').'> '.$langs->trans("Title").' | '.$langs->trans("Description").' | '.$langs->trans("Keywords").'<br>'; + print '<input type="checkbox" class="marginleftonly" name="optionsitefiles" value="sitefiles"'.(GETPOST('optionsitefiles', 'aZ09') ? ' checked' : '').'> '.$langs->trans("GlobalCSSorJS").'<br>'; print '</div>'; print '</div>'; @@ -3253,7 +3282,7 @@ if ($action == 'replacesite' || $action == 'replacesiteconfirm') print $langs->trans("SearchString"); print '</div>'; print '<div class="tagtd">'; - print '<input type="text" name="searchstring" value="'.dol_escape_htmltag($searchkey).'">'; + print '<input type="text" name="searchstring" value="'.dol_escape_htmltag($searchkey).'" autofocus>'; print '</div>'; print '</div>'; @@ -3266,9 +3295,9 @@ if ($action == 'replacesite' || $action == 'replacesiteconfirm') if ($action == 'replacesiteconfirm') { $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'; $listofpages = getPagesFromSearchCriterias('', $algo, $searchkey, 1000); @@ -3280,7 +3309,7 @@ if ($action == 'replacesite' || $action == 'replacesiteconfirm') print '<!-- List of search result -->'."\n"; print '<div class="rowsearchresult">'; - if ($action == 'replacesiteconfirm') + if ($action == 'replacesiteconfirm' && $conf->global->MAIN_FEATURES_LEVEL >= 2) { print '<div class="tagtr">'; print '<div class="tagtd paddingrightonly">'; @@ -3302,12 +3331,14 @@ if ($action == 'replacesite' || $action == 'replacesiteconfirm') print '<th>'.$langs->trans("Description").'</th>'; print '</tr>'; - foreach($listofpages['list'] as $answerrecord) + foreach ($listofpages['list'] as $answerrecord) { if (get_class($answerrecord) == 'WebsitePage') { print '<tr>'; - print '<td>'.$langs->trans("Container").'</td>'; + print '<td>'.$langs->trans("Container").' - '; + print $langs->trans($answerrecord->type_container); // TODO Use label of container + print '</td>'; print '<td>'; print $answerrecord->getNomUrl(1); print ' <span class="opacitymedium">('.($answerrecord->title ? $answerrecord->title : $langs->trans("NoTitle")).')</span>'; @@ -3319,7 +3350,23 @@ if ($action == 'replacesite' || $action == 'replacesiteconfirm') else { print '<tr>'; - print '<td>'.$answerrecord['type'].'</td>'; + print '<td>'; + + $translateofrecordtype = array( + 'website_csscontent'=>'WEBSITE_CSS_INLINE', + 'website_jscontent'=>'WEBSITE_JS_INLINE', + 'website_robotcontent'=>'WEBSITE_ROBOT', + 'website_htmlheadercontent'=>'WEBSITE_HTML_HEADER', + 'website_htaccess'=>'WEBSITE_HTACCESS', + 'website_readme'=>'WEBSITE_README', + 'website_manifestjson'=>'WEBSITE_MANIFEST_JSON' + ); + if (! empty($translateofrecordtype[$answerrecord['type']])) { + print $langs->trans($translateofrecordtype[$answerrecord['type']]); + } else { + print $answerrecord['type']; + } + print '</td>'; print '<td>'; $backtopageurl = $_SERVER["PHP_SELF"].'?action=replacesiteconfirm&searchstring='.urlencode($searchkey).'&optioncontent='.GETPOST('optioncontent', 'aZ09').'&optionmeta='.GETPOST('optionmeta', 'aZ09').'&optionsitefiles='.GETPOST('optionsitefiles', 'aZ09'); print '<a href="'.$_SERVER["PHP_SELF"].'?action=editcss&website='.$website->ref.'&backtopage='.urlencode($backtopageurl).'">'.$langs->trans("EditCss").'</a>'; @@ -3363,11 +3410,11 @@ if ($action == 'preview' || $action == 'createfromclone' || $action == 'createpa { $out .= "<iframe><body></html>"; }*/ - $out.="\n<html><head>\n"; - $out.="<!-- htmlheader/style of page from database -->\n"; - $out.=dolWebsiteReplacementOfLinks($object, $objectpage->htmlheader, 1, 'htmlheader'); + $out .= "\n<html><head>\n"; + $out .= "<!-- htmlheader/style of page from database -->\n"; + $out .= dolWebsiteReplacementOfLinks($object, $objectpage->htmlheader, 1, 'htmlheader'); - $out.="<!-- htmlheader/style of website from files -->\n"; + $out .= "<!-- htmlheader/style of website from files -->\n"; // TODO Keep only the <link> or the <script> tags /* $htmlheadercontent = @file_get_contents($filehtmlheader); @@ -3385,51 +3432,51 @@ if ($action == 'preview' || $action == 'createfromclone' || $action == 'createpa } */ - $out.="</head>\n"; - $out.="\n<body>"; + $out .= "</head>\n"; + $out .= "\n<body>"; - $out.='<div id="websitecontentundertopmenu" class="websitecontentundertopmenu boostrap-iso">'."\n"; + $out .= '<div id="websitecontentundertopmenu" class="websitecontentundertopmenu boostrap-iso">'."\n"; // REPLACEMENT OF LINKS When page called by website editor - $out.='<!-- style of website from file -->'."\n"; - $out.='<style scoped>'."\n"; // "scoped" means "apply to parent element only". No more supported by browsers, snif ! - $tmpout=''; - $tmpout.= '/* Include website CSS file */'."\n"; + $out .= '<!-- style of website from file -->'."\n"; + $out .= '<style scoped>'."\n"; // "scoped" means "apply to parent element only". No more supported by browsers, snif ! + $tmpout = ''; + $tmpout .= '/* Include website CSS file */'."\n"; //$csscontent = @file_get_contents($filecss); ob_start(); include $filecss; $csscontent = ob_get_contents(); ob_end_clean(); - $tmpout.= dolWebsiteReplacementOfLinks($object, $csscontent, 1, 'css'); - $tmpout.= '/* Include style from the HTML header of page */'."\n"; + $tmpout .= dolWebsiteReplacementOfLinks($object, $csscontent, 1, 'css'); + $tmpout .= '/* Include style from the HTML header of page */'."\n"; // Clean the html header of page to get only <style> content $tmp = preg_split('(<style[^>]*>|</style>)', $objectpage->htmlheader); - $tmpstyleinheader =''; - $i=0; - foreach($tmp as $valtmp) + $tmpstyleinheader = ''; + $i = 0; + foreach ($tmp as $valtmp) { $i++; - if ($i % 2 == 0) $tmpstyleinheader.=$valtmp."\n"; + if ($i % 2 == 0) $tmpstyleinheader .= $valtmp."\n"; } - $tmpout.= $tmpstyleinheader."\n"; + $tmpout .= $tmpstyleinheader."\n"; // Clean style that may affect global style of Dolibarr - $tmpout=preg_replace('/}[\s\n]*body\s*{[^}]+}/ims', '}', $tmpout); - $out.=$tmpout; - $out.='</style>'."\n"; + $tmpout = preg_replace('/}[\s\n]*body\s*{[^}]+}/ims', '}', $tmpout); + $out .= $tmpout; + $out .= '</style>'."\n"; // Note: <div> or <section> with contenteditable="true" inside this can be edited with inline ckeditor // Do not enable the contenteditable when page was grabbed, ckeditor is removing span and adding borders, // so editable will be available only from container created from scratch //$out.='<div id="bodywebsite" class="bodywebsite"'.($objectpage->grabbed_from ? ' contenteditable="true"' : '').'>'."\n"; - $out.='<div id="divbodywebsite" class="bodywebsite bodywebpage-'.$objectpage->ref.'">'."\n"; + $out .= '<div id="divbodywebsite" class="bodywebsite bodywebpage-'.$objectpage->ref.'">'."\n"; $newcontent = $objectpage->content; // If mode WEBSITE_SUBCONTAINERSINLINE is on - if (! empty($conf->global->WEBSITE_SUBCONTAINERSINLINE)) + if (!empty($conf->global->WEBSITE_SUBCONTAINERSINLINE)) { //var_dump($filetpl); $filephp = $filetpl; @@ -3449,12 +3496,12 @@ if ($action == 'preview' || $action == 'createfromclone' || $action == 'createpa { // Keep the contenteditable="true" when mode Edit Inline is on } - $out.=dolWebsiteReplacementOfLinks($object, $newcontent, 0, 'html', $objectpage->id)."\n"; + $out .= dolWebsiteReplacementOfLinks($object, $newcontent, 0, 'html', $objectpage->id)."\n"; //$out.=$newcontent; - $out.='</div>'; + $out .= '</div>'; - $out.='</div> <!-- End div id=websitecontentundertopmenu -->'; + $out .= '</div> <!-- End div id=websitecontentundertopmenu -->'; /*if ($includepageintoaframeoradiv == 'iframe') { @@ -3462,7 +3509,7 @@ if ($action == 'preview' || $action == 'createfromclone' || $action == 'createpa }*/ $out .= "\n</body></html>\n"; - $out.= "\n".'<!-- End page content '.$filetpl.' -->'."\n\n"; + $out .= "\n".'<!-- End page content '.$filetpl.' -->'."\n\n"; print $out; diff --git a/htdocs/website/websiteaccount_card.php b/htdocs/website/websiteaccount_card.php index be7c773ed25..e6c5b0f7c3d 100644 --- a/htdocs/website/websiteaccount_card.php +++ b/htdocs/website/websiteaccount_card.php @@ -29,48 +29,48 @@ require_once DOL_DOCUMENT_ROOT.'/societe/class/societeaccount.class.php'; require_once DOL_DOCUMENT_ROOT.'/website/lib/websiteaccount.lib.php'; // Load translation files required by the page -$langs->loadLangs(array("website","other")); +$langs->loadLangs(array("website", "other")); // Get parameters -$id = GETPOST('id', 'int'); +$id = GETPOST('id', 'int'); $ref = GETPOST('ref', 'alpha'); -$action = GETPOST('action', 'alpha'); +$action = GETPOST('action', 'alpha'); $confirm = GETPOST('confirm', 'alpha'); $cancel = GETPOST('cancel', 'aZ09'); $backtopage = GETPOST('backtopage', 'alpha'); // Initialize technical objects -$object=new SocieteAccount($db); +$object = new SocieteAccount($db); $extrafields = new ExtraFields($db); -$diroutputmassaction=$conf->website->dir_output . '/temp/massgeneration/'.$user->id; -$hookmanager->initHooks(array('websiteaccountcard')); // Note that conf->hooks_modules contains array +$diroutputmassaction = $conf->website->dir_output.'/temp/massgeneration/'.$user->id; +$hookmanager->initHooks(array('websiteaccountcard')); // 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_'); +$search_array_options = $extrafields->getOptionalsFromPost($object->table_element, '', 'search_'); // Initialize array of search criterias -$search_all=trim(GETPOST("search_all", 'alpha')); -$search=array(); -foreach($object->fields as $key => $val) +$search_all = trim(GETPOST("search_all", 'alpha')); +$search = array(); +foreach ($object->fields as $key => $val) { - if (GETPOST('search_'.$key, 'alpha')) $search[$key]=GETPOST('search_'.$key, 'alpha'); + 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) access_forbidden(); //if ($user->socid > 0) $socid = $user->socid; //$result = restrictedArea($user, 'website', $id); -$permissionnote=$user->rights->websiteaccount->write; // Used by the include of actions_setnotes.inc.php -$permissiondellink=$user->rights->websiteaccount->write; // Used by the include of actions_dellink.inc.php -$permissiontoadd=$user->rights->websiteaccount->write; // Used by the include of actions_addupdatedelete.inc.php and actions_lineupdown.inc.php +$permissionnote = $user->rights->websiteaccount->write; // Used by the include of actions_setnotes.inc.php +$permissiondellink = $user->rights->websiteaccount->write; // Used by the include of actions_dellink.inc.php +$permissiontoadd = $user->rights->websiteaccount->write; // Used by the include of actions_addupdatedelete.inc.php and actions_lineupdown.inc.php // Load object -include DOL_DOCUMENT_ROOT.'/core/actions_fetchobject.inc.php'; // Must be include, not include_once. +include DOL_DOCUMENT_ROOT.'/core/actions_fetchobject.inc.php'; // Must be include, not include_once. @@ -78,13 +78,13 @@ include DOL_DOCUMENT_ROOT.'/core/actions_fetchobject.inc.php'; // Must be inclu * Actions */ -$parameters=array(); -$reshook=$hookmanager->executeHooks('doActions', $parameters, $object, $action); // Note that $action and $object may have been modified by some hooks +$parameters = array(); +$reshook = $hookmanager->executeHooks('doActions', $parameters, $object, $action); // Note that $action and $object may have been modified by some hooks if ($reshook < 0) setEventMessages($hookmanager->error, $hookmanager->errors, 'errors'); if (empty($reshook)) { - $error=0; + $error = 0; $permissiontoadd = $user->rights->website->write; $permissiontodelete = $user->rights->website->delete; @@ -97,9 +97,9 @@ if (empty($reshook)) include DOL_DOCUMENT_ROOT.'/core/actions_printing.inc.php'; // Actions to send emails - $trigger_name='WEBSITEACCOUNT_SENTBYMAIL'; - $autocopy='MAIN_MAIL_AUTOCOPY_WEBSITEACCOUNT_TO'; - $trackid='websiteaccount'.$object->id; + $trigger_name = 'WEBSITEACCOUNT_SENTBYMAIL'; + $autocopy = 'MAIN_MAIL_AUTOCOPY_WEBSITEACCOUNT_TO'; + $trackid = 'websiteaccount'.$object->id; include DOL_DOCUMENT_ROOT.'/core/actions_sendmails.inc.php'; } @@ -108,8 +108,8 @@ if (empty($reshook)) * View */ -$form=new Form($db); -$formfile=new FormFile($db); +$form = new Form($db); +$formfile = new FormFile($db); llxHeader('', 'WebsiteAccount', ''); @@ -144,10 +144,10 @@ if ($action == 'create') print '<table class="border centpercent">'."\n"; // Common attributes - include DOL_DOCUMENT_ROOT . '/core/tpl/commonfields_add.tpl.php'; + include DOL_DOCUMENT_ROOT.'/core/tpl/commonfields_add.tpl.php'; // Other attributes - include DOL_DOCUMENT_ROOT . '/core/tpl/extrafields_add.tpl.php'; + include DOL_DOCUMENT_ROOT.'/core/tpl/extrafields_add.tpl.php'; print '</table>'."\n"; @@ -156,7 +156,7 @@ if ($action == 'create') print '<div class="center">'; print '<input type="submit" class="button" name="add" value="'.dol_escape_htmltag($langs->trans("Create")).'">'; print '  '; - print '<input type="'.($backtopage?"submit":"button").'" class="button" 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 '<input type="'.($backtopage ? "submit" : "button").'" class="button" 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>'; @@ -177,10 +177,10 @@ if (($id || $ref) && $action == 'edit') print '<table class="border centpercent">'."\n"; // Common attributes - include DOL_DOCUMENT_ROOT . '/core/tpl/commonfields_edit.tpl.php'; + include DOL_DOCUMENT_ROOT.'/core/tpl/commonfields_edit.tpl.php'; // Other attributes - include DOL_DOCUMENT_ROOT . '/core/tpl/extrafields_edit.tpl.php'; + include DOL_DOCUMENT_ROOT.'/core/tpl/extrafields_edit.tpl.php'; print '</table>'; @@ -196,7 +196,7 @@ 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->fk_soc > 0 && empty($socid)) $socid = $object->fk_soc; $res = $object->fetch_optionals(); @@ -207,14 +207,14 @@ if ($object->id > 0 && (empty($action) || ($action != 'edit' && $action != 'crea // Confirmation to delete if ($action == 'delete') { - $formconfirm = $form->formconfirm($_SERVER["PHP_SELF"] . '?id=' . $object->id, $langs->trans('DeleteWebsiteAccount'), $langs->trans('ConfirmDeleteWebsiteAccount'), 'confirm_delete', '', 0, 1); + $formconfirm = $form->formconfirm($_SERVER["PHP_SELF"].'?id='.$object->id, $langs->trans('DeleteWebsiteAccount'), $langs->trans('ConfirmDeleteWebsiteAccount'), 'confirm_delete', '', 0, 1); } // Call Hook formConfirm $parameters = array('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; @@ -222,11 +222,11 @@ 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("BackToListOfThirdParty") . '</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>'; + $linkback = ''; + if ($socid) $linkback = '<a href="'.DOL_URL_ROOT.'/societe/website.php?socid='.$socid.'&restore_lastsearch_values=1'.(!empty($socid) ? '&socid='.$socid : '').'">'.$langs->trans("BackToListOfThirdParty").'</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">'; + $morehtmlref = '<div class="refidno">'; /* // Ref bis $morehtmlref.=$form->editfieldkey("RefBis", 'ref_client', $object->ref_client, $object, $user->rights->website->creer, 'string', '', 0, 1); @@ -268,7 +268,7 @@ if ($object->id > 0 && (empty($action) || ($action != 'edit' && $action != 'crea } } */ - $morehtmlref.='</div>'; + $morehtmlref .= '</div>'; if ($socid > 0) $object->next_prev_filter = 'te.fk_soc = '.$socid; @@ -281,10 +281,10 @@ if ($object->id > 0 && (empty($action) || ($action != 'edit' && $action != 'crea print '<table class="border centpercent">'."\n"; // Common attributes - include DOL_DOCUMENT_ROOT . '/core/tpl/commonfields_view.tpl.php'; + include DOL_DOCUMENT_ROOT.'/core/tpl/commonfields_view.tpl.php'; // Other attributes - include DOL_DOCUMENT_ROOT . '/core/tpl/extrafields_view.tpl.php'; + include DOL_DOCUMENT_ROOT.'/core/tpl/extrafields_view.tpl.php'; print '</table>'; print '</div>'; @@ -299,14 +299,14 @@ if ($object->id > 0 && (empty($action) || ($action != 'edit' && $action != 'crea // 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 + $parameters = array(); + $reshook = $hookmanager->executeHooks('addMoreActionsButtons', $parameters, $object, $action); // Note that $action and $object may have been modified by hook if ($reshook < 0) setEventMessages($hookmanager->error, $hookmanager->errors, 'errors'); if (empty($reshook)) { // Send - 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"; + 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) { @@ -376,8 +376,8 @@ if ($object->id > 0 && (empty($action) || ($action != 'edit' && $action != 'crea } // Presend form - $modelmail='websiteaccount'; - $defaulttopic='Information'; + $modelmail = 'websiteaccount'; + $defaulttopic = 'Information'; $diroutput = $conf->website->dir_output; $trackid = 'websiteaccount'.$object->id; diff --git a/htdocs/zapier/admin/setup.php b/htdocs/zapier/admin/setup.php index b8b203b8ab1..167da89cfe9 100644 --- a/htdocs/zapier/admin/setup.php +++ b/htdocs/zapier/admin/setup.php @@ -26,22 +26,22 @@ require '../../main.inc.php'; // Libraries -require_once DOL_DOCUMENT_ROOT . "/core/lib/admin.lib.php"; +require_once DOL_DOCUMENT_ROOT."/core/lib/admin.lib.php"; require_once '../lib/zapier.lib.php'; // Translations $langs->loadLangs(array("admin", "zapier@zapier")); // Access control -if (! $user->admin) accessforbidden(); +if (!$user->admin) accessforbidden(); // Parameters $action = GETPOST('action', 'alpha'); $backtopage = GETPOST('backtopage', 'alpha'); -$arrayofparameters=array( - 'ZAPIERFORDOLIBARR_MYPARAM1'=>array('css'=>'minwidth200','enabled'=>1), - 'ZAPIERFORDOLIBARR_MYPARAM2'=>array('css'=>'minwidth500','enabled'=>1) +$arrayofparameters = array( + 'ZAPIERFORDOLIBARR_MYPARAM1'=>array('css'=>'minwidth200', 'enabled'=>1), + 'ZAPIERFORDOLIBARR_MYPARAM2'=>array('css'=>'minwidth500', 'enabled'=>1) ); @@ -61,7 +61,7 @@ $page_name = "ZapierSetup"; llxHeader('', $langs->trans($page_name)); // Subheader -$linkback = '<a href="'.($backtopage?$backtopage:DOL_URL_ROOT.'/admin/modules.php?restore_lastsearch_values=1').'">'.$langs->trans("BackToModuleList").'</a>'; +$linkback = '<a href="'.($backtopage ? $backtopage : DOL_URL_ROOT.'/admin/modules.php?restore_lastsearch_values=1').'">'.$langs->trans("BackToModuleList").'</a>'; print load_fiche_titre($langs->trans($page_name), $linkback, 'object_zapier@zapier'); @@ -78,13 +78,13 @@ if ($action == 'edit') { print '<input type="hidden" name="token" value="'.$_SESSION['newtoken'].'">'; print '<input type="hidden" name="action" value="update">'; - print '<table class="noborder" width="100%">'; + print '<table class="noborder centpercent">'; print '<tr class="liste_titre"><td class="titlefield">'.$langs->trans("Parameter").'</td><td>'.$langs->trans("Value").'</td></tr>'; - foreach($arrayofparameters as $key => $val) { + foreach ($arrayofparameters as $key => $val) { print '<tr class="oddeven"><td>'; print $form->textwithpicto($langs->trans($key), $langs->trans($key.'Tooltip')); - print '</td><td><input name="'.$key.'" class="flat '.(empty($val['css'])?'minwidth200':$val['css']).'" value="' . $conf->global->$key . '"></td></tr>'; + print '</td><td><input name="'.$key.'" class="flat '.(empty($val['css']) ? 'minwidth200' : $val['css']).'" value="'.$conf->global->$key.'"></td></tr>'; } print '</table>'; @@ -95,14 +95,14 @@ if ($action == 'edit') { print '</form>'; print '<br>'; } else { - if (! empty($arrayofparameters)) { - print '<table class="noborder" width="100%">'; + if (!empty($arrayofparameters)) { + print '<table class="noborder centpercent">'; print '<tr class="liste_titre"><td class="titlefield">'.$langs->trans("Parameter").'</td><td>'.$langs->trans("Value").'</td></tr>'; - foreach($arrayofparameters as $key => $val) { + foreach ($arrayofparameters as $key => $val) { print '<tr class="oddeven"><td>'; print $form->textwithpicto($langs->trans($key), $langs->trans($key.'Tooltip')); - print '</td><td>' . $conf->global->$key . '</td></tr>'; + print '</td><td>'.$conf->global->$key.'</td></tr>'; } print '</table>'; diff --git a/htdocs/zapier/class/hook.class.php b/htdocs/zapier/class/hook.class.php index 5c79d68aefe..fdc7aba2bc9 100644 --- a/htdocs/zapier/class/hook.class.php +++ b/htdocs/zapier/class/hook.class.php @@ -633,39 +633,22 @@ class Hook extends CommonObject public function LibStatut($status, $mode = 0) { // phpcs:enable - if (empty($this->labelStatus)) { - global $langs; - //$langs->load("zapier@zapier"); - $this->labelStatus[1] = $langs->trans('Enabled'); - $this->labelStatus[0] = $langs->trans('Disabled'); - } + global $langs; - if ($mode == 0) { - return $this->labelStatus[$status]; - } elseif ($mode == 1) { - return $this->labelStatus[$status]; - } elseif ($mode == 2) { - if ($status == 1) { - return img_picto($this->labelStatus[$status], 'statut4', '', false, 0, 0, '', 'valignmiddle').' '.$this->labelStatus[$status]; - } elseif ($status == 0) { - return img_picto($this->labelStatus[$status], 'statut5', '', false, 0, 0, '', 'valignmiddle').' '.$this->labelStatus[$status]; - } - } elseif ($mode == 3) { - if ($status == 1) return img_picto($this->labelStatus[$status], 'statut4', '', false, 0, 0, '', 'valignmiddle'); - elseif ($status == 0) return img_picto($this->labelStatus[$status], 'statut5', '', false, 0, 0, '', 'valignmiddle'); - } elseif ($mode == 4) { - if ($status == 1) return img_picto($this->labelStatus[$status], 'statut4', '', false, 0, 0, '', 'valignmiddle').' '.$this->labelStatus[$status]; - elseif ($status == 0) return img_picto($this->labelStatus[$status], 'statut5', '', false, 0, 0, '', 'valignmiddle').' '.$this->labelStatus[$status]; - } elseif ($mode == 5) { - if ($status == 1) return $this->labelStatus[$status].' '.img_picto($this->labelStatus[$status], 'statut4', '', false, 0, 0, '', 'valignmiddle'); - elseif ($status == 0) return $this->labelStatus[$status].' '.img_picto($this->labelStatus[$status], 'statut5', '', false, 0, 0, '', 'valignmiddle'); - } elseif ($mode == 6) { - if ($status == 1) { - return $this->labelStatus[$status].' '.img_picto($this->labelStatus[$status], 'statut4', '', false, 0, 0, '', 'valignmiddle'); - } elseif ($status == 0) { - return $this->labelStatus[$status].' '.img_picto($this->labelStatus[$status], 'statut5', '', false, 0, 0, '', 'valignmiddle'); - } - } + if (empty($this->labelStatus) || empty($this->labelStatusShort)) + { + global $langs; + //$langs->load("mymodule"); + $this->labelStatus[self::STATUS_DRAFT] = $langs->trans('Disabled'); + $this->labelStatus[self::STATUS_VALIDATED] = $langs->trans('Enabled'); + $this->labelStatusShort[self::STATUS_DRAFT] = $langs->trans('Disabled'); + $this->labelStatusShort[self::STATUS_VALIDATED] = $langs->trans('Enabled'); + } + + $statusType = 'status5'; + if ($status == self::STATUS_VALIDATED) $statusType = 'status4'; + + return dolGetStatus($this->labelStatus[$status], $this->labelStatusShort[$status], '', $statusType, $mode); } /** diff --git a/htdocs/zapier/hook_agenda.php b/htdocs/zapier/hook_agenda.php index 52909360ba0..98812cd47b5 100644 --- a/htdocs/zapier/hook_agenda.php +++ b/htdocs/zapier/hook_agenda.php @@ -23,19 +23,19 @@ */ // Load Dolibarr environment -$res=0; +$res = 0; // Try main.inc.php into web root known defined into CONTEXT_DOCUMENT_ROOT (not always defined) -if (! $res && ! empty($_SERVER["CONTEXT_DOCUMENT_ROOT"])) $res=@include $_SERVER["CONTEXT_DOCUMENT_ROOT"]."/main.inc.php"; +if (!$res && !empty($_SERVER["CONTEXT_DOCUMENT_ROOT"])) $res = @include $_SERVER["CONTEXT_DOCUMENT_ROOT"]."/main.inc.php"; // Try main.inc.php into web root detected using web root calculated from SCRIPT_FILENAME -$tmp=empty($_SERVER['SCRIPT_FILENAME'])?'':$_SERVER['SCRIPT_FILENAME'];$tmp2=realpath(__FILE__); $i=strlen($tmp)-1; $j=strlen($tmp2)-1; -while($i > 0 && $j > 0 && isset($tmp[$i]) && isset($tmp2[$j]) && $tmp[$i]==$tmp2[$j]) { $i--; $j--; } -if (! $res && $i > 0 && file_exists(substr($tmp, 0, ($i+1))."/main.inc.php")) $res=@include substr($tmp, 0, ($i+1))."/main.inc.php"; -if (! $res && $i > 0 && file_exists(dirname(substr($tmp, 0, ($i+1)))."/main.inc.php")) $res=@include dirname(substr($tmp, 0, ($i+1)))."/main.inc.php"; +$tmp = empty($_SERVER['SCRIPT_FILENAME']) ? '' : $_SERVER['SCRIPT_FILENAME']; $tmp2 = realpath(__FILE__); $i = strlen($tmp) - 1; $j = strlen($tmp2) - 1; +while ($i > 0 && $j > 0 && isset($tmp[$i]) && isset($tmp2[$j]) && $tmp[$i] == $tmp2[$j]) { $i--; $j--; } +if (!$res && $i > 0 && file_exists(substr($tmp, 0, ($i + 1))."/main.inc.php")) $res = @include substr($tmp, 0, ($i + 1))."/main.inc.php"; +if (!$res && $i > 0 && file_exists(dirname(substr($tmp, 0, ($i + 1)))."/main.inc.php")) $res = @include dirname(substr($tmp, 0, ($i + 1)))."/main.inc.php"; // Try main.inc.php using relative path -if (! $res && file_exists("../main.inc.php")) $res=@include "../main.inc.php"; -if (! $res && file_exists("../../main.inc.php")) $res=@include "../../main.inc.php"; -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 && file_exists("../../main.inc.php")) $res = @include "../../main.inc.php"; +if (!$res && file_exists("../../../main.inc.php")) $res = @include "../../../main.inc.php"; +if (!$res) die("Include of main fails"); require_once DOL_DOCUMENT_ROOT.'/contact/class/contact.class.php'; require_once DOL_DOCUMENT_ROOT.'/core/lib/company.lib.php'; @@ -78,21 +78,21 @@ if (empty($page) || $page == -1) { $page = 0; } // If $page is not defined, $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 MyObject($db); +$object = new MyObject($db); $extrafields = new ExtraFields($db); -$diroutputmassaction=$conf->mymodule->dir_output . '/temp/massgeneration/'.$user->id; -$hookmanager->initHooks(array('myobjectagenda','globalcard')); // Note that conf->hooks_modules contains array +$diroutputmassaction = $conf->mymodule->dir_output.'/temp/massgeneration/'.$user->id; +$hookmanager->initHooks(array('myobjectagenda', 'globalcard')); // Note that conf->hooks_modules contains array // 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 // Must be include, not include_once. Include fetch and fetch_thirdparty but not fetch_optionals -if ($id > 0 || ! empty($ref)) $upload_dir = $conf->mymodule->multidir_output[$object->entity] . "/" . $object->id; +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->mymodule->multidir_output[$object->entity]."/".$object->id; @@ -100,14 +100,14 @@ if ($id > 0 || ! empty($ref)) $upload_dir = $conf->mymodule->multidir_output[$ob * Actions */ -$parameters=array('id'=>$socid); -$reshook=$hookmanager->executeHooks('doActions', $parameters, $object, $action); // Note that $action and $object may have been modified by some hooks +$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 (empty($reshook)) { // Cancel - if (GETPOST('cancel', 'alpha') && ! empty($backtopage)) + if (GETPOST('cancel', 'alpha') && !empty($backtopage)) { header("Location: ".$backtopage); exit; @@ -116,8 +116,8 @@ if (empty($reshook)) // Purge search criteria if (GETPOST('button_removefilter_x', 'alpha') || GETPOST('button_removefilter.x', 'alpha') || GETPOST('button_removefilter', 'alpha')) // All tests are required to be compatible with all browsers { - $actioncode=''; - $search_agenda_label=''; + $actioncode = ''; + $search_agenda_label = ''; } } @@ -133,12 +133,12 @@ $form = new Form($db); if ($object->id > 0) { - $title=$langs->trans("Agenda"); + $title = $langs->trans("Agenda"); //if (! empty($conf->global->MAIN_HTML_TITLE) && preg_match('/thirdpartynameonly/',$conf->global->MAIN_HTML_TITLE) && $object->name) $title=$object->name." - ".$title; $help_url = ''; llxHeader('', $title, $help_url); - if (! empty($conf->notification->enabled)) $langs->load("mails"); + if (!empty($conf->notification->enabled)) $langs->load("mails"); $head = myobjectPrepareHead($object); @@ -146,9 +146,9 @@ if ($object->id > 0) // Object card // ------------------------------------------------------------ - $linkback = '<a href="' .dol_buildpath('/mymodule/myobject_list.php', 1) . '?restore_lastsearch_values=1' . (! empty($socid) ? '&socid=' . $socid : '') . '">' . $langs->trans("BackToList") . '</a>'; + $linkback = '<a href="'.dol_buildpath('/mymodule/myobject_list.php', 1).'?restore_lastsearch_values=1'.(!empty($socid) ? '&socid='.$socid : '').'">'.$langs->trans("BackToList").'</a>'; - $morehtmlref='<div class="refidno">'; + $morehtmlref = '<div class="refidno">'; /* // Ref customer $morehtmlref.=$form->editfieldkey("RefCustomer", 'ref_client', $object->ref_client, $object, 0, 'string', '', 0, 1); @@ -188,7 +188,7 @@ if ($object->id > 0) } } }*/ - $morehtmlref.='</div>'; + $morehtmlref .= '</div>'; dol_banner_tab($object, 'ref', $linkback, 1, 'ref', 'ref', $morehtmlref); @@ -207,16 +207,16 @@ if ($object->id > 0) // Actions buttons - $objthirdparty=$object; - $objcon=new stdClass(); + $objthirdparty = $object; + $objcon = new stdClass(); - $out=''; - $permok=$user->rights->agenda->myactions->create; - if ((! empty($objthirdparty->id) || ! empty($objcon->id)) && $permok) + $out = ''; + $permok = $user->rights->agenda->myactions->create; + if ((!empty($objthirdparty->id) || !empty($objcon->id)) && $permok) { //$out.='<a href="'.DOL_URL_ROOT.'/comm/action/card.php?action=create'; - if (get_class($objthirdparty) == 'Societe') $out.='&socid='.$objthirdparty->id; - $out.=(! empty($objcon->id)?'&contactid='.$objcon->id:'').'&backtopage=1&percentage=-1'; + if (get_class($objthirdparty) == 'Societe') $out .= '&socid='.$objthirdparty->id; + $out .= (!empty($objcon->id) ? '&contactid='.$objcon->id : '').'&backtopage=1&percentage=-1'; //$out.=$langs->trans("AddAnAction").' '; //$out.=img_picto($langs->trans("AddAnAction"),'filenew'); //$out.="</a>"; @@ -225,9 +225,9 @@ if ($object->id > 0) print '<div class="tabsAction">'; - if (! empty($conf->agenda->enabled)) + if (!empty($conf->agenda->enabled)) { - if (! empty($user->rights->agenda->myactions->create) || ! empty($user->rights->agenda->allactions->create)) + if (!empty($user->rights->agenda->myactions->create) || !empty($user->rights->agenda->allactions->create)) { print '<a class="butAction" href="'.DOL_URL_ROOT.'/comm/action/card.php?action=create'.$out.'">'.$langs->trans("AddAction").'</a>'; } @@ -239,18 +239,18 @@ if ($object->id > 0) print '</div>'; - if (! empty($conf->agenda->enabled) && (!empty($user->rights->agenda->myactions->read) || !empty($user->rights->agenda->allactions->read) )) + if (!empty($conf->agenda->enabled) && (!empty($user->rights->agenda->myactions->read) || !empty($user->rights->agenda->allactions->read))) { - $param='&socid='.$socid; - if (! empty($contextpage) && $contextpage != $_SERVER["PHP_SELF"]) $param.='&contextpage='.$contextpage; - if ($limit > 0 && $limit != $conf->liste_limit) $param.='&limit='.$limit; + $param = '&socid='.$socid; + 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("ActionsOnMyObject"), '', ''); // List of all actions - $filters=array(); - $filters['search_agenda_label']=$search_agenda_label; + $filters = array(); + $filters['search_agenda_label'] = $search_agenda_label; // TODO Replace this with same code than into list.php //show_actions_done($conf,$langs,$db,$object,null,0,$actioncode, '', $filters, $sortfield, $sortorder); diff --git a/htdocs/zapier/hook_card.php b/htdocs/zapier/hook_card.php index aca2e59df9b..1ea85ce8d57 100644 --- a/htdocs/zapier/hook_card.php +++ b/htdocs/zapier/hook_card.php @@ -43,19 +43,19 @@ // Load Dolibarr environment -$res=0; +$res = 0; // Try main.inc.php into web root known defined into CONTEXT_DOCUMENT_ROOT (not always defined) -if (! $res && ! empty($_SERVER["CONTEXT_DOCUMENT_ROOT"])) $res=@include $_SERVER["CONTEXT_DOCUMENT_ROOT"]."/main.inc.php"; +if (!$res && !empty($_SERVER["CONTEXT_DOCUMENT_ROOT"])) $res = @include $_SERVER["CONTEXT_DOCUMENT_ROOT"]."/main.inc.php"; // Try main.inc.php into web root detected using web root calculated from SCRIPT_FILENAME -$tmp=empty($_SERVER['SCRIPT_FILENAME'])?'':$_SERVER['SCRIPT_FILENAME'];$tmp2=realpath(__FILE__); $i=strlen($tmp)-1; $j=strlen($tmp2)-1; -while($i > 0 && $j > 0 && isset($tmp[$i]) && isset($tmp2[$j]) && $tmp[$i]==$tmp2[$j]) { $i--; $j--; } -if (! $res && $i > 0 && file_exists(substr($tmp, 0, ($i+1))."/main.inc.php")) $res=@include substr($tmp, 0, ($i+1))."/main.inc.php"; -if (! $res && $i > 0 && file_exists(dirname(substr($tmp, 0, ($i+1)))."/main.inc.php")) $res=@include dirname(substr($tmp, 0, ($i+1)))."/main.inc.php"; +$tmp = empty($_SERVER['SCRIPT_FILENAME']) ? '' : $_SERVER['SCRIPT_FILENAME']; $tmp2 = realpath(__FILE__); $i = strlen($tmp) - 1; $j = strlen($tmp2) - 1; +while ($i > 0 && $j > 0 && isset($tmp[$i]) && isset($tmp2[$j]) && $tmp[$i] == $tmp2[$j]) { $i--; $j--; } +if (!$res && $i > 0 && file_exists(substr($tmp, 0, ($i + 1))."/main.inc.php")) $res = @include substr($tmp, 0, ($i + 1))."/main.inc.php"; +if (!$res && $i > 0 && file_exists(dirname(substr($tmp, 0, ($i + 1)))."/main.inc.php")) $res = @include dirname(substr($tmp, 0, ($i + 1)))."/main.inc.php"; // Try main.inc.php using relative path -if (! $res && file_exists("../main.inc.php")) $res=@include "../main.inc.php"; -if (! $res && file_exists("../../main.inc.php")) $res=@include "../../main.inc.php"; -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 && file_exists("../../main.inc.php")) $res = @include "../../main.inc.php"; +if (!$res && file_exists("../../../main.inc.php")) $res = @include "../../../main.inc.php"; +if (!$res) die("Include of main fails"); require_once DOL_DOCUMENT_ROOT.'/core/class/html.formcompany.class.php'; require_once DOL_DOCUMENT_ROOT.'/core/class/html.formfile.class.php'; @@ -63,40 +63,40 @@ dol_include_once('/mymodule/class/myobject.class.php'); dol_include_once('/mymodule/lib/mymodule_myobject.lib.php'); // Load translation files required by the page -$langs->loadLangs(array("mymodule@mymodule","other")); +$langs->loadLangs(array("mymodule@mymodule", "other")); // Get parameters -$id = GETPOST('id', 'int'); +$id = GETPOST('id', 'int'); $ref = GETPOST('ref', 'alpha'); -$action = GETPOST('action', 'aZ09'); +$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 +$contextpage = GETPOST('contextpage', 'aZ') ?GETPOST('contextpage', 'aZ') : 'myobjectcard'; // To manage different context of search $backtopage = GETPOST('backtopage', 'alpha'); // Initialize technical objects -$object=new MyObject($db); +$object = new MyObject($db); $extrafields = new ExtraFields($db); -$diroutputmassaction=$conf->mymodule->dir_output . '/temp/massgeneration/'.$user->id; -$hookmanager->initHooks(array('myobjectcard','globalcard')); // Note that conf->hooks_modules contains array +$diroutputmassaction = $conf->mymodule->dir_output.'/temp/massgeneration/'.$user->id; +$hookmanager->initHooks(array('myobjectcard', '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_'); +$search_array_options = $extrafields->getOptionalsFromPost($object->table_element, '', 'search_'); // Initialize array of search criterias -$search_all=trim(GETPOST("search_all", 'alpha')); -$search=array(); -foreach($object->fields as $key => $val) +$search_all = trim(GETPOST("search_all", 'alpha')); +$search = array(); +foreach ($object->fields as $key => $val) { - if (GETPOST('search_'.$key, 'alpha')) $search[$key]=GETPOST('search_'.$key, 'alpha'); + 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 // Must be include, not include_once. Include fetch and fetch_thirdparty but not fetch_optionals +include DOL_DOCUMENT_ROOT.'/core/actions_fetchobject.inc.php'; // Must be include, not include_once // Must be include, not include_once. Include fetch and fetch_thirdparty but not fetch_optionals // Security check - Protection if external user //if ($user->socid > 0) access_forbidden(); @@ -111,13 +111,13 @@ include DOL_DOCUMENT_ROOT.'/core/actions_fetchobject.inc.php'; // Must be inclu * Put here all code to do according to value of "action" parameter */ -$parameters=array(); -$reshook=$hookmanager->executeHooks('doActions', $parameters, $object, $action); // Note that $action and $object may have been modified by some hooks +$parameters = array(); +$reshook = $hookmanager->executeHooks('doActions', $parameters, $object, $action); // Note that $action and $object may have been modified by some hooks if ($reshook < 0) setEventMessages($hookmanager->error, $hookmanager->errors, 'errors'); if (empty($reshook)) { - $error=0; + $error = 0; $permissiontoadd = $user->rights->mymodule->write; $permissiontodelete = $user->rights->mymodule->delete || ($permissiontoadd && $object->status == 0); @@ -126,7 +126,7 @@ if (empty($reshook)) if (empty($id)) $backtopage = $backurlforlist; else $backtopage = dol_buildpath('/mymodule/myobject_card.php', 1).($id > 0 ? $id : '__ID__'); } - $triggermodname = 'MYMODULE_MYOBJECT_MODIFY'; // Name of trigger action code to execute when we modify record + $triggermodname = 'MYMODULE_MYOBJECT_MODIFY'; // Name of trigger action code to execute when we modify record // Actions cancel, add, update, delete or clone include DOL_DOCUMENT_ROOT.'/core/actions_addupdatedelete.inc.php'; @@ -138,9 +138,9 @@ if (empty($reshook)) include DOL_DOCUMENT_ROOT.'/core/actions_printing.inc.php'; // Actions to send emails - $trigger_name='MYOBJECT_SENTBYMAIL'; - $autocopy='MAIN_MAIL_AUTOCOPY_MYOBJECT_TO'; - $trackid='myobject'.$object->id; + $trigger_name = 'MYOBJECT_SENTBYMAIL'; + $autocopy = 'MAIN_MAIL_AUTOCOPY_MYOBJECT_TO'; + $trackid = 'myobject'.$object->id; include DOL_DOCUMENT_ROOT.'/core/actions_sendmails.inc.php'; } @@ -153,8 +153,8 @@ if (empty($reshook)) * Put here all code to build page */ -$form=new Form($db); -$formfile=new FormFile($db); +$form = new Form($db); +$formfile = new FormFile($db); llxHeader('', 'MyObject', ''); @@ -189,10 +189,10 @@ if ($action == 'create') print '<table class="border centpercent">'."\n"; // Common attributes - include DOL_DOCUMENT_ROOT . '/core/tpl/commonfields_add.tpl.php'; + include DOL_DOCUMENT_ROOT.'/core/tpl/commonfields_add.tpl.php'; // Other attributes - include DOL_DOCUMENT_ROOT . '/core/tpl/extrafields_add.tpl.php'; + include DOL_DOCUMENT_ROOT.'/core/tpl/extrafields_add.tpl.php'; print '</table>'."\n"; @@ -201,7 +201,7 @@ if ($action == 'create') print '<div class="center">'; print '<input type="submit" class="button" name="add" value="'.dol_escape_htmltag($langs->trans("Create")).'">'; print '  '; - print '<input type="'.($backtopage?"submit":"button").'" class="button" 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 '<input type="'.($backtopage ? "submit" : "button").'" class="button" 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>'; @@ -223,10 +223,10 @@ if (($id || $ref) && $action == 'edit') print '<table class="border centpercent">'."\n"; // Common attributes - include DOL_DOCUMENT_ROOT . '/core/tpl/commonfields_edit.tpl.php'; + include DOL_DOCUMENT_ROOT.'/core/tpl/commonfields_edit.tpl.php'; // Other attributes - include DOL_DOCUMENT_ROOT . '/core/tpl/extrafields_edit.tpl.php'; + include DOL_DOCUMENT_ROOT.'/core/tpl/extrafields_edit.tpl.php'; print '</table>'; @@ -252,20 +252,20 @@ if ($object->id > 0 && (empty($action) || ($action != 'edit' && $action != 'crea // Confirmation to delete if ($action == 'delete') { - $formconfirm = $form->formconfirm($_SERVER["PHP_SELF"] . '?id=' . $object->id, $langs->trans('DeleteMyObject'), $langs->trans('ConfirmDeleteMyObject'), 'confirm_delete', '', 0, 1); + $formconfirm = $form->formconfirm($_SERVER["PHP_SELF"].'?id='.$object->id, $langs->trans('DeleteMyObject'), $langs->trans('ConfirmDeleteMyObject'), 'confirm_delete', '', 0, 1); } // Clone confirmation if ($action == 'clone') { // Create an array for form $formquestion = array(); - $formconfirm = $form->formconfirm($_SERVER["PHP_SELF"] . '?id=' . $object->id, $langs->trans('ToClone'), $langs->trans('ConfirmCloneMyObject', $object->ref), 'confirm_clone', $formquestion, 'yes', 1); + $formconfirm = $form->formconfirm($_SERVER["PHP_SELF"].'?id='.$object->id, $langs->trans('ToClone'), $langs->trans('ConfirmCloneMyObject', $object->ref), 'confirm_clone', $formquestion, 'yes', 1); } // Confirmation of action xxxx if ($action == 'xxx') { - $formquestion=array(); + $formquestion = array(); /* $forcecombo=0; if ($conf->browser->name == 'ie') $forcecombo = 1; // There is a bug in IE10 that make combo inside popup crazy @@ -276,14 +276,14 @@ if ($object->id > 0 && (empty($action) || ($action != 'edit' && $action != 'crea // array('type' => 'other', 'name' => 'idwarehouse', 'label' => $langs->trans("SelectWarehouseForStockDecrease"), 'value' => $formproduct->selectWarehouses(GETPOST('idwarehouse')?GETPOST('idwarehouse'):'ifone', 'idwarehouse', '', 1, 0, 0, '', 0, $forcecombo)) ); */ - $formconfirm = $form->formconfirm($_SERVER["PHP_SELF"] . '?id=' . $object->id, $langs->trans('XXX'), $text, 'confirm_xxx', $formquestion, 0, 1, 220); + $formconfirm = $form->formconfirm($_SERVER["PHP_SELF"].'?id='.$object->id, $langs->trans('XXX'), $text, 'confirm_xxx', $formquestion, 0, 1, 220); } // Call Hook formConfirm $parameters = array('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; @@ -291,9 +291,9 @@ if ($object->id > 0 && (empty($action) || ($action != 'edit' && $action != 'crea // Object card // ------------------------------------------------------------ - $linkback = '<a href="' .dol_buildpath('/mymodule/myobject_list.php', 1) . '?restore_lastsearch_values=1' . (! empty($socid) ? '&socid=' . $socid : '') . '">' . $langs->trans("BackToList") . '</a>'; + $linkback = '<a href="'.dol_buildpath('/mymodule/myobject_list.php', 1).'?restore_lastsearch_values=1'.(!empty($socid) ? '&socid='.$socid : '').'">'.$langs->trans("BackToList").'</a>'; - $morehtmlref='<div class="refidno">'; + $morehtmlref = '<div class="refidno">'; /* // Ref bis $morehtmlref.=$form->editfieldkey("RefBis", 'ref_client', $object->ref_client, $object, $user->rights->mymodule->creer, 'string', '', 0, 1); @@ -331,7 +331,7 @@ if ($object->id > 0 && (empty($action) || ($action != 'edit' && $action != 'crea } } */ - $morehtmlref.='</div>'; + $morehtmlref .= '</div>'; dol_banner_tab($object, 'ref', $linkback, 1, 'ref', 'ref', $morehtmlref); @@ -344,10 +344,10 @@ if ($object->id > 0 && (empty($action) || ($action != 'edit' && $action != 'crea // Common attributes //$keyforbreak='fieldkeytoswithonsecondcolumn'; - include DOL_DOCUMENT_ROOT . '/core/tpl/commonfields_view.tpl.php'; + include DOL_DOCUMENT_ROOT.'/core/tpl/commonfields_view.tpl.php'; // Other attributes - include DOL_DOCUMENT_ROOT . '/core/tpl/extrafields_view.tpl.php'; + include DOL_DOCUMENT_ROOT.'/core/tpl/extrafields_view.tpl.php'; print '</table>'; print '</div>'; @@ -361,14 +361,14 @@ if ($object->id > 0 && (empty($action) || ($action != 'edit' && $action != 'crea // 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 + $parameters = array(); + $reshook = $hookmanager->executeHooks('addMoreActionsButtons', $parameters, $object, $action); // Note that $action and $object may have been modified by hook if ($reshook < 0) setEventMessages($hookmanager->error, $hookmanager->errors, 'errors'); if (empty($reshook)) { // Send - print '<a class="butAction" href="' . $_SERVER["PHP_SELF"] . '?id=' . $object->id . '&action=presend&mode=init#formmailbeforetitle">' . $langs->trans('SendMail') . '</a>'."\n"; + print '<a class="butAction" href="'.$_SERVER["PHP_SELF"].'?id='.$object->id.'&action=presend&mode=init#formmailbeforetitle">'.$langs->trans('SendMail').'</a>'."\n"; // Modify if ($user->rights->mymodule->write) @@ -383,7 +383,7 @@ if ($object->id > 0 && (empty($action) || ($action != 'edit' && $action != 'crea // Clone if ($user->rights->mymodule->write) { - print '<div class="inline-block divButAction"><a class="butAction" href="' . $_SERVER['PHP_SELF'] . '?id=' . $object->id . '&socid=' . $object->socid . '&action=clone&object=order">' . $langs->trans("ToClone") . '</a></div>'; + print '<div class="inline-block divButAction"><a class="butAction" href="'.$_SERVER['PHP_SELF'].'?id='.$object->id.'&socid='.$object->socid.'&action=clone&object=order">'.$langs->trans("ToClone").'</a></div>'; } /* @@ -443,11 +443,11 @@ if ($object->id > 0 && (empty($action) || ($action != 'edit' && $action != 'crea $MAXEVENT = 10; $morehtmlright = '<a href="'.dol_buildpath('/mymodule/myobject_info.php', 1).'?id='.$object->id.'">'; - $morehtmlright.= $langs->trans("SeeAll"); - $morehtmlright.= '</a>'; + $morehtmlright .= $langs->trans("SeeAll"); + $morehtmlright .= '</a>'; // List of actions on element - include_once DOL_DOCUMENT_ROOT . '/core/class/html.formactions.class.php'; + include_once DOL_DOCUMENT_ROOT.'/core/class/html.formactions.class.php'; $formactions = new FormActions($db); $somethingshown = $formactions->showactions($object, 'myobject', $socid, 1, '', $MAXEVENT, '', $morehtmlright); diff --git a/htdocs/zapier/hook_document.php b/htdocs/zapier/hook_document.php index 6ad31221cc4..67d438c106b 100644 --- a/htdocs/zapier/hook_document.php +++ b/htdocs/zapier/hook_document.php @@ -23,19 +23,19 @@ */ // Load Dolibarr environment -$res=0; +$res = 0; // Try main.inc.php into web root known defined into CONTEXT_DOCUMENT_ROOT (not always defined) -if (! $res && ! empty($_SERVER["CONTEXT_DOCUMENT_ROOT"])) $res=@include $_SERVER["CONTEXT_DOCUMENT_ROOT"]."/main.inc.php"; +if (!$res && !empty($_SERVER["CONTEXT_DOCUMENT_ROOT"])) $res = @include $_SERVER["CONTEXT_DOCUMENT_ROOT"]."/main.inc.php"; // Try main.inc.php into web root detected using web root calculated from SCRIPT_FILENAME -$tmp=empty($_SERVER['SCRIPT_FILENAME'])?'':$_SERVER['SCRIPT_FILENAME'];$tmp2=realpath(__FILE__); $i=strlen($tmp)-1; $j=strlen($tmp2)-1; -while($i > 0 && $j > 0 && isset($tmp[$i]) && isset($tmp2[$j]) && $tmp[$i]==$tmp2[$j]) { $i--; $j--; } -if (! $res && $i > 0 && file_exists(substr($tmp, 0, ($i+1))."/main.inc.php")) $res=@include substr($tmp, 0, ($i+1))."/main.inc.php"; -if (! $res && $i > 0 && file_exists(dirname(substr($tmp, 0, ($i+1)))."/main.inc.php")) $res=@include dirname(substr($tmp, 0, ($i+1)))."/main.inc.php"; +$tmp = empty($_SERVER['SCRIPT_FILENAME']) ? '' : $_SERVER['SCRIPT_FILENAME']; $tmp2 = realpath(__FILE__); $i = strlen($tmp) - 1; $j = strlen($tmp2) - 1; +while ($i > 0 && $j > 0 && isset($tmp[$i]) && isset($tmp2[$j]) && $tmp[$i] == $tmp2[$j]) { $i--; $j--; } +if (!$res && $i > 0 && file_exists(substr($tmp, 0, ($i + 1))."/main.inc.php")) $res = @include substr($tmp, 0, ($i + 1))."/main.inc.php"; +if (!$res && $i > 0 && file_exists(dirname(substr($tmp, 0, ($i + 1)))."/main.inc.php")) $res = @include dirname(substr($tmp, 0, ($i + 1)))."/main.inc.php"; // Try main.inc.php using relative path -if (! $res && file_exists("../main.inc.php")) $res=@include "../main.inc.php"; -if (! $res && file_exists("../../main.inc.php")) $res=@include "../../main.inc.php"; -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 && file_exists("../../main.inc.php")) $res = @include "../../main.inc.php"; +if (!$res && file_exists("../../../main.inc.php")) $res = @include "../../../main.inc.php"; +if (!$res) die("Include of main fails"); require_once DOL_DOCUMENT_ROOT.'/core/lib/company.lib.php'; require_once DOL_DOCUMENT_ROOT.'/core/lib/files.lib.php'; @@ -45,12 +45,12 @@ dol_include_once('/mymodule/class/myobject.class.php'); dol_include_once('/mymodule/lib/mymodule_myobject.lib.php'); // Load translation files required by the page -$langs->loadLangs(array("mymodule@mymodule","companies","other","mails")); +$langs->loadLangs(array("mymodule@mymodule", "companies", "other", "mails")); -$action=GETPOST('action', 'aZ09'); -$confirm=GETPOST('confirm'); -$id=(GETPOST('socid', 'int') ? GETPOST('socid', 'int') : GETPOST('id', 'int')); +$action = GETPOST('action', 'aZ09'); +$confirm = GETPOST('confirm'); +$id = (GETPOST('socid', 'int') ? GETPOST('socid', 'int') : GETPOST('id', 'int')); $ref = GETPOST('ref', 'alpha'); // Security check - Protection if external user @@ -66,31 +66,31 @@ if (empty($page) || $page == -1) { $page = 0; } // If $page is not defined, $offset = $conf->liste_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 -$object=new MyObject($db); +$object = new MyObject($db); $extrafields = new ExtraFields($db); -$diroutputmassaction=$conf->mymodule->dir_output . '/temp/massgeneration/'.$user->id; -$hookmanager->initHooks(array('myobjectdocument','globalcard')); // Note that conf->hooks_modules contains array +$diroutputmassaction = $conf->mymodule->dir_output.'/temp/massgeneration/'.$user->id; +$hookmanager->initHooks(array('myobjectdocument', 'globalcard')); // Note that conf->hooks_modules contains array // 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 // Must be include, not include_once. Include fetch and fetch_thirdparty but not fetch_optionals +include DOL_DOCUMENT_ROOT.'/core/actions_fetchobject.inc.php'; // Must be include, not include_once // Must be include, not include_once. Include fetch and fetch_thirdparty but not fetch_optionals //if ($id > 0 || ! empty($ref)) $upload_dir = $conf->sellyoursaas->multidir_output[$object->entity] . "/myobject/" . dol_sanitizeFileName($object->id); -if ($id > 0 || ! empty($ref)) $upload_dir = $conf->sellyoursaas->multidir_output[$object->entity] . "/myobject/" . dol_sanitizeFileName($object->ref); +if ($id > 0 || !empty($ref)) $upload_dir = $conf->sellyoursaas->multidir_output[$object->entity]."/myobject/".dol_sanitizeFileName($object->ref); /* * Actions */ -include_once DOL_DOCUMENT_ROOT . '/core/actions_linkedfiles.inc.php'; +include_once DOL_DOCUMENT_ROOT.'/core/actions_linkedfiles.inc.php'; /* @@ -99,8 +99,8 @@ include_once DOL_DOCUMENT_ROOT . '/core/actions_linkedfiles.inc.php'; $form = new Form($db); -$title=$langs->trans("MyObject").' - '.$langs->trans("Files"); -$help_url=''; +$title = $langs->trans("MyObject").' - '.$langs->trans("Files"); +$help_url = ''; //$help_url='EN:Module_Third_Parties|FR:Module_Tiers|ES:Empresas'; llxHeader('', $title, $help_url); @@ -115,16 +115,16 @@ 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) + $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) { - $totalsize+=$file['size']; + $totalsize += $file['size']; } // Object card // ------------------------------------------------------------ - $linkback = '<a href="' .dol_buildpath('/mymodule/myobject_list.php', 1) . '?restore_lastsearch_values=1' . (! empty($socid) ? '&socid=' . $socid : '') . '">' . $langs->trans("BackToList") . '</a>'; + $linkback = '<a href="'.dol_buildpath('/mymodule/myobject_list.php', 1).'?restore_lastsearch_values=1'.(!empty($socid) ? '&socid='.$socid : '').'">'.$langs->trans("BackToList").'</a>'; dol_banner_tab($object, 'ref', $linkback, 1, 'ref', 'ref', $morehtmlref); @@ -144,18 +144,6 @@ if ($object->id) print '</div>'; dol_fiche_end(); - - $modulepart = 'mymodule'; - //$permission = $user->rights->mymodule->create; - $permission = 1; - //$permtoedit = $user->rights->mymodule->create; - $permtoedit = 1; - $param = '&id=' . $object->id; - - //$relativepathwithnofile='myobject/' . dol_sanitizeFileName($object->id).'/'; - $relativepathwithnofile='myobject/' . dol_sanitizeFileName($object->ref).'/'; - - include_once DOL_DOCUMENT_ROOT . '/core/tpl/document_actions_post_headers.tpl.php'; } else { diff --git a/htdocs/zapier/hook_list.php b/htdocs/zapier/hook_list.php index 21e9c991d07..a49c0655b80 100644 --- a/htdocs/zapier/hook_list.php +++ b/htdocs/zapier/hook_list.php @@ -42,19 +42,19 @@ //if (! defined("XFRAMEOPTIONS_ALLOWALL")) define('XFRAMEOPTIONS_ALLOWALL',1); // Do not add the HTTP header 'X-Frame-Options: SAMEORIGIN' but 'X-Frame-Options: ALLOWALL' // Load Dolibarr environment -$res=0; +$res = 0; // Try main.inc.php into web root known defined into CONTEXT_DOCUMENT_ROOT (not always defined) -if (! $res && ! empty($_SERVER["CONTEXT_DOCUMENT_ROOT"])) $res=@include $_SERVER["CONTEXT_DOCUMENT_ROOT"]."/main.inc.php"; +if (!$res && !empty($_SERVER["CONTEXT_DOCUMENT_ROOT"])) $res = @include $_SERVER["CONTEXT_DOCUMENT_ROOT"]."/main.inc.php"; // Try main.inc.php into web root detected using web root calculated from SCRIPT_FILENAME -$tmp=empty($_SERVER['SCRIPT_FILENAME'])?'':$_SERVER['SCRIPT_FILENAME'];$tmp2=realpath(__FILE__); $i=strlen($tmp)-1; $j=strlen($tmp2)-1; -while($i > 0 && $j > 0 && isset($tmp[$i]) && isset($tmp2[$j]) && $tmp[$i]==$tmp2[$j]) { $i--; $j--; } -if (! $res && $i > 0 && file_exists(substr($tmp, 0, ($i+1))."/main.inc.php")) $res=@include substr($tmp, 0, ($i+1))."/main.inc.php"; -if (! $res && $i > 0 && file_exists(dirname(substr($tmp, 0, ($i+1)))."/main.inc.php")) $res=@include dirname(substr($tmp, 0, ($i+1)))."/main.inc.php"; +$tmp = empty($_SERVER['SCRIPT_FILENAME']) ? '' : $_SERVER['SCRIPT_FILENAME']; $tmp2 = realpath(__FILE__); $i = strlen($tmp) - 1; $j = strlen($tmp2) - 1; +while ($i > 0 && $j > 0 && isset($tmp[$i]) && isset($tmp2[$j]) && $tmp[$i] == $tmp2[$j]) { $i--; $j--; } +if (!$res && $i > 0 && file_exists(substr($tmp, 0, ($i + 1))."/main.inc.php")) $res = @include substr($tmp, 0, ($i + 1))."/main.inc.php"; +if (!$res && $i > 0 && file_exists(dirname(substr($tmp, 0, ($i + 1)))."/main.inc.php")) $res = @include dirname(substr($tmp, 0, ($i + 1)))."/main.inc.php"; // Try main.inc.php using relative path -if (! $res && file_exists("../main.inc.php")) $res=@include "../main.inc.php"; -if (! $res && file_exists("../../main.inc.php")) $res=@include "../../main.inc.php"; -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 && file_exists("../../main.inc.php")) $res = @include "../../main.inc.php"; +if (!$res && file_exists("../../../main.inc.php")) $res = @include "../../../main.inc.php"; +if (!$res) die("Include of main fails"); require_once DOL_DOCUMENT_ROOT.'/core/class/html.formcompany.class.php'; require_once DOL_DOCUMENT_ROOT.'/core/lib/date.lib.php'; @@ -62,24 +62,24 @@ require_once DOL_DOCUMENT_ROOT.'/core/lib/company.lib.php'; require_once __DIR__.'/class/hook.class.php'; // Load translation files required by the page -$langs->loadLangs(array("mymodule@mymodule","other")); +$langs->loadLangs(array("mymodule@mymodule", "other")); // The action 'add', 'create', 'edit', 'update', 'view', ... -$action = GETPOST('action', 'aZ09')?GETPOST('action', 'aZ09'):'view'; +$action = GETPOST('action', 'aZ09') ?GETPOST('action', 'aZ09') : 'view'; // The bulk action (combo box choice into lists) $massaction = GETPOST('massaction', 'alpha'); -$show_files = GETPOST('show_files', 'int'); // Show files area generated by bulk actions ? -$confirm = GETPOST('confirm', 'alpha'); // Result of a confirmation -$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'):'hooklist'; // 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') +$show_files = GETPOST('show_files', 'int'); // Show files area generated by bulk actions ? +$confirm = GETPOST('confirm', 'alpha'); // Result of a confirmation +$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') : 'hooklist'; // 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') $id = GETPOST('id', 'int'); // Load variable for pagination -$limit = GETPOST('limit', 'int')?GETPOST('limit', 'int'):$conf->liste_limit; +$limit = GETPOST('limit', 'int') ?GETPOST('limit', 'int') : $conf->liste_limit; $sortfield = GETPOST('sortfield', 'alpha'); $sortorder = GETPOST('sortorder', 'alpha'); $page = GETPOST('page', 'int'); @@ -96,7 +96,7 @@ $pagenext = $page + 1; // Initialize technical objects $object = new Hook($db); $extrafields = new ExtraFields($db); -$diroutputmassaction = $conf->mymodule->dir_output . '/temp/massgeneration/'.$user->id; +$diroutputmassaction = $conf->mymodule->dir_output.'/temp/massgeneration/'.$user->id; // Note that conf->hooks_modules contains array $hookmanager->initHooks(array('hooklist')); @@ -106,16 +106,16 @@ $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) { +if (!$sortfield) { // Set here default search field. By default 1st field in definition. - $sortfield="t.".key($object->fields); + $sortfield = "t.".key($object->fields); } -if (! $sortorder) { - $sortorder="ASC"; +if (!$sortorder) { + $sortorder = "ASC"; } // Security check -$socid=0; +$socid = 0; if ($user->socid > 0) { // Protection if external user //$socid = $user->socid; @@ -124,29 +124,29 @@ if ($user->socid > 0) { //$result = restrictedArea($user, 'mymodule', $id, ''); // Initialize array of search criterias -$search_all=trim(GETPOST("search_all", 'alpha')); -$search=array(); -foreach($object->fields as $key => $val) { - if (GETPOST('search_'.$key, 'alpha')) $search[$key]=GETPOST('search_'.$key, 'alpha'); +$search_all = trim(GETPOST("search_all", 'alpha')); +$search = array(); +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) { +$arrayfields = array(); +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'], 'position'=>$val['position']); + if (!empty($val['visible'])) $arrayfields['t.'.$key] = array('label'=>$val['label'], 'checked'=>(($val['visible'] < 0) ? 0 : 1), 'enabled'=>$val['enabled'], '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 (! empty($extrafields->attributes[$object->table_element]['list'][$key])) - $arrayfields["ef.".$key]=array('label'=>$extrafields->attributes[$object->table_element]['label'][$key], 'checked'=>(($extrafields->attributes[$object->table_element]['list'][$key]<0)?0:1), 'position'=>$extrafields->attributes[$object->table_element]['pos'][$key], 'enabled'=>(abs($extrafields->attributes[$object->table_element]['list'][$key])!=3 && $extrafields->attributes[$object->table_element]['perms'][$key])); + 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], 'checked'=>(($extrafields->attributes[$object->table_element]['list'][$key] < 0) ? 0 : 1), 'position'=>$extrafields->attributes[$object->table_element]['pos'][$key], 'enabled'=>(abs($extrafields->attributes[$object->table_element]['list'][$key]) != 3 && $extrafields->attributes[$object->table_element]['perms'][$key])); } } $object->fields = dol_sort_array($object->fields, 'position'); @@ -159,15 +159,15 @@ $arrayfields = dol_sort_array($arrayfields, 'position'); */ if (GETPOST('cancel', 'alpha')) { - $action='list'; - $massaction=''; + $action = 'list'; + $massaction = ''; } -if (! GETPOST('confirmmassaction', 'alpha') && $massaction != 'presend' && $massaction != 'confirm_presend') { - $massaction=''; +if (!GETPOST('confirmmassaction', 'alpha') && $massaction != 'presend' && $massaction != 'confirm_presend') { + $massaction = ''; } -$parameters=array(); -$reshook=$hookmanager->executeHooks('doActions', $parameters, $object, $action); // Note that $action and $object may have been modified by some hooks +$parameters = array(); +$reshook = $hookmanager->executeHooks('doActions', $parameters, $object, $action); // Note that $action and $object may have been modified by some hooks if ($reshook < 0) setEventMessages($hookmanager->error, $hookmanager->errors, 'errors'); if (empty($reshook)) { @@ -175,22 +175,22 @@ if (empty($reshook)) { 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')) { + 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]=''; + foreach ($object->fields as $key => $val) { + $search[$key] = ''; } - $toselect=''; - $search_array_options=array(); + $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')) { - $massaction=''; // Protection to avoid mass action if we force a new search during a mass action confirmation + $massaction = ''; // Protection to avoid mass action if we force a new search during a mass action confirmation } // Mass actions - $objectclass='Hook'; - $objectlabel='Hook'; + $objectclass = 'Hook'; + $objectlabel = 'Hook'; $permissiontoread = $user->rights->mymodule->read; $permissiontodelete = $user->rights->mymodule->delete; $uploaddir = $conf->mymodule->dir_output; @@ -203,57 +203,57 @@ if (empty($reshook)) { * View */ -$form=new Form($db); +$form = new Form($db); -$now=dol_now(); +$now = dol_now(); //$help_url="EN:Module_Hook|FR:Module_Hook_FR|ES:Módulo_Hook"; -$help_url=''; +$help_url = ''; $title = $langs->trans('ListOf', $langs->transnoentitiesnoconv("Hooks")); // Build and execute select // -------------------------------------------------------------------- $sql = 'SELECT '; -foreach($object->fields as $key => $val) { - $sql.='t.'.$key.', '; +foreach ($object->fields as $key => $val) { + $sql .= 't.'.$key.', '; } // Add fields from extrafields -if (! empty($extrafields->attributes[$object->table_element]['label'])) { +if (!empty($extrafields->attributes[$object->table_element]['label'])) { foreach ($extrafields->attributes[$object->table_element]['label'] as $key => $val) { - $sql.=($extrafields->attributes[$object->table_element]['type'][$key] != 'separate' ? "ef.".$key.' as options_'.$key.', ' : ''); + $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, $object); // Note that $action and $object may have been modified by hook -$sql.=$hookmanager->resPrint; -$sql=preg_replace('/, $/', '', $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)"; +$parameters = array(); +$reshook = $hookmanager->executeHooks('printFieldListSelect', $parameters, $object); // Note that $action and $object may have been modified by hook +$sql .= $hookmanager->resPrint; +$sql = preg_replace('/, $/', '', $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).")"; + $sql .= " WHERE t.entity IN (".getEntity($object->element).")"; } else { - $sql.=" WHERE 1 = 1"; + $sql .= " WHERE 1 = 1"; } -foreach($search as $key => $val) { +foreach ($search as $key => $val) { if ($key == 'status' && $search[$key] == -1) { continue; } - $mode_search=(($object->isInt($object->fields[$key]) || $object->isFloat($object->fields[$key]))?1:0); + $mode_search = (($object->isInt($object->fields[$key]) || $object->isFloat($object->fields[$key])) ? 1 : 0); if ($search[$key] != '') { - $sql.=natural_search($key, $search[$key], (($key == 'status')?2:$mode_search)); + $sql .= natural_search($key, $search[$key], (($key == 'status') ? 2 : $mode_search)); } } if ($search_all) { - $sql.= natural_search(array_keys($fieldstosearchall), $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 -$parameters=array(); -$reshook=$hookmanager->executeHooks('printFieldListWhere', $parameters, $object); // Note that $action and $object may have been modified by hook -$sql.=$hookmanager->resPrint; +$parameters = array(); +$reshook = $hookmanager->executeHooks('printFieldListWhere', $parameters, $object); // Note that $action and $object may have been modified by hook +$sql .= $hookmanager->resPrint; /* If a group by is required $sql.= " GROUP BY " @@ -271,7 +271,7 @@ $sql.=$hookmanager->resPrint; $sql=preg_replace('/, $/','', $sql); */ -$sql.=$db->order($sortfield, $sortorder); +$sql .= $db->order($sortfield, $sortorder); // Count total nb of records $nbtotalofrecords = ''; @@ -288,10 +288,10 @@ if (empty($conf->global->MAIN_DISABLE_FULL_SCANLIST)) { if (is_numeric($nbtotalofrecords) && $limit > $nbtotalofrecords) { $num = $nbtotalofrecords; } else { - $sql.= $db->plimit($limit+1, $offset); + $sql .= $db->plimit($limit + 1, $offset); - $resql=$db->query($sql); - if (! $resql) { + $resql = $db->query($sql); + if (!$resql) { dol_print_error($db); exit; } @@ -300,7 +300,7 @@ if (is_numeric($nbtotalofrecords) && $limit > $nbtotalofrecords) { } // Direct jump if only one record found -if ($num == 1 && ! empty($conf->global->MAIN_SEARCH_DIRECT_OPEN_IF_ONLY_ONE) && $search_all) { +if ($num == 1 && !empty($conf->global->MAIN_SEARCH_DIRECT_OPEN_IF_ONLY_ONE) && $search_all) { $obj = $db->fetch_object($resql); $id = $obj->rowid; header("Location: ".dol_buildpath('/zapierfordolibarr/hook_card.php', 1).'?id='.$id); @@ -328,32 +328,32 @@ jQuery(document).ready(function() { }); </script>'; -$arrayofselected=is_array($toselect)?$toselect:array(); +$arrayofselected = is_array($toselect) ? $toselect : array(); -$param=''; -if (! empty($contextpage) && $contextpage != $_SERVER["PHP_SELF"]) $param.='&contextpage='.urlencode($contextpage); -if ($limit > 0 && $limit != $conf->liste_limit) $param.='&limit='.urlencode($limit); -foreach($search as $key => $val) { +$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); + foreach ($search[$key] as $skey) { + $param .= '&search_'.$key.'[]='.urlencode($skey); } } else { - $param.= '&search_'.$key.'='.urlencode($search[$key]); + $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'; // List of mass actions available -$arrayofmassactions = array( +$arrayofmassactions = array( //'presend'=>$langs->trans("SendByMail"), //'builddoc'=>$langs->trans("PDFMerge"), ); -if ($user->rights->mymodule->delete) $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); +if ($user->rights->mymodule->delete) $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); print '<form method="POST" id="searchFormList" action="'.$_SERVER["PHP_SELF"].'">'; if ($optioncss != '') print '<input type="hidden" name="optioncss" value="'.$optioncss.'">'; @@ -365,12 +365,12 @@ 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=''; +$newcardbutton = ''; //if ($user->rights->mymodule->creer) //{ - $newcardbutton='<a class="butActionNew" href="hook_card.php?action=create&backtopage='.urlencode($_SERVER['PHP_SELF']).'"><span class="valignmiddle text-plus-circle">'.$langs->trans('New').'</span>'; - $newcardbutton.= '<span class="fa fa-plus-circle valignmiddle"></span>'; - $newcardbutton.= '</a>'; + $newcardbutton = '<a class="butActionNew" href="hook_card.php?action=create&backtopage='.urlencode($_SERVER['PHP_SELF']).'"><span class="valignmiddle text-plus-circle">'.$langs->trans('New').'</span>'; + $newcardbutton .= '<span class="fa fa-plus-circle valignmiddle"></span>'; + $newcardbutton .= '</a>'; //} //else //{ @@ -382,15 +382,15 @@ $newcardbutton=''; print_barre_liste($title, $page, $_SERVER["PHP_SELF"], $param, $sortfield, $sortorder, $massactionbutton, $num, $nbtotalofrecords, 'title_companies', 0, $newcardbutton, '', $limit); // Add code for pre mass action (confirmation or email presend form) -$topicmail="SendHookRef"; -$modelmail="hook"; -$objecttmp=new Hook($db); -$trackid='xxxx'.$object->id; +$topicmail = "SendHookRef"; +$modelmail = "hook"; +$objecttmp = new Hook($db); +$trackid = 'xxxx'.$object->id; include DOL_DOCUMENT_ROOT.'/core/tpl/massactions_pre.tpl.php'; if ($sall) { - foreach($fieldstosearchall as $key => $val) $fieldstosearchall[$key]=$langs->trans($val); - print '<div class="divsearchfieldfilter">'.$langs->trans("FilterOnInto", $sall) . join(', ', $fieldstosearchall).'</div>'; + foreach ($fieldstosearchall as $key => $val) $fieldstosearchall[$key] = $langs->trans($val); + print '<div class="divsearchfieldfilter">'.$langs->trans("FilterOnInto", $sall).join(', ', $fieldstosearchall).'</div>'; } $moreforfilter = ''; @@ -398,56 +398,56 @@ $moreforfilter = ''; $moreforfilter.= $langs->trans('MyFilter') . ': <input type="text" name="search_myfield" value="'.dol_escape_htmltag($search_myfield).'">'; $moreforfilter.= '</div>';*/ -$parameters=array(); -$reshook=$hookmanager->executeHooks('printFieldPreListTitle', $parameters, $object); // Note that $action and $object may have been modified by hook +$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($moreforfilter)) { +if (!empty($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 -$selectedfields.=(count($arrayofmassactions) ? $form->showCheckAddButtons('checkforselect', 1) : ''); +$varpage = empty($contextpage) ? $_SERVER["PHP_SELF"] : $contextpage; +$selectedfields = $form->multiSelectArrayWithCheckbox('selectedfields', $arrayfields, $varpage); // This also change content of $arrayfields +$selectedfields .= (count($arrayofmassactions) ? $form->showCheckAddButtons('checkforselect', 1) : ''); -print '<div class="div-table-responsive">'; // You can use div-table-responsive-no-min if you dont need reserved height for your table -print '<table class="tagtable liste'.($moreforfilter?" listwithfilterbefore":"").'">'."\n"; +print '<div class="div-table-responsive">'; // You can use div-table-responsive-no-min if you dont need reserved height for your table +print '<table class="tagtable liste'.($moreforfilter ? " listwithfilterbefore" : "").'">'."\n"; // Fields title search // -------------------------------------------------------------------- print '<tr class="liste_titre">'; -foreach($object->fields as $key => $val) { - $cssforfield=''; - if (in_array($val['type'], array('date','datetime','timestamp'))) { - $cssforfield.=($cssforfield?' ':'').'center'; +foreach ($object->fields as $key => $val) { + $cssforfield = ''; + if (in_array($val['type'], array('date', 'datetime', 'timestamp'))) { + $cssforfield .= ($cssforfield ? ' ' : '').'center'; } if (in_array($val['type'], array('timestamp'))) { - $cssforfield.=($cssforfield?' ':'').'nowrap'; + $cssforfield .= ($cssforfield ? ' ' : '').'nowrap'; } if (in_array($val['type'], array('double(24,8)', 'double(6,3)', 'integer', 'real'))) { - $cssforfield.=($cssforfield?' ':'').'right'; + $cssforfield .= ($cssforfield ? ' ' : '').'right'; } if ($key == 'status') { - $cssforfield.=($cssforfield?' ':'').'center'; + $cssforfield .= ($cssforfield ? ' ' : '').'center'; } - if (! empty($arrayfields['t.'.$key]['checked'])) { - print '<td class="liste_titre'.($cssforfield?' '.$cssforfield:'').'"><input type="text" class="flat maxwidth75" name="search_'.$key.'" value="'.dol_escape_htmltag($search[$key]).'"></td>'; + if (!empty($arrayfields['t.'.$key]['checked'])) { + print '<td class="liste_titre'.($cssforfield ? ' '.$cssforfield : '').'"><input type="text" class="flat maxwidth75" name="search_'.$key.'" value="'.dol_escape_htmltag($search[$key]).'"></td>'; } } // Extra fields include DOL_DOCUMENT_ROOT.'/core/tpl/extrafields_list_search_input.tpl.php'; // Fields from hook -$parameters=array('arrayfields'=>$arrayfields); -$reshook=$hookmanager->executeHooks('printFieldListOption', $parameters, $object); // Note that $action and $object may have been modified by hook +$parameters = array('arrayfields'=>$arrayfields); +$reshook = $hookmanager->executeHooks('printFieldListOption', $parameters, $object); // Note that $action and $object may have been modified by hook print $hookmanager->resPrint; // Action column print '<td class="liste_titre right">'; -$searchpicto=$form->showFilterButtons(); +$searchpicto = $form->showFilterButtons(); print $searchpicto; print '</td>'; print '</tr>'."\n"; @@ -456,16 +456,16 @@ print '</tr>'."\n"; // Fields title label // -------------------------------------------------------------------- print '<tr class="liste_titre">'; -foreach($object->fields as $key => $val) { - $cssforfield=''; - if (in_array($val['type'], array('date','datetime','timestamp'))) $cssforfield.=($cssforfield?' ':'').'center'; - if (in_array($val['type'], array('timestamp'))) $cssforfield.=($cssforfield?' ':'').'nowrap'; - if (in_array($val['type'], array('double(24,8)', 'double(6,3)', 'integer', 'real'))) $cssforfield.=($cssforfield?' ':'').'right'; +foreach ($object->fields as $key => $val) { + $cssforfield = ''; + if (in_array($val['type'], array('date', 'datetime', 'timestamp'))) $cssforfield .= ($cssforfield ? ' ' : '').'center'; + if (in_array($val['type'], array('timestamp'))) $cssforfield .= ($cssforfield ? ' ' : '').'nowrap'; + if (in_array($val['type'], array('double(24,8)', 'double(6,3)', 'integer', 'real'))) $cssforfield .= ($cssforfield ? ' ' : '').'right'; if ($key == 'status') { - $cssforfield.=($cssforfield?' ':'').'center'; + $cssforfield .= ($cssforfield ? ' ' : '').'center'; } - 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"; + 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"; } } // Extra fields @@ -477,7 +477,7 @@ $parameters = array( 'sortfield' => $sortfield, 'sortorder' => $sortorder, ); -$reshook=$hookmanager->executeHooks('printFieldListTitle', $parameters, $object); // Note that $action and $object may have been modified by hook +$reshook = $hookmanager->executeHooks('printFieldListTitle', $parameters, $object); // Note that $action and $object may have been modified by hook print $hookmanager->resPrint; // Action column print getTitleFieldOfList($selectedfields, 0, $_SERVER["PHP_SELF"], '', '', '', '', $sortfield, $sortorder, 'center maxwidthsearch ')."\n"; @@ -485,7 +485,7 @@ print '</tr>'."\n"; // Detect if we need a fetch on each output line -$needToFetchEachLine=0; +$needToFetchEachLine = 0; if (is_array($extrafields->attributes[$object->table_element]['computed']) && count($extrafields->attributes[$object->table_element]['computed']) > 0) { foreach ($extrafields->attributes[$object->table_element]['computed'] as $key => $val) { if (preg_match('/\$object/', $val)) { @@ -498,36 +498,36 @@ if (is_array($extrafields->attributes[$object->table_element]['computed']) && co // Loop on record // -------------------------------------------------------------------- -$i=0; -$totalarray=array(); +$i = 0; +$totalarray = array(); while ($i < min($num, $limit)) { $obj = $db->fetch_object($resql); if (empty($obj)) { - break; // Should not happen + break; // Should not happen } // Store properties in $object $object->id = $obj->rowid; - foreach($object->fields as $key => $val) { + foreach ($object->fields as $key => $val) { if (isset($obj->$key)) $object->$key = $obj->$key; } // Show here line of result print '<tr class="oddeven">'; - foreach($object->fields as $key => $val) { - $cssforfield=''; - if (in_array($val['type'], array('date','datetime','timestamp'))) { - $cssforfield.=($cssforfield?' ':'').'center'; + foreach ($object->fields as $key => $val) { + $cssforfield = ''; + if (in_array($val['type'], array('date', 'datetime', 'timestamp'))) { + $cssforfield .= ($cssforfield ? ' ' : '').'center'; } elseif ($key == 'status') { - $cssforfield.=($cssforfield?' ':'').'center'; + $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'))) $cssforfield.=($cssforfield?' ':'').'right'; + if (in_array($val['type'], array('double(24,8)', 'double(6,3)', 'integer', 'real'))) $cssforfield .= ($cssforfield ? ' ' : '').'right'; - if (! empty($arrayfields['t.'.$key]['checked'])) { + if (!empty($arrayfields['t.'.$key]['checked'])) { print '<td'; if ($cssforfield || $val['css']) print ' class="'; print $cssforfield; @@ -536,13 +536,13 @@ while ($i < min($num, $limit)) { if ($cssforfield || $val['css']) print '"'; print '>'; if ($key == 'status') print $object->getLibStatut(5); - elseif (in_array($val['type'], array('date','datetime','timestamp'))) print $object->showOutputField($val, $key, $db->jdate($obj->$key), ''); + elseif (in_array($val['type'], array('date', 'datetime', 'timestamp'))) print $object->showOutputField($val, $key, $db->jdate($obj->$key), ''); else print $object->showOutputField($val, $key, $obj->$key, ''); print '</td>'; - if (! $i) $totalarray['nbfield']++; - if (! empty($val['isameasure'])) + if (!$i) $totalarray['nbfield']++; + if (!empty($val['isameasure'])) { - if (! $i) $totalarray['pos'][$totalarray['nbfield']]='t.'.$key; + if (!$i) $totalarray['pos'][$totalarray['nbfield']] = 't.'.$key; $totalarray['val']['t.'.$key] += $obj->$key; } } @@ -550,19 +550,19 @@ while ($i < min($num, $limit)) { // Extra fields include DOL_DOCUMENT_ROOT.'/core/tpl/extrafields_list_print_fields.tpl.php'; // Fields from hook - $parameters=array('arrayfields'=>$arrayfields, 'obj'=>$obj); - $reshook=$hookmanager->executeHooks('printFieldListValue', $parameters, $object); // Note that $action and $object may have been modified by hook + $parameters = array('arrayfields'=>$arrayfields, 'obj'=>$obj); + $reshook = $hookmanager->executeHooks('printFieldListValue', $parameters, $object); // Note that $action and $object may have been modified by hook print $hookmanager->resPrint; // 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 - $selected=0; - 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"':'').'>'; + $selected = 0; + 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>'; @@ -575,9 +575,9 @@ include DOL_DOCUMENT_ROOT.'/core/tpl/list_print_total.tpl.php'; // If no record found if ($num == 0) { - $colspan=1; - foreach($arrayfields as $key => $val) { - if (! empty($val['checked'])) { + $colspan = 1; + foreach ($arrayfields as $key => $val) { + if (!empty($val['checked'])) { $colspan++; } } @@ -591,7 +591,7 @@ $parameters = array( 'arrayfields' => $arrayfields, 'sql' => $sql, ); -$reshook=$hookmanager->executeHooks('printFieldListFooter', $parameters, $object); // Note that $action and $object may have been modified by hook +$reshook = $hookmanager->executeHooks('printFieldListFooter', $parameters, $object); // Note that $action and $object may have been modified by hook print $hookmanager->resPrint; print '</table>'."\n"; @@ -600,21 +600,21 @@ print '</div>'."\n"; print '</form>'."\n"; if (in_array('builddoc', $arrayofmassactions) && ($nbtotalofrecords === '' || $nbtotalofrecords)) { - $hidegeneratedfilelistifempty=1; + $hidegeneratedfilelistifempty = 1; if ($massaction == 'builddoc' || $action == 'remove_file' || $show_files) { - $hidegeneratedfilelistifempty=0; + $hidegeneratedfilelistifempty = 0; } require_once DOL_DOCUMENT_ROOT.'/core/class/html.formfile.class.php'; $formfile = new FormFile($db); // Show list of available documents - $urlsource=$_SERVER['PHP_SELF'].'?sortfield='.$sortfield.'&sortorder='.$sortorder; - $urlsource.=str_replace('&', '&', $param); + $urlsource = $_SERVER['PHP_SELF'].'?sortfield='.$sortfield.'&sortorder='.$sortorder; + $urlsource .= str_replace('&', '&', $param); - $filedir=$diroutputmassaction; - $genallowed=$user->rights->mymodule->read; - $delallowed=$user->rights->mymodule->create; + $filedir = $diroutputmassaction; + $genallowed = $user->rights->mymodule->read; + $delallowed = $user->rights->mymodule->create; print $formfile->showdocuments('massfilesarea_mymodule', '', $filedir, $urlsource, 0, $delallowed, '', 1, 1, 0, 48, 1, $param, $title, '', '', '', null, $hidegeneratedfilelistifempty); } diff --git a/htdocs/zapier/hook_note.php b/htdocs/zapier/hook_note.php index dcfba358da1..c56b36be33e 100644 --- a/htdocs/zapier/hook_note.php +++ b/htdocs/zapier/hook_note.php @@ -23,38 +23,38 @@ */ // Load Dolibarr environment -$res=0; +$res = 0; // Try main.inc.php into web root known defined into CONTEXT_DOCUMENT_ROOT (not always defined) -if (! $res && ! empty($_SERVER["CONTEXT_DOCUMENT_ROOT"])) $res=@include $_SERVER["CONTEXT_DOCUMENT_ROOT"]."/main.inc.php"; +if (!$res && !empty($_SERVER["CONTEXT_DOCUMENT_ROOT"])) $res = @include $_SERVER["CONTEXT_DOCUMENT_ROOT"]."/main.inc.php"; // Try main.inc.php into web root detected using web root calculated from SCRIPT_FILENAME -$tmp=empty($_SERVER['SCRIPT_FILENAME'])?'':$_SERVER['SCRIPT_FILENAME'];$tmp2=realpath(__FILE__); $i=strlen($tmp)-1; $j=strlen($tmp2)-1; -while($i > 0 && $j > 0 && isset($tmp[$i]) && isset($tmp2[$j]) && $tmp[$i]==$tmp2[$j]) { $i--; $j--; } -if (! $res && $i > 0 && file_exists(substr($tmp, 0, ($i+1))."/main.inc.php")) $res=@include substr($tmp, 0, ($i+1))."/main.inc.php"; -if (! $res && $i > 0 && file_exists(dirname(substr($tmp, 0, ($i+1)))."/main.inc.php")) $res=@include dirname(substr($tmp, 0, ($i+1)))."/main.inc.php"; +$tmp = empty($_SERVER['SCRIPT_FILENAME']) ? '' : $_SERVER['SCRIPT_FILENAME']; $tmp2 = realpath(__FILE__); $i = strlen($tmp) - 1; $j = strlen($tmp2) - 1; +while ($i > 0 && $j > 0 && isset($tmp[$i]) && isset($tmp2[$j]) && $tmp[$i] == $tmp2[$j]) { $i--; $j--; } +if (!$res && $i > 0 && file_exists(substr($tmp, 0, ($i + 1))."/main.inc.php")) $res = @include substr($tmp, 0, ($i + 1))."/main.inc.php"; +if (!$res && $i > 0 && file_exists(dirname(substr($tmp, 0, ($i + 1)))."/main.inc.php")) $res = @include dirname(substr($tmp, 0, ($i + 1)))."/main.inc.php"; // Try main.inc.php using relative path -if (! $res && file_exists("../main.inc.php")) $res=@include "../main.inc.php"; -if (! $res && file_exists("../../main.inc.php")) $res=@include "../../main.inc.php"; -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 && file_exists("../../main.inc.php")) $res = @include "../../main.inc.php"; +if (!$res && file_exists("../../../main.inc.php")) $res = @include "../../../main.inc.php"; +if (!$res) die("Include of main fails"); dol_include_once('/mymodule/class/myobject.class.php'); dol_include_once('/mymodule/lib/mymodule_myobject.lib.php'); // Load translation files required by the page -$langs->loadLangs(array("mymodule@mymodule","companies")); +$langs->loadLangs(array("mymodule@mymodule", "companies")); // Get parameters -$id = GETPOST('id', 'int'); +$id = GETPOST('id', 'int'); $ref = GETPOST('ref', 'alpha'); -$action = GETPOST('action', 'alpha'); +$action = GETPOST('action', 'alpha'); $cancel = GETPOST('cancel', 'aZ09'); $backtopage = GETPOST('backtopage', 'alpha'); // Initialize technical objects -$object=new MyObject($db); +$object = new MyObject($db); $extrafields = new ExtraFields($db); -$diroutputmassaction=$conf->mymodule->dir_output . '/temp/massgeneration/'.$user->id; -$hookmanager->initHooks(array('myobjectnote','globalcard')); // Note that conf->hooks_modules contains array +$diroutputmassaction = $conf->mymodule->dir_output.'/temp/massgeneration/'.$user->id; +$hookmanager->initHooks(array('myobjectnote', 'globalcard')); // Note that conf->hooks_modules contains array // Fetch optionals attributes and labels $extrafields->fetch_name_optionals_label($object->table_element); @@ -65,10 +65,10 @@ $extrafields->fetch_name_optionals_label($object->table_element); //$result = restrictedArea($user, 'mymodule', $id); // 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->mymodule->multidir_output[$object->entity] . "/" . $object->id; +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->mymodule->multidir_output[$object->entity]."/".$object->id; -$permissionnote=1; +$permissionnote = 1; //$permissionnote=$user->rights->mymodule->creer; // Used by the include of actions_setnotes.inc.php @@ -77,7 +77,7 @@ $permissionnote=1; * Actions */ -include DOL_DOCUMENT_ROOT.'/core/actions_setnotes.inc.php'; // Must be include, not include_once +include DOL_DOCUMENT_ROOT.'/core/actions_setnotes.inc.php'; // Must be include, not include_once /* @@ -87,10 +87,10 @@ include DOL_DOCUMENT_ROOT.'/core/actions_setnotes.inc.php'; // Must be include, $form = new Form($db); //$help_url='EN:Customers_Orders|FR:Commandes_Clients|ES:Pedidos de clientes'; -$help_url=''; +$help_url = ''; llxHeader('', $langs->trans('MyObject'), $help_url); -if ($id > 0 || ! empty($ref)) +if ($id > 0 || !empty($ref)) { $object->fetch_thirdparty(); @@ -100,9 +100,9 @@ if ($id > 0 || ! empty($ref)) // Object card // ------------------------------------------------------------ - $linkback = '<a href="' .dol_buildpath('/mymodule/myobject_list.php', 1) . '?restore_lastsearch_values=1' . (! empty($socid) ? '&socid=' . $socid : '') . '">' . $langs->trans("BackToList") . '</a>'; + $linkback = '<a href="'.dol_buildpath('/mymodule/myobject_list.php', 1).'?restore_lastsearch_values=1'.(!empty($socid) ? '&socid='.$socid : '').'">'.$langs->trans("BackToList").'</a>'; - $morehtmlref='<div class="refidno">'; + $morehtmlref = '<div class="refidno">'; /* // Ref customer $morehtmlref.=$form->editfieldkey("RefCustomer", 'ref_client', $object->ref_client, $object, 0, 'string', '', 0, 1); @@ -142,7 +142,7 @@ if ($id > 0 || ! empty($ref)) } } }*/ - $morehtmlref.='</div>'; + $morehtmlref .= '</div>'; dol_banner_tab($object, 'ref', $linkback, 1, 'ref', 'ref', $morehtmlref); @@ -152,7 +152,7 @@ if ($id > 0 || ! empty($ref)) print '<div class="underbanner clearboth"></div>'; - $cssclass="titlefield"; + $cssclass = "titlefield"; include DOL_DOCUMENT_ROOT.'/core/tpl/notes.tpl.php'; print '</div>'; diff --git a/htdocs/zapier/zapierindex.php b/htdocs/zapier/zapierindex.php index f70f9e8c95d..f9931a29d41 100644 --- a/htdocs/zapier/zapierindex.php +++ b/htdocs/zapier/zapierindex.php @@ -104,7 +104,7 @@ if (! empty($conf->zapierfordolibarr->enabled) && $user->rights->zapierfordoliba $total = 0; $num = $db->num_rows($resql); - print '<table class="noborder" width="100%">'; + print '<table class="noborder centpercent">'; print '<tr class="liste_titre">'; print '<th colspan="3">'.$langs->trans("DraftOrders").($num?'<span class="badge marginleftonlyshort">'.$num.'</span>':'').'</th></tr>'; @@ -188,7 +188,7 @@ if (! empty($conf->zapierfordolibarr->enabled) && $user->rights->zapierfordoliba $num = $db->num_rows($resql); $i = 0; - print '<table class="noborder" width="100%">'; + print '<table class="noborder centpercent">'; print '<tr class="liste_titre">'; print '<th colspan="2">'; if (empty($conf->global->SOCIETE_DISABLE_PROSPECTS) && empty($conf->global->SOCIETE_DISABLE_CUSTOMERS)) print $langs->trans("BoxTitleLastCustomersOrProspects",$max); diff --git a/scripts/accountancy/export-thirdpartyaccount.php b/scripts/accountancy/export-thirdpartyaccount.php index 4a55aa81376..b03f397fd7e 100755 --- a/scripts/accountancy/export-thirdpartyaccount.php +++ b/scripts/accountancy/export-thirdpartyaccount.php @@ -57,16 +57,16 @@ if (empty($date_start) || empty($date_end)) // We define date_start and date_end // We define date_start and date_end $year_end = $year_start; $month_start = GETPOST("month") ? GETPOST("month") : ($conf->global->SOCIETE_FISCAL_MONTH_START ? ($conf->global->SOCIETE_FISCAL_MONTH_START) : 1); - if (! GETPOST('month')) { - if (! GETPOST("year") && $month_start > $month_current) { - $year_start --; - $year_end --; + if (!GETPOST('month')) { + if (!GETPOST("year") && $month_start > $month_current) { + $year_start--; + $year_end--; } $month_end = $month_start - 1; if ($month_end < 1) $month_end = 12; else - $year_end ++; + $year_end++; } else $month_end = $month_start; $date_start = dol_get_first_day($year_start, $month_start, false); @@ -100,11 +100,11 @@ $periodlink = ''; $exportlink = ''; $nom = $langs->trans("ReportThirdParty"); -$period = $form->selectDate($date_start, 'date_start', 0, 0, 0, '', 1, 0) . ' - ' . $form->selectDate($date_end, 'date_end', 0, 0, 0, '', 1, 0); +$period = $form->selectDate($date_start, 'date_start', 0, 0, 0, '', 1, 0).' - '.$form->selectDate($date_end, 'date_end', 0, 0, 0, '', 1, 0); $description = $langs->trans("DescThirdPartyReport"); -$builddate=dol_now(); +$builddate = dol_now(); -$moreparam=array('action' => ''); +$moreparam = array('action' => ''); report_header($nom, $nomlink, $period, $periodlink, $description, $builddate, $exportlink, $moreparam); print '<input type="button" class="button" style="float: right;" value="Export CSV" onclick="launch_export();" />'; @@ -121,36 +121,36 @@ print ' $sql = "(SELECT s.rowid, s.nom as name , s.address, s.zip , s.town, s.code_compta as compta , "; $sql .= " s.fk_forme_juridique , s.fk_pays , s.phone , s.fax , f.datec , f.fk_soc , cp.label as country "; -$sql .= " FROM " . MAIN_DB_PREFIX . "societe as s"; -$sql .= ", " . MAIN_DB_PREFIX . "facture as f"; -$sql .= ", " . MAIN_DB_PREFIX . "c_country as cp"; +$sql .= " FROM ".MAIN_DB_PREFIX."societe as s"; +$sql .= ", ".MAIN_DB_PREFIX."facture as f"; +$sql .= ", ".MAIN_DB_PREFIX."c_country as cp"; $sql .= " WHERE f.fk_soc = s.rowid"; $sql .= " AND s.fk_pays = cp.rowid"; -if (! empty($date_start) && ! empty($date_end)) - $sql .= " AND f.datec >= '" . $db->idate($date_start) . "' AND f.datec <= '" . $db->idate($date_end) . "'"; +if (!empty($date_start) && !empty($date_end)) + $sql .= " AND f.datec >= '".$db->idate($date_start)."' AND f.datec <= '".$db->idate($date_end)."'"; $sql .= " AND f.entity IN (".getEntity('invoice', 0).")"; if ($socid) - $sql .= " AND f.fk_soc = " . $socid; + $sql .= " AND f.fk_soc = ".$socid; $sql .= " GROUP BY name"; $sql .= ")"; $sql .= "UNION (SELECT s.rowid, s.nom as name , s.address, s.zip , s.town, s.code_compta_fournisseur as compta , "; $sql .= " s.fk_forme_juridique , s.fk_pays , s.phone , s.fax , ff.datec , ff.fk_soc , cp.label as country "; -$sql .= " FROM " . MAIN_DB_PREFIX . "societe as s"; -$sql .= ", " . MAIN_DB_PREFIX . "facture_fourn as ff"; -$sql .= ", " . MAIN_DB_PREFIX . "c_country as cp"; +$sql .= " FROM ".MAIN_DB_PREFIX."societe as s"; +$sql .= ", ".MAIN_DB_PREFIX."facture_fourn as ff"; +$sql .= ", ".MAIN_DB_PREFIX."c_country as cp"; $sql .= " WHERE ff.fk_soc = s.rowid"; $sql .= " AND s.fk_pays = cp.rowid"; -if (! empty($date_start) && ! empty($date_end)) - $sql .= " AND ff.datec >= '" . $db->idate($date_start) . "' AND ff.datec <= '" . $db->idate($date_end) . "'"; -$sql .= " AND ff.entity = " . $conf->entity; +if (!empty($date_start) && !empty($date_end)) + $sql .= " AND ff.datec >= '".$db->idate($date_start)."' AND ff.datec <= '".$db->idate($date_end)."'"; +$sql .= " AND ff.entity = ".$conf->entity; if ($socid) - $sql .= " AND f.fk_soc = " . $socid; + $sql .= " AND f.fk_soc = ".$socid; $sql .= " GROUP BY name"; $sql .= ")"; $sql .= "ORDER BY name ASC"; -dol_syslog('accountancy/admin/thirdpartyaccount.php:: $sql=' . $sql); +dol_syslog('accountancy/admin/thirdpartyaccount.php:: $sql='.$sql); $resql = $db->query($sql); if ($resql) { $num = $db->num_rows($resql); @@ -163,15 +163,15 @@ if ($resql) { $obj = $db->fetch_object($resql); - print '"' . $obj->compta . '",'; - print '"' . $obj->address . '",'; - print '"' . $obj->zip . '",'; - print '"' . $obj->town . '",'; - print '"' . $obj->country . '",'; - print '"' . $obj->phone . '",'; - print '"' . $obj->fax . '",'; + print '"'.$obj->compta.'",'; + print '"'.$obj->address.'",'; + print '"'.$obj->zip.'",'; + print '"'.$obj->town.'",'; + print '"'.$obj->country.'",'; + print '"'.$obj->phone.'",'; + print '"'.$obj->fax.'",'; print "\n"; - $i ++; + $i++; } /* @@ -182,21 +182,21 @@ if ($resql) { print '<br><br>'; - print '<table class="noborder" width="100%">'; + print '<table class="noborder centpercent">'; print "</table>\n"; print '</td><td valign="top" width="70%" class="notopnoleftnoright"></td>'; print '</tr><tr><td colspan=2>'; - print '<table class="noborder" width="100%">'; - print '<tr class="liste_titre"><td class="left">' . $langs->trans("ThirdParties") . '</td>'; - print '<td class="left">' . $langs->trans("AccountNumber") . '</td>'; - print '<td class="left">' . $langs->trans("RaisonSociale") . '</td>'; - print '<td class="left">' . $langs->trans("Address") . '</td>'; - print '<td class="left">' . $langs->trans("Zip") . '</td>'; - print '<td class="left">' . $langs->trans("Town") . '</td>'; - print '<td class="left">' . $langs->trans("Country") . '</td>'; - print '<td class="left">' . $langs->trans("Contact") . '</td>'; - print '<td class="left">' . $langs->trans("Phone") . '</td>'; - print '<td class="left">' . $langs->trans("Fax") . '</td></tr>'; + print '<table class="noborder centpercent">'; + print '<tr class="liste_titre"><td class="left">'.$langs->trans("ThirdParties").'</td>'; + print '<td class="left">'.$langs->trans("AccountNumber").'</td>'; + print '<td class="left">'.$langs->trans("RaisonSociale").'</td>'; + print '<td class="left">'.$langs->trans("Address").'</td>'; + print '<td class="left">'.$langs->trans("Zip").'</td>'; + print '<td class="left">'.$langs->trans("Town").'</td>'; + print '<td class="left">'.$langs->trans("Country").'</td>'; + print '<td class="left">'.$langs->trans("Contact").'</td>'; + print '<td class="left">'.$langs->trans("Phone").'</td>'; + print '<td class="left">'.$langs->trans("Fax").'</td></tr>'; while ($obj = $db->fetch_object($resql)) { @@ -209,18 +209,18 @@ if ($resql) { $thirdpartystatic->status = $obj->status; print $thirdpartystatic->getNomUrl(1); print '</td>'; - print '<td class="left">' . $obj->compta . '</td>' . "\n"; + print '<td class="left">'.$obj->compta.'</td>'."\n"; print '<td class="left"></td>'; - print '<td class="left">' . $obj->address . '</td>'; - print '<td class="left">' . $obj->zip . '</td>'; - print '<td class="left">' . $obj->town . '</td>'; - print '<td class="left">' . $obj->country . '</td>'; + print '<td class="left">'.$obj->address.'</td>'; + print '<td class="left">'.$obj->zip.'</td>'; + print '<td class="left">'.$obj->town.'</td>'; + print '<td class="left">'.$obj->country.'</td>'; print '<td class="left"></td>'; - print '<td class="left">' . $obj->phone . '</td>'; - print '<td class="left">' . $obj->fax . '</td>'; + print '<td class="left">'.$obj->phone.'</td>'; + print '<td class="left">'.$obj->fax.'</td>'; print "</tr>\n"; - $i ++; + $i++; } print "</table>";
    '.$langs->trans("Ref").''; @@ -2138,7 +2137,7 @@ else // Login print "
    '.$langs->trans("Login").''; - if ($user->admin && !$object->ldap_sid) + if ($user->admin && !$object->ldap_sid) { print ''; } @@ -2153,43 +2152,43 @@ else // Pass print '
    '.$langs->trans("Password").''; - $valuetoshow=''; + $valuetoshow = ''; if (preg_match('/ldap/', $dolibarr_main_authentication)) { - $valuetoshow.=($valuetoshow?(' '.$langs->trans("or").' '):'').$langs->trans("PasswordOfUserInLDAP"); + $valuetoshow .= ($valuetoshow ? (' '.$langs->trans("or").' ') : '').$langs->trans("PasswordOfUserInLDAP"); } if (preg_match('/http/', $dolibarr_main_authentication)) { - $valuetoshow.=($valuetoshow?(' '.$langs->trans("or").' '):'').$form->textwithpicto($text, $langs->trans("DolibarrInHttpAuthenticationSoPasswordUseless", $dolibarr_main_authentication), 1, 'warning'); + $valuetoshow .= ($valuetoshow ? (' '.$langs->trans("or").' ') : '').$form->textwithpicto($text, $langs->trans("DolibarrInHttpAuthenticationSoPasswordUseless", $dolibarr_main_authentication), 1, 'warning'); } if (preg_match('/dolibarr/', $dolibarr_main_authentication)) { if ($caneditpassword) { - $valuetoshow.=($valuetoshow?(' '.$langs->trans("or").' '):'').''; + $valuetoshow .= ($valuetoshow ? (' '.$langs->trans("or").' ') : '').''; } else { - $valuetoshow.=($valuetoshow?(' '.$langs->trans("or").' '):'').preg_replace('/./i', '*', $object->pass); + $valuetoshow .= ($valuetoshow ? (' '.$langs->trans("or").' ') : '').preg_replace('/./i', '*', $object->pass); } } // Other form for user password - $parameters=array('valuetoshow' => $valuetoshow, 'caneditpassword' => $caneditpassword); - $reshook=$hookmanager->executeHooks('printUserPasswordField', $parameters, $object, $action); // Note that $action and $object may have been modified by hook - if ($reshook > 0) $valuetoshow=$hookmanager->resPrint; // to replace - else $valuetoshow.=$hookmanager->resPrint; // to add + $parameters = array('valuetoshow' => $valuetoshow, 'caneditpassword' => $caneditpassword); + $reshook = $hookmanager->executeHooks('printUserPasswordField', $parameters, $object, $action); // Note that $action and $object may have been modified by hook + if ($reshook > 0) $valuetoshow = $hookmanager->resPrint; // to replace + else $valuetoshow .= $hookmanager->resPrint; // to add print $valuetoshow; print "
    '.$langs->trans("ApiKey").''; print ''; - if (! empty($conf->use_javascript_ajax)) + if (!empty($conf->use_javascript_ajax)) print ' '.img_picto($langs->trans('Generate'), 'refresh', 'id="generate_api_key" class="linkobject"'); print '
    '.$langs->trans("Type").''; - if ($user->id == $object->id || ! $user->admin) + if ($user->id == $object->id || !$user->admin) { - $type=$langs->trans("Internal"); - if ($object->socid) $type=$langs->trans("External"); + $type = $langs->trans("Internal"); + if ($object->socid) $type = $langs->trans("External"); print $form->textwithpicto($type, $langs->trans("InternalExternalDesc")); if ($object->ldap_sid) print ' ('.$langs->trans("DomainUser").')'; } else { - $type=0; - if ($object->contactid) $type=$object->contactid; + $type = 0; + if ($object->contactid) $type = $object->contactid; print $form->selectcontacts(0, $type, 'contactid', 2, '', '', 1, '', false, 1); if ($object->ldap_sid) print ' ('.$langs->trans("DomainUser").')'; } @@ -2299,8 +2298,8 @@ else // Gender print '
    '.$langs->trans("Gender").''; - $arraygender=array('man'=>$langs->trans("Genderman"),'woman'=>$langs->trans("Genderwoman")); - print $form->selectarray('gender', $arraygender, GETPOST('gender')?GETPOST('gender'):$object->gender, 1); + $arraygender = array('man'=>$langs->trans("Genderman"), 'woman'=>$langs->trans("Genderwoman")); + print $form->selectarray('gender', $arraygender, GETPOST('gender') ?GETPOST('gender') : $object->gender, 1); print '
    '.$form->editfieldkey('Country', 'selectcounty_id', '', $object, 0).''; - print $form->select_country((GETPOST('country_id')!=''?GETPOST('country_id'):$object->country_id), 'country_id'); + print $form->select_country((GETPOST('country_id') != '' ?GETPOST('country_id') : $object->country_id), 'country_id'); if ($user->admin) print info_admin($langs->trans("YouCanChangeValuesForThisListFromDictionarySetup"), 1); print '
    '.img_picto('', 'object_phoning').' '.$langs->trans("PhonePro").''; - if ($caneditfield && empty($object->ldap_sid)) + if ($caneditfield && empty($object->ldap_sid)) { print ''; } @@ -2439,7 +2438,7 @@ else // Fax print "
    '.img_picto('', 'object_phoning_fax').' '.$langs->trans("Fax").''; - if ($caneditfield && empty($object->ldap_sid)) + if ($caneditfield && empty($object->ldap_sid)) { print ''; } @@ -2451,9 +2450,9 @@ else print '
    '; - if ($caneditfield && empty($object->ldap_sid)) + if ($caneditfield && empty($object->ldap_sid)) { print ''; } @@ -2464,12 +2463,12 @@ else } print '
    '.$langs->trans($value['label']).''; - if ($caneditfield && empty($object->ldap_sid)) { + if ($caneditfield && empty($object->ldap_sid)) { print ''; } else { print ''; @@ -2552,7 +2551,7 @@ else // } // OpenID url - if (isset($conf->file->main_authentication) && preg_match('/openid/', $conf->file->main_authentication) && ! empty($conf->global->MAIN_OPENIDURL_PERUSER)) + if (isset($conf->file->main_authentication) && preg_match('/openid/', $conf->file->main_authentication) && !empty($conf->global->MAIN_OPENIDURL_PERUSER)) { print "
    '.$langs->trans("OpenIDURL").''; @@ -2590,14 +2589,14 @@ else } // User color - if (! empty($conf->agenda->enabled)) + if (!empty($conf->agenda->enabled)) { print '
    '.$langs->trans("ColorUser").''; if ($caneditfield) { - print $formother->selectColor(GETPOST('color')?GETPOST('color'):$object->color, 'color', null, 1, '', 'hideifnotset'); - }else{ + print $formother->selectColor(GETPOSTISSET('color')?GETPOST('color', 'alphanohtml'):$object->color, 'color', null, 1, '', 'hideifnotset'); + } else { print $formother->showColor($object->color, ''); } print '
    ' . $form->editfieldkey('Categories', 'usercats', '', $object, 0) . '
    '.$form->editfieldkey('Categories', 'usercats', '', $object, 0).''; $cate_arbo = $form->select_all_categories(Categorie::TYPE_USER, null, null, null, null, 1); $c = new Categorie($db); @@ -2625,7 +2624,7 @@ else if ($caneditfield) { print $form->multiselectarray('usercats', $cate_arbo, $arrayselected, '', 0, '', 0, '90%'); - }else{ + } else { print $form->showCategories($object->id, 'user', 1); } print "
    '.$langs->trans("LinkToCompanyContact").''; @@ -2664,16 +2663,16 @@ else } // Module Adherent - if (! empty($conf->adherent->enabled)) + if (!empty($conf->adherent->enabled)) { $langs->load("members"); print '
    '.$langs->trans("LinkedToDolibarrMember").''; if ($object->fk_member) { - $adh=new Adherent($db); + $adh = new Adherent($db); $adh->fetch($object->fk_member); - $adh->ref=$adh->login; // Force to show login instead of id + $adh->ref = $adh->login; // Force to show login instead of id print $adh->getNomUrl(1); } else @@ -2686,15 +2685,15 @@ else // Multicompany // TODO check if user not linked with the current entity before change entity (thirdparty, invoice, etc.) !! - if (! empty($conf->multicompany->enabled) && is_object($mc)) + if (!empty($conf->multicompany->enabled) && is_object($mc)) { // This is now done with hook formObjectOptions. Keep this code for backward compatibility with old multicompany module - if (! method_exists($mc, 'formObjectOptions')) + if (!method_exists($mc, 'formObjectOptions')) { - if (empty($conf->multicompany->transverse_mode) && $conf->entity == 1 && $user->admin && ! $user->entity) + if (empty($conf->multicompany->transverse_mode) && $conf->entity == 1 && $user->admin && !$user->entity) { print "
    '.$langs->trans("Entity").'".$mc->select_entities($object->entity, 'entity', '', 0, 1, false, false, 1); // last parameter 1 means, show also a choice 0=>'all entities' + print "".$mc->select_entities($object->entity, 'entity', '', 0, 1, false, false, 1); // last parameter 1 means, show also a choice 0=>'all entities' print "
    '.$langs->trans("DefaultWarehouse").''; print $formproduct->selectWarehouses($object->fk_warehouse, 'fk_warehouse', 'warehouseopen', 1); @@ -2762,36 +2761,36 @@ else } print '
    '; - $text=$langs->trans("THM"); + $text = $langs->trans("THM"); print $form->textwithpicto($text, $langs->trans("THMDescription"), 1, 'help', 'classthm'); print ''; - if($caneditfield){ - print ''; - }else{ - print ($object->thm!=''?price($object->thm, '', $langs, 1, -1, -1, $conf->currency):''); + if ($caneditfield) { + print ''; + } else { + print ($object->thm != '' ?price($object->thm, '', $langs, 1, -1, -1, $conf->currency) : ''); } print '
    '; - $text=$langs->trans("TJM"); + $text = $langs->trans("TJM"); print $form->textwithpicto($text, $langs->trans("TJMDescription"), 1, 'help', 'classthm'); print ''; - if($caneditfield) + if ($caneditfield) { - print ''; - }else{ - print ($object->tjm!=''?price($object->tjm, '', $langs, 1, -1, -1, $conf->currency):''); + print ''; + } else { + print ($object->tjm != '' ?price($object->tjm, '', $langs, 1, -1, -1, $conf->currency) : ''); } print '
    '.$langs->trans("Salary").''; - print ''; + print ''; print '
    '.$langs->trans("WeeklyHours").''; - if($caneditfield) + if ($caneditfield) { - print ''; - }else{ + print ''; + } else { print price2num($object->weeklyhours); } print '
    '.$langs->trans("DateEmployment").''; - if($caneditfield) + if ($caneditfield) { - print $form->selectDate(GETPOST('dateemployment')?GETPOST('dateemployment'):$object->dateemployment, 'dateemployment', 0, 0, 1, 'formdateemployment', 1, 0); - }else{ + print $form->selectDate(GETPOST('dateemployment') ?GETPOST('dateemployment') : $object->dateemployment, 'dateemployment', 0, 0, 1, 'formdateemployment', 1, 0); + } else { print dol_print_date($object->dateemployment, 'day'); } print '
    '.$langs->trans("DateEmploymentEnd").''; - if($caneditfield) + if ($caneditfield) { - print $form->selectDate(GETPOST('dateemploymentend')?GETPOST('dateemploymentend'):$object->dateemploymentend, 'dateemploymentend', 0, 0, 1, 'formdateemploymentend', 1, 0); - }else{ + print $form->selectDate(GETPOST('dateemploymentend') ?GETPOST('dateemploymentend') : $object->dateemploymentend, 'dateemploymentend', 0, 0, 1, 'formdateemploymentend', 1, 0); + } else { print dol_print_date($object->dateemploymentend, 'day'); } print '
    '.$langs->trans("DateToBirth").''; - if($caneditfield) + if ($caneditfield) { - echo $form->selectDate(GETPOST('birth')?GETPOST('birth'):$object->birth, 'birth', 0, 0, 1, 'updateuser', 1, 0); - }else{ + echo $form->selectDate(GETPOST('birth') ?GETPOST('birth') : $object->birth, 'birth', 0, 0, 1, 'updateuser', 1, 0); + } else { print dol_print_date($object->birth, 'day'); } print '